Linux

User Management and sudo

·2 min read

Unix has a single piece of state for "who you are" — a numeric UID. Everything else is policy bolted on top: groups, the password file, the sudoers file, PAM modules. Knowing where each piece lives saves hours when something is broken.

/etc/passwd, /etc/shadow, /etc/group

The classic Unix files. /etc/passwd is world-readable and holds username, UID, GID, home dir, and shell. /etc/shadow is root-only and holds the password hash. /etc/group maps group names to GIDs and lists members.

grep alice /etc/passwd
# alice:x:1001:1001:Alice Example:/home/alice:/bin/bash

sudo grep alice /etc/shadow
# alice:$6$xK...:19560:0:99999:7:::

getent passwd alice    # use this instead of grep; respects NSS

Creating and modifying users

useradd -m -s /bin/bash -G sudo,docker bob   # create with home, shell, groups
passwd bob                                    # set password
usermod -aG www-data bob                      # ADD bob to www-data; -a is critical
usermod -L bob                                # lock account (disable password)
userdel -r bob                                # delete user and their home
Always use -a with usermod -G.

Without -a, you replace the user's secondary groups instead of appending. People have locked themselves out of sudo this way.

Groups

groupadd developers
groupmod -n devs developers          # rename
gpasswd -a alice devs                # add user to group
gpasswd -d alice devs                # remove
groups alice                         # what groups is alice in?
id alice                             # full identity

sudo and the sudoers file

Never edit /etc/sudoers directly — use visudo, which validates syntax before saving. A broken sudoers file means you can't fix it with sudo.

sudo visudo

The format is USER HOST=(RUNAS) COMMANDS. Common patterns:

# Members of group "sudo" can run anything
%sudo   ALL=(ALL:ALL) ALL

# alice can restart nginx and only nginx, without password
alice   ALL=(root) NOPASSWD: /usr/bin/systemctl restart nginx

# devs can run apt update, no password
%devs   ALL=(root) NOPASSWD: /usr/bin/apt update

Drop fragments into /etc/sudoers.d/ instead of editing the main file. Filename must not contain dots, file mode must be 0440.

su, sudo -s, sudo -i

Three ways to become another user, three different environments. su - gives you a full login shell as root (reads root's profile). sudo -i is similar but uses the invoking user's authentication. sudo -s spawns a shell with sudo's environment — your PATH may not have /sbin.

PAM in one paragraph

PAM (Pluggable Authentication Modules) is what decides whether a login attempt succeeds. Configuration lives in /etc/pam.d/, one file per service. Each line is a rule of the form type control module args. The four types are auth (who are you?), account (are you allowed in?), password (change credentials), session (set up the environment). Most distributions ship a sane stack — touch carefully.

Related