Linux: permissions/права/sudo & user/group management

  • 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
su – тоже самое что su root. Нужно вводить пароль root, а не свой, даже если у тебя есть права sudo.
~ ll /usr/bin/su
-rwxr-xr-x 1 root root 32072 Aug 2 20:12 /usr/bin/su
sudo -i -u root – нужно вводить свой пароль, а не root.
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
Permissions are set on files and directories to restrict their access to authorized users only. Users are grouped into three distinct categories. Each user category is then assigned required permissions.
The user mask may be defined for individual users so that the new files and directories they create always get preset permissions.
Every file in Linux has an owner and a group associated with it.
FILE PERMISSIONS
Access permissions on files and directories allow administrative control over which users (permission classes) can
access them and to what level (permission types). File and directory permissions discussed in this section are referred
to as standard ugo/rwx permissions.
Permission Classes
Users are categorized into three unique classes for maintaining file security through access rights
  • 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
Permission Types
Permissions control what actions can be performed on a file or directory and by whom. There are three types of permissions
  • 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.
Permission Modes
A permission mode is used to add, revoke, or assign a permission type to a permission class.
  • Add (+) Allocates permissions.
  • Revoke (-) Removes permissions.
  • Assign (=) Allocates permissions to owner, group members, and public at once.
We can view permission settings on files and directories using the ll command. This information is enclosed in the first
column of the command output. The first character indicates the type of file: d for directory, – for regular file, l for
symbolic link, c for character device file, b for block device file, p for named pipe, s for socket, and so on. The next
nine characters—three groups of three characters—show the read (r), write (w), and execute (x) permissions for the
three user classes: user (owner), group, and others (public), respectively. The hyphen character represents a permission
denial for that level.
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
Linux provides the chmod command to modify access rights on files and directories. It works identically for both files
and directories. chmod can be used by root or the file owner, and can modify permissions specified in one of two ways:
symbolic or octal. Symbolic notation uses a combination of letters and symbols to add, revoke, or assign permissions to
each class of users. The octal notation (a.k.a. the absolute notation), on the other hand, uses a three-digit numbering
system ranging from 0 to 7 to express permissions for the three user classes.
The right-most position has weight 1, the middle position carries weight 2, and the left-most position has 4. If we
assign a permission of 6, for example, it would correspond to the two left-most digit positions. Similarly, a permission
of 2 would point to the middle digit position only.
Изменение атрибутов для нескольких групп текстом.
chmod u=rwx,g=,o=
umask u=rwx,g=,o=
Notation
x - вес 1
w - вес 2
wx - вес 3
r - вес 4
Мне кажется symbolic notation намного лучше Octal в случае добавления/удаления прав для отдельной группы и немного лучше в случае редактирования прав для всех групп.
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
Default Permissions
Linux assigns default permissions to a file or directory at the time of its creation. Default permissions are calculated based on the umask (user mask) permission value subtracted from a preset value called initial permissions.
  • don pezet ни разу не менял umask в проде за всю свою карьеру с Linux (с 90х годов)
The umask is a three-digit value that refers to read/write/execute permissions for owner, group, and public. Its purpose
is to set default permissions on new files and directories created without touching the existing files and directories. In RHEL, the default umask value is set to 0022 for the root and other system users and 0002 for all regular users (бывает и 0022) with bash shell assigned. Note that the left-most 0 has no significance. Run the umask command without any options and it will display the current umask value:
Change the umask value.
~ umask u=rwx,g=r,o=w
~ umask
0022
~ umask 0035
~ umask
0035
Изменить umask для пользователей на пользователей на постоянной основе проще всего в bashrc / profile / etc, но можно и через login.defs.
#Set umask
umask 0027
The pre-defined initial permission values are 666 (rw-rw-rw-) for files and 777 (rwxrwxrwx) for directories. Even if the umask is set to 000, the new files will always get a maximum of 666 permissions, and we use the chmod command to add executable bits explicitly if desired.
Consider the following example to calculate the default permission values on files for regular users:
666 (init) – 002 (mask) = 664 (permissions)
This indicates that every new file will have read and write permissions assigned to the owner and the owning group,
and a read-only permission to others.
To calculate default permission values on directories for regular users:
777 (init) – 002 (mask) = 775 (permissions)
Now, if you wish to have different default permissions set for new files and directories, you need to modify the umask.
You first need to determine the desired default values. For instance, if you want all your new files and directories to get 640 and 750 permissions, respectively, you can set the value to 027 as follows:
$ umask 027
The new value becomes effective right away, and it will only be applied to files and directories created thereafter. The
existing files and directories will remain intact. Now create file10 and dir10 as user1 under /home/user1 to test the
effect of the new umask.
$ 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
The above examples show that the new file and directory were created with different permissions. The file got (666 –
027 = 640) and the directory (777 – 027 = 750) permissions. The umask value set at the command line will be lost as soon as you log off. In order to retain the new setting, place it in an appropriate shell startup files.
File Ownership and Group Membership
In Linux, every file and directory has an owner. By default, the creator assumes ownership but this may be altered and
allocated to a different user if required.
Similarly, every user is a member of one or more groups. A group is a collection of users with common requirements. By default, the owner’s group is assigned to a file or directory.
The following ll command output shows the owner and the owning group for file file10:
$ ll file10
-rw-r-----. 1 user1 user1 0 Dec 1 08:48 file10
The output indicates that the owner of file10 is user1 who belongs to group user1. If you wish to view the corresponding UID and GID instead, you can specify the –n option with ll:
$ ll –n file10
-rw-r-----. 1 1000 1000 0 Dec 1 08:48 file10
CHOWN/CHGRP
Linux provides the chown and chgrp commands that you can use to alter ownership and owning group for files and
directories. you must be root to make these modifications (даже текущий собственник не может менять – защита что создашь скрипт от имени пользователя и убедишь этого пользователя этот скрипт запустить).
Create user accounts user100 and user200:
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
modify the ownership on file10
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
Change the owning group
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
Assign both ownership and owning group
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
Change both ownership and group membership recursively on directory
chown -R owner_name:group_name folder_name
Special Permissions
Linux offers three types of special permission bits that may be set on executable files or directories to allow them to respond differently for certain operations.
The first two bits may be defined on executable files to provide non-owners and non-group members the ability to run executables with the privileges of the owner or the owning group, respectively. The setgid bit may also be set on shared directories for group collaboration. The last bit may be set on public directories for inhibiting file deletion by nonowners. The use of the special bits should be regulated and monitored appropriately to avoid potential security issues to the system and applications.
You can use either: 
chmod 4755 /usrbin/su  # 4 - setuid, 2 - setgid, 1 - sticky bit 
chmod u+s /usr/bin/su
setuid (set user identifier) bit – исполнения от имени владельца файла.
Классический пример использования этого бита в операционной системе это команда sudo. Очевидно, что не следует навешивать этот бит на любое приложение т.к. это может привести к тому, что ты будешь исполнять неизвестное/потенциально опасное приложение от имени того пользователя, которому оно принадлежит (напр. root). При наличии в выводе ls флаг x заменяется на s для пользователя и/или группы несмотря на наличие или отсутствие прав на execution.
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.
setgid (set group identifier) bit – аналогично вышестоящему, только исполнение от имени группы владельца файла.
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
sticky bit – используется редко, но это полезный бит, который
в настоящее время используется в основном для каталогов, чтобы защитить в них файлы. Из такого каталога пользователь может удалить только те файлы, владельцем которых он является. Примером может служить каталог /tmp, в который запись открыта для всех пользователей, но нежелательно удаление чужих файлов. Только владелец файла может удалять файлы в папке с sticky bit, но все могут создавать файлы в этой папке. Установка атрибута производится утилитой chmod.
В выводе ls отображается как буква t в разделе для other.
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/ 

