← Back to Blog

Defending Against Subdomain Takeover Attacks

Understand subdomain takeover vulnerabilities, how attackers exploit them, and implement robust defenses to protect your organization's digital assets.

Understanding Subdomain Takeover Vulnerabilities

Subdomain takeover is a critical security vulnerability that occurs when an attacker gains control over a subdomain of a target domain. This happens when a subdomain points to a service (like a cloud service, CDN, or hosting platform) that the organization no longer controls, but the DNS record still exists. Attackers can then claim the abandoned service and serve malicious content on what appears to be a legitimate subdomain.

The impact of successful subdomain takeovers can be severe, ranging from phishing campaigns and malware distribution to session hijacking and reputation damage. For security teams, understanding and preventing these vulnerabilities is crucial for maintaining organizational security posture.

How Subdomain Takeovers Work

The attack follows a predictable pattern that security teams need to understand to defend effectively:

The Vulnerability Chain

  1. Service Creation: Organization creates a cloud service (S3 bucket, GitHub pages, etc.)
  2. DNS Configuration: DNS record points subdomain to the service
  3. Service Deletion: Service is deleted but DNS record remains
  4. Dangling DNS: Subdomain points to non-existent or unclaimed service
  5. Attacker Claims Service: Attacker creates service with same name
  6. Malicious Control: Attacker now controls content on legitimate subdomain

Common Vulnerable Services

Many cloud services are susceptible to takeover attacks:

Cloud Storage Services

  • Amazon S3: bucket-name.s3.amazonaws.com
  • Google Cloud Storage: bucket-name.storage.googleapis.com
  • Azure Blob Storage: storage-account.blob.core.windows.net
  • DigitalOcean Spaces: bucket-name.region.digitaloceanspaces.com

Content Delivery Networks

  • CloudFront: distribution-id.cloudfront.net
  • Fastly: domain.global.ssl.fastly.net
  • KeyCDN: zone-name.kxcdn.com
  • MaxCDN: zone-name.netdna-cdn.com

Platform-as-a-Service

  • Heroku: app-name.herokuapp.com
  • GitHub Pages: username.github.io
  • GitLab Pages: username.gitlab.io
  • Vercel: app-name.vercel.app
  • Netlify: app-name.netlify.app

Attack Vectors and Real-World Impact

Phishing and Social Engineering

Attackers commonly use subdomain takeovers for sophisticated phishing attacks:

  • Credential harvesting: Fake login pages on legitimate subdomains
  • Brand impersonation: Official-looking communication channels
  • Supply chain attacks: Compromising developer tools and resources
  • Session hijacking: Stealing authentication cookies and tokens

Malware Distribution

Legitimate subdomains provide trusted distribution channels:

  • Bypassing security filters and blacklists
  • Exploiting user trust in the parent domain
  • Distributing malware through "official" channels
  • Hosting command and control infrastructure

SEO Manipulation and Defacement

  • Injecting malicious content for SEO spam
  • Defacing subdomains to damage reputation
  • Redirecting traffic to competitor sites
  • Manipulating search engine rankings

Detection and Assessment Strategies

Automated Detection Tools

Several tools can help identify potential subdomain takeover vulnerabilities:

Subjack

# Install and use Subjack
go get github.com/haccer/subjack
subjack -w subdomains.txt -t 100 -timeout 30 -o takeover_results.txt -ssl

# Custom fingerprint file
subjack -w subdomains.txt -c custom_fingerprints.json

SubOver

# Python-based subdomain takeover tool
pip install subover
subover -l subdomains.txt -t 50

# With verbose output
subover -l subdomains.txt -v

Can I Take Over XYZ

This repository maintains up-to-date information about takeover possibilities:

# Clone the repository for reference
git clone https://github.com/EdOverflow/can-i-take-over-xyz.git

# Regular updates on service vulnerabilities
# Check for new services and attack vectors

Manual Detection Techniques

DNS Analysis

# Check for CNAME records pointing to external services
dig CNAME subdomain.example.com

# Look for NXDOMAIN responses
dig subdomain.example.com

# Check for specific error patterns
curl -I https://subdomain.example.com

HTTP Response Analysis

# Look for specific error messages
curl -s https://subdomain.example.com | grep -i "NoSuchBucket\|404\|not found"

# Check HTTP status codes
curl -o /dev/null -s -w "%{http_code}\n" https://subdomain.example.com

# Analyze response headers
curl -I https://subdomain.example.com | grep -i "server\|x-"

Comprehensive Assessment Script

#!/bin/bash
# Subdomain takeover assessment script

SUBDOMAIN_FILE=$1
OUTPUT_FILE="takeover_assessment.txt"

echo "Subdomain Takeover Assessment - $(date)" > $OUTPUT_FILE
echo "=============================================" >> $OUTPUT_FILE

while read subdomain; do
    echo "Testing: $subdomain"

    # DNS resolution test
    DNS_RESULT=$(dig +short $subdomain)
    if [ -z "$DNS_RESULT" ]; then
        echo "POTENTIAL: $subdomain - No DNS resolution" >> $OUTPUT_FILE
        continue
    fi

    # CNAME analysis
    CNAME=$(dig +short CNAME $subdomain)
    if [ ! -z "$CNAME" ]; then
        # Check for vulnerable services
        if echo "$CNAME" | grep -E "(amazonaws|github\.io|herokuapp|netlify)"; then
            echo "INVESTIGATE: $subdomain -> $CNAME" >> $OUTPUT_FILE

            # HTTP response check
            HTTP_CODE=$(curl -o /dev/null -s -w "%{http_code}" --max-time 10 "https://$subdomain")
            if [ "$HTTP_CODE" = "404" ] || [ "$HTTP_CODE" = "000" ]; then
                echo "HIGH RISK: $subdomain (HTTP $HTTP_CODE)" >> $OUTPUT_FILE
            fi
        fi
    fi

done < $SUBDOMAIN_FILE

echo "Assessment complete. Check $OUTPUT_FILE for results."

Prevention and Mitigation Strategies

DNS Management Best Practices

Inventory and Documentation

  • Maintain DNS inventory: Document all subdomains and their purposes
  • Service mapping: Track which services each subdomain points to
  • Ownership tracking: Know who manages each subdomain and service
  • Lifecycle management: Plan for service creation and deletion

Change Management Process

# DNS Change Checklist
1. Document the change request
2. Verify service availability before DNS update
3. Test DNS resolution after changes
4. Monitor for proper functionality
5. Update inventory documentation
6. Plan cleanup procedures

Automated Prevention Systems

DNS Monitoring Script

#!/bin/bash
# Continuous DNS monitoring for takeover prevention

DOMAINS_FILE="monitored_domains.txt"
ALERT_EMAIL="security@company.com"
SLACK_WEBHOOK="https://hooks.slack.com/services/..."

check_subdomain() {
    local subdomain=$1

    # Check DNS resolution
    DNS_RESULT=$(dig +short $subdomain)
    if [ -z "$DNS_RESULT" ]; then
        alert "DNS_FAILURE" "$subdomain has no DNS resolution"
        return
    fi

    # Check HTTP accessibility
    HTTP_CODE=$(curl -o /dev/null -s -w "%{http_code}" --max-time 10 "https://$subdomain")
    if [ "$HTTP_CODE" = "404" ] || [ "$HTTP_CODE" = "000" ]; then
        # Check for vulnerable CNAME patterns
        CNAME=$(dig +short CNAME $subdomain)
        if echo "$CNAME" | grep -E "(amazonaws|github\.io|herokuapp|netlify)"; then
            alert "TAKEOVER_RISK" "$subdomain may be vulnerable to takeover (CNAME: $CNAME, HTTP: $HTTP_CODE)"
        fi
    fi
}

alert() {
    local type=$1
    local message=$2

    # Email alert
    echo "$message" | mail -s "[$type] Subdomain Alert" $ALERT_EMAIL

    # Slack notification
    curl -X POST -H 'Content-type: application/json' \
        --data "{\"text\":\"🚨 $type: $message\"}" \
        $SLACK_WEBHOOK

    # Log to syslog
    logger "SubdomainMonitor [$type]: $message"
}

# Main monitoring loop
while read domain; do
    check_subdomain "$domain"
done < $DOMAINS_FILE

Infrastructure as Code Integration

Integrate subdomain management into your IaC workflows:

# Terraform example for S3 bucket with DNS
resource "aws_s3_bucket" "website" {
  bucket = "my-website-bucket"

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_route53_record" "website" {
  zone_id = var.zone_id
  name    = "assets.example.com"
  type    = "CNAME"
  ttl     = 300
  records = [aws_s3_bucket.website.bucket_domain_name]

  depends_on = [aws_s3_bucket.website]
}

