check session and login in authorize request
[authserver.git] / authutils.php-class
... / ...
CommitLineData
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
6class AuthUtils {
7 // KaiRo.at authentication utilities PHP class
8 // This class contains helper functions for the authentication system.
9 //
10 // function __construct($settings, $db)
11 // CONSTRUCTOR
12 // Settings are an associative array with a numeric pwd_cost field and an array pwd_nonces field.
13 // The DB is a PDO object.
14 //
15 // public $db
16 // A PDO database object for interaction.
17 //
18 // public $running_on_localhost
19 // A boolean telling if the system is running on localhost (where https is not required).
20 //
21 // private $pwd_cost
22 // The cost parameter for use with PHP password_hash function.
23 //
24 // private $pwd_nonces
25 // The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used.
26 // Generate a nonce with this command: |openssl rand -base64 48|
27 //
28 // function log($code, $additional_info)
29 // Log an entry for admin purposes, with a code and some additional info.
30 //
31 // function checkForSecureConnection()
32 // Check is the connection is secure and return an array of error messages (empty if it's secure).
33 //
34 // function initSession()
35 // Initialize a session. Returns an associative array of all the DB fields of the session.
36 //
37 // function checkPasswordConstraints($new_password, $user_email)
38 // Check password constraints and return an array of error messages (empty if all constraints are met).
39 //
40 // function createSessionKey()
41 // Return a random session key.
42 //
43 // function createVerificationCode()
44 // Return a random acount/email verification code.
45 //
46 // function createTimeCode($session, [$offset], [$validity_minutes])
47 // Return a time-based code based on the key and ID of the given session.
48 // An offset can be given to create a specific code for verification, otherwise and offset will be generated.
49 // Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used.
50 //
51 // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes])
52 // Verify a given time-based code and return true if it's valid or false if it's not.
53 // See createTimeCode() documentation for the session and validity paramerters.
54 //
55 // function pwdHash($new_password)
56 // Return a hash for the given password.
57 //
58 // function pwdVerify($password_to_verify, $user)
59 // Return true if the password verifies against the pwdhash field of the user, false if not.
60 //
61 // function pwdNeedsRehash($user)
62 // Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
63
64 function __construct($settings, $db) {
65 // *** constructor ***
66 $this->db = $db;
67 $this->db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly.
68 $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
69 if (array_key_exists('pwd_cost', $settings)) {
70 $this->pwd_cost = $settings['pwd_cost'];
71 }
72 if (array_key_exists('pwd_nonces', $settings)) {
73 $this->pwd_nonces = $settings['pwd_nonces'];
74 }
75 }
76
77 public $db = null;
78 public $running_on_localhost = false;
79 private $pwd_cost = 10;
80 private $pwd_nonces = array();
81
82 function log($code, $info) {
83 $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
84 if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
85 // print($result->errorInfo()[2]);
86 }
87 }
88
89 function checkForSecureConnection() {
90 $errors = array();
91 if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) {
92 $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
93 }
94 return $errors;
95 }
96
97 function initSession() {
98 $session = null;
99 if (strlen(@$_COOKIE['sessionkey'])) {
100 // Fetch the session - or at least try to.
101 $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
102 $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
103 $row = $result->fetch(PDO::FETCH_ASSOC);
104 if ($row) {
105 $session = $row;
106 }
107 }
108 if (is_null($session)) {
109 // Create new session and set cookie.
110 $sesskey = $this->createSessionKey();
111 setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
112 $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
113 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
114 // After insert, actually fetch the session row from the DB so we have all values.
115 $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
116 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
117 $row = $result->fetch(PDO::FETCH_ASSOC);
118 if ($row) {
119 $session = $row;
120 }
121 else {
122 $this->log('session_create_failure', 'key: '.$sesskey);
123 }
124 }
125 return $session;
126 }
127
128 function checkPasswordConstraints($new_password, $user_email) {
129 $errors = array();
130 if ($new_password != trim($new_password)) {
131 $errors[] = _('Password must not start or end with a whitespace character like a space.');
132 }
133 if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
134 if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
135 if ((strtolower($new_password) == strtolower($user_email)) ||
136 in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
137 $errors[] = _('The passwort can not be equal to your email or any part of it.');
138 }
139 if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
140 $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
141 }
142 if (preg_match('/^\d+$/', $new_password)) {
143 $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
144 }
145 if (strlen(count_chars($new_password, 3)) < 5) {
146 $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
147 }
148 return $errors;
149 }
150
151 function createSessionKey() {
152 return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
153 }
154
155 function createVerificationCode() {
156 return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
157 }
158
159 function createTimeCode($session, $offset = null, $validity_minutes = 10) {
160 // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
161 $valid_seconds = intval($validity_minutes) * 60;
162 if ($valid_seconds < 60) { $valid_seconds = 60; }
163 $code_digits = 8;
164 $time = time();
165 $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.
166 $counter = floor(($time - $rest) / $valid_seconds);
167 $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']);
168 $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number.
169 $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit.
170 $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
171 return $rest.'.'.$totp_value;
172 }
173
174 function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) {
175 if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) {
176 return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes));
177 }
178 return false;
179 }
180
181 function pwdHash($new_password) {
182 $hash_prefix = '';
183 if (count($this->pwd_nonces)) {
184 $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1];
185 $hash_prefix = (count($this->pwd_nonces) - 1).'|';
186 }
187 return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
188 }
189
190 function pwdVerify($password_to_verify, $userdata) {
191 $pwdhash = $userdata['pwdhash'];
192 if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
193 $password_to_verify .= $this->pwd_nonces[$regs[1]];
194 $pwdhash = $regs[2];
195 }
196 return password_verify($password_to_verify, $pwdhash);
197 }
198
199 function pwdNeedsRehash($userdata) {
200 $nonceid = -1;
201 $pwdhash = $userdata['pwdhash'];
202 if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
203 $nonceid = $regs[1];
204 $pwdhash = $regs[2];
205 }
206 if ($nonceid == count($this->pwd_nonces) - 1) {
207 return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
208 }
209 else {
210 return true;
211 }
212 }
213}
214?>