Короткий список команд для создания пользователя

Создание пользователя. В файле /etc/passwd  хранятся все пользователи (бекап в /etc/passwd-).
sudo useradd -m -s /bin/bash weril
sudo passwd weril
sudo login weril - тестово логинемся
sudo passwd -e weril - (expire) делаем пароль протухшим (после авторизации пользователя заставят поменять пароль)
# sudo passwd -l weril - (lock) блокируем пользователя
sudo vi /etc/ssh/sshd_config - добавляем в AllowUsers в sshd (AllowUsers <username>@*)
sudo /etc/init.d/sshd restart - рестартуем службу (sudo service sshd restart)

При смене пароля может запрашивать старый пароль, мы его можем не знать (напр. потерял пользователь/учетная запись создана облаком), в таком случае меняем из под root.

sudo su
passwd weril

В Centos чтобы не добавлять каждого пользователя отдельно есть группа wheel, в Ubuntu группа sudo. Если добавить в эту группу – будут так же права sudo.

sudo usermod -a -G wheel [user name]
sudo usermod -a -G sudo [user name]

Типы пользователей

RHEL supports three fundamental user account types: root, normal, and service.

  • The root user, the superuser or the administrator with full access to all services and administrative functions, possesses full powers on the system. This user is automatically created during RHEL installation.
  • The normal users have user-level privileges. They cannot perform any administrative functions, but can run applications and programs that they are authorized to execute.
  • The service accounts are responsible for taking care of the installed services. These accounts include apache, ftp, mail, ntp, postfix, and qemu.

Ключевые файлы по управлению пользователями и группами

https://learning.lpi.org/en/learning-materials/010-160/5/5.2/5.2_01/

User account information for local users is stored in four files in the /etc directory. These files are passwd, shadow, group, and gshadow, and they are updated when a user account is created, modified, or deleted. The same files are referenced to check and validate the credentials for a user at the time of their login attempt into the system, and hence these files are referred to as user authentication files. These files are so critical to the operation of the system that, by default, the system maintains a backup of each of these files as passwd-, shadow-, group-, and gshadow- in the /etc directory. The shadow and gshadow files, as well as the user administration commands are part of the shadow-utils package that is installed on the system at the time of OS installation.

/etc/passwd

a file of seven colon-delimited fields containing basic information about users

frank:x:1001:1001::/home/frank:/bin/bash

Each line consists of seven colon-delimited fields:

Username
The name used when the user logs into the system.
Password
The encrypted password (or an x if shadow passwords are used).
User ID (UID)
The ID number assigned to the user in the system.
Group ID (GID)
The primary group number of the user in the system.
GECOS
An optional comment field, which is used to add extra information about the user (such as the full name). The field can contain multiple comma-separated entries.
Home directory
The absolute path of the user’s home directory.
Shell
The absolute path of the program that is automatically launched when the user logs into the system (usually an interactive shell such as /bin/bash).

/etc/group

a file of four colon-delimited fields containing basic information about groups

developer:x:1002:

Each line consists of four colon-delimited fields:

Group Name
The name of the group.
Group Password
The encrypted password of the group (or an x if shadow passwords are used).
Group ID (GID)
The ID number assigned to the group in the system.
Member list
A comma-delimited list of users belonging to the group, except those for whom this is the primary group.

/etc/shadow

a file of nine colon-delimited fields containing encrypted user passwords, file readable only by root and users with root privileges and contains the encrypted passwords of the users, each on a separate line:

frank:$6$i9gjM4Md4MuelZCd$7jJa8Cd2bbADFH4dwtfvTvJLOYCCCBf/.jYbK1IMYx7Wh4fErXcc2xQVU2N1gb97yIYaiqH.jjJammzof2Jfr/:18029:0:99999:7:::

Each line consists of nine colon-delimited fields:

Username
The name used when user logs into the system.
Encrypted password
The encrypted password of the user (if the value is !, the account is locked).
Date of last password change
The date of the last password change, as number of days since 01/01/1970. A value of 0 means that the user must change the password at the next access.
Minimum password age
The minimum number of days, after a password change, which must pass before the user will be allowed to change the password again.
Maximum password age
The maximum number of days that must pass before a password change is required.
Password warning period
The number of days, before the password expires, during which the user is warned that the password must be changed.
Password inactivity period
The number of days after a password expires during which the user should update the password. After this period, if the user does not change the password, the account will be disabled.
Account expiration date
The date, as number of days since 01/01/1970, in which the user account will be disabled. An empty field means that the user account will never expire.
A reserved field
A field that is reserved for future use.

/etc/gshadow

