Skip to content
ImagineWorld

Users and Groups

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-05-users-and-groups
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleUsers and Groups
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’ll be taking a look at two of the building blocks that Linux uses to manage resources and maintain security: users and groups. After learning the basics and covering a very special user, root, we’ll show you how the concept of Linux user groups adds a convenient layer on top of the user abstraction.

Once we’ve covered the necessary theory, you’ll jump directly into the practical commands you need to create and modify users and groups. And, in a stunning triumph that will pay dividends if it ever comes up in an interview, you’ll see for yourself what a Linux user is actually made of (hint: it’s just three lines of plaintext).

By the end of this chapter, you’ll:

  • Understand what users are and what they’re used for
  • Understand the distinction between root and normal users, and how to switch between them when you need to
  • Know how to create and modify users and groups
  • Take a deeper dive into user metadata, and see what a Linux user is actually made of

A user, in the context of a Unix system, is simply a named entity that can do things on the system. Users can launch and own processes, own files and directories and have various permissions on them, and be allowed or prevented from doing things or using resources on the system. Practically, a user is who you log in as, what your processes run as, or who owns your files.

The word “user” is obviously a metaphor for a real person with a user account, a password, and so on. But most “users” on real systems don’t actually represent specific humans. They’re machine accounts, meant to group resources like processes and files for the purposes of security or organization.

But there’s a much more important distinction than whether or not an account is intended to be used interactively by a human operator. There are exactly two types of users, and before we jump into practical user-management skills, we need to talk about that distinction.

The world can be a harsh place, and sometimes it’s dangerous to run a command. For example, fdisk can wipe the partitions of a disk or otherwise modify hardware. iptables can open a network port and let an attacker exploit a vulnerability. Even using an innocuous echo command to send a value to the wrong place on a filesystem can change the operating system’s configuration in subtle and terrible ways.

To guard against this, the Unix-like environment that your command-line interface is running in has some built-in guardrails. There is a “superuser” called root in every Unix system. As a result, the basic security model is as follows:

  • First, there is root. This user is the equivalent of the system administrator on other systems and is the user with the highest number of permissions. root can do almost anything.
  • Then, there’s everybody else. Non-root users have limited permissions – they can’t launch processes or edit files that could affect the whole system, but they can launch their own (unprivileged) applications and edit their own files.

To guard against problems, only the root user can execute commands that change important aspects of your system. Because even seemingly innocuous commands can cause potential havoc if they’re run with the right arguments, you may find yourself needing root privileges just to edit a text file.

Because it would be an inconvenience to have to log in as a separate user every time you want to do something potentially dangerous on a system, there’s the sudo command. Prefixing a command with sudo, which stands for “substitute user (and) do,” lets you perform that command as the root user. When that command finishes executing and exits, your next command is interpreted as coming from your regular (non-root) user again.

You can see this behavior for yourself by running two commands. First, run the whoami command, which is a command that prints out the current user:

whoami

In this case. I’m logged in as the “ dave ” user, so this command prints out:

dave

Now, prepend “ sudo ” to that same command:

sudo whoami

Even though you’re still logged in as a non-root user, your effective user ID has changed for the duration of a single command, because of sudo:

root

Let’s look at a more practical example where we want to run a single action as root, but then continue running other commands as our regular user:

sudo systemctl start nginx
<go back to doing regular-user stuff>

That first command starts the nginx web server (presuming the nginx package is installed), which is something that only root can do. Any commands after that are executed as your regular user again.

This is a common workflow that ensures safety – you spend most of your time working as a regular user, incapable of borking the entire system in a single command. When you need root powers, you invoke them by prepending only those commands that require it with root. It’s a nice psychological barrier to accidentally breaking things on a system.

You’ll see this pattern used for various potentially dangerous things on a system, such as editing system-level configuration files, creating directories outside of your user’s home directory (covered later in this chapter), and more:

  • sudo mkdir /var/log/foobar
  • sudo vim /etc/hosts
  • sudo mount /dev/sdb1

You can use sudo to get a long-lived root shell session if you plan on running many commands as root (or if you’re troubleshooting something that runs as root, or simulating the environment that a cloud-init script would be executing in):

sudo -i

This will get you an interactive shell session as the root user. Be careful with this! There’s nothing stopping you from destroying the system with a mistake or a poorly typed command.

While sudo defaults to replace the current user with the root user, you can also change that to another user, via the –u option. For example:

sudo –u myuser vim /home/myuser/.bashrc

This will open /home/myuser/.bashrc in vim as the user myuser.

Which user (or group) is allowed to do what exactly can be defined in /etc/sudo.conf. You should never edit this file directly; use the visudo command to modify the file.

