Posted by

Create a Sudo Admin User on Ubuntu and Debian: sudo Group, sudoers.d Drop-ins, visudo Checks and Least Privilege

Logging in as root for daily work is risky: one typo runs with full power, and you lose a record of who did what. The usual fix on Ubuntu and Debian servers is a normal user account that can run admin commands through sudo. This guide shows how to create that user, how sudo decides what a user may run, how to write rules safely with visudo, and how to give a service account access to one command instead of everything.

The commands below were written for current Ubuntu LTS and Debian releases. Paths and defaults can differ on your system, so check the man sudoers and man visudo pages installed on your own server.

Before you start: keep a way back in

A broken sudo rule or a wrong group change can lock you out of admin access. Before you change anything:

  • Keep one root shell (or one working sudo session) open the whole time. Do not close it until you have tested the new setup in a second SSH session.
  • Know how to reach your provider's web console or recovery mode, in case SSH stops working.
  • Never edit /etc/sudoers or files in /etc/sudoers.d/ with a plain editor. Use visudo, which checks the syntax before it saves.

Step 1: Create the admin user

On Debian and Ubuntu, adduser is the friendly tool. It creates the home folder, copies the default files and asks for a password:

sudo adduser alice

(If you are logged in as root, leave out sudo.) The lower-level useradd command also exists, but it does not create a home folder or set a password unless you ask for it, so adduser is easier for people accounts.

If this person will log in with an SSH key, add the key to /home/alice/.ssh/authorized_keys and make sure the folder is owned by the user with strict permissions (700 for .ssh, 600 for authorized_keys). Our SSH hardening guide covers key-only login in detail.

Step 2: Give full admin rights with the sudo group

On Debian and Ubuntu the default /etc/sudoers file already contains this rule:

%sudo   ALL=(ALL:ALL) ALL

The % means "group". Any member of the sudo group may run any command as any user after typing their own password. So to make alice an administrator you only add the account to that group:

sudo usermod -aG sudo alice

The -a (append) is important. Without it, usermod -G replaces the user's other supplementary groups with the list you give. On Debian you can also use sudo adduser alice sudo, which does the same thing.

Group membership is read when a user logs in. An existing session does not see the new group, so log in again before testing.

Step 3: Test in a second session

Open a new SSH session as the new user and run:

id
sudo -l
sudo whoami
  • id should list sudo among the groups.
  • sudo -l lists what sudo allows this user to run. You should see (ALL : ALL) ALL.
  • sudo whoami should print root.

Only when this works should you close your original root session or make other changes, such as turning off root login over SSH.

How sudo reads its rules

A sudoers rule has this shape:

WHO   WHERE=(AS_WHOM)   WHAT
alice ALL=(ALL:ALL)     ALL
PartExampleMeaning
Whoalice or %sudoA user name, or a group name starting with %.
WhereALLThe host the rule applies to. On a single server this is almost always ALL.
As whom(ALL:ALL) or (root)The target user (and optionally group) the command may run as.
TagsNOPASSWD:Optional. NOPASSWD skips the password prompt for the commands that follow.
WhatALL or /usr/bin/systemctl restart myapp.serviceThe commands allowed. Use full paths. ALL means every command.

