Contents
https://www.debian.org/doc/manuals/debian-reference/ch01.en.html#_filesystem_permissions - Filesystem permissions in Debian Reference
https://www.debian.org/doc/manuals/debian-handbook/sect.rights-management.en.html - Managing Rights in The Debian Administrator's Handbook
Introduction
One of the key factors to system security is access permissions control. All modern operating systems support this feature. It allows file owners to restrict who can read, write, execute and otherwise change files, running processes and other parts of the system.
Linux, as every UNIX-like OS, has a built-in file permission control system. It assigns the following attributes to every file on its file system:
owner - user who owns the file, has unlimited control over it and can change other file attributes
group - group the file belongs to
UNIX permissions - a set of rules defining who can do what with the file
To see what user and group you are, run id -a in a Shell:
uid: your user name and id
gid: your primary group name and id
groups: all other groups your user belongs to.
If a particular access permission is granted to one your groups, then it will be also be granted to you.
Your effective group id (taken into account when creating files and directories, as explained below), is most of the time set to your primary group id.
Page refactoring in progress below this point
Used terms:
file system - an on-disk structure holding descriptions of files (such as the attributes mentioned above, file modification date etc.) and the files' contents themselves. File systems are contained in disk partitions (also called slices). Some of the most popular file systems today are ext4, xfs and btrfs. If you run Debian, you probably use ext4. Worth mentioning is the fact that directories ('folders') are also considered files, simply containing other files. Therefore, permissions apply to directories, too.
user group - in UNIX-like systems, every user is assigned to some group(s). Users in the same group may share rights, for example a file's permissions may be set so that all users in a group can modify its contents.
Section 2: UNIX permissions explained
Having learnt the theory, it's time to pass on to practice - what do UNIX file permissions look like and how to use them? First of all, let us examine the permissions of an example file. By issuing the following command in Linux console or a terminal emulator:
stat /etc/hostname
you will see a list of file's attributes. It includes file type (it could also be a directory, a symlink, etc.), file size et cetera and a line like the one quoted below, which is the item of our interest:
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
This file is owned by the root user (system administrator) and belongs to the root group. Before the slash, numeric user IDs are shown - that's the way they are stored in the file system. The user and group names are retrieved by looking up the numeric IDs in the password and group databases.
The Access field contains an octal number and its human-readable representation (though some people consider the numeric one to be more readable). It is crucial to know what the permission number means. It consists of four digits, ranging from 0 to 7. For now, we shall skip the first one and focus on the last three, as they are used most commonly on every system. In our example, those are 644. Each digit may be a sum of 4, 2 and 1, but not every component has to be included, giving a possible range from 0 to 7. Below is the meaning of the sum components, with Subject being user, group or others, as discussed below.
- 4 - read permission. Subject is allowed to read the contents of the file or list the content of a directory. Directory content is more than the names of the files, sub-directories, and the other filesystem objects held within each directory; it also includes other meta-information such as whether the filesystem object is a file or directory, the permissions associated with the object, and so forth.
- 2 - write permission. Subject may modify file content. With directories, it allows the subject to modify what's recorded as being in the directory. This means being able to create files within the directory, or equivalently, move files into the directory; delete files from the directory, or equivalently, move files out of the directory; and, because the directory is where there's a record of the directory content, to modify the permissions of each file or sub-directory contained in the directory.
- 1 - execute permission. Subject may execute the file. Any file may be marked executable; when the content won't execute an error is reported at runtime. Likewise any file may have execution privileges removed; files with executable content but no permission to execute can't be run. In the case of directories, execute permission lets the subject traverse through the directory into sub-directories. Note that directory traversal does not require read permission. See the note on path handling below.
Therefore, number 5, for example, would mean: a permission to read and execute, but not to write.
The digits define respectively: owner, group and others' permissions. Therefore, we can see that, in our example, file owner (root) may write to the file and read its contents, while group 'root' and other users (not being root nor a member of group 'root') are given the right to read the file.
Now, compare it to file permissions of /etc/shadow (use 'stat' again). This file has 0 as the third meaningful digit, so users not being root nor in group 'shadow' may not even read the file. You can easily confirm that by running a text editor and trying to open /etc/shadow - you, as a regular user, should not be allowed to see its contents as it contains system-wide passwords (and this is beyond the scope of this little How To).
Human-readable form
Several system tools and graphical programs recognize the idea of a human-readable form - a string of 10 consecutive characters. To see an example, issue the command below:
ls -l /etc
The -l flag tells ls to display file permissions in the left column of output. The full sequence that you might encounter is as follows (although you probably won't find such files in /etc):
-rwxrwxrwx+
Now, let's divide this into parts. The first character defines node type, which is - for normal file, d for a directory, l for symbolic link, c for a character device, p for a pseudo-terminal and b for a block device. You will find files, directories and links commonly throughout the filesystem, while devices and pseudo-terminals should only appear in /dev. Then we have 3 chunks, 3 characters each: rwx rwx rwx. They directly correspond to respective digits of permissions: if the permission is enabled, you get a letter, and if not, you get - in place of that letter. In this case, the first rwx means 7 to owner, the second is also 7 for owner's group, and the third is the world (others) permission. Thus, for example, 640 translates to:
rw-r-----
(rw- for owner, r-- for group, --- for others). The last column is the + sign. You are unlikely to see it while listing a directory now (it will appear empty), but it means that extended access rules are in effect, so the file's real permissions are not only what the file access mode says - you can read about ACL below in this howto.
A note on path handling
To access any path in the filesystem, the user (which the particular process is running as) needs at least execute privilege for all its parent directories. Therefore, if you try to access an example file /etc/security/limits.conf, even though it has a mode of 0755 (for the sake of example), it does not necessarily mean you are free to read it. To read the file, you have to be able to 'execute' all of its parent directories, so you need execute permission on /etc and /etc/security. If either /etc or /etc/security has permissions set so that you are not allowed to execute it (1), then reading /etc/security/limits.conf will fail. This rule applies anywhere in the filesystem.
The defaults for new files and directories
This section is included primarily for reference and to aid understanding. Default permissions and group assignment are not often changed so it is safe to skim over this section and come back to re-read it for more detail should the need arise.
The permissions associated with newly created files and directories are, for the most part, determined by something called a umask. The umask is a 3 digit octal number and often prefixed with extra 0 to make it clear that it is a base 8 number. The value is subtracted from 0777 to produce the default permission associated with objects newly created in the filesystem. The umask of a 'stock' Debian system is 0002 or 0022 (depending on whether user private groups are configured). For example 0022 makes the default permissions be 0755 -- the owner has all permissions, the group read and execute but not write, and everybody else can read and execute but not write. One would then expect all newly created files to be marked executable but this is prevented because the system call that creates files defaults to creating files that are not executable. Directories on the other hand do have their execute bit set, umask permitting, and so by default can be traversed by all.
The shell umask command can be used to display the current umask (without any arguments) or to change its value, see bash-builtins(7) § umask.
$ umask 0022 $ (umask 0077; touch private.log) $ echo 'default' >default.log $ ls -l total 4 -rw-r--r-- 1 test test 8 Jul 30 10:24 default.log -rw------- 1 test test 0 Jul 30 10:24 private.log
Spawned process inherits umask value from its parent and may change it using the umask(2) system call. See the Setting default umask section below how to configure default umask.
The user uid (user id number) associated with a newly created file or directory is that of the running process effective uid. In most cases this is the uid of the user who logged in and started the process.
The group associated with a newly created file or directory is the effective group of the running process. This is normally the group named with the username of the logged in user, but can be manually changed (along with the "real" group) on a per-process basis with the newgrp command although this is rarely done.
The first of the 4 octal digits which represent permissions contains the setuid and setgid bits. These can be used to override some of the defaults described above but it is not worth getting into details other than to note that the user private groups project collaboration idiom (see below) depends on the behavior of the setgid bit.
Section 3: Modifying file permissions
This section shows, using an example, the very basic usage of chmod command. Chmod is one of sysadmin's best friends and the standard tool for manipulating file permissions in various Unices (also works with *BSD and Solaris!). Let's begin... First of all, create a file for demonstration purposes. In the example, I will be using name testfile. Commands below are to be executed in a terminal emulator or Linux console. You can just copy and paste, and see how it works.
# first of all, create the file using touch command (see 'man touch' for details) touch testfile # now, let's see its permissions stat testfile # modify the file so that group members and other users can write to it chmod 666 testfile # see the new permissions stat testfile
There is a special case: to clear special bits with directories, you must mention the file mode bits explicitly (in symbolic mode) or by operator numeric mode (in octal description) (see more with: 'info coreutils, section 27.5 "Directories and the Set-User-ID and Set-Group-ID Bits")
Have the file permissions changed? You can verify that it actually worked by starting a new session and logging on to another user account, or issuing su username. If you only have one user account, create a new one for testing:
su (your root password here, to log on to root account and add a test user) adduser demo # you can remove this user when you've finished: deluser demo
Now, log on to demo, open testfile (in your regular user's home directory) and type something in it. Save, and then check with your own user's account that it contains whatever you may have written. Voila! You may now want to check it with various different permissions. Try chmod with arguments like 644, 640 and so on.
Section 4: Example scenarios involving chmod
You now know how to change file permissions. However, how can they be useful in real life besides letting your buddy leave you a random message in your own text files?
Case 1: Family photos
Situation: You store family photos in directory Photos on your user account. Several other family members use the computer and you want them to be able to access the photos.
Question: How to set directory permissions so that other users can see your files and their content?
Answer: Set the directory to 755 and all files under it to 644:
chmod 755 Photos # Photos/* means all files in Photos directory chmod 0644 Photos/*
Case 2: Software and data files for your department at work
Note on below: ~ means your home directory.
Situation: In your home directory you have a program in ~/AppSoftware/program.bin . It stores your department-specific data files in ~/OurData. The system operator has assigned you and other people in your department a user group 'mydept'. You want other people from your department to be able to run the provided software and to write the data files. At the same time, other people from outside the group should be allowed to run the software but not to modify the data. For simplicity's sake, we skip things like logging who added/removed what in terms of data (logging is a necessity in real life), focusing only on appropriate permissions.
Question: How to allow execute access for a group to one file (program binary) and read-write access to other directory for the same group, while denying world (other users) access?
Answer: In our example, this would be:
# below: -R flag, affects the directory and files/subdirs inside chmod -R 0755 ~/AppSoftware chmod -R 0770 ~/OurData
In case files have a wrong group attribute set, you can correct it by first running chgrp -R mydept files, where 'mydept' is the group name, 'files' is file path, and -R switch tells chgrp to run recursively (see above code example). Chgrp changes files' group to the one given.
Case 3: Classified files
Question: How to protect files that are to be kept secret?
Answer: A very basic protection can be achieved by chmodding the sensitive files/directories to 0600. However, remember that the system administrator (root) can still access them, regardless of set file permissions. Therefore, besides locking down file permissions, it is highly advisable that you encrypt the files using strong encryption software (try OpenPGP encryption via programs like KGpg, or see ccrypt - symmetric cryptography).
Group file sharing scenarios and the limits of basic UNIX permissions
Examples above show the usefulness of UNIX file permissions. You can grant users from your group access to your files, expose them to the whole world or have them only for yourself. However, there are use cases in which this access control model is not enough. Assume that you are on a large system (perhaps a server) and, together with several dozen users you are members of group 'users'. Now, you want to make some of your files available to just one of them so that the others can not read it. How can UNIX permissions benefit you? You could use the user private groups directory sharing idiom; a common solution to this problem. But the user private groups idiom pushes the UNIX permission system to its limits and there are cases, even simple file sharing cases between 2 people, where the idiom is simply not suitable.
When the limits of basic UNIX file permissions are reached it is time to make use of...
Access Control Lists in Linux
Access Control Lists (called ACL) are an extended means of defining access rights to files and objects. They allow you to specify file permissions in a more fine-grained way, assigning any user or group (besides owner and file's set group) different privileges. For instance, you may share a file with just one specific user, no matter what group they are in. How to make use of this new, powerful feature?
First, make sure your system supports ACL. Several criteria must be met before you can enable ACL for your files. Check your kernel version. If it is anything later than 2.6.18, then chances are you already have ACL support built-in. (I'm not quite certain at which version Debian kernels received the ACL patch). The next thing is acl package, required for ACL attribute manipulation. You can install it by issuing:
# if you are not logged on as root, use 'su' first apt-get install acl
Alternatively, you can use Synaptic package manager, or another package manager, to get and install the package. If you are not the system administrator, ask your sysadmin to enable ACL on your machine.
Once you have installed acl, you can try and see if your file system supports it. Example command (I assume that file 'testfile' exists):
setfacl --modify user:demo:5 testfile
If setfacl complains about an error, you probably need to mount your filesystem with acl option. Assuming that the filesystem 'testfile' is located on is / , execute the below as root:
mount -o remount,acl /
Try setfacl again. If successful, a call to:
getfacl testfile
should show, among others, a line like this:
user:demo:r-x
Here, rx means 'read, execute' permission, which is equivalent to 5. To see if Access Control Lists work, set the file permissions on testfile to 700 using chmod and try to open it from 'demo' user account. If successful, ACL did override UNIX permissions indeed. Your file system is now ready for granular access control with ACL!
Note: To enable ACL permanently for certain filesystems, you should include acl option in /etc/fstab. Please refer to fstab(5) manual page for instructions.
Example uses of setfacl to manage file permissions
setfacl -R -m user:josh:6 filedir # sets read-write permissions for josh on filedir and all its contents setfacl -m group:junior-sys-admins:4 /var/log/apache2/error.log # let group members of junior-sys-admins read Apache2 error log file setfacl -m user:evilcraig:0 my_notes.txt # prevent user evilcraig from accessing my_notes.txt
Default (inherited) ACL
Note: a bug in coreutils commands cp and mv limits the scope of the below to pure file creation, e.g. with touch: with copy and move, the "Default mask" of the target parent directory won't be inherited as the "Access mask" for the copied/moved file/directory: http://debbugs.gnu.org/db/85/8527.html
Default ACL are an invaluable tool when making a directory that you want to share for reading or writing among users. This hint is inspired by this thread on the Debian forums: http://forums.debian.net/viewtopic.php?f=10&t=53591
Default ACL are access control entries that get inherited by all sub-items of a directory (recursion deeper is allowed!). Thus, if you want to create a directory for bob and fred so that both can work on each other's files, the below should suffice (notice the -d flag to setfacl, it sets a default ACL):
mkdir common_workspace setfacl -m u:bob:7 common_workspace setfacl -d -m u:bob:7 common_workspace setfacl -m u:fred:7 common_workspace setfacl -d -m u:fred:7 common_workspace
Note to the above: a default ACL is inherited by all child nodes as an ACL entry and default ACL, but a default ACL on its own does not take any action permission-wise - hence the double command. The first call gives user 'bob' the right to write, read and execute the directory, and the second one sets up the default ACL which will be inherited.
Now, whenever a file gets created, it retains its original owner and group, but should automatically get assigned the above ACL. This is, for example, useful when you have users co-working on website development. You can use Apache or PHP running as www-data, write a script to change file ownership upon creation to www-data (inotify helps!), and all files are still writable by bob and fred, your Web developers.
Appendix: Some hints
- On Debian systems, every user is traditionally assigned their own group. File sharing may be accomplished by adding one user to other's group, as shown below (only to be done as root):
adduser me otherguy # adds user 'me' to group 'otherguy'
Then, 'otherguy' can just set their files to 0750 or whatever permissions they want you to have. However, this is the old-fashioned approach to granular file permissions and should be avoided whenever possible in favour of user private groups or ACLs.
Konqueror (at least in Debian Squeeze) supports ACL out-of-the-box when filesystems are mounted with acl option. It allows for easy, graphical management of extended access rights, similar to that of Microsoft Windows.
Sometimes you have to mount a filesystem that does not support ACL. For example, a NFS volume exported by a central storage solution, or an userspace zfs diskset. In these situations, you can try one simple solution: http://cintrabatista.net/nfs_with_posix_acl.html
You can find a wonderful but pretty old (still current, though) ACL guide here: http://www.vanemery.com/Linux/ACL/linux-acl.html
That's all! Have fun and thanks for bearing with me.
Setting default umask
https://www.debian.org/doc/manuals/securing-debian-manual/ch04s11.en.html#idm1514 - Setting users umasks in Securing Debian Manual
Umask affects permissions for new files and directories. Examples of wide spread values:
022 is the default for Debian 12 bookworm and earlier. It is reasonable balance for cooperation with other users. Files may be read and executed by other users, but they can not modify content. Unfortunately users have to explicitly make files group-writable inside shared directories.
002 is suitable for active usage of shared directories. It requires configuration of user private groups (enabled by default) and dangerous for users having no own group. If user primary group is not their private group then all members of that group (e.g. a whole department) have chance to modify almost any user's file, in some cases it applies to whole home directory. Pay attention to security consideration and CAUTION sections of the article on user private groups. Since Debian Trixie it is default for users with proper primary group and 022 otherwise. Debian 12 bookworm requires explicit pam_umask configuration with usergroups option (see below).
077 or 007 may be appropriate for users seeking privacy when other users should not be able to read files, maybe besides a specific group.
Citing /etc/login.defs: "There is no One True Answer here: each sysadmin must make up his/her mind". You may find some links to discussions in Debate/umask.
Setting umask is similar to configuring EnvironmentVariables in some aspects and adding umask 077 to ~/.profile or ~/.bashrc may not be enough despite you may notice this recipe in various guides. In the past umask for all users were set in the /etc/profile file, but it was changed in 2010 (#583967), so use PAM instead.
System-wide umask configuration
Be careful if you decide to change default umask value. Restrictive value may make files or directories not readable or writable by users who should have access. The worst case is broken applications that could not read config files. The opposite case is group write bit not cleared by umask combined with inappropriate default group.
- System administrator often create files that must be world readable. Pay attention that umask for root is overridden by 022 for all ways to acquire privileges:
su with and without -/--login option, sudo with various options like -i/--login, sudoedit, ssh, virtual terminal.
Setting umask 022 in ~/.profile or ~/.bashrc is not enough since e.g. sudo may execute commands directly with no shell involved.
With restrictive umask explicit chmod may be required to make files accessible for e.g. web server.
Since Debian 12 Bookworm home directories for users are created with 0700 permissions by default, so most of user files are protected despite default permissive umask. Permissions of earlier created directories may be changed in the same way. As an alternative to umask it is not ideal. Files created in /tmp are not protected unless every application explicitly sets umask or permissions. In some cases home directory must be traversible for other users. Examples are ~/public_html for Apache and unprivileged LXC containers. Possible solutions are access control lists or world execute bit without read one for the home directory.
System-wide umask is configured in the /etc/login.defs file. Read comments there and login.defs(5).
UMASK 077
In Debian 12 Bookworm and earlier releases, pam_umask(8) is missing in PAM configuration. As a result, the value specified in etc/login.defs is not applied. Because of this, umask is not reset when a user executes e.g. su - to run some commands as administrator. This group of bugs is fixed in Trixie (see e.g. 583958).
To fix this locally, check that the /etc/pam.d/common-session and /etc/pam.d/common-session-noninteractive files contain
session optional pam_umask.so usergroups
and add the line otherwise. In Trixie usergroups may be omitted, it is default set through a build option.
Consider setting HOME_MODE in /etc/login.defs as well since otherwise UMASK affects permissions for home directories created by useradd(8). In Debian however the recommended tool is adduser(8) that ignores login.defs and reads adduser.conf(5) instead. (With default settings adduser and adduser create home directories with different permissions.)
Per-user umask settings
Depending on login type and the way a particular process is started the following options may be applied:
umask 007 shell built-in placed in ~/.profile or an equivalent file for virtual terminal or ssh login. In the case of graphical login some display managers, e.g. SDDM may read this file as well.
umask 007 shell built-in in an Xsession file, e.g. ~/.xsessionrc for graphical login and X11 session.
UMask=007 systemd directive from [Service] section, see systemd.exec(5) § PROCESS PROPERTIES for processes started by systemd. It is applied to some processes for any login type. Some desktop environments may start all application as or from services that belong to systemd user session.
systemd-homed(8) has its own way to specify user's umask.
Have in mind that umask value may be preserved by su and sudo unless pam_umask is enabled, see System-wide umask configuration.
For processes started through system user session system administrator may create override files for specific UID's, e.g /etc/systemd/system/user@1000.service.d/umask.conf (source)
[Service] UMask=0007
and run
systemctl daemon-reload
A user who cannot modify system files may drop the same file into ~/.config/systemd/user/service.d/ and it will be applied to all services in their user session; see systemd.unit(5) § EXAMPLES. It is necessary to log out and log in again to make this change effective. It is not enough systemctl --user daemon-reload, in addition running application launcher should be restarted as well. Use UMask=0077 if the user does not have its private user group.
See also
CategoryCommandLineInterface | CategorySystemSecurity | CategorySystemAdministration | ToDo: refactor
