| 1 | <?php |
| 2 | /* This Source Code Form is subject to the terms of the Mozilla Public |
| 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this file, |
| 4 | * You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 5 | |
| 6 | class AuthUtils { |
| 7 | // KaiRo.at authentication utilities PHP class |
| 8 | // This class contains helper functions for the authentication system. |
| 9 | // |
| 10 | // function __construct() |
| 11 | // CONSTRUCTOR |
| 12 | // |
| 13 | // public $settings |
| 14 | // An array of settings for the auth server website. |
| 15 | // |
| 16 | // public $db |
| 17 | // A PDO database object for interaction. |
| 18 | // |
| 19 | // public $running_on_localhost |
| 20 | // A boolean telling if the system is running on localhost (where https is not required). |
| 21 | // |
| 22 | // public $client_reg_email_whitelist |
| 23 | // An array of emails that are whitelisted for registering clients. |
| 24 | // |
| 25 | // private $pwd_cost |
| 26 | // The cost parameter for use with PHP password_hash function. |
| 27 | // |
| 28 | // private $pwd_nonces |
| 29 | // The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used. |
| 30 | // Generate a nonce with this command: |openssl rand -base64 48| |
| 31 | // |
| 32 | // function log($code, $additional_info) |
| 33 | // Log an entry for admin purposes, with a code and some additional info. |
| 34 | // |
| 35 | // function checkForSecureConnection() |
| 36 | // Check is the connection is secure and return an array of error messages (empty if it's secure). |
| 37 | // |
| 38 | // function sendSecurityHeaders() |
| 39 | // Rend HTTP headers for improving security. |
| 40 | // |
| 41 | // function initSession() |
| 42 | // Initialize a session. Returns an associative array of all the DB fields of the session. |
| 43 | // |
| 44 | // function getLoginSession($user) |
| 45 | // Return an associative array of a session with the given user logged in (new if user changed compared to given previous session, otherwise updated variant of that previous session). |
| 46 | // |
| 47 | // function setRedirect($session, $redirect) |
| 48 | // Set a redirect on the session for performing later. Returns true if a redirect was saved, otherwise false. |
| 49 | // |
| 50 | // function doRedirectIfSet($session) |
| 51 | // If the session has a redirect set, perform it. Returns true if a redirect was performed, otherwise false. |
| 52 | // |
| 53 | // function resetRedirect($session) |
| 54 | // If the session has a redirect set, remove it. Returns true if a redirect was removed, otherwise false. |
| 55 | // |
| 56 | // function getDomainBaseURL() |
| 57 | // Get the base URL of the current domain, e.g. 'https://example.com'. |
| 58 | // |
| 59 | // function checkPasswordConstraints($new_password, $user_email) |
| 60 | // Check password constraints and return an array of error messages (empty if all constraints are met). |
| 61 | // |
| 62 | // function createSessionKey() |
| 63 | // Return a random session key. |
| 64 | // |
| 65 | // function createVerificationCode() |
| 66 | // Return a random acount/email verification code. |
| 67 | // |
| 68 | // function createClientSecret() |
| 69 | // Return a random client secret. |
| 70 | // |
| 71 | // function createTimeCode($session, [$offset], [$validity_minutes]) |
| 72 | // Return a time-based code based on the key and ID of the given session. |
| 73 | // An offset can be given to create a specific code for verification, otherwise and offset will be generated. |
| 74 | // Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used. |
| 75 | // |
| 76 | // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes]) |
| 77 | // Verify a given time-based code and return true if it's valid or false if it's not. |
| 78 | // See createTimeCode() documentation for the session and validity paramerters. |
| 79 | // |
| 80 | // function pwdHash($new_password) |
| 81 | // Return a hash for the given password. |
| 82 | // |
| 83 | // function pwdVerify($password_to_verify, $user) |
| 84 | // Return true if the password verifies against the pwdhash field of the user, false if not. |
| 85 | // |
| 86 | // function pwdNeedsRehash($user) |
| 87 | // Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed. |
| 88 | // |
| 89 | // function setUpL10n() |
| 90 | // Set up the localization stack (gettext). |
| 91 | // |
| 92 | // function negotiateLocale($supportedLanguages) |
| 93 | // Return the language to use out of the given array of supported locales, via netotiation based on the HTTP Accept-Language header. |
| 94 | // |
| 95 | // function getGroupedEmails($group_id, [$exclude_email]) |
| 96 | // Return all emails grouped in the specified group ID, optionally exclude a specific email (e.g. because you only want non-current entries) |
| 97 | // |
| 98 | // function getOAuthServer() |
| 99 | // Return an OAuth2 server object to use for all our actual OAuth2 interaction. |
| 100 | // |
| 101 | // function initHTMLDocument($titletext, [$headlinetext]) { |
| 102 | // initialize the HTML document for the auth system, with some elements we always use, esp. all the scripts and stylesheet. |
| 103 | // Sets the title of the document to the given title, the main headline will be the same as the title if not set explicitly. |
| 104 | // Returns an associative array with the following elements: 'document', 'html', 'head', 'title', 'body'. |
| 105 | // |
| 106 | // function appendLoginForm($dom_element, $session, $user, [$addfields]) |
| 107 | // Append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array. |
| 108 | // The optional $addfields parameter is an array of name=>value pairs of hidden fields to add to the form. |
| 109 | // |
| 110 | // function updateDBSchema() |
| 111 | // update DB Schema to current requirements as specified by getDBSchema(). |
| 112 | // |
| 113 | // function getDBSchema() |
| 114 | // Return a DB schema with all tables, fields, etc. that the app requires. |
| 115 | |
| 116 | function __construct() { |
| 117 | // *** constructor *** |
| 118 | $this->settings = json_decode(@file_get_contents('/etc/kairo/auth_settings.json'), true); |
| 119 | if (!is_array($this->settings)) { throw new ErrorException('Authentication system settings not found', 0); } |
| 120 | |
| 121 | // Sanitize settings. |
| 122 | $this->settings['piwik_enabled'] = (@$this->settings['piwik_enabled']) ? true : false; |
| 123 | $this->settings['piwik_site_id'] = intval(@$this->settings['piwik_site_id']); |
| 124 | $this->settings['piwik_url'] = strlen(@$this->settings['piwik_url']) ? $this->settings['piwik_url'] : '/matomo/'; |
| 125 | $this->settings['piwik_tracker_path'] = strlen(@$this->settings['piwik_tracker_path']) ? $this->settings['piwik_tracker_path'] : '../vendor/matomo/matomo-php-tracker/'; |
| 126 | $this->settings['skin'] = (@$this->settings['skin'] && is_dir('skin/'.$this->settings['skin'])) ? $this->settings['skin'] : 'default'; |
| 127 | $this->settings['operator_name'] = (@$this->settings['operator_name']) ? $this->settings['operator_name'] : 'Example'; |
| 128 | $this->settings['operator_contact_url'] = (@$this->settings['operator_contact_url']) ? $this->settings['operator_contact_url'] : 'https://github.com/KaiRo_at/authserver/'; |
| 129 | $this->settings['info_from_email'] = (@$this->settings['info_from_email']) ? $this->settings['info_from_email'] : 'noreply@example.com'; |
| 130 | |
| 131 | // Initialize database. |
| 132 | $config = new \Doctrine\DBAL\Configuration(); |
| 133 | $connectionParams = array( |
| 134 | 'dbname' => $this->settings['db_name'], |
| 135 | 'user' => $this->settings['db_username'], |
| 136 | 'password' => $this->settings['db_password'], |
| 137 | 'host' => $this->settings['db_host'], |
| 138 | 'driver' => 'pdo_mysql', |
| 139 | ); |
| 140 | $this->db = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); |
| 141 | $this->db->executeQuery('SET time_zone = "+00:00";'); // Make sure the DB runs on UTC for this connection. |
| 142 | // Update DB schema if needed (if the utils PHP file has been changed since we last checked the DB, we trigger the update functionality). |
| 143 | try { |
| 144 | $last_log = $this->db->fetchColumn('SELECT time_logged FROM auth_log WHERE code = \'db_checked\' ORDER BY id DESC LIMIT 1', array(1), 0); |
| 145 | $utils_mtime = filemtime(__FILE__); |
| 146 | } |
| 147 | catch (Exception $e) { |
| 148 | $last_log = false; |
| 149 | } |
| 150 | if (!$last_log || strtotime($last_log) < $utils_mtime) { |
| 151 | $this->updateDBSchema(); |
| 152 | } |
| 153 | |
| 154 | // Set local variables. |
| 155 | // For debugging, potentially add |robert\.box\.kairo\.at to that regex temporarily. |
| 156 | $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']); |
| 157 | if (array_key_exists('pwd_cost', $this->settings)) { |
| 158 | $this->pwd_cost = $this->settings['pwd_cost']; |
| 159 | } |
| 160 | if (array_key_exists('pwd_nonces', $this->settings)) { |
| 161 | $this->pwd_nonces = $this->settings['pwd_nonces']; |
| 162 | } |
| 163 | if (array_key_exists('client_reg_email_whitelist', $this->settings) && is_array($this->settings['client_reg_email_whitelist'])) { |
| 164 | // If the config lists any emails, set whitelist to them, otherwise there is no whitelist and any user can add OAuth2 clients. |
| 165 | $this->client_reg_email_whitelist = $this->settings['client_reg_email_whitelist']; |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | public $settings = null; |
| 170 | public $db = null; |
| 171 | public $running_on_localhost = false; |
| 172 | public $client_reg_email_whitelist = false; |
| 173 | private $pwd_cost = 10; |
| 174 | private $pwd_nonces = array(); |
| 175 | |
| 176 | function log($code, $info) { |
| 177 | $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);'); |
| 178 | if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) { |
| 179 | // print($result->errorInfo()[2]); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | function checkForSecureConnection() { |
| 184 | $errors = array(); |
| 185 | if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) { |
| 186 | $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.'); |
| 187 | } |
| 188 | return $errors; |
| 189 | } |
| 190 | |
| 191 | function sendSecurityHeaders() { |
| 192 | // Send various headers that we want to have for security resons, mostly as recommended by https://observatory.mozilla.org/ |
| 193 | |
| 194 | // CSP - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy |
| 195 | // Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) from ourselves; also disable framing. |
| 196 | header('Content-Security-Policy: default-src \'none\';img-src \'self\'; script-src \'self\'; style-src \'self\'; frame-ancestors \'none\''); |
| 197 | |
| 198 | // X-Content-Type-Options - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Content-Type-Options |
| 199 | // Prevent browsers from incorrectly detecting non-scripts as scripts |
| 200 | header('X-Content-Type-Options: nosniff'); |
| 201 | |
| 202 | // X-Frame-Options (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Frame-Options |
| 203 | // Block site from being framed |
| 204 | header('X-Frame-Options: DENY'); |
| 205 | |
| 206 | // X-XSS-Protection (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-XSS-Protection |
| 207 | // Block pages from loading when they detect reflected XSS attacks |
| 208 | header('X-XSS-Protection: 1; mode=block'); |
| 209 | } |
| 210 | |
| 211 | function initSession() { |
| 212 | $session = null; |
| 213 | if (strlen(@$_COOKIE['sessionkey'])) { |
| 214 | // Fetch the session - or at least try to. |
| 215 | $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); |
| 216 | $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s'))); |
| 217 | $row = $result->fetch(PDO::FETCH_ASSOC); |
| 218 | if ($row) { |
| 219 | $session = $row; |
| 220 | } |
| 221 | } |
| 222 | if (is_null($session)) { |
| 223 | // Create new session and set cookie. |
| 224 | $sesskey = $this->createSessionKey(); |
| 225 | setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. |
| 226 | $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);'); |
| 227 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes')))); |
| 228 | // After insert, actually fetch the session row from the DB so we have all values. |
| 229 | $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); |
| 230 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s'))); |
| 231 | $row = $result->fetch(PDO::FETCH_ASSOC); |
| 232 | if ($row) { |
| 233 | $session = $row; |
| 234 | } |
| 235 | else { |
| 236 | $this->log('session_create_failure', 'key: '.$sesskey); |
| 237 | } |
| 238 | } |
| 239 | return $session; |
| 240 | } |
| 241 | |
| 242 | function getLoginSession($userid, $prev_session) { |
| 243 | $session = $prev_session; |
| 244 | $sesskey = $this->createSessionKey(); |
| 245 | setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. |
| 246 | // If the previous session has a user set, create a new one - otherwise take existing session entry. |
| 247 | if (intval($session['user'])) { |
| 248 | $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);'); |
| 249 | $result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')))); |
| 250 | // After insert, actually fetch the session row from the DB so we have all values. |
| 251 | $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); |
| 252 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s'))); |
| 253 | $row = $result->fetch(PDO::FETCH_ASSOC); |
| 254 | if ($row) { |
| 255 | $session = $row; |
| 256 | } |
| 257 | else { |
| 258 | $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$userid); |
| 259 | $errors[] = _('The session system is not working.').' ' |
| 260 | .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $this->settings['operator_contact_url'], $this->settings['operator_name']); |
| 261 | } |
| 262 | } |
| 263 | else { |
| 264 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;'); |
| 265 | if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) { |
| 266 | $utils->log('login_failure', 'session: '.$session['id'].', user: '.$userid); |
| 267 | $errors[] = _('Login failed unexpectedly.').' ' |
| 268 | .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $this->settings['operator_contact_url'], $this->settings['operator_name']); |
| 269 | } |
| 270 | else { |
| 271 | // After update, actually fetch the session row from the DB so we have all values. |
| 272 | $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); |
| 273 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s'))); |
| 274 | $row = $result->fetch(PDO::FETCH_ASSOC); |
| 275 | if ($row) { |
| 276 | $session = $row; |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | return $session; |
| 281 | } |
| 282 | |
| 283 | function setRedirect($session, $redirect) { |
| 284 | $success = false; |
| 285 | // Save the request in the session so we can get back to fulfilling it if one of the links is clicked. |
| 286 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;'); |
| 287 | if (!$result->execute(array(':redir' => $redirect, ':sessid' => $session['id']))) { |
| 288 | $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: '.$redirect); |
| 289 | } |
| 290 | else { |
| 291 | $success = true; |
| 292 | } |
| 293 | return $success; |
| 294 | } |
| 295 | |
| 296 | function doRedirectIfSet($session) { |
| 297 | $success = false; |
| 298 | // If the session has a redirect set, make sure it's performed. |
| 299 | if (strlen(@$session['saved_redirect'])) { |
| 300 | // Remove redirect. |
| 301 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;'); |
| 302 | if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) { |
| 303 | $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)'); |
| 304 | } |
| 305 | else { |
| 306 | $success = true; |
| 307 | } |
| 308 | header('Location: '.$this->getDomainBaseURL().$session['saved_redirect']); |
| 309 | } |
| 310 | return $success; |
| 311 | } |
| 312 | |
| 313 | function resetRedirect($session) { |
| 314 | $success = false; |
| 315 | // If the session has a redirect set, remove it. |
| 316 | if (strlen(@$session['saved_redirect'])) { |
| 317 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;'); |
| 318 | if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) { |
| 319 | $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)'); |
| 320 | } |
| 321 | else { |
| 322 | $success = true; |
| 323 | } |
| 324 | } |
| 325 | return $success; |
| 326 | } |
| 327 | |
| 328 | function getDomainBaseURL() { |
| 329 | return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME']; |
| 330 | } |
| 331 | |
| 332 | function checkPasswordConstraints($new_password, $user_email) { |
| 333 | $errors = array(); |
| 334 | if ($new_password != trim($new_password)) { |
| 335 | $errors[] = _('Password must not start or end with a whitespace character like a space.'); |
| 336 | } |
| 337 | if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); } |
| 338 | if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); } |
| 339 | if ((strtolower($new_password) == strtolower($user_email)) || |
| 340 | in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) { |
| 341 | $errors[] = _('The passwort can not be equal to your email or any part of it.'); |
| 342 | } |
| 343 | if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) { |
| 344 | $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15); |
| 345 | } |
| 346 | if (preg_match('/^\d+$/', $new_password)) { |
| 347 | $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15); |
| 348 | } |
| 349 | if (strlen(count_chars($new_password, 3)) < 5) { |
| 350 | $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5); |
| 351 | } |
| 352 | return $errors; |
| 353 | } |
| 354 | |
| 355 | function createSessionKey() { |
| 356 | return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string). |
| 357 | } |
| 358 | |
| 359 | function createVerificationCode() { |
| 360 | return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string). |
| 361 | } |
| 362 | |
| 363 | function createClientSecret() { |
| 364 | return bin2hex(openssl_random_pseudo_bytes(160 / 8)); // Get 160 bits of randomness (40 byte hex string). |
| 365 | } |
| 366 | |
| 367 | function createTimeCode($session, $offset = null, $validity_minutes = 10) { |
| 368 | // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm |
| 369 | $valid_seconds = intval($validity_minutes) * 60; |
| 370 | if ($valid_seconds < 60) { $valid_seconds = 60; } |
| 371 | $code_digits = 8; |
| 372 | $time = time(); |
| 373 | $rest = is_null($offset)?($time % $valid_seconds):intval($offset); // T0, will be sent as part of code to make it valid for the full duration. |
| 374 | $counter = floor(($time - $rest) / $valid_seconds); |
| 375 | $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']); |
| 376 | $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number. |
| 377 | $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit. |
| 378 | $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits)); |
| 379 | return $rest.'.'.$totp_value; |
| 380 | } |
| 381 | |
| 382 | function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) { |
| 383 | if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) { |
| 384 | return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes)); |
| 385 | } |
| 386 | return false; |
| 387 | } |
| 388 | |
| 389 | /* |
| 390 | Some resources for how to store passwords: |
| 391 | - https://blog.mozilla.org/webdev/2012/06/08/lets-talk-about-password-storage/ |
| 392 | - https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines |
| 393 | oauth-server-php: https://bshaffer.github.io/oauth2-server-php-docs/cookbook |
| 394 | */ |
| 395 | function pwdHash($new_password) { |
| 396 | $hash_prefix = ''; |
| 397 | if (count($this->pwd_nonces)) { |
| 398 | $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1]; |
| 399 | $hash_prefix = (count($this->pwd_nonces) - 1).'|'; |
| 400 | } |
| 401 | return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost)); |
| 402 | } |
| 403 | |
| 404 | function pwdVerify($password_to_verify, $userdata) { |
| 405 | $pwdhash = $userdata['pwdhash']; |
| 406 | if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) { |
| 407 | $password_to_verify .= $this->pwd_nonces[$regs[1]]; |
| 408 | $pwdhash = $regs[2]; |
| 409 | } |
| 410 | return password_verify($password_to_verify, $pwdhash); |
| 411 | } |
| 412 | |
| 413 | function pwdNeedsRehash($userdata) { |
| 414 | $nonceid = -1; |
| 415 | $pwdhash = $userdata['pwdhash']; |
| 416 | if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) { |
| 417 | $nonceid = $regs[1]; |
| 418 | $pwdhash = $regs[2]; |
| 419 | } |
| 420 | if ($nonceid == count($this->pwd_nonces) - 1) { |
| 421 | return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost)); |
| 422 | } |
| 423 | else { |
| 424 | return true; |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | function setUpL10n() { |
| 429 | // This is an array of locale tags in browser style mapping to unix system locale codes to use with gettext. |
| 430 | $supported_locales = array( |
| 431 | 'en-US' => 'en_US', |
| 432 | 'de' => 'de_DE', |
| 433 | ); |
| 434 | |
| 435 | $textdomain = 'kairo_auth'; |
| 436 | $textlocale = $this->negotiateLocale(array_keys($supported_locales)); |
| 437 | putenv('LC_ALL='.$supported_locales[$textlocale]); |
| 438 | $selectedlocale = setlocale(LC_ALL, $supported_locales[$textlocale]); |
| 439 | bindtextdomain($textdomain, '../locale'); |
| 440 | bind_textdomain_codeset($textdomain, 'utf-8'); |
| 441 | textdomain($textdomain); |
| 442 | } |
| 443 | |
| 444 | function negotiateLocale($supportedLanguages) { |
| 445 | $nlocale = $supportedLanguages[0]; |
| 446 | $headers = getAllHeaders(); |
| 447 | $accLcomp = explode(',', @$headers['Accept-Language']); |
| 448 | $accLang = array(); |
| 449 | foreach ($accLcomp as $lcomp) { |
| 450 | if (strlen($lcomp)) { |
| 451 | $ldef = explode(';', $lcomp); |
| 452 | $accLang[$ldef[0]] = (float)((strpos(@$ldef[1],'q=')===0)?substr($ldef[1],2):1); |
| 453 | } |
| 454 | } |
| 455 | if (count($accLang)) { |
| 456 | $pLang = ''; $pLang_q = 0; |
| 457 | foreach ($supportedLanguages as $wantedLang) { |
| 458 | if (isset($accLang[$wantedLang]) && ($accLang[$wantedLang] > $pLang_q)) { |
| 459 | $pLang = $wantedLang; |
| 460 | $pLang_q = $accLang[$wantedLang]; |
| 461 | } |
| 462 | } |
| 463 | if (strlen($pLang)) { $nlocale = $pLang; } |
| 464 | } |
| 465 | return $nlocale; |
| 466 | } |
| 467 | |
| 468 | function getGroupedEmails($group_id, $exclude_email = '') { |
| 469 | $emails = array(); |
| 470 | if (intval($group_id)) { |
| 471 | $result = $this->db->prepare('SELECT `email` FROM `auth_users` WHERE `group_id` = :groupid AND `status` = \'ok\' AND `email` != :excludemail ORDER BY `email` ASC;'); |
| 472 | $result->execute(array(':groupid' => $group_id, ':excludemail' => $exclude_email)); |
| 473 | foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) { |
| 474 | $emails[] = $row['email']; |
| 475 | } |
| 476 | } |
| 477 | return $emails; |
| 478 | } |
| 479 | |
| 480 | function getOAuthServer() { |
| 481 | // Simple server based on https://bshaffer.github.io/oauth2-server-php-docs/cookbook |
| 482 | $dbdata = array('dsn' => 'mysql:dbname='.$this->settings['db_name'].';host='.$this->settings['db_host'], |
| 483 | 'username' => $this->settings['db_username'], |
| 484 | 'password' => $this->settings['db_password']); |
| 485 | $oauth2_storage = new OAuth2\Storage\Pdo($dbdata); |
| 486 | |
| 487 | // Set configuration |
| 488 | $oauth2_config = array( |
| 489 | 'require_exact_redirect_uri' => false, |
| 490 | 'always_issue_new_refresh_token' => true, // Needs to be handed below as well as there it's not constructed from within the server object. |
| 491 | 'refresh_token_lifetime' => 90*24*3600, |
| 492 | ); |
| 493 | |
| 494 | // Pass a storage object or array of storage objects to the OAuth2 server class |
| 495 | $server = new OAuth2\Server($oauth2_storage, $oauth2_config); |
| 496 | |
| 497 | // Add the "Client Credentials" grant type (it is the simplest of the grant types) |
| 498 | //$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage)); |
| 499 | |
| 500 | // Add the "Authorization Code" grant type (this is where the oauth magic happens) |
| 501 | $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($oauth2_storage)); |
| 502 | |
| 503 | // Add the "Refresh Token" grant type (required to get longer-living resource access by generating new access tokens) |
| 504 | $server->addGrantType(new OAuth2\GrantType\RefreshToken($oauth2_storage, array('always_issue_new_refresh_token' => true))); |
| 505 | |
| 506 | // Add 'token' response type (mirroring what getDefaultResponseTypes is doing). |
| 507 | $server->addResponseType(new OAuth2\ResponseType\AccessToken($oauth2_storage, $oauth2_storage, $oauth2_config)); |
| 508 | |
| 509 | // Add 'code' response type (mirroring what getDefaultResponseTypes is doing). |
| 510 | $server->addResponseType(new OAuth2\ResponseType\AuthorizationCode($oauth2_storage)); |
| 511 | |
| 512 | return $server; |
| 513 | } |
| 514 | |
| 515 | function initHTMLDocument($titletext, $headlinetext = null) { |
| 516 | global $settings; |
| 517 | if (is_null($headlinetext)) { $headlinetext = $titletext; } |
| 518 | // Start HTML document as a DOM object. |
| 519 | extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body |
| 520 | $document->formatOutput = true; // we want a nice output |
| 521 | |
| 522 | $style = $head->appendElement('link'); |
| 523 | $style->setAttribute('rel', 'stylesheet'); |
| 524 | $style->setAttribute('href', 'authsystem.css'); |
| 525 | $style = $head->appendElement('link'); |
| 526 | $style->setAttribute('rel', 'stylesheet'); |
| 527 | $style->setAttribute('href', 'skin/'.$settings['skin'].'/authskin.css'); |
| 528 | $head->appendJSFile('authsystem.js'); |
| 529 | if ($settings['piwik_enabled']) { |
| 530 | $head->setAttribute('data-piwiksite', $settings['piwik_site_id']); |
| 531 | $head->setAttribute('data-piwikurl', $settings['piwik_url']); |
| 532 | $head->appendJSFile('piwik.js', true, true); |
| 533 | } |
| 534 | $icon = $head->appendElement('link'); |
| 535 | $icon->setAttribute('rel', 'shortcut icon'); |
| 536 | $icon->setAttribute('href', 'skin/'.$settings['skin'].'/icon32.png'); |
| 537 | $icon->setAttribute('type', 'image/png'); |
| 538 | $title->appendText($titletext); |
| 539 | $h1 = $body->appendElement('h1', $headlinetext); |
| 540 | |
| 541 | if ($settings['piwik_enabled']) { |
| 542 | // Piwik noscript element |
| 543 | $noscript = $body->appendElement('noscript'); |
| 544 | $para = $noscript->appendElement('p'); |
| 545 | $img = $para->appendImage($settings['piwik_url'].'piwik.php?idsite='.$settings['piwik_site_id']); |
| 546 | $img->setAttribute('style', 'border:0;'); |
| 547 | } |
| 548 | |
| 549 | // Make the document not be scaled on mobile devices. |
| 550 | $vpmeta = $head->appendElement('meta'); |
| 551 | $vpmeta->setAttribute('name', 'viewport'); |
| 552 | $vpmeta->setAttribute('content', 'width=device-width, height=device-height'); |
| 553 | |
| 554 | $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.')); |
| 555 | $para->setAttribute('id', 'jswarning'); |
| 556 | $para->setAttribute('class', 'warn'); |
| 557 | |
| 558 | return array('document' => $document, |
| 559 | 'html' => $html, |
| 560 | 'head' => $head, |
| 561 | 'title' => $title, |
| 562 | 'body' => $body); |
| 563 | } |
| 564 | |
| 565 | function appendLoginForm($dom_element, $session, $user, $addfields = array()) { |
| 566 | $form = $dom_element->appendForm('./', 'POST', 'loginform'); |
| 567 | $form->setAttribute('id', 'loginform'); |
| 568 | $form->setAttribute('class', 'loginarea hidden'); |
| 569 | $ulist = $form->appendElement('ul'); |
| 570 | $ulist->setAttribute('class', 'flat login'); |
| 571 | $litem = $ulist->appendElement('li'); |
| 572 | $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval(@$user['id'])?$user['email']:'')); |
| 573 | $inptxt->setAttribute('autocomplete', 'email'); |
| 574 | $inptxt->setAttribute('required', ''); |
| 575 | $inptxt->setAttribute('placeholder', _('Email')); |
| 576 | $inptxt->setAttribute('class', 'login'); |
| 577 | $litem = $ulist->appendElement('li'); |
| 578 | $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', ''); |
| 579 | $inptxt->setAttribute('required', ''); |
| 580 | $inptxt->setAttribute('placeholder', _('Password')); |
| 581 | $inptxt->setAttribute('class', 'login'); |
| 582 | $litem = $ulist->appendElement('li'); |
| 583 | $litem->appendLink('./?reset', _('Forgot password?')); |
| 584 | /* |
| 585 | $litem = $ulist->appendElement('li'); |
| 586 | $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false); |
| 587 | $cbox->setAttribute('class', 'logincheck'); |
| 588 | $label = $litem->appendLabel('login_remember', _('Remember me')); |
| 589 | $label->setAttribute('id', 'rememprompt'); |
| 590 | $label->setAttribute('class', 'loginprompt'); |
| 591 | */ |
| 592 | $litem = $ulist->appendElement('li'); |
| 593 | $litem->appendInputHidden('tcode', $this->createTimeCode($session)); |
| 594 | foreach ($addfields as $fname => $fvalue) { |
| 595 | $litem->appendInputHidden($fname, $fvalue); |
| 596 | } |
| 597 | $submit = $litem->appendInputSubmit(_('Log in / Register')); |
| 598 | $submit->setAttribute('class', 'loginbutton'); |
| 599 | } |
| 600 | |
| 601 | function updateDBSchema() { |
| 602 | $newSchema = $this->getDBSchema(); |
| 603 | $synchronizer = new \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer($this->db); |
| 604 | $up_sql = $synchronizer->getUpdateSchema($newSchema); // for logging only |
| 605 | $synchronizer->updateSchema($newSchema); |
| 606 | $this->log('db_checked', implode("\n", $up_sql)); |
| 607 | } |
| 608 | |
| 609 | function getDBSchema() { |
| 610 | $schema = new \Doctrine\DBAL\Schema\Schema(); |
| 611 | |
| 612 | $table = $schema->createTable('auth_sessions'); |
| 613 | $table->addColumn('id', 'bigint', array('unsigned' => true, 'notnull' => true, 'autoincrement' => true)); |
| 614 | $table->addColumn('sesskey', 'string', array('length' => 150, 'notnull' => true, 'default' => '')); |
| 615 | $table->addColumn('user', 'integer', array('unsigned' => true, 'notnull' => false, 'default' => null)); |
| 616 | $table->addColumn('logged_in', 'boolean', array('notnull' => true, 'default' => false)); |
| 617 | $table->addColumn('time_created', 'datetime', array('notnull' => true, 'default' => 'CURRENT_TIMESTAMP')); |
| 618 | $table->addColumn('time_expire', 'datetime', array('notnull' => true, 'default' => 'CURRENT_TIMESTAMP')); |
| 619 | $table->addColumn('saved_redirect', 'string', array('length' => 2000, 'notnull' => true, 'default' => '')); |
| 620 | $table->setPrimaryKey(array('id'), 'id'); |
| 621 | $table->addIndex(array('sesskey'), 'sesskey'); |
| 622 | $table->addIndex(array('time_expire'), 'time_expire'); |
| 623 | |
| 624 | $table = $schema->createTable('auth_users'); |
| 625 | $table->addColumn('id', 'integer', array('unsigned' => true, 'notnull' => true, 'autoincrement' => true)); |
| 626 | $table->addColumn('email', 'string', array('length' => 255, 'notnull' => true, 'default' => '')); |
| 627 | $table->addColumn('pwdhash', 'string', array('length' => 255, 'notnull' => true, 'default' => '')); |
| 628 | $table->addColumn('status', 'string', array('length' => 20, 'notnull' => true, 'default' => 'unverified')); |
| 629 | $table->addColumn('verify_hash', 'string', array('length' => 150, 'notnull' => false, 'default' => null)); |
| 630 | $table->addColumn('group_id', 'integer', array('unsigned' => true, 'notnull' => true, 'default' => 0)); |
| 631 | $table->setPrimaryKey(array('id'), 'id'); |
| 632 | $table->addUniqueIndex(array('email'), 'email'); |
| 633 | |
| 634 | $table = $schema->createTable('auth_log'); |
| 635 | $table->addColumn('id', 'bigint', array('unsigned' => true, 'notnull' => true, 'autoincrement' => true)); |
| 636 | $table->addColumn('code', 'string', array('length' => 100, 'notnull' => true, 'default' => '')); |
| 637 | $table->addColumn('info', 'text', array('notnull' => false, 'default' => null)); |
| 638 | $table->addColumn('ip_addr', 'string', array('length' => 50, 'notnull' => false, 'default' => null)); |
| 639 | $table->addColumn('time_logged', 'datetime', array('notnull' => true, 'default' => 'CURRENT_TIMESTAMP')); |
| 640 | $table->setPrimaryKey(array('id'), 'id'); |
| 641 | $table->addIndex(array('time_logged'), 'time_logged'); |
| 642 | |
| 643 | /* Doctrine DBAL variant of http://bshaffer.github.io/oauth2-server-php-docs/cookbook/#define-your-schema */ |
| 644 | $table = $schema->createTable('oauth_clients'); |
| 645 | $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true)); |
| 646 | $table->addColumn('client_secret', 'string', array('length' => 80, 'notnull' => false)); |
| 647 | $table->addColumn('redirect_uri', 'string', array('length' => 2000, 'notnull' => true)); |
| 648 | $table->addColumn('grant_types', 'string', array('length' => 80, 'notnull' => false)); |
| 649 | $table->addColumn('scope', 'string', array('length' => 100, 'notnull' => false)); |
| 650 | $table->addColumn('user_id', 'string', array('length' => 80, 'notnull' => false)); |
| 651 | $table->setPrimaryKey(array('client_id'), 'clients_client_id_pk'); |
| 652 | |
| 653 | $table = $schema->createTable('oauth_access_tokens'); |
| 654 | $table->addColumn('access_token', 'string', array('length' => 40, 'notnull' => true)); |
| 655 | $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true)); |
| 656 | $table->addColumn('user_id', 'string', array('length' => 255, 'notnull' => false)); |
| 657 | $table->addColumn('expires', 'datetime', array('notnull' => true)); |
| 658 | $table->addColumn('scope', 'string', array('length' => 2000, 'notnull' => false)); |
| 659 | $table->setPrimaryKey(array('access_token'), 'access_token_pk'); |
| 660 | |
| 661 | $table = $schema->createTable('oauth_authorization_codes'); |
| 662 | $table->addColumn('authorization_code', 'string', array('length' => 40, 'notnull' => true)); |
| 663 | $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true)); |
| 664 | $table->addColumn('user_id', 'string', array('length' => 255, 'notnull' => false)); |
| 665 | $table->addColumn('redirect_uri', 'string', array('length' => 2000, 'notnull' => false)); |
| 666 | $table->addColumn('expires', 'datetime', array('notnull' => true)); |
| 667 | $table->addColumn('scope', 'string', array('length' => 2000, 'notnull' => false)); |
| 668 | $table->setPrimaryKey(array('authorization_code'), 'auth_code_pk'); |
| 669 | |
| 670 | $table = $schema->createTable('oauth_refresh_tokens'); |
| 671 | $table->addColumn('refresh_token', 'string', array('length' => 40, 'notnull' => true)); |
| 672 | $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true)); |
| 673 | $table->addColumn('user_id', 'string', array('length' => 255, 'notnull' => false)); |
| 674 | $table->addColumn('expires', 'datetime', array('notnull' => true)); |
| 675 | $table->addColumn('scope', 'string', array('length' => 2000, 'notnull' => false)); |
| 676 | $table->setPrimaryKey(array('refresh_token'), 'refresh_token_pk'); |
| 677 | |
| 678 | $table = $schema->createTable('oauth_users'); |
| 679 | $table->addColumn('username', 'string', array('length' => 255, 'notnull' => true)); |
| 680 | $table->addColumn('password', 'string', array('length' => 2000, 'notnull' => false)); |
| 681 | $table->addColumn('first_name', 'string', array('length' => 255, 'notnull' => false)); |
| 682 | $table->addColumn('last_name', 'string', array('length' => 255, 'notnull' => false)); |
| 683 | $table->setPrimaryKey(array('username'), 'username_pk'); |
| 684 | |
| 685 | $table = $schema->createTable('oauth_scopes'); |
| 686 | $table->addColumn('scope', 'text', array('notnull' => false)); |
| 687 | $table->addColumn('is_default', 'boolean', array('notnull' => false)); |
| 688 | |
| 689 | $table = $schema->createTable('oauth_jwt'); |
| 690 | $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true)); |
| 691 | $table->addColumn('subject', 'string', array('length' => 80, 'notnull' => false)); |
| 692 | $table->addColumn('public_key', 'string', array('length' => 2000, 'notnull' => false)); |
| 693 | $table->setPrimaryKey(array('client_id'), 'client_id_pk'); |
| 694 | |
| 695 | return $schema; |
| 696 | } |
| 697 | } |
| 698 | ?> |