Ownership, Mode Bits & Timestamps
Gatekeeping open() with access() creates exploitable TOCTOU privilege escalations, while forgetting VFS short-circuit owner rules or directory execute bits causes mysterious EACCES errors. You will evaluate real vs effective credentials, control umask, fchmod, and fchown safely, and update nanosecond timestamps via futimens() and utimensat().
What you'll learn
- Evaluate VFS owner/group/other DAC checks, directory
r/w/xbits, andS_ISUID/S_ISGID/S_ISVTXagainst real/effective UIDs. - Modify file modes and ownership via
umask(),fchmod(), andfchown()/lchown()withoutaccess()+open()TOCTOU races. - Update inode timestamps at nanosecond precision via
futimens()andutimensat()(UTIME_NOW,UTIME_OMIT,AT_SYMLINK_NOFOLLOW).
Privilege Escalation Races and Mysterious EACCES Denials
Consider a set-user-ID (S_ISUID) diagnostic helper owned by root (UID 0) that lets operators export logs to a user-chosen path. To prevent overwriting /etc/shadow, the author writes if (access(user_path, W_OK) == 0) { fd = open(user_path, O_WRONLY | O_TRUNC); }. An unprivileged local user points user_path at a scratch file they own, waits a few microseconds for access() to pass against their real UID, and atomically swaps user_path with a symbolic link to /etc/shadow right before open() runs with effective UID 0—wiping system authentication. On the same gateway, another developer sets a shared drop directory to 0660 (drw-rw----) and is baffled when every open("/srv/drop/job.json", ...) fails with EACCES despite read and write bits being set.
Both defects stem from misunderstanding how the Linux kernel Discretionary Access Control (DAC) engine separates real from effective credentials, checks ancestor directories, and splits check-from-use syscalls across preemptible user-space gaps. Every Linux task carries real credentials (getuid(), getgid()—recording the account that launched the task) and effective credentials (geteuid(), getegid() plus supplementary groups—consulted by VFS permission checks). Executing a binary carrying set-user-ID (S_ISUID, octal 04000) or set-group-ID (S_ISGID, 02000) elevates geteuid() or getegid() to st_uid or st_gid, while sticky (S_ISVTX, 01000, as on /tmp 01777) forbids unlinking or renaming entries inside a shared writable directory unless the caller owns the entry, owns the directory, or has CAP_FOWNER (UID 0).
note: Think of a badge-controlled laboratory wing where outer corridor doors check traversal clearance while inner equipment lockers check the active role encoded on your badge, inspecting only the first matching tier rather than combining every group you belong to.
Where it stops working: Unlike physical badge readers, the Linux kernel evaluates directory x traversal bits on every path component in nanoseconds and updates st_ctim automatically in VFS RAM whenever inode metadata changes.
Origin & Formal Definition (umask, chmod, and Short-Circuit DAC): umask contracts user file-creation mode mask—a per-process bitmask of permissions subtracted during inode creation (effective_mode = requested_mode & ~umask), whereas chmod (change mode) writes exact permission bits onto an existing inode without consulting umask. When resolving any path, the Linux kernel verifies execute/search (x) permission on every ancestor directory first, then evaluates the target inode's 9 rwx bits in strict short-circuit order: (1) geteuid() == 0 (CAP_DAC_OVERRIDE), (2) geteuid() == st_uid (owner tier 0700 only), (3) getegid() or supplementary groups matching st_gid (group tier 0070 only), else (4) other tier (0007 only). It never unions tiers together.
| Permission / Timestamp Concept | Regular File Semantics | Directory Semantics | Governing C Interfaces |
|---|---|---|---|
Read (r: 0400/0040/0004) | Read byte payload (O_RDONLY) | Read [d_ino, d_name] names (readdir) | chmod, fchmod, umask |
Write (w: 0200/0020/0002) | Modify/truncate payload bytes | Create, unlink, or rename entries (requires x) | chmod, fchmod, umask |
Execute (x: 0100/010/001) | execve() binary image | Traverse/resolve child inodes (stat/open) | chmod, fchmod, umask |
S_ISUID / S_ISGID / S_ISVTX | 04000 set-UID, 02000 set-GID | 02000 inherit dir GID; 01000 sticky delete guard | chmod, fchmod (umask ignores S) |
st_atim / st_mtim / st_ctim | Last read / write / inode status change | Last readdir / entry add-del / metadata change | futimens, utimensat (st_ctim kernel-only) |
Figure 1.2 and the step sequence below trace how VFS short-circuit evaluation, umask versus chmod, and nanosecond timestamp updates interact inside the kernel.
- Step 1. Step 1: Kernel verifies execute (x) search permission across each parent directory component.
- Step 2. Step 2: Credential check short-circuits on geteuid() == st_uid before ever inspecting group or other bits.
- Step 3. Step 3: open(..., O_CREAT, mode) applies mode & ~umask, whereas chmod()/fchmod() write exact mode bits.
- Step 4. Step 4: futimens(fd, ts) and utimensat(..., UTIME_OMIT/UTIME_NOW) set nanosecond atime/mtime and bump ctime.
Figure 1.2a. VFS checks ancestor directory x bits first, short-circuits on the first matching credential tier (root -> owner -> group -> other), and updates nanosecond timestamps atomically via futimens/utimensat.
Figure 1.2. Short-circuit VFS DAC evaluation, TOCTOU race elimination, umask() versus chmod(), and nanosecond futimens()/utimensat() control.
One Layer Down: TOCTOU Races, Bitwise Mode Algebra & Nanosecond timespec
Formal Definition (TOCTOU): Time-of-Check to Time-of-Use (TOCTOU) is a concurrency vulnerability where security validation (access(pathname, W_OK)) and resource consumption (open(pathname, ...)) occur in two separate system calls, allowing another process to mutate the filesystem binding in the preemption gap between them. Even faccessat(dfd, path, W_OK, AT_EACCESS) cannot make a subsequent open() atomic. Eliminate TOCTOU by dropping effective privileges (seteuid(getuid())) or calling open() directly with O_NOFOLLOW or O_CREAT | O_EXCL, then operating exclusively by descriptor via fstat(fd, ...), fchmod(fd, mode), and fchown(fd, uid, gid) (passing (uid_t)-1 or (gid_t)-1 leaves that ID unchanged; only CAP_CHOWN may alter st_uid, and lchown() updates symlink owners without dereferencing).
Work through the exact 12-bit octal arithmetic of umask(0027) paired with open(..., O_CREAT, 0666):
0666in binary is000_110_110_110(rw-rw-rw-);0027is000_000_010_111(----w-rwx).- Inverting
~0027masks off bit4(groupw) and bits2..0(otherrwx), so0666 & ~0027 == 0640(rw-r-----). - Conversely, if an owner accidentally sets
chmod(path, 0060)(---rw----) while belonging tost_gid,inode_permission()in the Linux kernel seesgeteuid() == inode->i_uid, tests0060 & 0400 == 0, and returns-EACCESin< 50 nswithout ever inspecting group bits0060.
While st_ctim (inode status-change time, never creation birth time) is bumped solely by the kernel whenever payload bytes, permissions, link counts, or owners change, user space controls st_atim (times[0]) and st_mtim (times[1]) to 1 ns resolution (0..999,999,999 ns) via futimens(fd, times) and utimensat(dirfd, pathname, times, flags). Passing times == NULL sets both timestamps to current kernel UTC time; setting tv_nsec = UTIME_NOW updates one field to now; setting tv_nsec = UTIME_OMIT leaves that field untouched without a racy stat() read-modify-write; and AT_SYMLINK_NOFOLLOW updates a symbolic link's own timestamps. Remember from Lesson 1.1 that 32-bit ARMv7 builds require _TIME_BITS=64 so struct timespec fields inside futimens() stay 64-bit past 2038.
Auditing Effective IDs, chmod vs umask & UTIME_OMIT in C11
Save perm_times_audit.c below. It verifies real/effective UIDs and GIDs, proves open(..., 0666) under umask(0027) yields 0640 whereas chmod(path, 0666) writes unmasked 0666, applies fchmod(fd, 0400 | S_ISVTX) on the open descriptor, confirms (uid_t)-1 no-op fchown(), and updates st_mtim to nanosecond precision while preserving st_atim via UTIME_OMIT.
learner@ksa:~/gl-c02/m01-l02$ bat -H 21 -H 36 -H 44 -H 64 perm_times_audit.c File: perm_times_audit.c #define _XOPEN_SOURCE 700 #define _FILE_OFFSET_BITS 64 #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> int main(void) { const char *path = "/tmp/ksa_c02_l02.dat"; (void)unlink(path); uid_t ruid = getuid(); uid_t euid = geteuid(); gid_t rgid = getgid(); gid_t egid = getegid(); mode_t old_mask = umask(0027); int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0666); if (fd == -1) { umask(old_mask); return EXIT_FAILURE; } struct stat st1, st2, st3; if (fstat(fd, &st1) == -1) { (void)close(fd); (void)unlink(path); umask(old_mask); return EXIT_FAILURE; } int masked_mode_ok = ((st1.st_mode & 0777U) == 0640U); if (chmod(path, 0666) == -1 || fstat(fd, &st2) == -1) { (void)close(fd); (void)unlink(path); umask(old_mask); return EXIT_FAILURE; } int chmod_bypass_umask = ((st2.st_mode & 0777U) == 0666U); if (fchmod(fd, 0400 | S_ISVTX) == -1) { (void)close(fd); (void)unlink(path); umask(old_mask); return EXIT_FAILURE; } int r_ok = (access(path, F_OK | R_OK) == 0); errno = 0; int w_denied = (euid == 0U) ? 1 : (access(path, W_OK) == -1 && errno == EACCES); int chown_noop_ok = (fchown(fd, (uid_t)-1, (gid_t)-1) == 0); struct timespec init_ts[2] = { {1700000000, 123456789L}, {1700000500, 987654321L} }; struct timespec omit_ts[2] = { {0, UTIME_OMIT}, {1700000900, 555000111L} }; int ts_ok = (futimens(fd, init_ts) == 0 && utimensat(AT_FDCWD, path, omit_ts, AT_SYMLINK_NOFOLLOW) == 0 && fstat(fd, &st3) == 0 && st3.st_atim.tv_sec == 1700000000 && st3.st_atim.tv_nsec == 123456789L && st3.st_mtim.tv_sec == 1700000900 && st3.st_mtim.tv_nsec == 555000111L); (void)close(fd); (void)unlink(path); umask(old_mask); printf("ids_match=%d masked_0640=%d chmod_0666=%d sticky_set=%d\n", (ruid == euid && rgid == egid && st1.st_uid == euid), masked_mode_ok, chmod_bypass_umask, (st3.st_mode & S_ISVTX) != 0U); printf("access_r=%d write_denied=%d chown_noop=%d ns_times_ok=%d\n", r_ok, w_denied, chown_noop_ok, ts_ok); return EXIT_SUCCESS; }- Line 21.
O_CREAT | O_EXCLunderumask(0027)computes0666 & ~0027 == 0640atomically inside VFS. - Line 36.
chmod()writes exact mode bits (0666) directly to the inode, ignoring the active processumask. - Line 44.
fchmod(fd, ...)mutates the openstruct inodedirectly by descriptor without path re-lookup. - Line 64.
UTIME_OMITpreservesst_atimat1700000000.123456789while updatingst_mtimin one syscall.
Guided Practice
Trace two permission and timestamp edge cases in perm_times_audit.c before running it:
- Cue 1 (Read-only descriptor writes): After
fchmod(fd, 0400 | S_ISVTX)strips write permission from the inode on line 44, wouldwrite(fd, "X", 1)fail withEACCESor succeed? (*Hint:* Recall fromGL-C01when VFS checksst_mode—atopen()time when populatingstruct file->f_mode, not on each subsequentwrite(fd, ...).) - Cue 2 (Short-circuit prediction): If you inserted
fchmod(fd, 0060)on a non-root user who ownsfdand also belongs tost1.st_gid, what wouldopen(path, O_RDONLY)return? Predict both return code (-1) anderrno(EACCES).
Independent Practice
Build a standalone verification snippet in a temporary directory:
- Task: Create a temporary directory
/tmp/ksa_dir_permwith mode0600(drw-------, noxbit) after placing one file inside it while mode was0700. Prove in C thatopendir()+readdir()still lists the filename string (rbit), whereasfstatat(dirfd, name, &st, 0)fails witherrno == EACCESuntilfchmod(dirfd, 0700)restoresx. - Transfer Challenge: When a privileged security agent scans untrusted user directories to quarantine malware without following attacker-planted symlinks along intermediate path components, why does Linux
openat2()(RESOLVE_NO_SYMLINKS | RESOLVE_BENEATH) outperform chaining plainopen(..., O_NOFOLLOW)calls?
Verifying Permission Masks and Nanosecond Timestamps
Compile and run perm_times_audit on the Linux 6.12 host to confirm 0666 & ~0027 == 0640 on creation, unmasked 0666 on chmod(), read-only EACCES write denial, and exact nanosecond preservation under UTIME_OMIT.
learner@ksa:~/gl-c02/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror perm_times_audit.c -o perm_times_auditlearner@ksa:~/gl-c02/m01-l02./perm_times_auditids_match=1 masked_0640=1 chmod_0666=1 sticky_set=1access_r=1 write_denied=1 chown_noop=1 ns_times_ok=1learner@ksa:~/gl-c02/m01-l02Tracing Credential Checks and Selective Timespec Updates
Every assertion in ./perm_times_audit verified a core VFS contract. Setting umask(0027) stripped group-write and all other bits during open(..., O_CREAT, 0666) (masked_0640=1), whereas chmod(path, 0666) wrote 0666 directly to the inode (chmod_0666=1). Notice too that although fchmod(fd, 0400 | S_ISVTX) stripped write permission from path, futimens(fd, ...) and utimensat(...) still succeeded because explicit timestamp updates check inode ownership (geteuid() == st_uid), consulting file write bits only when non-owners pass times == NULL (both UTIME_NOW).
Passing UTIME_OMIT in omit_ts[0].tv_nsec updated st_mtim to 1700000900.555000111 in one atomic syscall without touching st_atim (1700000000.123456789) while the kernel automatically advanced st_ctim. Next, we move from single-inode attributes to hard links, symbolic links, directory streams, and crash-atomic renameat().
utimensat(2) Quick Reference
utimensat(2) GL-C02 Quick Reference utimensat(2) NAME utimensat, futimens - update inode timestamps with nanosecond precision SYNOPSIS #include <fcntl.h> /* AT_* constants */ #include <sys/stat.h> int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags); int futimens(int fd, const struct timespec times[2]); STANDARDS POSIX.1-2008; requires _POSIX_C_SOURCE >= 200809L. RETURN VALUE Returns 0 on success, or -1 on error with errno set. ERRORS EACCES times is NULL (or both UTIME_NOW) and caller lacks write access. EINVAL Invalid tv_nsec (> 999999999 and neither UTIME_NOW/UTIME_OMIT). EPERM Explicit timestamp requested by neither owner nor root. NOTES times[0] sets st_atim; times[1] sets st_mtim; st_ctim is kernel-set. Pass AT_SYMLINK_NOFOLLOW to utimensat() to update a symlink itself. SEE ALSO chmod(2), chown(2), openat(2), stat(2), statx(2) Kernel Systems Academy Lesson 1.2 utimensat(2) GL-C02 quick reference · full manual page: man 2 utimensat Common Production Pitfalls
warning: Symptom: A privileged service runs if (access(user_path, W_OK) == 0) { fd = open(user_path, O_WRONLY); } and an unprivileged local user tricks it into overwriting /etc/shadow. Root Cause: Between access() and open() (TOCTOU), the attacker atomically replaces user_path with a symlink to /etc/shadow. Fix: Never pair access() with open(); drop effective privileges if needed or open() directly with O_NOFOLLOW and inspect fstat(fd, &st).
warning: Symptom: A user owns secret.key with mode 0060 (---rw----) and also belongs to the file's group, yet open("secret.key", O_RDONLY) fails with EACCES. Root Cause: VFS permission evaluation short-circuits on geteuid() == st_uid (000 owner bits) and never falls through to group bits (060). Fix: Ensure owner permissions are always at least as permissive as group permissions (0660).
Knowledge Check
Key takeaways
- The Linux kernel checks ancestor directory
xsearch bits first and evaluatesst_modein strict short-circuit order (root->geteuid() == st_uid-> group -> other) using effective credentials (geteuid(),getegid()). - Directory
rlists entry names,xtraverses to child inodes,w+xcreates or unlinks entries, andS_ISVTX(01000) prevents non-owners from unlinking peers' files in shared directories. umask()masks only creation modes (mode & ~umaskinopen/mkdir), whereaschmod()/fchmod()write exact modes andfchown()/lchown()updatest_uid/st_gidwithoutaccess()+open()TOCTOUraces.futimens()andutimensat(..., AT_SYMLINK_NOFOLLOW)updatest_atimandst_mtimat nanosecond precision withUTIME_NOWandUTIME_OMIT, while the kernel updatesst_ctimautomatically.