The Linux Newbie Guide  ⇒    Fundamentals     Advanced     Supplement   Command Index   ENG⇒中
All rights reserved, please indicate the source when citing
 

 File Ownership and Permissions

1.0 File Owners and Permissions
       Ownership
       Permissions
       Directory Permissions
       Special Permissions
           Sticky Bit
           SGID (Set Group ID bit)
           SUID (Set User ID Bit)
       chmod : Change File Permissions
           Numerical representation
           Symbolic representation
       Symlink Permissions
       umask: Change Default File Permissions
1.1 File Attributes
       chattr : Change File Attributes
       lsattr : Display File Attributes
ENG⇒中ENG⇒中
  1.0 File Owners and Permissions

As mentioned in the file-related commands: "File extensions in Linux are for "reference" only; for example, Linux executables do not use ".exe" as an extension like in Windows.

So how does Linux determine which files are executables? Why can't you enter certain directories when logged in as a regular user? Why can't you delete any files except those you created? Why are many files unreadable? Everything is related to file "ownership" and "permissions". Before we explain, let's experience it firsthand.

Example: (Test with a regular account, do not log in as root because the Superuser is not subject to permission restrictions)
$ cd /root ←← Try entering the `/root` directory
bash: cd: /root: Permission denied ←Permission denied
$ cat /etc/shadow ← Try reading the account password information file `/etc/shadow`
cat: /etc/shadow: Permission denied ← Permission denied
$ cp /etc/shadow ~/ ←Try copying `/etc/shadow`
cp: cannot open '/etc/shadow' for reading: Permission denied ←Permission denied
$ rm -f /bin/ls ←Try deleting the command `/bin/ls`
rm: cannot remove `/bin/ls': Permission denied ←Permission denied

Ownership
Because Linux is a multi-tasking & multi-user OS, that is, it can be used by many people, so there must be some mechanism to properly isolate the reading and writing of files by different logins. Write, execute and delete, or even enter a certain directory, this security mechanism is the "ownership" and "permission" of the file. The owner category of Linux files can be divided into " owner" (user), "group" and "others" as follows:


Because Linux is a multi-tasking, multi-user operating system, meaning many people can use it, there must be a mechanism to properly isolate different logged-in users' ability to read, write, execute, delete files, and even enter certain directories. This security mechanism is file "ownership" and "permissions".

Linux file owner categories can be divided into "user or owner", "group", and "other", as follows:

When logging into Linux, there are actually two identities: the logged-in user and the group accompanying the logged-in user. If a file is created, this file will record these two identities.

Example: :
$ echo "hello Wold" > /tmp/myfile ←Create a file `myfile`
$ ls -l /tmp/myfile ←Use `ls -l` to list detailed file information
-rw-rw-r-- 1 aaa aaa 11 2011-10-10 10:10 myfile ←The red marked text is the user, the green marked text is the group

^ back on top ^


Permissions
File permissions determine whether the owner (user/group/other) has the ability to "read," "write," or "execute" the file (Linux executables are not determined by file extensions, but by having "execute" permissions).These file permissions, except for the execute permission for root, are otherwise ineffective. This means that if you log in as "root", you can do anything you want, such as deleting or tampering with files, as if there were no restrictions.

Let's review the example when introducing the ls command, which uses ls -l to list detailed file information, as follows:

$  ls -l ← List detailed file contents
drw-rw-r-- aaa  aaa  292 2011-09-07  11:44  myfile
 ↑    ↑  ↑         
 permission   user  group        

In the above example, the "permissions" column lists 9 characters in total. For easy identification, it is deliberately displayed in different colors for illustration. The 9 characters of the permission are similar to "rwxrwxrwx" , representing three different ownership The meaning is as follows:

In the example above, the "permissions" field lists a total of 9 characters. For easy identification, different colors are used to explain them. The 9 permission characters are similar to "rwxrwxrwx", representing three different owner meanings as follows:


The characters "r", "w", and "x" (the order "rwx" is fixed) appearing in the file permissions field represent read, write, and execute permissions for the file, respectively. Permissions that are not set are displayed as "-". For example,"r--" means only read permission.

The table below shows the effects of permissions on files:
Permission Effect on File
r (read) Can view the content of the file, e.g., can be read using cat, less, or other tools.
w (write) Can modify its content, e.g., can be modified using vi or by redirection for appending.
x (execute) If it's an executable file, it can be executed. However, if it's a shell script, it also needs read permission to be executed (because the shell needs to read the file).

Example:
$ ls -l /tmp/myfile
-rw-rw-r-- 1 aaa aaa 11 2011-10-10 10:10 myfile

In the example above, the ls -l output shows permissions as "rw-rw-r--". The first character in red, "r", means the owner (account aaa) has "read" permission for this file. The second character, "w", means the owner has "write" permission. The third character, "-", means the owner has no execute permission.

Similarly, the green characters mean that the "aaa" group also has read and write but no execute permissions for this file, while "other" (anyone not defined as owner or in a group) can only read but not write.

Next, let's test with different accounts.

Example:
$ echo "hello Wold" > /tmp/myfile ←Create a file `myfile`
$ ls -l /tmp/myfile ←Verify permissions
-rw-rw-r-- 1 aaa aaa 15 2011-09-07 00:46 /tmp/myfile ←Same owner/group can read and write, but other can only read
$ cat /tmp/myfile←Try reading (testing `read` permission)
Hello Wold
$ echo 'Hello Linux' >> /tmp/myfile ←Try changing the content of `myfile` (testing `write` permission)
$ cat /tmp/myfile ←Verify
Hello World
Hello Linux
$ su bbb ←Temporarily change to another account
Password: ←Enter the account password
$ cat myfile ←Test `read` permission
Hello World ←This file has `read` permission for "other", so everyone else can read files created by account `aaa` Hello Linux
Hello Linux
$ echo 'Hello Unix' >> /tmp/myfile←Try adding content to `myfile`
bash: /tmp/myfile: Permission denied ←Permission denied (because `other` has no `write` permission for this file)

Let's look at other examples.

Ex:
$ ls -l /etc/shadow ←List detailed file information for the account password file `/etc/shadow`
-r-------- 1 root root 1147 2011-09-07 11:47 /etc/shadow

In the example above, the file "/etc/shadow" is the shadow file for account passwords. Although its content is encoded in ASCII text, it has been encrypted from plaintext to ciphertext. Because this file is very important and could be cracked by hackers to find login passwords for each account, its owner and group are both root, and its permissions are displayed as "r--------", meaning this file can only be read, not written to, even if logged in as "root". However, "cannot write" is more of a declaration than a practical restriction for "root", as the "root" account has unlimited privileges.

Let's look at what the owner and permissions of a typical executable file look like.

Example:
$ ls -l /bin/cat
-rwxr-xr-x 1 root root 23360 2007-10-31 11:52 /bin/cat

In the example above, the cat command's owner and group are "root", and it has full read, write, and execute permissions. For non-root owners and groups, users of this command are considered "other" and can only read and execute.

Additionally, some commands like cp change the owner and group of the destination file to that of the operator. The purpose of this is to allow the copied file to be fully controlled.

Example: (Please test with a regular account)
$ cp /bin/cat ~/ ←Copy `/bin/ls` to the home directory
$ ls -l /bin/cat  ~/cat ←List these two files for comparison
-rwxr-xr-x 1 root root 23360 2007-10-31 11:52 /bin/cat
-rwxr-xr-x 1 aaa  aaa  23360 2011-10-10 10:10 ./cat ←Notice how the owner and group of the copied file changed to that of the operator

So how do you keep the copied file exactly as it was? For example, when backing up system files, you can't just change the original owner and permissions, otherwise, restoring the system could lead to chaos. Using the cp -a or cp -p options will preserve the original file's owner and permissions.


^ back on top ^


Directory Permissions
Directory permissions function somewhat differently from file permissions, as shown in the table below:
permission Effect on Directory
r List files or subdirectories within the directory (e.g., ls can display files within the directory, but cat cannot read files within the directory).
w Add, delete, or rename files within the directory (e.g., rm , cp , or mv can be used on files within the directory).
x Enter the directory or execute programs within the directory (e.g., cd can enter the directory).

Of course, these directory permissions have no restrictions on "root".

Example:
$ ls -l /home ←List permissions for all home directories within `/home`
drwx------ 28 aaa aaa 4096 4096 2-11-10-11 15:41 aaa
drwx------ 3  bbb bbb 4096 4096 2-11-10-03 19:59 bbb
$ ls /home/bbb ←See what's inside someone else's home directory
ls: cannot open directory /home/bbb: Permission denied ← No permission

In the example above, each user's home directory has "x" permission for the owner, so they can freely enter their own home directory. They also have "rw" permissions, so they can list and add/delete files within their home directory. However, users from other accounts (considered "other") will be blocked at the doorstep (except for the "root" account).

Special Permissions
Permission settings can meet most needs, but there are grey areas. For example, if a file's permission is "rw- --- ---." it should logically be that only the owner can change the file's content. However, if "other" has open access set to "--- --- -wx", meaning the directory's "other" permissions include "x" (permission to enter the directory) and "w" (permission to add/delete files within the directory), it seems that others can also enter the directory and delete or rename files not belonging to the owner.

If file and directory permissions contradict each other, which one should be obeyed? If there are laws, there will be loopholes; if there is software, there will be bugs. Of course, we need to find ways to prevent them, and that's where special permissions come in handy.

Special permissions borrow the "x" (execute) position for setting and displaying. If "t" or "s" appears in the "x" permission position, it means special permissions have been set.

Below is an overview of the uses and syntax of special permissions:
special permission file/directory Effect Caveat ls -l
Permission
Display
Sticky bit Directory In a directory with Sticky bit, only the file owner or "root" can delete or rename the file Others must also have "x" permission. --- --- --t
Set Group ID File For executable files only; temporarily changes to the file's group during execution. Group must also have "x" permission. --- --s ---
Directory Any file placed in the directory will become the group of this directory.
Set User ID File For executable files only; temporarily changes to the file's owner during execution. User must also have "x" permission. --s --- ---

^ back on top ^


chmod : Change File Permissions
The chmod command (change mode) can change file and directory permissions and special permissions. Only the file owner and "root" have the right to modify its permissions.

chmod accepts "Numeric representation" and "Symbolic representation." The proportion of users for these two methods is about equal. Numeric representation is shorter, but non-engineering personnel might find "decimal to binary" daunting, while symbolic representation can be more verbose.


^ back on top ^


Symlink Permissions
If it's a symlink , should its permissions be based on the original file or its symbolic link? If it's a symbolic link , using ls -l to query its permissions will always display "lrwxrwxrwx". However, this does not mean that anyone can read/write/execute (enter the directory); rather, it means "completely depends on the original file's permissions." If you change the permissions of a symbolic link, you are actually changing the permissions of the original file, and the symbolic link will always remain unchanged, displaying "lrwxrwxrwx". If it's a hard link , since a hard link is both the original and a link, changing the permissions of either the original or the link will change both.

umask: Change Default File Permissions
When a file is created by a regular user, most Linux distributions default the file permissions to "rw- rw- r--" (others have no write permission); if the file is created by Superuser, the file permissions will be more restricted, set to "rw- r-- r--" (group and others have no write permission). The umask command can change the default permissions for creating files or directories.

Example: (This is tested as a regular user; results may vary if tested as "root")
$ umask ←If no options, output displays default permissions when creating files or directories
0002

The umask output numbers correspond to the permissions for creating files or directories in the table below.
umask File Permissions Directory Permissions
000
666 (rw- rw- rw-)
777 (rwx rwx rwx)
002
664 (rw- rw- r--)
775 (rwx rwx r-x)
022
644 (rw- r-- r--)
755 (rwx r-x r-x)
027
640 (rw- r-- ---)
750 (rwx r-x ---)
077
600 (rw- --- ---)
700 (rwx --- ---)
277
400 (r-- --- ---)
500 (r-x --- ---)

From the table, umask=0002 means that the permissions for creating a file are "rw- rw- r--", and for a directory, they are "rwx rwx r-x". To change the default file creation permissions, simply enter umask [#][###] ("#" is a digit, refer to the table above, and the first "#" is for special permissions , which is generally not changed, so it remains 0).

Example: (This is tested as a regular user; results may vary if tested as "root")
$ umask ←Check default permissions
0002
$ echo 'umask file1' > umask_0002 ←Create file "umask_0002"
$ umask 0027 ←Change default permissions to "0027" (rw- r-- ---)
$ umask ←Confirm if default permissions have changed
0027 ←Changed to "0027"
$ echo 'umask file2' > umask_0027 ←Create file "umask_0027" with umask=0027
$ ls -l umask_0002 umask_0027 ←List permissions of both files to compare
-rw-rw-r-- 1 aaa  aaa  12 2011-10-10 10:10 umask_0002 ←Note the different permissions for the two files
-rw-r----- 1 aaa  aaa  12 2011-10-10 10:11 umask_0027



^ back on top ^


  1.1 File attributes
File permissions have little restraint on the "root" account, as root has "permission exemption." Therefore, if an accidental operation error occurs, such as issuing the command rm -fr / (deleting the root directory and all subdirectories and files without mercy), Linux would likely perish. So, is there any way to regulate root? That is "file attributes." File attributes can compensate for the danger of root having too much power.

chattr : Change File Attributes
chattr (change attribute) can change 16 types of Linux file attributes, with only about 8-14 types defined (the number and definition of supported attributes may vary among different distributions). Its usage is somewhat similar to chmod , with "+" to add attributes, "-" to remove attributes, and "=" to directly set attributes. The syntax is as follows:
Syntax: chattr [-otpiton][+-=][mode] file/directroy
Command name/Function/Command user Options Function The attributes of mode are [aAcdDisSu], each meaning is
chattr/
change attribute/
Any(mainly for Superuser)
-R Change the attributes of files recursively
"a": Used for files can only be accumulated, can not be deleted. When used in a directory, only the content of the files in the directory can be modified, but the files cannot be added or deleted. And only "root" can use .
"A": Do not update the atime of the file
"c": Automatically compress files when archiving, and automatically decompress when reading
"d": Exclude dump data, that is, this file will be excluded when executing the dump command
"D" If the directory is set, the data in the buffer memory will be saved to the hard disk synchronously
"i": Make the file indestructible; including cannot delete, rename, modify content, change permissions, etc. and only "root" can use it
"s": Destroy corpses and wipe out traces. When a file is deleted, the block of the file will be filled with 0 (so that those who are interested cannot restore the file)
"S": When archiving, do not write to the buffer memory first, but directly write to the hard disk (the performance is poor, but it can prevent file loss when the power is cut off)
"u": Contrary to "s" destroying and erasing traces, when the file is just deleted, only the inode is deleted, so that the file can be saved if you regret it in the future "maybe"
-V The process of displaying transaction attributes

From the usage of chattr's mode, it can be seen that many attributes are designed to regulate "root" (Superuser). For example, attribute "a" is mainly used for log files that accumulate, and even with the "root" account, this file cannot be deleted. Attribute "i" in mode means the file cannot be touched at all. When deleting a file, Linux, for performance reasons, only deletes the file's inode and does not truly clear the data (block). If it's confidential data and you're afraid of it being recovered upon deletion, adding attribute "s" is the way to go.

Experiment: (Logged in as "root", for testing)
# echo '123' > myfile ←Create file "myfile"
# chattr +a myfile ←Set "a" attribute: only append, cannot delete
# rm -f myfile ←Try to delete
rm: cannot remove `myfile': Operation not permitted ←Permission denied
# echo '456' > myfile ←Try to overwrite
bash: myfile: Operation not permitted ←Permission denied
# echo '456' >> myfile ←Try to append
cat myfile ← verify
123
456
# chattr -V -a myfile ←Remove "a" attribute so it can be deleted
chattr 1.40.2 (12-Jul-2007)
Flags of myfile set as ----------------

