22
33from __future__ import annotations
44
5+ import http .client
56import ipaddress
7+ import json
68import re
79import socket
810from typing import Any
3032_COULD_NOT_FETCH_WELL_KNOWN = "Could not fetch well-known JSON."
3133_WELL_KNOWN_INVALID_JSON = "Well-known response was not valid JSON."
3234_WELL_KNOWN_NOT_OBJECT = "Well-known response was not a JSON object."
35+ _HTTP_SUCCESS_STATUS_MIN = 200
36+ _HTTP_SUCCESS_STATUS_MAX = 299
37+ _NO_PINNED_ADDRESSES = "no pinned addresses to connect"
3338
3439
3540class RegistryVerifyFetchError (Exception ):
@@ -47,8 +52,8 @@ def _is_lab_self_fetch(fqdn: str) -> bool:
4752 return bool (site_fqdn ) and _normalized_host (fqdn ) == site_fqdn
4853
4954
50- def validate_applicant_hostname_for_verify (fqdn : str ) -> None :
51- """Reject private, link-local, and non-public resolved targets ."""
55+ def _resolve_global_addresses_for_verify (fqdn : str ) -> list [ str ] :
56+ """Resolve once; reject private targets; return global address strings ."""
5257 host = _normalized_host (fqdn )
5358 if not host or "%" in host or "/" in host or "@" in host or ":" in host :
5459 raise RegistryVerifyFetchError (_INVALID_APPLICANT_HOSTNAME )
@@ -61,7 +66,7 @@ def validate_applicant_hostname_for_verify(fqdn: str) -> None:
6166 else :
6267 if not literal .is_global :
6368 raise RegistryVerifyFetchError (_APPLICANT_HOSTNAME_NOT_ALLOWED )
64- return
69+ return [ str ( literal )]
6570
6671 try :
6772 infos = socket .getaddrinfo (host , 443 , type = socket .SOCK_STREAM )
@@ -72,10 +77,87 @@ def validate_applicant_hostname_for_verify(fqdn: str) -> None:
7277 if not infos :
7378 raise RegistryVerifyFetchError (_COULD_NOT_RESOLVE_HOSTNAME )
7479
80+ addresses : list [str ] = []
7581 for * _ , sockaddr in infos :
7682 addr = ipaddress .ip_address (sockaddr [0 ])
7783 if not addr .is_global :
7884 raise RegistryVerifyFetchError (_APPLICANT_HOSTNAME_NOT_ALLOWED )
85+ addresses .append (sockaddr [0 ])
86+ return list (dict .fromkeys (addresses ))
87+
88+
89+ def validate_applicant_hostname_for_verify (fqdn : str ) -> None :
90+ """Reject private, link-local, and non-public resolved targets."""
91+ _resolve_global_addresses_for_verify (fqdn )
92+
93+
94+ class _PinnedHTTPSConnection (http .client .HTTPSConnection ):
95+ """TLS to ``host`` while TCP connects to a pre-validated address."""
96+
97+ def __init__ (self , host : str , pinned_address : str , * , timeout : float ) -> None :
98+ self ._pinned_address = pinned_address
99+ super ().__init__ (host , port = 443 , timeout = timeout )
100+
101+ def connect (self ) -> None :
102+ self .sock = self ._create_connection (
103+ (self ._pinned_address , self .port ),
104+ self .timeout ,
105+ self .source_address ,
106+ )
107+ server_hostname = self ._tunnel_host or self .host
108+ self .sock = self ._context .wrap_socket (
109+ self .sock , server_hostname = server_hostname
110+ )
111+
112+
113+ def _read_response_body_limited (
114+ response : http .client .HTTPResponse ,
115+ max_bytes : int ,
116+ ) -> bytes :
117+ chunks : list [bytes ] = []
118+ total = 0
119+ while True :
120+ chunk = response .read (8192 )
121+ if not chunk :
122+ break
123+ total += len (chunk )
124+ if total > max_bytes :
125+ raise RegistryVerifyFetchError (_WELL_KNOWN_TOO_LARGE )
126+ chunks .append (chunk )
127+ return b"" .join (chunks )
128+
129+
130+ def _pinned_https_get (
131+ url : str ,
132+ hostname : str ,
133+ pinned_addresses : list [str ],
134+ timeout : int ,
135+ ) -> tuple [int , bytes ]:
136+ """GET over HTTPS using only addresses from verify DNS resolution."""
137+ parsed = urlparse (url )
138+ path = parsed .path or "/"
139+ if parsed .query :
140+ path = f"{ path } ?{ parsed .query } "
141+
142+ last_error : BaseException | None = None
143+ for pinned in pinned_addresses :
144+ conn = _PinnedHTTPSConnection (hostname , pinned , timeout = timeout )
145+ try :
146+ conn .request ("GET" , path , headers = {"Accept" : "application/json" })
147+ response = conn .getresponse ()
148+ body = _read_response_body_limited (response , _MAX_RESPONSE_BYTES )
149+ except RegistryVerifyFetchError :
150+ raise
151+ except (OSError , TimeoutError , http .client .HTTPException ) as exc :
152+ last_error = exc
153+ else :
154+ return response .status , body
155+ finally :
156+ conn .close ()
157+
158+ if last_error is not None :
159+ raise last_error
160+ raise OSError (_NO_PINNED_ADDRESSES )
79161
80162
81163def fetch_well_known_json (
@@ -84,29 +166,46 @@ def fetch_well_known_json(
84166) -> dict [str , Any ]:
85167 """GET applicant well-known JSON (HTTPS; local lab may use internal HTTP)."""
86168 url = resolve_well_known_fetch_url (fqdn )
169+ expected_host = _normalized_host (fqdn )
170+ pinned_addresses : list [str ] | None = None
87171 if not _is_lab_self_fetch (fqdn ):
88- validate_applicant_hostname_for_verify (fqdn )
172+ pinned_addresses = _resolve_global_addresses_for_verify (fqdn )
89173 parsed = urlparse (url )
90- expected_host = _normalized_host (fqdn )
91174 if (
92175 parsed .scheme != "https"
93176 or _normalized_host (parsed .hostname or "" ) != expected_host
94177 ):
95178 raise RegistryVerifyFetchError (_INVALID_VERIFY_FETCH_URL )
96179
97180 try :
98- response = requests .get (
99- url ,
100- timeout = timeout ,
101- allow_redirects = False ,
102- headers = {"Accept" : "application/json" },
103- )
104- response .raise_for_status ()
105- content = response .content
106- if len (content ) > _MAX_RESPONSE_BYTES :
107- raise RegistryVerifyFetchError (_WELL_KNOWN_TOO_LARGE )
108- payload = response .json ()
109- except requests .RequestException :
181+ if pinned_addresses is not None :
182+ status , content = _pinned_https_get (
183+ url ,
184+ expected_host ,
185+ pinned_addresses ,
186+ timeout ,
187+ )
188+ if status < _HTTP_SUCCESS_STATUS_MIN or status > _HTTP_SUCCESS_STATUS_MAX :
189+ http_error_msg = f"HTTP { status } "
190+ raise requests .HTTPError (http_error_msg )
191+ else :
192+ response = requests .get (
193+ url ,
194+ timeout = timeout ,
195+ allow_redirects = False ,
196+ headers = {"Accept" : "application/json" },
197+ )
198+ response .raise_for_status ()
199+ content = response .content
200+ if len (content ) > _MAX_RESPONSE_BYTES :
201+ raise RegistryVerifyFetchError (_WELL_KNOWN_TOO_LARGE )
202+ payload = json .loads (content )
203+ except (
204+ requests .RequestException ,
205+ OSError ,
206+ TimeoutError ,
207+ http .client .HTTPException ,
208+ ):
110209 logger .warning (
111210 "registry verify HTTP failed fqdn={} url={}" ,
112211 fqdn ,
0 commit comments