a file of four colon-delimited fields file containing encrypted group passwords, file readable only by root and by users with root privileges that contains encrypted passwords for groups, each on a separate line:

developer:$6$7QUIhUX1WdO6$H7kOYgsboLkDseFHpk04lwAtweSUQHipoxIgo83QNDxYtYwgmZTCU0qSCuCkErmyR263rvHiLctZVDR7Ya9Ai1::

Each line consists of four colon-delimited fields:

Group name
The name of the group.
Encrypted password
The encrypted password for the group (it is used when a user, who is not a member of the group, wants to join the group using the newgrp command — if the password starts with !, no one is allowed to access the group with newgrp).
Group administrators
A comma-delimited list of the administrators of the group (they can change the password of the group and can add or remove group members with the gpasswd command).
Group members
A comma-delimited list of the members of the group.

 

vipw/vigr

  • vipw – редактируем безопасно файл passwd & shadow
  • vigr – редактируем безопасно файл group & gshadow

The vipw and vigr commands edits the files /etc/passwd and /etc/group, respectively. With the -s flag, they will edit the shadow versions of those files, /etc/shadow and /etc/gshadow, respectively. The programs will set the appropriate locks to prevent file corruption. When looking for an editor, the programs will first try the environment variable $VISUAL, then the environment variable $EDITOR, and finally the default editor, vi(1).

Occasionally, it is imperative for the administrator to modify the passwd file manually using an editor such as vi. If another user attempts to change their password while the file is being edited, it results in a successful password update for the user. Unfortunately, this change is lost when the file is later saved by the administrator. To prevent this from happening, and to prevent any corruption resulting from such a condition, the shadow-utils package offers two tools called vipw and vigr that allow a privileged user to edit the passwd and group files while disabling write access to them. The same commands are also used to edit the shadow versions of these files when they are executed with the –s option. Both commands make a copy of the respective file in the /etc directory with the .edit extension and also a corresponding lock file with the .lock extension in the same directory. The .edit file stores the changes being made while the .lock file saves the PID of the process. During this time, if a user attempts to change their password, the passwd command accepts the new password and checks for the existence of a .lock file before attempting to update the original file. The presence of a .lock file is an indication for the passwd command that an edit session is in progress and that it has to wait for it to complete. As soon as the administrator finishes with the editing and quits the file, some automatic checks are performed on the file for data and syntax validity. The original file is backed up with the hyphen sign as a suffix to its name and the edited version replaces the original file. The .edit and .lock files are then removed. At this point, the passwd command that was waiting for the editing session to finish goes ahead and updates the user password successfully.
The same rule is applied to other commands that attempt to write to these files while they are being amended. Also, while an instance of either of these tools is running on any of the four files, invoking another session of either of these tools generates an error message similar to the following:
# vigr –s
vigr: Couldn't lock file: Interrupted system call
vigr: /etc/gshadow is unchanged
At the end of an editing session for any of the four files, a message is displayed, reminding us of modifying the corresponding file also. For example, the following reminder is shown after the completion of passwd file modification with the vipw command:
You have modified /etc/passwd.
You may need to modify /etc/shadow for consistency.
Please use the command 'vipw -s' to do so.
And after the execution of the vigr command on the gshadow file:
You have modified /etc/gshadow.
You may need to modify /etc/group for consistency.
Please use the command 'vigr' to do so.

pwck / grpck

pwck / grpck – verify integrity of password/group files

 The pwck command verifies the integrity of the users and authentication information. It checks that all entries in /etc/passwd and /etc/shadow have the proper format and contain valid
data. The user is prompted to delete entries that are improperly formatted or which have other uncorrectable errors.
Over the period of time or, especially, after making a manual modification, inconsistencies may occur in any of the four authentication files and require administrative attention. The passwd and shadow files are particularly important, as they are the primary sources for validating local user existence and authenticating them. The shadow-utils package offers a tool called pwck that we can use to check the integrity and validity of data in these files. This command checks each line entry for the correct number of fields, uniqueness and validity of the login name, and validity of the UID, GID, primary group, login directory, and the shell file. For the shadow file, it checks for the existence of corresponding entries, the correct number of fields, duplicate entries, the presence of passwords, and some password aging attributes based on the directives defined in the /etc/login.defs file. This command reports any inconsistencies as it finds.
~$ sudo pwck
[sudo] password for admin:
user 'ftp': directory '/var/ftp' does not exist
user 'avahi-autoipd': directory '/var/lib/avahi-autoipd' does not exist
pwck: no changes

~$ sudo pwck
[sudo] password for redkin_p:
user 'lp': directory '/var/spool/lpd' does not exist
user 'news': directory '/var/spool/news' does not exist
user 'uucp': directory '/var/spool/uucp' does not exist
pwck: no changes
The shadow-utils package offers a cousin of pwck called grpck that is used to verify the information in the group and gshadow files for validity and consistency. This command performs checks on the validity of the number of fields in each line entry and whether a user belonging to a group is absent from the passwd or the shadow file. It reports inconsistencies as well.
~$ sudo grpck

 

pwconv  / grpconv or pwunconv / grpunconv : Activating and Deactivating Shadow Password Mechanism

The shadow password mechanism that enables the use of shadow and gshadow files for storing user and group passwords and password aging information may be deactivated if desired. However, this is an undesirable and unrecommended action unless there is a specific need to do so. The shadow-utils package offers four tools, two (pwconv and grpconv) to activate the mechanism and the other two (pwunconv and grpunconv) to deactivate it.
  • pwconv – Creates and updates the shadow file and moves user passwords over from the passwd file. Activates password shadowing if it is not already active. The activation tools reference the /etc/login.defs file for some password aging attributes while being executed. This command works quietly and does not display any output unless there is a problem. It creates the shadow file with read-only permission for the root user.
  • pwunconv – Moves user passwords back to the passwd file and removes the shadow file. Deactivates password shadowing.
  • grpconv – Creates and updates the gshadow file and moves group passwords over from the group file. Activates password shadowing at the group level if it is not already active. This command works quietly and does not display any output unless there is a problem. It creates the gshadow file with read-only permission for the root user.
  • grpunconv – Moves group passwords back to the group file and removes the gshadow file. Deactivates password shadowing.

 

The Skeleton Directory

