Este conteúdo não está disponível no idioma selecionado.

Chapter 10. Managing sudo access


System administrators can grant sudo access to allow non-root users to execute administrative commands that are normally reserved for the root user. As a result, non-root users can execute such commands without logging in to the root user account.

10.1. User authorizations in sudoers

The /etc/sudoers file specifies which users can use the sudo command to execute other commands. The rules can apply to individual users and user groups. You can also define rules for groups of hosts, commands, and even users more easily by using aliases. Default aliases are defined in the first part of the /etc/sudoers file.

When a user enters a command with sudo for which the user does not have authorization, the system records a message that contains the string <username> : user NOT in sudoers to the journal log.

The default /etc/sudoers file provides information and examples of authorizations. You can activate a specific example rule by uncommenting the corresponding line. The section with user authorizations is marked with the following introduction:

## Next comes the main part: which users can run what software on
## which machines  (the sudoers file can be shared between multiple
## systems).

You can create new sudoers authorizations and modify existing authorizations by using the following format:

<username> <hostname.example.com>=(<run_as_user>:<run_as_group>) <path/to/command>

Where:

  • <username> is the user that enters the command, for example, user1. If the value starts with %, it defines a group, for example, %group1.
  • <hostname.example.com> is the name of the host on which the rule applies.
  • The section (<run_as_user>:<run_as_group>) defines the user or group as which the command is executed. If you omit this section, <username> can execute the command as root.
  • <path/to/command> is the complete absolute path to the command. You can also limit the user to only performing a command with specific options and arguments by adding those options after the command path. If you do not specify any options, the user can use the command with all options.

You can apply the rule to all users, hosts, or commands by replacing any of these variables with ALL.

Warning

With overly permissive rules, such as ALL ALL=(ALL) ALL, all users can run all commands as all users on all hosts. This presents serious security risks.

You can specify the arguments negatively by using the ! operator. For example, !root specifies all users except root. Note that allowing specific users, groups, and commands is more secure than disallowing specific users, groups, and commands. This is because allow rules also block new unauthorized users or groups.

Warning

Avoid using negative rules for commands because users can overcome such rules by renaming commands with the alias command.

The system reads the /etc/sudoers file from beginning to end. Therefore, if the file contains multiple entries for a user, the entries are applied in order. In case of conflicting values, the system uses the last match, even if it is not the most specific match.

To preserve the rules during system updates and for easier fixing of errors, enter new rules by creating new files in the /etc/sudoers.d/ directory instead of entering rules directly to the /etc/sudoers file. The system reads the files in the /etc/sudoers.d directory when it reaches the following line in the /etc/sudoers file:

#includedir /etc/sudoers.d

