KaiRo bug 393 - Create a grouping mechanism for user names so people with multiple...
[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 //
ea0452ad
RK
21 // public $client_reg_email_whitelist
22 // An array of emails that are whitelisted for registering clients.
23 //
ac442755
RK
24 // private $pwd_cost
25 // The cost parameter for use with PHP password_hash function.
26 //
27 // private $pwd_nonces
28 // The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used.
087085d6 29 // Generate a nonce with this command: |openssl rand -base64 48|
ac442755 30 //
558e9862
RK
31 // function log($code, $additional_info)
32 // Log an entry for admin purposes, with a code and some additional info.
33 //
77f0f9ff
RK
34 // function checkForSecureConnection()
35 // Check is the connection is secure and return an array of error messages (empty if it's secure).
36 //
4c6d8064
RK
37 // function initSession()
38 // Initialize a session. Returns an associative array of all the DB fields of the session.
39 //
60e46184
RK
40 // function getLoginSession($user)
41 // 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).
42 //
43 // function setRedirect($session, $redirect)
44 // Set a redirect on the session for performing later. Returns true if a redirect was saved, otherwise false.
45 //
46 // function doRedirectIfSet($session)
47 // If the session has a redirect set, perform it. Returns true if a redirect was performed, otherwise false.
48 //
49 // function resetRedirect($session)
50 // If the session has a redirect set, remove it. Returns true if a redirect was removed, otherwise false.
51 //
409b55f4
RK
52 // function getDomainBaseURL()
53 // Get the base URL of the current domain, e.g. 'https://example.com'.
54 //
ac442755 55 // function checkPasswordConstraints($new_password, $user_email)
d46a42f1
RK
56 // Check password constraints and return an array of error messages (empty if all constraints are met).
57 //
ac442755 58 // function createSessionKey()
d46a42f1
RK
59 // Return a random session key.
60 //
ac442755 61 // function createVerificationCode()
d46a42f1
RK
62 // Return a random acount/email verification code.
63 //
ea0452ad
RK
64 // function createClientSecret()
65 // Return a random client secret.
66 //
ac442755 67 // function createTimeCode($session, [$offset], [$validity_minutes])
d46a42f1
RK
68 // Return a time-based code based on the key and ID of the given session.
69 // An offset can be given to create a specific code for verification, otherwise and offset will be generated.
70 // Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used.
71 //
ac442755 72 // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes])
d46a42f1
RK
73 // Verify a given time-based code and return true if it's valid or false if it's not.
74 // See createTimeCode() documentation for the session and validity paramerters.
be1082a6 75 //
ac442755 76 // function pwdHash($new_password)
be1082a6
RK
77 // Return a hash for the given password.
78 //
ac442755 79 // function pwdVerify($password_to_verify, $user)
be1082a6
RK
80 // Return true if the password verifies against the pwdhash field of the user, false if not.
81 //
ac442755 82 // function pwdNeedsRehash($user)
be1082a6 83 // Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
409b55f4 84 //
60e46184
RK
85 // function getGroupedEmails($group_id, [$exclude_email])
86 // Return all emails grouped in the specified group ID, optionally exclude a specific email (e.g. because you only want non-current entries)
87 //
88 // function appendLoginForm($dom_element, $session, $user, [$addfields])
89 // Append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array.
90 // The optional $addfields parameter is an array of name=>value pairs of hidden fields to add to the form.
be1082a6 91
558e9862 92 function __construct($settings, $db) {
ac442755 93 // *** constructor ***
558e9862 94 $this->db = $db;
4c6d8064 95 $this->db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly.
a5d730af 96 // For debugging, potentially add |robert\.box\.kairo\.at to that regex temporarily.
77f0f9ff 97 $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
ac442755
RK
98 if (array_key_exists('pwd_cost', $settings)) {
99 $this->pwd_cost = $settings['pwd_cost'];
100 }
558e9862
RK
101 if (array_key_exists('pwd_nonces', $settings)) {
102 $this->pwd_nonces = $settings['pwd_nonces'];
103 }
ac442755
RK
104 }
105
558e9862 106 public $db = null;
77f0f9ff 107 public $running_on_localhost = false;
ea0452ad 108 public $client_reg_email_whitelist = array('kairo@kairo.at', 'com@kairo.at');
ac442755
RK
109 private $pwd_cost = 10;
110 private $pwd_nonces = array();
d46a42f1 111
558e9862
RK
112 function log($code, $info) {
113 $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
114 if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
115 // print($result->errorInfo()[2]);
116 }
117 }
118
77f0f9ff
RK
119 function checkForSecureConnection() {
120 $errors = array();
121 if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) {
122 $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
123 }
124 return $errors;
125 }
126
b0e48c35
RK
127 function sendSecurityHeaders() {
128 // Send various headers that we want to have for security resons, mostly as recommended by https://observatory.mozilla.org/
129
130 // CSP - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy
131 // Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) from ourselves; also disable framing.
132 header('Content-Security-Policy: default-src \'none\';img-src \'self\'; script-src \'self\'; style-src \'self\'; frame-ancestors \'none\'');
133
134 // X-Content-Type-Options - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Content-Type-Options
135 // Prevent browsers from incorrectly detecting non-scripts as scripts
136 header('X-Content-Type-Options: nosniff');
137
138 // X-Frame-Options (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Frame-Options
139 // Block site from being framed
140 header('X-Frame-Options: DENY');
141
142 // X-XSS-Protection (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-XSS-Protection
143 // Block pages from loading when they detect reflected XSS attacks
144 header('X-XSS-Protection: 1; mode=block');
145 }
146
4c6d8064
RK
147 function initSession() {
148 $session = null;
149 if (strlen(@$_COOKIE['sessionkey'])) {
150 // Fetch the session - or at least try to.
151 $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
152 $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
153 $row = $result->fetch(PDO::FETCH_ASSOC);
154 if ($row) {
155 $session = $row;
156 }
157 }
158 if (is_null($session)) {
159 // Create new session and set cookie.
160 $sesskey = $this->createSessionKey();
161 setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
162 $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
163 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
164 // After insert, actually fetch the session row from the DB so we have all values.
165 $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
166 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
167 $row = $result->fetch(PDO::FETCH_ASSOC);
168 if ($row) {
169 $session = $row;
170 }
171 else {
172 $this->log('session_create_failure', 'key: '.$sesskey);
173 }
174 }
175 return $session;
176 }
177
60e46184
RK
178 function getLoginSession($userid, $prev_session) {
179 $session = $prev_session;
180 $sesskey = $this->createSessionKey();
181 setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
182 // If the previous session has a user set, create a new one - otherwise take existing session entry.
183 if (intval($session['user'])) {
184 $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
185 $result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
186 // After insert, actually fetch the session row from the DB so we have all values.
187 $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
188 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
189 $row = $result->fetch(PDO::FETCH_ASSOC);
190 if ($row) {
191 $session = $row;
192 }
193 else {
194 $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$userid);
195 $errors[] = _('The session system is not working. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
196 }
197 }
198 else {
199 $result = $this->db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
200 if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
201 $utils->log('login_failure', 'session: '.$session['id'].', user: '.$userid);
202 $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
203 }
204 else {
205 // After update, actually fetch the session row from the DB so we have all values.
206 $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
207 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
208 $row = $result->fetch(PDO::FETCH_ASSOC);
209 if ($row) {
210 $session = $row;
211 }
212 }
213 }
214 return $session;
215 }
216
217 function setRedirect($session, $redirect) {
218 $success = false;
219 // Save the request in the session so we can get back to fulfilling it if one of the links is clicked.
220 $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
221 if (!$result->execute(array(':redir' => $redirect, ':sessid' => $session['id']))) {
222 $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: '.$redirect);
223 }
224 else {
225 $success = true;
226 }
227 return $success;
228 }
229
230 function doRedirectIfSet($session) {
231 $success = false;
232 // If the session has a redirect set, make sure it's performed.
233 if (strlen(@$session['saved_redirect'])) {
234 // Remove redirect.
235 $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
236 if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
237 $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
238 }
239 else {
240 $success = true;
241 }
242 header('Location: '.$this->getDomainBaseURL().$session['saved_redirect']);
243 }
244 return $success;
245 }
246
247 function resetRedirect($session) {
248 $success = false;
249 // If the session has a redirect set, remove it.
250 if (strlen(@$session['saved_redirect'])) {
251 $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
252 if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
253 $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
254 }
255 else {
256 $success = true;
257 }
258 }
259 return $success;
260 }
261
409b55f4
RK
262 function getDomainBaseURL() {
263 return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'];
264 }
265
ac442755 266 function checkPasswordConstraints($new_password, $user_email) {
d46a42f1
RK
267 $errors = array();
268 if ($new_password != trim($new_password)) {
269 $errors[] = _('Password must not start or end with a whitespace character like a space.');
270 }
271 if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
272 if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
273 if ((strtolower($new_password) == strtolower($user_email)) ||
274 in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
275 $errors[] = _('The passwort can not be equal to your email or any part of it.');
276 }
277 if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
278 $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
279 }
280 if (preg_match('/^\d+$/', $new_password)) {
281 $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
282 }
283 if (strlen(count_chars($new_password, 3)) < 5) {
284 $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
285 }
286 return $errors;
287 }
288
ac442755 289 function createSessionKey() {
d46a42f1
RK
290 return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
291 }
292
ac442755 293 function createVerificationCode() {
d46a42f1
RK
294 return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
295 }
296
ea0452ad
RK
297 function createClientSecret() {
298 return bin2hex(openssl_random_pseudo_bytes(160 / 8)); // Get 160 bits of randomness (40 byte hex string).
299 }
300
ac442755 301 function createTimeCode($session, $offset = null, $validity_minutes = 10) {
d46a42f1
RK
302 // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
303 $valid_seconds = intval($validity_minutes) * 60;
304 if ($valid_seconds < 60) { $valid_seconds = 60; }
305 $code_digits = 8;
306 $time = time();
307 $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.
308 $counter = floor(($time - $rest) / $valid_seconds);
309 $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']);
310 $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number.
311 $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit.
312 $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
313 return $rest.'.'.$totp_value;
314 }
315
ac442755 316 function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) {
d46a42f1 317 if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) {
ac442755 318 return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes));
d46a42f1
RK
319 }
320 return false;
321 }
be1082a6 322
ac442755
RK
323 function pwdHash($new_password) {
324 $hash_prefix = '';
325 if (count($this->pwd_nonces)) {
326 $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1];
327 $hash_prefix = (count($this->pwd_nonces) - 1).'|';
328 }
329 return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
be1082a6
RK
330 }
331
ac442755 332 function pwdVerify($password_to_verify, $userdata) {
087085d6
RK
333 $pwdhash = $userdata['pwdhash'];
334 if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
ac442755 335 $password_to_verify .= $this->pwd_nonces[$regs[1]];
087085d6 336 $pwdhash = $regs[2];
ac442755 337 }
087085d6 338 return password_verify($password_to_verify, $pwdhash);
be1082a6
RK
339 }
340
ac442755
RK
341 function pwdNeedsRehash($userdata) {
342 $nonceid = -1;
343 $pwdhash = $userdata['pwdhash'];
344 if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
345 $nonceid = $regs[1];
346 $pwdhash = $regs[2];
347 }
348 if ($nonceid == count($this->pwd_nonces) - 1) {
349 return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
350 }
351 else {
352 return true;
353 }
be1082a6 354 }
409b55f4 355
60e46184
RK
356 function getGroupedEmails($group_id, $exclude_email = '') {
357 $emails = array();
358 if (intval($group_id)) {
359 $result = $this->db->prepare('SELECT `email` FROM `auth_users` WHERE `group_id` = :groupid AND `status` = \'ok\' AND `email` != :excludemail ORDER BY `email` ASC;');
360 $result->execute(array(':groupid' => $group_id, ':excludemail' => $exclude_email));
361 foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
362 $emails[] = $row['email'];
363 }
364 }
365 return $emails;
366 }
367
368 function appendLoginForm($dom_element, $session, $user, $addfields = array()) {
409b55f4
RK
369 $form = $dom_element->appendForm('./', 'POST', 'loginform');
370 $form->setAttribute('id', 'loginform');
371 $form->setAttribute('class', 'loginarea hidden');
372 $ulist = $form->appendElement('ul');
373 $ulist->setAttribute('class', 'flat login');
374 $litem = $ulist->appendElement('li');
375 $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval(@$user['id'])?$user['email']:''));
376 $inptxt->setAttribute('autocomplete', 'email');
377 $inptxt->setAttribute('required', '');
378 $inptxt->setAttribute('placeholder', _('Email'));
379 $inptxt->setAttribute('class', 'login');
380 $litem = $ulist->appendElement('li');
381 $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
382 $inptxt->setAttribute('required', '');
383 $inptxt->setAttribute('placeholder', _('Password'));
384 $inptxt->setAttribute('class', 'login');
385 $litem = $ulist->appendElement('li');
386 $litem->appendLink('./?reset', _('Forgot password?'));
387 $litem = $ulist->appendElement('li');
388 $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
389 $cbox->setAttribute('class', 'logincheck');
390 $label = $litem->appendLabel('login_remember', _('Remember me'));
391 $label->setAttribute('id', 'rememprompt');
392 $label->setAttribute('class', 'loginprompt');
393 $litem = $ulist->appendElement('li');
394 $litem->appendInputHidden('tcode', $this->createTimeCode($session));
60e46184
RK
395 foreach ($addfields as $fname => $fvalue) {
396 $litem->appendInputHidden($fname, $fvalue);
397 }
409b55f4
RK
398 $submit = $litem->appendInputSubmit(_('Log in / Register'));
399 $submit->setAttribute('class', 'loginbutton');
400 }
d46a42f1
RK
401}
402?>