When you add a new user account, even creating its home directory, the newly created home directory is populated with files and folders that are copied from the skeleton directory (by default /etc/skel). The idea behind this is simple: a system administrator wants to add new users having the same files and directories in their home. Therefore, if you want to customize the files and folders that are created automatically in the home directory of the new user accounts, you must add these new files and folders to the skeleton directory.

 

ID

id – просмотр информации по себе uid (user id), gid (primary group id – она назначается для новых файлов), список групп с их ID.

root@serv:~# id
uid=0(root) gid=0(root) groups=0(root)

user@serv:~$ id
uid=1000(user) gid=1000(user) groups=1000(user),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev)

Useradd

https://linux.die.net/man/8/useradd

When invoked with only the -D option, useradd will display the current default values. When invoked with -D plus other options, useradd will update the default values for the specified options.

~# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no
Базовое создание пользователя
[root@localhost ~]# useradd user2 - Create a User Account with Default Values defined in the useradd and login.defs files

[root@localhost ~]# useradd -u 1010 -g 1001 -m -d /home/user3 -k /etc/skel -s /bin/bash user3 - Create user3 with UID 1010 (–u), home directory /home/user3 (–m and –d) shell /bin/bash (–s) membership in group 1001 (–g), and default startup files copied into this user’s home directory (–k)

[root@localhost ~]# useradd -s /sbin/nologin user4 - Create user4 with shell file /sbin/nologin. This shell is primarily used for application accounts that do not require login access to the system. It can also be assigned to a regular user to disable access temporarily using the usermod command.

[root@localhost ~]# ls /home/
user1 user2 user3 user4
Проверка инфы в файлах: проверяем что все файлы правильно заполнены.
### grep for user2 on the passwd, shadow, group, and gshadow files to check what the useradd command has added:

[root@localhost ~]# cd /etc; grep user2 passwd shadow group gshadow
passwd:user2:x:1001:1001::/home/user2:/bin/bash
shadow:user2:$6$k8Zc4syc$vGkOpb5g/kcNEE8SwYy9kcw5pc6I.eWP90bWwS7WXpk.gXzmiawBueQIvJOaiEtCaEIRDe3Nacr5hFKRDztM5/:17098:0:99999:7:::
group:user2:x:1001:
gshadow:user2:!::

[root@localhost etc]# cd /etc ; grep user3 passwd shadow group gshadow
passwd:user3:x:1010:1001::/home/user3:/bin/bash
shadow:user3:$6$4Y9/Kbaz$J3E6ndqZ7dOXGF5t/gTwDXL7vaDJjiadR9jg4JnfX5BLnClm0lfnRba6qkE6RSRcy6xpe9qNRZXuBXnXX58VM1:17098:0:99999:7:::

[root@localhost etc]# cd /etc ; grep user4 passwd shadow group gshadow
passwd:user4:x:1011:1011::/home/user4:/sbin/nologin
shadow:user4:$6$yjNYeAkL$GPmyvzx0ipg6ZKndwJyGA8VhUrKvjKpsOYSwX.KpvfBEjBY6H085l0WJtYa04DX.bFgDUuTEMsI2r2APgwk1v.:17098:0:99999:7:::
group:user4:x:1011:
gshadow:user4:!::
Проверяем работу
[user1@localhost ~]$ su - user2
Password:
Last login: Mon Oct 24 17:20:51 MSK 2016 on pts/0

[root@localhost ~]# su - user4
Last login: Mon Oct 24 17:51:42 MSK 2016 on pts/0
This account is currently not available. -- The message “This account is currently not available” is displayed when a user with a nologin shell attempts to log in.

[root@localhost ~]# su - user5
su: user user5 does not exist
useradd – Adds a user. The useradd command adds entries to the passwd, group, shadow, and gshadow files for each user added to the system. This command creates a home directory for the user and copies the default user startup files from the skeleton directory /etc/skel into the user’s home directory. It can also be used to update the default settings that are used at the time of new user creation for unspecified settings. The useradd command has several options available with it.
login – Specifies a login name to be assigned to the new user account.
–b/–base-dir – Defines the absolute path to the base directory for placing user home directories.
–c/–comment – Describes useful information about the user .
d/–home-dir – Defines the absolute path to the user home directory.
–D/–defaults – Displays or modifies the default settings. The useradd command picks up the default values from the /etc/default/useradd and /etc/login.defs files for any options that are not specified at the command line. Moreover, the login.defs file is also consulted by the usermod, userdel, chage, and passwd commands as needed. We can view the useradd file contents with a command such as cat or more, or display the settings with the useradd -D command.
[root@localhost ~]# useradd -GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
We can modify these defaults and set them to our desired values. For instance, the following changes the default base directory to /usr/home as the new location for placing home directories for new users:
[root@localhost ~]# useradd -D -b /usr/home