Note that the number sign (#) at the beginning of this line is part of the syntax and does not mean the line is a comment. The names of files in that directory must not contain a period and must not end with a tilde (~).

Additional resources

  • sudo(8) and sudoers(5) man pages on your system

10.2. Granting sudo access to a user

System administrators can allow non-root users to execute administrative commands by granting them sudo access. The sudo command provides users with administrative access without using the password of the root user.

When users need to perform an administrative command, they can precede that command with sudo. If the user has authorization for the command, the command is executed as if they were root.

Be aware of the following limitations:

  • Only users listed in the /etc/sudoers configuration file can use the sudo command.
  • The command is executed in the shell of the user, not in the root shell. However, there are some exceptions such as when full sudo privileges are granted to any user. In such cases, users can switch to and run the commands in root shell. For example:
  • sudo -i
  • sudo su -

Prerequisites

  • You have root access to the system.

Procedure

  1. As root, open the /etc/sudoers file.

    # visudo

    The /etc/sudoers file defines the policies applied by the sudo command.

  2. In the /etc/sudoers file, find the lines that grant sudo access to users in the administrative wheel group.

    ## Allows people in group wheel to run all commands
    %wheel        ALL=(ALL)       ALL
  3. Make sure the line that starts with %wheel is not commented out with the number sign (#).
  4. Save any changes, and exit the editor.
  5. Add users you want to grant sudo access to into the administrative wheel group.

     # usermod --append -G wheel <username>

    Replace <username> with the name of the user.

Verification

  • Verify that the user is in the administrative wheel group:

    # id <username>
    uid=5000(<username>) gid=5000(<username>) groups=5000(<username>),10(wheel)

Additional resources

  • sudo(8), visudo(8), and sudoers(5) man pages on your system

10.3. Enabling unprivileged users to run certain commands

As an administrator, you can allow unprivileged users to enter certain commands on specific workstations by configuring a policy in the /etc/sudoers.d/ directory. This is more secure than granting full sudo access to a user or giving someone the root password for the following reasons:

  • More granular control over privileged actions. You can allow a user to perform certain actions on specific hosts instead of giving them full administrative access.
  • Better logging. When a user performs an action through sudo, the action is logged with their user name and not just root.
  • Transparent control. You can set email notifications for every time the user attempts to use sudo privileges.

Prerequisites

  • You have root access to the system.

Procedure

  1. As root, create a new sudoers.d directory under /etc/:

    # mkdir -p /etc/sudoers.d/
  2. Create a new file in the /etc/sudoers.d directory:

    # visudo -f /etc/sudoers.d/<filename>

    The file opens automatically.

  3. Add the following line to the /etc/sudoers.d/<filename> file:

    <username> <hostname.example.com> = (<run_as_user>:<run_as_group>) <path/to/command>
    • Replace <username> with the name of the user.
    • Replace <hostname.example.com> with the URL of the host.
    • Replace (<run_as_user>:<run_as_group>) with the user or group as which the command can be executed. If you omit this section, <username> can execute the command as root.
    • Replace <path/to/command> with the complete absolute path to the command. You can also limit the user to only performing a command with specific options and arguments by adding those options after the command path. If you do not specify any options, the user can use the command with all options.
    • To allow two and more commands on the same host on one line, you can list them separated by a comma followed by a space.

      For example, to allow user1 to execute the dnf and reboot commands on host1.example.com, enter user1 host1.example.com = /bin/dnf, /sbin/reboot.

  4. Optional: To receive email notifications every time the user attempts to use sudo privileges, add the following lines to the file:

    Defaults    mail_always
    Defaults    mailto="<email@example.com>"
  5. Save the changes, and exit the editor.

Verification

  1. To verify if a user can run a command with sudo privileges, switch the account:

    # su <username> -
  2. As the user, enter the command with the sudo command:

    $ sudo <command>
    [sudo] password for <username>:

    Enter the user’s sudo password.

  3. If the privileges are configured correctly, the system displays the list of commands and options. For example, with the dnf command, it shows the following output:

    ...
    usage: dnf [options] COMMAND
    ...

    If the system returns the error message <username> is not in the sudoers file. This incident will be reported, the file for <username> in /etc/sudoers.d/ does not exist.

    If the system returns the error message <username> is not allowed to run sudo on <host.example.com>, the configuration was not completed correctly. Ensure that you are logged in as root and that the configuration was performed correctly.

    If the system returns the error message Sorry, user <username> is not allowed to execute '<path/to/command>' as root on <host.example.com>., the command is not correctly defined in the rule for the user.

Additional resources

  • sudo(8), visudo(8), and sudoers(5) man pages on your system

10.4. Applying custom sudoers configuration by using RHEL system roles

You can use the sudo RHEL system role to apply custom sudoers configuration on your managed nodes. That way, you can define which users can run which commands on which hosts, with better configuration efficiency and more granular control.

Prerequisites

Procedure

  1. Create a playbook file, for example ~/playbook.yml, with the following content:

    ---
    - name: "Configure sudo"
      hosts: managed-node-01.example.com
      tasks:
        - name: "Apply custom /etc/sudoers configuration"
          ansible.builtin.include_role:
            name: rhel-system-roles.sudo
          vars:
            sudo_sudoers_files:
              - path: "/etc/sudoers"
                user_specifications:
                  - users:
                      - <user_name>
                    hosts:
                      - <host_name>
                    commands:
                      - <path_to_command_binary>

    The settings specified in the playbook include the following:

    users
    The list of users that the rule applies to.
    hosts
    The list of hosts that the rule applies to. You can use ALL for all hosts.
    commands

    The list of commands that the rule applies to. You can use ALL for all commands.

    For details about all variables used in the playbook, see the /usr/share/ansible/roles/rhel-system-roles.sudo/README.md file on the control node.

  2. Validate the playbook syntax:

    $ ansible-playbook --syntax-check ~/playbook.yml

    Note that this command only validates the syntax and does not protect against a wrong but valid configuration.

  3. Run the playbook:

    $ ansible-playbook ~/playbook.yml

Verification

  1. On the managed node, verify that the playbook applied the new rules.

    # cat /etc/sudoers | tail -n1
    <user_name> <host_name>= <path_to_command_binary>

Additional resources

  • /usr/share/ansible/roles/rhel-system-roles.sudo/README.md file
  • /usr/share/doc/rhel-system-roles.sudo/sudo/ directory
Red Hat logoGithubRedditYoutubeTwitter

Aprender

Experimente, compre e venda

Comunidades

Sobre a documentação da Red Hat

Ajudamos os usuários da Red Hat a inovar e atingir seus objetivos com nossos produtos e serviços com conteúdo em que podem confiar.

Tornando o open source mais inclusivo

A Red Hat está comprometida em substituir a linguagem problemática em nosso código, documentação e propriedades da web. Para mais detalhes veja oBlog da Red Hat.

Sobre a Red Hat

Fornecemos soluções robustas que facilitam o trabalho das empresas em plataformas e ambientes, desde o data center principal até a borda da rede.

© 2024 Red Hat, Inc.