HIGH dns rebindingaws

Dns Rebinding on Aws

How Dns Rebinding Manifests in Aws

Dns rebinding attacks exploit the trust relationship between AWS services and their internal endpoints. When an attacker controls DNS resolution, they can manipulate time-to-live (TTL) values to make a domain resolve to different IP addresses at different times. This creates a window where an application might trust a DNS name that resolves to an internal AWS IP address, bypassing network security controls.

In AWS environments, the most common attack pattern involves targeting metadata services. EC2 instances expose the instance metadata service at http://169.254.169.254, which provides sensitive information including IAM role credentials. An attacker can use DNS rebinding to trick a client into making requests to this internal endpoint.

Consider this vulnerable Node.js code running on an EC2 instance:

const axios = require('axios');

async function fetchUserData() {
  const response = await axios.get('http://example.com/api/user');
  return response.data;
}

// Vulnerable: attacker controls DNS, could rebind to metadata service
fetchUserData().then(data => {
  console.log(data);
});

The vulnerability occurs because the application makes HTTP requests to user-controlled domains without validating the resolved IP addresses. An attacker can set up DNS records with low TTL values, causing the domain to resolve to 169.254.169.254 during the request window.

Another AWS-specific manifestation involves Lambda functions that make outbound requests to user-provided URLs. Since Lambda functions run in a VPC, they might have access to internal AWS services like DynamoDB, S3, or RDS. A DNS rebinding attack could potentially access these services if proper validation isn't in place.

API Gateway endpoints are also vulnerable when they proxy requests to internal services. If an API Gateway endpoint accepts user-controlled URLs without validation, an attacker could potentially access internal services through DNS rebinding.

AWS-Specific Detection

Detecting DNS rebinding in AWS environments requires examining both network configurations and application code. AWS provides several native tools for this purpose.

First, use VPC Flow Logs to monitor unusual traffic patterns. Look for requests to internal IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) from external sources. The CloudWatch Logs Insights query below identifies suspicious traffic:

filter destinationAddress like /(10|172|192)// 
  and sourceAddress not like /(10|172|192)//
  and action = 'ACCEPT'
| stats count() by destinationAddress, sourceAddress

Network ACLs and Security Groups should explicitly deny outbound traffic to internal IP ranges unless absolutely necessary. Review these configurations to ensure they don't contain overly permissive rules.

For application-level detection, middleBrick's AWS-specific scanning identifies DNS rebinding vulnerabilities by testing how your API handles requests to domains that resolve to internal AWS IP addresses. The scanner tests 12 security categories including authentication bypasses and data exposure scenarios specific to AWS environments.

middleBrick's CLI tool can be integrated into your AWS CI/CD pipeline:

npm install -g middlebrick
middlebrick scan https://api.yourdomain.com --output json --severity high

The scanner specifically tests for AWS metadata service access attempts and validates that your application properly handles internal IP addresses. It also checks for vulnerable patterns in your OpenAPI specifications that might expose internal services.

For Lambda functions, use AWS X-Ray to trace outbound requests and identify any that resolve to internal IP addresses. X-Ray traces can reveal if user-controlled URLs are being resolved to unexpected internal endpoints.

AWS-Specific Remediation

Remediating DNS rebinding in AWS requires a defense-in-depth approach combining network controls, application hardening, and AWS-native security features.

Network Layer Controls:

Configure VPC security groups to explicitly deny outbound traffic to internal IP ranges:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "ec2:RevokeSecurityGroupEgress",
      "Resource": "*",
      "Condition": {
        "IpAddress": {
          "aws:SourceIp": [
            "10.0.0.0/8",
            "172.16.0.0/12", 
            "192.168.0.0/16",
            "169.254.169.254/32"
          ]
        }
      }
    }
  ]
}

Application Layer Controls:

Implement IP address validation before making HTTP requests. Here's a Node.js example using the valid-url and ip-address libraries:

const validUrl = require('valid-url');
const IPAddress = require('ip-address');

function isInternalIp(ip) {
  const address = new IPAddress(ip);
  if (address.isValid()) {
    return address.isPrivate();
  }
  return false;
}

async function safeHttpRequest(url) {
  if (!validUrl.isWebUri(url)) {
    throw new Error('Invalid URL format');
  }

  // Resolve DNS and check IP addresses
  const dnsPromises = require('dns').promises;
  const addresses = await dnsPromises.resolve4(url, { ttl: true });
  
  for (const address of addresses) {
    if (isInternalIp(address)) {
      throw new Error('Internal IP address detected in DNS response');
    }
  }

  // Proceed with HTTP request
  const axios = require('axios');
  const response = await axios.get(url);
  return response.data;
}

// Usage
safeHttpRequest('http://example.com/api/user')
  .then(data => console.log(data))
  .catch(err => console.error(err.message));

AWS WAF Integration:

Configure AWS WAF rules to block requests containing internal IP addresses or suspicious patterns. Use AWS Firewall Manager to enforce consistent security policies across your AWS accounts.

{
  "Type": "AWS::WAFv2::WebACL",
  "Properties": {
    "Name": "DnsRebindingProtection",
    "Scope": "REGIONAL",
    "DefaultAction": { "Allow": {} },
    "Rules": [
      {
        "Name": "BlockInternalIps",
        "Action": { "Block": {} },
        "Priority": 1,
        "Statement": {
          "ByteMatchStatement": {
            "FieldToMatch": { "UriPath": {} },
            "PositionalConstraint": "CONTAINS",
            "SearchString": "169.254.169.254",
            "TextTransformations": [
              { "Priority": 0, "Type": "LOWERCASE" }
            ]
          }
        }
      }
    ],
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "DnsRebindingProtection"
    }
  }
}

Lambda Security Best Practices:

When using Lambda functions, configure environment variables to prevent network access to internal services unless explicitly needed. Use IAM roles with least privilege and avoid granting permissions to internal AWS services when possible.

API Gateway Protection:

Configure API Gateway to validate request parameters and reject URLs that might resolve to internal IP addresses. Use request validation and custom authorizers to implement additional security checks.

Frequently Asked Questions

How does DNS rebinding differ from other AWS network attacks?
DNS rebinding specifically exploits the time-based resolution of DNS names to access internal services, while other attacks like SSRF typically involve direct requests to internal endpoints. DNS rebinding is more subtle because it abuses the trust in DNS names rather than directly targeting internal IPs. The attack window is also limited by DNS TTL values, making it harder to detect through traditional network monitoring.
Can middleBrick detect DNS rebinding vulnerabilities in my AWS APIs?
Yes, middleBrick's black-box scanning specifically tests for DNS rebinding vulnerabilities by attempting to resolve user-controlled domains to internal AWS IP addresses during the scan. The scanner tests the unauthenticated attack surface and identifies if your API makes requests to domains without proper IP validation. middleBrick's AWS-specific checks include testing for metadata service access attempts and validating that your application properly handles internal IP addresses.