Two rules from the sudoers manual are worth remembering:

  • The last matching rule wins. If a user matches several rules, sudo uses the last one that matches. A broad rule placed after a narrow one can silently undo it.
  • Files in /etc/sudoers.d/ are read in sorted order, through the @includedir /etc/sudoers.d line at the end of the main file (older versions write #includedir, which is not a comment). File names that end in ~ or contain a . are skipped, so a file called deploy.conf is silently ignored. Use names like 50-deploy.

Step 4: Use sudoers.d drop-ins instead of editing the main file

Package updates may want to replace /etc/sudoers. Keeping your own rules in separate files under /etc/sudoers.d/ keeps them apart from the default file and makes them easy to review or remove. Create or edit a drop-in with visudo -f:

sudo visudo -f /etc/sudoers.d/50-deploy

visudo locks the file, opens your editor and checks the syntax when you save. If there is an error it tells you the line and asks what to do; choose to edit again rather than save a broken file. To pick the editor, set it for that one command, for example sudo EDITOR=nano visudo -f /etc/sudoers.d/50-deploy.

Files in sudoers.d should be owned by root and not writable by anyone else. Mode 0440 is the usual choice:

sudo chown root:root /etc/sudoers.d/50-deploy
sudo chmod 0440 /etc/sudoers.d/50-deploy

After any change, check the whole configuration, including every included file:

sudo visudo -c

Each file should be reported as parsed OK. If you created a file some other way (for example with a configuration tool), check it before it is used: sudo visudo -cf /path/to/file.

Step 5: Least privilege for service accounts

A deploy script or CI job rarely needs full root. Often it only needs to restart one service. Give it exactly that:

# /etc/sudoers.d/50-deploy
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp.service, /usr/bin/systemctl status myapp.service

With this rule the deploy user can run those two commands as root without a password, and nothing else. Some points that keep such rules safe:

  • Use the full path. Find it with command -v systemctl. On current Ubuntu and Debian it is /usr/bin/systemctl.
  • Arguments matter. When you list arguments, the user must type them exactly as written. If you list only the command with no arguments, any arguments are allowed, which for systemctl would mean stopping or disabling any service.
  • Avoid wildcards in arguments. A rule like /usr/bin/systemctl restart * lets the user restart every service, and wildcards can match more than you expect.
  • Do not allow programs that can start a shell. Editors (vim, nano), pagers (less), find, tar, script interpreters and many other tools can run other commands, so allowing them through sudo is close to allowing full root. To let someone edit one file, use sudoedit (below).
  • Never allow a script the user can write to. If deploy can change /home/deploy/restart.sh and may run it with sudo, deploy is effectively root. Put such scripts in a root-owned folder such as /usr/local/sbin/ with mode 755.

Check the result as root:

sudo -l -U deploy

This prints the rules that apply to deploy without logging in as that user.

Let someone edit one file with sudoedit

Instead of allowing an editor as root, allow sudoedit for a specific file:

# /etc/sudoers.d/60-web-editors
%webadmins ALL=(root) sudoedit /etc/nginx/sites-available/example.conf

Members of webadmins then run sudoedit /etc/nginx/sites-available/example.conf. Sudo copies the file to a temporary file, opens the user's own editor as the user, and copies the result back. The editor itself never runs as root, so it cannot be used to start a root shell.

A note on NOPASSWD for people

Many cloud images give the default user passwordless sudo, often through a file such as /etc/sudoers.d/90-cloud-init-users. It is convenient, but it means anyone who gets that user's session (a stolen SSH key, a leftover open terminal) is instantly root. For human admin accounts, consider removing NOPASSWD once the account has a password, and keep NOPASSWD for narrow, specific service-account rules like the one above. Before you remove it, make sure the user really has a password set (sudo passwd alice) and test in a second session.

Useful sudo commands

CommandWhat it does
sudo -lShow what you are allowed to run.
sudo -l -U aliceShow what another user may run (needs admin rights).
sudo -iStart a root login shell with root's environment. Use sparingly.
sudo -u www-data commandRun a command as another user, if the rules allow it.
sudo -kForget your cached credentials, so the next sudo asks for the password again.
sudo visudo -cCheck the syntax of the main sudoers file and all included files.
sudoedit /path/fileEdit a file safely with your own editor running as you.

See who used sudo

Sudo logs every command it runs, both allowed and refused. On systems that run rsyslog, look in /var/log/auth.log:

sudo grep sudo /var/log/auth.log | tail -n 20

Some recent installs do not include rsyslog, so /var/log/auth.log may not exist. The systemd journal has the same entries:

sudo journalctl _COMM=sudo --since today

Lines that contain NOT in sudoers or command not allowed show refused attempts and are worth a look.

Remove sudo rights

When a person leaves or a role changes, remove the group membership:

sudo gpasswd -d alice sudo

(sudo deluser alice sudo does the same on Debian and Ubuntu.) Then search for rules that name the user directly and remove or update them with visudo:

sudo grep -rn alice /etc/sudoers /etc/sudoers.d/

Group changes take effect at the next login, so also end the user's open sessions (for example with sudo loginctl terminate-user alice). If the account is no longer needed at all, lock it with sudo usermod -L -e 1 alice or remove it with sudo deluser alice.

Common problems

  • "alice is not in the sudoers file": the user is not in the sudo group, or they have not logged in again since being added. Check with id alice.
  • A new sudoers.d rule has no effect: the file name contains a dot or ends in ~, or a later rule overrides it. Rename the file and check the order with sudo -l -U user.
  • "syntax error" and sudo stops working: a file was saved without visudo. Use your still-open root session to fix it, or run pkexec visudo if polkit is installed, or boot into recovery mode or the provider console.
  • A NOPASSWD rule still asks for a password: the command typed does not exactly match the rule (different path or arguments), or the user also matches a later rule without NOPASSWD.

Quick checklist

  1. Keep a root session open and know your console access.
  2. Create the user with adduser and add SSH keys.
  3. Add admins with usermod -aG sudo; never forget -a.
  4. Put custom rules in /etc/sudoers.d/ with names without dots, edited with visudo -f, mode 0440.
  5. Run sudo visudo -c after every change.
  6. Give service accounts only the exact commands they need, with full paths and fixed arguments.
  7. Test with sudo -l in a second session before closing the first.

Sources