Subversion Repositories oidplus

Rev

Rev 1303 | Rev 1305 | 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 OIDplusAuthUtils extends OIDplusBaseClass {
  27.  
  28.         // Useful functions
  29.  
  30.         /**
  31.          * @param string $password
  32.          * @return string
  33.          * @throws OIDplusException
  34.          */
  35.         private function raPepperProcessing(string $password): string {
  36.                 // Additional feature: Pepper
  37.                 // The pepper is stored inside the base configuration file
  38.                 // It prevents that an attacker with SQL write rights can
  39.                 // create accounts.
  40.                 // ATTENTION!!! If a pepper is used, then the
  41.                 // hashes are bound to that pepper. If you change the pepper,
  42.                 // then ALL passwords of RAs become INVALID!
  43.                 $pepper = OIDplus::baseConfig()->getValue('RA_PASSWORD_PEPPER','');
  44.                 if ($pepper !== '') {
  45.                         $algo = OIDplus::baseConfig()->getValue('RA_PASSWORD_PEPPER_ALGO','sha512'); // sha512 works with PHP 7.0
  46.                         if (strtolower($algo) === 'sha3-512') {
  47.                                 $hmac = sha3_512_hmac($password, $pepper);
  48.                         } else {
  49.                                 $hmac = hash_hmac($algo, $password, $pepper);
  50.                         }
  51.                         if ($hmac === "") throw new OIDplusException(_L('HMAC failed'));
  52.                         return $hmac;
  53.                 } else {
  54.                         return $password;
  55.                 }
  56.         }
  57.  
  58.         // Content provider
  59.  
  60.         /**
  61.          * @return string
  62.          * @throws OIDplusException
  63.          */
  64.         public function getAuthMethod(): string {
  65.                 $acs = $this->getAuthContentStore();
  66.                 if (is_null($acs)) return 'null';
  67.                 return get_class($acs);
  68.         }
  69.  
  70.         /**
  71.          * @return OIDplusAuthContentStore|null
  72.          * @throws OIDplusException
  73.          */
  74.         protected function getAuthContentStore()/*: ?OIDplusAuthContentStore*/ {
  75.                 // Logged in via JWT
  76.                 // (The JWT can come from a REST Authentication Bearer, an AJAX Cookie, or an Automated AJAX Call GET/POST token.)
  77.                 $tmp = OIDplusAuthContentStoreJWT::getActiveProvider();
  78.                 if ($tmp) return $tmp;
  79.  
  80.                 // Normal login via web-browser
  81.                 // Cookie will only be created once content is stored
  82.                 $tmp = OIDplusAuthContentStoreSession::getActiveProvider();
  83.                 if ($tmp) return $tmp;
  84.  
  85.                 // No active session and no JWT token available. User is not logged in.
  86.                 return null;
  87.         }
  88.  
  89.         /**
  90.          * @param string $name
  91.          * @param mixed|null $default
  92.          * @return mixed
  93.          * @throws OIDplusException
  94.          */
  95.         public function getExtendedAttribute(string $name, $default=NULL) {
  96.                 $acs = $this->getAuthContentStore();
  97.                 if (is_null($acs)) return $default;
  98.                 return $acs->getValue($name, $default);
  99.         }
  100.  
  101.         // RA authentication functions
  102.  
  103.         /**
  104.          * @param string $email
  105.          * @return void
  106.          * @throws OIDplusException
  107.          */
  108.         public function raLogin(string $email) {
  109.                 $acs = $this->getAuthContentStore();
  110.                 if (is_null($acs)) return;
  111.                 $acs->raLogin($email);
  112.         }
  113.  
  114.         /**
  115.          * @param string $email
  116.          * @return void
  117.          * @throws OIDplusException
  118.          */
  119.         public function raLogout(string $email) {
  120.                 $acs = $this->getAuthContentStore();
  121.                 if (is_null($acs)) return;
  122.                 $acs->raLogout($email);
  123.         }
  124.  
  125.         /**
  126.          * @param string $ra_email
  127.          * @param string $password
  128.          * @return bool
  129.          * @throws OIDplusException
  130.          */
  131.         public function raCheckPassword(string $ra_email, string $password): bool {
  132.                 $ra = new OIDplusRA($ra_email);
  133.  
  134.                 // Get RA info from RA
  135.                 $authInfo = $ra->getAuthInfo();
  136.                 if (!$authInfo) return false; // user not found
  137.  
  138.                 // Ask plugins if they can verify this hash
  139.                 $plugins = OIDplus::getAuthPlugins();
  140.                 if (count($plugins) == 0) {
  141.                         throw new OIDplusException(_L('No RA authentication plugins found'));
  142.                 }
  143.                 foreach ($plugins as $plugin) {
  144.                         if ($plugin->verify($authInfo, $this->raPepperProcessing($password))) return true;
  145.                 }
  146.  
  147.                 return false;
  148.         }
  149.  
  150.         /**
  151.          * @return int
  152.          * @throws OIDplusException
  153.          */
  154.         public function raNumLoggedIn(): int {
  155.                 $acs = $this->getAuthContentStore();
  156.                 if (is_null($acs)) return 0;
  157.                 return $acs->raNumLoggedIn();
  158.         }
  159.  
  160.         /**
  161.          * @return OIDplusRA[]
  162.          * @throws OIDplusException
  163.          */
  164.         public function loggedInRaList(): array {
  165.                 if ($this->forceAllLoggedOut()) {
  166.                         return array();
  167.                 } else {
  168.                         $acs = $this->getAuthContentStore();
  169.                         if (is_null($acs)) return array();
  170.                         return $acs->loggedInRaList();
  171.                 }
  172.         }
  173.  
  174.         /**
  175.          * @param string|OIDplusRA $ra
  176.          * @return bool
  177.          * @throws OIDplusException
  178.          */
  179.         public function isRaLoggedIn($ra): bool {
  180.                 $email = $ra instanceof OIDplusRA ? $ra->raEmail() : $ra;
  181.                 $acs = $this->getAuthContentStore();
  182.                 if (is_null($acs)) return false;
  183.                 return $acs->isRaLoggedIn($email);
  184.         }
  185.  
  186.         // "High level" function including logging and checking for valid JWT alternations
  187.  
  188.         /**
  189.          * @param string $email
  190.          * @param bool $remember_me
  191.          * @param string $origin
  192.          * @return void
  193.          * @throws OIDplusException
  194.          */
  195.         public function raLoginEx(string $email, bool $remember_me, string $origin='') {
  196.                 $loginfo = '';
  197.                 $acs = $this->getAuthContentStore();
  198.                 if (!is_null($acs)) {
  199.                         // User is already logged in (a session or JWT exists), so we modify their login status
  200.                         $acs->raLoginEx($email, $loginfo);
  201.                         $acs->activate();
  202.                 } else {
  203.                         // No user is logged in (no session or JWT exists). We now create a auth content store and activate it (cookies will be set etc.)
  204.                         if ($remember_me) {
  205.                                 if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_USER', true)) {
  206.                                         throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_USER'));
  207.                                 }
  208.                                 $ttl = OIDplus::baseConfig()->getValue('JWT_TTL_LOGIN_USER', 10*365*24*60*60);
  209.                                 $newAuthStore = new OIDplusAuthContentStoreJWT();
  210.                                 $newAuthStore->setValue('oidplus_generator', OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN);
  211.                                 $newAuthStore->setValue('exp', time()+$ttl); // JWT "exp" attribute
  212.                         } else {
  213.                                 $newAuthStore = new OIDplusAuthContentStoreSession();
  214.                         }
  215.                         $newAuthStore->raLoginEx($email, $loginfo);
  216.                         $newAuthStore->activate();
  217.                 }
  218.                 $logmsg = "RA '$email' logged in";
  219.                 if ($origin != '') $logmsg .= " via $origin";
  220.                 if ($loginfo != '') $logmsg .= " ($loginfo)";
  221.                 OIDplus::logger()->log("V2:[OK]RA(%1)", "%2", $email, $logmsg);
  222.         }
  223.  
  224.         /**
  225.          * @param string $email
  226.          * @return void
  227.          * @throws OIDplusException
  228.          */
  229.         public function raLogoutEx(string $email) {
  230.                 $loginfo = '';
  231.  
  232.                 $acs = $this->getAuthContentStore();
  233.                 if (is_null($acs)) return;
  234.                 $acs->raLogoutEx($email, $loginfo);
  235.  
  236.                 OIDplus::logger()->log("V2:[OK]RA(%1)", "RA '%1' logged out (%2)", $email, $loginfo);
  237.  
  238.                 if (($this->raNumLoggedIn() == 0) && (!$this->isAdminLoggedIn())) {
  239.                         // Nobody logged in anymore. Destroy session cookie to make GDPR people happy
  240.                         $acs->destroySession();
  241.                 } else {
  242.                         // Get a new token for the remaining users
  243.                         $acs->activate();
  244.                 }
  245.         }
  246.  
  247.         // Admin authentication functions
  248.  
  249.         /**
  250.          * @return void
  251.          * @throws OIDplusException
  252.          */
  253.         public function adminLogin() {
  254.                 $acs = $this->getAuthContentStore();
  255.                 if (is_null($acs)) return;
  256.                 $acs->adminLogin();
  257.         }
  258.  
  259.         /**
  260.          * @return void
  261.          * @throws OIDplusException
  262.          */
  263.         public function adminLogout() {
  264.                 $acs = $this->getAuthContentStore();
  265.                 if (is_null($acs)) return;
  266.                 $acs->adminLogout();
  267.         }
  268.  
  269.         /**
  270.          * @param string $password
  271.          * @return bool
  272.          * @throws OIDplusException
  273.          */
  274.         public function adminCheckPassword(string $password): bool {
  275.                 $cfgData = OIDplus::baseConfig()->getValue('ADMIN_PASSWORD', '');
  276.                 if (empty($cfgData)) {
  277.                         throw new OIDplusException(_L('No admin password set in %1','userdata/baseconfig/config.inc.php'));
  278.                 }
  279.  
  280.                 if (!is_array($cfgData)) {
  281.                         $passwordDataArray = array($cfgData);
  282.                 } else {
  283.                         $passwordDataArray = $cfgData; // Multiple Administrator passwords
  284.                 }
  285.  
  286.                 foreach ($passwordDataArray as $passwordData) {
  287.                         if (str_starts_with($passwordData, '$')) {
  288.                                 // Version 3: BCrypt (or any other crypt)
  289.                                 $ok = password_verify($password, $passwordData);
  290.                         } else if (strpos($passwordData, '$') !== false) {
  291.                                 // Version 2: SHA3-512 with salt
  292.                                 list($salt, $hash) = explode('$', $passwordData, 2);
  293.                                 $ok = hash_equals(sha3_512($salt.$password, true), base64_decode($hash));
  294.                         } else {
  295.                                 // Version 1: SHA3-512 without salt
  296.                                 $ok = hash_equals(sha3_512($password, true), base64_decode($passwordData));
  297.                         }
  298.                         if ($ok) return true;
  299.                 }
  300.  
  301.                 return false;
  302.         }
  303.  
  304.         /**
  305.          * @return bool
  306.          * @throws OIDplusException
  307.          */
  308.         public function isAdminLoggedIn(): bool {
  309.                 if ($this->forceAllLoggedOut()) {
  310.                         return false;
  311.                 } else {
  312.                         $acs = $this->getAuthContentStore();
  313.                         if (is_null($acs)) return false;
  314.                         return $acs->isAdminLoggedIn();
  315.                 }
  316.         }
  317.  
  318.         /**
  319.          * "High level" function including logging and checking for valid JWT alternations
  320.          * @param bool $remember_me
  321.          * @param string $origin
  322.          * @return void
  323.          * @throws OIDplusException
  324.          */
  325.         public function adminLoginEx(bool $remember_me, string $origin='') {
  326.                 $loginfo = '';
  327.                 $acs = $this->getAuthContentStore();
  328.                 if (!is_null($acs)) {
  329.                         // User is already logged in (a session or JWT exists), so we modify their login status
  330.                         $acs->adminLoginEx($loginfo);
  331.                         $acs->activate();
  332.                 } else {
  333.                         // No user is logged in (no session or JWT exists). We now create a auth content store and activate it (cookies will be set etc.)
  334.                         if ($remember_me) {
  335.                                 if (!OIDplus::baseConfig()->getValue('JWT_ALLOW_LOGIN_ADMIN', true)) {
  336.                                         throw new OIDplusException(_L('The administrator has disabled this feature. (Base configuration setting %1).','JWT_ALLOW_LOGIN_ADMIN'));
  337.                                 }
  338.                                 $ttl = OIDplus::baseConfig()->getValue('JWT_TTL_LOGIN_ADMIN', 10*365*24*60*60);
  339.                                 $newAuthStore = new OIDplusAuthContentStoreJWT();
  340.                                 $newAuthStore->setValue('oidplus_generator', OIDplusAuthContentStoreJWT::JWT_GENERATOR_LOGIN);
  341.                                 $newAuthStore->setValue('exp', time()+$ttl); // JWT "exp" attribute
  342.                         } else {
  343.                                 $newAuthStore = new OIDplusAuthContentStoreSession();
  344.                         }
  345.                         $newAuthStore->adminLoginEx($loginfo);
  346.                         $newAuthStore->activate();
  347.                 }
  348.                 $logmsg = "Admin logged in";
  349.                 if ($origin != '') $logmsg .= " via $origin";
  350.                 if ($loginfo != '') $logmsg .= " ($loginfo)";
  351.                 OIDplus::logger()->log("V2:[OK]A", "%1", $logmsg);
  352.         }
  353.  
  354.         /**
  355.          * @return void
  356.          * @throws OIDplusException
  357.          */
  358.         public function adminLogoutEx() {
  359.                 $loginfo = '';
  360.  
  361.                 $acs = $this->getAuthContentStore();
  362.                 if (is_null($acs)) return;
  363.                 $acs->adminLogoutEx($loginfo);
  364.  
  365.                 if ($this->raNumLoggedIn() == 0) {
  366.                         // Nobody here anymore. Destroy the cookie to make GDPR people happy
  367.                         $acs->destroySession();
  368.                 } else {
  369.                         // Get a new token for the remaining users
  370.                         $acs->activate();
  371.                 }
  372.  
  373.                 OIDplus::logger()->log("V2:[OK]A", "Admin logged out (%1)", $loginfo);
  374.         }
  375.  
  376.         // Authentication keys for generating secrets or validating arguments (e.g. sent by mail)
  377.  
  378.         /**
  379.          * @param array|string $data
  380.          * @return string
  381.          * @throws OIDplusException
  382.          */
  383.         public function makeSecret($data): string {
  384.                 if (!is_array($data)) $data = [$data];
  385.                 $data = json_encode($data);
  386.                 return sha3_512_hmac($data, 'OIDplus:'.OIDplus::baseConfig()->getValue('SERVER_SECRET'), false);
  387.         }
  388.  
  389.         /**
  390.          * @param array|string $data Arbitary data to be validated later
  391.          * @return string A string that need to be validated with validateAuthKey
  392.          * @throws OIDplusException
  393.          */
  394.         public function makeAuthKey($data): string {
  395.                 if (!is_array($data)) $data = [$data];
  396.                 $ts = time();
  397.                 $data_ext = [$ts, $data];
  398.                 $secret = $this->makeSecret($data_ext);
  399.                 return $ts.'.'.$secret;
  400.         }
  401.  
  402.         /**
  403.          * @param array|string $data The original data that had been passed to makeAuthKey()
  404.          * @param string $auth_key The result from makeAuthKey()
  405.          * @param int $valid_secs How many seconds is the auth key valid? (-1 for infinite)
  406.          * @return bool True if the key is valid and not expired.
  407.          * @throws OIDplusException
  408.          */
  409.         public function validateAuthKey($data, string $auth_key, int $valid_secs=-1): bool {
  410.                 $auth_key_ary = explode('.', $auth_key, 2);
  411.                 if (count($auth_key_ary) != 2) return false; // invalid auth key syntax
  412.                 list($ts, $secret) = $auth_key_ary;
  413.                 if (!is_numeric($ts)) return false; // invalid auth key syntax
  414.                 if ($valid_secs >= 0) {
  415.                         if (time() > ($ts+$valid_secs)) return false; // expired auth key
  416.                 }
  417.                 if (!is_array($data)) $data = [$data];
  418.                 $data_ext = [(int)$ts, $data];
  419.                 return hash_equals($this->makeSecret($data_ext), $secret);
  420.         }
  421.  
  422.         // "Veto" functions to force logout state
  423.  
  424.         /**
  425.          * @return bool
  426.          */
  427.         protected function forceAllLoggedOut(): bool {
  428.                 if (isset($_SERVER['SCRIPT_FILENAME']) && (basename($_SERVER['SCRIPT_FILENAME']) == 'sitemap.php')) {
  429.                         // The sitemap may not contain any confidential information,
  430.                         // even if the user is logged in, because the admin could
  431.                         // accidentally copy-paste the sitemap to a
  432.                         // search engine control panel while they are logged in
  433.                         return true;
  434.                 } else {
  435.                         return false;
  436.                 }
  437.         }
  438.  
  439.         // CSRF functions
  440.  
  441.         private $enable_csrf = true;
  442.  
  443.         /**
  444.          * @return void
  445.          */
  446.         public function enableCSRF() {
  447.                 $this->enable_csrf = true;
  448.         }
  449.  
  450.         /**
  451.          * @return void
  452.          */
  453.         public function disableCSRF() {
  454.                 $this->enable_csrf = false;
  455.         }
  456.  
  457.         /**
  458.          * @return string
  459.          * @throws \Random\RandomException
  460.          */
  461.         public function genCSRFToken(): string {
  462.                 return random_bytes_ex(64, false, false);
  463.         }
  464.  
  465.         /**
  466.          * @return void
  467.          * @throws OIDplusException
  468.          */
  469.         public function checkCSRF() {
  470.                 if (!$this->enable_csrf) return;
  471.  
  472.                 $request_token = $_REQUEST['csrf_token'] ?? '';
  473.                 $cookie_token = $_COOKIE['csrf_token'] ?? '';
  474.  
  475.                 if (empty($request_token) || empty($cookie_token) || ($request_token !== $cookie_token)) {
  476.                         if (OIDplus::baseConfig()->getValue('DEBUG')) {
  477.                                 throw new OIDplusException(_L('Missing or wrong CSRF Token: Request %1 vs Cookie %2',
  478.                                         isset($_REQUEST['csrf_token']) ? '"'.$_REQUEST['csrf_token'].'"' : 'NULL',
  479.                                         $_COOKIE['csrf_token'] ?? 'NULL'
  480.                                 ));
  481.                         } else {
  482.                                 throw new OIDplusException(_L('Missing or wrong "CSRF Token". To fix the issue, try clearing your browser cache and reload the page. If you visited the page via HTTPS before, try HTTPS in case you are currently connected via HTTP.'));
  483.                         }
  484.                 }
  485.         }
  486.  
  487.         // Generate RA passwords
  488.  
  489.         /**
  490.          * @param string $password
  491.          * @return OIDplusRAAuthInfo
  492.          * @throws OIDplusException
  493.          */
  494.         public function raGeneratePassword(string $password): OIDplusRAAuthInfo {
  495.                 $plugin = OIDplus::getDefaultRaAuthPlugin(true);
  496.                 return $plugin->generate($this->raPepperProcessing($password));
  497.         }
  498.  
  499.         // Generate admin password
  500.  
  501.         /* Nothing here; the admin password will be generated in setup_base.js , purely in the web-browser */
  502.  
  503. }
  504.