Wednesday, April 27, 2022

[SOLVED] CHMOD vs UMASK - Linux file permissions

Issue

In a script, should I create a file first and then, use CHMOD to assign permissions (Example- first using TOUCH command to create a file and then, using CHMOD to edit permissions on that file) "OR" should I mask permissions using UMASK as I create a file ? Also, please explain what are the pros and cons of choosing one over another ?

Note: This file doesn't need to be executed.


Solution

As with most things, it depends on far more information than you've given :-)

However, it's usually a good idea to do things in a closed manner then open them up, rather than the other way around. This is basic "Security 101".

For example, let's say you're creating a file for the user and the user has foolishly selected a umask of zero (effectively all files created will have full permissions for everyone).

In that case, the file is fully open for anyone to change between the creation and chmod stage and, while you can minimise this time, you cannot really remove it totally.

For the truly paranoid among us, it would be better to actually create the file in as closed a manner as possible (probably just rw for owner), do whatever you have to do to create the content of that file, then use chmod to open it up to whatever state it needs to be, something like:

( umask 177 ; create_file myfile.txt ; chmod 644 myfile.txt )


Answered By - paxdiablo
Answer Checked By - Terry (WPSolving Volunteer)