Skip to content
shellhacks.dev
Security

Create files with safe permissions

Set umask 077 before creating files so only the owner can read them. The default 022 leaves new files readable by every local user.

1 min read
Summarize in AI

A script writes a token or a backup, and the file must not be readable by other users on the machine.

Shell
umask
touch default.txt
(umask 077; touch private.txt; mkdir private-dir)
stat -c '%a %n' default.txt private.txt private-dir
Text
0022
644 default.txt
600 private.txt
700 private-dir

The umask is a mask of permission bits removed from the mode a program asks for. With 022 a new file gets 644, and with 077 it gets 600, while a directory gets 700 instead of 755. The behavior is specified for the umask utility. Running the change in a subshell, as the second command does, confines it so the rest of the script keeps its normal mask.

The umask only affects files created after it is set, and not a file that already exists. A file that gets its mode from another program, such as one copied with cp -p, keeps the source mode. For one file, install -m 600 /dev/null file creates it with the right mode from the start, while chmod after creation leaves a short window where the mode is wrong.

Share

More snippets

Security

Avoid predictable temp names

Never build a temp file name from $$ or a fixed string. An attacker who guesses it can plant a symlink, and mktemp picks an unused random name with mode 600.

1 min read
Security

Avoid eval on input

Never pass input to eval. Run a command held in an array as "${cmd[@]}", or escape a value with printf %q when eval cannot be avoided.

1 min read
Security

Validate input with a whitelist

Validate input against a list of allowed values with a case statement. A grep check with ^ and $ can be fooled by a value that holds a newline.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.