# Cleanup automation
resource "null_resource" "dns_cleanup" {
  triggers = {
    bucket_id = aws_s3_bucket.website.id
  }

  provisioner "local-exec" {
    when    = destroy
    command = "echo 'Remember to clean up DNS record for ${aws_s3_bucket.website.bucket}'"
  }
}

Service-Specific Prevention

AWS S3 Protection

# Reserve bucket names proactively
aws s3 mb s3://company-backup-prod
aws s3 mb s3://company-logs-staging
aws s3 mb s3://company-assets-dev

# Set up bucket policies to prevent unauthorized access
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyAllExceptTrustedSources",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::company-bucket",
                "arn:aws:s3:::company-bucket/*"
            ],
            "Condition": {
                "StringNotEquals": {
                    "aws:PrincipalAccount": "123456789012"
                }
            }
        }
    ]
}

GitHub Pages Protection

# Reserve organization and user names
# Create placeholder repositories
# Monitor for unauthorized repositories

# GitHub API monitoring script
curl -H "Authorization: token $GITHUB_TOKEN" \
     "https://api.github.com/users/company-name/repos" | \
     jq '.[] | select(.name | contains("github.io"))'

Incident Response and Remediation

Immediate Response Steps

When a subdomain takeover is discovered:

  1. Assess Impact: Determine scope and potential damage
  2. Document Evidence: Screenshot the malicious content
  3. Remove DNS Record: Immediately remove the vulnerable DNS entry
  4. Notify Stakeholders: Inform security team and management
  5. Monitor for Abuse: Watch for ongoing malicious activity
  6. Conduct Investigation: Determine how the vulnerability occurred

Incident Response Playbook

# Subdomain Takeover Incident Response

## Phase 1: Detection and Initial Assessment
- [ ] Confirm the takeover (verify malicious content)
- [ ] Document the affected subdomain and service
- [ ] Screenshot evidence of malicious content
- [ ] Check for additional compromised subdomains
- [ ] Assess potential data exposure

## Phase 2: Containment
- [ ] Remove or modify DNS record immediately
- [ ] Block traffic to affected subdomain if necessary
- [ ] Notify CDN/cloud provider if applicable
- [ ] Update WAF rules if relevant

## Phase 3: Investigation
- [ ] Review DNS change logs
- [ ] Identify when service was deleted
- [ ] Determine who had access to the service
- [ ] Check for insider threat indicators
- [ ] Review monitoring logs for missed alerts

## Phase 4: Recovery
- [ ] Recreate legitimate service if needed
- [ ] Update DNS with correct configuration
- [ ] Test functionality of restored service
- [ ] Monitor for continued malicious activity

## Phase 5: Lessons Learned
- [ ] Document root cause analysis
- [ ] Update prevention procedures
- [ ] Improve monitoring capabilities
- [ ] Conduct team training if needed

Legal and Regulatory Considerations

  • Data breach notification: Assess if personal data was exposed
  • Regulatory compliance: Consider GDPR, CCPA, and industry requirements
  • Customer notification: Inform affected users if necessary
  • Law enforcement: Consider reporting if criminal activity occurred

Advanced Monitoring and Defense

Certificate Transparency Monitoring

Monitor CT logs for unauthorized certificates on your subdomains:

#!/usr/bin/env python3
# Certificate Transparency monitoring for subdomain takeovers

import requests
import json
import time
import smtplib
from email.mime.text import MIMEText

def check_ct_logs(domain):
    """Check CT logs for new certificates on subdomains"""
    url = f"https://crt.sh/?q=%25.{domain}&output=json"

    try:
        response = requests.get(url, timeout=30)
        certificates = response.json()

        # Get certificates from last 24 hours
        recent_certs = []
        current_time = time.time()

        for cert in certificates:
            cert_time = cert.get('not_before', '')
            # Parse certificate time and check if recent
            # Add logic to filter recent certificates

        return recent_certs

    except Exception as e:
        print(f"Error checking CT logs: {e}")
        return []

def verify_subdomain_ownership(subdomain):
    """Verify that we still control a subdomain"""
    try:
        # Check for expected content or headers
        response = requests.get(f"https://{subdomain}", timeout=10)

        # Look for organization-specific indicators
        if "Our Company" in response.text:
            return True
        if "X-Our-Header" in response.headers:
            return True

        return False

    except:
        return False

