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().

20 minfree previewLinux 6.12C11glibc 2.39→ module 1 lab
What you'll learn
  • Evaluate VFS owner/group/other DAC checks, directory r/w/x bits, and S_ISUID/S_ISGID/S_ISVTX against real/effective UIDs.
  • Modify file modes and ownership via umask(), fchmod(), and fchown()/lchown() without access() + open() TOCTOU races.
  • Update inode timestamps at nanosecond precision via futimens() and utimensat() (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 ConceptRegular File SemanticsDirectory SemanticsGoverning 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 bytesCreate, unlink, or rename entries (requires x)chmod, fchmod, umask
Execute (x: 0100/010/001)execve() binary imageTraverse/resolve child inodes (stat/open)chmod, fchmod, umask
S_ISUID / S_ISGID / S_ISVTX04000 set-UID, 02000 set-GID02000 inherit dir GID; 01000 sticky delete guardchmod, fchmod (umask ignores S)
st_atim / st_mtim / st_ctimLast read / write / inode status changeLast readdir / entry add-del / metadata changefutimens, 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.

ast_m01_l02.svg — VFS checks ancestor directory x bits first,…step 1/4
  1. Step 1. Step 1: Kernel verifies execute (x) search permission across each parent directory component.
  2. Step 2. Step 2: Credential check short-circuits on geteuid() == st_uid before ever inspecting group or other bits.
  3. Step 3. Step 3: open(..., O_CREAT, mode) applies mode & ~umask, whereas chmod()/fchmod() write exact mode bits.
  4. 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.

fig_m01_l02_arch.svg — Short-circuit VFS DAC evaluation, TOCTOU race…

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):

  • 0666 in binary is 000_110_110_110 (rw-rw-rw-); 0027 is 000_000_010_111 (----w-rwx).
  • Inverting ~0027 masks off bit 4 (group w) and bits 2..0 (other rwx), so 0666 & ~0027 == 0640 (rw-r-----).
  • Conversely, if an owner accidentally sets chmod(path, 0060) (---rw----) while belonging to st_gid, inode_permission() in the Linux kernel sees geteuid() == inode->i_uid, tests 0060 & 0400 == 0, and returns -EACCES in < 50 ns without ever inspecting group bits 0060.

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
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;    }
  1. Line 21. O_CREAT | O_EXCL under umask(0027) computes 0666 & ~0027 == 0640 atomically inside VFS.
  2. Line 36. chmod() writes exact mode bits (0666) directly to the inode, ignoring the active process umask.
  3. Line 44. fchmod(fd, ...) mutates the open struct inode directly by descriptor without path re-lookup.
  4. Line 64. UTIME_OMIT preserves st_atim at 1700000000.123456789 while updating st_mtim in one syscall.

Guided Practice

Trace two permission and timestamp edge cases in perm_times_audit.c before running it:

  1. Cue 1 (Read-only descriptor writes): After fchmod(fd, 0400 | S_ISVTX) strips write permission from the inode on line 44, would write(fd, "X", 1) fail with EACCES or succeed? (*Hint:* Recall from GL-C01 when VFS checks st_mode—at open() time when populating struct file->f_mode, not on each subsequent write(fd, ...).)
  2. Cue 2 (Short-circuit prediction): If you inserted fchmod(fd, 0060) on a non-root user who owns fd and also belongs to st1.st_gid, what would open(path, O_RDONLY) return? Predict both return code (-1) and errno (EACCES).

Independent Practice

Build a standalone verification snippet in a temporary directory:

  • Task: Create a temporary directory /tmp/ksa_dir_perm with mode 0600 (drw-------, no x bit) after placing one file inside it while mode was 0700. Prove in C that opendir() + readdir() still lists the filename string (r bit), whereas fstatat(dirfd, name, &st, 0) fails with errno == EACCES until fchmod(dirfd, 0700) restores x.
  • 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 plain open(..., 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-l02
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-l02

Tracing 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) at a glance — GL-C02
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

quiz · 1 of 4

A directory /srv/drop has permissions 0600 (drw-------, read and write for owner, no execute x bit). What happens when the owner calls opendir("/srv/drop") versus stat("/srv/drop/job.json", &st)?

quiz · 2 of 4

You want to update a symbolic link's own st_mtim to the current kernel time while leaving its st_atim completely unchanged, without modifying the target file it points to. Which call achieves this atomically?

quiz · 3 of 4

Why is st_ctim absent from the times[2] array accepted by futimens() and utimensat()?

quiz · 4 of 4

A daemon running with umask(0027) executes fd = open("audit.db", O_RDWR | O_CREAT | O_EXCL, 0666); followed later by fchmod(fd, 0664);. What octal permission bits (st_mode & 0777) does audit.db hold immediately after open(), and immediately after fchmod()?

Key takeaways

  • The Linux kernel checks ancestor directory x search bits first and evaluates st_mode in strict short-circuit order (root -> geteuid() == st_uid -> group -> other) using effective credentials (geteuid(), getegid()).
  • Directory r lists entry names, x traverses to child inodes, w + x creates or unlinks entries, and S_ISVTX (01000) prevents non-owners from unlinking peers' files in shared directories.
  • umask() masks only creation modes (mode & ~umask in open/mkdir), whereas chmod()/fchmod() write exact modes and fchown()/lchown() update st_uid/st_gid without access() + open() TOCTOU races.
  • futimens() and utimensat(..., AT_SYMLINK_NOFOLLOW) update st_atim and st_mtim at nanosecond precision with UTIME_NOW and UTIME_OMIT, while the kernel updates st_ctim automatically.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure