Skip to content
Visual explainer 2h 30m to learn 4 steps

Directories, permissions & umask

Walk directory trees and create files with the intended permissions.

By Invicly Tech, , in Linux System Programming. About 12 minutes to read.

Topic 13 of 42

In short

Directories are special files you read with opendir and readdir. Every file has an owner, a group and nine permission bits: read, write and execute for user, group and others. The process umask clears bits from the mode you request, so open with 0666 usually produces a 0644 file.

Explained simply

A directory is a special file whose content is a list of names, each with an inode number. You cannot read it with read(); that fails with EISDIR. Instead you use opendir and readdir, which hand you one entry at a time.

Every file and directory has an owner, a group and permission bits for three classes: the owner, the group, and everyone else. The kernel picks exactly one class for you, the first that matches, and uses only those bits.

When your program creates a file, it asks for a mode such as 0666. The umask, a per-process setting inherited from the parent, then removes bits. With the usual umask 022, you get 0644: you can write, others can only read.

Later you can change the mode with chmod, or fchmod on an open descriptor. Only the file's owner (or root) may do that. Knowing these rules lets your program create files that are exactly as private or as shared as you intend.

Press Play on a diagram to walk through it one step at a time.

Comparerwx on files vs directories
File
  • r: read the contents
  • w: modify the contents
  • x: run it as a program
  • Deleting it depends on the directory
Directory
  • r: list the names
  • w: create, delete or rename entries
  • x: enter it and access entries by name
  • w without x is useless
FlowThe umask arithmetic
  1. Step 1
    Requested 0666

    rw-rw-rw- from open(..., O_CREAT, 0666)

  2. Step 2
    umask 0027

    Remove write for group, everything for others

  3. Step 3
    0666 & ~0027

    Bitwise AND with the inverted mask

  4. Step 4
    Result 0640

    rw-r----- (a directory from 0777 gets 0750)

CompareWays to walk a directory tree
opendir and readdir
  • One level at a time
  • You write the recursion
  • Full control over order and errors
nftw
  • Calls your function for every entry
  • FTW_PHYS: do not follow symlinks
  • FTW_DEPTH: children before parents, good for deleting
fts
  • Iterator style: you pull the next entry
  • Used by GNU tools such as rm, du and chmod
  • Can skip or revisit entries

In depth

How readdir really works

opendir opens the directory and allocates a buffer. readdir then calls the getdents64 system call, which fills that buffer with many entries at once, and hands them out one by one with no further system calls. strace on ls shows only a few getdents64 calls even for a large directory.

Entries are not sorted. Their order depends on the file system; on ext4 it follows a hash of the names. Sort them yourself if you need order. The d_type field tells you whether an entry is a file, directory or symlink without an extra stat call, but some file systems return DT_UNKNOWN, so be ready to fall back to lstat or fstatat.

readdir returns NULL both at the end and on error. To tell them apart, set errno to 0 before each call and check it afterwards. Files created or deleted while you iterate may or may not show up.

Sequencereaddir hides the real system calls
Your code
glibc
Kernel
  1. 1opendir("logs")
    Your code to glibc: opendir("logs")
  2. 2openat("logs", O_DIRECTORY)
    glibc to Kernel: openat("logs", O_DIRECTORY)
  3. 3first readdir()
    Your code to glibc: first readdir()
  4. 4getdents64(fd, buf, size): many entries at once
    glibc to Kernel: getdents64(fd, buf, size): many entries at once
  5. 5next readdir() calls: served from the buffer
    Your code to glibc: next readdir() calls: served from the buffer
  6. 6getdents64 returns 0: readdir returns NULL
    glibc to Kernel: getdents64 returns 0: readdir returns NULL

Directory permissions in practice

On a directory, r lets you list the names, x lets you use a name inside it (open, stat or enter), and w lets you create, delete or rename entries, which also needs x. These combine in useful ways. Mode 0711 on a home directory lets others reach a file whose name they know, such as public_html, without being able to list anything. With r but no x, ls shows the names but question marks for everything else, because it cannot stat the entries.

To open a file, you need x on every directory on the path, plus the right bit on the file itself. When a deep path gives "Permission denied", namei -l shows the permissions of each step so you can find the one that blocks you.

Deleting a file depends only on the directory, not on the file's own bits. The sticky bit (mode 1000, as on /tmp) adds a rule: only the file's owner, the directory's owner or root may delete it.

FlowCan I read /srv/app/conf/db.ini?
  1. 1
    x on /

    May use names in the root directory

  2. 2
    x on /srv

    May use the name app

  3. 3
    x on /srv/app

    May use the name conf

  4. 4
    x on /srv/app/conf

    May use the name db.ini

  5. 5
    r on db.ini

    May read the content: open succeeds

umask in code

umask(mask) sets the process's mask and returns the old one; there is no call that only reads it. The common trick is old = umask(0); umask(old). On Linux 4.7 and later you can also read the Umask: line in /proc/self/status. Because the umask is shared by every thread in the process, changing it in a multithreaded program affects the other threads too.

The umask applies whenever something is created: open with O_CREAT, mkdir, mkfifo, mknod, and binding a Unix socket to a path. It does not apply to chmod or fchmod, which set exactly the bits you give. A default ACL on the parent directory takes the place of the umask for new files inside it.

The usual convention is to ask for 0666 for files and 0777 for directories and let the user's umask decide. For secrets such as keys and tokens, ask for 0600 directly, because the umask can only remove bits, never add them. A systemd service can set its mask with UMask= in the unit file.

chmod, fchmod and avoiding races

chmod(path, mode) changes the file found at a path. fchmod(fd, mode) changes the file you already have open, and fchmodat works relative to a directory descriptor. Prefer the descriptor versions when the path might change between steps, because an attacker could swap the path for a symlink between your check and your chmod.

The classic mistake is creating a secret file with 0644 and calling chmod 0600 afterwards. For a short moment anyone can open it, and an open descriptor stays valid after the chmod. Create it with the right mode from the start.

Only the owner or a process with CAP_FOWNER (normally root) can change a mode. Two quiet rules surprise people: if you are not a member of the file's group, chmod silently clears the setgid bit you asked for, and changing a file's owner clears setuid and setgid bits on executables.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Iterate directories with opendir and readdir~40m
  2. 2
    Explain rwx bits on files and directories~40m
  3. 3
    Apply umask to new files~40m
  4. 4
    Change modes with chmod and fchmod~40m

Key points

  • Final mode = requested mode & ~umask.
  • Deleting a file needs write and execute on its directory, not on the file.
  • readdir also returns . and .., so skip them when walking trees.
  • Use nftw or fts for recursive walks instead of hand-rolled recursion.

Key terms

Tap a card to flip it. 0/5 known

Examples

c
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
  DIR *d = opendir(argc > 1 ? argv[1] : ".");
  if (!d) { perror("opendir"); return 1; }
  struct dirent *e;
  while ((e = readdir(d)) != NULL) {
    if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
    printf("%lu %s\n", (unsigned long)e->d_ino, e->d_name);
  }
  closedir(d);
  return 0;
}

List a directory with inode numbers, like ls -i.

A simple du with nftw

You want the disk space used under a directory. Step 1: nftw walks the whole tree and calls add for each entry, passing a struct stat it already filled in. Step 2: FTW_PHYS stops it from following symlinks, so a link to / cannot send it across the whole disk. Step 3: for each regular file, add st_blocks times 512, the real space used. Step 4: return 0 to keep walking; any other value stops the walk. Unlike real du, this counts a file with two hard links twice.

c
#define _XOPEN_SOURCE 700
#include <ftw.h>
#include <stdio.h>
#include <sys/stat.h>
static long long total;
static int add(const char *path, const struct stat *st, int type, struct FTW *f) {
  (void)path; (void)f;
  if (type == FTW_F) total += (long long)st->st_blocks * 512;
  return 0;                        /* keep walking */
}
int main(int argc, char **argv) {
  if (nftw(argc > 1 ? argv[1] : ".", add, 32, FTW_PHYS) == -1) { perror("nftw"); return 1; }
  printf("%lld bytes on disk\n", total);
  return 0;
}

Create a private file the right way

A program stores an API token. Step 1: create the file with mode 0600 in the same open call, and O_EXCL so you never reuse a file someone else prepared. Step 2: check the result with fstat on the descriptor; whatever the umask, 0600 stays 0600 because the umask can only remove bits. Step 3: write the secret. The wrong version, creating with 0644 and calling chmod afterwards, leaves a window in which another user can open the file and keep the descriptor.

c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
  int fd = open("token.txt", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
  if (fd < 0) { perror("open"); return 1; }
  struct stat st;
  if (fstat(fd, &st) < 0) { perror("fstat"); return 1; }
  printf("mode %04o\n", (unsigned)(st.st_mode & 07777));   /* 0600 */
  if (write(fd, "s3cret\n", 7) != 7) { perror("write"); return 1; }
  return close(fd) < 0;
}

Quick reference

  • Set errno = 0 before readdir; NULL with errno still 0 means the end of the directory
  • d_type can be DT_UNKNOWN on some file systems; fall back to lstat or fstatat
  • On a directory: x = may use names inside, r = may list them, w + x = may add or remove
  • namei -l /path/to/file shows the permissions of every directory on the way
  • old = umask(0); umask(old); reads the umask, or see Umask: in /proc/self/status
  • Create secrets with open(..., O_CREAT | O_EXCL, 0600), never chmod them afterwards
  • fchmod(fd, 0640) changes the open file itself, immune to path swaps
  • nftw(dir, fn, 16, FTW_PHYS | FTW_DEPTH) visits children before parents, good for deleting

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A directory has mode 0711 (rwx--x--x). What can another user do?

Question 2

2With umask 077, what mode does mkdir(path, 0777) produce?

Question 3

3readdir returned NULL. How do you tell the end of the directory from an error?

Question 4

4Which of these is not affected by the umask?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Check your umask, predict the modes of a new file and a new directory, then create both and confirm with stat.

  2. Exercise 2medium

    List a directory and print a type letter (d, f, l or ?) before each name, using d_type and falling back to fstatat when it is DT_UNKNOWN.

  3. Exercise 3hard

    Write int rmtree(const char *path) that deletes a whole directory tree, like rm -r, without following symlinks.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why does ls -l show question marks for everything in a directory?
You have read permission on the directory but not execute. You can list the names, but the kernel will not let you look up each entry to get its details.
Why could someone delete my file when they cannot write to it?
Deleting changes the directory, not the file, so it needs write and execute permission on the directory. Set the sticky bit on shared directories, as /tmp has, to stop that.
Why is the order of readdir results random?
The kernel returns entries in the order the file system stores them, which on ext4 follows a hash of the names. Collect the names and sort them if you need a stable order.
What is the difference between chmod and fchmod?
chmod looks the file up by path every time, while fchmod changes the file behind a descriptor you already opened. fchmod cannot be tricked by someone replacing the path in between.

Go deeper

ShareXLinkedInWhatsApp