Part 4 of 7 · 2 min read
umask and directories
Think of a stamp that blanks out parts of a form before it is printed. The stamp (the umask) removes some of the rights that the form asked for. The analogy stops in one place: a stamp can be undone, while the umask only ever removes rights from new files.
In plain words: A program that creates a file asks for a mode, usually 0666 for files and 0777 for directories. The kernel removes the bits that are set in the process's umask. A umask of 022 removes the write bits for group and others. The mode of a new file is requested AND NOT umask. On a directory the bits mean something else. Read lets you list the names, write lets you create, delete and rename entries inside it, and execute (called search) lets you pass through it to reach a name. To open /a/b/c a process needs the execute bit on /a and /a/b. The sticky bit on a directory lets only the owner of a file, or of the directory, delete or rename that file. It is set on /tmp.
A worked example. On the test machine, files and a directory were created under two umasks:
umask 022: touch u022 -> 644 mkdir d022 -> 755
umask 077: touch u077 -> 600
With umask 022: 666 AND NOT 022 = 644, and 777 AND NOT 022 = 755. With umask 077: 666 AND NOT 077 = 600. A umask of 027 would give 640 for files and 750 for directories. The sticky bit appears as a t at the end of the mode: /tmp shows drwxrwxrwt. Everyone may create files there, and nobody may delete the files of another user.
The key lines. The system file /etc/shadow has mode -rw-r----- and is owned by root (the test machine shows exactly this), so ordinary users cannot read the password hashes, while /etc/passwd is world-readable.
umask
The umask is a per-process mask of permission bits that the kernel removes from the mode requested when a file or directory is created. The resulting mode is the requested mode with the bits in the umask cleared.
Example: with umask 027, a new file requested with 0666 gets 0640.
Common mistake
Execute permission on a directory is not the same as on a file. A directory without x cannot be entered, even if it has r and you can see its names. A script with chmod 644 on an executable program cannot run, and a directory with chmod 644 cannot be used.
Check yourself:
1. What mode does a new file get with umask 027?
2. What does the w bit allow on a directory?
3. What does the sticky bit on /tmp prevent?