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 username to 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:

FieldExampleDescription
UsernamestudentLogin name
PasswordxPlaceholder (actual hash in /etc/shadow)
UID1000User ID (numeric)
GID1000Primary group ID
GECOSStudent UserFull name/comment
Home Dir/home/studentHome directory path
Shell/bin/bashLogin 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:

FieldExampleDescription
Group NamesudoName of the group
PasswordxPlaceholder (in /etc/gshadow)
GID27Group ID
Membersstudent, adminSupplementary members (comma-separated)
  • Example Structure:
  •   Format: groupname:x:gid:members  
    

    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 newgrp command.
      • 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 groups command 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 su or sudo for privilege elevation as necessary.

    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
    • 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 exit to 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/sudoers file.
      • 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 otheruser triggers command execution as a different user.

    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.log for 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 exit to exit the root shell.

    /etc/sudoers File

    • Configuration Function: Controls which users can execute what commands through sudo. Edit with visudo only to avoid locking yourself out.

    • Critical Note: Always use sudo visudo for 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 -l to list sudo privileges.
      • View logs through sudo journalctl -xe | grep sudo.
      • Use #include to reference other configuration files.
      • Lines starting with # act as comments.

    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/passwd with new UID and GID.
      • User entry created in /etc/shadow for password information.
      • Primary group is set in /etc/group (if -g isn't specified).
      • If -m is 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.

    usermod Command


    • Modification Options:

    OptionPurpose
    -cChange GECOS (full name/comment)
    -dChange the home directory
    -sChange the login shell
    -gChange the primary group
    -GSet supplementary groups (overwriting)
    -aGAdd to supplementary groups (append)
    -LLock the user account (prevent login)
    -UUnlock 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/passwd and /etc/shadow.
      • If -r specified, 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.

    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:

    RangeTypePurpose
    0RootSystem administrator
    1-999System UsersRun services, daemons, system accounts
    1000+Regular UsersHuman users who log in to the system
  • Configuration Check: Verify definitions for 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 -g isn't used, automatically assigns the next available GID.
      • Use getent or grep to 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 gpasswd command 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/group and /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.

    Group Membership Management

    • Setup Preparation:
      • Initially create test users if required:sudo useradd user01 && sudo useradd user02.
    • 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).
      • groups or id: 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 exit to return to the original primary group.
      • Important for creating files with desired group ownership.
      • Permanent Change: To permanently change primary group use the usermod -g command.

    Password Security and Shadow Files

    Shadow Passwords

    • Purpose: Protect password data by using shadow files to securely store encrypted passwords.
    • File Locations:
      • /etc/shadow and /etc/gshadow for password storage.
      • /etc/passwd is 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:

    FieldExampleDescription
    LoginstudentUsername
    Password$6$…Encrypted hash (SHA-512)
    Last Change18990Days since Jan 1, 1970
    Min Days0Minimum days before password is changed
    Max Days99999Maximum days password is valid
    Warn Days7Days 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:
      1. User enters their password at the login prompt.
      2. The system retrieves the password hash from /etc/shadow.
      3. The input password is hashed using the same algorithm and salt.
      4. The computed hash is compared to the stored hash.
      5. 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:

    OptionPurpose
    -lList current password aging information
    -dSet the last password change date
    -MEstablish maximum days a password is valid
    -mDefine minimum days required before next password change
    -WSet warning days prior to expiration
    -EDefine the expiration date for the account
  • Example Command:
  •   sudo chage -M 90 student  # Password expires in 90 days  
    

    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:
      • -l lists 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 -E option (expiration date).
      • Using chage -d 0 forces a password change at the next login.

    Restricting Access

    • Approaches to Limit Access:
      • Set the user's shell to /sbin/nologin to prevent login (typified for service accounts).
      • Use passwd -l to lock accounts (adds ! to the password hash).
      • Use passwd -u to unlock accounts.
      • usermod -L and usermod -U achieve similar results for locking and unlocking accounts respectively.
      • Use chage -E 0 to immediately expire an account.
      • Remove user from sudoers to prevent privilege escalation.

    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-data and mail, 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 chage for 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.
      • chown and chgrp commands for managing ownership.
    • Best Practices:

      • Minimize direct root user access.
      • Utilize sudo for privilege escalation tasks.
      • Enforce strict password policies.
      • Conduct regular access audits.
      • Maintain monitor logs, focusing on /var/log/auth.log for security insights.