System Calls & the Kernel Interface Questions
The boundary between user space and the kernel: how programs request privileged services through system calls, the user/kernel mode transition, and the semantics of core POSIX calls such as fork, exec, wait, open, read, write, and stat. Covers syscall numbers, arguments, return values and errno, and how libc wrappers relate to the underlying trap. This is the foundational interface for all systems programming on Unix/Linux.
Explain the differences between stat(2), fstat(2), and lstat(2), including examples of when each should be used and how they behave with symbolic links. How would you robustly detect whether a path refers to a regular file, directory, or symlink, and what TOCTOU considerations apply when relying on stat information during a security review?
Sample Answer
The three calls and how they differ
stat(path, &st) resolves the path following ALL symlinks, including a final one, and returns metadata about whatever the path ultimately resolves to. Use stat() when you want metadata about the resolved target itself and have no reason to distinguish a symlink from what it points to: checking a config file's size or last-modified time before parsing it, for instance, where if that path happens to be a symlink to a versioned target, you want the real target's properties, not the symlink object's, so stat() (not lstat()) is the right call.
lstat(path, &st) resolves every symlink EXCEPT the final path component: if path itself names a symlink, lstat returns metadata about the symlink object itself (its own inode, st_size equal to the length of the link target string, st_mode showing S_IFLNK), not about whatever it points at. Use lstat when the question you're actually asking is "is this specific path a symlink," such as while enumerating a directory and needing to distinguish real entries from symlinks without following them.
fstat(fd, &st) takes an already-open file descriptor rather than a path, and returns metadata for whatever that descriptor's open file description points at. No path resolution happens at fstat() time at all, because the resolution already happened once, when the fd was created; whatever the fd refers to is fixed as of that open() call.
Robust type detection
Given a struct stat, use the S_ISREG, S_ISDIR, and S_ISLNK macros on st.st_mode (via stat/lstat/fstat as appropriate) rather than inspecting raw bits; S_ISLNK only ever returns true from an lstat()-populated struct, since a plain stat() has already followed the link by the time it returns, so there is no symlink left to detect in its result.
TOCTOU considerations during a security review, and why fstat on an open descriptor is the safer default
TOCTOU (time-of-check to time-of-use, a race condition class where a decision is made based on a CHECK against a path, but the actual USE re-resolves that same path string later, and the underlying object can change identity in between) is the central risk with path-based stat()/lstat() calls used for security decisions. If code does stat(path) to confirm a file is safe to trust, then later open(path)s the same string, an attacker with write access to a shared or attacker-influenced directory can swap what that path resolves to between the two calls (deleting a regular file and replacing it with a symlink to something sensitive, for example), and the open() call transparently follows the new target.
The mitigation this question's answer should lead with: prefer fstat() on an already-open descriptor over repeated path-based stat()/lstat() calls. Concretely, open the file first (with O_NOFOLLOW where a symlink should never legitimately appear), and only THEN call fstat() on the resulting fd to check its type/size/permissions. Because fstat() operates on a descriptor that is already bound to a specific, resolved object, there is no remaining resolution step for an attacker to hijack between the check and the use; the "thing you checked" and "the thing you use" are, by construction, the identical inode.
Detecting a swapped file via device and inode
When you must compare two points in time (for example, confirming a long-held fd still refers to the file you originally validated, or checking whether a path you stat'd earlier still means the same thing now), compare the (st_dev, st_ino) pair (device ID and inode number) from both observations rather than comparing st_mtime alone. A modification-time comparison can be defeated trivially by an attacker who touches the replacement file to match the original timestamp, or who simply doesn't care about matching it if the check never looks at it; st_dev/st_ino together uniquely identify the filesystem object within that filesystem, so any mismatch is unambiguous proof the underlying object changed identity, regardless of what the path string or timestamps claim.
You need to reduce the blast radius of a compromised helper process. What system-level techniques would you combine around fork()/exec() to drop privileges, restrict filesystem access, and prevent privilege regain?
Sample Answer
Reducing blast radius means: even if the helper is fully compromised (arbitrary code execution inside it), it should not be able to escalate privileges, read/write files outside a narrow allowlist, or spawn arbitrary new processes. The right approach is to apply several independent layers between fork() and the final exec() of the actual helper program, because any single layer can have a bypass and the layers should not depend on each other's correctness. Of these layers, the credential drop (step 1 below) is baseline hygiene that essentially any privilege-separated process should do regardless of threat model; the mount-namespace/pivot_root construction (step 2) is heavier, more specialized machinery, worth reaching for only when the process genuinely needs real filesystem isolation, not a default for every fork()/exec() boundary.
1. Drop privileges, correctly
In the forked child, before calling exec() on the real helper binary:
- Drop supplementary groups first with
setgroups(0, NULL), then drop the GID withsetresgid(gid, gid, gid), then drop the UID last withsetresuid(uid, uid, uid). Order matters: you need root to change groups, so you must do it before you give up UID 0. - Use
setresuid()/setresgid(), notseteuid()/setegid()alone.setresuid(uid, uid, uid)sets the real, effective, and saved UID all to the unprivileged value in one call. If you only callseteuid(uid), the saved UID is untouched and still root, and a compromised process can callseteuid(0)again and get root back with no further exploit needed. After dropping, callgetresuid()/getresgid()and assert all three values are the unprivileged UID/GID; this catches a silently-failed drop (e.g. a missed return-value check) before the child ever execs. - Set
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0). This tells the kernel that no future execve() by this process (or anything it forks) is allowed to grant more privilege than it has right now, permanently disabling the effect of setuid/setgid bits and file capabilities on any binary it might later exec. It cannot be unset once set, which is exactly the property you want for "prevent privilege regain."
2. Restrict filesystem access
chroot() alone is not a security boundary: a process retaining CAP_SYS_CHROOT (or root) can break out of a plain chroot with well-known techniques, so it should never be the only control. The stronger construction is: create a new mount namespace with unshare(CLONE_NEWNS) (or clone() with CLONE_NEWNS), build a minimal root filesystem in a scratch directory with only the files the helper needs bind-mounted in, then pivot_root() into it and unmount the old root, and finally drop CAP_SYS_ADMIN/CAP_SYS_CHROOT (a Linux capability is a narrow, named slice of root's privilege, e.g. the ability to mount filesystems or to call chroot(), that can be granted or revoked independently of full root access) from the process's capability set so it cannot repeat the trick or escape. Pairing this with a mount namespace where sensitive paths are mounted read-only, or not mounted at all, is what actually bounds "which files can this process touch," not the plain chroot() call by itself.
3. Prevent privilege regain
Beyond the credential drop above, clear the process's capability sets. Even after setresuid() to an unprivileged UID, a process can retain capabilities in its permitted/effective sets from before the drop (or regain them on a subsequent exec of a setuid/file-capability binary) unless you explicitly clear the bounding set with cap_set_proc()/capset(2) (via libcap) before the final exec, in addition to setting NO_NEW_PRIVS. Layer a seccomp-bpf filter (a kernel-enforced allowlist of syscalls that the kernel checks on every syscall the process makes, denying or killing the process on anything not on the list) on top: deny execve() outright if the helper never needs to spawn further processes, or restrict it to a fixed set of syscalls that has no path to setuid()/ptrace()/mount()/further execve(). This is defense-in-depth on top of the credential drop, not a replacement for it: if the credential drop has a bug, a tight seccomp filter that also blocks setuid()/capset() still stops the regain.
4. The combined order
fork() -> in the child: build the mount namespace and pivot_root() (needs privilege, so do it first) -> drop the capability bounding set -> setgroups(0, NULL) -> setresgid(gid_unpriv, gid_unpriv, gid_unpriv) -> setresuid(uid_unpriv, uid_unpriv, uid_unpriv) -> getresuid()/getresgid() to assert the drop actually happened -> prctl(PR_SET_NO_NEW_PRIVS, 1) -> install the seccomp-bpf filter -> execve() the real helper binary. Applying setrlimit() (e.g. RLIMIT_NOFILE, RLIMIT_NPROC) in the same child before exec is a cheap extra layer that bounds resource-exhaustion-style damage even within the already-restricted sandbox. This is, in outline, the pattern privilege-separated daemons like OpenSSH's sshd and Postfix's mail-delivery workers use: the privileged parent does the fork and the setup that still needs root, the child sheds every bit of that privilege before it ever runs code that parses attacker-controlled input.
Describe TOCTOU (time-of-check to time-of-use) race conditions when performing file system operations. Provide concrete examples where checking a path then opening it leads to vulnerabilities. Explain how openat(2), O_NOFOLLOW, O_DIRECTORY, and fstatat(2) can be used to avoid races and perform secure atomic checks and opens.
Sample Answer
A concrete worked example first
Consider a security scanner tasked with hashing files it's told to inspect: it does stat(path) to confirm the target is a regular file under some size limit, decides it's safe, and then open(path)s the SAME path string to read and hash its contents. Between the stat() call and the open() call, an attacker with write access to that directory (a shared upload/scan-queue directory, or any directory a lower-privileged or scanned user controls) deletes the original file and creates a symlink at the exact same path, pointing at /etc/shadow, a device file, or any other file entirely. The scanner's open() transparently follows the new symlink, and the tool hashes and reports on a completely different file than the one it validated, either exfiltrating or misreporting on privileged content it should never have touched, or, if the operation had been a write instead of a read, corrupting a file the scanner never intended to write to at all. The vulnerability exists purely because "check" and "use" are two independent path resolutions with an exploitable gap between them; this is TOCTOU (time-of-check to time-of-use), the general name for this race condition class.
Generalizing: any check-path-then-open-path sequence is exposed
The same shape recurs anywhere code does: resolve a path to decide something (is it a regular file, does it belong to the expected owner, is it under a size limit), then LATER performs a privileged action by resolving that path string again (open, unlink, chmod, exec). Anything with write access to a directory in that path, at any point between the two resolutions, can change what the path means. This applies just as much to a config loader that validates a file before parsing it, a backup tool that stats before archiving, or a privilege-dropping helper that checks a target binary before exec'ing it.
How openat, O_NOFOLLOW, O_DIRECTORY, and fstatat close the race
openat(dirfd, name, ...): resolvesnamerelative to an already-open directory file descriptor rather than re-walking a path string from the root each time. On its own it doesn't remove TOCTOU, but it is the building block the rest of the mitigation is built on, because it anchors resolution to a specific, already-validated directory object rather than a name that has to be looked up fresh.O_NOFOLLOW: passed toopen()/openat(), makes the call FAIL withELOOPif the final path component is a symlink, instead of silently following it. This converts "attacker swapped the file for a symlink" from a silent, invisible redirection into a loud, immediately checkable error.O_DIRECTORY: fails the open unless the resolved target is genuinely a directory, which matters when walking a tree, so a symlink planted where a subdirectory was expected can't trick the walker into descending into somewhere else entirely.fstatat(dirfd, name, &st, AT_SYMLINK_NOFOLLOW): the*at-family equivalent of stat, checking metadata using the same directory-fd-anchored resolution the subsequentopenat()will use, rather than re-resolving a brand-new path string from the filesystem root as a second, independent operation (itself a second opportunity for the meaning of the path to differ, especially across mount namespaces or symlinked intermediate directories).
The secure atomic pattern
Reorder the operations so the check happens AFTER acquisition, not before: openat(dirfd, name, O_RDONLY | O_NOFOLLOW) first (a single resolution, with symlinks rejected outright), and only then fstat() the resulting fd to verify size, type, and ownership. There is no remaining check-then-use gap, because by the time any check runs, the fd already IS the object being checked; there is no second resolution left for an attacker to hijack. Applied to the worked example above, the scanner would open the candidate file with O_NOFOLLOW first (failing loudly if it's a symlink) and confirm S_ISREG via fstat() on that descriptor before ever reading a byte, closing the exact window the naive stat-then-open version left wide open.
During an incident, you notice a suspicious process tree spawning rapidly and executing different binaries. How would you use your understanding of fork(), exec(), and process parent-child relationships to distinguish normal automation from a fork bomb or malware loader?
Sample Answer
The investigation comes down to reading the SHAPE of the process tree and the IDENTITY of what's actually being executed at each hop, then comparing both against what's normal for this host.
What a fork bomb looks like
A fork bomb is defined by rate and self-similarity, not by what any individual process does. Symptoms: an extremely high, near-instantaneous rate of new PIDs, potentially thousands per second; the SAME short-lived binary re-forking itself recursively (the parent and the child are typically running the identical program, sometimes literally the same shell one-liner re-invoking itself); and system-wide symptoms that show up FAST, fork() starting to fail everywhere on the host with EAGAIN/ENOMEM because the global PID space or resource limits are being exhausted, CPU pegged near 100% from pure scheduling/context-switch overhead even though no individual process is doing meaningful work (no real file I/O, no network activity, nothing but forking). Confirming this: ps -eo pid,ppid,etimes,cmd --sort=start_time | tail -50 (or pstree -p) shows a large cluster of processes all born within the same second or two, almost all running the same command, with a shallow but extremely WIDE tree (one ancestor with an enormous number of direct or near-direct descendants), rather than a deep chain.
What a malware loader / process-chaining attack looks like
The opposite shape: a NARROW, sequential chain, parent -> child -> grandchild, where each hop exec()s into a DIFFERENT binary than the one before it ("process chaining," commonly discussed as part of "living off the land" tradecraft). The telltale signal is fork() immediately followed by execve() into an unrelated program, especially when: the target binary lives in a WRITABLE, non-standard location (/tmp, /dev/shm, a user's Downloads directory) rather than a normal system binary path; or it's a legitimate, trusted system binary being invoked with unusual, scripted-looking arguments that a human wouldn't type interactively (a base64-encoded inline script, a curl/wget piped directly into a shell interpreter, a download-then-exec two-step); or a process that has no legitimate reason to spawn a shell at all suddenly does, a web server worker process forking sh -c "...", or a document viewer (PDF reader, Office app) spawning a script interpreter, is a strong standalone signal on its own, since normal automation for those specific parent processes essentially never legitimately does that.
What normal automation looks like, as the baseline to compare against
A stable, REPEATING, predictable tree shape: a cron job or systemd timer forking the same handful of children on a fixed schedule; a CI runner spawning build-tool subprocesses in a consistent pattern run after run. Children exec well-known binaries from standard system paths (/usr/bin, /usr/local/bin, not a temp directory). The fork rate is moderate and clearly correlated with an actual trigger (a cron entry firing, a webhook arriving), not continuous, unbounded self-replication. And critically, the specific argv patterns and binary paths involved are ones you'd expect to have SEEN BEFORE on this host if you have any historical baseline (fleet-wide EDR telemetry, prior audit logs), whereas malicious activity commonly shows a first-time-ever binary path, argv combination, or parent/child pairing for that specific host.
Concrete investigative steps
pstree -p <suspect_root_pid>first, to see the actual tree SHAPE at a glance: wide-and-shallow (fork bomb candidate) versus narrow-and-deep with binary changes at each hop (loader candidate) versus a familiar, repeating pattern (probably fine).ps -eo pid,ppid,lstart,etime,cmdfor exact start times and full command lines, WHEN things started (clustered instantaneously, or spread out on a schedule) and WHAT was actually typed as arguments (a base64 blob, a download URL, a-enc/-EncodedCommand-style obfuscation flag are all strong indicators).- Don't trust the process name alone:
argv[0](what shows up as the "command" in a casualps) can be rewritten by the process itself to look innocuous. Cross-check/proc/<pid>/exe(a symlink that resolves to the ACTUAL binary inode being executed, harder to spoof after the fact than an in-process argv rewrite) and/proc/<pid>/cmdline(the real argv the kernel recorded at exec time) against whatpsdisplayed; a mismatch between a friendly-looking process name and a suspicious/proc/<pid>/exetarget is itself a finding. - Check
/proc/<pid>/statusforPPID(confirm the actual parentage rather than trusting a displayed process name) and cross-reference againstwho/last/authentication logs: does this chain trace back to an interactive login session, a legitimate cron entry, or a network-facing service process, and if it's the latter, does that service have any legitimate reason to be spawning a shell or a script interpreter AT ALL? A network-facing daemon forking a shell is close to always worth escalating on its own. - Recognize the limits of reasoning from the CURRENT process tree alone:
fork()/execve()calls aren't logged anywhere by default, so if the malicious chain has already partially exited by the time you're looking, the tree you're inspecting is incomplete. This is exactly why Linux audit (auditctl -a exit,always -F arch=b64 -S execve) or an eBPF (a Linux kernel facility that lets small sandboxed monitoring programs run in-kernel, the basis for many modern tracing/EDR tools)-based EDR agent recording exec events needs to be enabled BEFORE an incident, not reached for during one; reconstructing a process-chaining attack cleanly from an execve audit trail is straightforward, reconstructing it purely frompssnapshots and whatever remnants are still running when you happen to look is much harder and can miss steps that already completed and exited.
A malware analyst tool walks a directory tree, filters for regular files, and then hashes them. How would you make the file-type checks and traversal resistant to symlink tricks, renamed paths, and concurrent filesystem changes?
Sample Answer
Why this is a live attack surface, not a theoretical edge case
The vulnerable pattern is: enumerate a directory tree with readdir(), filter entries down to "regular files" using d_type and/or stat(), then separately open() and hash the same path string. Every gap between "decided this is safe to hash" and "actually opened it" is a TOCTOU (time-of-check to time-of-use) window, and in malware analysis the directory tree being walked is explicitly adversarial input: the sample itself, or anything an attacker controls in a shared analysis environment, can plant content specifically designed to defeat or redirect the scanner. This isn't a hardening nicety here, it's the expected threat model.
The specific tricks to defend against
- Symlink tricks: an entry named to look like an innocuous sample (
report.pdf,invoice.exe) that is actually a symlink to/etc/shadow, a device file, or a named pipe designed to block the scanner forever (a denial-of-service against the tool itself), or a symlink to an enormous sparse file designed to exhaust disk or memory when "hashed." - Renamed-path tricks: the entry
readdir()reported gets deleted and a DIFFERENT object created under the same name before the tool acts on it, possible whenever the directory being scanned is live and writable, whether by the sample's own partial execution, by another process sharing the analysis filesystem, or by an operator re-triaging concurrently. - Concurrent filesystem changes: directories scanned on a live system, as opposed to a static forensic image, can have entries added, removed, or replaced mid-walk; POSIX gives no ordering or consistency guarantee for
readdir()under concurrent modification, so entries can be seen twice, missed entirely, or observed in an inconsistent state relative to each other.
A resistant design
- Walk using directory FILE DESCRIPTORS, not path strings. Open the top directory once with
open(path, O_DIRECTORY); for every subdirectory encountered, descend viaopenat(parent_dirfd, name, O_DIRECTORY | O_NOFOLLOW)rather than concatenating a path string, so a symlink planted where a subdirectory was expected is rejected instead of followed. - For each entry, don't trust
d_typeas authoritative (it can beDT_UNKNOWN, and even when populated it reflects a moment in time that has already passed by the time you act). Instead of a check-then-open sequence,openat(dirfd, name, O_RDONLY | O_NOFOLLOW)directly: if the entry is a symlink, this call fails withELOOP(too many levels of symbolic links encountered, the same errnoO_NOFOLLOWproduces when it hits a symlink directly) and the entry can be flagged and skipped rather than silently redirected. fstat()the resulting fd, neverfstatat/staton the name a second time, and verifyS_ISREGbefore reading a single byte, so the object being hashed is guaranteed to be the exact fd already held open, with zero remaining path re-resolution for anything to hijack.- Compare
(st_dev, st_ino)(device and inode, from the same fd'sfstat()) against a set of already-visited identifiers to detect hardlink loops or the same file linked into the tree more than once, avoiding both infinite loops and double-counted results. - Don't trust
st_sizeblindly before reading: a pathological entry (a sparse file reporting a huge logical size, or a FIFO with a stale or meaningless size field) can turn a naive "read st_size bytes" into a resource-exhaustion or hang condition. Read in bounded chunks with an overall size and time budget, and use non-blocking I/O or a read timeout so a FIFO planted specifically to block forever can't stall the whole walk. - Run the entire scan under explicit resource limits (a wall-clock timeout per file,
RLIMIT_FSIZE(a per-process resource limit capping the largest file the process may write, to stop the scanner itself from being tricked into writing an unbounded amount of data), memory caps), treating the sample directory as hostile input for the whole duration of the walk, not just at the point of opening each file, since the scanner's own resource consumption is as much a part of the attack surface as the data it reads.
Unlock Full Question Bank
Get access to all 10 System Calls & the Kernel Interface interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.