chmod 400 sets the mode to r--------: the owner can read (4), nobody can write or execute, and the group and everyone else get nothing (0). It’s the strictest mode that still lets the owner read the file: a secret that one user reads and nobody should change.
The AWS key pair case
AWS’s EC2 guide tells you to run chmod 400 on the .pem file you download. A download usually comes out 644, and ssh refuses a private key that the group or others can access:
chmod 400 ~/Downloads/my-key.pem
ssh -i ~/Downloads/my-key.pem [email protected]
stat -c '%a %n' ~/Downloads/my-key.pem # 400 /home/alice/Downloads/my-key.pem
ssh accepts 400 and 600 alike. The only difference is that 400 also stops you overwriting the key by accident.
What 400 doesn’t stop
- The owner changing it back. Only the owner or root can
chmoda file, and the owner always can. - Deletion. Removing a file takes write on the directory, not on the file.
rmasksremove write-protected regular file?and then deletes it. - Replacement. Tools that save by writing a new file and renaming it over the old one, such as
sed -i, succeed in a directory you can write. - Root. Root’s reads and writes ignore the permission bits.
So 400 is a guard against mistakes and against other users, not against the owner or an administrator.
Not for directories
A 400 directory lets its owner list names, but without execute nobody but root can open anything inside or cd into it. A directory of keys wants 700, with 400 or 600 on the files.
In git, Kubernetes and Docker
- Git can’t keep it. It stores
100644, and every checkout recreates the file as666with the umask cleared,644under022, so apply400in the deploy step, after checkout. - Kubernetes:
defaultMode: 0400on a Secret volume, or256in JSON. The default is0644. - Docker Swarm mounts secrets under
/run/secrets/as0444by default;docker service create --secret source=key,mode=0400narrows it.