UID/GID Identity, Octal Mode Bits, Sticky Directories & Profile Safety

Running chmod -R 777 to silence a permission error instantly bricks sudo and SSH key logins, misunderstanding directory x versus r bits exposes or blocks unintended paths, and one typo in /etc/profile locks every user out of their login session.

20 minfree previewLinux 6.12C11glibc 2.39→ module 2 lab
What you'll learn
  • Evaluate Linux VFS permission checks across UID/GID classes, directory traverse (x) vs list (r) bits, and sticky (01000) shared directories.
  • Calculate effective file and directory modes under process umask values and explain why chmod -R 777 disables sudo and OpenSSH.
  • Author syntax-checked, idempotent /etc/profile.d/ environment scripts without causing desktop or SSH login loops.

Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations

Two reflexes account for more reinstalled Ubuntu workstations in embedded courses than any other mistake. First, a learner hits Permission denied on a build folder and runs sudo chmod -R 777 / or chmod -R 777 ~. Within milliseconds, OpenSSH refuses every public-key login because StrictModes rejects group- or world-writable ~/.ssh (0700 required) and ~/.ssh/authorized_keys (0600 required), and if /etc/sudoers (0440) or /usr/bin/sudo (04755 setuid root) is touched, sudo itself aborts with /etc/sudoers is world writable—leaving no way to fix the machine without booting recovery media!

Second, when adding an ARM cross-compiler permanently, an engineer edits /etc/profile and writes export PATH=/opt/arm/bin (forgetting :$PATH!) or leaves an unclosed quote or blocking foreground command. On the next boot, the display manager sources /etc/profile, fails to find /bin/ls or /usr/bin/dbus-run-session, and bounces straight back to the login screen in an infinite loop!

fig_m02_l02_a.svg — VFS checks owner, group, and other classes mutually…

Figure 2.2a. VFS checks owner, group, and other classes mutually exclusively (first match wins, never union!) alongside 04000/02000/01000 high bits.

mental model: Think of a directory as a locked filing-cabinet room containing sealed envelopes (files): r (04) turns on the room light so you can read the index sheet of envelope names, x (01) unlocks the door so you can walk in and grab an envelope whose exact name you already know (even in the dark when r is off!), and w (02) lets you toss envelopes into the shredder—regardless of whose seal is on the envelope—unless the room guard (01000 sticky bit) checks that your badge matches the envelope's owner!

Where it stops working: Unlike physical rooms where holding both an employee badge and a visitor badge gives you the best of both, POSIX VFS permission matching is strictly mutually exclusive: if euid == st_uid and owner bits are 000 (---rwxrwx), open() returns EACCES even when group and world have rwx!

definition ( and Set-Group-ID Directory (S_ISGID / 02000)): Historically named because early Unix kept a program's text segment 'stuck' in swap space, on modern Linux kernel directories S_ISVTX (01000, rendered as t in drwxrwxrwt when o+x is set, or T when o+x is clear) modifies may_delete() in fs/namei.c: unlinking or renaming a child requires w+x on the directory plus euid == 0 || euid == dir_uid || euid == file_uid. Meanwhile, S_ISGID (02000, drwxrwsr-x) on a shared team build directory makes newly created files and subdirectories inherit the directory's st_gid automatically.

