Managing Users Groups Presentation
Chapter 10: Managing Local Users and Groups
Chapter Objectives
- Understand Linux user and group concepts
- Work with user and group administration commands
- Manage user accounts and permissions
- Configure sudo access and privileges
- Implement security best practices
- Understand password management and shadow files
Linux Users Overview
Foundation of Linux Security: Users are integral to the security and access control of the system.
Process Ownership: Every running process in Linux operates with a user's identity, denoted as UID (User ID).
User Organization: Groups allow users with similar permissions to be organized together.
User Information Storage:
User details are stored in:
/etc/passwd: Contains basic user info./etc/shadow: Contains password and aging details.Group information is stored in:
/etc/group: Basic group info./etc/gshadow: Group password and member info.
Root User: The superuser with UID 0, possessing unrestricted access to the system.
User Types
Root User:
- UID: 0
- Capabilities:
- Full system access.
- Can create/delete users and modify any file.
- Recommendations: Use sparingly due to security risks.
System Users:
- UID: < 1000
- Purpose: Run services and daemons.
- Login Shell: Not applicable.
- Examples:
www-data,mail. - Privileges: Limited.
Regular Users:
- UID: >= 1000
- Capabilities:
- Regular login capabilities.
- Home directories available.
- Limited permissions.
- Can use sudo for privilege escalation.
The id Command
- Purpose: Display user and group identities.
- Example Command:
$ id
uid=1000(student) gid=1000(student) groups=1000(student),27(sudo)
- Explanation of Output:
- uid: User ID (numeric identifier).
- gid: Primary Group ID.
- groups: All group memberships (both primary and supplementary).
- Check Other Users: Use
id usernameto check a specific user's information if that user exists.
/etc/passwd File
- Purpose: Contains user account information; it is world-readable.
- Example Content:
$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
student:x:1000:1000:Student User:/home/student:/bin/bash
- File Structure:
- One line per user account.
- Fields separated by colons
:.
- Password Field: Contains 'x' symbol indicating that actual passwords are stored in
/etc/shadow.
/etc/passwd Format
- Fields in /etc/passwd:
| Field | Example | Description | |
|---|---|---|---|
| Username | student | Login name | |
| Password | x | Placeholder (actual hash in /etc/shadow) | |
| UID | 1000 | User ID (numeric) | |
| GID | 1000 | Primary group ID | |
| GECOS | Student User | Full name/comment | |
| Home Dir | /home/student | Home directory path | |
| Shell | /bin/bash | Login shell | |
Linux Groups |
- Definition: Groups are collections of user accounts that share permissions.
- Primary Group Requirement: Every user is required to belong to at least one group (their primary group).
- Supplementary Groups: Users can belong to multiple additional groups.
- Group Identifiers: Each group has a numeric identifier known as GID (Group ID).
- Types of Groups:
- System Groups: GID < 1000
- User Groups: GID >= 1000
- Purpose: Groups help manage access to files and resources.
/etc/group Format
- Fields in /etc/group:
| Field | Example | Description | |
|---|---|---|---|
| Group Name | sudo | Name of the group | |
| Password | x | Placeholder (in /etc/gshadow) | |
| GID | 27 | Group ID | |
| Members | student, admin | Supplementary members (comma-separated) | |
|
Primary vs Supplementary Groups
Primary Group:
- Each user has exactly one primary group.
- This is set in
/etc/passwd(GID field). - Files created by the user belong to this primary group.
- Can be changed using the
newgrpcommand. - Typically shares the same name as the username.
Supplementary Groups:
- Users can have zero or more supplementary groups.
- Configurations are found in
/etc/group(members field). - Used to grant additional permissions.
- Visible through the
groupscommand output. - Common examples include: sudo, wheel, docker.
User Access and Privilege Management
Superuser (Root)
- Access Levels:
- The root user (UID 0) serves as the system administrator with unrestricted access.
- Capabilities include reading, writing, and executing any file.
- Full control over user creation, modification, and deletion along with system configurations.
- Security Risks:
- Direct use of the root account poses potential security risks; thus, it is advised to utilize
suorsudofor privilege elevation as necessary.
- Direct use of the root account poses potential security risks; thus, it is advised to utilize
su Command
- Function: Switches to another user account.
- Setup Requirement: Ensure the desired target user exists prior to switching.
- Example command:
bash $ su Password: [enter root password] $ su - username Password: [enter user's password] $ exit
- Example command:
- Behavior:
su -: Switches to the specified user, loading complete environment for that user.su: Preserves current environment (less secure).- Requires the password of the target user if switching or root access if moving to the root user.
- Use
exitto return to the previous user context.
su vs su -
su (without dash):
- Preserves current environment.
- PATH and variables remain unchanged; home directory does not switch.
- Quicker privilege elevation but less secure.
su - (with dash):
- Loads the target user’s environment.
- Transfers to the login shell for that user.
- Changes to the home directory of the target user.
- Full environment is set up, considered a more secure practice.
sudo Command
- Meaning: Stands for substitute user do.
- Purpose: Allows execution of commands with root or another user's privileges.
- Security Features:
- Does not require the root password; instead, it uses the password of the user executing the command.
- Privileges are determined as specified in the
/etc/sudoersfile. - All executed commands under sudo are logged, providing an audit trail.
- More secure than directly providing the root password.
- Considered a best practice for privilege escalation.
How sudo Works
- Typical Usage Examples:
$ sudo useradd newuser
$ sudo usermod -L username
$ sudo systemctl restart apache2
$ sudo -u otheruser whoami
- Process Overview:
- Check user’s sudo privileges via
/etc/sudoers. - User is prompted for their password (not the root password).
- The system verifies the entered password.
- The command is executed with elevated privileges.
- Log of the executed command is maintained.
- Use of
sudo -u otherusertriggers command execution as a different user.
- Check user’s sudo privileges via
sudo Access Denied
- Common Denials:
- If the user is not listed in the sudoers file: "student is not in the sudoers file."
- If the sudoers entry does not permit the attempted command: "sorry, you are not allowed to execute this command."
- If the password is entered incorrectly: access denied.
- All denied attempts are logged for auditing; check
/var/log/auth.logfor logs of sudo attempts.
Interactive Root Shell
- Starting Commands:
$ sudo -i
Password: [enter password]
# whoami
root
# exit
- Functionality:
sudo -i: Initiates an interactive shell as the root user.sudo -s: Starts root shell with the current environment settings.- Useful for executing multiple commands with elevated privileges while remaining logged and auditable.
- Use
exitto exit the root shell.
/etc/sudoers File
Configuration Function: Controls which users can execute what commands through sudo. Edit with
visudoonly to avoid locking yourself out.Critical Note: Always use
sudo visudofor editing; direct changes can disrupt sudo functionality.File Format:
# User privilege specification
root ALL=(ALL:ALL) ALL
student ALL=(ALL) NOPASSWD: /usr/bin/systemctl
%sudo ALL=(ALL:ALL) ALL
- Format Description:
user host=(runuser:group) command%groupname: Designates all users belonging to that group.NOPASSWD: Indicates no password prompt required.
sudo Config Examples
- Illustrative Entries:
# Allow student to run reboot without prompting for a password
student ALL=(ALL) NOPASSWD: /sbin/reboot
# Allow admin group to execute all commands
%admin ALL=(ALL:ALL) ALL
# Allow user john to run only the passwd command
john ALL=(ALL) /usr/bin/passwd
- Editing and Testing:
- Edit with
sudo visudo. - Test changes using
sudo -lto list sudo privileges. - View logs through
sudo journalctl -xe | grep sudo. - Use
#includeto reference other configuration files. - Lines starting with
#act as comments.
- Edit with
User and Group Management Commands
useradd Command
- Purpose: Creates new user accounts.
- Example Command:
$ sudo useradd -m -s /bin/bash -G sudo newuser
$ sudo passwd newuser # Set password
$ id newuser # Verify user creation
- Options:
-m: Create a home directory for the user.-s: Specify the login shell (default:/bin/sh).-g: Assign a primary group.-G: Add the user to the supplementary groups (comma-separated list).-c: Set GECOS comment (e.g., full name).-d: Define the home directory path.
useradd Process
- Process Overview:
- Default values checked in
/etc/login.defs(e.g., UIDMIN, UIDMAX, PASSMAXDAYS). - User entry created in
/etc/passwdwith new UID and GID. - User entry created in
/etc/shadowfor password information. - Primary group is set in
/etc/group(if-gisn't specified). - If
-mis specified, a home directory is created, and skeleton files copied from/etc/skel. - Set appropriate permissions and ownership for files within the user's home directory.
- Default values checked in
usermod Command
- Modification Options:
| Option | Purpose | |
|---|---|---|
| -c | Change GECOS (full name/comment) | |
| -d | Change the home directory | |
| -s | Change the login shell | |
| -g | Change the primary group | |
| -G | Set supplementary groups (overwriting) | |
| -aG | Add to supplementary groups (append) | |
| -L | Lock the user account (prevent login) | |
| -U | Unlock the user account | |
userdel Command |
- Functionality: Deletes user accounts.
- Examples:
$ sudo userdel olduser # Deletes user only
$ sudo userdel -r olduser # Deletes user and home directory
- Process Description:
- Removes entries from
/etc/passwdand/etc/shadow. - If
-rspecified, associated home directory and mail spool will be removed. - Note: Files owned by deleted user still exist and are retained under their UID.
- User must not be currently logged in or running any processes for deletion to succeed.
- Removes entries from
passwd Command
- Purpose: Change user passwords and manage password settings.
- Examples:
$ passwd # Change own password
$ sudo passwd username # Change another user's password
$ sudo passwd -l username # Lock account
$ sudo passwd -u username # Unlock account
- Options:
- Without a username: Change the password for the user executing the command.
-l: Lock the password (adds!to the hash).-u: Unlock the password.-e: Expire the password, forcing reset at next login.-S: Show the password status.
UID Ranges
- Range Details:
| Range | Type | Purpose | |
|---|---|---|---|
| 0 | Root | System administrator | |
| 1-999 | System Users | Run services, daemons, system accounts | |
| 1000+ | Regular Users | Human users who log in to the system | |
UID_MIN and UID_MAX in /etc/login.defs. | |||
Group Management |
groupadd Command
- Purpose: Creates new groups.
- Examples:
$ sudo groupadd developers
$ sudo groupadd -g 2000 testgroup # Specify GID
$ getent group developers # Verify group creation
- Options:
-g: Assign a specific GID (must be unique and greater than 999).- If
-gisn't used, automatically assigns the next available GID. - Use
getentorgrepto confirm successful group creation.
groupmod Command
- Modify Group Properties:
$ sudo groupmod -n newname oldname # Rename group
$ sudo groupmod -g 3000 groupname # Change GID
$ sudo groupmod -p password groupname # Set group password
- Options:
-n: Renames the group from old to new.-g: Changes the GID (must be unique).-p: Sets a group password, though rarely utilized.
- Member Management: Use the
gpasswdcommand to add or remove group members. Updates will be reflected in/etc/group.
groupdel Command
- Functionality: Deletes groups.
- Examples:
$ sudo groupdel groupname
$ getent group groupname # Confirm deletion
- Important Notes:
- Removes group entries from
/etc/groupand/etc/gshadow. - Cannot delete the primary group of existing users; these users must first be removed from the group or the user must be deleted.
- If an error states 'group is a primary group', it indicates some user has this as their primary group.
- Confirm deletion using
getent group groupname.
- Removes group entries from
Group Membership Management
- Setup Preparation:
- Initially create test users if required:
sudo useradd user01 && sudo useradd user02.
- Initially create test users if required:
- Example Commands:
$ sudo gpasswd -a student sudo # Adds student to sudo group
$ sudo gpasswd -d student sudo # Removes student from sudo group
$ groups student # Show groups for student
$ id student # User ID information
- Functionality of Commands:
gpasswd -a user group: Adds a user to a specified group.gpasswd -d user group: Removes a user from a specified group.usermod -aG groups user: Adds a user to multiple groups (persistent).usermod -G groups user: Sets groups for a user (replaces all existing groups).groupsorid: Shows current group membership.
Temporarily Changing Primary Group
- Usage of newgrp Command:
newgrp: Allows switching to a different primary group temporarily during a session.- Requirements: User must be a member of the target group.
- Functionality:
- New files created in the new shell will inherit the new group.
- Use
exitto return to the original primary group. - Important for creating files with desired group ownership.
- Permanent Change: To permanently change primary group use the
usermod -gcommand.
Password Security and Shadow Files
Shadow Passwords
- Purpose: Protect password data by using shadow files to securely store encrypted passwords.
- File Locations:
/etc/shadowand/etc/gshadowfor password storage./etc/passwdis world-readable, but shadow files are restricted to root access.
- Benefits:
- Prevents password cracking attempts by not showing plaintext passwords.
- Additional information related to password aging is also stored.
- In
/etc/passwd, the password field contains an 'x' as a placeholder rather than the actual hash. - Activated when the
shadow()function is invoked during user creation.
- Management Commands:
pwconv: Converts the traditional password file to shadow format.pwunconv: Reverts shadow files back to traditional format.
/etc/shadow Format
- Fields in /etc/shadow:
| Field | Example | Description | |
|---|---|---|---|
| Login | student | Username | |
| Password | $6$… | Encrypted hash (SHA-512) | |
| Last Change | 18990 | Days since Jan 1, 1970 | |
| Min Days | 0 | Minimum days before password is changed | |
| Max Days | 99999 | Maximum days password is valid | |
| Warn Days | 7 | Days warning before expiration | |
| Inactive | [number] | Days after expiration before disabling account | |
| Expiration | [date] | Account expiration date | |
Crypto Hashing |
- Hashing Mechanisms: Passwords are stored using irreversible hashing, meaning they cannot be converted back to plaintext.
- Different Hash Types:
$1$= MD5 (considered weak, deprecated).$5$= SHA-256 (medium strength, used in older systems).$6$= SHA-512 (strong and currently the default for modern systems).$2a$/$2b$/$2x$/$2y$= bcrypt (very strong).
- Salting: Adding random data to the password prior to hashing to enhance security.
- Non-Retrievability: Once hashed, passwords cannot be recovered in their original form.
Password Verification Process
- User Login Sequence:
- User enters their password at the login prompt.
- The system retrieves the password hash from
/etc/shadow. - The input password is hashed using the same algorithm and salt.
- The computed hash is compared to the stored hash.
- If the hashes match, the password is correct; if they do not, access is denied.
- Limitations: No method exists to retrieve lost passwords after hashing; users must reset passwords instead.
chage Command
- Purpose: Manage aspects of password aging and settings.
- Options Available:
| Option | Purpose | |
|---|---|---|
| -l | List current password aging information | |
| -d | Set the last password change date | |
| -M | Establish maximum days a password is valid | |
| -m | Define minimum days required before next password change | |
| -W | Set warning days prior to expiration | |
| -E | Define the expiration date for the account | |
|
chage Examples
- Common Commands:
$ chage -l student # Show password aging info
$ sudo chage -M 90 student # Max validity of 90 days
$ sudo chage -W 7 student # Warn 7 days before expiration
$ sudo chage -E 2025-12-31 student # Expire on a specific date
- Functionality:
-llists current password aging settings for users.- Regular users can only view their own password aging settings while root can modify any user's.
- Use YYYY-MM-DD format for
-Eoption (expiration date). - Using
chage -d 0forces a password change at the next login.
Restricting Access
- Approaches to Limit Access:
- Set the user's shell to
/sbin/nologinto prevent login (typified for service accounts). - Use
passwd -lto lock accounts (adds!to the password hash). - Use
passwd -uto unlock accounts. usermod -Landusermod -Uachieve similar results for locking and unlocking accounts respectively.- Use
chage -E 0to immediately expire an account. - Remove user from sudoers to prevent privilege escalation.
- Set the user's shell to
nologin Shell
- Definition:
/sbin/nologin: A pseudo-shell specifically designed to refuse login attempts.- No interactive shell is provided – users cannot log in, although the account may still run processes through the system.
- Use Case: Particularly useful for service accounts such as
www-dataandmail, etc. - Customization: A custom message can be displayed if an unauthorized access is attempted, typically sourced from
/etc/nologin.txt. - Command Example:
sudo usermod -s /sbin/nologin username
Chapter Summary - Part 1
User Management:
useradd: Create users.usermod: Modify users.userdel: Delete users.passwd: Change passwords.id: Show user info.
Group Management:
groupadd: Create groups.groupmod: Modify groups.groupdel: Delete groups.gpasswd: Manage group members.groups: Show memberships.
Privilege Escalation:
su: Switch user context.sudo: Elevate privileges.visudo: Safely edit sudoers file.newgrp: Change primary group temporarily.sudo -i: Start an interactive root shell.
Chapter Summary - Part 2
Password Security:
- Shadow files are used to protect password hashes.
- SHA-512 is the modern hashing standard.
- Password aging policies can be instituted.
- Use of
chagefor managing password ages. - Various methods of account locking are available.
Access Control:
- Groups control access to specific files.
- Differentiation between primary and supplementary groups.
- Characteristic identifiers for UID and GID.
- Mechanisms for permission inheritance.
chownandchgrpcommands for managing ownership.
Best Practices:
- Minimize direct root user access.
- Utilize
sudofor privilege escalation tasks. - Enforce strict password policies.
- Conduct regular access audits.
- Maintain monitor logs, focusing on
/var/log/auth.logfor security insights.