# Users and groups: who can do what

Create, change, lock and remove accounts, use groups to share access, give exactly the sudo rights someone needs, and run services as accounts nobody can log in to.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 8. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/08-users-groups

## What you will learn

- Read /etc/passwd, /etc/shadow and /etc/group, and look accounts up with id and getent
- Create, modify, lock and delete users, and set password ageing
- Add users to groups without removing their other groups
- Give a team limited sudo rights with a file in /etc/sudoers.d, checked by visudo
- Create a service account that can run a program but can't log in
- Set up a shared team folder where every new file belongs to the team

## Who you are

Before a server had separate accounts, people could share a login and its access. That made it impossible to
tell which person changed a file or to remove one person's access without changing everyone else's. Linux
identities assign each process a user ID and groups, which the kernel checks against file permissions and
other access controls.

Every process runs as a **user**, and every file belongs to a user and a **group**. The primary group is used
for newly created files; supplementary groups add access such as `sudo` or log reading. Start by checking the
identity of the shell before changing a file or running an administrative command:

```sh
$ id
uid=1000(rajeev) gid=1000(rajeev) groups=1000(rajeev),4(adm),27(sudo),998(docker)
$ getent passwd rajeev
rajeev:x:1000:1000:Rajeev Kumar:/home/rajeev:/bin/bash
```

Your **primary group** (gid) is given to the files you create. Your **supplementary groups** give
extra access: `sudo` lets you use sudo, `docker` lets you talk to Docker, `adm` lets you read
many logs.

## Where accounts live

> **Figure.** A line from /etc/passwd split into its seven fields, separated by colons: user name asha; x, meaning the password hash is in /etc/shadow; user id 1001; primary group id 1001; a comment with her full name; home folder /home/asha; login shell /bin/bash. Below, matching lines from /etc/shadow, with the password hash and ageing fields readable only by root, and /etc/group, listing group members.
>
> Three plain-text files hold every account. Read them with getent; change them with the tools.

| File          | Holds                            | Readable by |
| ------------- | -------------------------------- | ----------- |
| `/etc/passwd` | names, ids, home folders, shells | everyone    |
| `/etc/shadow` | password hashes, password ageing | root only   |
| `/etc/group`  | groups and their members         | everyone    |

```sh
$ getent group devops                # a group and its members
devops:x:1005:asha,ravi
$ awk -F: '$3 >= 1000 {print $1}' /etc/passwd   # human accounts (ids from 1000)
```

User ids below 1000 belong to the system and to services (`www-data`, `postgres`, `sshd`). Don't
edit these files by hand: the tools below lock them, validate the fields and keep the three files
in step. `getent` also asks LDAP or other directories if the server uses them.

## Creating, changing and removing users

Use the account-management tools rather than editing `/etc/passwd` or `/etc/shadow` directly. `useradd`
creates the account and can create its home directory; `passwd` sets credentials; `usermod` changes account
settings; and `userdel` removes it. These tools validate fields and update related account files safely.

```sh
$ sudo useradd -m -s /bin/bash -c "Asha Verma" asha   # -m home folder, -s shell, -c full name
$ sudo passwd asha                                    # set her first password
$ sudo chage -d 0 asha                                # must choose a new one at first login
$ sudo chage -l asha                                  # password ageing details
$ sudo usermod -s /bin/zsh asha                       # change her shell
$ sudo usermod -L asha                                # lock: no password logins
$ sudo usermod -U asha                                # unlock
$ sudo chage -E 2026-12-31 contractor1                # the account expires on that date
$ sudo userdel -r olduser                             # delete the user and their home folder
```

New home folders are copied from `/etc/skel`. Put a default `.bashrc` there and every new user
gets it.

On Debian and Ubuntu, `adduser asha` is a friendlier wrapper that asks questions and creates the
home folder for you. Scripts and other distributions use `useradd`, so learn that one.

> **When someone leaves the team.** Lock first, delete later: `sudo usermod -L` the account, remove their SSH key from `~/.ssh/authorized_keys`, and check `crontab -l -u name` for jobs that still run as them. Delete the account once you're sure nothing depends on it. A locked password doesn't stop SSH key logins, which is why the key must go too.

