secure token requests
[authserver.git] / authutils.php-class
CommitLineData
d46a42f1
RK
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 //
558e9862 10 // function __construct($settings, $db)
ac442755 11 // CONSTRUCTOR
558e9862
RK
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.
be1082a6 17 //
77f0f9ff
RK
18 // public $running_on_localhost
19 // A boolean telling if the system is running on localhost (where https is not required).
20 //
ac442755
RK
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.
087085d6 26 // Generate a nonce with this command: |openssl rand -base64 48|
ac442755 27 //
558e9862
RK
28 // function log($code, $additional_info)
29 // Log an entry for admin purposes, with a code and some additional info.
30 //
77f0f9ff
RK
31 // function checkForSecureConnection()
32 // Check is the connection is secure and return an array of error messages (empty if it's secure).
33 //
4c6d8064
RK
34 // function initSession()
35 // Initialize a session. Returns an associative array of all the DB fields of the session.
36 //
409b55f4
RK
37 // function getDomainBaseURL()
38 // Get the base URL of the current domain, e.g. 'https://example.com'.
39 //
ac442755 40 // function checkPasswordConstraints($new_password, $user_email)
d46a42f1
RK
41 // Check password constraints and return an array of error messages (empty if all constraints are met).
42 //
ac442755 43 // function createSessionKey()
d46a42f1
RK
44 // Return a random session key.
45 //
ac442755 46 // function createVerificationCode()
d46a42f1
RK
47 // Return a random acount/email verification code.
48 //
ac442755 49 // function createTimeCode($session, [$offset], [$validity_minutes])
d46a42f1
RK
50 // Return a time-based code based on the key and ID of the given session.
51 // An offset can be given to create a specific code for verification, otherwise and offset will be generated.
52 // Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used.
53 //
ac442755 54 // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes])
d46a42f1
RK
55 // Verify a given time-based code and return true if it's valid or false if it's not.
56 // See createTimeCode() documentation for the session and validity paramerters.
be1082a6 57 //
ac442755 58 // function pwdHash($new_password)
be1082a6
RK
59 // Return a hash for the given password.
60 //
ac442755 61 // function pwdVerify($password_to_verify, $user)
be1082a6
RK
62 // Return true if the password verifies against the pwdhash field of the user, false if not.
63 //
ac442755 64 // function pwdNeedsRehash($user)
be1082a6 65 // Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
409b55f4
RK
66 //
67 // function appendLoginForm($dom_element, $session, $user)
68 // append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array.
be1082a6 69
558e9862 70 function __construct($settings, $db) {
ac442755 71 // *** constructor ***
558e9862 72 $this->db = $db;
4c6d8064 73 $this->db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly.
77f0f9ff 74 $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
ac442755
RK
75 if (array_key_exists('pwd_cost', $settings)) {
76 $this->pwd_cost = $settings['pwd_cost'];
77 }
558e9862
RK
78 if (array_key_exists('pwd_nonces', $settings)) {
79 $this->pwd_nonces = $settings['pwd_nonces'];
80 }
ac442755
RK
81 }
82
558e9862 83 public $db = null;
77f0f9ff 84 public $running_on_localhost = false;
ac442755
RK
85 private $pwd_cost = 10;
86 private $pwd_nonces = array();
d46a42f1 87
558e9862
RK
88 function log($code, $info) {
89 $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
90 if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
91 // print($result->errorInfo()[2]);
92 }
93 }
94
77f0f9ff
RK
95 function checkForSecureConnection() {
96 $errors = array();
97 if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) {
98 $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
99 }
100 return $errors;
101 }
102
4c6d8064
RK
103 function initSession() {
104 $session = null;
105 if (strlen(@$_COOKIE['sessionkey'])) {
106 // Fetch the session - or at least try to.
107 $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
108 $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
109 $row = $result->fetch(PDO::FETCH_ASSOC);
110 if ($row) {
111 $session = $row;
112 }
113 }
114 if (is_null($session)) {
115 // Create new session and set cookie.
116 $sesskey = $this->createSessionKey();
117 setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
118 $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
119 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
120 // After insert, actually fetch the session row from the DB so we have all values.
121 $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
122 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
123 $row = $result->fetch(PDO::FETCH_ASSOC);
124 if ($row) {
125 $session = $row;
126 }
127 else {
128 $this->log('session_create_failure', 'key: '.$sesskey);
129 }
130 }
131 return $session;
132 }
133
409b55f4
RK
134 function getDomainBaseURL() {
135 return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'];
136 }
137
ac442755 138 function checkPasswordConstraints($new_password, $user_email) {
d46a42f1
RK
139 $errors = array();
140 if ($new_password != trim($new_password)) {
141 $errors[] = _('Password must not start or end with a whitespace character like a space.');
142 }
143 if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
144 if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
145 if ((strtolower($new_password) == strtolower($user_email)) ||
146 in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
147 $errors[] = _('The passwort can not be equal to your email or any part of it.');
148 }
149 if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
150 $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
151 }
152 if (preg_match('/^\d+$/', $new_password)) {
153 $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
154 }
155 if (strlen(count_chars($new_password, 3)) < 5) {
156 $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
157 }
158 return $errors;
159 }
160
ac442755 161 function createSessionKey() {
d46a42f1
RK
162 return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
163 }
164
ac442755 165 function createVerificationCode() {
d46a42f1
RK
166 return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
167 }
168
ac442755 169 function createTimeCode($session, $offset = null, $validity_minutes = 10) {
d46a42f1
RK
170 // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
171 $valid_seconds = intval($validity_minutes) * 60;
172 if ($valid_seconds < 60) { $valid_seconds = 60; }
173 $code_digits = 8;
174 $time = time();
175 $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.
176 $counter = floor(($time - $rest) / $valid_seconds);
177 $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']);
178 $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number.
179 $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit.
180 $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
181 return $rest.'.'.$totp_value;
182 }
183
ac442755 184 function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) {
d46a42f1 185 if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) {
ac442755 186 return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes));
d46a42f1
RK
187 }
188 return false;
189 }
be1082a6 190
ac442755
RK
191 function pwdHash($new_password) {
192 $hash_prefix = '';
193 if (count($this->pwd_nonces)) {
194 $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1];
195 $hash_prefix = (count($this->pwd_nonces) - 1).'|';
196 }
197 return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
be1082a6
RK
198 }
199
ac442755 200 function pwdVerify($password_to_verify, $userdata) {
087085d6
RK
201 $pwdhash = $userdata['pwdhash'];
202 if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
ac442755 203 $password_to_verify .= $this->pwd_nonces[$regs[1]];
087085d6 204 $pwdhash = $regs[2];
ac442755 205 }
087085d6 206 return password_verify($password_to_verify, $pwdhash);
be1082a6
RK
207 }
208
ac442755
RK
209 function pwdNeedsRehash($userdata) {
210 $nonceid = -1;
211 $pwdhash = $userdata['pwdhash'];
212 if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
213 $nonceid = $regs[1];
214 $pwdhash = $regs[2];
215 }
216 if ($nonceid == count($this->pwd_nonces) - 1) {
217 return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
218 }
219 else {
220 return true;
221 }
be1082a6 222 }
409b55f4
RK
223
224 function appendLoginForm($dom_element, $session, $user) {
225 $form = $dom_element->appendForm('./', 'POST', 'loginform');
226 $form->setAttribute('id', 'loginform');
227 $form->setAttribute('class', 'loginarea hidden');
228 $ulist = $form->appendElement('ul');
229 $ulist->setAttribute('class', 'flat login');
230 $litem = $ulist->appendElement('li');
231 $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval(@$user['id'])?$user['email']:''));
232 $inptxt->setAttribute('autocomplete', 'email');
233 $inptxt->setAttribute('required', '');
234 $inptxt->setAttribute('placeholder', _('Email'));
235 $inptxt->setAttribute('class', 'login');
236 $litem = $ulist->appendElement('li');
237 $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
238 $inptxt->setAttribute('required', '');
239 $inptxt->setAttribute('placeholder', _('Password'));
240 $inptxt->setAttribute('class', 'login');
241 $litem = $ulist->appendElement('li');
242 $litem->appendLink('./?reset', _('Forgot password?'));
243 $litem = $ulist->appendElement('li');
244 $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
245 $cbox->setAttribute('class', 'logincheck');
246 $label = $litem->appendLabel('login_remember', _('Remember me'));
247 $label->setAttribute('id', 'rememprompt');
248 $label->setAttribute('class', 'loginprompt');
249 $litem = $ulist->appendElement('li');
250 $litem->appendInputHidden('tcode', $this->createTimeCode($session));
251 $submit = $litem->appendInputSubmit(_('Log in / Register'));
252 $submit->setAttribute('class', 'loginbutton');
253 }
d46a42f1
RK
254}
255?>