db5dd891a27754f1bf906ed8f6464f031c575d41
[authserver.git] / app / authutils.php-class
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($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   // public $client_reg_email_whitelist
22   //   An array of emails that are whitelisted for registering clients.
23   //
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.
29   //     Generate a nonce with this command: |openssl rand -base64 48|
30   //
31   // function log($code, $additional_info)
32   //   Log an entry for admin purposes, with a code and some additional info.
33   //
34   // function checkForSecureConnection()
35   //   Check is the connection is secure and return an array of error messages (empty if it's secure).
36   //
37   // function initSession()
38   //   Initialize a session. Returns an associative array of all the DB fields of the session.
39   //
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   //
52   // function getDomainBaseURL()
53   //   Get the base URL of the current domain, e.g. 'https://example.com'.
54   //
55   // function checkPasswordConstraints($new_password, $user_email)
56   //   Check password constraints and return an array of error messages (empty if all constraints are met).
57   //
58   // function createSessionKey()
59   //   Return a random session key.
60   //
61   // function createVerificationCode()
62   //   Return a random acount/email verification code.
63   //
64   // function createClientSecret()
65   //   Return a random client secret.
66   //
67   // function createTimeCode($session, [$offset], [$validity_minutes])
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   //
72   // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes])
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.
75   //
76   // function pwdHash($new_password)
77   //   Return a hash for the given password.
78   //
79   // function pwdVerify($password_to_verify, $user)
80   //   Return true if the password verifies against the pwdhash field of the user, false if not.
81   //
82   // function pwdNeedsRehash($user)
83   //   Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
84   //
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   //
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 initHTMLDocument($titletext, [$headlinetext]) {
92   //   initialize the HTML document for the auth system, with some elements we always use, esp. all the scripts and stylesheet.
93   //     Sets the title of the document to the given title, the main headline will be the same as the title if not set explicitly.
94   //     Returns an associative array with the following elements: 'document', 'html', 'head', 'title', 'body'.
95   //
96   // function appendLoginForm($dom_element, $session, $user, [$addfields])
97   //   Append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array.
98   //     The optional $addfields parameter is an array of name=>value pairs of hidden fields to add to the form.
99
100   function __construct($settings, $db) {
101     // *** constructor ***
102     $this->db = $db;
103     $this->db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly.
104     // For debugging, potentially add |robert\.box\.kairo\.at to that regex temporarily.
105     $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
106     if (array_key_exists('pwd_cost', $settings)) {
107       $this->pwd_cost = $settings['pwd_cost'];
108     }
109     if (array_key_exists('pwd_nonces', $settings)) {
110       $this->pwd_nonces = $settings['pwd_nonces'];
111     }
112   }
113
114   public $db = null;
115   public $running_on_localhost = false;
116   public $client_reg_email_whitelist = array('kairo@kairo.at', 'com@kairo.at');
117   private $pwd_cost = 10;
118   private $pwd_nonces = array();
119
120   function log($code, $info) {
121     $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
122     if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
123       // print($result->errorInfo()[2]);
124     }
125   }
126
127   function checkForSecureConnection() {
128     $errors = array();
129     if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) {
130       $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
131     }
132     return $errors;
133   }
134
135   function sendSecurityHeaders() {
136     // Send various headers that we want to have for security resons, mostly as recommended by https://observatory.mozilla.org/
137
138     // CSP - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy
139     // Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) from ourselves; also disable framing.
140     header('Content-Security-Policy: default-src \'none\';img-src \'self\'; script-src \'self\'; style-src \'self\'; frame-ancestors \'none\'');
141
142     // X-Content-Type-Options - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Content-Type-Options
143     // Prevent browsers from incorrectly detecting non-scripts as scripts
144     header('X-Content-Type-Options: nosniff');
145
146     // X-Frame-Options (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Frame-Options
147     // Block site from being framed
148     header('X-Frame-Options: DENY');
149
150     // X-XSS-Protection (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-XSS-Protection
151     // Block pages from loading when they detect reflected XSS attacks
152     header('X-XSS-Protection: 1; mode=block');
153   }
154
155   function initSession() {
156     $session = null;
157     if (strlen(@$_COOKIE['sessionkey'])) {
158       // Fetch the session - or at least try to.
159       $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
160       $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
161       $row = $result->fetch(PDO::FETCH_ASSOC);
162       if ($row) {
163         $session = $row;
164       }
165     }
166     if (is_null($session)) {
167       // Create new session and set cookie.
168       $sesskey = $this->createSessionKey();
169       setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
170       $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
171       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
172       // After insert, actually fetch the session row from the DB so we have all values.
173       $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
174       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
175       $row = $result->fetch(PDO::FETCH_ASSOC);
176       if ($row) {
177         $session = $row;
178       }
179       else {
180         $this->log('session_create_failure', 'key: '.$sesskey);
181       }
182     }
183     return $session;
184   }
185
186   function getLoginSession($userid, $prev_session) {
187     $session = $prev_session;
188     $sesskey = $this->createSessionKey();
189     setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
190     // If the previous session has a user set, create a new one - otherwise take existing session entry.
191     if (intval($session['user'])) {
192       $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
193       $result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
194       // After insert, actually fetch the session row from the DB so we have all values.
195       $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
196       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
197       $row = $result->fetch(PDO::FETCH_ASSOC);
198       if ($row) {
199         $session = $row;
200       }
201       else {
202         $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$userid);
203         $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.');
204       }
205     }
206     else {
207       $result = $this->db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
208       if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
209         $utils->log('login_failure', 'session: '.$session['id'].', user: '.$userid);
210         $errors[] = _('Login failed unexpectedly.').' '._('Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
211       }
212       else {
213         // After update, actually fetch the session row from the DB so we have all values.
214         $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
215         $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
216         $row = $result->fetch(PDO::FETCH_ASSOC);
217         if ($row) {
218           $session = $row;
219         }
220       }
221     }
222     return $session;
223   }
224
225   function setRedirect($session, $redirect) {
226     $success = false;
227     // Save the request in the session so we can get back to fulfilling it if one of the links is clicked.
228     $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
229     if (!$result->execute(array(':redir' => $redirect, ':sessid' => $session['id']))) {
230       $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: '.$redirect);
231     }
232     else {
233       $success = true;
234     }
235     return $success;
236   }
237
238   function doRedirectIfSet($session) {
239     $success = false;
240     // If the session has a redirect set, make sure it's performed.
241     if (strlen(@$session['saved_redirect'])) {
242       // Remove redirect.
243       $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
244       if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
245         $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
246       }
247       else {
248         $success = true;
249       }
250       header('Location: '.$this->getDomainBaseURL().$session['saved_redirect']);
251     }
252     return $success;
253   }
254
255   function resetRedirect($session) {
256     $success = false;
257     // If the session has a redirect set, remove it.
258     if (strlen(@$session['saved_redirect'])) {
259       $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
260       if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
261         $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
262       }
263       else {
264         $success = true;
265       }
266     }
267     return $success;
268   }
269
270   function getDomainBaseURL() {
271     return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'];
272   }
273
274   function checkPasswordConstraints($new_password, $user_email) {
275     $errors = array();
276     if ($new_password != trim($new_password)) {
277       $errors[] = _('Password must not start or end with a whitespace character like a space.');
278     }
279     if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
280     if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
281     if ((strtolower($new_password) == strtolower($user_email)) ||
282         in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
283       $errors[] = _('The passwort can not be equal to your email or any part of it.');
284     }
285     if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
286       $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
287     }
288     if (preg_match('/^\d+$/', $new_password)) {
289       $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
290     }
291     if (strlen(count_chars($new_password, 3)) < 5) {
292       $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
293     }
294     return $errors;
295   }
296
297   function createSessionKey() {
298     return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
299   }
300
301   function createVerificationCode() {
302     return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
303   }
304
305   function createClientSecret() {
306     return bin2hex(openssl_random_pseudo_bytes(160 / 8)); // Get 160 bits of randomness (40 byte hex string).
307   }
308
309   function createTimeCode($session, $offset = null, $validity_minutes = 10) {
310     // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
311     $valid_seconds = intval($validity_minutes) * 60;
312     if ($valid_seconds < 60) { $valid_seconds = 60; }
313     $code_digits = 8;
314     $time = time();
315     $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.
316     $counter = floor(($time - $rest) / $valid_seconds);
317     $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']);
318     $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number.
319     $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit.
320     $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
321     return $rest.'.'.$totp_value;
322   }
323
324   function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) {
325     if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) {
326       return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes));
327     }
328     return false;
329   }
330
331   function pwdHash($new_password) {
332     $hash_prefix = '';
333     if (count($this->pwd_nonces)) {
334       $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1];
335       $hash_prefix = (count($this->pwd_nonces) - 1).'|';
336     }
337     return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
338   }
339
340   function pwdVerify($password_to_verify, $userdata) {
341     $pwdhash = $userdata['pwdhash'];
342     if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
343       $password_to_verify .= $this->pwd_nonces[$regs[1]];
344       $pwdhash = $regs[2];
345     }
346     return password_verify($password_to_verify, $pwdhash);
347   }
348
349   function pwdNeedsRehash($userdata) {
350     $nonceid = -1;
351     $pwdhash = $userdata['pwdhash'];
352     if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
353       $nonceid = $regs[1];
354       $pwdhash = $regs[2];
355     }
356     if ($nonceid == count($this->pwd_nonces) - 1) {
357       return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
358     }
359     else {
360       return true;
361     }
362   }
363
364   function negotiateLocale($supportedLanguages) {
365     $nlocale = $supportedLanguages[0];
366     $headers = getAllHeaders();
367     $accLcomp = explode(',', @$headers['Accept-Language']);
368     $accLang = array();
369     foreach ($accLcomp as $lcomp) {
370       if (strlen($lcomp)) {
371         $ldef = explode(';', $lcomp);
372         $accLang[$ldef[0]] = (float)((strpos(@$ldef[1],'q=')===0)?substr($ldef[1],2):1);
373       }
374     }
375     if (count($accLang)) {
376       $pLang = ''; $pLang_q = 0;
377       foreach ($supportedLanguages as $wantedLang) {
378         if (isset($accLang[$wantedLang]) && ($accLang[$wantedLang] > $pLang_q)) {
379           $pLang = $wantedLang;
380           $pLang_q = $accLang[$wantedLang];
381         }
382       }
383       if (strlen($pLang)) { $nlocale = $pLang; }
384     }
385     return $nlocale;
386   }
387
388   function getGroupedEmails($group_id, $exclude_email = '') {
389     $emails = array();
390     if (intval($group_id)) {
391       $result = $this->db->prepare('SELECT `email` FROM `auth_users` WHERE `group_id` = :groupid AND `status` = \'ok\' AND `email` != :excludemail ORDER BY `email` ASC;');
392       $result->execute(array(':groupid' => $group_id, ':excludemail' => $exclude_email));
393       foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
394         $emails[] = $row['email'];
395       }
396     }
397     return $emails;
398   }
399
400   function initHTMLDocument($titletext, $headlinetext = null) {
401     global $settings;
402     if (is_null($headlinetext)) { $headlinetext = $titletext; }
403     // Start HTML document as a DOM object.
404     extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
405     $document->formatOutput = true; // we want a nice output
406
407     $style = $head->appendElement('link');
408     $style->setAttribute('rel', 'stylesheet');
409     $style->setAttribute('href', 'authsystem.css');
410     $head->appendJSFile('authsystem.js');
411     if ($settings['piwik_enabled']) {
412       $head->setAttribute('data-piwiksite', $settings['piwik_site_id']);
413       $head->setAttribute('data-piwikurl', $settings['piwik_url']);
414       $head->appendJSFile('piwik.js', true, true);
415     }
416     $title->appendText($titletext);
417     $h1 = $body->appendElement('h1', $headlinetext);
418
419     if ($settings['piwik_enabled']) {
420       // Piwik noscript element
421       $noscript = $body->appendElement('noscript');
422       $para = $noscript->appendElement('p');
423       $img = $para->appendImage($settings['piwik_url'].'piwik.php?idsite='.$settings['piwik_site_id']);
424       $img->setAttribute('style', 'border:0;');
425     }
426
427     // Make the document not be scaled on mobile devices.
428     $vpmeta = $head->appendElement('meta');
429     $vpmeta->setAttribute('name', 'viewport');
430     $vpmeta->setAttribute('content', 'width=device-width, height=device-height');
431
432     $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
433     $para->setAttribute('id', 'jswarning');
434     $para->setAttribute('class', 'warn');
435
436     return array('document' => $document,
437                  'html' => $html,
438                  'head' => $head,
439                  'title' => $title,
440                  'body' => $body);
441   }
442
443   function appendLoginForm($dom_element, $session, $user, $addfields = array()) {
444     $form = $dom_element->appendForm('./', 'POST', 'loginform');
445     $form->setAttribute('id', 'loginform');
446     $form->setAttribute('class', 'loginarea hidden');
447     $ulist = $form->appendElement('ul');
448     $ulist->setAttribute('class', 'flat login');
449     $litem = $ulist->appendElement('li');
450     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval(@$user['id'])?$user['email']:''));
451     $inptxt->setAttribute('autocomplete', 'email');
452     $inptxt->setAttribute('required', '');
453     $inptxt->setAttribute('placeholder', _('Email'));
454     $inptxt->setAttribute('class', 'login');
455     $litem = $ulist->appendElement('li');
456     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
457     $inptxt->setAttribute('required', '');
458     $inptxt->setAttribute('placeholder', _('Password'));
459     $inptxt->setAttribute('class', 'login');
460     $litem = $ulist->appendElement('li');
461     $litem->appendLink('./?reset', _('Forgot password?'));
462     /*
463     $litem = $ulist->appendElement('li');
464     $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
465     $cbox->setAttribute('class', 'logincheck');
466     $label = $litem->appendLabel('login_remember', _('Remember me'));
467     $label->setAttribute('id', 'rememprompt');
468     $label->setAttribute('class', 'loginprompt');
469     */
470     $litem = $ulist->appendElement('li');
471     $litem->appendInputHidden('tcode', $this->createTimeCode($session));
472     foreach ($addfields as $fname => $fvalue) {
473       $litem->appendInputHidden($fname, $fvalue);
474     }
475     $submit = $litem->appendInputSubmit(_('Log in / Register'));
476     $submit->setAttribute('class', 'loginbutton');
477   }
478 }
479 ?>