Subversion Repositories oidplus

Rev

Rev 1283 | Rev 1300 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  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.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusAuthContentStoreJWT extends OIDplusAuthContentStoreDummy {
  27.  
  28.         /**
  29.          * Cookie name for the JWT auth token
  30.          */
  31.         const COOKIE_NAME = 'OIDPLUS_AUTH_JWT';
  32.  
  33.         /**
  34.          * "Automated AJAX" plugin
  35.          */
  36.         const JWT_GENERATOR_AJAX   = 10;
  37.         /**
  38.          * "REST API" plugin
  39.          */
  40.         const JWT_GENERATOR_REST   = 20;
  41.         /**
  42.          * "Remember me" login method
  43.          */
  44.         const JWT_GENERATOR_LOGIN  = 40;
  45.         /**
  46.          * "Manually crafted" JWT tokens
  47.          */
  48.         const JWT_GENERATOR_MANUAL = 80;
  49.  
  50.         /**
  51.          * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_...
  52.          * @param string $sub
  53.          * @return string
  54.          */
  55.         private static function jwtGetBlacklistConfigKey(int $gen, string $sub): string {
  56.                 // Note: Needs to be <= 50 characters! If $gen is 2 chars, then the config key is 49 chars long
  57.                 return 'jwt_blacklist_gen('.$gen.')_sub('.trim(base64_encode(md5($sub,true)),'=').')';
  58.         }
  59.  
  60.         /**
  61.          * @param int $gen
  62.          */
  63.         private static function generatorName($gen) {
  64.                 // Note: The strings are not translated, because the name is used in config keys or logs
  65.                 if ($gen === self::JWT_GENERATOR_AJAX)   return 'Automated AJAX calls';
  66.                 if ($gen === self::JWT_GENERATOR_REST)   return 'REST API';
  67.                 if ($gen === self::JWT_GENERATOR_LOGIN)  return 'Login ("Remember me")';
  68.                 if ($gen === self::JWT_GENERATOR_MANUAL) return 'Manually created';
  69.                 return 'Unknown generator';
  70.         }
  71.  
  72.         /**
  73.          * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_...
  74.          * @param string $sub
  75.          * @return void
  76.          * @throws OIDplusException
  77.          */
  78.         public static function jwtBlacklist(int $gen, string $sub) {
  79.                 $cfg = self::jwtGetBlacklistConfigKey($gen, $sub);
  80.                 $bl_time = time()-1;
  81.  
  82.                 $gen_desc = self::generatorName($gen);
  83.  
  84.                 OIDplus::config()->prepareConfigKey($cfg, 'Revoke timestamp of all JWT tokens for $sub with generator $gen ($gen_desc)', "$bl_time", OIDplusConfig::PROTECTION_HIDDEN, function($value) {});
  85.                 OIDplus::config()->setValue($cfg, $bl_time);
  86.         }
  87.  
  88.         /**
  89.          * @param int $gen OIDplusAuthContentStoreJWT::JWT_GENERATOR_...
  90.          * @param string $sub
  91.          * @return int
  92.          * @throws OIDplusException
  93.          */
  94.         public static function jwtGetBlacklistTime(int $gen, string $sub): int {
  95.                 $cfg = self::jwtGetBlacklistConfigKey($gen, $sub);
  96.                 return (int)OIDplus::config()->getValue($cfg,0);
  97.         }
  98.  
  99.         /**
  100.          * 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
  101.          * @return string
  102.          * @throws OIDplusException
  103.          */
  104.         private static function getSsh(): string {
  105.                 return OIDplus::authUtils()->makeSecret(['bb1aebd6-fe6a-11ed-a553-3c4a92df8582']);
  106.         }
  107.  
  108.         /**
  109.          * Do various checks if the token is allowed and not blacklisted
  110.          * @param OIDplusAuthContentStore $contentProvider
  111.          * @param int|null $validGenerators Bitmask which generators to allow (null = allow all)
  112.          * @return void
  113.          * @throws OIDplusException
  114.          */
  115.         private static function jwtSecurityCheck(OIDplusAuthContentStore $contentProvider, int $validGenerators=null) {
  116.                 // Check if the token is intended for us
  117.                 if ($contentProvider->getValue('aud','') !== OIDplus::getEditionInfo()['jwtaud']) {
  118.                         throw new OIDplusException(_L('Token has wrong audience'));
  119.                 }
  120.  
  121.                 if ($contentProvider->getValue('oidplus_ssh', '') !== self::getSsh()) {
  122.                         throw new OIDplusException(_L('"Server Secret" was changed; therefore the JWT is not valid anymore'));
  123.                 }
  124.  
  125.                 $gen = $contentProvider->getValue('oidplus_generator', -1);
  126.  
  127.                 $has_admin = $contentProvider->isAdminLoggedIn();
  128.                 $has_ra = $contentProvider->raNumLoggedIn() > 0;
  129.  
  130.                 // Check if the token generator is allowed
  131.                 if ($gen === self::JWT_GENERATOR_AJAX) {
  132.                         if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_AJAX_ADMIN', true)) {
  133.                                 // Generator: plugins/viathinksoft/adminPages/910_automated_ajax_calls/OIDplusPageAdminAutomatedAJAXCalls.class.php
  134.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_AJAX_ADMIN'));
  135.                         }
  136.                         if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_AJAX_USER', true)) {
  137.                                 // Generator: plugins/viathinksoft/raPages/910_automated_ajax_calls/OIDplusPageRaAutomatedAJAXCalls.class.php
  138.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_AJAX_USER'));
  139.                         }
  140.                 }
  141.                 else if ($gen === self::JWT_GENERATOR_REST) {
  142.                         if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_REST_ADMIN', true)) {
  143.                                 // Generator: plugins/viathinksoft/adminPages/911_rest_api/OIDplusPageAdminRestApi.class.php
  144.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_REST_ADMIN'));
  145.                         }
  146.                         if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_REST_USER', true)) {
  147.                                 // Generator: plugins/viathinksoft/raPages/911_rest_api/OIDplusPageRaRestApi.class.php
  148.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_REST_USER'));
  149.                         }
  150.                 }
  151.                 else if ($gen === self::JWT_GENERATOR_LOGIN) {
  152.                         // Used for feature "Remember me" (use JWT token in a cookie as alternative to PHP session):
  153.                         // - No PHP session will be used
  154.                         // - Session will not be bound to IP address (therefore, you can switch between mobile/WiFi for example)
  155.                         // - No server-side session needed
  156.                         if (($has_admin) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) {
  157.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_ADMIN'));
  158.                         }
  159.                         if (($has_ra) && !OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) {
  160.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_USER'));
  161.                         }
  162.                 }
  163.                 else if ($gen === self::JWT_GENERATOR_MANUAL) {
  164.                         // Generator 2 are "hand-crafted" tokens
  165.                         if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_MANUAL', false)) {
  166.                                 throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_MANUAL'));
  167.                         }
  168.                 } else {
  169.                         throw new OIDplusException(_L('Token generator %1 not recognized',$gen));
  170.                 }
  171.  
  172.                 // Make sure that the IAT (issued at time) isn't in a blacklisted timeframe
  173.                 // When an user believes that a token was compromised, then they can blacklist the tokens identified by their "iat" ("Issued at") property
  174.                 // When a user logs out of a "remember me" session, the JWT token will be blacklisted as well
  175.                 // Small side effect: All "remember me" sessions of that user will be revoked then
  176.                 $iat = $contentProvider->getValue('iat',0);
  177.                 if (($iat-120/*leeway 2min*/) > time()) {
  178.                         // Token was created in the future. Something is wrong!
  179.                         throw new OIDplusException(_L('JWT Token cannot be verified because the server time is wrong'));
  180.                 }
  181.                 $sublist = $contentProvider->loggedInRaList();
  182.                 $usernames = array();
  183.                 foreach ($sublist as $sub) {
  184.                         $usernames[] = $sub->raEmail();
  185.                 }
  186.                 if ($has_admin) $usernames[] = 'admin';
  187.                 foreach ($usernames as $username) {
  188.                         $bl_time = self::jwtGetBlacklistTime($gen, $username);
  189.                         if ($iat <= $bl_time) {
  190.                                 // Token is blacklisted (it was created before the last blacklist time)
  191.                                 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)));
  192.                         }
  193.                 }
  194.  
  195.                 // Optional feature: Limit the JWT to a specific IP address
  196.                 // Currently not used in OIDplus
  197.                 $ip = $contentProvider->getValue('ip','');
  198.                 if ($ip !== '') {
  199.                         if (isset($_SERVER['REMOTE_ADDR']) && ($ip !== $_SERVER['REMOTE_ADDR'])) {
  200.                                 throw new OIDplusException(_L('Your IP address is not allowed to use this token'));
  201.                         }
  202.                 }
  203.  
  204.                 // Checks if JWT are dependent on the generator
  205.                 if (!is_null($validGenerators)) {
  206.                         if (($gen & $validGenerators) === 0) {
  207.                                 throw new OIDplusException(_L('This kind of JWT token (%1) cannot be used in this request type', self::generatorName($gen)));
  208.                         }
  209.                 }
  210.         }
  211.  
  212.         // Override abstract functions
  213.  
  214.         /**
  215.          * @return void
  216.          */
  217.         public function activate() {
  218.                 // Send cookie at the end of the HTTP request, in case there are multiple activate() calls
  219.                 OIDplus::register_shutdown_function(array($this,'activateNow'));
  220.         }
  221.  
  222.         /**
  223.          * @return void
  224.          * @throws OIDplusException
  225.          */
  226.         public function activateNow() {
  227.                 $token = $this->getJWTToken();
  228.                 $exp = $this->getValue('exp',0);
  229.                 OIDplus::cookieUtils()->setcookie(self::COOKIE_NAME, $token, $exp, false);
  230.         }
  231.  
  232.         /**
  233.          * @return void
  234.          * @throws OIDplusException
  235.          */
  236.         public function destroySession() {
  237.                 OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME);
  238.         }
  239.  
  240.         /**
  241.          * @param string $email
  242.          * @return void
  243.          * @throws OIDplusException
  244.          */
  245.         public function raLogout(string $email) {
  246.                 $gen = $this->getValue('oidplus_generator', -1);
  247.                 if ($gen >= 0) self::jwtBlacklist($gen, $email);
  248.                 parent::raLogout($email);
  249.         }
  250.  
  251.         /**
  252.          * @param string $email
  253.          * @param string $loginfo
  254.          * @return void
  255.          * @throws OIDplusException
  256.          */
  257.         public function raLogoutEx(string $email, string &$loginfo) {
  258.                 $this->raLogout($email);
  259.                 $loginfo = 'from JWT session';
  260.         }
  261.  
  262.         /**
  263.          * @return void
  264.          * @throws OIDplusException
  265.          */
  266.         public function adminLogout() {
  267.                 $gen = $this->getValue('oidplus_generator', -1);
  268.                 if ($gen >= 0) self::jwtBlacklist($gen, 'admin');
  269.                 parent::adminLogout();
  270.         }
  271.  
  272.         /**
  273.          * @param string $loginfo
  274.          * @return void
  275.          * @throws OIDplusException
  276.          */
  277.         public function adminLogoutEx(string &$loginfo) {
  278.                 $this->adminLogout();
  279.                 $loginfo = 'from JWT session';
  280.         }
  281.  
  282.         private static $contentProvider = null;
  283.  
  284.         /**
  285.          * @return OIDplusAuthContentStore|null
  286.          * @throws OIDplusException
  287.          */
  288.         public static function getActiveProvider()/*: ?OIDplusAuthContentStore*/ {
  289.                 if (!self::$contentProvider) {
  290.  
  291.                         $tmp = null;
  292.                         $silent_error = false;
  293.  
  294.                         try {
  295.  
  296.                                 $rel_url = substr($_SERVER['REQUEST_URI'], strlen(OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT)));
  297.                                 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.
  298.  
  299.                                         // REST may only use Bearer Authentication
  300.                                         $bearer = getBearerToken();
  301.                                         if (!is_null($bearer)) {
  302.                                                 $silent_error = false;
  303.                                                 $tmp = new OIDplusAuthContentStoreJWT();
  304.                                                 $tmp->loadJWT($bearer);
  305.                                                 self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_REST | self::JWT_GENERATOR_MANUAL);
  306.                                         }
  307.  
  308.                                 } else {
  309.  
  310.                                         // A web-visitor (HTML and AJAX, but not REST) can use a JWT "remember me" Cookie
  311.                                         if (isset($_COOKIE[self::COOKIE_NAME])) {
  312.                                                 $silent_error = true;
  313.                                                 $tmp = new OIDplusAuthContentStoreJWT();
  314.                                                 $tmp->loadJWT($_COOKIE[self::COOKIE_NAME]);
  315.                                                 self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_LOGIN | self::JWT_GENERATOR_MANUAL);
  316.                                         }
  317.  
  318.                                         // AJAX may additionally use GET/POST automated AJAX (in addition to the normal JWT "remember me" Cookie)
  319.                                         if (isset($_SERVER['SCRIPT_FILENAME']) && (strtolower(basename($_SERVER['SCRIPT_FILENAME'])) !== 'ajax.php')) {
  320.                                                 if (isset($_POST[self::COOKIE_NAME])) {
  321.                                                         $silent_error = false;
  322.                                                         $tmp = new OIDplusAuthContentStoreJWT();
  323.                                                         $tmp->loadJWT($_POST[self::COOKIE_NAME]);
  324.                                                         self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_AJAX | self::JWT_GENERATOR_MANUAL);
  325.                                                 }
  326.                                                 if (isset($_GET[self::COOKIE_NAME])) {
  327.                                                         $silent_error = false;
  328.                                                         $tmp = new OIDplusAuthContentStoreJWT();
  329.                                                         $tmp->loadJWT($_GET[self::COOKIE_NAME]);
  330.                                                         self::jwtSecurityCheck($tmp, self::JWT_GENERATOR_AJAX | self::JWT_GENERATOR_MANUAL);
  331.                                                 }
  332.                                         }
  333.  
  334.                                 }
  335.  
  336.                         } catch (\Exception $e) {
  337.                                 if (!$silent_error) {
  338.                                         // Most likely an AJAX request. We can throw an Exception
  339.                                         throw new OIDplusException(_L('The JWT token was rejected: %1',$e->getMessage()));
  340.                                 } else {
  341.                                         // Most likely an expired Cookie/Login session. We must not throw an Exception, otherwise we will break jsTree
  342.                                         OIDplus::cookieUtils()->unsetcookie(self::COOKIE_NAME);
  343.                                         return null;
  344.                                 }
  345.                         }
  346.  
  347.                         self::$contentProvider = $tmp;
  348.                 }
  349.  
  350.                 return self::$contentProvider;
  351.         }
  352.  
  353.         /**
  354.          * @param string $email
  355.          * @param string $loginfo
  356.          * @return void
  357.          * @throws OIDplusException
  358.          */
  359.         public function raLoginEx(string $email, string &$loginfo) {
  360.                 if (is_null(self::getActiveProvider())) {
  361.                         $this->raLogin($email);
  362.                         $loginfo = 'into new JWT session';
  363.                         self::$contentProvider = $this;
  364.                 } else {
  365.                         $gen = $this->getValue('oidplus_generator',-1);
  366.                         switch ($gen) {
  367.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_AJAX :
  368.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_REST :
  369.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_MANUAL :
  370.                                         throw new OIDplusException(_L('This kind of JWT token cannot be altered. Therefore you cannot do this action.'));
  371.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN :
  372.                                         if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) {
  373.                                                 throw new OIDplusException(_L('You cannot add this login credential to your existing "remember me" session. You need to log-out first.'));
  374.                                         }
  375.                                         break;
  376.                                 default:
  377.                                         assert(false); // This cannot happen because jwtSecurityCheck will check for unknown generators
  378.                                         break;
  379.                         }
  380.                         $this->raLogin($email);
  381.                         $loginfo = 'into existing JWT session';
  382.                 }
  383.         }
  384.  
  385.         /**
  386.          * @param string $loginfo
  387.          * @return void
  388.          * @throws OIDplusException
  389.          */
  390.         public function adminLoginEx(string &$loginfo) {
  391.                 if (is_null(self::getActiveProvider())) {
  392.                         $this->adminLogin();
  393.                         $loginfo = 'into new JWT session';
  394.                         self::$contentProvider = $this;
  395.                 } else {
  396.                         $gen = $this->getValue('oidplus_generator',-1);
  397.                         switch ($gen) {
  398.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_AJAX :
  399.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_REST :
  400.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_MANUAL :
  401.                                         throw new OIDplusException(_L('This kind of JWT token cannot be altered. Therefore you cannot do this action.'));
  402.                                 case OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN :
  403.                                         if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) {
  404.                                                 throw new OIDplusException(_L('You cannot add this login credential to your existing "remember me" session. You need to log-out first.'));
  405.                                         }
  406.                                         break;
  407.                                 default:
  408.                                         assert(false); // This cannot happen because jwtSecurityCheck will check for unknown generators
  409.                                         break;
  410.                         }
  411.                         $this->adminLogin();
  412.                         $loginfo = 'into existing JWT session';
  413.                 }
  414.         }
  415.  
  416.         // Individual functions
  417.  
  418.         /**
  419.          * Decode the JWT. In this step, the signature as well as EXP/NBF times will be checked
  420.          * @param string $jwt
  421.          * @return void
  422.          * @throws OIDplusException
  423.          */
  424.         public function loadJWT(string $jwt) {
  425.                 \Firebase\JWT\JWT::$leeway = 60; // leeway in seconds
  426.                 if (OIDplus::getPkiStatus()) {
  427.                         $pubKey = OIDplus::getSystemPublicKey();
  428.                         $k = new \Firebase\JWT\Key($pubKey, 'RS256'); // RSA+SHA256 is hardcoded in getPkiStatus() generation
  429.                         $this->content = (array) \Firebase\JWT\JWT::decode($jwt, $k);
  430.                 } else {
  431.                         $key = OIDplus::authUtils()->makeSecret(['0be35e52-f4ef-11ed-b67e-3c4a92df8582']);
  432.                         $key = hash_pbkdf2('sha512', $key, '', 10000, 32/*256bit*/, false);
  433.                         $k = new \Firebase\JWT\Key($key, 'HS512'); // HMAC+SHA512 is hardcoded here
  434.                         $this->content = (array) \Firebase\JWT\JWT::decode($jwt, $k);
  435.                 }
  436.         }
  437.  
  438.         /**
  439.          * @return string
  440.          * @throws OIDplusException
  441.          */
  442.         public function getJWTToken(): string {
  443.                 $payload = $this->content;
  444.                 $payload["iss"] = OIDplus::getEditionInfo()['jwtaud'];
  445.                 $payload["aud"] = OIDplus::getEditionInfo()['jwtaud'];
  446.                 $payload["jti"] = gen_uuid();
  447.                 $payload["iat"] = time();
  448.                 $payload["oidplus_ssh"] = self::getSsh(); // SSH = Server Secret Hash
  449.  
  450.                 if (OIDplus::getPkiStatus()) {
  451.                         $privKey = OIDplus::getSystemPrivateKey();
  452.                         return \Firebase\JWT\JWT::encode($payload, $privKey, 'RS256'); // RSA+SHA256 is hardcoded in getPkiStatus() generation
  453.                 } else {
  454.                         $key = OIDplus::authUtils()->makeSecret(['0be35e52-f4ef-11ed-b67e-3c4a92df8582']);
  455.                         $key = hash_pbkdf2('sha512', $key, '', 10000, 32/*256bit*/, false);
  456.                         return \Firebase\JWT\JWT::encode($payload, $key, 'HS512'); // HMAC+SHA512 is hardcoded here
  457.                 }
  458.         }
  459.  
  460. }
  461.