Completed
Pull Request β€” master (#157)
by
unknown
10:28
created

TrustedHostsNetworkResolver::withAttributeIps()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 8
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Yii\Web\Middleware;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseFactoryInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Message\UriInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Yiisoft\NetworkUtilities\IpHelper;
13
use Yiisoft\Validator\Rule\Ip;
14
use Yiisoft\Yii\Web\Helper\HeaderHelper;
15
16
/**
17
 * Trusted hosts network resolver
18
 *
19
 * Code example with comments:
20
 * ```
21
 * (new TrustedHostsNetworkResolver($responseFactory))
22
 * ->withAddedTrustedHosts(
23
 *   // List of secure hosts including $ _SERVER['REMOTE_ADDR'], can specify IPv4, IPv6, domains and aliases (see {{Ip}})
24
 *   ['1.1.1.1', '2.2.2.1/3', '2001::/32', 'localhost']
25
 *   // IP list headers. For advanced handling headers, see the constants IP_HEADER_TYPE_ *.
26
 *   // Headers containing multiple sub-elements (eg RFC 7239) must also be listed for other relevant types
27
 *   // (eg. host headers), otherwise they will only be used as an IP list.
28
 *   ['x-forwarded-for', [TrustedHostsNetworkResolver::IP_HEADER_TYPE_RFC7239, 'forwarded']]
29
 *   // protocol headers with accepted protocols and values. Matching of values ​​is case insensitive.
30
 *   ['front-end-https' => ['https' => 'on']],
31
 *   // Host headers
32
 *   ['forwarded', 'x-forwarded-for']
33
 *   // URL headers
34
 *   ['x-rewrite-url'],
35
 *   // Trusted headers. It is a good idea to list all relevant headers.
36
 *   ['x-forwarded-for', 'forwarded', ...]
37
 * );
38
 * ->withAddedTrustedHosts(...)
39
 * ;
40
 * ```
41
 *
42
 */
43
class TrustedHostsNetworkResolver implements MiddlewareInterface
44
{
45
    public const IP_HEADER_TYPE_RFC7239 = 'rfc7239';
46
47
    public const DEFAULT_TRUSTED_HEADERS = [
48
        // common:
49
        'x-forwarded-for',
50
        'x-forwarded-host',
51
        'x-forwarded-proto',
52
        'x-forwarded-port',
53
54
        // RFC:
55
        'forward',
56
57
        // Microsoft:
58
        'front-end-https',
59
        'x-rewrite-url',
60
    ];
61
62
    private const DATA_KEY_HOSTS = 'hosts';
63
    private const DATA_KEY_IP_HEADERS = 'ipHeaders';
64
    private const DATA_KEY_HOST_HEADERS = 'hostHeaders';
65
    private const DATA_KEY_URL_HEADERS = 'urlHeaders';
66
    private const DATA_KEY_PROTOCOL_HEADERS = 'protocolHeaders';
67
    private const DATA_KEY_TRUSTED_HEADERS = 'trustedHeaders';
68
    private const DATA_KEY_PORT_HEADERS = 'portHeaders';
69
70
    private $trustedHosts = [];
71
72
    /**
73
     * @var string|null
74
     */
75
    private $attributeIps;
76
77
    /**
78
     * @var ResponseFactoryInterface
79
     */
80
    private $responseFactory;
81
82
    /**
83
     * @var Ip|null
84
     */
85
    private $ipValidator;
86
87
    public function __construct(ResponseFactoryInterface $responseFactory)
88
    {
89
        $this->responseFactory = $responseFactory;
90
    }
91
92
    /**
93
     * @return static
94
     */
95
    public function withIpValidator(Ip $ipValidator)
96
    {
97
        $new = clone $this;
98
        $new->ipValidator = $ipValidator;
99
        return $new;
100
    }
101
102
    /**
103
     * With added trusted hosts and related headers
104
     *
105
     * The header lists are evaluated in the order they were specified.
106
     * If you specify multiple headers by type (eg IP headers), you must ensure that the irrelevant header is removed
107
     * eg. web server application, otherwise spoof clients can be use this vulnerability.
108
     *
109
     * @param string[] $hosts List of trusted hosts IP addresses. If `isValidHost` is extended, then can use
110
     *                        domain names with reverse DNS resolving eg. yiiframework.com, * .yiiframework.com.
111
     * @param array $ipHeaders List of headers containing IP lists.
112
     * @param array $protocolHeaders List of headers containing protocol. eg. ['x-forwarded-for' => ['http' => 'http', 'https' => ['on', 'https']]]
113
     * @param string[] $hostHeaders List of headers containing HTTP host.
114
     * @param string[] $urlHeaders List of headers containing HTTP URL.
115
     * @param string[] $portHeaders List of headers containing port number.
116
     * @param string[]|null $trustedHeaders List of trusted headers. Removed from the request, if in checking process
117
     *                                      are classified as untrusted by hosts.
118
     * @return static
119
     */
120
    public function withAddedTrustedHosts(
121
        array $hosts,
122
        // Defining default headers is not secure!
123
        array $ipHeaders = [],
124
        array $protocolHeaders = [],
125
        array $hostHeaders = [],
126
        array $urlHeaders = [],
127
        array $portHeaders = [],
128
        ?array $trustedHeaders = null
129
    ) {
130
        $new = clone $this;
131
        foreach ($ipHeaders as $ipHeader) {
132
            if (\is_string($ipHeader)) {
133
                continue;
134
            }
135
            if (!\is_array($ipHeader)) {
136
                throw new \InvalidArgumentException('Type of ipHeader is not a string and not array');
137
            }
138
            if (count($ipHeader) !== 2) {
139
                throw new \InvalidArgumentException('The ipHeader array must have exactly 2 elements');
140
            }
141
            [$type, $header] = $ipHeader;
142
            if (!\is_string($type)) {
143
                throw new \InvalidArgumentException('The type is not a string');
144
            }
145
            if (!\is_string($header)) {
146
                throw new \InvalidArgumentException('The header is not a string');
147
            }
148
            if ($type === self::IP_HEADER_TYPE_RFC7239) {
149
                continue;
150
            }
151
152
            throw new \InvalidArgumentException("Not supported IP header type: $type");
153
        }
154
        if (count($hosts) === 0) {
155
            throw new \InvalidArgumentException("Empty hosts not allowed");
156
        }
157
        $trustedHeaders = $trustedHeaders ?? self::DEFAULT_TRUSTED_HEADERS;
158
        $protocolHeaders = $this->prepareProtocolHeaders($protocolHeaders);
159
        $this->checkTypeStringOrArray($hosts, 'hosts');
160
        $this->checkTypeStringOrArray($trustedHeaders, 'trustedHeaders');
161
        $this->checkTypeStringOrArray($hostHeaders, 'hostHeaders');
162
        $this->checkTypeStringOrArray($urlHeaders, 'urlHeaders');
163
        $this->checkTypeStringOrArray($portHeaders, 'portHeaders');
164
165
        foreach ($hosts as $host) {
166
            $host = str_replace('*', 'wildcard', $host);        // wildcard is allowed in host
167
            if (filter_var($host, FILTER_VALIDATE_DOMAIN) === false) {
168
                throw new \InvalidArgumentException("'$host' host is not a domain and not an IP address");
169
            }
170
        }
171
        $new->trustedHosts[] = [
172
            self::DATA_KEY_HOSTS => $hosts,
173
            self::DATA_KEY_IP_HEADERS => $ipHeaders,
174
            self::DATA_KEY_PROTOCOL_HEADERS => $protocolHeaders,
175
            self::DATA_KEY_TRUSTED_HEADERS => $trustedHeaders,
176
            self::DATA_KEY_HOST_HEADERS => $hostHeaders,
177
            self::DATA_KEY_URL_HEADERS => $urlHeaders,
178
            self::DATA_KEY_PORT_HEADERS => $portHeaders,
179
        ];
180
        return $new;
181
    }
182
183
    private function checkTypeStringOrArray(array $array, string $field): void
184
    {
185
        foreach ($array as $item) {
186
            if (!is_string($item)) {
187
                throw new \InvalidArgumentException("$field must be string type");
188
            }
189
            if (trim($item) === '') {
190
                throw new \InvalidArgumentException("$field cannot be empty strings");
191
            }
192
        }
193
    }
194
195
    /**
196
     * @return static
197
     */
198
    public function withoutTrustedHosts()
199
    {
200
        $new = clone $this;
201
        $new->trustedHosts = [];
202
        return $new;
203
    }
204
205
    /**
206
     * Request's attribute name to which trusted path data is added.
207
     *
208
     * The list starts with the server and the last item is the client itself.
209
     *
210
     * @return static
211
     * @see getElementsByRfc7239
212
     */
213
    public function withAttributeIps(?string $attribute)
214
    {
215
        if ($attribute === '') {
216
            throw new \RuntimeException('Attribute should not be empty');
217
        }
218
        $new = clone $this;
219
        $new->attributeIps = $attribute;
220
        return $new;
221
    }
222
223
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
224
    {
225
        $actualHost = $request->getServerParams()['REMOTE_ADDR'] ?? null;
226
        if ($actualHost === null) {
227
            // Validation is not possible.
228
            return $this->handleNotTrusted($request, $handler);
229
        }
230
        $trustedHostData = null;
231
        $trustedHeaders = [];
232
        $ipValidator = ($this->ipValidator ?? new Ip())->disallowSubnet()->disallowNegation();
233
        foreach ($this->trustedHosts as $data) {
234
            // collect all trusted headers
235
            $trustedHeaders = array_merge($trustedHeaders, $data[self::DATA_KEY_TRUSTED_HEADERS]);
236
            if ($trustedHostData !== null) {
237
                // trusted hosts already found
238
                continue;
239
            }
240
            if ($this->isValidHost($actualHost, $data[self::DATA_KEY_HOSTS], $ipValidator)) {
241
                $trustedHostData = $data;
242
            }
243
        }
244
        $untrustedHeaders = array_diff($trustedHeaders, $trustedHostData[self::DATA_KEY_TRUSTED_HEADERS] ?? []);
245
        $request = $this->removeHeaders($request, $untrustedHeaders);
246
        if ($trustedHostData === null) {
247
            // No trusted host at all.
248
            return $this->handleNotTrusted($request, $handler);
249
        }
250
        [$ipListType, $ipHeader, $ipList] = $this->getIpList($request, $trustedHostData[self::DATA_KEY_IP_HEADERS]);
251
        $ipList = array_reverse($ipList);       // the first item should be the closest to the server
252
        if ($ipListType === null) {
253
            $ipList = $this->getFormattedIpList($ipList);
254
        } elseif ($ipListType === self::IP_HEADER_TYPE_RFC7239) {
255
            $ipList = $this->getElementsByRfc7239($ipList);
256
        }
257
        array_unshift($ipList, ['ip' => $actualHost]);  // server's ip to first position
258
        $ipDataList = [];
259
        do {
260
            $ipData = array_shift($ipList);
261
            if (!isset($ipData['ip'])) {
262
                $ipData = $this->reverseObfuscate($ipData, $ipDataList, $ipList, $request);
263
                if (!isset($ipData['ip'])) {
264
                    break;
265
                }
266
            }
267
            $ip = $ipData['ip'];
268
            if (!$this->isValidHost($ip, ['any'], $ipValidator)) {
269
                break;
270
            }
271
            $ipDataList[] = $ipData;
272
            if (!$this->isValidHost($ip, $trustedHostData[self::DATA_KEY_HOSTS], $ipValidator)) {
273
                break;
274
            }
275
        } while (count($ipList) > 0);
276
277
        if ($this->attributeIps !== null) {
278
            $request = $request->withAttribute($this->attributeIps, $ipDataList);
279
        }
280
281
        $uri = $request->getUri();
282
        // find HTTP host
283
        foreach ($trustedHostData[self::DATA_KEY_HOST_HEADERS] as $hostHeader) {
284
            if (!$request->hasHeader($hostHeader)) {
285
                continue;
286
            }
287
            if ($hostHeader === $ipHeader && $ipListType === self::IP_HEADER_TYPE_RFC7239 && isset($ipData['httpHost'])) {
288
                $uri = $uri->withHost($ipData['httpHost']);
289
                break;
290
            }
291
            $host = $request->getHeaderLine($hostHeader);
292
            if (filter_var($host, FILTER_VALIDATE_DOMAIN) !== false) {
293
                $uri = $uri->withHost($host);
294
                break;
295
            }
296
        }
297
298
        // find protocol
299
        foreach ($trustedHostData[self::DATA_KEY_PROTOCOL_HEADERS] as $protocolHeader => $protocols) {
300
            if (!$request->hasHeader($protocolHeader)) {
301
                continue;
302
            }
303
            if ($protocolHeader === $ipHeader && $ipListType === self::IP_HEADER_TYPE_RFC7239 && isset($ipData['protocol'])) {
304
                $uri = $uri->withScheme($ipData['protocol']);
305
                break;
306
            }
307
            $protocolHeaderValue = $request->getHeaderLine($protocolHeader);
308
            foreach ($protocols as $protocol => $acceptedValues) {
309
                if (\in_array($protocolHeaderValue, $acceptedValues)) {
310
                    $uri = $uri->withScheme($protocol);
311
                    break 2;
312
                }
313
            }
314
        }
315
        $urlParts = $this->getUrl($request, $trustedHostData[self::DATA_KEY_URL_HEADERS]);
316
        if ($urlParts !== null) {
317
            [$path, $query] = $urlParts;
318
            $uri = $uri->withPath($path);
319
            if ($query !== null) {
320
                $uri = $uri->withQuery($query);
321
            }
322
        }
323
324
        // find port
325
        foreach ($trustedHostData[self::DATA_KEY_PORT_HEADERS] as $portHeader) {
326
            if (!$request->hasHeader($portHeader)) {
327
                continue;
328
            }
329
            if ($portHeader === $ipHeader && $ipListType === self::IP_HEADER_TYPE_RFC7239 && isset($ipData['port']) && $this->checkPort($ipData['port'])) {
330
                $uri = $uri->withPort($ipData['port']);
331
                break;
332
            }
333
            $port = $request->getHeaderLine($portHeader);
334
            if ($this->checkPort($port)) {
335
                $uri = $uri->withPort($port);
0 ignored issues
show
Bug introduced by
$port of type string is incompatible with the type integer|null expected by parameter $port of Psr\Http\Message\UriInterface::withPort(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

335
                $uri = $uri->withPort(/** @scrutinizer ignore-type */ $port);
Loading history...
336
                break;
337
            }
338
        }
339
340
        return $handler->handle($request->withUri($uri)->withAttribute('requestClientIp', $ipData['ip']));
341
    }
342
343
    /**
344
     * Validate host by range
345
     *
346
     * This method can be extendable by overwriting eg. with reverse DNS verification.
347
     */
348
    protected function isValidHost(string $host, array $ranges, Ip $validator): bool
349
    {
350
        return $validator->ranges($ranges)->validate($host)->isValid();
351
    }
352
353
    /**
354
     * Reverse obfuscating host data
355
     *
356
     * The base operation does not perform any transformation on the data.
357
     * This method can be extendable by overwriting eg.
358
     *
359
     * The `$ipData` array must contain relevant keys (eg` ip`) for the validation process ({{isValidHost}}) to process the request.
360
     *
361
     * @see getElementsByRfc7239
362
     */
363
    protected function reverseObfuscate(
364
        array $ipData,
365
        array $ipDataListValidated,
0 ignored issues
show
Unused Code introduced by
The parameter $ipDataListValidated is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

365
        /** @scrutinizer ignore-unused */ array $ipDataListValidated,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
366
        array $ipDataListRemaining,
0 ignored issues
show
Unused Code introduced by
The parameter $ipDataListRemaining is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

366
        /** @scrutinizer ignore-unused */ array $ipDataListRemaining,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
367
        RequestInterface $request
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

367
        /** @scrutinizer ignore-unused */ RequestInterface $request

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
368
    ): array {
369
        return $ipData;
370
    }
371
372
    private function handleNotTrusted(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
373
    {
374
        if ($this->attributeIps !== null) {
375
            $request = $request->withAttribute($this->attributeIps, null);
376
        }
377
        return $handler->handle($request->withAttribute('requestClientIp', null));
378
    }
379
380
    private function prepareProtocolHeaders(array $protocolHeaders): array
381
    {
382
        $output = [];
383
        foreach ($protocolHeaders as $header => $protocolAndAcceptedValues) {
384
            $header = strtolower($header);
385
            if (\is_callable($protocolAndAcceptedValues)) {
386
                $output[$header] = $protocolAndAcceptedValues;
387
                continue;
388
            }
389
            if (!\is_array($protocolAndAcceptedValues)) {
390
                throw new \RuntimeException('Accepted values is not an array nor callable');
391
            }
392
            if (count($protocolAndAcceptedValues) === 0) {
393
                throw new \RuntimeException('Accepted values cannot be an empty array');
394
            }
395
            $output[$header] = [];
396
            foreach ($protocolAndAcceptedValues as $protocol => $acceptedValues) {
397
                if (!\is_string($protocol)) {
398
                    throw new \RuntimeException('The protocol must be a string');
399
                }
400
                if ($protocol === '') {
401
                    throw new \RuntimeException('The protocol cannot be empty');
402
                }
403
                $output[$header][$protocol] = array_map('strtolower', (array)$acceptedValues);
404
            }
405
        }
406
        return $output;
407
    }
408
409
    private function removeHeaders(ServerRequestInterface $request, array $headers): ServerRequestInterface
410
    {
411
        foreach ($headers as $header) {
412
            $request = $request->withoutAttribute($header);
413
        }
414
        return $request;
415
    }
416
417
    private function getIpList(RequestInterface $request, array $ipHeaders): array
418
    {
419
        foreach ($ipHeaders as $ipHeader) {
420
            $type = null;
421
            if (\is_array($ipHeader)) {
422
                $type = array_shift($ipHeader);
423
                $ipHeader = array_shift($ipHeader);
424
            }
425
            if ($request->hasHeader($ipHeader)) {
426
                return [$type, $ipHeader, $request->getHeader($ipHeader)];
427
            }
428
        }
429
        return [null, null, []];
430
    }
431
432
    /**
433
     * @see getElementsByRfc7239
434
     */
435
    private function getFormattedIpList(array $forwards): array
436
    {
437
        $list = [];
438
        foreach ($forwards as $ip) {
439
            $list[] = ['ip' => $ip];
440
        }
441
        return $list;
442
    }
443
444
    /**
445
     * Forwarded elements by RFC7239
446
     *
447
     * The structure of the elements:
448
     * - `host`: IP or obfuscated hostname or "unknown"
449
     * - `ip`: IP address (only if presented)
450
     * - `by`: used user-agent by proxy (only if presented)
451
     * - `port`: port number received by proxy (only if presented)
452
     * - `protocol`: protocol received by proxy (only if presented)
453
     * - `httpHost`: HTTP host received by proxy (only if presented)
454
     *
455
     * @link https://tools.ietf.org/html/rfc7239
456
     * @return array proxy data elements
457
     */
458
    private function getElementsByRfc7239(array $forwards): array
459
    {
460
        $list = [];
461
        foreach ($forwards as $forward) {
462
            $data = HeaderHelper::getParameters($forward);
463
            if (!isset($data['for'])) {
464
                // Invalid item, the following items will be dropped
465
                break;
466
            }
467
            $pattern = '/^(?<host>' . IpHelper::IPV4_PATTERN . '|unknown|_[\w\.-]+|[[]' . IpHelper::IPV6_PATTERN . '[]])(?::(?<port>[\w\.-]+))?$/';
468
            if (preg_match($pattern, $data['for'], $matches) === 0) {
469
                // Invalid item, the following items will be dropped
470
                break;
471
            }
472
            $ipData = [];
473
            $host = $matches['host'];
474
            $obfuscatedHost = $host === 'unknown' || strpos($host, '_') === 0;
475
            if (!$obfuscatedHost) {
476
                // IPv4 & IPv6
477
                $ipData['ip'] = strpos($host, '[') === 0 ? trim($host /* IPv6 */, '[]') : $host;
478
            }
479
            $ipData['host'] = $host;
480
            if (isset($matches['port'])) {
481
                $port = $matches['port'];
482
                if (!$obfuscatedHost && !$this->checkPort($port)) {
483
                    // Invalid port, the following items will be dropped
484
                    break;
485
                }
486
                $ipData['port'] = $obfuscatedHost ? $port : (int)$port;
487
            }
488
489
            // copy other properties
490
            foreach (['proto' => 'protocol', 'host' => 'httpHost', 'by' => 'by'] as $source => $destination) {
491
                if (isset($data[$source])) {
492
                    $ipData[$destination] = $data[$source];
493
                }
494
            }
495
            if (isset($ipData['httpHost']) && filter_var($ipData['httpHost'], FILTER_VALIDATE_DOMAIN) === false) {
496
                // remove not valid HTTP host
497
                unset($ipData['httpHost']);
498
            }
499
500
            $list[] = $ipData;
501
        }
502
        return $list;
503
    }
504
505
    private function getUrl(RequestInterface $request, array $urlHeaders): ?array
506
    {
507
        foreach ($urlHeaders as $header) {
508
            if (!$request->hasHeader($header)) {
509
                continue;
510
            }
511
            $url = $request->getHeaderLine($header);
512
            if (strpos($url, '/') === 0) {
513
                return array_pad(explode('?', $url, 2), 2, null);
514
            }
515
        }
516
        return null;
517
    }
518
519
    private function checkPort(string $port): bool
520
    {
521
        return preg_match('/^\d{1,5}$/', $port) === 1 && (int)$port <= 65535;
522
    }
523
}
524