-
Notifications
You must be signed in to change notification settings - Fork 673
/
ServerResponseCheck.php
379 lines (350 loc) · 14.5 KB
/
ServerResponseCheck.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Install\SystemEnvironment\ServerResponse;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\TransferException;
use function GuzzleHttp\Promise\settle;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Core\Crypto\Random;
use TYPO3\CMS\Core\Http\Uri;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Install\Controller\ServerResponseCheckController;
use TYPO3\CMS\Install\SystemEnvironment\CheckInterface;
use TYPO3\CMS\Reports\Status;
/**
* Checks how use web server is interpreting static files concerning
* their `content-type` and evaluated content in HTTP responses.
*
* @internal should only be used from within TYPO3 Core
*/
class ServerResponseCheck implements CheckInterface
{
protected const WRAP_FLAT = 1;
protected const WRAP_NESTED = 2;
/**
* @var bool
*/
protected $useMarkup;
/**
* @var FlashMessageQueue
*/
protected $messageQueue;
/**
* @var FileLocation
*/
protected $assetLocation;
/**
* @var FileLocation
*/
protected $fileadminLocation;
/**
* @var FileDeclaration[]
*/
protected $fileDeclarations;
public function __construct(bool $useMarkup = true)
{
$this->useMarkup = $useMarkup;
$fileName = bin2hex(random_bytes(4));
$folderName = bin2hex(random_bytes(4));
$this->assetLocation = new FileLocation(sprintf('/typo3temp/assets/%s.tmp/', $folderName));
$fileadminDir = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] ?? 'fileadmin', '/');
$this->fileadminLocation = new FileLocation(sprintf('/%s/%s.tmp/', $fileadminDir, $folderName));
$this->fileDeclarations = $this->initializeFileDeclarations($fileName);
}
public function asStatus(): Status
{
$messageQueue = $this->getStatus();
$messages = [];
foreach ($messageQueue->getAllMessages() as $flashMessage) {
$messages[] = $flashMessage->getMessage();
}
$detailsLink = sprintf(
'<p><a href="%s" rel="noreferrer" target="_blank">%s</a></p>',
'https://docs.typo3.org/c/typo3/cms-core/main/en-us/Changelog/9.5.x/Feature-91354-IntegrateServerResponseSecurityChecks.html',
'Please see documentation for further details...'
);
if ($messageQueue->getAllMessages(ContextualFeedbackSeverity::ERROR) !== []) {
$title = 'Potential vulnerabilities';
$label = $detailsLink;
$severity = ContextualFeedbackSeverity::ERROR;
} elseif ($messageQueue->getAllMessages(ContextualFeedbackSeverity::WARNING) !== []) {
$title = 'Warnings';
$label = $detailsLink;
$severity = ContextualFeedbackSeverity::WARNING;
}
return new Status(
'Server Response',
$title ?? 'OK',
$this->wrapList($messages, $label ?? '', self::WRAP_NESTED),
$severity ?? ContextualFeedbackSeverity::OK
);
}
public function getStatus(): FlashMessageQueue
{
$messageQueue = new FlashMessageQueue('install-server-response-check');
if (PHP_SAPI === 'cli-server') {
$messageQueue->addMessage(
new FlashMessage(
'Skipped for PHP_SAPI=cli-server',
'Checks skipped',
ContextualFeedbackSeverity::WARNING
)
);
return $messageQueue;
}
try {
$this->buildFileDeclarations();
$this->processHostCheck($messageQueue);
$this->processFileDeclarations($messageQueue);
$this->finishMessageQueue($messageQueue);
} finally {
$this->purgeFileDeclarations();
}
return $messageQueue;
}
protected function initializeFileDeclarations(string $fileName): array
{
$cspClosure = function (ResponseInterface $response): ?StatusMessage {
$cspHeader = new ContentSecurityPolicyHeader(
$response->getHeaderLine('content-security-policy')
);
if ($cspHeader->isEmpty()) {
return new StatusMessage(
'missing Content-Security-Policy for this location'
);
}
if (!$cspHeader->mitigatesCrossSiteScripting()) {
return new StatusMessage(
'weak Content-Security-Policy for this location "%s"',
$response->getHeaderLine('content-security-policy')
);
}
return null;
};
return [
(new FileDeclaration($this->assetLocation, $fileName . '.html'))
->withExpectedContentType('text/html')
->withExpectedContent('HTML content'),
(new FileDeclaration($this->assetLocation, $fileName . '.wrong'))
->withUnexpectedContentType('text/html')
->withExpectedContent('HTML content'),
(new FileDeclaration($this->assetLocation, $fileName . '.html.wrong'))
->withUnexpectedContentType('text/html')
->withExpectedContent('HTML content'),
(new FileDeclaration($this->assetLocation, $fileName . '.1.svg.wrong'))
->withBuildFlags(FileDeclaration::FLAG_BUILD_SVG | FileDeclaration::FLAG_BUILD_SVG_DOCUMENT)
->withUnexpectedContentType('image/svg+xml')
->withExpectedContent('SVG content'),
(new FileDeclaration($this->assetLocation, $fileName . '.2.svg.wrong'))
->withBuildFlags(FileDeclaration::FLAG_BUILD_SVG | FileDeclaration::FLAG_BUILD_SVG_DOCUMENT)
->withUnexpectedContentType('image/svg')
->withExpectedContent('SVG content'),
(new FileDeclaration($this->assetLocation, $fileName . '.php.wrong', true))
->withBuildFlags(FileDeclaration::FLAG_BUILD_PHP | FileDeclaration::FLAG_BUILD_HTML_DOCUMENT)
->withUnexpectedContent('PHP content'),
(new FileDeclaration($this->assetLocation, $fileName . '.html.txt'))
->withExpectedContentType('text/plain')
->withUnexpectedContentType('text/html')
->withExpectedContent('HTML content'),
(new FileDeclaration($this->assetLocation, $fileName . '.php.txt', true))
->withBuildFlags(FileDeclaration::FLAG_BUILD_PHP | FileDeclaration::FLAG_BUILD_HTML_DOCUMENT)
->withUnexpectedContent('PHP content'),
(new FileDeclaration($this->fileadminLocation, $fileName . '.html'))
->withBuildFlags(FileDeclaration::FLAG_BUILD_HTML_DOCUMENT)
->withHandler($cspClosure),
(new FileDeclaration($this->fileadminLocation, $fileName . '.svg'))
->withBuildFlags(FileDeclaration::FLAG_BUILD_SVG | FileDeclaration::FLAG_BUILD_SVG_DOCUMENT)
->withHandler($cspClosure),
];
}
protected function buildFileDeclarations(): void
{
foreach ($this->fileDeclarations as $fileDeclaration) {
$filePath = $fileDeclaration->getFileLocation()->getFilePath();
if (!is_dir($filePath)) {
GeneralUtility::mkdir_deep($filePath);
}
file_put_contents(
$filePath . $fileDeclaration->getFileName(),
$fileDeclaration->buildContent()
);
}
}
protected function purgeFileDeclarations(): void
{
GeneralUtility::rmdir($this->assetLocation->getFilePath(), true);
GeneralUtility::rmdir($this->fileadminLocation->getFilePath(), true);
}
protected function processHostCheck(FlashMessageQueue $messageQueue): void
{
$random = GeneralUtility::makeInstance(Random::class);
$randomHost = $random->generateRandomHexString(10) . '.random.example.org';
$time = (string)time();
$url = GeneralUtility::makeInstance(UriBuilder::class)->buildUriFromRoute(
'install.server-response-check.host',
['src-time' => $time, 'src-hash' => ServerResponseCheckController::hmac($time)],
UriBuilder::ABSOLUTE_URL
);
try {
$client = new Client(['timeout' => 10]);
$response = $client->request('GET', (string)$url, [
'headers' => ['Host' => $randomHost],
'allow_redirects' => false,
'verify' => false,
]);
} catch (TransferException $exception) {
// it is expected that the previous request fails
return;
}
// in case we end up here, the server processed an HTTP request with invalid HTTP host header
$messageParts = [];
$locationHeader = $response->getHeaderLine('location');
if (!empty($locationHeader) && (new Uri($locationHeader))->getHost() === $randomHost) {
$messageParts[] = sprintf('HTTP Location header contained unexpected "%s"', $randomHost);
}
$data = json_decode((string)$response->getBody(), true);
$serverHttpHost = $data['server.HTTP_HOST'] ?? null;
$serverServerName = $data['server.SERVER_NAME'] ?? null;
if ($serverHttpHost === $randomHost) {
$messageParts[] = sprintf('HTTP_HOST contained unexpected "%s"', $randomHost);
}
if ($serverServerName === $randomHost) {
$messageParts[] = sprintf('SERVER_NAME contained unexpected "%s"', $randomHost);
}
if ($messageParts !== []) {
$messageQueue->addMessage(
new FlashMessage(
$this->wrapList($messageParts, (string)$url, self::WRAP_FLAT),
'Unexpected server response',
ContextualFeedbackSeverity::ERROR
)
);
}
}
protected function processFileDeclarations(FlashMessageQueue $messageQueue): void
{
$promises = [];
$client = new Client(['timeout' => 10]);
foreach ($this->fileDeclarations as $fileDeclaration) {
$promises[] = $client->requestAsync('GET', $fileDeclaration->getUrl());
}
foreach (settle($promises)->wait() as $index => $response) {
$fileDeclaration = $this->fileDeclarations[$index];
if (($response['reason'] ?? null) instanceof BadResponseException) {
$messageQueue->addMessage(
new FlashMessage(
sprintf(
'(%d): %s',
$response['reason']->getCode(),
$response['reason']->getRequest()->getUri()
),
'HTTP warning',
ContextualFeedbackSeverity::WARNING
)
);
continue;
}
if (!($response['value'] ?? null) instanceof ResponseInterface || $fileDeclaration->matches($response['value'])) {
continue;
}
$messageQueue->addMessage(
new FlashMessage(
$this->createMismatchMessage($fileDeclaration, $response['value']),
'Unexpected server response',
$fileDeclaration->shallFail() ? ContextualFeedbackSeverity::ERROR : ContextualFeedbackSeverity::WARNING
)
);
}
}
protected function finishMessageQueue(FlashMessageQueue $messageQueue): void
{
if ($messageQueue->getAllMessages(ContextualFeedbackSeverity::WARNING) !== []
|| $messageQueue->getAllMessages(ContextualFeedbackSeverity::ERROR) !== []) {
return;
}
$messageQueue->addMessage(
new FlashMessage(
sprintf('All %d files processed correctly', count($this->fileDeclarations)),
'Expected server response',
ContextualFeedbackSeverity::OK
)
);
}
protected function createMismatchMessage(FileDeclaration $fileDeclaration, ResponseInterface $response): string
{
$messageParts = array_map(
function (StatusMessage $mismatch): string {
return vsprintf(
$mismatch->getMessage(),
$this->wrapValues($mismatch->getValues(), '<code>', '</code>')
);
},
$fileDeclaration->getMismatches($response)
);
return $this->wrapList($messageParts, $fileDeclaration->getUrl(), self::WRAP_FLAT);
}
protected function wrapList(array $items, string $label, int $style): string
{
if (!$this->useMarkup) {
return sprintf(
'%s%s',
$label ? $label . ': ' : '',
implode(', ', $items)
);
}
if ($style === self::WRAP_NESTED) {
return sprintf(
'%s<ul>%s</ul>',
$label,
implode('', $this->wrapItems($items, '<li>', '</li>'))
);
}
return sprintf(
'<p>%s%s</p>',
$label,
implode('', $this->wrapItems($items, '<br>', ''))
);
}
protected function wrapItems(array $items, string $before, string $after): array
{
return array_map(
function (string $item) use ($before, $after): string {
return $before . $item . $after;
},
array_filter($items)
);
}
protected function wrapValues(array $values, string $before, string $after): array
{
return array_map(
function (string $value) use ($before, $after): string {
return $this->wrapValue($value, $before, $after);
},
array_filter($values)
);
}
protected function wrapValue(string $value, string $before, string $after): string
{
if ($this->useMarkup) {
return $before . htmlspecialchars($value) . $after;
}
return $value;
}
}