Understanding privilege escalation: become

Ansible uses existing privilege escalation systems to execute tasks with root privileges or with another user’s permissions. Because this feature allows you to ‘become’ another user, different from the user that logged into the machine (remote user), we call it become. The become keyword leverages existing privilege escalation tools like sudo, su, pfexec, doas, pbrun, dzdo, ksu, runas, machinectl and others.

Using become

You can control the use of become with play or task directives, connection variables, or at the command line. If you set privilege escalation properties in multiple ways, review the general precedence rules to understand which settings will be used.

A full list of all become plugins that are included in Ansible can be found in the Plugin List.

Become directives

You can set the directives that control become at the play or task level. You can override these by setting connection variables, which often differ from one host to another. These variables and directives are independent. For example, setting become_user does not set become.

  • become
  • set to yes to activate privilege escalation.
  • become_user
  • set to user with desired privileges — the user you become, NOT the user you login as. Does NOT imply become: yes, to allow it to be set at host level. Default value is root.
  • become_method
  • (at play or task level) overrides the default method set in ansible.cfg, set to use any of the Become Plugins.
  • become_flags
  • (at play or task level) permit the use of specific flags for the tasks or role. One common use is to change the user to nobody when the shell is set to no login. Added in Ansible 2.2.

For example, to manage a system service (which requires root privileges) when connected as a non-root user, you can use the default value of become_user (root):

  1. - name: Ensure the httpd service is running
  2. service:
  3. name: httpd
  4. state: started
  5. become: yes

To run a command as the apache user:

  1. - name: Run a command as the apache user
  2. command: somecommand
  3. become: yes
  4. become_user: apache

To do something as the nobody user when the shell is nologin:

  1. - name: Run a command as nobody
  2. command: somecommand
  3. become: yes
  4. become_method: su
  5. become_user: nobody
  6. become_flags: '-s /bin/sh'

Become connection variables

You can define different become options for each managed node or group. You can define these variables in inventory or use them as normal variables.

  • ansible_become
  • equivalent of the become directive, decides if privilege escalation is used or not.
  • ansible_become_method
  • which privilege escalation method should be used
  • ansible_become_user
  • set the user you become through privilege escalation; does not imply ansible_become: yes
  • ansible_become_password
  • set the privilege escalation password. See Using Vault in playbooks for details on how to avoid having secrets in plain text

For example, if you want to run all tasks as root on a server named webserver, but you can only connect as the manager user, you could use an inventory entry like this:

  1. webserver ansible_user=manager ansible_become=yes

Note

The variables defined above are generic for all become plugins but plugin specific ones can also be set instead.Please see the documentation for each plugin for a list of all options the plugin has and how they can be defined.A full list of become plugins in Ansible can be found at Become Plugins.

Become command-line options

—ask-become-pass, -K
ask for privilege escalation password; does not imply become will be used. Note that this password will be used for all hosts.
—become, -brun operations with become (no password implied)
—become-method=BECOME_METHOD
privilege escalation method to use (default=sudo),valid choices: [ sudo | su | pbrun | pfexec | doas | dzdo | ksu | runas | machinectl ]
—become-user=BECOME_USER
run operations as this user (default=root), does not imply –become/-b

Risks and limitations of become

Although privilege escalation is mostly intuitive, there are a few limitationson how it works. Users should be aware of these to avoid surprises.

Risks of becoming an unprivileged user

Ansible modules are executed on the remote machine by first substituting theparameters into the module file, then copying the file to the remote machine,and finally executing it there.

Everything is fine if the module file is executed without using become,when the become_user is root, or when the connection to the remote machineis made as root. In these cases Ansible creates the module file with permissionsthat only allow reading by the user and root, or only allow reading by the unprivilegeduser being switched to.

However, when both the connection user and the become_user are unprivileged,the module file is written as the user that Ansible connects as, but the file needs tobe readable by the user Ansible is set to become. In this case, Ansible makesthe module file world-readable for the duration of the Ansible module execution.Once the module is done executing, Ansible deletes the temporary file.

If any of the parameters passed to the module are sensitive in nature, and you donot trust the client machines, then this is a potential danger.

Ways to resolve this include:

  • Use pipelining. When pipelining is enabled, Ansible does not save themodule to a temporary file on the client. Instead it pipes the module tothe remote python interpreter’s stdin. Pipelining does not work forpython modules involving file transfer (for example: copy,fetch, template), or for non-python modules.
  • Install POSIX.1e filesystem acl support on themanaged host. If the temporary directory on the remote host is mounted withPOSIX acls enabled and the setfacl tool is in the remote PATHthen Ansible will use POSIX acls to share the module file with the secondunprivileged user instead of having to make the file readable by everyone.
  • Avoid becoming an unprivilegeduser. Temporary files are protected by UNIX file permissions when youbecome root or do not use become. In Ansible 2.1 and above, UNIXfile permissions are also secure if you make the connection to the managedmachine as root and then use become to access an unprivileged account.

Warning

Although the Solaris ZFS filesystem has filesystem ACLs, the ACLsare not POSIX.1e filesystem acls (they are NFSv4 ACLs instead). Ansiblecannot use these ACLs to manage its temp file permissions so you may haveto resort to allow_world_readable_tmpfiles if the remote machines use ZFS.

Changed in version 2.1.

Ansible makes it hard to unknowingly use become insecurely. Starting in Ansible 2.1,Ansible defaults to issuing an error if it cannot execute securely with become.If you cannot use pipelining or POSIX ACLs, you must connect as an unprivileged user,you must use become to execute as a different unprivileged user,and you decide that your managed nodes are secure enough for themodules you want to run there to be world readable, you can turn onallow_world_readable_tmpfiles in the ansible.cfg file. Settingallow_world_readable_tmpfiles will change this from an error intoa warning and allow the task to run as it did prior to 2.1.

Not supported by all connection plugins

Privilege escalation methods must also be supported by the connection pluginused. Most connection plugins will warn if they do not support become. Somewill just ignore it as they always run as root (jail, chroot, etc).

Only one method may be enabled per host

Methods cannot be chained. You cannot use sudo /bin/su - to become a user,you need to have privileges to run the command as that user in sudo or be ableto su directly to it (the same for pbrun, pfexec or other supported methods).

Privilege escalation must be general

You cannot limit privilege escalation permissions to certain commands.Ansible does not alwaysuse a specific command to do something but runs modules (code) froma temporary file name which changes every time. If you have ‘/sbin/service’or ‘/bin/chmod’ as the allowed commands this will fail with ansible as thosepaths won’t match with the temporary file that Ansible creates to run themodule. If you have security rules that constrain your sudo/pbrun/doas environmentto running specific command paths only, use Ansible from a special account thatdoes not have this constraint, or use Red Hat Ansible Tower to manage indirect access to SSH credentials.

May not access environment variables populated by pamd_systemd

For most Linux distributions using systemd as their init, the defaultmethods used by become do not open a new “session”, in the sense ofsystemd. Because the pam_systemd module will not fully initialize a newsession, you might have surprises compared to a normal session opened throughssh: some environment variables set by pam_systemd, most notablyXDG_RUNTIME_DIR, are not populated for the new user and instead inheritedor just emptied.

This might cause trouble when trying to invoke systemd commands that depend onXDG_RUNTIME_DIR to access the bus:

  1. $ echo $XDG_RUNTIME_DIR
  2.  
  3. $ systemctl --user status
  4. Failed to connect to bus: Permission denied

To force become to open a new systemd session that goes throughpam_systemd, you can use become_method: machinectl.

For more information, see this systemd issue.

Become and network automation

As of version 2.6, Ansible supports become for privilege escalation (entering enable mode or privileged EXEC mode) on all Ansible-maintained platforms that support enable mode. Using become replaces the authorize and auth_pass options in a provider dictionary.

You must set the connection type to either connection: network_cli or connection: httpapi to use become for privilege escalation on network devices. Check the Platform Options and Network modules documentation for details.

You can use escalated privileges on only the specific tasks that need them, on an entire play, or on all plays. Adding become: yes and become_method: enable instructs Ansible to enter enable mode before executing the task, play, or playbook where those parameters are set.

If you see this error message, the task that generated it requires enable mode to succeed:

  1. Invalid input (privileged mode required)

To set enable mode for a specific task, add become at the task level:

  1. - name: Gather facts (eos)
  2. eos_facts:
  3. gather_subset:
  4. - "!hardware"
  5. become: yes
  6. become_method: enable

To set enable mode for all tasks in a single play, add become at the play level:

  1. - hosts: eos-switches
  2. become: yes
  3. become_method: enable
  4. tasks:
  5. - name: Gather facts (eos)
  6. eos_facts:
  7. gather_subset:
  8. - "!hardware"

Setting enable mode for all tasks

Often you wish for all tasks in all plays to run using privilege mode, that is best achieved by using group_vars:

group_vars/eos.yml

  1. ansible_connection: network_cli
  2. ansible_network_os: eos
  3. ansible_user: myuser
  4. ansible_become: yes
  5. ansible_become_method: enable

Passwords for enable mode

If you need a password to enter enable mode, you can specify it in one of two ways:

  • providing the —ask-become-pass command line option
  • setting the ansible_become_password connection variable

Warning

As a reminder passwords should never be stored in plain text. For information on encrypting your passwords and other secrets with Ansible Vault, see Ansible Vault.

authorize and auth_pass

Ansible still supports enable mode with connection: local for legacy network playbooks. To enter enable mode with connection: local, use the module options authorize and auth_pass:

  1. - hosts: eos-switches
  2. ansible_connection: local
  3. tasks:
  4. - name: Gather facts (eos)
  5. eos_facts:
  6. gather_subset:
  7. - "!hardware"
  8. provider:
  9. authorize: yes
  10. auth_pass: " {{ secret_auth_pass }}"

We recommend updating your playbooks to use become for network-device enable mode consistently. The use of authorize and of provider dictionaries will be deprecated in future. Check the Platform Options and Network modules documentation for details.

Become and Windows

Since Ansible 2.3, become can be used on Windows hosts through therunas method. Become on Windows uses the same inventory setup andinvocation arguments as become on a non-Windows host, so the setup andvariable names are the same as what is defined in this document.

While become can be used to assume the identity of another user, there are other uses forit with Windows hosts. One important use is to bypass some of thelimitations that are imposed when running on WinRM, such as constrained networkdelegation or accessing forbidden system calls like the WUA API. You can usebecome with the same user as ansible_user to bypass these limitationsand run commands that are not normally accessible in a WinRM session.

Administrative rights

Many tasks in Windows require administrative privileges to complete. When usingthe runas become method, Ansible will attempt to run the module with thefull privileges that are available to the remote user. If it fails to elevatethe user token, it will continue to use the limited token during execution.

A user must have the SeDebugPrivilege to run a become process with elevatedprivileges. This privilege is assigned to Administrators by default. If thedebug privilege is not available, the become process will run with a limitedset of privileges and groups.

To determine the type of token that Ansible was able to get, run the followingtask:

  1. - win_whoami:
  2. become: yes

The output will look something similar to the below:

  1. ok: [windows] => {
  2. "account": {
  3. "account_name": "vagrant-domain",
  4. "domain_name": "DOMAIN",
  5. "sid": "S-1-5-21-3088887838-4058132883-1884671576-1105",
  6. "type": "User"
  7. },
  8. "authentication_package": "Kerberos",
  9. "changed": false,
  10. "dns_domain_name": "DOMAIN.LOCAL",
  11. "groups": [
  12. {
  13. "account_name": "Administrators",
  14. "attributes": [
  15. "Mandatory",
  16. "Enabled by default",
  17. "Enabled",
  18. "Owner"
  19. ],
  20. "domain_name": "BUILTIN",
  21. "sid": "S-1-5-32-544",
  22. "type": "Alias"
  23. },
  24. {
  25. "account_name": "INTERACTIVE",
  26. "attributes": [
  27. "Mandatory",
  28. "Enabled by default",
  29. "Enabled"
  30. ],
  31. "domain_name": "NT AUTHORITY",
  32. "sid": "S-1-5-4",
  33. "type": "WellKnownGroup"
  34. },
  35. ],
  36. "impersonation_level": "SecurityAnonymous",
  37. "label": {
  38. "account_name": "High Mandatory Level",
  39. "domain_name": "Mandatory Label",
  40. "sid": "S-1-16-12288",
  41. "type": "Label"
  42. },
  43. "login_domain": "DOMAIN",
  44. "login_time": "2018-11-18T20:35:01.9696884+00:00",
  45. "logon_id": 114196830,
  46. "logon_server": "DC01",
  47. "logon_type": "Interactive",
  48. "privileges": {
  49. "SeBackupPrivilege": "disabled",
  50. "SeChangeNotifyPrivilege": "enabled-by-default",
  51. "SeCreateGlobalPrivilege": "enabled-by-default",
  52. "SeCreatePagefilePrivilege": "disabled",
  53. "SeCreateSymbolicLinkPrivilege": "disabled",
  54. "SeDebugPrivilege": "enabled",
  55. "SeDelegateSessionUserImpersonatePrivilege": "disabled",
  56. "SeImpersonatePrivilege": "enabled-by-default",
  57. "SeIncreaseBasePriorityPrivilege": "disabled",
  58. "SeIncreaseQuotaPrivilege": "disabled",
  59. "SeIncreaseWorkingSetPrivilege": "disabled",
  60. "SeLoadDriverPrivilege": "disabled",
  61. "SeManageVolumePrivilege": "disabled",
  62. "SeProfileSingleProcessPrivilege": "disabled",
  63. "SeRemoteShutdownPrivilege": "disabled",
  64. "SeRestorePrivilege": "disabled",
  65. "SeSecurityPrivilege": "disabled",
  66. "SeShutdownPrivilege": "disabled",
  67. "SeSystemEnvironmentPrivilege": "disabled",
  68. "SeSystemProfilePrivilege": "disabled",
  69. "SeSystemtimePrivilege": "disabled",
  70. "SeTakeOwnershipPrivilege": "disabled",
  71. "SeTimeZonePrivilege": "disabled",
  72. "SeUndockPrivilege": "disabled"
  73. },
  74. "rights": [
  75. "SeNetworkLogonRight",
  76. "SeBatchLogonRight",
  77. "SeInteractiveLogonRight",
  78. "SeRemoteInteractiveLogonRight"
  79. ],
  80. "token_type": "TokenPrimary",
  81. "upn": "[email protected]",
  82. "user_flags": []
  83. }

Under the label key, the account_name entry determines whether the userhas Administrative rights. Here are the labels that can be returned and whatthey represent:

  • Medium: Ansible failed to get an elevated token and ran under a limitedtoken. Only a subset of the privileges assigned to user are available duringthe module execution and the user does not have administrative rights.
  • High: An elevated token was used and all the privileges assigned to theuser are available during the module execution.
  • System: The NT AUTHORITY\System account is used and has the highestlevel of privileges available.

The output will also show the list of privileges that have been granted to theuser. When the privilege value is disabled, the privilege is assigned tothe logon token but has not been enabled. In most scenarios these privilegesare automatically enabled when required.

If running on a version of Ansible that is older than 2.5 or the normalrunas escalation process fails, an elevated token can be retrieved by:

  • Set the become_user to System which has full control over theoperating system.

  • Grant SeTcbPrivilege to the user Ansible connects with onWinRM. SeTcbPrivilege is a high-level privilege that grantsfull control over the operating system. No user is given this privilege bydefault, and care should be taken if you grant this privilege to a user or group.For more information on this privilege, please seeAct as part of the operating system).You can use the below task to set this privilege on a Windows host:

  1. - name: grant the ansible user the SeTcbPrivilege right
  2. win_user_right:
  3. name: SeTcbPrivilege
  4. users: '{{ansible_user}}'
  5. action: add
  • Turn UAC off on the host and reboot before trying to become the user. UAC isa security protocol that is designed to run accounts with theleast privilege principle. You can turn UAC off by running the followingtasks:
  1. - name: turn UAC off
  2. win_regedit:
  3. path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system
  4. name: EnableLUA
  5. data: 0
  6. type: dword
  7. state: present
  8. register: uac_result
  9.  
  10. - name: reboot after disabling UAC
  11. win_reboot:
  12. when: uac_result is changed

Note

Granting the SeTcbPrivilege or turning UAC off can cause Windowssecurity vulnerabilities and care should be given if these steps are taken.

Local service accounts

Prior to Ansible version 2.5, become only worked on Windows with a local or domainuser account. Local service accounts like System or NetworkServicecould not be used as become_user in these older versions. This restrictionhas been lifted since the 2.5 release of Ansible. The three service accountsthat can be set under become_user are:

  • System
  • NetworkService
  • LocalService

Because local service accounts do not have passwords, theansible_become_password parameter is not required and is ignored ifspecified.

Become without setting a password

As of Ansible 2.8, become can be used to become a Windows local or domain accountwithout requiring a password for that account. For this method to work, thefollowing requirements must be met:

  • The connection user has the SeDebugPrivilege privilege assigned
  • The connection user is part of the BUILTIN\Administrators group
  • The become_user has either the SeBatchLogonRight or SeNetworkLogonRight user right

Using become without a password is achieved in one of two different methods:

  • Duplicating an existing logon session’s token if the account is already logged on
  • Using S4U to generate a logon token that is valid on the remote host only

In the first scenario, the become process is spawned from another logon of thatuser account. This could be an existing RDP logon, console logon, but this isnot guaranteed to occur all the time. This is similar to theRun only when user is logged on option for a Scheduled Task.

In the case where another logon of the become account does not exist, S4U isused to create a new logon and run the module through that. This is similar tothe Run whether user is logged on or not with the Do not store passwordoption for a Scheduled Task. In this scenario, the become process will not beable to access any network resources like a normal WinRM process.

To make a distinction between using become with no password and becoming anaccount that has no password make sure to keep ansible_become_password asundefined or set ansible_become_password:.

Note

Because there are no guarantees an existing token will exist for auser when Ansible runs, there’s a high change the become process will onlyhave access to local resources. Use become with a password if the task needsto access network resources

Accounts without a password

Warning

As a general security best practice, you should avoid allowing accounts without passwords.

Ansible can be used to become a Windows account that does not have a password (like theGuest account). To become an account without a password, set up thevariables like normal but set ansible_become_password: ''.

Before become can work on an account like this, the local policyAccounts: Limit local account use of blank passwords to console logon only)must be disabled. This can either be done through a Group Policy Object (GPO)or with this Ansible task:

  1. - name: allow blank password on become
  2. win_regedit:
  3. path: HKLM:\SYSTEM\CurrentControlSet\Control\Lsa
  4. name: LimitBlankPasswordUse
  5. data: 0
  6. type: dword
  7. state: present

Note

This is only for accounts that do not have a password. You still needto set the account’s password under ansible_become_password if thebecome_user has a password.

Become flags for Windows

Ansible 2.5 added the become_flags parameter to the runas become method.This parameter can be set using the become_flags task directive or set inAnsible’s configuration using ansible_become_flags. The two valid valuesthat are initially supported for this parameter are logon_type andlogon_flags.

Note

These flags should only be set when becoming a normal user account, not a local service account like LocalSystem.

The key logon_type sets the type of logon operation to perform. The valuecan be set to one of the following:

  • interactive: The default logon type. The process will be run under acontext that is the same as when running a process locally. This bypasses allWinRM restrictions and is the recommended method to use.
  • batch: Runs the process under a batch context that is similar to ascheduled task with a password set. This should bypass most WinRMrestrictions and is useful if the become_user is not allowed to log oninteractively.
  • new_credentials: Runs under the same credentials as the calling user, butoutbound connections are run under the context of the become_user andbecome_password, similar to runas.exe /netonly. The logon_flagsflag should also be set to netcredentials_only. Use this flag ifthe process needs to access a network resource (like an SMB share) using adifferent set of credentials.
  • network: Runs the process under a network context without any cachedcredentials. This results in the same type of logon session as running anormal WinRM process without credential delegation, and operates under the samerestrictions.
  • network_cleartext: Like the network logon type, but instead cachesthe credentials so it can access network resources. This is the same type oflogon session as running a normal WinRM process with credential delegation.

For more information, seedwLogonType.

The logon_flags key specifies how Windows will log the user on when creatingthe new process. The value can be set to none or multiple of the following:

  • with_profile: The default logon flag set. The process will load theuser’s profile in the HKEY_USERS registry key to HKEY_CURRENT_USER.
  • netcredentials_only: The process will use the same token as the callerbut will use the become_user and become_password when accessing a remoteresource. This is useful in inter-domain scenarios where there is no trustrelationship, and should be used with the new_credentials logon_type.

By default logon_flags=with_profile is set, if the profile should not beloaded set logon_flags= or if the profile should be loaded withnetcredentials_only, set logon_flags=with_profile,netcredentials_only.

For more information, see dwLogonFlags.

Here are some examples of how to use become_flags with Windows tasks:

  1. - name: copy a file from a fileshare with custom credentials
  2. win_copy:
  3. src: \\server\share\data\file.txt
  4. dest: C:\temp\file.txt
  5. remote_src: yes
  6. vars:
  7. ansible_become: yes
  8. ansible_become_method: runas
  9. ansible_become_user: DOMAIN\user
  10. ansible_become_password: Password01
  11. ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only
  12.  
  13. - name: run a command under a batch logon
  14. win_whoami:
  15. become: yes
  16. become_flags: logon_type=batch
  17.  
  18. - name: run a command and not load the user profile
  19. win_whomai:
  20. become: yes
  21. become_flags: logon_flags=

Limitations of become on Windows

  • Running a task with async and become on Windows Server 2008, 2008 R2and Windows 7 only works when using Ansible 2.7 or newer.
  • By default, the become user logs on with an interactive session, so it musthave the right to do so on the Windows host. If it does not inherit theSeAllowLogOnLocally privilege or inherits the SeDenyLogOnLocallyprivilege, the become process will fail. Either add the privilege or set thelogon_type flag to change the logon type used.
  • Prior to Ansible version 2.3, become only worked whenansible_winrm_transport was either basic or credssp. Thisrestriction has been lifted since the 2.4 release of Ansible for all hostsexcept Windows Server 2008 (non R2 version).
  • The Secondary Logon service seclogon must be running to use ansible_become_method: runas

See also