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