-
Notifications
You must be signed in to change notification settings - Fork 16
/
AbstractExceptionHandler.php
222 lines (204 loc) · 8.92 KB
/
AbstractExceptionHandler.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
<?php
/*
* 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\Core\Error;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Http\ApplicationType;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\SysLog\Action as SystemLogGenericAction;
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
/**
* An abstract exception handler
*
* This file is a backport from TYPO3 Flow
*/
abstract class AbstractExceptionHandler implements ExceptionHandlerInterface, SingletonInterface, LoggerAwareInterface
{
use LoggerAwareTrait;
public const CONTEXT_WEB = 'WEB';
public const CONTEXT_CLI = 'CLI';
protected bool $logExceptionStackTrace = false;
protected const IGNORED_EXCEPTION_CODES = [
1396795884, // Current host header value does not match the configured trusted hosts pattern
1616175867, // Backend login request is rate limited
1616175847, // Frontend login request is rate limited
1436717275, // Request with unsupported HTTP method
1699604555, // Outdated __trustedProperties format in extbase property mapping
1517949792, // The IP address of your client does not match the list of allowed IP addresses
1517949793, // Backend access by browser is locked for maintenance
1517949794, // Backend and Install Tool are locked for maintenance
];
public const IGNORED_HMAC_EXCEPTION_CODES = [
1581862822, // Failed HMAC validation due to modified __trustedProperties in extbase property mapping
1581862823, // Failed HMAC validation due to modified form state in ext:forms
1320830018, // Failed HMAC validation due to modified HMAC string in Extbase HashService
1320830276, // Failed HMAC validation due to too short HMAC string in Extbase HashService
1704454157, // Failed HMAC validation due to modified HMAC string in Core HashService
1704454152, // Failed HMAC validation due to too short HMAC string in Core HashService
];
/**
* Displays the given exception
*
* @param \Throwable $exception The throwable object.
*
* @throws \Exception
*/
public function handleException(\Throwable $exception)
{
switch (PHP_SAPI) {
case 'cli':
$this->echoExceptionCLI($exception);
break;
default:
$this->echoExceptionWeb($exception);
}
}
/**
* Writes exception to different logs
*
* @param \Throwable $exception The throwable object.
* @param string $mode The context where the exception was thrown.
* Either self::CONTEXT_WEB or self::CONTEXT_CLI.
*/
protected function writeLogEntries(\Throwable $exception, string $mode): void
{
// Do not write any logs for some messages to avoid filling up tables or files with illegal requests
$ignoredCodes = array_merge(self::IGNORED_EXCEPTION_CODES, self::IGNORED_HMAC_EXCEPTION_CODES);
if (in_array($exception->getCode(), $ignoredCodes, true)) {
return;
}
// PSR-3 logging framework.
try {
if ($this->logger) {
// 'FE' if in FrontendApplication, else 'BE' (also in CLI without request object)
$applicationMode = ($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface
&& ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isFrontend()
? 'FE'
: 'BE';
$requestUrl = $this->anonymizeToken(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));
$this->logger->critical('Core: Exception handler ({mode}: {application_mode}): {exception_class}, code #{exception_code}, file {file}, line {line}: {message}', [
'mode' => $mode,
'application_mode' => $applicationMode,
'exception_class' => get_class($exception),
'exception_code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'message' => $exception->getMessage(),
'request_url' => $requestUrl,
'exception' => $this->logExceptionStackTrace ? $exception : null,
]);
}
} catch (\Exception $exception) {
// A nested exception here was probably caused by a database failure, which means there's little
// else that can be done other than moving on and letting the system hard-fail.
}
// Legacy logger. Remove this section eventually.
$filePathAndName = $exception->getFile();
$exceptionCodeNumber = $exception->getCode() > 0 ? '#' . $exception->getCode() . ': ' : '';
$logTitle = 'Core: Exception handler (' . $mode . ')';
$logMessage = 'Uncaught TYPO3 Exception: ' . $exceptionCodeNumber . $exception->getMessage() . ' | '
. get_class($exception) . ' thrown in file ' . $filePathAndName . ' in line ' . $exception->getLine();
if ($mode === self::CONTEXT_WEB) {
$logMessage .= '. Requested URL: ' . $this->anonymizeToken(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));
}
// When database credentials are wrong, the exception is probably
// caused by this. Therefore we cannot do any database operation,
// otherwise this will lead into recurring exceptions.
try {
// Write error message to sys_log table
$this->writeLog($logTitle . ': ' . $logMessage);
} catch (\Throwable $exception) {
}
}
/**
* Writes an exception in the sys_log table
*
* @param string $logMessage Default text that follows the message.
*/
protected function writeLog(string $logMessage)
{
$connection = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('sys_log');
if (!$connection->isConnected()) {
return;
}
$userId = 0;
$workspace = 0;
$data = [];
$backendUser = $this->getBackendUser();
if ($backendUser !== null) {
if (isset($backendUser->user['uid'])) {
$userId = $backendUser->user['uid'];
}
$workspace = $backendUser->workspace;
if ($backUserId = $backendUser->getOriginalUserIdWhenInSwitchUserMode()) {
$data['originalUser'] = $backUserId;
}
}
$connection->insert(
'sys_log',
[
'userid' => $userId,
'type' => SystemLogType::ERROR,
'channel' => SystemLogType::toChannel(SystemLogType::ERROR),
'action' => SystemLogGenericAction::UNDEFINED,
'error' => SystemLogErrorClassification::SYSTEM_ERROR,
'level' => SystemLogType::toLevel(SystemLogType::ERROR),
'details_nr' => 0,
'details' => str_replace('%', '%%', $logMessage),
'log_data' => empty($data) ? '' : json_encode($data),
'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
'tstamp' => $GLOBALS['EXEC_TIME'],
'workspace' => $workspace,
]
);
}
/**
* Sends the HTTP Status 500 code, if $exception is *not* a
* TYPO3\CMS\Core\Error\Http\StatusException and headers are not sent, yet.
*
* @param \Throwable $exception The throwable object.
*/
protected function sendStatusHeaders(\Throwable $exception)
{
if (method_exists($exception, 'getStatusHeaders')) {
$headers = $exception->getStatusHeaders();
} else {
$headers = [HttpUtility::HTTP_STATUS_500];
}
if (!headers_sent()) {
foreach ($headers as $header) {
header($header);
}
}
}
protected function getBackendUser(): ?BackendUserAuthentication
{
return $GLOBALS['BE_USER'] ?? null;
}
/**
* Replaces the generated token with a generic equivalent
*/
protected function anonymizeToken(string $requestedUrl): string
{
$pattern = '/(?:(?<=[tT]oken=)|(?<=[tT]oken%3D))[0-9a-fA-F]{40}/';
return preg_replace($pattern, '--AnonymizedToken--', $requestedUrl);
}
}