> **Video.** [Linux Crash Course -  Managing Users](https://www.youtube.com/watch?v=19WOD84JFxA) (Learn Linux TV)

## Groups

A group gives several users the same access without repeating permission changes for every person. Files can
belong to a group, and supplementary group membership can grant access to devices, logs or administrative
commands. Keep groups aligned with team responsibilities and review membership when people change roles.

```sh
$ sudo groupadd devops                  # create a group
$ sudo usermod -aG devops asha          # ADD asha to devops (keeps her other groups)
$ id asha
uid=1001(asha) gid=1001(asha) groups=1001(asha),1005(devops)
$ sudo gpasswd -d asha devops           # remove her from one group
$ sudo groupmod -n platform devops      # rename the group
$ sudo groupdel platform                # delete it
```

> **-a, every time.** `usermod -G docker asha` (without `-a`) **replaces** all her supplementary groups with just `docker`. If that removed her `sudo` group on a server where she was the only admin, nobody can use sudo there any more. Type `-aG` as one word, every time.

Group changes apply at the next login. The person has to log out and back in (or run
`newgrp devops`) before `id` shows the new group in their session.

Use group membership for shared access and remove membership when the job changes. Check the user's full
group list before editing it, and use `-aG` with `usermod` to append one group without replacing the others.
The new group list applies to new login sessions, not processes that are already running. A common mistake is
assuming a user has the new permission immediately inside an existing SSH shell.

> **Video.** [Linux Crash Course - Managing Groups](https://www.youtube.com/watch?v=GnlgAD8-GhE) (Learn Linux TV)

## Service accounts

If every service runs as root, a bug or compromise in one service can change any file on the host. A **service
account** is a dedicated non-human user that owns or accesses only the files the application needs. Give it no
interactive login and no unnecessary supplementary groups.

```sh
$ sudo useradd --system --no-create-home --shell /usr/sbin/nologin myapp
$ sudo chown -R myapp:myapp /srv/myapp
$ sudo -u myapp /srv/myapp/bin/server     # run something AS that user
```

If the app is broken into, the attacker gets only what `myapp` can touch, and `nologin` means
nobody can open a shell as it. Package installs already do this: `www-data` for nginx, `postgres`
for PostgreSQL.

Use systemd's `User=` and `Group=` settings or the package's service account to run the process with limited
rights. Keep writable directories separate from executable code when practical. A common mistake is creating
a service user but still launching the process as root, so verify the effective user in the service status or
process list.

## sudo rights: exactly what is needed

Members of the `sudo` group (`wheel` on Red Hat systems) may run anything as root. That's right for
administrators and too much for most people. Give everyone else exactly the commands they need,
in a separate file per team:

> **Figure.** A sudoers rule explained. %devops is who: the devops group. ALL is on which hosts. (root) is as which user. Then the exact commands allowed, with full paths: /usr/bin/systemctl restart nginx and /usr/bin/systemctl reload nginx. Anything else they run with sudo is refused and logged.
>
> Who, where, as whom, and exactly which commands. Nothing else is allowed.

```sh
$ sudo visudo -f /etc/sudoers.d/devops
```

```text
# devops may manage nginx, nothing else
%devops ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx
```

```sh
$ sudo visudo -c                         # check every sudoers file
/etc/sudoers: parsed OK
/etc/sudoers.d/devops: parsed OK
$ sudo -l -U asha                        # what may asha run?
User asha may run the following commands on web-01:
    (root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx
```

Always use full paths in rules (`which systemctl` tells you), and always edit with `visudo`: it
refuses to save a file with a mistake in it. Be careful with `NOPASSWD:` and with programs that
can start a shell (editors, `less`, `find -exec`, any script the user can edit): allowing them is
the same as allowing everything.

`su - asha` switches to another account and needs **her** password. `sudo -iu asha` does the same
with **your** sudo rights, which is how admins check a user's environment without knowing their
password.

> **Video.** [Linux Crash Course - sudo](https://www.youtube.com/watch?v=07JOqKOBRnU) (Learn Linux TV)

## A shared team folder

When several people maintain one deployment tree, personal ownership can block teammates from updating files.
Give the directory a shared group, enable the setgid bit so new entries inherit that group, and choose a
umask that grants the intended group access without opening files to every user.

Combine groups with the setgid bit from the previous lessons:

```sh
$ sudo mkdir -p /srv/app
$ sudo chgrp devops /srv/app
$ sudo chmod 2775 /srv/app               # 2 = setgid, 775 = rwx for owner and group
$ ls -ld /srv/app
drwxrwsr-x 2 root devops 4096 Oct 13 12:10 /srv/app
```

The `s` in the group set is setgid. New entries inherit the directory's `devops` group, regardless of who
creates them. Group inheritance alone does not make every file writable; the creating process's umask still
controls its permission bits.

Use a shared group and setgid on team directories, then choose a group-friendly umask for the users or
services writing there. Verify new files with `ls -l` before relying on the setup. A common mistake is
assuming setgid grants write access by itself; it selects the group, while mode bits decide what that group
can do.

## Mission: Onboard a developer and a service

Asha joins the devops team. She needs a login, membership of devops, permission to restart and reload nginx with sudo (nothing else), and write access to /srv/app. The app itself must run as its own account that can't log in.

- You need: A Linux VM where you have sudo
- You'll have: Users asha and myapp, /etc/sudoers.d/devops, /srv/app

```sh
$ sudo groupadd devops
$ sudo useradd -m -s /bin/bash -c "Asha Verma" -G devops asha
$ sudo passwd asha && sudo chage -d 0 asha
$ echo '%devops ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx' \
    | sudo EDITOR='tee' visudo -f /etc/sudoers.d/devops > /dev/null
$ sudo visudo -c
$ sudo useradd --system --no-create-home --shell /usr/sbin/nologin myapp
$ sudo mkdir -p /srv/app && sudo chgrp devops /srv/app && sudo chmod 2775 /srv/app
$ id asha
uid=1001(asha) gid=1001(asha) groups=1001(asha),1005(devops)
$ sudo -l -U asha | tail -n 1
    (root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx
$ getent passwd myapp
myapp:x:998:998::/home/myapp:/usr/sbin/nologin
```

`EDITOR='tee' visudo -f …` writes the rule through visudo, so it's still syntax-checked, without
opening an editor: handy in scripts. `getent` shows `myapp` with `nologin`, and its user id below
1000 marks it as a system account.

## Try it

- Run `id` and `getent passwd $USER`, and name each field of your passwd line.
- Create a test user with `sudo useradd -m -s /bin/bash testuser` and set a password.
- Add the user to a new group with `sudo usermod -aG`, then check with `id testuser`.
- Lock the account with `sudo usermod -L testuser` and confirm `sudo passwd -S testuser` shows `L`.
- Run `sudo -l` and read what you're allowed to do.
- Delete the test user and its home folder with `sudo userdel -r testuser`.

## Quiz

1. You run sudo usermod -G docker asha. What happens to her other groups, like sudo and devops?
   - Nothing, docker is added
   - **They are removed: without -a, -G replaces the whole list** (answer)
   - The command fails
   Why: usermod -aG docker asha appends. Plain -G sets the supplementary groups to exactly the list given, which has locked people out of sudo more than once.

2. Where are password hashes stored?
   - /etc/passwd
   - **/etc/shadow, readable only by root** (answer)
   - ~/.password
   Why: /etc/passwd must be readable by everyone (programs look up names in it), so the x in its second field points to /etc/shadow, which only root can read.

3. Your app runs as its own user. Which shell should that account have?
   - /bin/bash, so you can debug it
   - **/usr/sbin/nologin, so nobody can log in as it** (answer)
   - No shell field at all
   Why: A service account needs to own files and run a process, not to log in. nologin means a stolen password or key for it opens no shell.

4. Why add sudo rules in a file under /etc/sudoers.d with visudo, instead of editing /etc/sudoers directly?
   - It is faster
   - **visudo checks the syntax before saving: a broken sudoers file can lock everyone out of sudo** (answer)
   - Files in sudoers.d are ignored
   Why: One typo in a sudoers file stops sudo from working for everyone. visudo refuses to save a broken file, and a separate file per team is easy to review and remove.

5. Files the team creates in /srv/app keep getting each person's own group, so others can't edit them. What fixes it?
   - chmod 777 /srv/app
   - **chgrp devops /srv/app and chmod 2775 /srv/app (setgid), so new files inherit the devops group** (answer)
   - Give everyone the same login
   Why: The setgid bit on a folder makes new files and folders inside take the folder's group. With group write (the 7 in 775), the whole team can work together.

## Resources

- [useradd(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/useradd.8.html) (Ubuntu manpages)
- [usermod(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/usermod.8.html) (Ubuntu manpages)
- [sudoers(5): rules, aliases and examples](https://manpages.ubuntu.com/manpages/noble/man5/sudoers.5.html) (Ubuntu manpages)
- [shadow(5): the password file format](https://manpages.ubuntu.com/manpages/noble/man5/shadow.5.html) (Ubuntu manpages)
- [LPIC-1 exam 102, objectives 107.1 and 110.1](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