ast_m02_l02.svg — Avoid chmod 777; dir w+x + 01000 governs unlink;…step 1/4
  1. Step 1. Query numeric and symbolic mode bits with stat -c '%a %A' to audit special high bits (4=setuid, 2=setgid, 1=sticky).
  2. Step 2. Check active shell umask in both symbolic and octal forms before unpacking toolchains or creating staging trees.
  3. Step 3. Place global environment additions in a standalone /etc/profile.d/*.sh file rather than hand-editing /etc/profile.
  4. Step 4. Validate POSIX sh syntax with sh -n and spawn a clean login subshell (bash -lc) before logging out.

Figure 2.2b. Avoid chmod 777; dir w+x + 01000 governs unlink; syntax-check profile.d via sh -n.

12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety

Inside generic_permission() (fs/namei.c), the Linux kernel evaluates a 12-bit mode word (4 octal digits: [special][user][group][other]). For fsuid == 0, read/write checks succeed via CAP_DAC_OVERRIDE (though executing a regular file still requires at least one x bit 0111!). For non-root processes, the kernel tests fsuid == inode->i_uid first (using (mode >> 6) & 7); only if false does it check in_group_p(inode->i_gid) ((mode >> 3) & 7); and only if both are false does it use mode & 7.

Look closely at directory deletion: unlink("/shared/report.pdf") mutates /shared's directory entries, not report.pdf's bytes! Consequently, a user with 0000 permissions on report.pdf can still delete report.pdf if /shared is 0777 without the 01000 sticky bit. Finally, never edit /etc/sudoers directly with vim; always run sudo visudo (or drop validated files into /etc/sudoers.d/ mode 0440), which parses grammar on a temp file before atomic rename—and if /etc/sudoers ever becomes 0777 on a desktop machine with PolicyKit active, pkexec chmod 0440 /etc/sudoers can rescue it without rebooting!

fig_m02_l02_b.svg — Unlinking a file checks w+x (03) on the parent…

Figure 2.2b. Unlinking a file checks w+x (03) on the parent directory plus the 01000 sticky owner invariant—never the victim file's mode bits.

Critical PathRequired Octal ModeConsequence of chmod 777Safe Collaborative Alternative
/etc/sudoers & /etc/sudoers.d/*0440 (root:root)sudo refuses all commands (world writable)Edit exclusively via sudo visudo -f /etc/sudoers.d/dev
~/.ssh & ~/.ssh/authorized_keys0700 dir / 0600 filesshd StrictModes rejects SSH key login silentlyUse ssh-copy-id which enforces 0700 / 0600
/tmp & /var/tmp01777 (drwxrwxrwt)0777 (without 01000) lets any UID delete others' temp filesAlways include leading 1 (chmod 1777 /tmp)
Team shared /srv/builds02775 (root:eng)0777 exposes artifacts to untrusted daemons/userschmod 2775 (setgid) + umask 0002 for group collaboration
learner@ksa: ~/gl-e00/m02-l02
learner@ksa:~/gl-e00/m02-l02$ bat -H 2 -H 5 90-arm-toolchain.sh File: 90-arm-toolchain.sh    # /etc/profile.d/90-arm-toolchain.sh (mode 0644, root:root)  # Sourced by /etc/profile using POSIX sh — NEVER use bash-only arrays here!    if [ -d "/opt/toolchains/arm-gnu-toolchain/bin" ]; then        case ":${PATH:-}:" in          *":/opt/toolchains/arm-gnu-toolchain/bin:"*) ;;            *) PATH="/opt/toolchains/arm-gnu-toolchain/bin${PATH:+:${PATH}}" ;;        esac        export PATH    fi
  1. /etc/profile is sourced by /bin/sh (dash on Ubuntu/Debian) during GUI session startup, so bashisms crash login!
  2. Idempotent case guard prevents duplicate entries while ${PATH:+:${PATH}} preserves /usr/bin:/bin.
chmod(2) at a glance — GL-E00
chmod(2)                    GL-E00 Quick Reference                    chmod(2) NAME       chmod, umask, visudo - POSIX file mode bits, creation mask, and sudoers       editor SYNOPSIS       chmod 1777 /tmp # Sticky shared directory (drwxrwxrwt) chmod 2775       /srv/builds # Setgid shared team directory (drwxrwsr-x) sudo visudo -c       # Validate /etc/sudoers syntax & 0440 permissions sh -n       /etc/profile.d/custom.sh # Parse-check POSIX login script without       executing OCTAL SUMMARY       4000 setuid | 2000 setgid | 1000 sticky 400 u+r | 200 u+w | 100 u+x       (dir traverse) 040 g+r | 020 g+w | 010 g+x 004 o+r | 002 o+w | 001 o+x Kernel Systems Academy                   Lesson 2.2                   chmod(2) GL-E00 quick reference · full manual page: man 2 chmod 

Confirming Kernel umask Masking in strace

Observe the strace output: umask(027) returns the caller's previous mask, openat(..., 0666) and mkdirat(..., 0777) pass the unmasked request to the Linux kernel, and newfstatat() proves the kernel masked the created inodes to 0640 and 0750. At the same time, our VFS verifier confirms that 01777 blocks cross-user unlinks (0) while 0777 permits them (1).

Notice one subtle contrast between openat() creation and explicit chmod()/fchmodat(): umask filters permissions only at inode creation time (O_CREAT or mkdir), whereas an explicit chmod(path, 01777) sets mode bits verbatim without consulting umask. That is why sudo and sshd call stat() directly on /etc/sudoers (0440) and ~/.ssh (0700) before trusting configuration files.

learner@ksa: ~/gl-e00/m02-l02
learner@ksa:~/gl-e00/m02-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l02./verifyumask_0027: open_0666=0640 mkdir_0777=0750unlink_check: dir_0777=1 tmp_01777_stranger=0 tmp_01777_owner=1first_match_0077_owner_bits: 00learner@ksa:~/gl-e00/m02-l02
strace — learner@ksa: ~/gl-e00/m02-l02
learner@ksa:~/gl-e00/m02-l02strace -e \trace=umask,openat,mkdirat,newfstatat,unlinkat ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3umask(027)                              = 002openat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/secret.conf", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3umask(002)                              = 027newfstatat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/secret.conf", {st_mode=S_IFREG|0640, st_size=0, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/sub", {st_mode=S_IFDIR|0750, st_size=4096, ...}, 0) = 0+++ exited with 0 +++

Desktop Login Loops, Bashisms in /etc/profile & sudo Lockouts

Respecting octal mode invariants keeps multi-user build servers and embedded root filesystems secure without locking yourself out. Use 2775 + groups for shared directories, 1777 for /tmp, 0440 via visudo for /etc/sudoers, and POSIX-clean /etc/profile.d/*.sh scripts.

Ubuntu Desktop Infinite Login Loop After Adding Bash Syntax to /etc/profile.d/:

  • Symptom: You enter your correct password on the Ubuntu GUI login screen, the screen flashes black for one second, and returns straight to the password prompt.
  • Root Cause: gdm3/lightdm Xsession sources /etc/profile and /etc/profile.d/*.sh using /bin/sh (dash), which aborts the entire session startup on non-POSIX bashisms ([[ ... ]], source, arrays) or a clobbered PATH.
  • Fix: Switch to a text virtual console with Ctrl-Alt-F3 (or SSH in), inspect ~/.xsession-errors or journalctl -b, validate /etc/profile.d/*.sh with dash -n, and ensure PATH retains /usr/bin:/bin.

Directory Marked r-- (0400) Without Execute x (0100) Bit:

  • Symptom: ls dir/ lists filenames mixed with ls: cannot access 'dir/foo': Permission denied and ?????????? stat columns, and cat dir/foo fails even though dir/foo is 0644!
  • Root Cause: Read (r, 04) on a directory permits getdents64() to read raw filename strings, but without execute/search (x, 01) the VFS refuses inode lookup (stat/open) on every child inside dir/.
  • Fix: Directories practically always pair r with x (0755 or 0750); use chmod -R a+X (capital X adds +x only to directories and already-executable files, leaving regular 0644 data files non-executable!).

Guided Practice

Test the difference between lowercase chmod -R a+x and uppercase chmod -R a+X on a scratch directory in /tmp containing one subdirectory (0700) and one regular C source file (0600). Why is capital +X essential when fixing permissions across a source tree?

Independent Practice

Extend verify.c with a check_ssh_strict_modes(uint32_t home_mode, uint32_t ssh_dir_mode, uint32_t auth_keys_mode) function enforcing OpenSSH StrictModes (!(mode & 0022) on $HOME, ~/.ssh == 0700, authorized_keys == 0600).

Verification Checks

quiz · 1 of 3

User bob (UID 1001, GID 1001) finds a file /srv/drop/calib.bin owned by root:root with mode 0400 (-r--------). The parent directory /srv/drop is 0777 (drwxrwxrwx, no sticky bit). What happens if bob runs rm -f /srv/drop/calib.bin?

quiz · 2 of 3

With umask 0027, what octal permissions are assigned to a newly created regular log file (open(..., O_CREAT, 0666)) and a newly created directory (mkdir(..., 0777))?

quiz · 3 of 3

A file secret.key has permissions 0070 (----rwx---) and ownership alice:engineers. alice is a member of engineers. What happens when alice runs cat secret.key?

Key takeaways

  • Directory permissions govern namespace operations rather than file contents: read (04) allows listing names via getdents64, execute (01) allows traversing into known child inodes, and write (02) allows creating or unlinking entries.
  • The sticky bit (S_ISVTX, octal 01000) on shared writable directories like /tmp (01777) restricts unlink and rename to UID 0, the directory owner, or the individual file owner.
  • Kernel file creation masks effective_mode = base_mode & ~umask (0666 for regular files, 0777 for directories), and recursive chmod -R 777 breaks sudo (/etc/sudoers must remain 0440) and SSH StrictModes.
  • Shell startup scripts in /etc/profile and /etc/profile.d/*.sh must preserve existing PATH entries and pass sh -n syntax validation while keeping a rescue root PTY open to prevent login loops.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure