Understanding Privilege Escalation

Ansible can use existing privilege escalation systems to allow a user to execute tasks as another.

Become

Ansible allows you to ‘become’ another user, different from the user that logged into the machine (remote user). This is done using existing privilege escalation tools such as sudo, su, pfexec, doas, pbrun, dzdo, ksu, runas, machinectl and others.

Note

Prior to version 1.9, Ansible mostly allowed the use of sudo and a limited use of su to allow a login/remote user to become a different user and execute tasks and create resources with the second user’s permissions. As of Ansible version 1.9, become supersedes the old sudo/su, while still being backwards compatible. This new implementation also makes it easier to add other privilege escalation tools, including pbrun (Powerbroker), pfexec, dzdo (Centrify), and others.

Note

Become vars and directives are independent. For example, setting become_user does not set become.

Directives

These can be set from play to task level, but are overridden by connection variables as they can be host specific.

  • 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.
  • become_method
  • (at play or task level) overrides the default method set in ansible.cfg, set to sudo/su/pbrun/pfexec/doas/dzdo/ksu/runas/machinectl
  • 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 (this takes advantage of the fact that the default value of become_user is 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'

Connection variables

Each allows you to set an option per group and/or host, these are normally defined in inventory but can be used 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_pass
  • 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

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

For those from Pre 1.9 , sudo and su still work!

For those using old playbooks will not need to be changed, even though they are deprecated, sudo and su directives, variables and optionswill continue to work. It is recommended to move to become as they may be retired at one point.You cannot mix directives on the same object (become and sudo) though, Ansible will complain if you try to.

Become will default to using the old sudo/su configs and variables if they exist, but will override them if you specify any of the new ones.

Limitations

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

Becoming an Unprivileged User

Ansible 2.0.x and below has a limitation with regards to becoming anunprivileged user that can be a security risk if users are not aware of it.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 the module file is created with permissionsthat only allow reading by the user and root.

The problem occurs when the become_user is an unprivileged user. Ansible2.0.x and below make the module file world readable in this case, as the modulefile is written as the user that Ansible connects as, but the file needs tobe readable by the user Ansible is set to become.

Note

In Ansible 2.1, this window is further narrowed: If the connectionis made as a privileged user (root), then Ansible 2.1 and above will usechown to set the file’s owner to the unprivileged user being switched to.This means both the user making the connection and the user being switchedto via become must be unprivileged in order to trigger this problem.

If any of the parameters passed to the module are sensitive in nature, thenthose pieces of data are located in a world readable module file for theduration of the Ansible module execution. Once the module is done executing,Ansible will delete the temporary file. If you trust the client machines thenthere’s no problem here. If you do not trust the client machines then this isa potential danger.

Ways to resolve this include:

  • Use pipelining. When pipelining is enabled, Ansible doesn’t 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.
  • (Available in Ansible 2.1) 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.
  • Don’t perform an action on the remote machine by 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 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.

In addition to the additional means of doing this securely, Ansible 2.1 alsomakes it harder to unknowingly do this insecurely. Whereas in Ansible 2.0.xand below, Ansible will silently allow the insecure behaviour if it was unableto find another way to share the files with the unprivileged user, in Ansible2.1 and above Ansible defaults to issuing an error if it can’t do thissecurely. If you can’t make any of the changes above to resolve the problem,and you decide that the machine you’re running on is 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.

Connection Plugin Support

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).

Can’t limit escalation to certain commands

Privilege escalation permissions have to be general. 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.

Environment variables populated by pam_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 Networks

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: eos`, ios, and nxos. 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_pass 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 Using Vault in playbooks.

authorize and auth_pass

Ansible still supports enable mode with connection: local for legacy 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.

Note

Prior to Ansible 2.4, become would only work when ansible_winrm_transport wasset to either basic or credssp, but since Ansible 2.4 become now works onall transport types.

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.

Before Ansible 2.5, a token was only able to be elevated when UAC was disabledor the remote user had the SeTcbPrivilege assigned. This restriction hasbeen lifted in Ansible 2.5 and a user that is a member of theBUILTIN\Administrators group should have an elevated token during themodule execution.

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

  1. - win_whoami:
  2. become: yes

Under the GROUP INFORMATION section, the Mandatory Label entrydetermines whether the user has Administrative rights. Here are the labels thatcan be returned and what they mean:

  • 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 State==Disabled, the privileges have not been enabled but can beif required. In most scenarios these privileges are automatically enabled whenrequired.

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 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.

Accounts without a Password

Warning

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

Ansible can be used to become an account that does not have a password (like theGuest account). To become an account without a password, set up thevariables like normal but either do not define ansible_become_pass or setansible_become_pass: ''.

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_pass if thebecome_user has a password.

Become Flags

Ansible 2.5 adds 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: yex
  6. vars:
  7. ansible_become: yes
  8. ansible_become_method: runas
  9. ansible_become_user: DOMAIN\user
  10. ansible_become_pass: 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

Be aware of the following limitations with 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).

See also