Completed
Pull Request — master (#157)
by
unknown
02:01
created

TrustedHostsNetworkResolver::process()   F

Complexity

Conditions 29
Paths 8072

Size

Total Lines 102
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 29
eloc 70
nc 8072
nop 2
dl 0
loc 102
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Yiisoft\NetworkUtilities\IpHelper;
12
use Yiisoft\Validator\Rule\Ip;
13
use Yiisoft\Yii\Web\Helper\HeaderHelper;
14
15
class TrustedHostsNetworkResolver implements MiddlewareInterface
16
{
17
    public const IP_HEADER_TYPE_RFC7239 = 'rfc7239';
18
19
    public const DEFAULT_TRUSTED_HEADERS = [
20
        // common:
21
        'x-forwarded-for',
22
        'x-forwarded-host',
23
        'x-forwarded-proto',
24
25
        // RFC:
26
        'forward',
27
28
        // Microsoft:
29
        'front-end-https',
30
        'x-rewrite-url',
31
    ];
32
33
    private const DATA_KEY_HOSTS = 'hosts';
34
    private const DATA_KEY_IP_HEADERS = 'ipHeaders';
35
    private const DATA_KEY_HOST_HEADERS = 'hostHeaders';
36
    private const DATA_KEY_URL_HEADERS = 'urlHeaders';
37
    private const DATA_KEY_PROTOCOL_HEADERS = 'protocolHeaders';
38
    private const DATA_KEY_TRUSTED_HEADERS = 'trustedHeaders';
39
40
    private $trustedHosts = [];
41
42
    /**
43
     * @var string|null
44
     */
45
    private $attributeIps;
46
47
    /**
48
     * @var ResponseFactoryInterface
49
     */
50
    private $responseFactory;
51
    /**
52
     * @var Chain|null
53
     */
54
    private $notTrustedBranch;
55
56
    /**
57
     * @var Ip|null
58
     */
59
    private $ipValidator;
60
61
    public function __construct(ResponseFactoryInterface $responseFactory)
62
    {
63
        $this->responseFactory = $responseFactory;
64
    }
65
66
    /**
67
     * @return static
68
     */
69
    public function withIpValidator(Ip $ipValidator)
70
    {
71
        $new = clone $this;
72
        $ipValidator = clone $ipValidator;
73
        // force disable unacceptable validation
74
        $new->ipValidator = $ipValidator->disallowSubnet()->disallowNegation();
75
        return $new;
76
    }
77
78
    /**
79
     * @return static
80
     */
81
    public function withNotTrustedBranch(?MiddlewareInterface $middleware)
82
    {
83
        $new = clone $this;
84
        $new->notTrustedBranch = $middleware;
85
        return $new;
86
    }
87
88
    /**
89
     * @param string[] $hosts List of trusted hosts IP addresses. If `isValidHost` is extended, then can use
90
     *                        domain names with reverse DNS resolving eg. yiiframework.com, * .yiiframework.com.
91
     * @param array $ipHeaders List of headers containing IP lists.
92
     * @param array $protocolHeaders
93
     * @param string[] $hostHeaders List of headers containing HTTP host.
94
     * @param string[] $urlHeaders List of headers containing HTTP URL.
95
     * @param string[]|null $trustedHeaders List of trusted headers.
96
     * @return static
97
     */
98
    public function withAddedTrustedHosts(
99
        array $hosts,
100
        // Defining default headers is not secure!
101
        array $ipHeaders = [],
102
        array $protocolHeaders = [],
103
        array $hostHeaders = [],
104
        array $urlHeaders = [],
105
        ?array $trustedHeaders = null
106
    ) {
107
        $new = clone $this;
108
        foreach ($ipHeaders as $ipHeader) {
109
            if (\is_string($ipHeader)) {
110
                continue;
111
            }
112
            if (!\is_array($ipHeader)) {
113
                throw new \InvalidArgumentException('Type of ipHeader is not a string and not array');
114
            }
115
            if (count($ipHeader) !== 2) {
116
                throw new \InvalidArgumentException('The ipHeader array must have exactly 2 elements');
117
            }
118
            [$type, $header] = $ipHeader;
119
            if (!\is_string($type)) {
120
                throw new \InvalidArgumentException('The type is not a string');
121
            }
122
            if (!\is_string($header)) {
123
                throw new \InvalidArgumentException('The header is not a string');
124
            }
125
            if ($type === self::IP_HEADER_TYPE_RFC7239) {
126
                continue;
127
            }
128
129
            throw new \InvalidArgumentException("Not supported IP header type: $type");
130
        }
131
        if (count($hosts) === 0) {
132
            throw new \InvalidArgumentException("Empty hosts not allowed");
133
        }
134
        $data = [
135
            self::DATA_KEY_HOSTS => $hosts,
136
            self::DATA_KEY_IP_HEADERS => $ipHeaders,
137
            self::DATA_KEY_PROTOCOL_HEADERS => $this->prepareProtocolHeaders($protocolHeaders),
138
            self::DATA_KEY_TRUSTED_HEADERS => $trustedHeaders ?? self::DEFAULT_TRUSTED_HEADERS,
139
            self::DATA_KEY_HOST_HEADERS => $hostHeaders,
140
            self::DATA_KEY_URL_HEADERS => $urlHeaders,
141
        ];
142
        foreach ([
143
                     self::DATA_KEY_HOSTS,
144
                     self::DATA_KEY_TRUSTED_HEADERS,
145
                     self::DATA_KEY_HOST_HEADERS,
146
                     self::DATA_KEY_URL_HEADERS
147
                 ] as $key) {
148
            $this->checkStringArrayType($data[$key], $key);
149
        }
150
        foreach ($data[self::DATA_KEY_HOSTS] as $host) {
151
            $host = str_replace('*', 'wildcard', $host);        // wildcard is allowed in host
152
            if (filter_var($host, FILTER_VALIDATE_DOMAIN) === false) {
153
                throw new \InvalidArgumentException("'$host' host is not a domain and not an IP address");
154
            }
155
        }
156
        $new->trustedHosts[] = $data;
157
        return $new;
158
    }
159
160
    private function checkStringArrayType(array $array, string $field): void
161
    {
162
        foreach ($array as $item) {
163
            if (!is_string($item)) {
164
                throw new \InvalidArgumentException("$field must be string type");
165
            }
166
            if (trim($item) === '') {
167
                throw new \InvalidArgumentException("$field cannot be empty strings");
168
            }
169
        }
170
    }
171
172
    /**
173
     * @return static
174
     */
175
    public function withoutTrustedHosts()
176
    {
177
        $new = clone $this;
178
        $new->trustedHosts = [];
179
        return $new;
180
    }
181
182
    /**
183
     * @return static
184
     */
185
    public function withAttributeIps(?string $attribute)
186
    {
187
        if ($attribute === '') {
188
            throw new \RuntimeException('Attribute should not be empty');
189
        }
190
        $new = clone $this;
191
        $new->attributeIps = $attribute;
192
        return $new;
193
    }
194
195
    /**
196
     * Process an incoming server request.
197
     *
198
     * Processes an incoming server request in order to produce a response.
199
     * If unable to produce the response itself, it may delegate to the provided
200
     * request handler to do so.
201
     */
202
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
203
    {
204
        $actualHost = $request->getServerParams()['REMOTE_ADDR'];
205
        $trustedHostData = null;
206
        $trustedHeaders = [];
207
        $ipValidator = $this->ipValidator ?? new Ip();
208
        foreach ($this->trustedHosts as $data) {
209
            // collect all trusted headers
210
            $trustedHeaders = array_merge($trustedHeaders, $data[self::DATA_KEY_TRUSTED_HEADERS]);
211
            if ($trustedHostData !== null) {
212
                // trusted hosts already found
213
                continue;
214
            }
215
            if ($this->isValidHost($actualHost, $data[self::DATA_KEY_HOSTS], $ipValidator)) {
216
                $trustedHostData = $data;
217
            }
218
        }
219
        $untrustedHeaders = array_diff($trustedHeaders, $trustedHostData[self::DATA_KEY_TRUSTED_HEADERS] ?? []);
220
        $request = $this->removeHeaders($request, $untrustedHeaders);
221
        if ($trustedHostData === null) {
222
            // No trusted host at all.
223
            if ($this->notTrustedBranch !== null) {
224
                return $this->notTrustedBranch->process($request, $handler);
225
            }
226
            $response = $this->responseFactory->createResponse(412);
227
            $response->getBody()->write('Unable to verify your network.');
228
            return $response;
229
        }
230
        [$ipListType, $ipHeader, $ipList] = $this->getIpList($request, $trustedHostData[self::DATA_KEY_IP_HEADERS]);
231
        $ipList = array_reverse($ipList);       // the first item should be the closest to the server
232
        if ($ipListType === null) {
233
            $ipList = $this->getFormattedIpList($ipList);
234
        } elseif ($ipListType === self::IP_HEADER_TYPE_RFC7239) {
235
            $ipList = $this->getElementsByRfc7239($ipList);
236
        }
237
        array_unshift($ipList, ['ip' => $actualHost]);  // server's ip to first position
238
        $ipDataList = [];
239
        do {
240
            $ipData = array_shift($ipList);
241
            if (!isset($ipData['ip'])) {
242
                $ipData = $this->reverseObfuscate($ipData, $ipDataList, $ipList, $request);
243
                if (!isset($ipData['ip'])) {
244
                    break;
245
                }
246
            }
247
            $ip = $ipData['ip'];
248
            if (!$this->isValidHost($ip, ['any'], $ipValidator)) {
249
                break;
250
            }
251
            $ipDataList[] = $ipData;
252
            if (!$this->isValidHost($ip, $trustedHostData[self::DATA_KEY_HOSTS], $ipValidator)) {
253
                break;
254
            }
255
        } while (count($ipList) > 0);
256
257
        if ($this->attributeIps !== null) {
258
            $request = $request->withAttribute($this->attributeIps, $ipDataList);
259
        }
260
261
        $uri = $request->getUri();
262
        // find HTTP host
263
        foreach ($trustedHostData[self::DATA_KEY_HOST_HEADERS] as $hostHeader) {
264
            if (!$request->hasHeader($hostHeader)) {
265
                continue;
266
            }
267
            if ($hostHeader === $ipHeader && $ipListType === self::IP_HEADER_TYPE_RFC7239 && isset($ipData['httpHost'])) {
268
                $uri = $uri->withHost($ipData['httpHost']);
269
                break;
270
            }
271
            $host = $request->getHeaderLine($hostHeader);
272
            if (filter_var($host, FILTER_VALIDATE_DOMAIN) === false) {
273
                continue;
274
            }
275
            $uri = $uri->withHost($host);
276
        }
277
278
        // find protocol
279
        foreach ($trustedHostData[self::DATA_KEY_PROTOCOL_HEADERS] as $protocolHeader => $protocols) {
280
            if (!$request->hasHeader($protocolHeader)) {
281
                continue;
282
            }
283
            if ($protocolHeader === $ipHeader && $ipListType === self::IP_HEADER_TYPE_RFC7239 && isset($ipData['protocol'])) {
284
                $uri = $uri->withScheme($ipData['protocol']);
285
                break;
286
            }
287
            $protocolHeaderValue = $request->getHeaderLine($protocolHeader);
288
            foreach ($protocols as $protocol => $acceptedValues) {
289
                if (\in_array($protocolHeaderValue, $acceptedValues)) {
290
                    $uri = $uri->withScheme($protocol);
291
                    break 2;
292
                }
293
            }
294
        }
295
        $urlParts = $this->getUrl($request, $trustedHostData[self::DATA_KEY_URL_HEADERS]);
296
        if ($urlParts !== null) {
297
            [$path, $query] = $urlParts;
298
            $uri = $uri->withPath($path);
299
            if ($query !== null) {
300
                $uri = $uri->withQuery($query);
301
            }
302
        }
303
        return $handler->handle($request->withUri($uri)->withAttribute('requestClientIp', $ipData['ip']));
304
    }
305
306
    /**
307
     * Validate host by range
308
     *
309
     * This method can be extendable by overwriting eg. with reverse DNS verification.
310
     */
311
    protected function isValidHost(string $host, array $ranges, Ip $validator): bool
312
    {
313
        return $validator->ranges($ranges)->validate($host)->isValid();
314
    }
315
316
    /**
317
     * Reverse obfuscating host data
318
     *
319
     * The base operation does not perform any transformation on the data.
320
     * This method can be extendable by overwriting eg.
321
     */
322
    protected function reverseObfuscate(
323
        array $ipData,
324
        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

324
        /** @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...
325
        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

325
        /** @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...
326
        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

326
        /** @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...
327
    ): array {
328
        return $ipData;
329
    }
330
331
    private function prepareProtocolHeaders(array $protocolHeaders): array
332
    {
333
        $output = [];
334
        foreach ($protocolHeaders as $header => $protocolAndAcceptedValues) {
335
            $header = strtolower($header);
336
            if (\is_callable($protocolAndAcceptedValues)) {
337
                $output[$header] = $protocolAndAcceptedValues;
338
                continue;
339
            }
340
            if (!\is_array($protocolAndAcceptedValues)) {
341
                throw new \RuntimeException('Accepted values is not an array nor callable');
342
            }
343
            if (count($protocolAndAcceptedValues) === 0) {
344
                throw new \RuntimeException('Accepted values cannot be an empty array');
345
            }
346
            $output[$header] = [];
347
            foreach ($protocolAndAcceptedValues as $protocol => $acceptedValues) {
348
                if (!\is_string($protocol)) {
349
                    throw new \RuntimeException('The protocol must be a string');
350
                }
351
                if ($protocol === '') {
352
                    throw new \RuntimeException('The protocol cannot be empty');
353
                }
354
                $output[$header][$protocol] = array_map('strtolower', (array)$acceptedValues);
355
            }
356
        }
357
        return $output;
358
    }
359
360
    private function removeHeaders(ServerRequestInterface $request, array $headers): ServerRequestInterface
361
    {
362
        foreach ($headers as $header) {
363
            $request = $request->withoutAttribute($header);
364
        }
365
        return $request;
366
    }
367
368
    private function getIpList(RequestInterface $request, array $ipHeaders): array
369
    {
370
        foreach ($ipHeaders as $ipHeader) {
371
            $type = null;
372
            if (\is_array($ipHeader)) {
373
                $type = array_shift($ipHeader);
374
                $ipHeader = array_shift($ipHeader);
375
            }
376
            if ($request->hasHeader($ipHeader)) {
377
                return [$type, $ipHeader, $request->getHeader($ipHeader)];
378
            }
379
        }
380
        return [null, null, []];
381
    }
382
383
    private function getFormattedIpList(array $forwards): array
384
    {
385
        $list = [];
386
        foreach ($forwards as $ip) {
387
            $list[] = ['ip' => $ip];
388
        }
389
        return $list;
390
    }
391
392
    /**
393
     * Forwarded elements by RFC7239
394
     *
395
     * @link https://tools.ietf.org/html/rfc7239
396
     */
397
    private function getElementsByRfc7239(array $forwards): array
398
    {
399
        $list = [];
400
        foreach ($forwards as $forward) {
401
            $data = HeaderHelper::getParameters($forward);
402
            if (!isset($data['for'])) {
403
                // Invalid item, the following items will be dropped
404
                break;
405
            }
406
            $pattern = '/^(?<host>' . IpHelper::IPV4_PATTERN . '|unknown|_[\w\.-]+|[[]' . IpHelper::IPV6_PATTERN . '[]])(?::(?<port>[\w\.-]+))?$/';
407
            if (preg_match($pattern, $data['for'], $matches) === 0) {
408
                // Invalid item, the following items will be dropped
409
                break;
410
            }
411
            $ipData = [];
412
            $host = $matches['host'];
413
            $obfuscatedHost = $host === 'unknown' || strpos($host, '_') === 0;
414
            if (!$obfuscatedHost) {
415
                // IPv4 & IPv6
416
                $ipData['ip'] = strpos($host, '[') === 0 ? trim($host /* IPv6 */, '[]') : $host;
417
            }
418
            $ipData['host'] = $host;
419
            if (isset($matches['port'])) {
420
                $port = $matches['port'];
421
                if (!$obfuscatedHost && (preg_match('/^\d{1,5}$/', $port) === 0 || (int)$port > 65535)) {
422
                    // Invalid port, the following items will be dropped
423
                    break;
424
                }
425
                $ipData['port'] = $obfuscatedHost ? $port : (int)$port;
426
            }
427
428
            // copy other properties
429
            foreach (['proto' => 'protocol', 'host' => 'httpHost', 'by' => 'by'] as $source => $destination) {
430
                if (isset($data[$source])) {
431
                    $ipData[$destination] = $data[$source];
432
                }
433
            }
434
            if (isset($ipData['httpHost']) && filter_var($ipData['httpHost'], FILTER_VALIDATE_DOMAIN) === false) {
435
                // remove not valid HTTP host
436
                unset($ipData['httpHost']);
437
            }
438
439
            $list[] = $ipData;
440
        }
441
        return $list;
442
    }
443
444
    private function getUrl(RequestInterface $request, array $urlHeaders): ?array
445
    {
446
        foreach ($urlHeaders as $header) {
447
            if (!$request->hasHeader($header)) {
448
                continue;
449
            }
450
            $url = $request->getHeaderLine($header);
451
            if (strpos($url, '/') === 0) {
452
                return array_pad(explode('?', $url, 2), 2, null);
453
            }
454
        }
455
        return null;
456
    }
457
}
458