def send_alert(subdomain, details):
    """Send alert for potential takeover"""
    msg = MIMEText(f"Potential subdomain takeover detected: {subdomain}\n\nDetails: {details}")
    msg['Subject'] = f"SECURITY ALERT: Subdomain Takeover - {subdomain}"
    msg['From'] = "security-monitoring@company.com"
    msg['To'] = "security-team@company.com"

    # Send email (configure SMTP settings)
    # smtp_server.send_message(msg)

# Main monitoring loop
monitored_domains = ["company.com", "subsidiary.com"]

for domain in monitored_domains:
    recent_certs = check_ct_logs(domain)

    for cert in recent_certs:
        subdomain = cert['name_value']
        if not verify_subdomain_ownership(subdomain):
            send_alert(subdomain, cert)

Continuous Security Testing

Implement regular security testing for subdomain takeovers:

# Weekly subdomain takeover testing
#!/bin/bash

DOMAINS_FILE="production_domains.txt"
REPORT_FILE="weekly_takeover_report_$(date +%Y%m%d).txt"

echo "Weekly Subdomain Takeover Assessment" > $REPORT_FILE
echo "Generated: $(date)" >> $REPORT_FILE
echo "========================================" >> $REPORT_FILE

# Run automated tools
subjack -w $DOMAINS_FILE -t 50 -ssl -o subjack_results.txt
subover -l $DOMAINS_FILE -t 25 >> subover_results.txt

# Compile results
echo "Subjack Results:" >> $REPORT_FILE
cat subjack_results.txt >> $REPORT_FILE

echo -e "\n\nSubOver Results:" >> $REPORT_FILE
cat subover_results.txt >> $REPORT_FILE

# Send report to security team
mail -s "Weekly Subdomain Takeover Report" security-team@company.com < $REPORT_FILE

Organizational Security Measures

Team Training and Awareness

  • Developer education: Train development teams on secure DNS practices
  • DevOps awareness: Ensure operations teams understand takeover risks
  • Security team training: Keep security teams updated on latest techniques
  • Regular drills: Practice incident response procedures

Policy and Procedure Development

DNS Management Policy

# Example DNS Management Policy Points

1. All DNS changes must be approved by security team
2. DNS records must be documented in central inventory
3. Service decommissioning must include DNS cleanup
4. External services require security assessment
5. Monitoring must be configured for all subdomains
6. Regular audits of DNS records are mandatory
7. Incident response procedures must be followed

Cloud Service Guidelines

  • Require approval for new cloud services
  • Mandate naming conventions for resources
  • Implement resource tagging for ownership tracking
  • Require cleanup procedures before service deletion

Vendor and Third-Party Management

  • Due diligence: Assess third-party security practices
  • Contract terms: Include security requirements in agreements
  • Regular reviews: Audit third-party DNS configurations
  • Termination procedures: Ensure proper cleanup when relationships end

Future-Proofing Your Defense

Emerging Threats

  • Cloud service proliferation: New services create new attack vectors
  • Automation complexity: Infrastructure as Code can introduce gaps
  • Supply chain attacks: Third-party compromises affecting DNS
  • AI-powered attacks: Automated discovery and exploitation

Technology Evolution

  • DNS security enhancements: DNSSEC, DNS over HTTPS/TLS
  • Cloud security improvements: Better service controls and monitoring
  • Automated defense systems: AI-powered threat detection
  • Zero-trust architectures: Reduced reliance on DNS-based security

Conclusion

Defending against subdomain takeover attacks requires a comprehensive approach combining technical controls, process improvements, and organizational awareness. By implementing proper DNS management practices, deploying automated monitoring systems, and maintaining robust incident response capabilities, organizations can significantly reduce their risk exposure.

The key to successful defense lies in treating subdomain management as a critical security function rather than just an operational task. This means involving security teams in DNS decisions, implementing proper change management processes, and continuously monitoring for vulnerabilities.

As cloud services continue to proliferate and infrastructure becomes more complex, the risk of subdomain takeovers will likely increase. Organizations that proactively implement these defensive measures will be better positioned to protect their digital assets and maintain customer trust. Remember that prevention is always more cost-effective than remediation – invest in proper defenses before vulnerabilities are exploited.