HackBlue

Tools · Linux command line for security · 03 / 28

What umask does on Linux and how to set safer default permissions

Learn how umask subtracts bits from new files and directories, check the current value, and set 027 for service accounts and shared servers.

8 min read · practice only with authorization

A mask, not a mode

When a program creates a file, it asks for a mode, usually 666 for files and 777 for directories. The umask removes bits from that request. With the common default 022, files become 644 and directories 755. With 027, files become 640 and directories 750, so “others” get nothing.

umask only affects new files. It never changes existing ones, and a program can still call chmod afterward, so it is a default, not an enforcement.

Snippet
umask
umask -S
(umask 027; touch t1; mkdir d1; ls -ld t1 d1)

Where the value comes from

Interactive shells read umask from /etc/login.defs through PAM, /etc/profile, or shell startup files. systemd services ignore those and use UMask= in the unit file, which defaults to 0022. That difference is why a service can create world-readable logs even when your login shell uses 027.

Check a running process’s umask with grep Umask /proc/PID/status.

Lab: tighten a service’s default

Write a tiny systemd service that touches a file in /var/lib/demo. Start it and check the mode, likely 644. Add UMask=0027 to the [Service] section with systemctl edit, restart, delete the file, and start again. The new file should be 640.

Then set UMASK 027 in /etc/login.defs on a lab shared server and log in fresh to confirm the shell picks it up.

Snippet
sudo systemctl edit demo.service
# add:
[Service]
UMask=0027

sudo systemctl restart demo.service
ls -l /var/lib/demo/
grep Umask /proc/$(pgrep -f demo)/status

Choosing a value

022 suits single-user desktops. 027 suits shared servers and service accounts, because it keeps files away from unrelated users. 077 is for very sensitive accounts, at the cost of making group collaboration harder.

Pair umask with correct ownership. A good umask on a directory owned by the wrong group still shares with the wrong people.

Diagram

umask 022 versus 027 on new files

Same program, same requested mode.

022

File. 644: everyone can read.

Directory. 755: everyone can list and enter.

Fits. Single-user desktops.

027

File. 640: owner and group only.

Directory. 750.

Fits. Servers and service accounts.

Check yourself

1. With umask 027, what mode does a new file requested as 666 get?

2. Where does a systemd service get its umask?

3. Does changing umask fix existing world-readable files?