Experiment: (Logged in as "root", for testing)
# chattr =aAdS file ←Set file to have "a", "A", "d", "S" attributes
# chattr -V +i -ad file ←Add "i" attribute to file and remove "a", "d" attributes

lsattr : Displays File Attributes
Sometimes there may be no problem with permissions , but some files cannot be deleted or modified. At this time, you can use lsattr to check whether the attributes have been changed by chattr . lsattr is the abbreviation of l i s t attr bute, use To check the properties of the file, the usage is as follows:


Sometimes, you might encounter a situation where permissions are fine, but certain files cannot be deleted or modified. In such cases, you can use lsattr to check if attributes have been changed by chattr . lsattr is an abbreviation for list attribute and is used to view file attributes. Its usage is as follows:
Syntax::lsattr [-otpiton] file/directroy
Command Bane/Function/Command User
Options Function
lsattr/
list attrbute/
Any
-a List attributes of all files and directories, including hidden files, current directory, and parent directory.
-d Only list directory attributes.
-R Recursively list attributes of files and subdirectories within a directory.

Example: (Logged in as "root", for testing)
# echo > file
# chattr =aAdS file ←Set the file to have "a", "A", "d", "S" attributes
# lsattr file ←Display file attributes
--S--adA-------- file

Example:
# lsattr -a ←List the attributes of all files in the directory (including the working directory and its parent directory)
-----a---------- ./. ←Attributes of the working directory
---------------- ./.. ←Attributes of parent directory
-----a---------- ./jun ←Attributes of file in directory


^ back on top ^