Groups are an additional primitive that allows a set of users to share permissions. Groups are often used to get the functionality of a permission set or profile. For example, on Linux, there’s often a group called sudoers, and on macOS, you’ll encounter a group called wheel. By convention, users who are members of the sudoers or wheel groups on these systems are allowed to use sudo to execute commands as root. This is functionally the same thing as adding a user to the Administrators group in Windows.

You can extrapolate that if groups are useful for managing who is allowed to run the sudo command, they might be useful for grouping together users and managing other kinds of permissions, too.

For example, imagine that we want to allow every user who is a software developer at our company to read a given file – let’s call it document.txt. We can simply create a developers group and add all of our developer users to that group.

Then, when we’re setting ownership and permissions for document.txt, we can reference the developers group instead of trying to keep track of every single user who might be a member of that group individually.

On a Linux system that has the adduser command installed, you can use it to interactively create a user named dave. If you don’t, the package is usually named useradd (see Chapter 9, Managing Installed Software for more details on installing packages).

Running the command with a username as the only argument will give you a wizard-style user creation process. Notice that we’re using sudo here, since only root can add or delete users:

$ sudo adduser steve
Adding user \`steve' ...
Adding new group \`steve' (1000) ...
Adding new user \`steve' (1000) with group \`steve' ...
Creating home directory \`/home/steve' ...
Copying files from \`/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for steve
Enter the new value, or press ENTER for the default
Full Name []: Steve
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] y

We’ve bolded the parts that required user interaction on our part – namely, setting the password, the full name, and the confirmation that we want to create this user on the system.

This is a nice way to add one or two users, but what if you’re working on a Linux test server that needs individual accounts for your 300 largest customers? You’ll want the non-interactive useradd command instead, which lets you specify user attributes as arguments to a single command. This makes user changes easy to script (see our note about scriptability later in this chapter):

useradd --home-dir /home/dave --create-home --shell /bin/zsh -g dave -G sudoers dave

That command also:

  • Sets and creates the user’s home directory (--home-dir and - -create-home)
  • Sets a custom shell (--shell)
  • Sets the user’s primary group to dave (although this could also be something like employees) with the -g option
  • Adds a supplementary group membership to the sudoers group (you can pass multiple comma-separated group names here)

And that’s it – if the command exits successfully, your new user has been created!

But we’re not done yet – this user is going to be working on the new, top-secret tutorialinux application, so let’s create a group for that project and add our new user to it.

To create a new group called tutorialinux, you’ll use the groupadd command:

groupadd tutorialinux

This creates a new group on the system, adding a line to the /etc/group configuration file, which is the record of all groups that exist on a Unix system. You can validate that the group was created by “grepping” (searching) for the group name in that file:

# grep tutorialinux /etc/group
tutorialinux:x:1001:

You can see that a group with the name tutorialinux now exists, with Group ID (GID) of 1001.

We’re not going to dive deeply into what the x character here means; it’s enough to know that this file is made up of one line for every group, with colon-separated values. You’ll only ever care about the group name (first column), group ID (third column), and members (last column, which is empty in this example).

Just as useradd allows you to set user metadata to your heart’s content during user creation, usermod and gpasswd allow you to modify all aspects of an existing user. Let’s add the dave user we created earlier to the new tutorialinux group, so he can work on project files that only group members can see or modify.

To change the primary group of the user: sudo usermod -g groupname username

That’s not exactly what we want here, though: the dave user should continue to be in the eponymous dave group; it’s just that we want dave to also be a member of the tutorialinux group. To add a user to a group without making it that user’s primary group, use the -aG options (“ add to additional groups ”):

sudo usermod –aG tutorialinux dave

If you inspect /etc/group again, you can see that the dave user is now a member of three groups: dave, sudoers, and tutorialinux:

grep dave /etc/group
sudoers:x:27:dave
dave:x:1000:
tutorialinux:x:1001:dave

Using the commands you learned in the previous chapter to modify file ownership and permissions, you can now control the access that all members of the tutorialinux group have to certain files and directories.

Now, when a specific user is done working on the tutorialinux project, you can clean up and revoke their access without having to modify individual file and directory permissions.

To remove a user from a group, we can use the gpasswd command like this:

gpasswd –delete username groupname

To remove a Linux user entirely, use the userdel command:

userdel -r account_name

If you want to preserve that user’s home directory, omit the (-r / --remove) flag.

There’s also a groupdel command for groups that are no longer needed:

groupdel groupname

Users and groups are one place where something quite wonderful about Unix and Linux can be seen clearly: there’s very little magic here.

A Linux user is really just a User ID (UID), which is a simple numerical representation of a user (an unsigned 32-bit integer). The root user’s UID is 0. All other users have a UID larger than 0. The same goes for groups.

This information is not stored in some secret location, in some binary format, or some proprietary data structure that only the operating system can work with: users and groups are defined in plaintext files, which are traditionally modified using the few simple commands we’ve covered here.

That simplicity and lack of magic means that mere mortals (such as a panicked developer with just a faded memory of this chapter) can quickly find out the state of users and groups on a running system, troubleshooting application errors that may come from an incorrectly prepared host environment that’s missing a necessary application user. It also comes in handy during the “systems engineering” portions of developer interviews.

So, in the interest of cementing your intuition about how this stuff works, here are a few more useful facts about what’s going on under the hood as we create and manage users and groups.

Users defined only by a number aren’t particularly useful – not without some additional metadata to spice things up. For example, an account that I use for my day-to-day work on a Linux or macOS machine, which happens to have UID 502, might also have:

  • A friendly login name (dave)
  • Its own group (the dave group)
  • Various group memberships (staff, developer, and wheel)
  • A login shell (bash, zsh, and so on)
  • A home directory (/Users/dave/ on macOS, or /home/dave/ on Linux)

If you’re curious, you can get information about your current user by running the id command:

# id
uid=0(root) gid=0(root) groups=0(root)

By default, a few files define and contain all this extra user information:

  • /etc/passwd contains a username, UID, GID, home directory, and login shell, all on one colon-delimited line per user:
    root@localhost:~# cat /etc/passwd
    root:x:0:0:root:/root:/bin/bash
    daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
    bin:x:2:2:bin:/bin:/usr/sbin/nologin
    sys:x:3:3:sys:/dev:/usr/sbin/nologin
    sync:x:4:65534:sync:/bin:/bin/sync
  • /etc/shadow contains the user’s hashed, salted passwords; it is readable only by the root user:
    root@localhost:~# cat /etc/shadow
    root:$6$SPevRPxD94AYwtmF$IOp9k15dnaN8FW8RUpDDQlifLPp9pJ3btgJcMfI
    QEs1kT.ZNjDfX66XBOcPOBZzkRcGOb3Rwq6qTsDQ0jiZNh/:19251:0:99999:7:::
    daemon:*:19251:0:99999:7:::
    bin:*:19251:0:99999:7:::
    sys:*:19251:0:99999:7:::
    sync:*:19251:0:99999:7:::
  • /etc/group – the equivalent of /etc/passwd, but for groups instead of users. You saw (and used) this file earlier in the chapter.

Optionally, a home directory like /home/dave:

# /etc/passwd username:password:UID:GID:comment:home:shell

WARNING: While it makes sense to know what these files contain, you should NEVER edit any of these files manually. Use the tools we used in the previous sections to create, remove, or modify system users and groups.

Hopefully, this quick theoretical overview of the moving parts – or more accurately, the static plaintext files – that make up users and groups was enlightening. Not only do we want to make sure that you’ve got an intuition for how this works, but we hope that this section stresses how simple this really is under the covers. There’s no magic here! You can feel confident that you’re not missing something the next time you’re troubleshooting why an application won’t start, or why a user doesn’t have permission to view a certain file with specific group ownership permissions.

Earlier, we alluded to preferring automatable tools like useradd, instead of interactive wizard-based tools like adduser – even if those automatable tools are a bit more complex or hard to learn. Or perhaps you’re asking, “Why not just use a graphical tool, instead of these hard-to-remember CLI commands?”

One of the things we want to teach you during the course of this book is to generally prefer non-interactive commands.

Because these commands don’t rely on real-time user input when they run, they are scriptable: creating a hundred users is almost as easy as creating one. This really comes in handy when you’re dealing with real-life problems like building Docker images, repeatedly preparing production environments, or writing cloud-init setup scripts for your cloud instances.

As a developer, this should ring true: automating things makes them more repeatable, safe, and fast. By learning commands that are non-interactive, you retain the power to use that command as part of a larger piece of automation, instead of having steps that require error-prone, time-consuming, and risky manual intervention.

You just learned the basics of how Linux uses the abstractions of users and groups to manage and control processes, files, and other resources on a system. Just as importantly, you learned the basic commands you need to create and manage users and groups on a real system. You learned about the important difference between the root user and all of the other normal users on a system.

Then, we walked through a practical exercise where you created a user, added a group to the system, modified that user, and then cleaned up all the resources you created.

Finally, we went beyond the day-to-day commands to show you that there’s no magic behind the scenes here: it’s all just plaintext files that define users and groups on a Unix system. This is a good thing; it’s going to make your life as a developer easy, whether you’re:

  • Creating a Docker image to run your application as a specific non-root user.
  • Setting up a long-running cloud instance with logins and a shared group for your data science team.
  • Trying to minimize the blast radius of a mistake in your own local test environment.
  • Troubleshooting user- and group-based errors on applications, for example, on a web application that needs root-user powers to open a secret file or do privileged actions on a system.

In the next chapter, we’ll use all of this knowledge to dive deeply into how the Unix security model works, by looking at ownership and permissions.