[root@localhost ~]# useradd -D
GROUP=100
HOME=/usr/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
The other file /etc/login.defs comprises of additional directives that set several defaults. User and group management commands consult this file to obtain information that is not specified at the command line.
[root@localhost ~]# grep -v ^# /etc/login.defs | grep -v ^$
MAIL_DIR /var/spool/mail
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
UID_MIN 1000
UID_MAX 60000
SYS_UID_MIN 201
SYS_UID_MAX 999
GID_MIN 1000
GID_MAX 60000
SYS_GID_MIN 201
SYS_GID_MAX 999
CREATE_HOME yes
UMASK 077
USERGROUPS_ENAB yes
ENCRYPT_METHOD SHA512
These directives define the mail directory location for the user (MAIL_DIR), password aging attributes (PASS_MAX_DAYS, PASS_MIN_DAYS, PASS_MIN_LEN, and PASS_WARN_AGE), range of UIDs and GIDs to be allocated to new user and group accounts (UID_MIN, UID_MAX, GID_MIN and GID_MAX), range of UIDs and GIDs to be allocated to new system user and group accounts (SYS_UID_MIN, SYS_UID_MAX, SYS_GID_MIN and SYS_GID_MAX), and instructions for the useradd command to create a home directory (CREATE_HOME), set the default umask to 077 (UMASK), delete the user’s group if it contains no more members (USERGROUPS_ENAB), and use the SHA512 algorithm for encrypting user passwords (ENCRYPT_METHOD).
–e/–expiredate – Specifies a date after which a user account is automatically disabled. The format for date specification is YYYYMM-DD.
–f/–inactive – Denotes maximum days of inactivity before a user account is declared invalid.
–g/–gid – Specifies the primary group identifier . The base GID is 1000. If this option is not used, a group account matching the user name is created with the GID matching the UID. If you wish to assign a different GID, specify it with this option. Make sure that the group already exists. –G (–groups) Specifies the membership for up to 20 comma-separated supplementary groups. If this option is not specified, no supplementary groups are added.
–k/–skel – Specifies the location of the skeleton directory (default is /etc/skel), which contains default user startup files. These files are copied to the user’s home directory at the time of account creation. Three bash shell files – .bash_profile, .bashrc, and .bash_logout – are available in this directory by default.
You may customize these files or add more files to this directory to ensure new users get them. Existing user home directories are not affected by this change.
–K/–key Overrides some of the default values specified in the /etc/login.defs file.
–M/–no-create-home – Prevents the command from creating a home directory for the user .
–m/–create-home – Creates a home directory if it does not already exist.
–N/–no-user-group – Prevents the command from creating a private group for the user .
–o/–non-unique – Creates a user account sharing the UID of an existing user . When two users share a common UID, both get identical rights on each other’s files. This should only be done in specific situations.
–r/–system – Creates a system account with a UID below 1000 and a never-expiring password.
–s/–shell – Defines the absolute path to the shell file.
–u/–user-group – Indicates a unique user identifier . The base UID is 1000. If this option is not specified, the next available UID from the /etc/passwd file is used.

Usermod

  • usermod -u 2000 -m -d /home/user2new -s /sbin/nologin -l user2new user2 – Modify the login name for user2 to user2new (–l), UID to 2000 (–u), home directory to /home/user2new (–m and –d) and login shell to /sbin/nologin (–s)
[root@localhost ~]# cd /etc; grep user2 passwd
user2new:x:2000:1001::/home/user2new:/sbin/nologin
usermod – Modifies user attributes.  The syntax of this command is very similar to that of the useradd’s, with most options identical. Options that are specific to usermod only:
–L/–lock – Locks a user account by placing an exclamation mark at the beginning of the password field and before the encrypted password.
–U/–unlock – Unlocks a user’s account by removing the exclamation sign from the beginning of the password field.
-a/–append – Adds a user to the supplementary group(s).
–l/–login – Specifies a new login name.
–m/–move-home – Creates a new home directory and moves the contents from the old location to here.

Userdel

Пример Userdel (удаляем пользователя вместе с home директорией)
sudo userdel -r akandratov
userdel – Deletes a user. The userdel command is straightforward. It removes entries for the specified user from all the authentication files.
–r – deletes the user’s home directory if the option is specified.
–f – flag may be used to force the removal even if the user is still logged in.

passwd

passwd

Выставляем пароль
[root@localhost ~]# passwd user2
Changing password for user user2.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
Пример блокировки аккаунта passwd/usermod.
Lock user4 using either of the following

[root@localhost ~]# usermod -L user2new

[root@localhost ~]# passwd -l user2new
Locking password for user user2new.
passwd: Success

[root@localhost ~]# cat /etc/passwd | grep user2new
user2new:x:2000:1001::/home/user2new:/sbin/nologin
passwd – The common use of the passwd command is to set or modify a user’s password; however, we can also use this command to lock and unlock a user account and modify their password aging attributes.
–d (–delete) Deletes a user password without expiring the user account.
–e (–expire) Forces a user to change their password upon next logon.
–l (–lock) Locks a user account.
–u (–unlock) Unlocks a user account.
–k (–keep) Re-activates an expired user account without changing the password.
–i (–inactive) Defines the number of days of inactivity after the password expiry and before the account is locked. It corresponds to the seventh field in the shadow file.
–n (–minimum) Specifies the number of days that must elapse before the password can be changed. It corresponds to the fourth field in the shadow file.
–w (–warning) Defines the number of days a user gets warning messages to change password. It corresponds to the sixth field in the shadow file.
–x (maximum) Denotes the maximum days of validity of the password before a user starts getting warning messages to change password. It corresponds to the fifth field in the shadow file.

chage / passwd / usermod for managing password aging

change

    • chage -E 2024-12-31 user10  – deactivate user user10 at 2024-12-31
    • chage -d 0 user60 – force to change the password at next login (аналог sudo passwd -e weril)
    • chage -m 10 -M 30 -W 7 -E 2016-12-31 user3 – Configure password aging for user3 with mindays (–m) set to 10 (cannot change their password within 10 days after setting it), maxdays (–M) to 30 (password validity of 30 days), warndays (–W) to 7 (user should get  warning messages for changing password for 7 days before their account is locked), and account expiry set to December 31, 2016
    • passwd -n 7 -x 15 -w 3 user5 – configures password aging for user5 with mindays (–n) set to 7, maxdays (–x) to 16, and warndays (–w) to 3 using the passwd
    • passwd -n 7 -x 28 -w 5 user2 – Configure password aging for user2 with mindays (–n) set to 7, maxdays (–x) to 28, and warndays (–w) to 5 using the passwd
    • usermod -e 2016-12-31 user2new
      [root@localhost ~]# chage -l user2new | grep Account
      Account expires : Dec 31, 2016
  • show

chage -l user10  – lists password aging attributes for user

# chage -l user10
Last password change : May 24, 2021
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
[root@localhost ~]# chage -l user1
Last password change : never
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7


[root@localhost ~]# chage -l user2
Last password change : Oct 24, 2016
Password expires : Nov 21, 2016
Password inactive : never
Account expires : never
Minimum number of days between password change : 7
Maximum number of days between password change : 28
Number of days of warning before password expires : 5


[root@localhost ~]# chage -l user3
Last password change : Oct 24, 2016
Password expires : Nov 23, 2016
Password inactive : never
Account expires : Dec 31, 2016
Minimum number of days between password change : 10
Maximum number of days between password change : 30
Number of days of warning before password expires : 7
    • The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change
      his/her password.
