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