PortGate

Resources · Security guides · Security guide

Block server-side requests to the cloud metadata address

A URL fetch feature can be pointed at 169.254.169.254 and read cloud credentials. Validate destinations after DNS resolution, require IMDSv2, and block the address for the app user.

Fix command

sudo iptables -A OUTPUT -d 169.254.169.254 -m owner --uid-owner www-data -j REJECT

Copied.

Any feature that fetches a URL a user supplies (link previews, webhooks, "import from URL", image proxies, PDF renderers) can be aimed at addresses inside your network. The most valuable target is the cloud metadata service at 169.254.169.254, which hands out the instance's temporary cloud credentials to anything on the machine that asks.

How the attack works

The app is asked to fetch http://169.254.169.254/latest/meta-data/iam/security-credentials/. On AWS with the old IMDSv1 enabled, that returns a role name, and a second request returns an access key, secret and token. With those, the attacker works against your AWS account directly. Other clouds have equivalents: GCP and Azure require a special header, which makes simple SSRF harder but not impossible.

Validate destinations after resolving them

Checking the URL string is not enough: http://metadata.example.attacker.com can resolve to 169.254.169.254, and redirects can change the destination after your check. Resolve the hostname, reject private, loopback, link-local and reserved addresses, then connect to the address you checked and follow redirects only by repeating the check. In PHP:

$ip = gethostbyname($host);
$public = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
if ($public === false) {
    throw new InvalidArgumentException('Destination is not a public address.');
}

Then pin the connection to $ip (for cURL, CURLOPT_RESOLVE) and turn off automatic redirects. Handle IPv6 the same way.

Require IMDSv2 on AWS

IMDSv2 needs a token from a PUT request first, which most SSRF bugs cannot send:

aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required --http-put-response-hop-limit 1

A hop limit of 1 also stops containers on the instance from reaching it through the host.

Block the address for the web user

On any VPS, the web server user never needs the metadata service. Reject it at the host firewall for that user:

sudo iptables -A OUTPUT -d 169.254.169.254 -m owner --uid-owner www-data -j REJECT

Use the user your PHP-FPM pools run as. Save the rule with your distribution's persistence method so it survives a reboot. Tools that legitimately need metadata (the cloud agent itself) run as other users and keep working.

Check

As the web user, the request should fail:

sudo -u www-data curl -s -m 3 http://169.254.169.254/ || echo blocked