Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-SkillsFramework mappings
MITRE ATT&CK
When to Use
- When auditing web applications for references to expired or unclaimed external resources
- During supply chain security assessments of third-party script and resource dependencies
- When testing for subdomain takeover opportunities via dangling CNAME records
- During bug bounty hunting for broken link hijacking vulnerabilities
- When assessing the security of external resource dependencies in production applications
Prerequisites
- Web crawler or spider for discovering all external links (Burp Suite Spider, Scrapy)
- DNS lookup tools for checking CNAME records and domain availability
- Domain registrar access for claiming expired domains (as proof of concept)
- Understanding of CDN and cloud service provisioning (S3, Azure Blob, GitHub Pages)
- blc (broken-link-checker) or similar tool for automated link validation
- Knowledge of services vulnerable to subdomain takeover (can-i-take-over-xyz)
Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.
Workflow
Step 1 — Crawl and Extract All External References
# Use broken-link-checker to find dead links
npx broken-link-checker http://target.com --recursive --ordered \
--exclude-internal --filter-level 3 -o broken_links.txt
# Extract all external links from page source
curl -s http://target.com | grep -oP 'https?://[^"'"'"'\s>]+' | sort -u > all_links.txt
# Extract JavaScript sources
curl -s http://target.com | grep -oP 'src="[^"]*"' | grep -v target.com > external_scripts.txt
# Extract CSS references
curl -s http://target.com | grep -oP 'href="[^"]*\.css"' | grep -v target.com > external_css.txt
# Use wayback machine for historical external references
curl -s "https://web.archive.org/web/timemap/link/http://target.com" | \
grep -oP 'https?://[^>]+' | sort -u > historical_links.txt
# Spider with Burp Suite
# Configure Spider scope to include target.com
# Review Site Map > Filter by "External" to list all external referencesStep 2 — Identify Dead or Claimable Resources
# Check if external domains are registered
for domain in $(cat external_domains.txt); do
whois $domain 2>/dev/null | grep -qi "no match\|not found\|available" && \
echo "[CLAIMABLE] $domain"
done
# Check HTTP status of external links
while read url; do
status=$(curl -o /dev/null -s -w "%{http_code}" "$url" --max-time 5)
if [ "$status" = "000" ] || [ "$status" = "404" ]; then
echo "[DEAD] $url (Status: $status)"
fi
done < all_links.txt
# Check for dangling CNAME records
for sub in $(cat subdomains.txt); do
cname=$(dig +short CNAME $sub)
if [ -n "$cname" ]; then
resolved=$(dig +short $cname)
if [ -z "$resolved" ]; then
echo "[DANGLING] $sub -> $cname (UNRESOLVED)"
fi
fi
done
# Check cloud resource availability
# AWS S3 bucket
aws s3 ls s3://target-assets 2>&1 | grep -q "NoSuchBucket" && echo "[CLAIMABLE] S3: target-assets"Step 3 — Check Service-Specific Takeover Possibilities
# Check GitHub Pages takeover
# If CNAME points to <user>.github.io and 404 is returned
curl -s https://subdomain.target.com | grep -q "There isn't a GitHub Pages site here"
# Check AWS S3 takeover
curl -s http://subdomain.target.com | grep -q "NoSuchBucket"
# Check Azure Blob Storage
curl -s http://subdomain.target.com | grep -q "The specified container does not exist"
# Check Heroku
curl -s http://subdomain.target.com | grep -q "No such app"
# Check Shopify
curl -s http://subdomain.target.com | grep -q "Sorry, this shop is currently unavailable"
# Use subjack for automated takeover detection
subjack -w subdomains.txt -c fingerprints.json -t 100 -o takeover_candidates.txt
# Use nuclei takeover templates
subfinder -d target.com -silent | nuclei -t http/takeovers/ -o takeovers.txtStep 4 — Verify External Script Hijacking
# Check if external JavaScript domains are available for registration
curl -s http://target.com | grep -oP 'src="https?://([^/"]+)' | \
cut -d'/' -f3 | sort -u | while read domain; do
whois "$domain" 2>/dev/null | grep -qi "no match\|available" && \
echo "[HIJACKABLE SCRIPT] $domain loaded by target.com"
done
# Check npm/CDN package references
curl -s http://target.com | grep -oP 'unpkg\.com/[^@/]+' | sort -u
curl -s http://target.com | grep -oP 'cdn\.jsdelivr\.net/npm/[^@/]+' | sort -u
# Verify if referenced packages still exist
# Check npm registry for deprecated or removed packagesStep 5 — Exploit the Broken Link (Authorized Testing Only)
# For expired domain: Register the domain
# For S3 bucket: Create bucket with same name in same region
aws s3 mb s3://target-expired-bucket --region us-east-1
# For GitHub Pages: Create repository with matching name
# Create <org>.github.io repository with proof-of-concept content
# For unclaimed social media: Claim the handle
# Document the takeover with benign proof-of-concept content
# Serve proof-of-concept content
echo "<html><body><h1>Broken Link Hijacking PoC - [Your Name]</h1></body></html>" > index.html
# Upload to claimed resourceStep 6 — Assess Impact and Report
# Determine impact based on resource type:
# - External JavaScript: Full XSS on all pages loading the script
# - External CSS: UI defacement, data exfiltration via CSS injection
# - External image/resource: Phishing, tracking
# - CNAME subdomain: Cookie theft, phishing, OAuth bypass
# Check if hijacked resource serves cookies for parent domain
# Check if hijacked subdomain is in OAuth redirect whitelist
# Verify if hijacked domain receives sensitive Referer headersKey Concepts
| Concept | Description |
|---|---|
| Broken Link Hijacking | Claiming control of external resources referenced by target website |
| Dangling CNAME | DNS CNAME record pointing to unclaimed or decommissioned service |
| Subdomain Takeover | Claiming a subdomain by provisioning the service its CNAME points to |
| External Script Hijacking | Registering expired domains that serve JavaScript loaded by target |
| Supply Chain Attack | Compromising external dependencies to inject malicious content |
| Dead Link | URL reference returning 404 or DNS resolution failure |
| Resource Fingerprinting | Identifying specific cloud services from error messages and headers |
Tools & Systems
| Tool | Purpose |
|---|---|
| broken-link-checker | Automated broken link discovery via web crawling |
| subjack | Subdomain takeover detection tool |
| nuclei | Template-based takeover detection scanner |
| can-i-take-over-xyz | Community database of services vulnerable to takeover |
| BadDNS | DNS auditing tool for detecting domain/subdomain takeovers |
| Wayback Machine | Historical URL analysis for discovering past external references |
Common Scenarios
- JavaScript Supply Chain — Register expired domain that serves JavaScript loaded by target; inject malicious code affecting all visitors
- S3 Bucket Takeover — Claim deleted AWS S3 bucket referenced by target; serve malicious content or steal uploaded data
- GitHub Pages Hijack — Create GitHub Pages repository matching dangling CNAME to serve phishing pages on target subdomain
- Social Media Impersonation — Claim unclaimed social media handles linked from target website for brand impersonation
- CDN Package Hijack — Claim deprecated npm packages referenced via CDN URLs to inject malicious JavaScript
Output Format
## Broken Link Hijacking Report
- **Target**: http://target.com
- **Total External Links**: 145
- **Dead Links**: 12
- **Hijackable Resources**: 3
### Findings
| # | Resource | Type | Status | Impact |
|---|----------|------|--------|--------|
| 1 | analytics.expired-domain.com | JavaScript | Domain available | Full XSS |
| 2 | assets.target.com -> S3 bucket | Static assets | Bucket deleted | Content injection |
| 3 | blog.target.com -> GitHub Pages | Subdomain | No GitHub repo | Subdomain takeover |
### Remediation
- Remove references to decommissioned external resources
- Delete dangling CNAME records for unused subdomains
- Implement Subresource Integrity (SRI) for external scripts
- Regularly audit external dependencies for availability
- Use Content Security Policy to restrict allowed script sourcesSource materials
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.2 KB
API Reference: Broken Link Hijacking
Concept
Broken Link Hijacking (BLH) occurs when a website links to external resources that no longer exist. An attacker can register the expired resource (domain, GitHub repo, npm package) to serve malicious content via the trusted site.
Hijackable Platforms
| Platform | Hijack Vector |
|---|---|
| GitHub | Register abandoned username/repo |
| npm | Publish unclaimed package name |
| PyPI | Register unclaimed package |
| Twitter/X | Claim abandoned handle |
| BitBucket | Register abandoned team/repo |
| Custom domain | Register expired domain |
Python requests — Link Checking
HEAD Request
import requests
resp = requests.head(url, timeout=10, allow_redirects=True, verify=False)
# 404 = broken link, potential hijackConnection Error = Domain Takeover
try:
requests.head(url, timeout=5)
except requests.ConnectionError:
print("Domain may be unregistered - takeover possible")HTML Link Extraction
Regex Patterns
import re
# href links
re.finditer(r'href=["\']([^"\']+)', html)
# src links
re.finditer(r'src=["\']([^"\']+)', html)Domain Availability Check
WHOIS Lookup
whois expired-domain.com
# "No match for" = available for registrationDNS Check
dig expired-domain.com +short
# Empty = no DNS records (likely available)GitHub API — Check Username Availability
Check user exists
GET https://api.github.com/users/username- 200 = exists
- 404 = available for registration
Check repo exists
GET https://api.github.com/repos/owner/reponpm Registry — Check Package
GET https://registry.npmjs.org/package-name- 200 = exists
- 404 = available for registration
Subdomain Takeover Indicators
CNAME to Unclaimed Service
dig CNAME old-service.example.com
# old-service.example.com. CNAME unregistered.herokuapp.com.Common Vulnerable Services
| Service | Indicator |
|---|---|
| GitHub Pages | 404 "There isn't a GitHub Pages site here" |
| Heroku | "No such app" |
| AWS S3 | "NoSuchBucket" |
| Azure | "404 Web Site not found" |
| Shopify | "Sorry, this shop is currently unavailable" |
Scripts 1
agent.py4.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Agent for detecting broken link hijacking vulnerabilities on websites."""
import argparse
import json
import re
from datetime import datetime, timezone
from urllib.parse import urlparse, urljoin
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
HIJACKABLE_PATTERNS = {
"github": r"github\.com/[\w-]+(?!/[\w-]+)",
"npm": r"npmjs\.com/package/[\w-]+",
"twitter": r"twitter\.com/[\w]+",
"bitbucket": r"bitbucket\.org/[\w-]+",
"gitlab": r"gitlab\.com/[\w-]+",
"pypi": r"pypi\.org/project/[\w-]+",
}
def extract_links(html, base_url):
"""Extract all links from HTML content."""
links = set()
for match in re.finditer(r'href=["\']([^"\']+)', html):
link = match.group(1)
if link.startswith(("http://", "https://")):
links.add(link)
elif link.startswith("/"):
links.add(urljoin(base_url, link))
for match in re.finditer(r'src=["\']([^"\']+)', html):
link = match.group(1)
if link.startswith(("http://", "https://")):
links.add(link)
return links
def check_link_status(url):
"""Check if a URL is reachable and categorize its status."""
if not HAS_REQUESTS:
return {"url": url, "status": "unknown", "note": "requests library not available"}
try:
resp = requests.head(url, timeout=10, allow_redirects=True, verify=False)
return {
"url": url,
"status_code": resp.status_code,
"final_url": resp.url,
"broken": resp.status_code == 404,
}
except requests.ConnectionError:
return {"url": url, "status_code": None, "broken": True, "error": "connection_failed"}
except requests.Timeout:
return {"url": url, "status_code": None, "broken": False, "error": "timeout"}
except requests.RequestException as e:
return {"url": url, "status_code": None, "broken": False, "error": str(e)[:100]}
def check_hijackable(link_status):
"""Determine if a broken link is hijackable."""
url = link_status.get("url", "")
if not link_status.get("broken"):
return None
parsed = urlparse(url)
domain = parsed.netloc.lower()
for platform, pattern in HIJACKABLE_PATTERNS.items():
if re.search(pattern, url):
return {
"url": url,
"platform": platform,
"domain": domain,
"hijack_type": f"Register {platform} account/resource",
"severity": "HIGH",
}
if link_status.get("error") == "connection_failed":
return {
"url": url,
"domain": domain,
"hijack_type": "Domain takeover (unregistered domain)",
"severity": "CRITICAL",
}
return None
def scan_website(target_url):
"""Scan a website for broken link hijacking opportunities."""
if not HAS_REQUESTS:
return []
findings = []
try:
resp = requests.get(target_url, timeout=15, verify=False)
links = extract_links(resp.text, target_url)
except requests.RequestException:
return findings
external_links = [l for l in links if urlparse(l).netloc != urlparse(target_url).netloc]
print(f"[*] Found {len(external_links)} external links")
for link in external_links:
status = check_link_status(link)
hijack = check_hijackable(status)
if hijack:
findings.append(hijack)
return findings
def main():
parser = argparse.ArgumentParser(
description="Detect broken link hijacking vulnerabilities"
)
parser.add_argument("--url", required=True, help="Target website URL")
parser.add_argument("--output", "-o", help="Output JSON report")
parser.add_argument("--verbose", "-v", action="store_true")
args = parser.parse_args()
print("[*] Broken Link Hijacking Detection Agent")
findings = scan_website(args.url)
report = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"target": args.url,
"hijackable_links": findings,
"count": len(findings),
"risk_level": "CRITICAL" if any(f["severity"] == "CRITICAL" for f in findings) else "HIGH" if findings else "LOW",
}
print(f"[*] Hijackable links found: {len(findings)}")
if args.verbose:
for f in findings:
print(f" [{f['severity']}] {f['url']} - {f['hijack_type']}")
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
Keep exploring