chage – Sets or modifies password aging attributes for a user.
–l – Lists password aging attributes set on a user account.
–d/–lastday – Specifies a date in the YYYY-MM-DD format, or number of days since the epoch time when the password was last modified. With –d 0, the user is forced to change the password at next login. It corresponds to the third field in the shadow file.
–E (–expiredate) Sets a date in the YYYY-MM-DD format, or number of days since the epoch time on which the user account is deactivated. With -1, this feature can be disabled. It corresponds to the eighth field in the shadow file.
–I (–inactive) Defines the number of days of inactivity after the password expiry and before the account is locked. With -1, this feature can be disabled. It corresponds to the seventh field in the shadow file.
–m (–mindays) (cannot change their password within x days after setting it) Indicates the minimum number of days that must elapse before the password can be changed. A value of 0 in this field allows the user to change their password at any time. It corresponds to the fourth field in the shadow file.
–M (–maxdays) (password validity of x days) Denotes the maximum days of validity of the password before the user starts getting warning messages to change the password. With -1, this feature can be disabled. It corresponds to the fifth field in the shadow file.
–W (–warndays) (user should get  warning messages for changing password for x days before their account is locked) Designates the number of days the user gets warning messages to change password before the password expiry. It corresponds to the sixth field in the shadow file.

SU

The su command available in RHEL provides us with the ability to switch into other user accounts.

Even though we can log in to the system directly as root, it is not a recommended practice. The recommended practice is to log in with our own normal user account and then switch into the root account if necessary. This is safer and ensures system security and protection. In addition to becoming root, we can switch into another user account as well. In either case, we need to know the password for the target user account in order for a successful switch with exception – the root user can switch into any other user account on the system without being prompted for that user’s password..
To switch from user1 to root without executing startup scripts for the target user:
[user1@localhost ~]$ su
Password:
[root@localhost user1]#
To repeat the above while ensuring that startup scripts for the target user are also executed to provide an environment similar to a real login.
[user1@localhost ~]$ su -
Password:
Last login: Mon Oct 24 18:27:52 MSK 2016 on pts/0
[root@localhost ~]#
To switch into a different user account specify the name of the target user with the command:
[user1@localhost ~]$ su - user2new

To issue a command as a different user without switching into that user, the –c option is available with su. For example, the firewall-cmd command with the –list-services option requires superuser privileges. user1 can use su as follows and execute this privileged command to obtain desired results

[user1@localhost ~]$ su -c 'firewall-cmd --list-services'
Password:
dhcpv6-client ftp ssh
sudo/sudoers
    • The sudoers file contains several examples with a brief explanation. It is a good idea to look at those examples for a better understanding.

Добавление конкретного пользователя в sudo (sudoers).

sudo vi /etc/sudoers

## Allow root to run any commands anywhere
root ALL=(ALL) ALL
weril ALL=(ALL) ALL
RHEL offers a way for normal users to be able to run an assigned set of privileged commands without the knowledge of the root password. This allows the flexibility of assigning a specific command or a set of commands to an individual user or a group of users based on their needs. These users can then precede one of those commands with a utility called sudo (superuser do) at the time of executing that command. The users are prompted to enter their own password, and if correct, the command is executed successfully. The sudo utility is designed to provide protected access to administrative functions as defined in the /etc/sudoers file. It can also be used to allow a user or a group of users to run scripts and applications owned by a different user.
Any normal user who requires access to one or more administrative commands is defined in the sudoers file. This file can be edited with the visudo command, which creates a copy of the file as sudoers.tmp and applies the changes there. After the visudo session is over, the updated file overwrites the original sudoers file, and sudoers.tmp is deleted. This is done to prevent multiple users editing the file simultaneously.
The syntax for user and group entries in the file is similar to the following example entries for user user1 and members of the wheel group (group is prefixed by the % sign). These entries provide ALL privileges to ALL administrative commands. Now, when user1 or any dba group member executes a privileged command, they will be required to enter their own password.
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
user1 ALL=(ALL) ALL
If we want user1 and wheel group members not to be prompted for a password, we can modify their entries in the sudoers file to look like:
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) NOPASSWD: ALL
user1 ALL=(ALL) NOPASSWD: ALL

[user1@localhost ~]$ sudo cat [user1@localhost ~]$
To restrict user1 and wheel group members to run only the date and cat commands, modify the directives as follows:
## Allows people in group wheel to run all commands
%wheel ALL=/usr/bin/date,/usr/bin/cat
user1 ALL=/usr/bin/date,/usr/bin/cat

[user1@localhost ~]$ sudo cat 1
[sudo] password for user1:[user1@localhost ~]$ sudo tail 1
Sorry, user user1 is not allowed to execute '/bin/tail 1' as root on localhost.localdomain.
Configuring sudo to work the way it has just been explained may result in a cluttered sudoers file containing too many entries. To avoid this and for better management of this file, sudo allows us to use aliases to define groups of users, commands, and hosts using the User_Alias, Cmnd_Alias, and Host_Alias directives available in the file. For instance, we can define a Cmnd_Alias called PKGCMD containing yum and rpm package management commands, and a User_Alias called PKGADM containing users user1 to user5. These users may or may not belong to the same Linux group. We then give PKGADM access to PKGCMD. This way we set one rule that allows a group of users access to a group of commands. We can add or remove commands and users anytime as needed. Here is what needs to be added to the sudoers file to achieve this:
Cmnd_Alias PKGCMD = /usr/bin/yum, /usr/bin/rpm
User_Alias PKGADM = user1, user2, user3, user4, user5
%PKGADM ALL = PKGCMD
The sudo command logs successful authentication and command data to the /var/log/secure file. It uses the name of the actual user executing the command (and not root).

groups

Просмотр групп без ID (с ID смотрим по ID).

$ groups
user cdrom floppy audio dip video plugdev netdev

Add group shared with GID 9999. В файле /etc/group хранятся все группы (бекап в /etc/group-). groupmod используется для модификации существующей группы.

$ sudo groupadd -g 9999 shared
$ tail -1 /etc/group
shared:x:9999:
Add existing users as members to group
$ sudo usermod -G shared test_user1
$ sudo usermod -G shared test_user2
$ tail -1 /etc/group
shared:x:9999:test_user1,test_user2 # shared - имя группы, 
х - пароль зашифрован (чаще всего отсутствует и хранится в отдельном файле gshadow), 
9999 - id группы, 
test_user1/2 - члены группы

