Rev 1306 | Rev 1308 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
566 | daniel-mar | 1 | <?php |
2 | |||
3 | /* |
||
4 | * OIDplus 2.0 |
||
1086 | daniel-mar | 5 | * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft |
566 | daniel-mar | 6 | * |
7 | * Licensed under the Apache License, Version 2.0 (the "License"); |
||
8 | * you may not use this file except in compliance with the License. |
||
9 | * You may obtain a copy of the License at |
||
10 | * |
||
11 | * http://www.apache.org/licenses/LICENSE-2.0 |
||
12 | * |
||
13 | * Unless required by applicable law or agreed to in writing, software |
||
14 | * distributed under the License is distributed on an "AS IS" BASIS, |
||
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||
16 | * See the License for the specific language governing permissions and |
||
17 | * limitations under the License. |
||
18 | */ |
||
19 | |||
1050 | daniel-mar | 20 | namespace ViaThinkSoft\OIDplus; |
566 | daniel-mar | 21 | |
1086 | daniel-mar | 22 | // phpcs:disable PSR1.Files.SideEffects |
23 | \defined('INSIDE_OIDPLUS') or die; |
||
24 | // phpcs:enable PSR1.Files.SideEffects |
||
25 | |||
1303 | daniel-mar | 26 | /** |
1305 | daniel-mar | 27 | * Auth content store for JWT tokens (web browser login cookies, Automated AJAX argument, or REST Bearer) |
1303 | daniel-mar | 28 | */ |
1306 | daniel-mar | 29 | class OIDplusAuthContentStoreJWT implements OIDplusGetterSetterInterface { |
566 | daniel-mar | 30 | |
1130 | daniel-mar | 31 | /** |
32 | * Cookie name for the JWT auth token |
||
33 | */ |
||
585 | daniel-mar | 34 | const COOKIE_NAME = 'OIDPLUS_AUTH_JWT'; |
35 | |||
1130 | daniel-mar | 36 | /** |
1305 | daniel-mar | 37 | * Token generator; must be one of OIDplusAuthContentStoreJWT::JWT_GENERATOR_* |
38 | */ |
||
39 | const CLAIM_GENERATOR = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.7.1'; |
||
40 | |||
41 | /** |
||
42 | * List of logged-in users |
||
43 | */ |
||
44 | const CLAIM_LOGIN_LIST = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.7.2'; |
||
45 | |||
46 | /** |
||
47 | * SSH = Server Secret Hash |
||
48 | */ |
||
49 | const CLAIM_SSH = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.7.3'; |
||
50 | |||
51 | /** |
||
52 | * IP-Adress limit |
||
53 | */ |
||
54 | const CLAIM_LIMIT_IP = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.7.4'; |
||
55 | |||
56 | /** |
||
1130 | daniel-mar | 57 | * "Automated AJAX" plugin |
58 | */ |
||
1265 | daniel-mar | 59 | const JWT_GENERATOR_AJAX = 10; |
1130 | daniel-mar | 60 | /** |
1265 | daniel-mar | 61 | * "REST API" plugin |
62 | */ |
||
63 | const JWT_GENERATOR_REST = 20; |
||
64 | /** |
||
1305 | daniel-mar | 65 | * Web browser login method |
1130 | daniel-mar | 66 | */ |
1265 | daniel-mar | 67 | const JWT_GENERATOR_LOGIN = 40; |
1130 | daniel-mar | 68 | /** |
69 | * "Manually crafted" JWT tokens |
||
70 | */ |
||
1265 | daniel-mar | 71 | const JWT_GENERATOR_MANUAL = 80; |
585 | daniel-mar | 72 | |
1116 | daniel-mar | 73 | /** |
74 | * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_... |
||
75 | * @param string $sub |
||
76 | * @return string |
||
77 | */ |
||
78 | private static function jwtGetBlacklistConfigKey(int $gen, string $sub): string { |
||
1265 | daniel-mar | 79 | // Note: Needs to be <= 50 characters! If $gen is 2 chars, then the config key is 49 chars long |
585 | daniel-mar | 80 | return 'jwt_blacklist_gen('.$gen.')_sub('.trim(base64_encode(md5($sub,true)),'=').')'; |
81 | } |
||
82 | |||
1116 | daniel-mar | 83 | /** |
1265 | daniel-mar | 84 | * @param int $gen |
85 | */ |
||
86 | private static function generatorName($gen) { |
||
87 | // Note: The strings are not translated, because the name is used in config keys or logs |
||
88 | if ($gen === self::JWT_GENERATOR_AJAX) return 'Automated AJAX calls'; |
||
89 | if ($gen === self::JWT_GENERATOR_REST) return 'REST API'; |
||
1305 | daniel-mar | 90 | if ($gen === self::JWT_GENERATOR_LOGIN) return 'Browser login'; |
1265 | daniel-mar | 91 | if ($gen === self::JWT_GENERATOR_MANUAL) return 'Manually created'; |
92 | return 'Unknown generator'; |
||
93 | } |
||
94 | |||
95 | /** |
||
1116 | daniel-mar | 96 | * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_... |
97 | * @param string $sub |
||
98 | * @return void |
||
99 | * @throws OIDplusException |
||
100 | */ |
||
101 | public static function jwtBlacklist(int $gen, string $sub) { |
||
585 | daniel-mar | 102 | $cfg = self::jwtGetBlacklistConfigKey($gen, $sub); |
103 | $bl_time = time()-1; |
||
104 | |||
1265 | daniel-mar | 105 | $gen_desc = self::generatorName($gen); |
585 | daniel-mar | 106 | |
1305 | daniel-mar | 107 | OIDplus::config()->prepareConfigKey($cfg, "Revoke timestamp of all JWT tokens for $sub with generator $gen ($gen_desc)", "$bl_time", OIDplusConfig::PROTECTION_HIDDEN, function($value) {}); |
585 | daniel-mar | 108 | OIDplus::config()->setValue($cfg, $bl_time); |
109 | } |
||
110 | |||
1116 | daniel-mar | 111 | /** |
112 | * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_... |
||
113 | * @param string $sub |
||
114 | * @return int |
||
115 | * @throws OIDplusException |
||
116 | */ |
||
117 | public static function jwtGetBlacklistTime(int $gen, string $sub): int { |
||
585 | daniel-mar | 118 | $cfg = self::jwtGetBlacklistConfigKey($gen, $sub); |
1116 | daniel-mar | 119 | return (int)OIDplus::config()->getValue($cfg,0); |
585 | daniel-mar | 120 | } |
121 | |||
1116 | daniel-mar | 122 | /** |
1298 | daniel-mar | 123 | * We include a hash of the server-secret here (ssh = server-secret-hash), so that the JWT can be invalidated by changing the server-secret |
124 | * @return string |
||
125 | * @throws OIDplusException |
||
126 | */ |
||
127 | private static function getSsh(): string { |
||
1305 | daniel-mar | 128 | $hexadecimal_string = OIDplus::authUtils()->makeSecret(['bb1aebd6-fe6a-11ed-a553-3c4a92df8582']); |
129 | return base64_encode(pack('H*',$hexadecimal_string)); |
||
1298 | daniel-mar | 130 | } |
131 | |||
132 | /** |
||
1265 | daniel-mar | 133 | * Do various checks if the token is allowed and not blacklisted |
1305 | daniel-mar | 134 | * @param OIDplusAuthContentStoreJWT $contentProvider |
1277 | daniel-mar | 135 | * @param int|null $validGenerators Bitmask which generators to allow (null = allow all) |
1116 | daniel-mar | 136 | * @return void |
137 | * @throws OIDplusException |
||
138 | */ |
||
1305 | daniel-mar | 139 | private static function jwtSecurityCheck(OIDplusAuthContentStoreJWT $contentProvider, int $validGenerators=null) { |
585 | daniel-mar | 140 | // Check if the token is intended for us |
1307 | daniel-mar | 141 | // Note 'aud' is mandatory, so we do not check of exists() |
699 | daniel-mar | 142 | if ($contentProvider->getValue('aud','') !== OIDplus::getEditionInfo()['jwtaud']) { |
585 | daniel-mar | 143 | throw new OIDplusException(_L('Token has wrong audience')); |
144 | } |
||
1298 | daniel-mar | 145 | |
1307 | daniel-mar | 146 | // Note CLAIM_SSH is mandatory, so we do not check of exists() |
1305 | daniel-mar | 147 | if ($contentProvider->getValue(self::CLAIM_SSH, '') !== self::getSsh()) { |
1298 | daniel-mar | 148 | throw new OIDplusException(_L('"Server Secret" was changed; therefore the JWT is not valid anymore')); |
149 | } |
||
150 | |||
1307 | daniel-mar | 151 | // Note CLAIM_GENERATOR is mandatory, so we do not check of exists() |
1305 | daniel-mar | 152 | $gen = $contentProvider->getValue(self::CLAIM_GENERATOR, -1); |
585 | daniel-mar | 153 | |
154 | $has_admin = $contentProvider->isAdminLoggedIn(); |
||
155 | $has_ra = $contentProvider->raNumLoggedIn() > 0; |
||
156 | |||
157 | // Check if the token generator is allowed |
||
158 | if ($gen === self::JWT_GENERATOR_AJAX) { |
||
159 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_AJAX_ADMIN', true)) { |
||
635 | daniel-mar | 160 | // Generator: plugins/viathinksoft/adminPages/910_automated_ajax_calls/OIDplusPageAdminAutomatedAJAXCalls.class.php |
585 | daniel-mar | 161 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_AJAX_ADMIN')); |
162 | } |
||
163 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_AJAX_USER', true)) { |
||
635 | daniel-mar | 164 | // Generator: plugins/viathinksoft/raPages/910_automated_ajax_calls/OIDplusPageRaAutomatedAJAXCalls.class.php |
585 | daniel-mar | 165 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_AJAX_USER')); |
166 | } |
||
167 | } |
||
1265 | daniel-mar | 168 | else if ($gen === self::JWT_GENERATOR_REST) { |
169 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_REST_ADMIN', true)) { |
||
170 | // Generator: plugins/viathinksoft/adminPages/911_rest_api/OIDplusPageAdminRestApi.class.php |
||
171 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_REST_ADMIN')); |
||
172 | } |
||
173 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_REST_USER', true)) { |
||
174 | // Generator: plugins/viathinksoft/raPages/911_rest_api/OIDplusPageRaRestApi.class.php |
||
175 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_REST_USER')); |
||
176 | } |
||
177 | } |
||
585 | daniel-mar | 178 | else if ($gen === self::JWT_GENERATOR_LOGIN) { |
1305 | daniel-mar | 179 | // Used for web browser login (use JWT token in a cookie as alternative to PHP session): |
585 | daniel-mar | 180 | // - No PHP session will be used |
181 | // - Session will not be bound to IP address (therefore, you can switch between mobile/WiFi for example) |
||
182 | // - No server-side session needed |
||
183 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) { |
||
184 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_ADMIN')); |
||
185 | } |
||
186 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) { |
||
187 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_USER')); |
||
188 | } |
||
189 | } |
||
190 | else if ($gen === self::JWT_GENERATOR_MANUAL) { |
||
1300 | daniel-mar | 191 | // Generator: "hand-crafted" tokens |
192 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_MANUAL_ADMIN', false)) { |
||
193 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_MANUAL_ADMIN')); |
||
585 | daniel-mar | 194 | } |
1300 | daniel-mar | 195 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_MANUAL_USER', false)) { |
196 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_MANUAL_USER')); |
||
197 | } |
||
585 | daniel-mar | 198 | } else { |
199 | throw new OIDplusException(_L('Token generator %1 not recognized',$gen)); |
||
200 | } |
||
201 | |||
1307 | daniel-mar | 202 | // Every token must have and issued timestamp |
203 | $iat = $contentProvider->getValue('iat',null); |
||
204 | if (is_null($iat)) { |
||
205 | throw new OIDplusException(_L('The claim "%1" of the JWT token is missing or invalid','iat')); |
||
206 | } |
||
207 | |||
208 | // Verify that IAT has a valid value |
||
209 | // Note: This check is already done in Firebase\JWT. However, we do it again, just to be 100% sure. |
||
210 | if (($iat-120/*leeway 2min*/) > time()) { |
||
211 | // Token was created in the future. Something is wrong! |
||
212 | throw new OIDplusException(_L('JWT Token cannot be verified because the server time is wrong')); |
||
213 | } |
||
214 | |||
215 | // Check if token is not yet valid |
||
216 | // Note: This check is already done in Firebase\JWT. However, we do it again, just to be 100% sure. |
||
217 | $nbf = $contentProvider->getValue('nbf',null); |
||
218 | if (!is_null($nbf)) { |
||
219 | if (time() < $nbf-120/*leeway 2min*/) { |
||
220 | throw new OIDplusException(_L('Token not valid before %1',date('d F Y, H:i:s',$nbf))); |
||
221 | } |
||
222 | } |
||
223 | |||
1306 | daniel-mar | 224 | // Check if token has expired |
1307 | daniel-mar | 225 | // Note: This check is already done in Firebase\JWT. However, we do it again, just to be 100% sure. |
1306 | daniel-mar | 226 | $exp = $contentProvider->getValue('exp',null); |
227 | if (!is_null($exp)) { |
||
1307 | daniel-mar | 228 | if (time() > $exp+120/*leeway 2min*/) { |
1306 | daniel-mar | 229 | throw new OIDplusException(_L('Token has expired on %1',date('d F Y, H:i:s',$exp))); |
230 | } |
||
231 | } |
||
232 | |||
585 | daniel-mar | 233 | // Make sure that the IAT (issued at time) isn't in a blacklisted timeframe |
234 | // When an user believes that a token was compromised, then they can blacklist the tokens identified by their "iat" ("Issued at") property |
||
1305 | daniel-mar | 235 | // When a user logs out of a web browser session, the JWT token will be blacklisted as well |
236 | // Small side effect: All web browser login sessions of that user will be revoked then |
||
585 | daniel-mar | 237 | $sublist = $contentProvider->loggedInRaList(); |
1281 | daniel-mar | 238 | $usernames = array(); |
239 | foreach ($sublist as $sub) { |
||
240 | $usernames[] = $sub->raEmail(); |
||
585 | daniel-mar | 241 | } |
1281 | daniel-mar | 242 | if ($has_admin) $usernames[] = 'admin'; |
243 | foreach ($usernames as $username) { |
||
244 | $bl_time = self::jwtGetBlacklistTime($gen, $username); |
||
585 | daniel-mar | 245 | if ($iat <= $bl_time) { |
1281 | daniel-mar | 246 | // Token is blacklisted (it was created before the last blacklist time) |
585 | daniel-mar | 247 | throw new OIDplusException(_L('The JWT token was blacklisted on %1. Please generate a new one',date('d F Y, H:i:s',$bl_time))); |
248 | } |
||
249 | } |
||
250 | |||
251 | // Optional feature: Limit the JWT to a specific IP address |
||
252 | // Currently not used in OIDplus |
||
1305 | daniel-mar | 253 | $ip = $contentProvider->getValue(self::CLAIM_LIMIT_IP, null); |
254 | if (!is_null($ip)) { |
||
585 | daniel-mar | 255 | if (isset($_SERVER['REMOTE_ADDR']) && ($ip !== $_SERVER['REMOTE_ADDR'])) { |
256 | throw new OIDplusException(_L('Your IP address is not allowed to use this token')); |
||
257 | } |
||
258 | } |
||
259 | |||
1265 | daniel-mar | 260 | // Checks if JWT are dependent on the generator |
1277 | daniel-mar | 261 | if (!is_null($validGenerators)) { |
1265 | daniel-mar | 262 | if (($gen & $validGenerators) === 0) { |
263 | throw new OIDplusException(_L('This kind of JWT token (%1) cannot be used in this request type', self::generatorName($gen))); |
||
585 | daniel-mar | 264 | } |
265 | } |
||
266 | } |
||
267 | |||
268 | // Override abstract functions |
||
269 | |||
1116 | daniel-mar | 270 | /** |
1301 | daniel-mar | 271 | * @var array |
272 | */ |
||
273 | protected $content = array(); |
||
274 | |||
275 | /** |
||
276 | * @param string $name |
||
277 | * @param mixed|null $default |
||
278 | * @return mixed|null |
||
279 | */ |
||
280 | public function getValue(string $name, $default = NULL) { |
||
281 | return $this->content[$name] ?? $default; |
||
282 | } |
||
283 | |||
284 | /** |
||
285 | * @param string $name |
||
286 | * @param mixed $value |
||
1116 | daniel-mar | 287 | * @return void |
288 | */ |
||
1301 | daniel-mar | 289 | public function setValue(string $name, $value) { |
290 | $this->content[$name] = $value; |
||
291 | } |
||
292 | |||
293 | /** |
||
294 | * @param string $name |
||
295 | * @return bool |
||
296 | */ |
||
297 | public function exists(string $name): bool { |
||
298 | return isset($this->content[$name]); |
||
299 | } |
||
300 | |||
301 | /** |
||
302 | * @param string $name |
||
303 | * @return void |
||
304 | */ |
||
305 | public function delete(string $name) { |
||
306 | unset($this->content[$name]); |
||
307 | } |
||
308 | |||
309 | /** |
||
310 | * @return void |
||
311 | */ |
||
585 | daniel-mar | 312 | public function activate() { |
620 | daniel-mar | 313 | // Send cookie at the end of the HTTP request, in case there are multiple activate() calls |
639 | daniel-mar | 314 | OIDplus::register_shutdown_function(array($this,'activateNow')); |
620 | daniel-mar | 315 | } |
316 | |||
1116 | daniel-mar | 317 | /** |
318 | * @return void |
||
319 | * @throws OIDplusException |
||
320 | */ |
||
620 | daniel-mar | 321 | public function activateNow() { |
585 | daniel-mar | 322 | $token = $this->getJWTToken(); |
323 | $exp = $this->getValue('exp',0); |
||
324 | OIDplus::cookieUtils()->setcookie(self::COOKIE_NAME, $token, $exp, false); |
||
325 | } |
||
326 | |||
1116 | daniel-mar | 327 | /** |
328 | * @return void |
||
329 | * @throws OIDplusException |
||
330 | */ |
||
585 | daniel-mar | 331 | public function destroySession() { |
332 | OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME); |
||
333 | } |
||
334 | |||
1305 | daniel-mar | 335 | // RA authentication functions (low-level) |
336 | |||
1116 | daniel-mar | 337 | /** |
338 | * @param string $email |
||
339 | * @return void |
||
1305 | daniel-mar | 340 | */ |
341 | public function raLogin(string $email) { |
||
342 | if ($email == 'admin') return; |
||
343 | |||
344 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
345 | if (is_null($list)) $list = []; |
||
346 | if (!in_array($email, $list)) $list[] = $email; |
||
347 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
348 | } |
||
349 | |||
350 | /** |
||
351 | * @return int |
||
352 | */ |
||
353 | public function raNumLoggedIn(): int { |
||
354 | return count($this->loggedInRaList()); |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * @return OIDplusRA[] |
||
359 | */ |
||
360 | public function loggedInRaList(): array { |
||
361 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
362 | if (is_null($list)) $list = []; |
||
363 | |||
364 | $res = array(); |
||
365 | foreach (array_unique($list) as $username) { |
||
366 | if ($username == '') continue; // should not happen |
||
367 | if ($username == 'admin') continue; |
||
368 | $res[] = new OIDplusRA($username); |
||
369 | } |
||
370 | return $res; |
||
371 | } |
||
372 | |||
373 | /** |
||
374 | * @param string $email |
||
375 | * @return bool |
||
376 | */ |
||
377 | public function isRaLoggedIn(string $email): bool { |
||
378 | foreach ($this->loggedInRaList() as $ra) { |
||
379 | if ($email == $ra->raEmail()) return true; |
||
380 | } |
||
381 | return false; |
||
382 | } |
||
383 | |||
384 | /** |
||
385 | * @param string $email |
||
386 | * @return void |
||
1116 | daniel-mar | 387 | * @throws OIDplusException |
388 | */ |
||
389 | public function raLogout(string $email) { |
||
1305 | daniel-mar | 390 | if ($email == 'admin') return; |
391 | |||
392 | $gen = $this->getValue(self::CLAIM_GENERATOR, -1); |
||
585 | daniel-mar | 393 | if ($gen >= 0) self::jwtBlacklist($gen, $email); |
1305 | daniel-mar | 394 | |
395 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
396 | if (is_null($list)) $list = []; |
||
397 | $key = array_search($email, $list); |
||
398 | if ($key !== false) unset($list[$key]); |
||
399 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
585 | daniel-mar | 400 | } |
401 | |||
1116 | daniel-mar | 402 | /** |
403 | * @param string $email |
||
404 | * @param string $loginfo |
||
405 | * @return void |
||
406 | * @throws OIDplusException |
||
407 | */ |
||
408 | public function raLogoutEx(string $email, string &$loginfo) { |
||
585 | daniel-mar | 409 | $this->raLogout($email); |
410 | $loginfo = 'from JWT session'; |
||
411 | } |
||
412 | |||
1305 | daniel-mar | 413 | // Admin authentication functions (low-level) |
414 | |||
1116 | daniel-mar | 415 | /** |
416 | * @return void |
||
1305 | daniel-mar | 417 | */ |
418 | public function adminLogin() { |
||
419 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
420 | if (is_null($list)) $list = []; |
||
421 | if (!in_array('admin', $list)) $list[] = 'admin'; |
||
422 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
423 | } |
||
424 | |||
425 | /** |
||
426 | * @return bool |
||
427 | */ |
||
428 | public function isAdminLoggedIn(): bool { |
||
429 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
430 | if (is_null($list)) $list = []; |
||
431 | return in_array('admin', $list); |
||
432 | } |
||
433 | |||
434 | /** |
||
435 | * @return void |
||
1116 | daniel-mar | 436 | * @throws OIDplusException |
437 | */ |
||
585 | daniel-mar | 438 | public function adminLogout() { |
1305 | daniel-mar | 439 | $gen = $this->getValue(self::CLAIM_GENERATOR, -1); |
585 | daniel-mar | 440 | if ($gen >= 0) self::jwtBlacklist($gen, 'admin'); |
1305 | daniel-mar | 441 | |
442 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
443 | if (is_null($list)) $list = []; |
||
444 | $key = array_search('admin', $list); |
||
445 | if ($key !== false) unset($list[$key]); |
||
446 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
585 | daniel-mar | 447 | } |
448 | |||
1116 | daniel-mar | 449 | /** |
450 | * @param string $loginfo |
||
451 | * @return void |
||
452 | * @throws OIDplusException |
||
453 | */ |
||
454 | public function adminLogoutEx(string &$loginfo) { |
||
585 | daniel-mar | 455 | $this->adminLogout(); |
456 | $loginfo = 'from JWT session'; |
||
457 | } |
||
458 | |||
620 | daniel-mar | 459 | private static $contentProvider = null; |
1116 | daniel-mar | 460 | |
461 | /** |
||
1305 | daniel-mar | 462 | * @return OIDplusAuthContentStoreJWT|null |
1116 | daniel-mar | 463 | * @throws OIDplusException |
464 | */ |
||
1305 | daniel-mar | 465 | public static function getActiveProvider()/*: ?OIDplusAuthContentStoreJWT*/ { |
620 | daniel-mar | 466 | if (!self::$contentProvider) { |
585 | daniel-mar | 467 | |
1265 | daniel-mar | 468 | $tmp = null; |
469 | $silent_error = false; |
||
585 | daniel-mar | 470 | |
1265 | daniel-mar | 471 | try { |
585 | daniel-mar | 472 | |
1265 | daniel-mar | 473 | $rel_url = substr($_SERVER['REQUEST_URI'], strlen(OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT))); |
474 | if (str_starts_with($rel_url, 'rest/')) { // <== TODO: Find a way how to move this into the plugin, since REST does not belong to the core. |
||
475 | |||
476 | // REST may only use Bearer Authentication |
||
477 | $bearer = getBearerToken(); |
||
478 | if (!is_null($bearer)) { |
||
479 | $silent_error = false; |
||
480 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
481 | $tmp->loadJWT($bearer); |
||
482 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_REST | self::JWT_GENERATOR_MANUAL); |
||
585 | daniel-mar | 483 | } |
1265 | daniel-mar | 484 | |
485 | } else { |
||
486 | |||
1305 | daniel-mar | 487 | // A web-visitor (HTML and AJAX, but not REST) can use a JWT Cookie |
1265 | daniel-mar | 488 | if (isset($_COOKIE[self::COOKIE_NAME])) { |
489 | $silent_error = true; |
||
490 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
491 | $tmp->loadJWT($_COOKIE[self::COOKIE_NAME]); |
||
492 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_LOGIN | self::JWT_GENERATOR_MANUAL); |
||
493 | } |
||
494 | |||
1305 | daniel-mar | 495 | // AJAX may additionally use GET/POST automated AJAX (in addition to the normal web browser login Cookie) |
1265 | daniel-mar | 496 | if (isset($_SERVER['SCRIPT_FILENAME']) && (strtolower(basename($_SERVER['SCRIPT_FILENAME'])) !== 'ajax.php')) { |
497 | if (isset($_POST[self::COOKIE_NAME])) { |
||
498 | $silent_error = false; |
||
499 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
500 | $tmp->loadJWT($_POST[self::COOKIE_NAME]); |
||
501 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_AJAX | self::JWT_GENERATOR_MANUAL); |
||
502 | } |
||
503 | if (isset($_GET[self::COOKIE_NAME])) { |
||
504 | $silent_error = false; |
||
505 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
506 | $tmp->loadJWT($_GET[self::COOKIE_NAME]); |
||
507 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_AJAX | self::JWT_GENERATOR_MANUAL); |
||
508 | } |
||
509 | } |
||
510 | |||
585 | daniel-mar | 511 | } |
512 | |||
1265 | daniel-mar | 513 | } catch (\Exception $e) { |
1306 | daniel-mar | 514 | if (!$silent_error || OIDplus::baseConfig()->getValue('DEBUG',false)) { |
1265 | daniel-mar | 515 | // Most likely an AJAX request. We can throw an Exception |
516 | throw new OIDplusException(_L('The JWT token was rejected: %1',$e->getMessage())); |
||
517 | } else { |
||
518 | // Most likely an expired Cookie/Login session. We must not throw an Exception, otherwise we will break jsTree |
||
519 | OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME); |
||
520 | return null; |
||
521 | } |
||
585 | daniel-mar | 522 | } |
1265 | daniel-mar | 523 | |
524 | self::$contentProvider = $tmp; |
||
585 | daniel-mar | 525 | } |
526 | |||
620 | daniel-mar | 527 | return self::$contentProvider; |
585 | daniel-mar | 528 | } |
529 | |||
1116 | daniel-mar | 530 | /** |
531 | * @param string $email |
||
532 | * @param string $loginfo |
||
533 | * @return void |
||
534 | * @throws OIDplusException |
||
535 | */ |
||
536 | public function raLoginEx(string $email, string &$loginfo) { |
||
585 | daniel-mar | 537 | if (is_null(self::getActiveProvider())) { |
538 | $this->raLogin($email); |
||
539 | $loginfo = 'into new JWT session'; |
||
620 | daniel-mar | 540 | self::$contentProvider = $this; |
585 | daniel-mar | 541 | } else { |
1305 | daniel-mar | 542 | $gen = $this->getValue(self::CLAIM_GENERATOR,-1); |
585 | daniel-mar | 543 | switch ($gen) { |
544 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_AJAX : |
||
1265 | daniel-mar | 545 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_REST : |
585 | daniel-mar | 546 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_MANUAL : |
547 | throw new OIDplusException(_L('This kind of JWT token cannot be altered. Therefore you cannot do this action.')); |
||
548 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN : |
||
549 | if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) { |
||
1305 | daniel-mar | 550 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_USER')); |
585 | daniel-mar | 551 | } |
552 | break; |
||
553 | default: |
||
554 | assert(false); // This cannot happen because jwtSecurityCheck will check for unknown generators |
||
555 | break; |
||
556 | } |
||
557 | $this->raLogin($email); |
||
558 | $loginfo = 'into existing JWT session'; |
||
559 | } |
||
1306 | daniel-mar | 560 | $ttl = OIDplus::baseConfig()->getValue('JWT_TTL_LOGIN_USER', 10*365*24*60*60); |
561 | $this->setValue('exp', time()+$ttl); // JWT "exp" attribute |
||
585 | daniel-mar | 562 | } |
563 | |||
1116 | daniel-mar | 564 | /** |
565 | * @param string $loginfo |
||
566 | * @return void |
||
567 | * @throws OIDplusException |
||
568 | */ |
||
569 | public function adminLoginEx(string &$loginfo) { |
||
585 | daniel-mar | 570 | if (is_null(self::getActiveProvider())) { |
571 | $this->adminLogin(); |
||
572 | $loginfo = 'into new JWT session'; |
||
620 | daniel-mar | 573 | self::$contentProvider = $this; |
585 | daniel-mar | 574 | } else { |
1305 | daniel-mar | 575 | $gen = $this->getValue(self::CLAIM_GENERATOR,-1); |
585 | daniel-mar | 576 | switch ($gen) { |
577 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_AJAX : |
||
1265 | daniel-mar | 578 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_REST : |
585 | daniel-mar | 579 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_MANUAL : |
580 | throw new OIDplusException(_L('This kind of JWT token cannot be altered. Therefore you cannot do this action.')); |
||
581 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN : |
||
582 | if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) { |
||
1305 | daniel-mar | 583 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_ADMIN')); |
585 | daniel-mar | 584 | } |
585 | break; |
||
586 | default: |
||
587 | assert(false); // This cannot happen because jwtSecurityCheck will check for unknown generators |
||
588 | break; |
||
589 | } |
||
590 | $this->adminLogin(); |
||
591 | $loginfo = 'into existing JWT session'; |
||
592 | } |
||
1306 | daniel-mar | 593 | $ttl = OIDplus::baseConfig()->getValue('JWT_TTL_LOGIN_ADMIN', 10*365*24*60*60); |
594 | $this->setValue('exp', time()+$ttl); // JWT "exp" attribute |
||
585 | daniel-mar | 595 | } |
596 | |||
566 | daniel-mar | 597 | // Individual functions |
598 | |||
1116 | daniel-mar | 599 | /** |
1265 | daniel-mar | 600 | * Decode the JWT. In this step, the signature as well as EXP/NBF times will be checked |
1116 | daniel-mar | 601 | * @param string $jwt |
602 | * @return void |
||
603 | * @throws OIDplusException |
||
604 | */ |
||
605 | public function loadJWT(string $jwt) { |
||
571 | daniel-mar | 606 | \Firebase\JWT\JWT::$leeway = 60; // leeway in seconds |
570 | daniel-mar | 607 | if (OIDplus::getPkiStatus()) { |
830 | daniel-mar | 608 | $pubKey = OIDplus::getSystemPublicKey(); |
1298 | daniel-mar | 609 | $k = new \Firebase\JWT\Key($pubKey, 'RS256'); // RSA+SHA256 is hardcoded in getPkiStatus() generation |
679 | daniel-mar | 610 | $this->content = (array) \Firebase\JWT\JWT::decode($jwt, $k); |
570 | daniel-mar | 611 | } else { |
1283 | daniel-mar | 612 | $key = OIDplus::authUtils()->makeSecret(['0be35e52-f4ef-11ed-b67e-3c4a92df8582']); |
826 | daniel-mar | 613 | $key = hash_pbkdf2('sha512', $key, '', 10000, 32/*256bit*/, false); |
679 | daniel-mar | 614 | $k = new \Firebase\JWT\Key($key, 'HS512'); // HMAC+SHA512 is hardcoded here |
615 | $this->content = (array) \Firebase\JWT\JWT::decode($jwt, $k); |
||
570 | daniel-mar | 616 | } |
566 | daniel-mar | 617 | } |
618 | |||
1116 | daniel-mar | 619 | /** |
620 | * @return string |
||
621 | * @throws OIDplusException |
||
622 | */ |
||
623 | public function getJWTToken(): string { |
||
566 | daniel-mar | 624 | $payload = $this->content; |
1305 | daniel-mar | 625 | $payload[self::CLAIM_SSH] = self::getSsh(); // SSH = Server Secret Hash |
1307 | daniel-mar | 626 | // see also https://www.iana.org/assignments/jwt/jwt.xhtml#claims for some generic claims |
627 | $payload["iss"] = OIDplus::getEditionInfo()['jwtaud']; // sic: jwtaud |
||
699 | daniel-mar | 628 | $payload["aud"] = OIDplus::getEditionInfo()['jwtaud']; |
570 | daniel-mar | 629 | $payload["jti"] = gen_uuid(); |
566 | daniel-mar | 630 | $payload["iat"] = time(); |
1307 | daniel-mar | 631 | if (!isset($payload["nbf"])) $payload["nbf"] = time(); |
1306 | daniel-mar | 632 | if (!isset($payload["exp"])) $payload["exp"] = time()+3600/*1h*/; |
570 | daniel-mar | 633 | |
1306 | daniel-mar | 634 | uksort($payload, "strnatcmp"); // this is natsort on the key. Just to make the JWT look nicer. |
635 | |||
570 | daniel-mar | 636 | if (OIDplus::getPkiStatus()) { |
830 | daniel-mar | 637 | $privKey = OIDplus::getSystemPrivateKey(); |
1298 | daniel-mar | 638 | return \Firebase\JWT\JWT::encode($payload, $privKey, 'RS256'); // RSA+SHA256 is hardcoded in getPkiStatus() generation |
570 | daniel-mar | 639 | } else { |
1283 | daniel-mar | 640 | $key = OIDplus::authUtils()->makeSecret(['0be35e52-f4ef-11ed-b67e-3c4a92df8582']); |
826 | daniel-mar | 641 | $key = hash_pbkdf2('sha512', $key, '', 10000, 32/*256bit*/, false); |
679 | daniel-mar | 642 | return \Firebase\JWT\JWT::encode($payload, $key, 'HS512'); // HMAC+SHA512 is hardcoded here |
570 | daniel-mar | 643 | } |
566 | daniel-mar | 644 | } |
645 | |||
570 | daniel-mar | 646 | } |