- POSIX based file permissions пришли еще с UNIX (поэтому актуальны и для MacOS), они определили формат назначания прав read/write/execute для user/group/others; подробнее ниже
- ACL based file permissions позволяют назначать разные права для разных пользователей и групп, в отличии от классического POSIX подхода; подробнее ниже
- Удобный калькулятор разрешений в десятичом виде в зависимости от типа прав (r/w/e) и scope (u/g/o)
- Грамотные админы в повседневной работе не работают из под root, а заходят в эту учетку только если нужно что-то сделать – защита от случайных поломок, безопасность (как минимум пароль нужно ввести для входа под root)
- Изначально ownership придуман чтобы собственник даже в случае некорректной установки прав не потерял доступ
sudo/su
~ ll /usr/bin/su
-rwxr-xr-x 1 root root 32072 Aug 2 20:12 /usr/bin/su
ACL based file permissions
ACL based permissions – file access control lists (FACL) – позволяют назначать разные права для разных пользователей и групп, в отличии от классического POSIX подхода, где
- для назначения двух групп для одного файла требуется создание третьей группы, которая будет включать две целевые группы (nested groups), причем сделать разные права для этих вложенных групп не получится
- назначить же несколько пользователей неполучится никак (только через группы)
Причем FACL живут одновременно с POSIX правами, можно назначать одного пользователя/группу в posix, остальных в ACL. На практике обычно создателя файла назначают в posix как пользователя владельца и его группу как группу владельца, а все остальные в ACL – это позволяет в одном месте управлять всем (так использует Don Pezet).
Чаще всего FACL поддерживаются на уровне дистрибутива, но включены или нет FACL зависит от дистрибутива, при этом инструменты управления одинаковые между дистрибутивами. Управление включением/отключением FACL происходит посредством указания флага при монтировании раздела. Посмотреть отключена (она часто включена по умолчанию, например в ubuntu) ли опция обычно можно в file system table (fstab):
# cat /etc/fstab # /etc/fstab: static file system information. # # Use 'blkid' to print the universally unique identifier for a # device; this may be used with UUID= as a more robust way to name devices # that works even if disks are added and removed. See fstab(5). # # <file system> <mount point> <type> <options> <dump> <pass> # / was on /dev/sdb1 during installation UUID=48711f5b-89da-4c2c-b4f8-49c5d92945cb / ext4 errors=remount-ro 0 1 # swap was on /dev/sdb5 during installation UUID=e7717451-7951-4f3e-94d5-40bd83943003 none swap sw 0 0
# df -h
Filesystem Size Used Avail Use% Mounted on
udev 16G 0 16G 0% /dev
tmpfs 3.2G 342M 2.8G 11% /run
/dev/sda1 915G 17G 852G 2% /
# tune2fs -l /dev/sda1
tune2fs 1.44.5 (15-Dec-2018)
Filesystem volume name: <none>
Last mounted on: /
Filesystem UUID: 48711f5b-89da-4c2c-b4f8-49c5d92945cb
Filesystem magic number: 0xEF53
Filesystem revision #: 1 (dynamic)
Filesystem features: has_journal ext_attr resize_inode dir_index filetype needs_recovery extent 64bit flex_bg sparse_super large_file huge_file dir_nlink extra_isize metadata_csum
Filesystem flags: signed_directory_hash
Default mount options: user_xattr acl
Filesystem state: clean
Errors behavior: Continue
Filesystem OS type: Linux
Inode count: 60989440
Block count: 243940096
Reserved block count: 12197004
Free blocks: 236242783
Free inodes: 60813007
First block: 0
Block size: 4096
Fragment size: 4096
Group descriptor size: 64
Reserved GDT blocks: 1024
Blocks per group: 32768
Fragments per group: 32768
Inodes per group: 8192
Inode blocks per group: 512
Flex block group size: 16
Filesystem created: Wed Mar 17 15:13:45 2021
Last mount time: Wed Dec 27 20:00:13 2023
Last write time: Wed Dec 27 20:00:11 2023
Mount count: 64
Maximum mount count: -1
Last checked: Wed Mar 17 15:13:45 2021
Check interval: 0 (<none>)
Lifetime writes: 416 GB
Reserved blocks uid: 0 (user root)
Reserved blocks gid: 0 (group root)
First inode: 11
Inode size: 256
Required extra isize: 32
Desired extra isize: 32
Journal inode: 8
Default directory hash: half_md4
Directory Hash Seed: 3c32a2d8-b166-4a58-b8b3-49cd6136c939
Journal backup: inode blocks
Checksum type: crc32c
Checksum: 0xd51c8574
Для назначения и просмотра facl используются команды setfcl и getfacl.
Индикатором использования facl в выводе ls -l является знак «+» в конце списка прав – т.е. в дополнение к индикатору прав execution для всех будет символ плюса. И это логично – значит чтобы посмотреть все разрешения нужно использовать getfacl команду.
# ls -l
-rw-rwxr--+ 1 root root 4 Jun 9 16:48 sw
setfacl
setfacl -m – modify (аналог + chmod); даем права на rw пользователю redkin_p для файла somefile (в примере sw)
apt install acl
setfacl -m u:redkin_p:rwx sw setfacl -m u:user:rw sw groupadd marketing setfacl -m g:marketing:rw sw
команда так же прекрасно работает и на директории (в примере test) – с синтаксисом как на файл назначается именно на директорию, не наследуется; но можно сделать наследование (directory default), указав перед типом прав d. Тогда новые файлы (не старые или перемещенные move) в директории будут по умолчанию получать те права, которые мы укажем. Кроме того можно указать маску/mask (по умолчанию rwx), которая позволит задать максимальные права для файлов в директории – даже если права пользователя выше прав в mask, по факту пользователь сможет использовать mask права.
setfacl -m u:redkin_p:rwx test # без наследования setfacl -m d:u:redkin_p:r test # с наследованием
setfacl -s – replace (аналог = chmod)
setfacl -x – remove (аналог – chmod)
getfacl – смотрим разрешения.
# getfacl sw # file: sw # owner: root # group: root user::rw- user:user:rw- user:redkin:rwx group::r-- group:marketing:rw- mask::rw- other::r-- # getfacl test # file: test # owner: root # group: root user::rwx group::r-x other::r-x default:user::rwx default:user:redkin:r-- default:group::r-x default:mask::r-x default:other::r-x
Permissions
FILE PERMISSIONS
- User (u) The owner of file or directory. Usually, the file creator is its owner.
- Group (g) A set of users that need identical access on files and directories that they share. Group information is maintained in the /etc/group file and users are assigned to groups according to shared file access needs.
- Others (o) All other users on the system except for the owner and group members. Also called public
- Read (r) – Let us view file/directory contents. Let us copy file (not directory).
- Write (w) – Allow us to modify the contents – create/remove/rename file/directory and subdirectories.
- Execute (x) – Lets us execute a file. Let us to cd into the directory.
- Add (+) Allocates permissions.
- Revoke (-) Removes permissions.
- Assign (=) Allocates permissions to owner, group members, and public at once.
chatr
To apply attribute-based protection, we’ll use the chattr command to prevent the file from being deleted or modified:
$ lsattr -l permissions.txt
permissions.txt Extents
$ chattr +i permissions.txt
$ lsattr -l permissions.txt
permissions.txt Immutable, Extents
# rm sw
rm: невозможно удалить 'sw': Операция не позволена
~# cat > sw
-bash: sw: Операция не позволена
Modifying Access Permissions
- chmod command accepts the –v option to display what it has changed
chmod u=rwx,g=,o=
umask u=rwx,g=,o=
x - вес 1 w - вес 2 wx - вес 3 r - вес 4
Add the execute permission for the owner ~ chmod u+x test -v mode of ‘test’ changed from 0444 (r--r--r--) to 0544 (r-xr--r--) ~ chmod 544 test -v mode of ‘test’ changed from 0444 (r--r--r--) to 0544 (r-xr--r--) Add the write permission for group members and public and verify ~ chmod go+w test ~ chmod 766 test Remove the write permission for the public ~ chmod o-w test ~ chmod 764 test Assign read, write, and execute permissions to all three user categories ~ chmod a=rwx test ~ chmod 777 test Add read/write/execute permissions to user, read/write for group, read for others: ~ chmod u+rwx,g+rw,o=r test
- don pezet ни разу не менял umask в проде за всю свою карьеру с Linux (с 90х годов)
~ umask u=rwx,g=r,o=w ~ umask 0022 ~ umask 0035 ~ umask 0035
#Set umask
umask 0027
$ umask 027
$ touch file10 $ ll file10 -rw-r-----. 1 user1 user1 0 Dec 1 08:48 file10 $ mkdir dir10 $ ll –d dir10 drwxr-x---. 2 user1 user1 6 Dec 1 08:48 dir10
File Ownership and Group Membership
$ ll file10
-rw-r-----. 1 user1 user1 0 Dec 1 08:48 file10
$ ll –n file10
-rw-r-----. 1 1000 1000 0 Dec 1 08:48 file10
CHOWN/CHGRP
redkin.p@govnoserver:~$ sudo useradd test_user
redkin.p@govnoserver:~$ sudo useradd test_user2
redkin.p@govnoserver:~$ ll sw
-rw-rw-r-- 1 redkin.p redkin.p 0 авг. 8 19:13 sw
redkin.p@govnoserver:~$ sudo chown test_user sw
redkin.p@govnoserver:~$ ll sw
-rw-rw-r-- 1 test_user redkin.p 0 авг. 8 19:13 sw
redkin.p@govnoserver:~$ sudo chgrp test_user sw redkin.p@govnoserver:~$ sudo chown :test_user sw redkin.p@govnoserver:~$ ll sw -rw-rw-r-- 1 test_user test_user 0 авг. 8 19:13 sw
redkin.p@govnoserver:~$ sudo chown test_user2:test_user2 sw redkin.p@govnoserver:~$ ll sw -rw-rw-r-- 1 test_user2 test_user2 0 авг. 8 19:13 sw
chown -R owner_name:group_name folder_name
Special Permissions
You can use either: chmod 4755 /usrbin/su # 4 - setuid, 2 - setgid, 1 - sticky bit chmod u+s /usr/bin/su
Setuid – это бит разрешения, который позволяет пользователю запускать исполняемый файл с правами владельца этого файла. Другими словами, использование этого бита позволяет нам поднять привилегии пользователя в случае, если это необходимо. root@ruvds-hrc [~]# which sudo /usr/bin/sudo root@ruvds-hrc [~]# ls -l /usr/bin/sudo -rwsr-xr-x 1 root root 125308 Feb 20 14:15 /usr/bin/sudo Как мы видим на месте, где обычно установлен классический бит x (на исполнение), у нас выставлен специальный бит s. Это позволяет обычному пользователю системы выполнять команды с повышенными привилегиями без необходимости входа в систему как root, разумеется зная пароль пользователя root. Установка бита setuid не представляет сложности. Для этого используется команда: root@ruvds-hrc [~]# chmod u+s <filename> The setuid flag is set on executable files at the file owner level. With this bit set, the file is executed by other regular users with the same privileges as that of the file owner.A common example is that of su command that is owned by the root user. This command has the setuid bit enabled on it by default. When a normal user executes this command, it will run as if root (the owner) is running it and, therefore, the user is able to run it successfully and gets the desired result. See the highlighted s in the owner’s permission class below: ~ ll /usr/bin/su -rwsr-xr-x 1 root root 32072 Aug 2 20:12 /usr/bin/su When a normal user executes this command, it will run as if root (the owner) is running it and, therefore, the user is able to run it successfully and gets the desired result. Now, remove the setuid bit from su and replace it with the underlying execute attribute. You must be root in order to make this change. List the file after this modification for verification. user gets an “authentication failure” message even though they entered the correct login credentials. ~ sudo chmod u-s /usr/bin/su ~ ll /usr/bin/su -rwxr-xr-x 1 root root 32072 Aug 2 20:12 /usr/bin/su ~ su - Password: su: Authentication failure You can use either: chmod u+s /usr/bin/su chmod 4755 /usrbin/su # 4 - setuid, 2 - setgid, 1 - sticky bit When digit 4 is used with the chmod command in this manner, it enables setuid on the specified file.
The setgid attribute is set on executable files at the group level. With this bit set, the file is executed by non-owners with the exact same privileges that the group members have. For instance, the wall command is owned by root with group membership set to tty and setgid enabled. See the highlighted s in the group’s permission class below: # ll /usr/bin/wall -r-xr-sr-x. 1 root tty 15344 Jan 27 2014 /usr/bin/wall To remove the bit from /usr/bin/wall and replace it with the underlying execute flag. You must be root in order to make this change. List the file after this modification for confirmation. # chmod g-s /usr/bin/wall -r-xr-xr-x. 1 root tty 15344 Jan 27 2014 /usr/bin/wall To add the bit you can use: $ chmod g+s /usr/bin/wall $ chmod 2555 /usr/bin/wall. # 4 - setuid, 2 - setgid, 1 - sticky bit When digit 2 is used with the chmod command in this manner, it sets the setgid attribute on the specified file. The setgid bit can also be set on group-shared directories to allow files and sub-directories created in that directory to automatically inherit the directory’s owning group. This saves group members sharing the directory contents from changing the group on every new file and sub-directory that they add to that directory. The standard behavior for new files and sub-directories is to always receive the creator’s group. *** The wall command allows users to broadcast a message to all logged-in users and print it on their terminal screens. By default, normal users are allowed this privilege because of the presence of the setgid flag on the file. To test, run the command and supply a message as an argument: $ wall Hello, this is to test the setgid flag on the wall command Broadcast message from user1@host1.example.com (pts/0) (Mon Dec 1 11:26:24 2014): Hello, this is to test the setgid flag on the wall command
The sticky bit is set on public writable directories (or other directories with rw permissions for everyone) to protect files and sub-directories owned by regular users from being deleted or moved by other regular users. This attribute is set on /tmp and /var/tmp directories by default as depicted below:
~ ll -d /tmp /var/tmp
drwxrwxrwt 7 root root 4096 Aug 9 03:14 /tmp
drwxrwxrwt 2 root root 6 Aug 7 02:37 /var/tmp
You can use the chmod command to set and unset the sticky bit. When digit 1 is used with the chmod command, it sets the sticky bit on the specified directory
# основной вариант
[redkin.p@snake ~]$ chmod 1777 share/
Alternatively, you can use the symbolic notation to do exactly the same:
# chmod o+t /var
To unset, use either of the following:
# chmod 755 /var
mode of ‘/var’ changed from 1755 (rwxr-xr-t) to 0755 (rwxr-xr-x)
# chmod o-t /var
# альтернативный вариант
[redkin.p@snake ~]$ chmod +t share/
Questions
Which of the following commands enables the setuid (suid) permission on the executable /bin/foo?
A. chmod 1755 /bin/foo
B. chmod 4755 /bin/foo
C. chmod u-s /bin/foo
D. chmod 755+s /bin/foo
Answer: B
ls (general file, device character/block file)
file (file type)
The left-most digit has no significance in the umask value.
False. Default permissions are calculated by subtracting the umask value from the initial permission values.
False, only group
classes - user, group, others
types - read, write, execute
mode - add, revoke, assign
false
first digit, value 4
It would search the /var directory for directories with sticky bit set.
It would remove the setgid bit from file1.
False
11. The setgid bit enables group members to run a command at a higher priority. True or False?
False
12. The chown command may be used to modify both ownership and group membership on a file. True or False?
True
13. What is the equivalent symbolic value for permissions 751?
chmod u=rwx chmod g=rx chmod o=x rwxr-x--x
20. The ll command produces 9 columns in the output by default. True or False?
false, 10
22. What permissions would the owner of the file get if the chmod command is executed with 555?
u=rx (r-x)
23. What would the find / -name core –ok rm {} \; command do?
Nothing, needed –exec, not -ok
Sticky
Which of the following settings for umask ensures that new files have the default permissions -rw-r—– ?
A. 0017
B. 0640
C. 0038
D. 0027
Answer: D
Which of the following commands makes /bin/foo executable by everyone but writable only by its owner?
A. chmod u=rwx,go=rx /bin/foo
B. chmod o+rwx,a+rx /bin/foo
C. chmod 577 /bin/foo
D. chmod 775 /bin/foo
Answer: A The correct command to make /bin/foo executable by everyone but writable only by its owner is chmod u=rwx,go=rx /bin/foo. This command uses the symbolic method to set the permissions for the user (u), group (g), and others (o) classes. The equal sign (=) means that the permissions are set exactly as specified, not added or removed. The letters r, w, and x represent the read, write, and execute permissions respectively. The comma (,) separates the different classes. The command means that the user has read, write, and execute permissions (rwx), while the group and others have only read and execute permissions (rx). The other options are incorrect because they use the wrong syntax or values for the chmod command. Option B uses the wrong indicators for the classes. The letter o means others, not owner. The letter a means all, not group. Option C uses the numeric method, but the value 577 is not correct. The numeric method uses octal numbers (0-7) to represent the permissions for each class. The first digit is for the user, the second for the group, and the third for others. Each digit is the sum of the values for the read (4), write (2), and execute (1) permissions. For example, 7 means rwx, 6 means rw-, 5 means r-x, and so on. The value 577 means that the user has read, write, and execute permissions (rwx), the group has read and execute permissions (r-x), but the others have only write and execute permissions (w-x), which is not what the question asked. Option D uses the numeric method, but the value 775 is not correct. The value 775 means that the user and the group have read, write, and execute permissions (rwx), while the others have only read and execute permissions (r-x). This means that the group can also write to the file, which is not what the question asked.
What do the permissions -rwSr-xr-x mean for a binary file when it is executed as a command?
A. The command is SetUID and it will be executed with the effective rights of the owner.
B. The command will be executed with the effective rights of the group instead of the owner.
C. The execute flag is not set for the owner. Therefore the SetUID flag is ignored.
D. The command will be executed with the effective rights of the owner and group.
Answer: C The permissions -rwSr-xr-x mean that the file is readable and writable by the owner, readable and executable by the group, and readable and executable by others. The S in the owner's permissions indicates that the file has the SetUID bit set, which means that when the file is executed as a command, it will run with the effective user ID of the file owner, rather than the user who executed it. This allows the command to perform privileged operations that the user normally cannot do. For example, the /bin/passwd commandhas the SetUID bit set, so that it can modify the /etc/shadow file, which is only writable by root. The answer is C . if the S is capitalized then it means the execute was not set for that user or group. if it is lowercase then it means the execute was set for it. i.e root@serv:~# ls -ltr /bin/passwd -rwsr-xr-x 1 root root 63736 Jul 27 2018 /bin/passwd root@serv:~# chmod u-x /bin/passwd root@serv:~# ls -ltr /bin/passwd -rwSr-xr-x 1 root root 63736 Jul 27 2018 /bin/passwd
Which of the following commands set the sticky bit for the directory /tmp? (Choose TWO correct answers.)
A. chmod +s /tmp
B. chmod +t /tmp
C. chmod 1775 /tmp
D. chmod 4775 /tmp
E. chmod 2775 /tmp
Answer: BC
Which utility would be used to change how often a filesystem check is performed on an ext2 filesystem without losing any data stored on that filesystem?
A. mod2fs
B. fsck
C. tune2fs
D. mke2fs
E. fixe2fs
Answer: C
The correct utility to change how often a filesystem check is performed on an ext2 filesystem without losing any data stored on that filesystem istune2fs
. Explanation:ltune2fs
is a command-line utility that can be used to modify various parameters and settings of the ext2, ext3, and ext4 filesystems. One of the settings that can be modified usingtune2fs
is the frequency of filesystem checks.
When an ext2 filesystem is created, it is set up with a default frequency for filesystem checks. The default frequency is usually set to every 30 or 40 mounts, or every 180 days, whichever comes first. However, this frequency can be changed using thetune2fs
utility. To change the frequency of filesystem checks usingtune2fs
, you would use the-c
or-i
option followed by the new value. The-c
option is used to specify the maximum number of mounts after which a filesystem check should be performed. The-i
option is used to specify the maximum number of days after which a filesystem check should be performed.
For example, to set the maximum number of mounts to 50 before a filesystem check is performed, you would use the following command:
sudo tune2fs -c 50 /dev/sda1
Similarly, to set the maximum number of days to 365 before a filesystem check is performed, you would use the following command:
sudo tune2fs -i 365 /dev/sda1
Note that you need to specify the device file of the filesystem you want to modify after the options. In the above examples, we assumed the filesystem is located on /dev/sda1
, but this may vary depending on your system’s configuration.
It is important to note that changing the frequency of filesystem checks using tune2fs
does not require the filesystem to be unmounted or formatted, so you can modify this setting without losing any data stored on the filesystem.
Therefore, option C, tune2fs
, is the correct utility to change the frequency of filesystem checks on an ext2 filesystem without losing any data stored on that filesystem.