Managing group accounts involves creating and modifying groups, adding and deleting group members and administrators, setting and revoking group-level password, and deleting groups. RHEL provides a set of tools and the graphical User Manager for performing these operations. The command toolset is part of the shadow-utils package and the User Manager GUI application becomes available when the system-config-users package is installed on the system.

groupadd – Adds a group. The groupadd command picks up the default values from the login.defs file. Command adds entries to the group and gshadow files for each group added to the system.

–g/–gid – Specifies the GID to be assigned to the group.

–o/–non-unique – Creates a group account sharing the GID of an existing group. When two groups share a common GID, members of each group get identical rights on each other’s files. This should only be done in specific situations.

–r – Creates a system group account with a GID below 1000.

groupname Specifies a group name.

Create group account admins with GID 6666:

[root@localhost ~]# groupadd -g 6666 admins

Create group account tests sharing the GID of group admins:

[root@localhost ~]# groupadd -o -g 6666 tests

groupmod – Modifies group attributes. most options identical groupadd.

-n – us to change the name of an existing group from test to test666
[root@localhost ~]# groupmod -n tests666 tests

Change the GID of tests666 group to 6666

[root@localhost ~]# groupmod -g 6666 tests666

Usermod – Add user user1 to group admins while retaining the user’s existing memberships

[root@localhost ~]# usermod -a -G admins user1

[root@localhost ~]# id user1
uid=1000(user1) gid=1000(user1) groups=1000(user1),6666(admins)

[root@localhost ~]# groups user1
user1 : user1 admins

groupdel – Deletes a group. Removes entries for the specified group from both group and gshadow files.

[root@localhost ~]# groupdel admins

gpasswd – can be used to add group administrators, add or delete group members, assign or revoke a group password, and disable access to a group via the newgrp command. The root user can perform all of these tasks, while the group administrator can perform only the last three. This command prompts to change the group password if invoked by root or the group administrator. The gpasswd command updates the group and gshadow files. This command picks up the default values from the /etc/login.defs file.

–A/–administrators – Adds one or more group administrators. Inserts an entry in the third field of the gshadow file.

–a/–add – Adds a group member. Inserts an entry in the fourth field of both group and gshadow files.

–d/–delete – Deletes a group member.

–M/–members – Substitutes all existing group members.

–R/–restrict – Disables access to a group for non-members. Members with a password can still join the group.

–r/–remove-password – Revokes the password set on a group. Only group members can join the group

If a password is set the members can still use newgrp(1) without a password, and non-members must supply the password. Group passwords are an inherent security problem since more than one person is permitted to know the password. However, groups are a useful tool for permitting co-operation between different users.
gpasswd -A user1,user2new admins - Add user1 and user2new as administrators to the group

gpasswd -a user2new -a user3 admins - Add user2new and user3 as members to the group

gpasswd -M user4 admins - Substitute user2new and user3 with user4 as a member of the group

gpasswd admins - Set a password on the group

Log in as user4 and run the groups command to list group membership for user4. The primary group is listed first.

[user4@localhost ~]$ groups
user4 admins

Temporarily change the primary group for user4 to admins:

[user4@localhost ~]$ newgrp admins

Verify the new primary group membership for user4. It should be listed first in the output.

[user4@localhost ~]$ groups
admins user4

Return to the original primary group by issuing the exit command or pressing Ctrl+d, and verify

[user4@localhost ~]$ exit
logout

[root@localhost ~]# su - user4
Last login: Tue Oct 25 16:53:33 MSK 2016 on pts/1

[user4@localhost ~]$ groups
user4 admins

questions

1. What are the two utilities for manually editing shadow password files exclusively?
vipw, vigr
2. What are the two tools for checking shadow password files consistency?
pwck,grpck
3. What does the “x” in the password field in the passwd file imply?
The “x” in the password field implies that the encrypted password is stored in the shadow file.
4. What would the command useradd –D do?
show default values for created accounts
When invoked with only the -D option, useradd will display the current default values. When invoked with -D plus other options, useradd will update the default values for the specified options.
~# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no

5. Name the four local user authentication files.

passwd, shadow, group, gshadow
6. The passwd file contains secondary user group information. True or False?
nope
7. What does the gpasswd command do?
gpasswd command is used to add group administrators, add or delete group members, assign and revoke a group password, and disable access to a group with the newgrp command.
8. What is the name and location of the sudo configuration file?
/etc/sudoers
9. Which command would we use to add group administrators?
gpasswd
10. Name the two types of shell startup files?
system-wide, per-user
11. What would the command passwd –l user10 do?
lock login
12. What is the first UID assigned to a regular user?
1000
13. Name the three fundamental user account categories in RHEL.
root, normal, and system
14. Every user in RHEL gets a private group by default. True or False?
true
15. What would the userdel command do if it is run with the –r option?
delete user dir with account info
16. What is the first GID assigned to a group?
1000
17. Write two command names for managing password aging.
chage, passwd
18. What is the name of the default backup file for shadow?
shadow-
19. What would the command chage –E 2015-12-31 user10 do?
number of days since the epoch time on which the user account is deactivated
20. What would the command chage –l user5 do?
Lists password aging attributes set on a user account.
21. What is the difference between running the su command with and without the dash sign?
With the dash sign the su command will process the specified user’s startup files, and it won’t without this sign.
22. What is the significance of the –o option with the groupadd and groupmod commands?
create group with not uniq gid
23. What would the command passwd –n 7 –x 15 –w 3 user5 do?
Configures password aging for user5 with mindays (–n) set to 7, maxdays (–x) to 16, and warndays (–w) to 3 using the passwd
24. What two commands are used to create and update the shadow and gshadow files?
pwconv grpconv
25. What would the command useradd user500 do?
Create a User Account with Default Values defined in the useradd and login.defs files
26. Which command is used to change a user’s primary group temporarily?
newgrp
27. What would the command chage –d 0 user60 do?
With –d 0, the user is forced to change the password at next login.
28. What four local files are updated when a user account is created?
passwd, shadow, group, gshadow
29. UID 999 is reserved for normal users. True or False?
false
30. The /etc/bashrc file contains shell scripts that are executed at user login. True or False?
True

