make the JS compatible with older IE versions, though this is a hack that hardcodes...
[authserver.git] / 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 getDomainBaseURL()
41   //   Get the base URL of the current domain, e.g. 'https://example.com'.
42   //
43   // function checkPasswordConstraints($new_password, $user_email)
44   //   Check password constraints and return an array of error messages (empty if all constraints are met).
45   //
46   // function createSessionKey()
47   //   Return a random session key.
48   //
49   // function createVerificationCode()
50   //   Return a random acount/email verification code.
51   //
52   // function createClientSecret()
53   //   Return a random client secret.
54   //
55   // function createTimeCode($session, [$offset], [$validity_minutes])
56   //   Return a time-based code based on the key and ID of the given session.
57   //     An offset can be given to create a specific code for verification, otherwise and offset will be generated.
58   //     Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used.
59   //
60   // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes])
61   //   Verify a given time-based code and return true if it's valid or false if it's not.
62   //     See createTimeCode() documentation for the session and validity paramerters.
63   //
64   // function pwdHash($new_password)
65   //   Return a hash for the given password.
66   //
67   // function pwdVerify($password_to_verify, $user)
68   //   Return true if the password verifies against the pwdhash field of the user, false if not.
69   //
70   // function pwdNeedsRehash($user)
71   //   Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
72   //
73   // function appendLoginForm($dom_element, $session, $user)
74   //   append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array.
75
76   function __construct($settings, $db) {
77     // *** constructor ***
78     $this->db = $db;
79     $this->db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly.
80     $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
81     if (array_key_exists('pwd_cost', $settings)) {
82       $this->pwd_cost = $settings['pwd_cost'];
83     }
84     if (array_key_exists('pwd_nonces', $settings)) {
85       $this->pwd_nonces = $settings['pwd_nonces'];
86     }
87   }
88
89   public $db = null;
90   public $running_on_localhost = false;
91   public $client_reg_email_whitelist = array('kairo@kairo.at', 'com@kairo.at');
92   private $pwd_cost = 10;
93   private $pwd_nonces = array();
94
95   function log($code, $info) {
96     $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
97     if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
98       // print($result->errorInfo()[2]);
99     }
100   }
101
102   function checkForSecureConnection() {
103     $errors = array();
104     if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) {
105       $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
106     }
107     return $errors;
108   }
109
110   function sendSecurityHeaders() {
111     // Send various headers that we want to have for security resons, mostly as recommended by https://observatory.mozilla.org/
112
113     // CSP - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy
114     // Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) from ourselves; also disable framing.
115     header('Content-Security-Policy: default-src \'none\';img-src \'self\'; script-src \'self\'; style-src \'self\'; frame-ancestors \'none\'');
116
117     // X-Content-Type-Options - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Content-Type-Options
118     // Prevent browsers from incorrectly detecting non-scripts as scripts
119     header('X-Content-Type-Options: nosniff');
120
121     // X-Frame-Options (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Frame-Options
122     // Block site from being framed
123     header('X-Frame-Options: DENY');
124
125     // X-XSS-Protection (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-XSS-Protection
126     // Block pages from loading when they detect reflected XSS attacks
127     header('X-XSS-Protection: 1; mode=block');
128   }
129
130   function initSession() {
131     $session = null;
132     if (strlen(@$_COOKIE['sessionkey'])) {
133       // Fetch the session - or at least try to.
134       $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
135       $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
136       $row = $result->fetch(PDO::FETCH_ASSOC);
137       if ($row) {
138         $session = $row;
139       }
140     }
141     if (is_null($session)) {
142       // Create new session and set cookie.
143       $sesskey = $this->createSessionKey();
144       setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
145       $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
146       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
147       // After insert, actually fetch the session row from the DB so we have all values.
148       $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
149       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
150       $row = $result->fetch(PDO::FETCH_ASSOC);
151       if ($row) {
152         $session = $row;
153       }
154       else {
155         $this->log('session_create_failure', 'key: '.$sesskey);
156       }
157     }
158     return $session;
159   }
160
161   function getDomainBaseURL() {
162     return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'];
163   }
164
165   function checkPasswordConstraints($new_password, $user_email) {
166     $errors = array();
167     if ($new_password != trim($new_password)) {
168       $errors[] = _('Password must not start or end with a whitespace character like a space.');
169     }
170     if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
171     if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
172     if ((strtolower($new_password) == strtolower($user_email)) ||
173         in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
174       $errors[] = _('The passwort can not be equal to your email or any part of it.');
175     }
176     if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
177       $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
178     }
179     if (preg_match('/^\d+$/', $new_password)) {
180       $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
181     }
182     if (strlen(count_chars($new_password, 3)) < 5) {
183       $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
184     }
185     return $errors;
186   }
187
188   function createSessionKey() {
189     return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
190   }
191
192   function createVerificationCode() {
193     return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
194   }
195
196   function createClientSecret() {
197     return bin2hex(openssl_random_pseudo_bytes(160 / 8)); // Get 160 bits of randomness (40 byte hex string).
198   }
199
200   function createTimeCode($session, $offset = null, $validity_minutes = 10) {
201     // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
202     $valid_seconds = intval($validity_minutes) * 60;
203     if ($valid_seconds < 60) { $valid_seconds = 60; }
204     $code_digits = 8;
205     $time = time();
206     $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.
207     $counter = floor(($time - $rest) / $valid_seconds);
208     $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']);
209     $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number.
210     $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit.
211     $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
212     return $rest.'.'.$totp_value;
213   }
214
215   function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) {
216     if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) {
217       return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes));
218     }
219     return false;
220   }
221
222   function pwdHash($new_password) {
223     $hash_prefix = '';
224     if (count($this->pwd_nonces)) {
225       $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1];
226       $hash_prefix = (count($this->pwd_nonces) - 1).'|';
227     }
228     return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
229   }
230
231   function pwdVerify($password_to_verify, $userdata) {
232     $pwdhash = $userdata['pwdhash'];
233     if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
234       $password_to_verify .= $this->pwd_nonces[$regs[1]];
235       $pwdhash = $regs[2];
236     }
237     return password_verify($password_to_verify, $pwdhash);
238   }
239
240   function pwdNeedsRehash($userdata) {
241     $nonceid = -1;
242     $pwdhash = $userdata['pwdhash'];
243     if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
244       $nonceid = $regs[1];
245       $pwdhash = $regs[2];
246     }
247     if ($nonceid == count($this->pwd_nonces) - 1) {
248       return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
249     }
250     else {
251       return true;
252     }
253   }
254
255   function appendLoginForm($dom_element, $session, $user) {
256     $form = $dom_element->appendForm('./', 'POST', 'loginform');
257     $form->setAttribute('id', 'loginform');
258     $form->setAttribute('class', 'loginarea hidden');
259     $ulist = $form->appendElement('ul');
260     $ulist->setAttribute('class', 'flat login');
261     $litem = $ulist->appendElement('li');
262     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval(@$user['id'])?$user['email']:''));
263     $inptxt->setAttribute('autocomplete', 'email');
264     $inptxt->setAttribute('required', '');
265     $inptxt->setAttribute('placeholder', _('Email'));
266     $inptxt->setAttribute('class', 'login');
267     $litem = $ulist->appendElement('li');
268     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
269     $inptxt->setAttribute('required', '');
270     $inptxt->setAttribute('placeholder', _('Password'));
271     $inptxt->setAttribute('class', 'login');
272     $litem = $ulist->appendElement('li');
273     $litem->appendLink('./?reset', _('Forgot password?'));
274     $litem = $ulist->appendElement('li');
275     $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
276     $cbox->setAttribute('class', 'logincheck');
277     $label = $litem->appendLabel('login_remember', _('Remember me'));
278     $label->setAttribute('id', 'rememprompt');
279     $label->setAttribute('class', 'loginprompt');
280     $litem = $ulist->appendElement('li');
281     $litem->appendInputHidden('tcode', $this->createTimeCode($session));
282     $submit = $litem->appendInputSubmit(_('Log in / Register'));
283     $submit->setAttribute('class', 'loginbutton');
284   }
285 }
286 ?>