vendor/guzzlehttp/guzzle/src/Handler/HostValidator.php
198 lines · 7706 bytes
1<?php
2
3namespace GuzzleHttp\Handler;
4
5use GuzzleHttp\Exception\RequestException;
6use Psr\Http\Message\RequestInterface;
7
8/**
9 * Rejects request hosts that a handler could resolve differently from the host
10 * the request names.
11 *
12 * @internal
13 */
14final class HostValidator
15{
16 private function __construct()
17 {
18 }
19
20 /**
21 * Asserts that a request names one unambiguous network host.
22 *
23 * The URI host and every Host header value must use printable ASCII without
24 * percent escapes. The URI host must also exclude authority delimiters and
25 * numeric-looking parts followed by trailing dots. Handlers reparse the URI
26 * but send the Host header as given, so ambiguous spellings can name
27 * different connection and request hosts.
28 *
29 * @throws RequestException
30 */
31 public static function assertRequestHost(RequestInterface $request): void
32 {
33 $host = $request->getUri()->getHost();
34
35 self::assertUriHostValue($host, $request);
36 self::assertNoAuthorityDelimiter($host, $request);
37 self::assertNotADottedAddress($host, $request);
38
39 foreach ($request->getHeader('Host') as $value) {
40 self::assertHostHeaderValue((string) $value, $request);
41 }
42 }
43
44 /**
45 * @throws RequestException
46 */
47 private static function assertUriHostValue(string $value, RequestInterface $request): void
48 {
49 if (!self::isPrintableAscii($value)) {
50 throw new RequestException(\sprintf('The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', self::escape($value)), $request);
51 }
52
53 if (\strpos($value, '%') !== false) {
54 throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler can decode it and then connect to a host that differs from the one the request names.', self::escape($value)), $request);
55 }
56 }
57
58 /**
59 * The Host header is sent rather than reparsed for the connection, so its
60 * diagnostics describe a request authority the caller did not write.
61 *
62 * @throws RequestException
63 */
64 private static function assertHostHeaderValue(string $value, RequestInterface $request): void
65 {
66 if (!self::isPrintableAscii($value)) {
67 throw new RequestException(\sprintf('The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', self::escape($value)), $request);
68 }
69
70 if (\strpos($value, '%') !== false) {
71 throw new RequestException(\sprintf('The request Host header "%s" must not contain a percent escape, because an intermediary or an origin server can decode it and then read it as an authority that differs from the one the request names.', self::escape($value)), $request);
72 }
73 }
74
75 /**
76 * Matches the accepted shape positively so a PCRE failure rejects.
77 */
78 private static function isPrintableAscii(string $value): bool
79 {
80 return \preg_match('/\A[\x21-\x7E]*\z/D', $value) === 1;
81 }
82
83 /**
84 * Rejects a delimiter the transport could treat as the end of the URI host.
85 *
86 * This mirrors GuzzleHttp\Psr7\Uri::assertValidHost() and only affects
87 * third-party UriInterface values. Host headers may carry a port and are
88 * sent verbatim.
89 *
90 * @throws RequestException
91 */
92 private static function assertNoAuthorityDelimiter(string $host, RequestInterface $request): void
93 {
94 $message = 'The request URI host "%s" must not contain a URI authority delimiter, because a handler reparses the URI and can then connect to a host that differs from the one the request names.';
95
96 // Match the accepted shape positively so a PCRE engine failure rejects.
97 if (\preg_match('/\A[^\/?#@\\\\]*\z/D', $host) !== 1) {
98 throw new RequestException(\sprintf($message, self::escape($host)), $request);
99 }
100
101 if (\strpos($host, '[') !== false || \strpos($host, ']') !== false) {
102 if (\strpos($host, '[') !== 0 || \substr($host, -1) !== ']') {
103 throw new RequestException(\sprintf($message, self::escape($host)), $request);
104 }
105
106 return;
107 }
108
109 if (\strpos($host, ':') !== false) {
110 throw new RequestException(\sprintf($message, self::escape($host)), $request);
111 }
112 }
113
114 /**
115 * Rejects one to four numeric-looking parts followed by trailing dots.
116 *
117 * libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric hosts
118 * before connecting, while other validators treat the input as a name.
119 * Testing the shape also rejects some out-of-range values that transports
120 * keep as names; isNumericIpv4Host() explains that fail-closed tradeoff.
121 * Plain numeric shorthand stays accepted.
122 *
123 * @throws RequestException
124 */
125 private static function assertNotADottedAddress(string $host, RequestInterface $request): void
126 {
127 if (\substr($host, -1) !== '.') {
128 return;
129 }
130
131 if (!self::isNumericIpv4Host(\rtrim($host, '.'))) {
132 return;
133 }
134
135 throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request);
136 }
137
138 /**
139 * Reports whether a value has the transport's inet_aton-style shape: one
140 * to four decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts.
141 *
142 * Range and 32-bit overflow checks are deliberately omitted. This may
143 * reject a trailing-dot spelling the transport reads as a name, but avoids
144 * missing one it resolves as an address. No PCRE is used.
145 */
146 public static function isNumericIpv4Host(string $host): bool
147 {
148 if ($host === '') {
149 return false;
150 }
151
152 $parts = \explode('.', $host);
153
154 if (\count($parts) > 4) {
155 return false;
156 }
157
158 foreach ($parts as $part) {
159 if (!self::isNumericIpv4Part($part)) {
160 return false;
161 }
162 }
163
164 return true;
165 }
166
167 private static function isNumericIpv4Part(string $part): bool
168 {
169 if ($part === '') {
170 return false;
171 }
172
173 if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) {
174 return \strlen($part) > 2 && \strspn($part, '0123456789abcdefABCDEF', 2) === \strlen($part) - 2;
175 }
176
177 $digits = $part[0] === '0' ? '01234567' : '0123456789';
178
179 return \strspn($part, $digits) === \strlen($part);
180 }
181
182 /**
183 * Escapes non-printable bytes as uppercase \xNN for safe diagnostics.
184 * Printable delimiters and dots stay visible. The result is not a
185 * reversible encoding.
186 */
187 private static function escape(string $value): string
188 {
189 $escaped = '';
190
191 for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) {
192 $byte = \ord($value[$offset]);
193 $escaped .= $byte >= 0x21 && $byte <= 0x7E ? $value[$offset] : \sprintf('\\x%02X', $byte);
194 }
195
196 return $escaped;
197 }
198}