Which command adds the new user tux and creates the user’s home directory with default configuration files?

  1. passwd -a tux
  2. usercreate tux
  3. defaultuser tux
  4. useradd -m tux
  5. useradd -o default tux
@ useradd -m tux 
Команда создания пользователя — useradd. Опция '-m' используется для объявления необходимости создания домашнего каталога. Не забывайте о root-правах при использовании этой команды.

What is the UID of the user root?

@ В Linux учетной записью суперпользователя является root, который всегда имеет UID = 0. (cat /etc/passwd)

What information is stored in /etc/passwd?

(Choose three)

  1. The numerical user ID
  2. The user’s default shell
  3. The user’s storage space limit
  4. The username
  5. The encrypted password
@ 
The numerical user ID
The user's default shell
The username

Если вы посмотрите содержимое файла /etc/passwd, вы обнаружите, что
- первый столбец – имя пользователя,
- третий столбец — UID
- и последний столбец — это оболочка по умолчанию.
Когда-то раньше этот файл использовался также для хранения HASH паролей. Но сейчас не все об этом даже помнят, потому что это уже давно не так.

Which of the following tasks can the command passwd accomplish?

Change a user’s password. Изменить пароль пользователя.
Lock a user account. Заблокировать учетную запись пользователя.
Change a user’s username. Изменить имя пользователя.
Create a new user account. Создать новую учетную запись пользователя.
Create a new user group. Создать новую группу пользователей.
Основное назначение команды passwd — менять пароль пользователя. Но она также может заблокировать пользователя, используя опцию -l.

 

Which files are the source of the information in the following output? (Choose two.)

uid=1000 (bob) gid=1000 (bob) groups=1000 (bob), 10 (wheel), 150 (wireshark), 989 (docker), 1001 (libvirt)

/home/index

/etc/passwd

/etc/group

/var/db/users

/etc/id

Group,passwd
Файл /etc/passwd содержит список пользователей ОС, включая UID, GID, оболочку, домашний каталог...
Файл /etc/group содержит список групп, зарегистрированных в ОС, включая имя группы, GID, ее участников...

What happens to a file residing outside the home directory when the file owner’s account is deleted?

Оригинал Перевод
The UID of the former owner is shown when listing the file’s details. ID бывшего владельца отображается при перечислении сведений о файле.
Ownership and permissions of the file remain unchanged. Права владельцев и права доступа к файлу остаются неизменными.
During a file system check, the file is moved to /lost+found. Во время проверки файловой системы файл перемещается в папку /lost+found.
The user root is set as the new owner of the file. Пользователь root устанавливается в качестве нового владельца файла.
The file is removed from the file system Файл удаляется из файловой системы.
1-2
С самим файлом ничего не происходит (вроде удаления, перемещения или смены владельца).
Сценарий, реализован на скриншоте:

The ownership of the file doku.odt should be changed. The new owner is named tux. Which command accomplishes this change?

transfer tux: doku.odt

chmod u=tux doku.odt

newuser doku.odt tux

chown tux doku.odt

passwd doku.odt:tux

chown tux doku.odt

The current directory contains the following file:

-rw-r–r– 1 root exec 24551 Apr 2 12:36 test.sh

The file contains a valid shell script, but executing this file using ./test.sh leads to this error:                                         

bash: ./test.sh: Permission denied

What should be done in order to successfully execute the script?

Оригинал

Перевод

The execute bit should be set in the file’s permissions.

Бит выполнения должен быть установлен в правах доступа к файлу.

The file’s extension should be changed from .sh to .bin.

Расширение файла следует изменить с .sh на .bin.

The user executing the script should be added to the exec group.

Пользователь, выполняющий скрипт, должен быть добавлен в группу exec.

The SetUID bit should be set in the file’s permissions

Бит SetUID должен быть установлен в правах доступа к файлу.

The script should be run using #!./test. sh instead of ./test.sh.

Скриптследует запускать с использованием #!./test. sh вместо ./test.sh.

—-

The execute bit should be set in the file’s permissions. Основным моментом в этом вопросе является первый столбец содержимого каталога: -rw-r--r--

Там мы видим, что файл не имеет прав на исполнение. И это причина возникшей ошибки. Таким образом, чтобы решить проблему, нам нужно добавить права на выполнение файла (по крайней мере, владельцу файла). Решение может выглядеть так: chmod u+x test.sh

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
1. Which command can be used to determine a file type?
ls (general file, device character/block file)
file (file type)
2. The output generated by the umask command shows the current user mask in four digits. What is the significance of the left-most digit?
The left-most digit has no significance in the umask value.
3. Default permissions are calculated by subtracting the initial permissions from the umask value. True or False?
False. Default permissions are calculated by subtracting the umask value from the initial permission values.
4. The chgrp command may be used to modify both ownership and group membership on a file. True or False?
False, only group
5. Name the permission classes, types, and modes.
classes - user, group, others
types - read, write, execute
mode - add, revoke, assign
6. The default umask for a regular user in bash shell is 0027. True or False?
false
7. What digit represents the setuid bit in the chmod command?
first digit, value 4
8. What would the command find /var -perm -1000 –type d do?
It would search the /var directory for directories with sticky bit set.
9. What would the command chmod g-s file1 do?
It would remove the setgid bit from file1.
10. Sticky bit is recommended for every system directory. True or False?
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
24. Which special permission bit is set on a directory for team sharing?
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 is tune2fs. Explanation:l tune2fs 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 using tune2fs 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 the tune2fs utility. To change the frequency of filesystem checks using tune2fs, 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.

What is true about the owner of a file?

  1. Each file is owned by exactly one user and one group.
  2. The owner of a file always has full permissions when accessing the file.
  3. The user owning a file must be a member of the file’s group.
  4. When a user is deleted, all files owned by the user disappear.
  5. The owner of a file cannot be changed once it is assigned to an owner.
@ Each file is owned by exactly one user and one group.

Which of the following characters in a shell prompt indicates the shell is running with root privileges?

&

$

#

*
!

В основном есть два символа, обозначающие текущий тип привилегий.Это символы 
$, используемый для обычного пользователя, и символ
#, используемый для root.

 

Leave a Reply