Rev 1318 | Rev 1345 | 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 | /** |
||
1310 | daniel-mar | 57 | * Trace JTI, IP, and UserAgent |
58 | */ |
||
59 | const CLAIM_TRACE = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.7.5'; |
||
60 | |||
61 | /** |
||
1130 | daniel-mar | 62 | * "Automated AJAX" plugin |
63 | */ |
||
1265 | daniel-mar | 64 | const JWT_GENERATOR_AJAX = 10; |
1130 | daniel-mar | 65 | /** |
1265 | daniel-mar | 66 | * "REST API" plugin |
67 | */ |
||
68 | const JWT_GENERATOR_REST = 20; |
||
69 | /** |
||
1305 | daniel-mar | 70 | * Web browser login method |
1130 | daniel-mar | 71 | */ |
1265 | daniel-mar | 72 | const JWT_GENERATOR_LOGIN = 40; |
1130 | daniel-mar | 73 | /** |
74 | * "Manually crafted" JWT tokens |
||
75 | */ |
||
1265 | daniel-mar | 76 | const JWT_GENERATOR_MANUAL = 80; |
585 | daniel-mar | 77 | |
1116 | daniel-mar | 78 | /** |
1317 | daniel-mar | 79 | * @return string |
80 | */ |
||
81 | public static function getAudIss(): string { |
||
82 | $oid = OIDplus::getSystemId(true); |
||
83 | if ($oid !== false) return 'urn:oid:'.$oid; |
||
84 | $url = OIDplus::webpath(null, OIDplus::PATH_ABSOLUTE_CANONICAL); |
||
85 | if ($url) return $url; |
||
86 | return 'http://oidplus.com/'; |
||
87 | } |
||
88 | |||
89 | /** |
||
1116 | daniel-mar | 90 | * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_... |
91 | * @param string $sub |
||
92 | * @return string |
||
93 | */ |
||
94 | private static function jwtGetBlacklistConfigKey(int $gen, string $sub): string { |
||
1265 | daniel-mar | 95 | // Note: Needs to be <= 50 characters! If $gen is 2 chars, then the config key is 49 chars long |
585 | daniel-mar | 96 | return 'jwt_blacklist_gen('.$gen.')_sub('.trim(base64_encode(md5($sub,true)),'=').')'; |
97 | } |
||
98 | |||
1116 | daniel-mar | 99 | /** |
1265 | daniel-mar | 100 | * @param int $gen |
101 | */ |
||
102 | private static function generatorName($gen) { |
||
103 | // Note: The strings are not translated, because the name is used in config keys or logs |
||
104 | if ($gen === self::JWT_GENERATOR_AJAX) return 'Automated AJAX calls'; |
||
105 | if ($gen === self::JWT_GENERATOR_REST) return 'REST API'; |
||
1305 | daniel-mar | 106 | if ($gen === self::JWT_GENERATOR_LOGIN) return 'Browser login'; |
1265 | daniel-mar | 107 | if ($gen === self::JWT_GENERATOR_MANUAL) return 'Manually created'; |
108 | return 'Unknown generator'; |
||
109 | } |
||
110 | |||
111 | /** |
||
1116 | daniel-mar | 112 | * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_... |
113 | * @param string $sub |
||
114 | * @return void |
||
115 | * @throws OIDplusException |
||
116 | */ |
||
117 | public static function jwtBlacklist(int $gen, string $sub) { |
||
585 | daniel-mar | 118 | $cfg = self::jwtGetBlacklistConfigKey($gen, $sub); |
119 | $bl_time = time()-1; |
||
120 | |||
1265 | daniel-mar | 121 | $gen_desc = self::generatorName($gen); |
585 | daniel-mar | 122 | |
1305 | daniel-mar | 123 | 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 | 124 | OIDplus::config()->setValue($cfg, $bl_time); |
125 | } |
||
126 | |||
1116 | daniel-mar | 127 | /** |
128 | * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_... |
||
1321 | daniel-mar | 129 | * @param string $sub E-Mail-Adress of RA or 'admin' |
1116 | daniel-mar | 130 | * @return int |
131 | * @throws OIDplusException |
||
132 | */ |
||
133 | public static function jwtGetBlacklistTime(int $gen, string $sub): int { |
||
585 | daniel-mar | 134 | $cfg = self::jwtGetBlacklistConfigKey($gen, $sub); |
1116 | daniel-mar | 135 | return (int)OIDplus::config()->getValue($cfg,0); |
585 | daniel-mar | 136 | } |
137 | |||
1116 | daniel-mar | 138 | /** |
1298 | daniel-mar | 139 | * 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 |
140 | * @return string |
||
141 | * @throws OIDplusException |
||
142 | */ |
||
143 | private static function getSsh(): string { |
||
1305 | daniel-mar | 144 | $hexadecimal_string = OIDplus::authUtils()->makeSecret(['bb1aebd6-fe6a-11ed-a553-3c4a92df8582']); |
145 | return base64_encode(pack('H*',$hexadecimal_string)); |
||
1298 | daniel-mar | 146 | } |
147 | |||
148 | /** |
||
1265 | daniel-mar | 149 | * Do various checks if the token is allowed and not blacklisted |
1305 | daniel-mar | 150 | * @param OIDplusAuthContentStoreJWT $contentProvider |
1277 | daniel-mar | 151 | * @param int|null $validGenerators Bitmask which generators to allow (null = allow all) |
1116 | daniel-mar | 152 | * @return void |
153 | * @throws OIDplusException |
||
154 | */ |
||
1305 | daniel-mar | 155 | private static function jwtSecurityCheck(OIDplusAuthContentStoreJWT $contentProvider, int $validGenerators=null) { |
585 | daniel-mar | 156 | // Check if the token is intended for us |
1321 | daniel-mar | 157 | // Note 'aud' is mandatory for OIDplus, so we do not check for exists() |
1317 | daniel-mar | 158 | if ($contentProvider->getValue('aud','') !== $contentProvider->getAudIss()) { |
1318 | daniel-mar | 159 | throw new OIDplusException(_L('Token has wrong audience: Given %1 but expected %2.', $contentProvider->getValue('aud',''), $contentProvider->getAudIss())); |
585 | daniel-mar | 160 | } |
1298 | daniel-mar | 161 | |
1321 | daniel-mar | 162 | // Note CLAIM_SSH is mandatory for OIDplus, so we do not check for exists() |
1305 | daniel-mar | 163 | if ($contentProvider->getValue(self::CLAIM_SSH, '') !== self::getSsh()) { |
1298 | daniel-mar | 164 | throw new OIDplusException(_L('"Server Secret" was changed; therefore the JWT is not valid anymore')); |
165 | } |
||
166 | |||
1321 | daniel-mar | 167 | // Note CLAIM_GENERATOR is mandatory for OIDplus, so we do not check for exists() |
1305 | daniel-mar | 168 | $gen = $contentProvider->getValue(self::CLAIM_GENERATOR, -1); |
585 | daniel-mar | 169 | |
170 | $has_admin = $contentProvider->isAdminLoggedIn(); |
||
171 | $has_ra = $contentProvider->raNumLoggedIn() > 0; |
||
172 | |||
173 | // Check if the token generator is allowed |
||
174 | if ($gen === self::JWT_GENERATOR_AJAX) { |
||
175 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_AJAX_ADMIN', true)) { |
||
635 | daniel-mar | 176 | // Generator: plugins/viathinksoft/adminPages/910_automated_ajax_calls/OIDplusPageAdminAutomatedAJAXCalls.class.php |
585 | daniel-mar | 177 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_AJAX_ADMIN')); |
178 | } |
||
179 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_AJAX_USER', true)) { |
||
635 | daniel-mar | 180 | // Generator: plugins/viathinksoft/raPages/910_automated_ajax_calls/OIDplusPageRaAutomatedAJAXCalls.class.php |
585 | daniel-mar | 181 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_AJAX_USER')); |
182 | } |
||
183 | } |
||
1265 | daniel-mar | 184 | else if ($gen === self::JWT_GENERATOR_REST) { |
185 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_REST_ADMIN', true)) { |
||
186 | // Generator: plugins/viathinksoft/adminPages/911_rest_api/OIDplusPageAdminRestApi.class.php |
||
187 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_REST_ADMIN')); |
||
188 | } |
||
189 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_REST_USER', true)) { |
||
190 | // Generator: plugins/viathinksoft/raPages/911_rest_api/OIDplusPageRaRestApi.class.php |
||
191 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_REST_USER')); |
||
192 | } |
||
193 | } |
||
585 | daniel-mar | 194 | else if ($gen === self::JWT_GENERATOR_LOGIN) { |
1305 | daniel-mar | 195 | // Used for web browser login (use JWT token in a cookie as alternative to PHP session): |
585 | daniel-mar | 196 | // - No PHP session will be used |
197 | // - Session will not be bound to IP address (therefore, you can switch between mobile/WiFi for example) |
||
198 | // - No server-side session needed |
||
199 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) { |
||
200 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_ADMIN')); |
||
201 | } |
||
202 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) { |
||
203 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_USER')); |
||
204 | } |
||
205 | } |
||
206 | else if ($gen === self::JWT_GENERATOR_MANUAL) { |
||
1300 | daniel-mar | 207 | // Generator: "hand-crafted" tokens |
208 | if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_MANUAL_ADMIN', false)) { |
||
209 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_MANUAL_ADMIN')); |
||
585 | daniel-mar | 210 | } |
1300 | daniel-mar | 211 | if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_MANUAL_USER', false)) { |
212 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_MANUAL_USER')); |
||
213 | } |
||
585 | daniel-mar | 214 | } else { |
215 | throw new OIDplusException(_L('Token generator %1 not recognized',$gen)); |
||
216 | } |
||
217 | |||
1307 | daniel-mar | 218 | // Every token must have and issued timestamp |
219 | $iat = $contentProvider->getValue('iat',null); |
||
220 | if (is_null($iat)) { |
||
221 | throw new OIDplusException(_L('The claim "%1" of the JWT token is missing or invalid','iat')); |
||
222 | } |
||
223 | |||
224 | // Verify that IAT has a valid value |
||
225 | // Note: This check is already done in Firebase\JWT. However, we do it again, just to be 100% sure. |
||
226 | if (($iat-120/*leeway 2min*/) > time()) { |
||
227 | // Token was created in the future. Something is wrong! |
||
228 | throw new OIDplusException(_L('JWT Token cannot be verified because the server time is wrong')); |
||
229 | } |
||
230 | |||
231 | // Check if token is not yet valid |
||
232 | // Note: This check is already done in Firebase\JWT. However, we do it again, just to be 100% sure. |
||
233 | $nbf = $contentProvider->getValue('nbf',null); |
||
234 | if (!is_null($nbf)) { |
||
235 | if (time() < $nbf-120/*leeway 2min*/) { |
||
236 | throw new OIDplusException(_L('Token not valid before %1',date('d F Y, H:i:s',$nbf))); |
||
237 | } |
||
238 | } |
||
239 | |||
1306 | daniel-mar | 240 | // Check if token has expired |
1307 | daniel-mar | 241 | // Note: This check is already done in Firebase\JWT. However, we do it again, just to be 100% sure. |
1306 | daniel-mar | 242 | $exp = $contentProvider->getValue('exp',null); |
243 | if (!is_null($exp)) { |
||
1307 | daniel-mar | 244 | if (time() > $exp+120/*leeway 2min*/) { |
1306 | daniel-mar | 245 | throw new OIDplusException(_L('Token has expired on %1',date('d F Y, H:i:s',$exp))); |
246 | } |
||
247 | } |
||
248 | |||
585 | daniel-mar | 249 | // Make sure that the IAT (issued at time) isn't in a blacklisted timeframe |
250 | // 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 | 251 | // When a user logs out of a web browser session, the JWT token will be blacklisted as well |
252 | // Small side effect: All web browser login sessions of that user will be revoked then |
||
585 | daniel-mar | 253 | $sublist = $contentProvider->loggedInRaList(); |
1281 | daniel-mar | 254 | $usernames = array(); |
255 | foreach ($sublist as $sub) { |
||
256 | $usernames[] = $sub->raEmail(); |
||
585 | daniel-mar | 257 | } |
1281 | daniel-mar | 258 | if ($has_admin) $usernames[] = 'admin'; |
259 | foreach ($usernames as $username) { |
||
260 | $bl_time = self::jwtGetBlacklistTime($gen, $username); |
||
585 | daniel-mar | 261 | if ($iat <= $bl_time) { |
1281 | daniel-mar | 262 | // Token is blacklisted (it was created before the last blacklist time) |
585 | daniel-mar | 263 | 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))); |
264 | } |
||
265 | } |
||
266 | |||
1312 | daniel-mar | 267 | // Optional feature: Limit the JWT to a specific IP address (used if JWT_FIXED_IP_USER or JWT_FIXED_IP_ADMIN is true) |
1305 | daniel-mar | 268 | $ip = $contentProvider->getValue(self::CLAIM_LIMIT_IP, null); |
269 | if (!is_null($ip)) { |
||
585 | daniel-mar | 270 | if (isset($_SERVER['REMOTE_ADDR']) && ($ip !== $_SERVER['REMOTE_ADDR'])) { |
271 | throw new OIDplusException(_L('Your IP address is not allowed to use this token')); |
||
272 | } |
||
273 | } |
||
274 | |||
1265 | daniel-mar | 275 | // Checks if JWT are dependent on the generator |
1277 | daniel-mar | 276 | if (!is_null($validGenerators)) { |
1265 | daniel-mar | 277 | if (($gen & $validGenerators) === 0) { |
278 | throw new OIDplusException(_L('This kind of JWT token (%1) cannot be used in this request type', self::generatorName($gen))); |
||
585 | daniel-mar | 279 | } |
280 | } |
||
281 | } |
||
282 | |||
283 | // Override abstract functions |
||
284 | |||
1116 | daniel-mar | 285 | /** |
1301 | daniel-mar | 286 | * @var array |
287 | */ |
||
288 | protected $content = array(); |
||
289 | |||
290 | /** |
||
291 | * @param string $name |
||
292 | * @param mixed|null $default |
||
293 | * @return mixed|null |
||
294 | */ |
||
295 | public function getValue(string $name, $default = NULL) { |
||
296 | return $this->content[$name] ?? $default; |
||
297 | } |
||
298 | |||
299 | /** |
||
300 | * @param string $name |
||
301 | * @param mixed $value |
||
1116 | daniel-mar | 302 | * @return void |
303 | */ |
||
1301 | daniel-mar | 304 | public function setValue(string $name, $value) { |
305 | $this->content[$name] = $value; |
||
306 | } |
||
307 | |||
308 | /** |
||
309 | * @param string $name |
||
310 | * @return bool |
||
311 | */ |
||
312 | public function exists(string $name): bool { |
||
313 | return isset($this->content[$name]); |
||
314 | } |
||
315 | |||
316 | /** |
||
317 | * @param string $name |
||
318 | * @return void |
||
319 | */ |
||
320 | public function delete(string $name) { |
||
321 | unset($this->content[$name]); |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * @return void |
||
326 | */ |
||
585 | daniel-mar | 327 | public function activate() { |
620 | daniel-mar | 328 | // Send cookie at the end of the HTTP request, in case there are multiple activate() calls |
639 | daniel-mar | 329 | OIDplus::register_shutdown_function(array($this,'activateNow')); |
620 | daniel-mar | 330 | } |
331 | |||
1116 | daniel-mar | 332 | /** |
333 | * @return void |
||
334 | * @throws OIDplusException |
||
335 | */ |
||
620 | daniel-mar | 336 | public function activateNow() { |
585 | daniel-mar | 337 | $token = $this->getJWTToken(); |
338 | $exp = $this->getValue('exp',0); |
||
339 | OIDplus::cookieUtils()->setcookie(self::COOKIE_NAME, $token, $exp, false); |
||
340 | } |
||
341 | |||
1116 | daniel-mar | 342 | /** |
343 | * @return void |
||
344 | * @throws OIDplusException |
||
345 | */ |
||
585 | daniel-mar | 346 | public function destroySession() { |
347 | OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME); |
||
348 | } |
||
349 | |||
1314 | daniel-mar | 350 | /** |
351 | * @param string[] $ra RAs |
||
352 | * @param bool $admin Admin yes or no? |
||
353 | * @param int $gen Generator |
||
354 | * @param bool $limit_ip Limit IP to the current IP address? |
||
355 | * @param int $ttl How many seconds valid? |
||
356 | * @return string JWT token |
||
357 | */ |
||
358 | public static function craftJWT(array $ra, bool $admin, int $gen, bool $limit_ip=false, int $ttl=10*365*24*60*60): string { |
||
359 | $authSimulation = new OIDplusAuthContentStoreJWT(); |
||
360 | foreach ($ra as $username) { |
||
361 | if ($username == 'admin') continue; |
||
362 | $authSimulation->raLogin($username); |
||
363 | } |
||
364 | if ($admin) $authSimulation->adminLogin(); |
||
365 | $authSimulation->setValue(OIDplusAuthContentStoreJWT::CLAIM_GENERATOR, $gen); |
||
366 | $authSimulation->setValue('exp', time()+$ttl); |
||
367 | if ($limit_ip && isset($_SERVER['REMOTE_ADDR'])) { |
||
368 | $authSimulation->setValue(self::CLAIM_LIMIT_IP, $_SERVER['REMOTE_ADDR']); |
||
369 | } |
||
370 | return $authSimulation->getJWTToken(); |
||
371 | } |
||
372 | |||
1305 | daniel-mar | 373 | // RA authentication functions (low-level) |
374 | |||
1116 | daniel-mar | 375 | /** |
376 | * @param string $email |
||
377 | * @return void |
||
1305 | daniel-mar | 378 | */ |
379 | public function raLogin(string $email) { |
||
380 | if ($email == 'admin') return; |
||
381 | |||
382 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
383 | if (is_null($list)) $list = []; |
||
384 | if (!in_array($email, $list)) $list[] = $email; |
||
385 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
386 | } |
||
387 | |||
388 | /** |
||
389 | * @return int |
||
390 | */ |
||
391 | public function raNumLoggedIn(): int { |
||
392 | return count($this->loggedInRaList()); |
||
393 | } |
||
394 | |||
395 | /** |
||
396 | * @return OIDplusRA[] |
||
397 | */ |
||
398 | public function loggedInRaList(): array { |
||
399 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
400 | if (is_null($list)) $list = []; |
||
401 | |||
402 | $res = array(); |
||
403 | foreach (array_unique($list) as $username) { |
||
404 | if ($username == '') continue; // should not happen |
||
405 | if ($username == 'admin') continue; |
||
406 | $res[] = new OIDplusRA($username); |
||
407 | } |
||
408 | return $res; |
||
409 | } |
||
410 | |||
411 | /** |
||
412 | * @param string $email |
||
413 | * @return bool |
||
414 | */ |
||
415 | public function isRaLoggedIn(string $email): bool { |
||
416 | foreach ($this->loggedInRaList() as $ra) { |
||
417 | if ($email == $ra->raEmail()) return true; |
||
418 | } |
||
419 | return false; |
||
420 | } |
||
421 | |||
422 | /** |
||
423 | * @param string $email |
||
424 | * @return void |
||
1116 | daniel-mar | 425 | * @throws OIDplusException |
426 | */ |
||
427 | public function raLogout(string $email) { |
||
1305 | daniel-mar | 428 | if ($email == 'admin') return; |
429 | |||
430 | $gen = $this->getValue(self::CLAIM_GENERATOR, -1); |
||
585 | daniel-mar | 431 | if ($gen >= 0) self::jwtBlacklist($gen, $email); |
1305 | daniel-mar | 432 | |
433 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
434 | if (is_null($list)) $list = []; |
||
435 | $key = array_search($email, $list); |
||
436 | if ($key !== false) unset($list[$key]); |
||
437 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
585 | daniel-mar | 438 | } |
439 | |||
1116 | daniel-mar | 440 | /** |
441 | * @param string $email |
||
442 | * @param string $loginfo |
||
443 | * @return void |
||
444 | * @throws OIDplusException |
||
445 | */ |
||
446 | public function raLogoutEx(string $email, string &$loginfo) { |
||
585 | daniel-mar | 447 | $this->raLogout($email); |
448 | $loginfo = 'from JWT session'; |
||
449 | } |
||
450 | |||
1305 | daniel-mar | 451 | // Admin authentication functions (low-level) |
452 | |||
1116 | daniel-mar | 453 | /** |
454 | * @return void |
||
1305 | daniel-mar | 455 | */ |
456 | public function adminLogin() { |
||
457 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
458 | if (is_null($list)) $list = []; |
||
459 | if (!in_array('admin', $list)) $list[] = 'admin'; |
||
460 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
461 | } |
||
462 | |||
463 | /** |
||
464 | * @return bool |
||
465 | */ |
||
466 | public function isAdminLoggedIn(): bool { |
||
467 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
468 | if (is_null($list)) $list = []; |
||
469 | return in_array('admin', $list); |
||
470 | } |
||
471 | |||
472 | /** |
||
473 | * @return void |
||
1116 | daniel-mar | 474 | * @throws OIDplusException |
475 | */ |
||
585 | daniel-mar | 476 | public function adminLogout() { |
1305 | daniel-mar | 477 | $gen = $this->getValue(self::CLAIM_GENERATOR, -1); |
585 | daniel-mar | 478 | if ($gen >= 0) self::jwtBlacklist($gen, 'admin'); |
1305 | daniel-mar | 479 | |
480 | $list = $this->getValue(self::CLAIM_LOGIN_LIST, null); |
||
481 | if (is_null($list)) $list = []; |
||
482 | $key = array_search('admin', $list); |
||
483 | if ($key !== false) unset($list[$key]); |
||
484 | $this->setValue(self::CLAIM_LOGIN_LIST, $list); |
||
585 | daniel-mar | 485 | } |
486 | |||
1116 | daniel-mar | 487 | /** |
488 | * @param string $loginfo |
||
489 | * @return void |
||
490 | * @throws OIDplusException |
||
491 | */ |
||
492 | public function adminLogoutEx(string &$loginfo) { |
||
585 | daniel-mar | 493 | $this->adminLogout(); |
494 | $loginfo = 'from JWT session'; |
||
495 | } |
||
496 | |||
620 | daniel-mar | 497 | private static $contentProvider = null; |
1116 | daniel-mar | 498 | |
499 | /** |
||
1305 | daniel-mar | 500 | * @return OIDplusAuthContentStoreJWT|null |
1116 | daniel-mar | 501 | * @throws OIDplusException |
502 | */ |
||
1305 | daniel-mar | 503 | public static function getActiveProvider()/*: ?OIDplusAuthContentStoreJWT*/ { |
620 | daniel-mar | 504 | if (!self::$contentProvider) { |
585 | daniel-mar | 505 | |
1265 | daniel-mar | 506 | $tmp = null; |
507 | $silent_error = false; |
||
585 | daniel-mar | 508 | |
1265 | daniel-mar | 509 | try { |
585 | daniel-mar | 510 | |
1265 | daniel-mar | 511 | $rel_url = substr($_SERVER['REQUEST_URI'], strlen(OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT))); |
512 | 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. |
||
513 | |||
514 | // REST may only use Bearer Authentication |
||
515 | $bearer = getBearerToken(); |
||
516 | if (!is_null($bearer)) { |
||
517 | $silent_error = false; |
||
518 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
519 | $tmp->loadJWT($bearer); |
||
520 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_REST | self::JWT_GENERATOR_MANUAL); |
||
585 | daniel-mar | 521 | } |
1265 | daniel-mar | 522 | |
523 | } else { |
||
524 | |||
1305 | daniel-mar | 525 | // A web-visitor (HTML and AJAX, but not REST) can use a JWT Cookie |
1265 | daniel-mar | 526 | if (isset($_COOKIE[self::COOKIE_NAME])) { |
527 | $silent_error = true; |
||
528 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
529 | $tmp->loadJWT($_COOKIE[self::COOKIE_NAME]); |
||
530 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_LOGIN | self::JWT_GENERATOR_MANUAL); |
||
531 | } |
||
532 | |||
1305 | daniel-mar | 533 | // AJAX may additionally use GET/POST automated AJAX (in addition to the normal web browser login Cookie) |
1265 | daniel-mar | 534 | if (isset($_SERVER['SCRIPT_FILENAME']) && (strtolower(basename($_SERVER['SCRIPT_FILENAME'])) !== 'ajax.php')) { |
535 | if (isset($_POST[self::COOKIE_NAME])) { |
||
536 | $silent_error = false; |
||
537 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
538 | $tmp->loadJWT($_POST[self::COOKIE_NAME]); |
||
539 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_AJAX | self::JWT_GENERATOR_MANUAL); |
||
540 | } |
||
541 | if (isset($_GET[self::COOKIE_NAME])) { |
||
542 | $silent_error = false; |
||
543 | $tmp = new OIDplusAuthContentStoreJWT(); |
||
544 | $tmp->loadJWT($_GET[self::COOKIE_NAME]); |
||
545 | self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_AJAX | self::JWT_GENERATOR_MANUAL); |
||
546 | } |
||
547 | } |
||
548 | |||
585 | daniel-mar | 549 | } |
550 | |||
1265 | daniel-mar | 551 | } catch (\Exception $e) { |
1306 | daniel-mar | 552 | if (!$silent_error || OIDplus::baseConfig()->getValue('DEBUG',false)) { |
1265 | daniel-mar | 553 | // Most likely an AJAX request. We can throw an Exception |
1317 | daniel-mar | 554 | if (OIDplus::baseConfig()->getValue('DEBUG',false)) { |
555 | OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME); |
||
556 | } |
||
1265 | daniel-mar | 557 | throw new OIDplusException(_L('The JWT token was rejected: %1',$e->getMessage())); |
558 | } else { |
||
559 | // Most likely an expired Cookie/Login session. We must not throw an Exception, otherwise we will break jsTree |
||
560 | OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME); |
||
561 | return null; |
||
562 | } |
||
585 | daniel-mar | 563 | } |
1265 | daniel-mar | 564 | |
565 | self::$contentProvider = $tmp; |
||
585 | daniel-mar | 566 | } |
567 | |||
620 | daniel-mar | 568 | return self::$contentProvider; |
585 | daniel-mar | 569 | } |
570 | |||
1116 | daniel-mar | 571 | /** |
572 | * @param string $email |
||
573 | * @param string $loginfo |
||
574 | * @return void |
||
575 | * @throws OIDplusException |
||
576 | */ |
||
577 | public function raLoginEx(string $email, string &$loginfo) { |
||
585 | daniel-mar | 578 | if (is_null(self::getActiveProvider())) { |
579 | $loginfo = 'into new JWT session'; |
||
620 | daniel-mar | 580 | self::$contentProvider = $this; |
585 | daniel-mar | 581 | } else { |
1305 | daniel-mar | 582 | $gen = $this->getValue(self::CLAIM_GENERATOR,-1); |
585 | daniel-mar | 583 | switch ($gen) { |
584 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_AJAX : |
||
1265 | daniel-mar | 585 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_REST : |
585 | daniel-mar | 586 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_MANUAL : |
587 | throw new OIDplusException(_L('This kind of JWT token cannot be altered. Therefore you cannot do this action.')); |
||
588 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN : |
||
589 | if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) { |
||
1305 | daniel-mar | 590 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_USER')); |
585 | daniel-mar | 591 | } |
592 | break; |
||
593 | default: |
||
594 | assert(false); // This cannot happen because jwtSecurityCheck will check for unknown generators |
||
595 | break; |
||
596 | } |
||
597 | $loginfo = 'into existing JWT session'; |
||
598 | } |
||
1315 | daniel-mar | 599 | $this->raLogin($email); |
1312 | daniel-mar | 600 | $ttl = OIDplus::baseConfig()->getValue('JWT_TTL_LOGIN_USER', 30*24*60*60); |
1306 | daniel-mar | 601 | $this->setValue('exp', time()+$ttl); // JWT "exp" attribute |
1312 | daniel-mar | 602 | if (OIDplus::baseConfig()->getValue('JWT_FIXED_IP_USER', false) && isset($_SERVER['REMOTE_ADDR'])) { |
603 | $this->setValue(self::CLAIM_LIMIT_IP, $_SERVER['REMOTE_ADDR']); |
||
604 | } |
||
585 | daniel-mar | 605 | } |
606 | |||
1116 | daniel-mar | 607 | /** |
608 | * @param string $loginfo |
||
609 | * @return void |
||
610 | * @throws OIDplusException |
||
611 | */ |
||
612 | public function adminLoginEx(string &$loginfo) { |
||
585 | daniel-mar | 613 | if (is_null(self::getActiveProvider())) { |
614 | $loginfo = 'into new JWT session'; |
||
620 | daniel-mar | 615 | self::$contentProvider = $this; |
585 | daniel-mar | 616 | } else { |
1305 | daniel-mar | 617 | $gen = $this->getValue(self::CLAIM_GENERATOR,-1); |
585 | daniel-mar | 618 | switch ($gen) { |
619 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_AJAX : |
||
1265 | daniel-mar | 620 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_REST : |
585 | daniel-mar | 621 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_MANUAL : |
622 | throw new OIDplusException(_L('This kind of JWT token cannot be altered. Therefore you cannot do this action.')); |
||
623 | case OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN : |
||
624 | if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) { |
||
1305 | daniel-mar | 625 | throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_ADMIN')); |
585 | daniel-mar | 626 | } |
627 | break; |
||
628 | default: |
||
629 | assert(false); // This cannot happen because jwtSecurityCheck will check for unknown generators |
||
630 | break; |
||
631 | } |
||
632 | $loginfo = 'into existing JWT session'; |
||
633 | } |
||
1315 | daniel-mar | 634 | $this->adminLogin(); |
1312 | daniel-mar | 635 | $ttl = OIDplus::baseConfig()->getValue('JWT_TTL_LOGIN_ADMIN', 30*24*60*60); |
1306 | daniel-mar | 636 | $this->setValue('exp', time()+$ttl); // JWT "exp" attribute |
1312 | daniel-mar | 637 | if (OIDplus::baseConfig()->getValue('JWT_FIXED_IP_ADMIN', false) && isset($_SERVER['REMOTE_ADDR'])) { |
638 | $this->setValue(self::CLAIM_LIMIT_IP, $_SERVER['REMOTE_ADDR']); |
||
639 | } |
||
585 | daniel-mar | 640 | } |
641 | |||
566 | daniel-mar | 642 | // Individual functions |
643 | |||
1116 | daniel-mar | 644 | /** |
1265 | daniel-mar | 645 | * Decode the JWT. In this step, the signature as well as EXP/NBF times will be checked |
1116 | daniel-mar | 646 | * @param string $jwt |
647 | * @return void |
||
648 | * @throws OIDplusException |
||
649 | */ |
||
650 | public function loadJWT(string $jwt) { |
||
571 | daniel-mar | 651 | \Firebase\JWT\JWT::$leeway = 60; // leeway in seconds |
570 | daniel-mar | 652 | if (OIDplus::getPkiStatus()) { |
830 | daniel-mar | 653 | $pubKey = OIDplus::getSystemPublicKey(); |
1298 | daniel-mar | 654 | $k = new \Firebase\JWT\Key($pubKey, 'RS256'); // RSA+SHA256 is hardcoded in getPkiStatus() generation |
679 | daniel-mar | 655 | $this->content = (array) \Firebase\JWT\JWT::decode($jwt, $k); |
570 | daniel-mar | 656 | } else { |
1283 | daniel-mar | 657 | $key = OIDplus::authUtils()->makeSecret(['0be35e52-f4ef-11ed-b67e-3c4a92df8582']); |
826 | daniel-mar | 658 | $key = hash_pbkdf2('sha512', $key, '', 10000, 32/*256bit*/, false); |
679 | daniel-mar | 659 | $k = new \Firebase\JWT\Key($key, 'HS512'); // HMAC+SHA512 is hardcoded here |
660 | $this->content = (array) \Firebase\JWT\JWT::decode($jwt, $k); |
||
570 | daniel-mar | 661 | } |
566 | daniel-mar | 662 | } |
663 | |||
1116 | daniel-mar | 664 | /** |
665 | * @return string |
||
666 | * @throws OIDplusException |
||
667 | */ |
||
668 | public function getJWTToken(): string { |
||
566 | daniel-mar | 669 | $payload = $this->content; |
1305 | daniel-mar | 670 | $payload[self::CLAIM_SSH] = self::getSsh(); // SSH = Server Secret Hash |
1307 | daniel-mar | 671 | // see also https://www.iana.org/assignments/jwt/jwt.xhtml#claims for some generic claims |
1317 | daniel-mar | 672 | if (!isset($payload["iss"])) $payload["iss"] = $this->getAudIss(); |
673 | if (!isset($payload["aud"])) $payload["aud"] = $this->getAudIss(); |
||
1321 | daniel-mar | 674 | $payload["jti"] = gen_uuid(); // always set/renew it; therefore not checking isset() |
675 | $payload["iat"] = time(); // always set/renew it; therefore not checking isset() |
||
1307 | daniel-mar | 676 | if (!isset($payload["nbf"])) $payload["nbf"] = time(); |
1306 | daniel-mar | 677 | if (!isset($payload["exp"])) $payload["exp"] = time()+3600/*1h*/; |
570 | daniel-mar | 678 | |
1310 | daniel-mar | 679 | if (!isset($payload[self::CLAIM_TRACE])) { |
680 | // "Trace" can be used for later updates |
||
681 | // For example, if the IP changes "too much" (different country, different AS, etc.) |
||
682 | // Or revoke all tokens from a single login flow (sequence 1, 2, 3, ...) |
||
683 | $payload[self::CLAIM_TRACE] = array(); |
||
1312 | daniel-mar | 684 | $payload[self::CLAIM_TRACE]['iat_1st'] = $payload["iat"]; |
1310 | daniel-mar | 685 | $payload[self::CLAIM_TRACE]['jti_1st'] = $payload["jti"]; |
686 | $payload[self::CLAIM_TRACE]['seq'] = 1; |
||
687 | $payload[self::CLAIM_TRACE]['ip'] = $_SERVER['REMOTE_ADDR'] ?? ''; |
||
688 | $payload[self::CLAIM_TRACE]['ip_1st'] = $payload[self::CLAIM_TRACE]['ip']; |
||
689 | $payload[self::CLAIM_TRACE]['ua'] = $_SERVER['HTTP_USER_AGENT'] ?? ''; |
||
690 | $payload[self::CLAIM_TRACE]['ua_1st'] = $payload[self::CLAIM_TRACE]['ua']; |
||
691 | } else { |
||
692 | assert(is_numeric($payload[self::CLAIM_TRACE]['seq'])); |
||
693 | $payload[self::CLAIM_TRACE]['seq']++; |
||
694 | $payload[self::CLAIM_TRACE]['ip'] = $_SERVER['REMOTE_ADDR'] ?? ''; |
||
695 | $payload[self::CLAIM_TRACE]['ua'] = $_SERVER['HTTP_USER_AGENT'] ?? ''; |
||
696 | } |
||
697 | |||
1306 | daniel-mar | 698 | uksort($payload, "strnatcmp"); // this is natsort on the key. Just to make the JWT look nicer. |
699 | |||
570 | daniel-mar | 700 | if (OIDplus::getPkiStatus()) { |
830 | daniel-mar | 701 | $privKey = OIDplus::getSystemPrivateKey(); |
1298 | daniel-mar | 702 | return \Firebase\JWT\JWT::encode($payload, $privKey, 'RS256'); // RSA+SHA256 is hardcoded in getPkiStatus() generation |
570 | daniel-mar | 703 | } else { |
1283 | daniel-mar | 704 | $key = OIDplus::authUtils()->makeSecret(['0be35e52-f4ef-11ed-b67e-3c4a92df8582']); |
826 | daniel-mar | 705 | $key = hash_pbkdf2('sha512', $key, '', 10000, 32/*256bit*/, false); |
679 | daniel-mar | 706 | return \Firebase\JWT\JWT::encode($payload, $key, 'HS512'); // HMAC+SHA512 is hardcoded here |
570 | daniel-mar | 707 | } |
566 | daniel-mar | 708 | } |
709 | |||
570 | daniel-mar | 710 | } |