Subversion Repositories oidplus

Rev

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