Linux – See permissions for new files on a given directory

linuxpermissionsumask

I don't understand how my Linux machine is operating on new files.

I have an Amazon Linux AMI (RHEL based distro) and when I execute umask I get 0002, so I get whenever I create new stuff other users won't get write access.

But then I go to my home directory and I type:

$ mkdir myDir
$ touch myDir/myFile
$ ls -l | grep myDir

and I get

drwxrwxr-x 2 myself myself 4096 May 11 22:37 myDir

and for the folder:

$ ls -l myDir
-rw-rw-r-- 1 myself myself 0 May 11 22:37 myFile

So apparently there's more going on there then my umask, since myFile permissions are more restrictive than just write protection.

Digging deeper, if I try:

$ sudo touch /var/run/myPidFile.pid
$ ls -l /var/run/ | grep myPidFile.pid
-rw-r--r-- 1 root    root       0 May 11 22:42 myPidFile.pid

So myPidFile.pid gets a much more restrictive default permission, under /var/run then myFile gets under my home folder.

We could blame the root umask but if I run umask under root I get 0022 which is indeed more restrictive then my user's 0002 umask but still doesn't explain how the execution bit permission isn't set.

So how can I understand a folder's default permission on Linux?

Best Answer

The umask is most of the puzzle. Root has a different umask. This is pretty typical.

The part of the puzzle that you're missing is that the umask is a mask. When an application creates a file, it specifies some permissions; the umask is a filter for these permissions that removes some permission bits. The file only has permission bits that the application included. For example, an application that intends to create a non-executable file (such as touch) passes the permission bits 666 (in octal); with the umask 002 this results in permissions 664, i.e. rw-rw-r--: the umask removed the write-other bit. When creating a directory, the application (such as mkdir) would normally allow execution, and so specify 777 as the permissions; the umask 002 results in permissions 775 on the directory, i.e. rwxrwxr-x.

You can see what permissions the application uses by observing the system calls it makes. For example:

$ strace -e open,mkdir touch foo
… skipping opening of dynamically linked libraries etc. …
open("foo", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666) = 3
+++ exited with 0 +++
$ strace -e open,mkdir mkdir goo
… skipping opening of dynamically linked libraries etc. …
mkdir("goo", 0777)                      = 0
+++ exited with 0 +++
Related Question