Repository navigation
Fix remaining RFC 3986 host-parsing bugs in getURLHostRFC - #118979
Conversation
ClickHouse#118632 taught getURLHostRFC to parse a bracketed IPv6 host, including after a userinfo@ prefix, but several related bugs remain in the same parser, on top of that fix: - A bracketed host with an embedded IPv4 tail, e.g. "::ffff:192.168.0.1" or a NAT64 literal "64:ff9b::192.0.2.33", was rejected outright: any '.' while scanning inside brackets returned an empty host, even though this is a valid IPv6 address form and parseIPv6Whole already supports it. This is the bug reported in ClickHouse#118890. - The bracket contents were never validated as an actual IPv6 address, so a non-IPv6 string like "2001db81" was silently accepted as the host. Validate it with parseIPv6Whole (already used elsewhere in the codebase, e.g. isIPAddressInRange.cpp). - Nothing following the closing ']' was checked, so "[2001:db8::1]evil.com" returned "2001:db8::1" as the host. Only end of input, ':', '/', '?', or '#' may legally follow it. - colon_pos, dot_pos, and has_terminator_after_colon carried over across '@', so a colon or dot in the userinfo (e.g. "user:password@") could validate a malformed host afterward using state that actually describes the userinfo, not the host - reset all three at '@'. - userinfo may contain more than one ':' (RFC 3986), but the second one was read as the host:port separator before the parser ever reached '@', rejecting valid authorities like "user:pass:word@[2001:db8::1]:80". - A second raw '@' was accepted as if it were another userinfo separator, returning the segment in between as the host: "[email protected]@evil.com" returned "paypal.com" instead of being rejected - userinfo cannot legally contain an unescaped '@' at all, so a second one makes the whole authority unparseable. - A host starting with a literal '.', e.g. ".com", was accepted by checkAndReturnHost (shared by domain() and domainRFC()), since it only checked for a dot with nothing after it, not nothing before it either. Closes: ClickHouse#118890 Related: ClickHouse#118632
The port-digit loop in extractPort only treated '/' as the end of an explicit port, so a query string or fragment right after the port, e.g. https://example.com:8443?x=1, made the loop reject the '?' as a non-digit and fall back to the default port even though the port itself was perfectly valid. The host parsers already treat '/', '?', and '#' as the end of the authority; do the same for the port digits. This is the same fix as the separately open ClickHouse#118482, which covers reg-name hosts; the getURLHostRFC fixes in the previous commit make this also apply to bracketed IPv6 hosts, which ClickHouse#118482 does not touch.
|
Workflow [PR], commit [d7cef2c] Summary: ✅
AI ReviewSummaryThis PR finishes the Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit d7cef2c.
Changed lines: Changed C/C++ lines covered: 117/121 (96.69%) · Uncovered code |
Per review on ClickHouse#118979: checkAndReturnHost rejected a leading dot by comparing dot_pos to start_of_host, but dot_pos tracks the last dot seen while scanning, not the first one. A second leading dot overwrites dot_pos away from start_of_host, so domainRFC('http://..com/') and domain('http://[email protected]/') still returned '..com' instead of being rejected. Check *start_of_host == '.' directly instead, which catches any number of leading dots regardless of which one dot_pos ends up pointing to.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units14 translation units recompiled, 26 s compile time in total, 14 of them have a recent master baseline. |
|
@PedroTadim The stress test that failed is flaky and not related to this PR. I cannot restart the single job, so I would have to run the whole suite again. Is it possible to merge as is? |
|
It seems to be a regression introduced in the master today, so unrelated. Let's review and merge |
Per review from @PedroTadim on ClickHouse#118979: the earlier "reject a second raw '@'" fix only works if the scanner actually reaches the second '@'. It didn't for authorities like "[email protected]:[email protected]/" or "user@[::1]:[email protected]/": a ':' right after '@' was treated as the port separator via an immediate goto done, and a closing ']' returned the bracket host immediately - both cases end the scan before ever seeing the second '@', so it silently returned "paypal.com" / "::1" instead of being rejected. Make ':' only ever record a fallback port-separator position (as already done before '@' is seen) and keep scanning, whether or not '@' has been seen yet - a later '@' can still turn everything scanned so far into userinfo. Do the same for a closing ']': record where the bracket ends and keep scanning instead of returning right away, so a later '@' is still caught by the existing rejection. The bracket host returned at the end now spans up to the recorded closing bracket position rather than the (now further advanced) current position. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Per review from @PedroTadim on ClickHouse#118979: the earlier "reject a second raw '@'" fix only works if the scanner actually reaches the second '@'. It didn't for authorities like "[email protected]:[email protected]/" or "user@[::1]:[email protected]/": a ':' right after '@' was treated as the port separator via an immediate goto done, and a closing ']' returned the bracket host immediately - both cases end the scan before ever seeing the second '@', so it silently returned "paypal.com" / "::1" instead of being rejected. Make ':' only ever record a fallback port-separator position (as already done before '@' is seen) and keep scanning, whether or not '@' has been seen yet - a later '@' can still turn everything scanned so far into userinfo. Do the same for a closing ']': record where the bracket ends and keep scanning instead of returning right away, so a later '@' is still caught by the existing rejection. The bracket host returned at the end now spans up to the recorded closing bracket position rather than the (now further advanced) current position.
b150397 to
b8a1fd3
Compare
Per review on ClickHouse#118979: keeping the scan alive past a closing ']' (so a later '@' could still be caught) left has_end_bracket and bracket_close_pos live across that '@' too. If the authority started directly with a bracketed host, has_at_symbol was still false at that point, so the '@' case proceeded as if this were genuinely the first userinfo boundary, reopening a new bracket after it if one followed: domainRFC('http://[::1]:80@[::2]') returned '::2' instead of being rejected, even though "[::1]:80" can only become userinfo now that '@' showed up, and userinfo can never legally contain raw '[' or ']'. Worse, domainRFC('http://[::1]:[email protected]') reset start_of_host past this '@' while bracket_close_pos still pointed at the earlier, already-closed bracket - since that position now precedes start_of_host, done: still took the has_end_bracket branch and called parseIPv6Whole with a reversed (src > end) range, undefined behavior enforced by chassert in debug and sanitizer builds. Reject '@' outright once has_end_bracket is set, the same way it is already rejected inside a still-open bracket.
Per review on ClickHouse#118979: getURLHostRFC() can now return a bracketed IP-literal host with an embedded IPv4 tail, e.g. "::ffff:192.0.2.128" for http://[::ffff:192.0.2.128]:80, stripped of its brackets. Every "RFC" function built on top of it inherits this, but ExtractFirstSignificantSubdomain::execute() and ::executeCustom() (backing firstSignificantSubdomainRFC, firstSignificantSubdomainCustomRFC, cutToFirstSignificantSubdomainRFC, cutToFirstSignificantSubdomainWithWWWRFC, cutToFirstSignificantSubdomainCustomRFC, and cutToFirstSignificantSubdomainCustomWithWWWRFC) just dot-split the host looking for a TLD, with no check that it is actually a DNS name rather than an IP address. firstSignificantSubdomainRFC('http://[::ffff:192.0.2.128]:80') returned '2', carved out of the last octet of the embedded IPv4 tail, and firstSignificantSubdomainRFC('http://[2001:db8::1]:80') returned the whole address unchanged - neither is a sensible "subdomain". topLevelDomainRFC already happens to reject both forms via an unrelated numeric-tail check, which is why this family was the one left exposed. A reg-name host can never contain ':' (it is always consumed as the userinfo or port separator beforehand), so any ':' remaining in an RFC-parsed host means it came from an IP-literal. Reject it up front, the same way an empty host is already rejected.
Per review on ClickHouse#118979: RFC 3986, 3.2.2 defines IP-literal as either IPv6address or IPvFuture ("v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )), a placeholder for IP address formats beyond IPv6, but only the former was accepted - a bracketed host like "[v1.a]" was rejected outright, even though port.cpp's own comment already documented the full grammar for this code path. Added isIPvFuture() and try it as a fallback when parseIPv6Whole fails. Sub-delims (;=&~%) also had to stop tripping has_sub_delims while inside an open bracket, the same way '.' and ':' already do, since they are valid in IPvFuture's address part but that flag unconditionally rejects the whole host at the end regardless of where the character was seen.
Per review on ClickHouse#118979: past '@', the '.' case recorded dot_pos unconditionally, even for a dot appearing after colon_pos - i.e. in what should already be the port (or whatever junk follows it), not the host. domainRFC('http://user@foo:80.bar/') returned 'foo' instead of being rejected: the '.' in "80.bar" set dot_pos, done: rewound pos back to the first ':' (right after "foo"), and checkAndReturnHost saw a non-null dot_pos and validated "foo" as if it had a dot of its own. Make dot-tracking symmetric regardless of has_at_symbol: once colon_pos is set, a later dot no longer counts, the same way it already didn't before '@'.
Per review on ClickHouse#118979: the ':' heuristic added to ExtractFirstSignificantSubdomain::execute()/executeCustom() only catches the subset of IP-literal hosts whose stripped contents still contain a colon. After the IPvFuture support added earlier, getURLHostRFC can return a host like "v1.a" for http://[v1.a]:80/, with no ':' at all, so firstSignificantSubdomainRFC('http://[v1.a]:80/') still treated it as a DNS name and returned a bogus subdomain. topLevelDomainRFC has the same gap: http://[v1.a]:80/ became top-level domain "a". Both helpers still have the original data/size, so detect the bracket from the surrounding text instead of guessing from the host's own shape: the byte before the host is '[' and the byte after it is ']' whenever getURLHostRFC returned a bracketed literal, regardless of what it contains.
Fast test failures on 05154_first_significant_subdomain_rfc_ipv6 and
05155_domain_rfc_ipvfuture: the first execute() in
ExtractFirstSignificantSubdomain.h (backing firstSignificantSubdomainRFC
and cutToFirstSignificantSubdomainRFC) still had the old ':'-based
guard instead of the bracket-adjacency check applied to executeCustom()
in the previous commit, so firstSignificantSubdomainRFC('http://[v1.a]:80/')
still returned 'v1' instead of empty. Bring it in line with
executeCustom(). Also add FORMAT CSV to the topLevelDomainRFC test
line, which printed an empty string as a blank line instead of "" and
mismatched its reference for that reason alone.
Build (arm_tidy) failure: host.data()[-1] and host.data()[host.size()]
in topLevelDomain.cpp tripped clang-tidy's readability-simplify-subscript-expr
(warnings-as-errors). host.size() is out of bounds for operator[], so
switching to host[...] as suggested would be a real behavior change;
hoist host.data() into a local pointer instead so the flagged
container.data()[i] pattern no longer appears syntactically.
|
|
||
| /// RFC 3986, 3.2.2: IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) | ||
| /// A placeholder for IP address formats beyond IPv6, e.g. "[v1.a]". | ||
| inline bool isIPvFuture(const char * begin, const char * end) |
There was a problem hiding this comment.
The IPvFuture parsing seems a new feature, maybe should go to a new PR, but can keep on this one
There was a problem hiding this comment.
If it is ok, I'd rather keep it on this one.
|
@PedroTadim from my side, I think this is done and ready to merge. |
| -- Two (or more) leading dots must be rejected too, not just a host that is exactly ".something". | ||
| SELECT domainRFC('http://..com/') FORMAT CSV; | ||
| SELECT domainRFC('http://[email protected]/') FORMAT CSV; | ||
| SELECT domain('http://..com/') FORMAT CSV; |
There was a problem hiding this comment.
@lizardoluis merge with master one more time and add some bad url examples, such as nothing after : or [, missing ] and other parts of the url just to confirm nothing goes out-of-bounds
…fix-portrfc-ipv6-host-validation
Per review on ClickHouse#118979: add regression coverage for the same class of out-of-bounds risk that a09bdba fixed for the original bracket check, this time for the userinfo, port-colon, and IPvFuture handling added since. Covers truncation right after '[', ':', or '@', an unclosed bracket, every truncation point of a partial IPvFuture literal, empty brackets, and a truncated second '@', through domainRFC, portRFC, and the subdomain-family RFC functions, plus a materialize() variant for the vectorized route. Verified with an ASan-instrumented standalone harness against exact-size heap buffers (no padding), so a single-byte overread would abort immediately: all cases pass clean, and every returned value is empty/default as expected.
portRFC('http://') is the 22nd SELECT in this file, not the 21st -
topLevelDomainRFC (a String-returning function, correctly empty) comes
right before it. My reference reconstruction misplaced the single
non-empty "0" one line early, silently shifting every line of the new
section after it by one and causing a mismatch against the fast test.
Per AI review on ClickHouse#118979: RFC 3986, 3.1 defines scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ), which does not permit '['. The scheme-detection pre-scan allowed it anyway, so domainRFC('a[://foo.com') treated "a[" as if it were a valid scheme and returned "foo.com" as the host. '[' never needs to be treated as part of a scheme for a legitimate bracketed IP-literal host: it either starts the authority directly, which this pre-scan never examines (its loop begins one character in), or it follows the scheme's own '://', which the scan already recognizes and consumes first. Verified against the reported case and the full accumulated regression suite for this branch's bracket/userinfo/IPvFuture work - no regressions.
Per AI review on ClickHouse#118979: the scheme-detection scan in getURLHostRFC unconditionally skipped the first byte, on the assumption it might start a scheme, without ever checking that RFC 3986, 3.1 requires a scheme to start with a letter (scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )). Two consequences: - domainRFC('1://foo.com') treated "1" as if it were a valid scheme and returned "foo.com" as the host instead of rejecting it. - domainRFC('[v1.a]:80') (a bare, no-scheme IPvFuture authority) hit ']' inside the scheme scan before any ':' could trigger the fallback reset, so it never reached bracketed-host parsing at all - unlike the already-working bare IPv6 form '[2001:db8::1]:80', whose internal colons always trigger that reset. Only enter the scheme scan when the first byte is alphabetic; otherwise pos is left at the true start of the input, same as before this branch's IPv6/IPvFuture work began.
checkAndReturnHost rejects a host with a leading dot, but ExtractDomain stripped the "www." prefix after that check ran, so an input like "http://www..com/" passed validation as "www..com" and then had the strip turn it back into ".com" for domainWithoutWWW/domainWithoutWWWRFC. Re-check for a leading dot after stripping and reject in that case.
|
@PedroTadim this is ready for review please. |
…fix-portrfc-ipv6-host-validation
…fix-portrfc-ipv6-host-validation
|
@lizardoluis seems good to merge, one final check |
|
Obrigado @PedroTadim |
Closes: #118890
Related: #118632
Related: #118482
#118632 taught
getURLHostRFCto parse a bracketed IPv6 host, including after auserinfo@prefix, closing #118487. This PR fixes several related bugs that remain in the same parser on top of that fix, found while auditing it against RFC 3986:::ffff:192.168.0.1, or a NAT64 literal64:ff9b::192.0.2.33, was rejected outright, this is the bug reported in RFC URL functions return an empty host for a bracketed IPv6 host with an embedded IPv4 tail ([::ffff:192.168.0.1]) #118890.2001db81was silently accepted as the host.]was checked, so[2001:db8::1]evil.comreturned2001:db8::1as the host.colon_pos/dot_pos/has_terminator_after_coloncarried over across@, so a colon or dot in the userinfo could validate a malformed host afterward using state that actually describes the userinfo.userinfomay legally contain more than one:(RFC 3986), but a second one was read as the host:port separator before the parser ever reached@.@was accepted as another userinfo separator instead of being rejected, even with a port-like:80or a bracketed IPv6 host in between, so[email protected]@evil.com(and variants like[email protected]:[email protected]oruser@[::1]:[email protected]) returned the fake host instead of failing, a URL-confusion/phishing-pattern risk, independent of anything IPv6-specific.., e.g..comor..com, was accepted bycheckAndReturnHost(shared bydomain()anddomainRFC()).port()/portRFC()didn't stop at?or#after the port digits, so a query string or fragment right after an explicit port made them fall back to the default (same fix as the separately open Fix port and portRFC parsing before URL queries and fragments #118482 for reg-name hosts, extended here to also cover bracketed IPv6 hosts, which that PR doesn't touch).firstSignificantSubdomainRFC/cutToFirstSignificantSubdomainRFC(and theirWithWWW/Customvariants) inherited the bracketed IP-literal host fromgetURLHostRFCwith no check that it's actually a DNS name, sofirstSignificantSubdomainRFC('http://[::ffff:192.0.2.128]:80')returned a bogus label carved out of the address instead of empty.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed several
domainRFC/portRFCparsing bugs for URLs with a bracketed IPv6 host: an embedded IPv4 tail (e.g.[::ffff:192.168.0.1]) was rejected, non-IPv6 bracket contents and garbage following the closing bracket were silently accepted, and userinfo state could leak into host validation. Also fixeddomainRFC/portRFCresolving to the wrong host when a URL's userinfo contains more than one@, rejected a host starting with a literal dot indomain()/domainRFC(), and fixedfirstSignificantSubdomainRFC/cutToFirstSignificantSubdomainRFCreturning a bogus subdomain for a bracketed IPv6 host instead of an empty result.Workflow [PR]
Sync PR [sync-upstream/pr/118979]
Version info
26.10.1.53(included in26.10and later)