-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCsrfProtection.php
277 lines (238 loc) · 8.77 KB
/
CsrfProtection.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
<?php
/*
START LICENSE AND COPYRIGHT
This file is part of ZfExtended library
Copyright (c) 2013 - 2022 Marc Mittag; MittagQI - Quality Informatics; All rights reserved.
Contact: http://www.MittagQI.com/ / service (ATT) MittagQI.com
This file may be used under the terms of the GNU LESSER GENERAL PUBLIC LICENSE version 3
as published by the Free Software Foundation and appearing in the file lgpl3-license.txt
included in the packaging of this file. Please review the following information
to ensure the GNU LESSER GENERAL PUBLIC LICENSE version 3.0 requirements will be met:
https://www.gnu.org/licenses/lgpl-3.0.txt
@copyright Marc Mittag, MittagQI - Quality Informatics
@author MittagQI - Quality Informatics
@license GNU LESSER GENERAL PUBLIC LICENSE version 3
https://www.gnu.org/licenses/lgpl-3.0.txt
END LICENSE AND COPYRIGHT
*/
namespace MittagQI\ZfExtended;
use Exception;
use Zend_Controller_Request_Exception;
use Zend_Controller_Request_Http;
use Zend_Exception;
use Zend_Http_Client;
use Zend_Http_Client_Exception;
use Zend_Registry;
use Zend_Session_Namespace;
use ZfExtended_Authentication;
use ZfExtended_Exception;
use ZfExtended_NotAuthenticatedException;
/**
* Handles the token that secures API requests in the client against CSRF attacks
* This CSRF protection is active for all Endpoints of controllers inherited from ZfExtended_RestController,
* other endpoints must implement on their own to be secured
* The CSRF protection expects all requests to be sent with a header-field "CsrfToken" to contain the valid token
* This token then is validated against the token stored in the session (or in a temporary
* token-file in case of an API-test)
*/
final class CsrfProtection
{
/**
* The name of the header field
*/
public const HEADER_NAME = 'CsrfToken';
/**
* Dev option to completely deactivate feature. Must be true for production !!
*/
public const ACTIVE = true;
/**
* The file to store the token for API-tests
*/
public const APITEST_TOKENFILE = 'apitest-csrf.token';
public const ERRORS = [
'E1505' => 'The CSRF-token was empty',
'E1506' => 'The sent CSRF test-token "{token}" does not match the stored token {storedToken}',
'E1507' => 'The sent CSRF token "{token}" does not match the session token: "{storedToken}"',
'E1508' => 'The CSRF test-token-file "{tokenFile}" is missing or not readable',
'E1509' => 'The request had no {header} header',
];
private bool $isApiTest;
/**
* To be called by API-test commands to generate a token and save it to the test token-file
* This file will be the store of the token when running tests instead of the session
* @throws Zend_Exception
* @throws ZfExtended_Exception
* @throws Exception
*/
public static function createApiTestToken(): string
{
$config = Zend_Registry::get('config');
$tokenFile = $config->runtimeOptions->dir->tmp . '/' . self::APITEST_TOKENFILE;
$token = self::generateToken();
if (! file_put_contents($tokenFile, $token)) {
throw new ZfExtended_Exception(
'CsrfProtection::createApiTestToken: Could not generate token-file in tmp-dir ' . $tokenFile
);
}
// this API is probably called as root, the token must be readable for the apache user nevertheless
chmod($tokenFile, 0777);
return $token;
}
/**
* @throws Exception
*/
private static function generateToken(): string
{
return bin2hex(random_bytes(20));
}
private static ?self $instance = null;
public static function getInstance(): self
{
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
$this->isApiTest = defined('APPLICATION_APITEST') && APPLICATION_APITEST;
}
public function isActive(): bool
{
if (self::ACTIVE) {
// Crucial: if a request was initiated with an app-token, CSRF protection must be inactive
return ! ZfExtended_Authentication::getInstance()->isAuthenticatedByToken();
}
return false;
}
/**
* @throws Zend_Exception
* @throws Zend_Http_Client_Exception
* @throws ZfExtended_NotAuthenticatedException
* @throws Exception
*/
public function addRequestHeaders(Zend_Http_Client $client): void
{
if ($this->isActive()) {
$token = $this->isApiTest ? $this->getApiTestToken() : $this->getToken();
$client->setHeaders(self::HEADER_NAME, $token);
}
}
/**
* @throws ZfExtended_NotAuthenticatedException
* @throws Zend_Exception
* @throws Exception
*/
public function getHeaderString(): string
{
if ($this->isActive()) {
$token = $this->isApiTest ? $this->getApiTestToken() : $this->getToken();
return self::HEADER_NAME . ': ' . $token . "\r\n";
}
return '';
}
/**
* @throws Zend_Exception
* @throws ZfExtended_NotAuthenticatedException
* @throws Zend_Controller_Request_Exception
*/
public function validateRequest(Zend_Controller_Request_Http $request): bool
{
if ($this->isActive()) {
$token = $request->getHeader(self::HEADER_NAME);
// Non-XHR forms can send the token only as normal param
if (! $token && $request->isPost() && $request->getPost(self::HEADER_NAME) !== null) {
$token = $request->getPost(self::HEADER_NAME);
}
if (! $token) {
$this->throwException('E1509', [
'header' => self::HEADER_NAME,
]);
}
return $this->validateToken($token);
}
return true;
}
/**
* @throws Zend_Exception
* @throws ZfExtended_NotAuthenticatedException
*/
public function validateToken(string $token): bool
{
if ($this->isActive()) {
$session = $this->getSession();
if (empty($token)) {
$this->throwException('E1505');
}
// compare token with the session token or a file-based token in case of unit tests
if ($session->token !== $token) {
// we may be in an API-test, let's check
if ($this->isApiTest) {
// when API-testing, the token is stored in a temporary file for the test
$storedToken = $this->getApiTestToken();
if ($storedToken === $token) {
return true;
}
$this->throwException('E1506', [
'token' => $token,
'storedToken' => $storedToken,
]);
} else {
$this->throwException('E1507', [
'token' => $token,
'storedToken' => ($session->token ?? 'NO SESSION TOKEN SET'),
]);
}
}
}
return true;
}
/**
* Retrieves the current CSRF token and starts the session for it
* This API must only be used in IndexController where the app is served
* This is not suitable to retrieve a token as used in api-tests
* @throws Exception
*/
public function getToken(): string
{
if ($this->isActive()) {
$session = $this->getSession();
if (empty($session->token)) {
$session->token = self::generateToken();
}
return $session->token;
}
return '';
}
/**
* Retrieves the CSRF token in an api-test scenario
* @throws Zend_Exception
* @throws ZfExtended_NotAuthenticatedException
*/
private function getApiTestToken(): string
{
$config = Zend_Registry::get('config');
$tokenFile = $config->runtimeOptions->dir->tmp . '/' . self::APITEST_TOKENFILE;
$token = file_exists($tokenFile) ? file_get_contents($tokenFile) : false;
if (! $token) {
$this->throwException('E1508', [
'tokenFile' => $tokenFile,
]);
}
return $token;
}
/**
* @throws Zend_Exception
* @throws ZfExtended_NotAuthenticatedException
*/
private function throwException(string $ecode, array $extra = null)
{
Zend_Registry::get('logger')->error($ecode, 'CSRF Protection failed: ' . self::ERRORS[$ecode], $extra);
// We expose no security related infos to the browser
throw new ZfExtended_NotAuthenticatedException();
}
private function getSession(): Zend_Session_Namespace
{
return new Zend_Session_Namespace('csrf');
}
}