subdomainchecker 0.2.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- subdomainchecker/__init__.py +12 -0
- subdomainchecker/__main__.py +218 -0
- subdomainchecker/checker.py +385 -0
- subdomainchecker/data/fingerprints.json +588 -0
- subdomainchecker/data.py +64 -0
- subdomainchecker/dns.py +385 -0
- subdomainchecker/verify.py +198 -0
- subdomainchecker-0.2.2.dist-info/METADATA +182 -0
- subdomainchecker-0.2.2.dist-info/RECORD +13 -0
- subdomainchecker-0.2.2.dist-info/WHEEL +5 -0
- subdomainchecker-0.2.2.dist-info/entry_points.txt +2 -0
- subdomainchecker-0.2.2.dist-info/licenses/LICENSE +23 -0
- subdomainchecker-0.2.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""subdomainchecker — subdomain takeover checker.
|
|
2
|
+
|
|
3
|
+
Finds subdomains whose CNAME points at a takeover-capable service
|
|
4
|
+
whose resource has been deleted (a "dangling" record), using the
|
|
5
|
+
published fingerprints from the can-i-take-over-xyz dataset.
|
|
6
|
+
|
|
7
|
+
Strictly read-only: DNS lookups plus at most one benign GET per
|
|
8
|
+
candidate subdomain. subdomainchecker never attempts to claim, register,
|
|
9
|
+
or provision any resource.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "0.2.2"
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Command line: ``subdomainchecker check <domain>``,
|
|
2
|
+
``subdomainchecker check --list subdomains.txt``, or
|
|
3
|
+
``subdomainchecker --verify prior-report.json``.
|
|
4
|
+
|
|
5
|
+
Exit codes, following the scanner-family convention
|
|
6
|
+
(0 clean · 1 findings · 2 cannot judge · 3 judged under
|
|
7
|
+
degraded evidence). For check: 0 = every subdomain judged OK;
|
|
8
|
+
1 = at least one VULNERABLE or POSSIBLE finding and every
|
|
9
|
+
subdomain was judged; 2 = usage or enumeration error, or no
|
|
10
|
+
findings but at least one subdomain UNCHECKED (it could not
|
|
11
|
+
be judged); 3 = findings were judged, but at least one
|
|
12
|
+
subdomain was UNCHECKED, so the judgement rests on degraded
|
|
13
|
+
evidence. For --verify: 0 = every prior finding verified
|
|
14
|
+
FIXED-*, 1 = at least one prior finding is not fixed (in
|
|
15
|
+
particular any STILL-VULNERABLE), 2 = usage error or
|
|
16
|
+
unreadable prior report.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import json
|
|
23
|
+
import sys
|
|
24
|
+
from datetime import datetime, timezone
|
|
25
|
+
|
|
26
|
+
from . import __version__
|
|
27
|
+
from .checker import (EnumerationError, fetch_crtsh, load_list,
|
|
28
|
+
run_checks, summarize)
|
|
29
|
+
from .verify import (ReportError, all_fixed, load_prior_report,
|
|
30
|
+
run_verify, summarize_delta)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
34
|
+
parser = argparse.ArgumentParser(
|
|
35
|
+
prog="subdomainchecker",
|
|
36
|
+
description="Subdomain takeover checker — dangling "
|
|
37
|
+
"CNAMEs pointing at unclaimed services, "
|
|
38
|
+
"confirmed with published fingerprints. "
|
|
39
|
+
"Read-only: it never claims anything.")
|
|
40
|
+
parser.add_argument("--version", action="version",
|
|
41
|
+
version=f"subdomainchecker {__version__}")
|
|
42
|
+
parser.add_argument("--verify", dest="verify_path",
|
|
43
|
+
metavar="FILE",
|
|
44
|
+
help="verify fixes against a prior JSON "
|
|
45
|
+
"report: re-check only its findings "
|
|
46
|
+
"and classify each FIXED-REMOVED / "
|
|
47
|
+
"FIXED-RECLAIMED / STILL-VULNERABLE "
|
|
48
|
+
"/ STILL-POSSIBLE / CHANGED")
|
|
49
|
+
parser.add_argument("--json", action="store_true",
|
|
50
|
+
help="with --verify: emit JSON instead "
|
|
51
|
+
"of text")
|
|
52
|
+
parser.add_argument("--delay", type=float, default=0.3,
|
|
53
|
+
help="with --verify: seconds between "
|
|
54
|
+
"candidates (default 0.3)")
|
|
55
|
+
parser.add_argument("--timeout", type=float, default=10.0,
|
|
56
|
+
help="with --verify: per-request timeout "
|
|
57
|
+
"in seconds (default 10)")
|
|
58
|
+
sub = parser.add_subparsers(dest="command")
|
|
59
|
+
check = sub.add_parser(
|
|
60
|
+
"check", help="check a domain's subdomains for dangling "
|
|
61
|
+
"CNAMEs")
|
|
62
|
+
check.add_argument("domain", nargs="?",
|
|
63
|
+
help="apex domain to enumerate via "
|
|
64
|
+
"certificate transparency (crt.sh)")
|
|
65
|
+
check.add_argument("--list", dest="list_path", metavar="FILE",
|
|
66
|
+
help="read subdomain names from FILE (one "
|
|
67
|
+
"per line) instead of enumerating — "
|
|
68
|
+
"the reliable path for serious audits")
|
|
69
|
+
check.add_argument("--json", action="store_true",
|
|
70
|
+
help="emit JSON instead of text")
|
|
71
|
+
check.add_argument("--delay", type=float, default=0.3,
|
|
72
|
+
help="seconds between candidates "
|
|
73
|
+
"(default 0.3)")
|
|
74
|
+
check.add_argument("--timeout", type=float, default=10.0,
|
|
75
|
+
help="per-request timeout in seconds "
|
|
76
|
+
"(default 10)")
|
|
77
|
+
return parser
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def render_text(target: str, results: list[dict]) -> str:
|
|
81
|
+
lines = [f"subdomainchecker check: {target} "
|
|
82
|
+
f"({len(results)} subdomains checked)", ""]
|
|
83
|
+
for result in results:
|
|
84
|
+
lines.append(f"{result['verdict']:<10} "
|
|
85
|
+
f"{result['subdomain']}")
|
|
86
|
+
if result["cname"]:
|
|
87
|
+
lines.append(f"{'':<10} CNAME -> {result['cname']}")
|
|
88
|
+
lines.append(f"{'':<10} {result['evidence']}")
|
|
89
|
+
if result["remediation"]:
|
|
90
|
+
lines.append(f"{'':<10} Fix: {result['remediation']}")
|
|
91
|
+
counts = summarize(results)
|
|
92
|
+
lines.append("")
|
|
93
|
+
summary = (f"Summary: {counts['VULNERABLE']} vulnerable, "
|
|
94
|
+
f"{counts['POSSIBLE']} possible, "
|
|
95
|
+
f"{counts['OK']} ok")
|
|
96
|
+
if counts["UNCHECKED"]:
|
|
97
|
+
summary += f", {counts['UNCHECKED']} unchecked"
|
|
98
|
+
lines.append(summary)
|
|
99
|
+
return "\n".join(lines)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def render_verify_text(prior_path: str, findings_count: int,
|
|
103
|
+
records: list[dict],
|
|
104
|
+
verified_at: str) -> str:
|
|
105
|
+
lines = [f"subdomainchecker verify: {prior_path} "
|
|
106
|
+
f"({findings_count} prior findings, verified "
|
|
107
|
+
f"{verified_at})", ""]
|
|
108
|
+
for record in records:
|
|
109
|
+
prior = record["prior"]
|
|
110
|
+
lines.append(f"{record['classification']:<16} "
|
|
111
|
+
f"{record['subdomain']}")
|
|
112
|
+
was = f"was {prior['verdict']}"
|
|
113
|
+
if prior["cname"]:
|
|
114
|
+
was += f" — CNAME -> {prior['cname']}"
|
|
115
|
+
lines.append(f"{'':<16} {was}")
|
|
116
|
+
lines.append(f"{'':<16} {record['evidence']}")
|
|
117
|
+
counts = summarize_delta(records)
|
|
118
|
+
lines.append("")
|
|
119
|
+
lines.append(
|
|
120
|
+
f"Summary: {counts['FIXED-REMOVED']} fixed-removed, "
|
|
121
|
+
f"{counts['FIXED-RECLAIMED']} fixed-reclaimed, "
|
|
122
|
+
f"{counts['STILL-VULNERABLE']} still-vulnerable, "
|
|
123
|
+
f"{counts['STILL-POSSIBLE']} still-possible, "
|
|
124
|
+
f"{counts['CHANGED']} changed — "
|
|
125
|
+
+ ("ALL FIXED" if all_fixed(records) else "NOT ALL FIXED"))
|
|
126
|
+
return "\n".join(lines)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main(argv: list[str] | None = None) -> int:
|
|
130
|
+
parser = build_parser()
|
|
131
|
+
args = parser.parse_args(argv)
|
|
132
|
+
if args.verify_path:
|
|
133
|
+
try:
|
|
134
|
+
report, findings = load_prior_report(args.verify_path)
|
|
135
|
+
except ReportError as exc:
|
|
136
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
137
|
+
return 2
|
|
138
|
+
records = run_verify(findings, delay=args.delay,
|
|
139
|
+
timeout=args.timeout)
|
|
140
|
+
verified_at = datetime.now(
|
|
141
|
+
timezone.utc).isoformat(timespec="seconds")
|
|
142
|
+
if args.json:
|
|
143
|
+
print(json.dumps({
|
|
144
|
+
"tool": "subdomainchecker",
|
|
145
|
+
"schema_version": 1,
|
|
146
|
+
"version": __version__,
|
|
147
|
+
"mode": "verify",
|
|
148
|
+
"prior_report": args.verify_path,
|
|
149
|
+
"prior_target": report.get("target"),
|
|
150
|
+
"prior_version": report.get("version"),
|
|
151
|
+
"verified_at": verified_at,
|
|
152
|
+
"prior_findings": len(findings),
|
|
153
|
+
"summary": summarize_delta(records),
|
|
154
|
+
"all_fixed": all_fixed(records),
|
|
155
|
+
"results": records,
|
|
156
|
+
}, indent=2))
|
|
157
|
+
else:
|
|
158
|
+
print(render_verify_text(args.verify_path,
|
|
159
|
+
len(findings), records,
|
|
160
|
+
verified_at))
|
|
161
|
+
return 0 if all_fixed(records) else 1
|
|
162
|
+
if args.command != "check":
|
|
163
|
+
parser.print_help()
|
|
164
|
+
return 2
|
|
165
|
+
if bool(args.domain) == bool(args.list_path):
|
|
166
|
+
print("error: give exactly one of <domain> or --list FILE",
|
|
167
|
+
file=sys.stderr)
|
|
168
|
+
return 2
|
|
169
|
+
|
|
170
|
+
if args.list_path:
|
|
171
|
+
try:
|
|
172
|
+
subdomains = load_list(args.list_path)
|
|
173
|
+
except OSError as exc:
|
|
174
|
+
print(f"error: cannot read list: {exc}",
|
|
175
|
+
file=sys.stderr)
|
|
176
|
+
return 2
|
|
177
|
+
target = f"list:{args.list_path}"
|
|
178
|
+
else:
|
|
179
|
+
domain = args.domain.strip().lower().rstrip(".")
|
|
180
|
+
try:
|
|
181
|
+
subdomains = fetch_crtsh(domain)
|
|
182
|
+
except EnumerationError as exc:
|
|
183
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
184
|
+
return 2
|
|
185
|
+
target = domain
|
|
186
|
+
|
|
187
|
+
results = run_checks(subdomains, delay=args.delay,
|
|
188
|
+
timeout=args.timeout)
|
|
189
|
+
if args.json:
|
|
190
|
+
print(json.dumps({
|
|
191
|
+
"tool": "subdomainchecker",
|
|
192
|
+
"schema_version": 1,
|
|
193
|
+
"version": __version__,
|
|
194
|
+
"target": target,
|
|
195
|
+
"checked": len(results),
|
|
196
|
+
"summary": summarize(results),
|
|
197
|
+
"results": results,
|
|
198
|
+
}, indent=2))
|
|
199
|
+
else:
|
|
200
|
+
print(render_text(target, results))
|
|
201
|
+
counts = summarize(results)
|
|
202
|
+
if counts["VULNERABLE"] or counts["POSSIBLE"]:
|
|
203
|
+
# Findings. If part of the run could not be judged, the
|
|
204
|
+
# findings stand but the evidence base is degraded.
|
|
205
|
+
return 3 if counts["UNCHECKED"] else 1
|
|
206
|
+
if counts["UNCHECKED"]:
|
|
207
|
+
# Nothing found — but not everything could be judged,
|
|
208
|
+
# so this is not a clean pass.
|
|
209
|
+
return 2
|
|
210
|
+
return 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def cli() -> None:
|
|
214
|
+
sys.exit(main())
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
if __name__ == "__main__":
|
|
218
|
+
cli()
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""Core checking logic: enumerate, resolve, confirm, verdict.
|
|
2
|
+
|
|
3
|
+
Evidence discipline (the product's whole point):
|
|
4
|
+
|
|
5
|
+
- A subdomain is only VULNERABLE when its CNAME points at a
|
|
6
|
+
takeover-capable service AND the resource is confirmed
|
|
7
|
+
unclaimed — by DNS (the target no longer resolves) or by the
|
|
8
|
+
service's own published "not found / not configured"
|
|
9
|
+
fingerprint in one benign GET.
|
|
10
|
+
- A dangling CNAME whose service is unknown, or whose
|
|
11
|
+
fingerprint could not be confirmed, is POSSIBLE — a prompt
|
|
12
|
+
for a human to review the record, not an accusation.
|
|
13
|
+
- A subdomain whose state could not be determined at all —
|
|
14
|
+
the CNAME lookup failed, or the target's resolution failed
|
|
15
|
+
and the service is unknown — is UNCHECKED. A failed lookup
|
|
16
|
+
is never reported as OK: absence of evidence is stated as
|
|
17
|
+
absence of evidence.
|
|
18
|
+
- Everything else is OK. Using a service is not a finding;
|
|
19
|
+
only an *unclaimed* service is.
|
|
20
|
+
|
|
21
|
+
subdomainchecker never attempts to claim, register, or provision the
|
|
22
|
+
resources it finds. It reports them so the owner can remove
|
|
23
|
+
the record or reclaim the resource first.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import http.client
|
|
29
|
+
import ipaddress
|
|
30
|
+
import json
|
|
31
|
+
import socket
|
|
32
|
+
import ssl
|
|
33
|
+
import time
|
|
34
|
+
import urllib.parse
|
|
35
|
+
import urllib.request
|
|
36
|
+
|
|
37
|
+
from . import __version__
|
|
38
|
+
from .data import (fingerprint_matches, load_dataset, match_service,
|
|
39
|
+
services_by_pattern)
|
|
40
|
+
from .dns import DnsError, Resolver
|
|
41
|
+
|
|
42
|
+
USER_AGENT = (f"subdomainchecker/{__version__} "
|
|
43
|
+
"(+https://github.com/PHPatch/subdomainchecker)")
|
|
44
|
+
CRT_SH_URL = "https://crt.sh/?q=%25.{domain}&output=json"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class EnumerationError(Exception):
|
|
48
|
+
"""Subdomain enumeration failed (e.g. crt.sh unreachable)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fetch_crtsh(domain: str, retries: int = 3,
|
|
52
|
+
timeout: float = 20.0) -> list[str]:
|
|
53
|
+
"""Enumerate subdomains of *domain* from certificate logs.
|
|
54
|
+
|
|
55
|
+
Uses crt.sh's public JSON API. Raises EnumerationError with
|
|
56
|
+
a --list suggestion after the retries are exhausted.
|
|
57
|
+
"""
|
|
58
|
+
url = CRT_SH_URL.format(domain=domain)
|
|
59
|
+
last_error: Exception | None = None
|
|
60
|
+
for attempt in range(retries):
|
|
61
|
+
try:
|
|
62
|
+
request = urllib.request.Request(
|
|
63
|
+
url, headers={"User-Agent": USER_AGENT})
|
|
64
|
+
with urllib.request.urlopen(request,
|
|
65
|
+
timeout=timeout) as resp:
|
|
66
|
+
payload = json.loads(resp.read().decode("utf-8"))
|
|
67
|
+
names: set[str] = set()
|
|
68
|
+
for row in payload:
|
|
69
|
+
for name in row.get("name_value", "").splitlines():
|
|
70
|
+
name = name.strip().lower().lstrip("*.")
|
|
71
|
+
if name.endswith("." + domain):
|
|
72
|
+
names.add(name)
|
|
73
|
+
return sorted(names)
|
|
74
|
+
except Exception as exc: # crt.sh is famously flaky; retry
|
|
75
|
+
last_error = exc
|
|
76
|
+
if attempt < retries - 1:
|
|
77
|
+
time.sleep(2 * (attempt + 1))
|
|
78
|
+
raise EnumerationError(
|
|
79
|
+
f"certificate-transparency lookup via crt.sh failed "
|
|
80
|
+
f"({last_error}). crt.sh is intermittently unavailable; "
|
|
81
|
+
f"retry later, or supply your own subdomain list with "
|
|
82
|
+
f"--list subdomains.txt (the reliable path for audits).")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def load_list(path: str) -> list[str]:
|
|
86
|
+
"""Load a user-supplied subdomain list (one name per line)."""
|
|
87
|
+
names: set[str] = set()
|
|
88
|
+
with open(path, encoding="utf-8") as handle:
|
|
89
|
+
for line in handle:
|
|
90
|
+
name = line.strip().lower().lstrip("*.")
|
|
91
|
+
if name and not name.startswith("#"):
|
|
92
|
+
names.add(name)
|
|
93
|
+
return sorted(names)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class BlockedTarget(Exception):
|
|
97
|
+
"""The HTTP target was refused by the SSRF policy."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# Ranges that Python's is_global / is_private flags do not
|
|
101
|
+
# classify consistently across versions, checked explicitly —
|
|
102
|
+
# the same list the rest of the scanner family uses: carrier-
|
|
103
|
+
# grade NAT, the IETF special-purpose /24, benchmarking space,
|
|
104
|
+
# the deprecated 6to4 relay anycast, and the IPv6 transition
|
|
105
|
+
# prefixes whose embedded IPv4 destination could be non-public
|
|
106
|
+
# (NAT64 well-known prefix, Teredo).
|
|
107
|
+
_EXTRA_BLOCKED = [ipaddress.ip_network(n) for n in (
|
|
108
|
+
"100.64.0.0/10", "192.0.0.0/24", "198.18.0.0/15",
|
|
109
|
+
"192.88.99.0/24", "64:ff9b::/96", "2001::/32")]
|
|
110
|
+
|
|
111
|
+
_ALLOWED_PORTS = (80, 443)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _ip_blocked(ip) -> bool:
|
|
115
|
+
"""True unless the address is globally routable public space."""
|
|
116
|
+
return (not ip.is_global or ip.is_multicast
|
|
117
|
+
or any(ip in n for n in _EXTRA_BLOCKED))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _public_ips(host: str) -> list[str]:
|
|
121
|
+
"""Resolve *host* and require EVERY answer to be a public
|
|
122
|
+
address, so the checker can never be pointed at internal
|
|
123
|
+
services."""
|
|
124
|
+
try:
|
|
125
|
+
infos = socket.getaddrinfo(host, None,
|
|
126
|
+
proto=socket.IPPROTO_TCP)
|
|
127
|
+
except socket.gaierror as exc:
|
|
128
|
+
raise BlockedTarget(
|
|
129
|
+
f"DNS lookup failed for {host}: {exc}") from exc
|
|
130
|
+
ips: list[str] = []
|
|
131
|
+
for info in infos:
|
|
132
|
+
ip = ipaddress.ip_address(info[4][0])
|
|
133
|
+
# Unwrap transition forms: the real TCP destination of
|
|
134
|
+
# an IPv4-mapped (::ffff:a.b.c.d) or 6to4 (2002:xxxx::)
|
|
135
|
+
# address is the embedded IPv4, so THAT is what must be
|
|
136
|
+
# checked.
|
|
137
|
+
if isinstance(ip, ipaddress.IPv6Address):
|
|
138
|
+
if ip.ipv4_mapped is not None:
|
|
139
|
+
ip = ip.ipv4_mapped
|
|
140
|
+
elif ip.sixtofour is not None:
|
|
141
|
+
ip = ip.sixtofour
|
|
142
|
+
if _ip_blocked(ip):
|
|
143
|
+
raise BlockedTarget(
|
|
144
|
+
f"{host} resolves to a non-public address "
|
|
145
|
+
f"({ip}); refusing to fetch it")
|
|
146
|
+
if str(ip) not in ips:
|
|
147
|
+
ips.append(str(ip))
|
|
148
|
+
if not ips:
|
|
149
|
+
raise BlockedTarget(
|
|
150
|
+
f"DNS lookup returned nothing for {host}")
|
|
151
|
+
return ips
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class _PinnedHTTPS(http.client.HTTPSConnection):
|
|
155
|
+
"""HTTPS to a pinned IP, with SNI + certificate checks
|
|
156
|
+
against the original hostname."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, ip, port, hostname, timeout):
|
|
159
|
+
super().__init__(ip, port, timeout=timeout,
|
|
160
|
+
context=ssl.create_default_context())
|
|
161
|
+
self._hostname = hostname
|
|
162
|
+
|
|
163
|
+
def connect(self):
|
|
164
|
+
http.client.HTTPConnection.connect(self)
|
|
165
|
+
self.sock = self._context.wrap_socket(
|
|
166
|
+
self.sock, server_hostname=self._hostname)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def http_get(url: str, timeout: float = 10.0) -> tuple[int, str]:
|
|
170
|
+
"""One benign GET; returns (status, body text capped at 64K).
|
|
171
|
+
|
|
172
|
+
Guarded, in the scanner family's pattern but simplified for
|
|
173
|
+
a laptop CLI: http/https only, ports 80/443 only, no URL
|
|
174
|
+
credentials, every DNS answer for the host must be a
|
|
175
|
+
globally routable public address, and the connection is
|
|
176
|
+
pinned to a checked address (with SNI + certificate
|
|
177
|
+
validation against the hostname for HTTPS), so DNS
|
|
178
|
+
rebinding between the policy check and the connect gets
|
|
179
|
+
nothing. Redirects are NOT followed: a 3xx is itself the
|
|
180
|
+
response and is returned like any other status — an error
|
|
181
|
+
status is still evidence, as fingerprint pages are commonly
|
|
182
|
+
served with a 404.
|
|
183
|
+
"""
|
|
184
|
+
parts = urllib.parse.urlsplit(url)
|
|
185
|
+
if parts.scheme not in ("http", "https"):
|
|
186
|
+
raise BlockedTarget(f"refusing non-http(s) URL: {url}")
|
|
187
|
+
if parts.username or parts.password:
|
|
188
|
+
raise BlockedTarget("URLs with credentials are refused")
|
|
189
|
+
host = parts.hostname
|
|
190
|
+
if not host:
|
|
191
|
+
raise BlockedTarget(f"URL has no host: {url}")
|
|
192
|
+
default_port = 443 if parts.scheme == "https" else 80
|
|
193
|
+
try:
|
|
194
|
+
port = parts.port or default_port
|
|
195
|
+
except ValueError:
|
|
196
|
+
raise BlockedTarget(
|
|
197
|
+
f"URL has an invalid port: {url}") from None
|
|
198
|
+
if port not in _ALLOWED_PORTS:
|
|
199
|
+
raise BlockedTarget(
|
|
200
|
+
f"refusing non-standard port {port} in {url}")
|
|
201
|
+
ip = _public_ips(host)[0]
|
|
202
|
+
path = parts.path or "/"
|
|
203
|
+
if parts.query:
|
|
204
|
+
path += "?" + parts.query
|
|
205
|
+
host_header = f"[{host}]" if ":" in host else host
|
|
206
|
+
if port != default_port:
|
|
207
|
+
host_header += f":{port}"
|
|
208
|
+
if parts.scheme == "https":
|
|
209
|
+
conn: http.client.HTTPConnection = _PinnedHTTPS(
|
|
210
|
+
ip, port, host, timeout)
|
|
211
|
+
else:
|
|
212
|
+
conn = http.client.HTTPConnection(ip, port,
|
|
213
|
+
timeout=timeout)
|
|
214
|
+
try:
|
|
215
|
+
conn.request("GET", path, headers={
|
|
216
|
+
"Host": host_header,
|
|
217
|
+
"User-Agent": USER_AGENT,
|
|
218
|
+
"Accept": "*/*",
|
|
219
|
+
"Connection": "close",
|
|
220
|
+
})
|
|
221
|
+
response = conn.getresponse()
|
|
222
|
+
body = response.read(65536)
|
|
223
|
+
return response.status, body.decode("utf-8", "replace")
|
|
224
|
+
finally:
|
|
225
|
+
conn.close()
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def check_subdomain(subdomain: str, resolver, get,
|
|
229
|
+
pairs) -> dict:
|
|
230
|
+
"""Check one subdomain. *resolver* and *get* are injectable
|
|
231
|
+
so tests never touch the network."""
|
|
232
|
+
result = {
|
|
233
|
+
"subdomain": subdomain,
|
|
234
|
+
"cname": None,
|
|
235
|
+
"service": None,
|
|
236
|
+
"service_status": None,
|
|
237
|
+
"verdict": "OK",
|
|
238
|
+
"evidence": "no CNAME record",
|
|
239
|
+
"remediation": None,
|
|
240
|
+
}
|
|
241
|
+
try:
|
|
242
|
+
target = resolver.cname(subdomain)
|
|
243
|
+
except DnsError as exc:
|
|
244
|
+
# A failed lookup is not "no CNAME": the record could
|
|
245
|
+
# not be read, so nothing about this subdomain is
|
|
246
|
+
# confirmed. Never report it OK.
|
|
247
|
+
result["verdict"] = "UNCHECKED"
|
|
248
|
+
result["evidence"] = f"CNAME lookup failed: {exc}"
|
|
249
|
+
result["remediation"] = (
|
|
250
|
+
f"Re-run the check for {subdomain} when DNS is "
|
|
251
|
+
f"responding normally; until then its state is "
|
|
252
|
+
f"unknown.")
|
|
253
|
+
return result
|
|
254
|
+
if not target:
|
|
255
|
+
return result
|
|
256
|
+
result["cname"] = target
|
|
257
|
+
|
|
258
|
+
entry = match_service(target, pairs) if pairs is not None else None
|
|
259
|
+
if entry is not None:
|
|
260
|
+
result["service"] = entry["service"]
|
|
261
|
+
result["service_status"] = entry["status"]
|
|
262
|
+
|
|
263
|
+
status = resolver.resolve_status(target)
|
|
264
|
+
|
|
265
|
+
if status in ("nxdomain", "nodata"):
|
|
266
|
+
result["evidence"] = (
|
|
267
|
+
f"CNAME target {target} does not resolve "
|
|
268
|
+
f"({status}) — the resource it pointed at is gone")
|
|
269
|
+
if entry is not None:
|
|
270
|
+
result["verdict"] = "VULNERABLE"
|
|
271
|
+
result["remediation"] = (
|
|
272
|
+
f"Remove the DNS record for {subdomain}, or "
|
|
273
|
+
f"reclaim the resource on {entry['service']} "
|
|
274
|
+
f"before someone else does.")
|
|
275
|
+
else:
|
|
276
|
+
result["verdict"] = "POSSIBLE"
|
|
277
|
+
result["remediation"] = (
|
|
278
|
+
f"Review the DNS record for {subdomain}: its "
|
|
279
|
+
f"CNAME target {target} no longer resolves. If "
|
|
280
|
+
f"the service is gone, remove the record; if it "
|
|
281
|
+
f"moved, update the record to the new target.")
|
|
282
|
+
return result
|
|
283
|
+
|
|
284
|
+
if status == "error":
|
|
285
|
+
# A failed lookup confirms nothing — in particular it
|
|
286
|
+
# does not confirm that the target "resolves". Say so
|
|
287
|
+
# rather than guessing, for known and unknown services
|
|
288
|
+
# alike.
|
|
289
|
+
if entry is None:
|
|
290
|
+
result["verdict"] = "UNCHECKED"
|
|
291
|
+
result["evidence"] = (
|
|
292
|
+
f"CNAME to {target}; resolving the target "
|
|
293
|
+
f"failed, so it cannot be confirmed whether "
|
|
294
|
+
f"the record dangles")
|
|
295
|
+
result["remediation"] = (
|
|
296
|
+
f"Re-run the check for {subdomain} when DNS "
|
|
297
|
+
f"is responding normally, or verify manually "
|
|
298
|
+
f"that {target} still resolves and is yours.")
|
|
299
|
+
return result
|
|
300
|
+
result["verdict"] = "POSSIBLE"
|
|
301
|
+
result["evidence"] = (
|
|
302
|
+
f"CNAME to {entry['service']} ({target}); resolving "
|
|
303
|
+
f"the target failed, so the unclaimed fingerprint "
|
|
304
|
+
f"could not be confirmed from here")
|
|
305
|
+
result["remediation"] = (
|
|
306
|
+
f"Verify the {entry['service']} resource behind "
|
|
307
|
+
f"{subdomain} is still yours; if it is not, remove "
|
|
308
|
+
f"the DNS record for {subdomain}.")
|
|
309
|
+
return result
|
|
310
|
+
|
|
311
|
+
if entry is None:
|
|
312
|
+
result["evidence"] = (f"CNAME to {target}, which resolves "
|
|
313
|
+
f"and is not a known takeover-capable "
|
|
314
|
+
f"service")
|
|
315
|
+
return result
|
|
316
|
+
|
|
317
|
+
fingerprint = entry.get("fingerprint")
|
|
318
|
+
if not fingerprint or fingerprint == "NXDOMAIN":
|
|
319
|
+
# This service's only published fingerprint is the
|
|
320
|
+
# DNS-level one, and the target resolves — the resource
|
|
321
|
+
# exists. Nothing further can be claimed honestly.
|
|
322
|
+
result["evidence"] = (
|
|
323
|
+
f"CNAME to {entry['service']} ({target}), which "
|
|
324
|
+
f"resolves; the service's only published fingerprint "
|
|
325
|
+
f"is DNS-level (NXDOMAIN), which does not apply")
|
|
326
|
+
return result
|
|
327
|
+
|
|
328
|
+
try:
|
|
329
|
+
code, body = get(f"https://{subdomain}/")
|
|
330
|
+
except Exception as exc:
|
|
331
|
+
result["verdict"] = "POSSIBLE"
|
|
332
|
+
result["evidence"] = (
|
|
333
|
+
f"CNAME to {entry['service']} ({target}); the "
|
|
334
|
+
f"fingerprint check could not be completed ({exc})")
|
|
335
|
+
result["remediation"] = (
|
|
336
|
+
f"Verify the {entry['service']} resource behind "
|
|
337
|
+
f"{subdomain} is still yours; if it is not, remove "
|
|
338
|
+
f"the DNS record for {subdomain}.")
|
|
339
|
+
return result
|
|
340
|
+
|
|
341
|
+
status_matches = entry.get("http_status") is not None \
|
|
342
|
+
and code == entry["http_status"]
|
|
343
|
+
if status_matches or fingerprint_matches(fingerprint, body):
|
|
344
|
+
result["verdict"] = "VULNERABLE"
|
|
345
|
+
note = (" (upstream rates this service an edge case — "
|
|
346
|
+
"takeover may need additional conditions)"
|
|
347
|
+
if entry["status"] == "Edge case" else "")
|
|
348
|
+
result["evidence"] = (
|
|
349
|
+
f"{entry['service']} serves its unclaimed-resource "
|
|
350
|
+
f"fingerprint at {subdomain} (HTTP {code}){note}")
|
|
351
|
+
result["remediation"] = (
|
|
352
|
+
f"Remove the DNS record for {subdomain}, or "
|
|
353
|
+
f"reclaim the resource on {entry['service']} "
|
|
354
|
+
f"before someone else does.")
|
|
355
|
+
else:
|
|
356
|
+
result["evidence"] = (
|
|
357
|
+
f"{entry['service']} resource at {target} is "
|
|
358
|
+
f"claimed and serving (HTTP {code}); no unclaimed "
|
|
359
|
+
f"fingerprint")
|
|
360
|
+
return result
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def run_checks(subdomains: list[str], resolver=None, get=None,
|
|
364
|
+
delay: float = 0.3, timeout: float = 10.0) -> list[dict]:
|
|
365
|
+
"""Check every subdomain, sequentially, with small delays."""
|
|
366
|
+
resolver = resolver or Resolver()
|
|
367
|
+
if get is None:
|
|
368
|
+
def get(url: str):
|
|
369
|
+
return http_get(url, timeout=timeout)
|
|
370
|
+
pairs = services_by_pattern(load_dataset())
|
|
371
|
+
results = []
|
|
372
|
+
for index, subdomain in enumerate(subdomains):
|
|
373
|
+
if index and delay:
|
|
374
|
+
time.sleep(delay)
|
|
375
|
+
results.append(check_subdomain(subdomain, resolver, get,
|
|
376
|
+
pairs))
|
|
377
|
+
return results
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def summarize(results: list[dict]) -> dict:
|
|
381
|
+
counts = {"VULNERABLE": 0, "POSSIBLE": 0, "OK": 0,
|
|
382
|
+
"UNCHECKED": 0}
|
|
383
|
+
for result in results:
|
|
384
|
+
counts[result["verdict"]] += 1
|
|
385
|
+
return counts
|