bea265aceab214221b8eb8d912a1423da3b516a7
[authserver.git] / index.php
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 // Include the common auth system files (including the OAuth2 Server object).
7 require_once(__DIR__.'/authsystem.inc.php');
8
9 $errors = array();
10
11 // Start HTML document as a DOM object.
12 extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
13 $document->formatOutput = true; // we want a nice output
14
15 $style = $head->appendElement('link');
16 $style->setAttribute('rel', 'stylesheet');
17 $style->setAttribute('href', 'authsystem.css');
18 $head->appendJSFile('authsystem.js');
19 $title->appendText('KaiRo.at Authentication Server');
20 $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server');
21
22 $running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
23 if (($_SERVER['SERVER_PORT'] != 443) && !$running_on_localhost) {
24   $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
25 }
26
27 $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
28 $para->setAttribute('id', 'jswarning');
29 $para->setAttribute('class', 'warn');
30
31 if (!count($errors)) {
32   $session = null;
33   $user = array('id' => 0, 'email' => '');
34   $pagetype = 'default';
35   $db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly.
36   if (strlen(@$_COOKIE['sessionkey'])) {
37     // Fetch the session - or at least try to.
38     $result = $db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
39     $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
40     $row = $result->fetch(PDO::FETCH_ASSOC);
41     if ($row) {
42       $session = $row;
43
44       if (array_key_exists('logout', $_GET)) {
45         $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
46         if (!$result->execute(array(':sessid' => $session['id']))) {
47           // XXXlog: Unexpected logout failure!
48           $errors[] = _('The email address is invalid.');
49         }
50         $session['logged_in'] = 0;
51       }
52       elseif (array_key_exists('email', $_POST)) {
53         if (!preg_match('/^[^@]+@[^@]+\.[^@]+$/', $_POST['email'])) {
54           $errors[] = _('The email address is invalid.');
55         }
56         else {
57           $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash` FROM `auth_users` WHERE `email` = :email;');
58           $result->execute(array(':email' => $_POST['email']));
59           $user = $result->fetch(PDO::FETCH_ASSOC);
60           if ($user['id'] && array_key_exists('pwd', $_POST)) {
61             // existing user, check password
62             if (($user['status'] == 'ok') && password_verify(@$_POST['pwd'], $user['pwdhash'])) {
63               // Check if a newer hashing algorithm is available
64               // or the cost has changed
65               if (password_needs_rehash($user['pwdhash'], PASSWORD_DEFAULT, $pwd_options)) {
66                 // If so, create a new hash, and replace the old one
67                 $newHash = password_hash($_POST['pwd'], PASSWORD_DEFAULT, $pwd_options);
68                 $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash WHERE `id` = :userid;');
69                 if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $user['id']))) {
70                   // XXXlog: Failed to update user hash!
71                 }
72               }
73
74               // Log user in - update session key for that, see https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Login
75               $sesskey = bin2hex(openssl_random_pseudo_bytes(512/8)); // Get 512 bits of randomness (128 byte hex string).
76               setcookie('sessionkey', $sesskey, 0, "", "", !$running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
77               // If the session has a user set, create a new one - otherwise take existing session entry.
78               if (intval($session['user'])) {
79                 $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
80                 $result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
81                 // After insert, actually fetch the session row from the DB so we have all values.
82                 $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
83                 $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
84                 $row = $result->fetch(PDO::FETCH_ASSOC);
85                 if ($row) {
86                   $session = $row;
87                 }
88                 else {
89                   // XXXlog: unexpected failure to create session!
90                   $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.');
91                 }
92               }
93               else {
94                 $result = $db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
95                 if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
96                   // XXXlog: Unexpected login failure!
97                   $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
98                 }
99               }
100             }
101             else {
102               $errors[] = _('This password is invalid or your email is not verified yet. Did you type them correctly?');
103             }
104           }
105           else {
106             // new user: check password, create user and send verification; existing users: re-send verification or send password change instructions
107             if (array_key_exists('pwd', $_POST)) {
108               $errors += checkPasswordConstraints(strval($_POST['pwd']), $_POST['email']);
109             }
110             if (!count($errors)) {
111               // Put user into the DB
112               if (!$user['id']) {
113                 $newHash = password_hash($_POST['pwd'], PASSWORD_DEFAULT, $pwd_options);
114                 $vcode = bin2hex(openssl_random_pseudo_bytes(512/8)); // Get 512 bits of randomness (128 byte hex string).
115                 $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, \'unverified\', :vcode);');
116                 if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':vcode' => $vcode))) {
117                   // XXXlog: User insertion failure!
118                   $errors[] = _('Could not add user. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
119                 }
120                 $user = array('id' => $db->lastInsertId(),
121                               'email' => $_POST['email'],
122                               'pwdhash' => $newHash,
123                               'status' => 'unverified',
124                               'verify_hash' => $vcode);
125               }
126               if ($user['status'] == 'unverified') {
127                 // Send email for verification and show message to point to it.
128                 $mail = new email();
129                 $mail->setCharset('utf-8');
130                 $mail->addHeader('X-KAIRO-AUTH', 'email_verification');
131                 $mail->addRecipient($user['email']);
132                 $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
133                 $mail->setSubject('Email Verification for KaiRo.at Authentication');
134                 $mail->addMailText(_('Welcome!')."\n\n");
135                 $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'),
136                                           $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
137                 $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n");
138                 $mail->addMailText(($running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true)
139                                   .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n");
140                 $mail->addMailText(_('With this confirmation, you accept that we handle your data for the purpose of logging you into other websites when you request that.')."\n");
141                 $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n");
142                 $mail->addMailText(_('If you do not call this confirmation link within 72 hours, your data will be deleted from our database.')."\n\n");
143                 $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
144                 //$mail->setDebugAddress("robert@localhost");
145                 $mailsent = $mail->send();
146                 if ($mailsent) {
147                   $pagetype = 'verification_sent';
148                 }
149                 else {
150                   $errors[] = _('The confirmation email could not be sent to you. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
151                 }
152               }
153               else {
154                 // Send email with instructions for resetting the password.
155               }
156             }
157           }
158         }
159       }
160       elseif (array_key_exists('reset', $_GET)) {
161         if ($session['logged_in']) {
162           $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
163           $result->execute(array(':userid' => $session['user']));
164           $user = $result->fetch(PDO::FETCH_ASSOC);
165           if (!$user['id']) {
166             // XXXlog: unexpected failure to fetch user data!
167           }
168           $pagetype = 'resetpwd';
169         }
170         else {
171           // Display form for entering email.
172           $pagetype = 'resetstart';
173         }
174       }
175       elseif (array_key_exists('verification_code', $_GET)) {
176         $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `email` = :email AND `status` = \'unverified\' AND `verify_hash` = :vcode;');
177         $result->execute(array(':email' => @$_GET['email'], ':vcode' => $_GET['verification_code']));
178         $user = $result->fetch(PDO::FETCH_ASSOC);
179         if ($user['id']) {
180           $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\', `status` = \'ok\' WHERE `id` = :userid;');
181           if (!$result->execute(array(':userid' => $user['id']))) {
182             // XXXlog: unexpected failure to save verification!
183             $errors[] = _('Could not save confirmation. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
184           }
185           $pagetype = 'verification_done';
186         }
187         else {
188           $errors[] = _('The confirmation link you called is not valid. Possibly it has expired and you need to try registering again.');
189         }
190       }
191       elseif (intval($session['user'])) {
192         $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
193         $result->execute(array(':userid' => $session['user']));
194         $user = $result->fetch(PDO::FETCH_ASSOC);
195         if (!$user['id']) {
196           // XXXlog: unexpected failure to fetch user data!
197         }
198         // Password reset requested.
199         if (array_key_exists('pwd', $_POST) && array_key_exists('reset', $_POST) && array_key_exists('tcode', $_POST)) {
200           $errors += checkPasswordConstraints(strval($_POST['pwd']), $user['email']);
201           if (!count($errors)) {
202             $newHash = password_hash($_POST['pwd'], PASSWORD_DEFAULT, $pwd_options);
203             $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash WHERE `id` = :userid;');
204             if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $session['user']))) {
205               // XXXlog: Password reset failure!
206               $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
207             }
208             else {
209               $pagetype = 'pwd_reset_done';
210             }
211           }
212         }
213       }
214     }
215   }
216   if (is_null($session)) {
217     // Create new session and set cookie.
218     $sesskey = bin2hex(openssl_random_pseudo_bytes(512/8)); // Get 512 bits of randomness (128 byte hex string).
219     setcookie('sessionkey', $sesskey, 0, "", "", !$running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
220     $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
221     $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
222     // After insert, actually fetch the session row from the DB so we have all values.
223     $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
224     $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
225     $row = $result->fetch(PDO::FETCH_ASSOC);
226     if ($row) {
227       $session = $row;
228     }
229     else {
230       // XXXlog: unexpected failure to create session!
231       $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.');
232     }
233   }
234 }
235
236 if (!count($errors)) {
237   if ($pagetype == 'verification_sent') {
238     $para = $body->appendElement('p', sprintf(_('An email for confirmation has been sent to %s. Please follow the link provided there to complete the process.'), $user['email']));
239     $para->setAttribute('class', 'verifyinfo pending');
240   }
241   elseif ($pagetype == 'resetstart') {
242     $para = $body->appendElement('p', _('If you forgot your password or didn\'t receive the registration confirmation, please enter your email here.'));
243     $para->setAttribute('class', '');
244     $form = $body->appendForm('?reset', 'POST', 'resetform');
245     $form->setAttribute('id', 'loginform');
246     $form->setAttribute('class', 'loginarea hidden');
247     $ulist = $form->appendElement('ul');
248     $ulist->setAttribute('class', 'flat login');
249     $litem = $ulist->appendElement('li');
250     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email');
251     $inptxt->setAttribute('autocomplete', 'email');
252     $inptxt->setAttribute('required', '');
253     $inptxt->setAttribute('placeholder', _('Email'));
254     $litem = $ulist->appendElement('li');
255     $litem->appendInputHidden('tcode', createTimeCode($session));
256     $submit = $litem->appendInputSubmit(_('Send instructions to email'));
257   }
258   elseif ($pagetype == 'resetpwd') {
259     $para = $body->appendElement('p', _('You can set a new password here.'));
260     $para->setAttribute('class', '');
261     $form = $body->appendForm('?', 'POST', 'newpwdform');
262     $form->setAttribute('id', 'loginform');
263     $form->setAttribute('class', 'loginarea hidden');
264     $ulist = $form->appendElement('ul');
265     $ulist->setAttribute('class', 'flat login');
266     $litem = $ulist->appendElement('li');
267     $litem->setAttribute('class', 'donotshow');
268     $inptxt = $litem->appendInputEmail('email_hidden', 30, 20, 'login_email', $user['email']);
269     $inptxt->setAttribute('autocomplete', 'email');
270     $inptxt->setAttribute('placeholder', _('Email'));
271     $litem = $ulist->appendElement('li');
272     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
273     $inptxt->setAttribute('required', '');
274     $inptxt->setAttribute('placeholder', _('Password'));
275     $inptxt->setAttribute('class', 'login');
276     $litem = $ulist->appendElement('li');
277     $litem->appendInputHidden('reset', '');
278     $litem->appendInputHidden('tcode', createTimeCode($session));
279     $submit = $litem->appendInputSubmit(_('Save password'));
280   }
281   elseif ($session['logged_in']) {
282     if ($pagetype == 'reset_done') {
283       $para = $body->appendElement('p', _('Your password has successfully been reset.'));
284       $para->setAttribute('class', 'resetinfo done');
285     }
286     $div = $body->appendElement('div', $user['email']);
287     $div->setAttribute('class', 'loginheader');
288     $div = $body->appendElement('div');
289     $div->setAttribute('class', 'loginlinks');
290     $ulist = $div->appendElement('ul');
291     $ulist->setAttribute('class', 'flat');
292     $litem = $ulist->appendElement('li');
293     $link = $litem->appendLink('?logout', _('Log out'));
294     $litem = $ulist->appendElement('li');
295     $litem->appendLink('?reset', _('Set new password'));
296   }
297   else { // not logged in
298     if ($pagetype == 'verification_done') {
299       $para = $body->appendElement('p', _('Hooray! Your email was successfully confirmed! You can log in now.'));
300       $para->setAttribute('class', 'verifyinfo done');
301     }
302     elseif ($pagetype == 'reset_done') {
303       $para = $body->appendElement('p', _('Your password has successfully been reset. You can log in now with the new password.'));
304       $para->setAttribute('class', 'resetinfo done');
305     }
306     $form = $body->appendForm('?', 'POST', 'loginform');
307     $form->setAttribute('id', 'loginform');
308     $form->setAttribute('class', 'loginarea hidden');
309     $ulist = $form->appendElement('ul');
310     $ulist->setAttribute('class', 'flat login');
311     $litem = $ulist->appendElement('li');
312     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval($user['id'])?$user['email']:''));
313     $inptxt->setAttribute('autocomplete', 'email');
314     $inptxt->setAttribute('required', '');
315     $inptxt->setAttribute('placeholder', _('Email'));
316     $inptxt->setAttribute('class', 'login');
317     $litem = $ulist->appendElement('li');
318     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
319     $inptxt->setAttribute('required', '');
320     $inptxt->setAttribute('placeholder', _('Password'));
321     $inptxt->setAttribute('class', 'login');
322     $litem = $ulist->appendElement('li');
323     $litem->appendLink('?reset', _('Forgot password?'));
324     $litem = $ulist->appendElement('li');
325     $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
326     $cbox->setAttribute('class', 'logincheck');
327     $label = $litem->appendLabel('login_remember', _('Remember me'));
328     $label->setAttribute('id', 'rememprompt');
329     $label->setAttribute('class', 'loginprompt');
330     $litem = $ulist->appendElement('li');
331     $litem->appendInputHidden('tcode', createTimeCode($session));
332     $submit = $litem->appendInputSubmit(_('Log in / Register'));
333     $submit->setAttribute('class', 'loginbutton');
334   }
335 }
336
337 if (count($errors)) {
338   $body->appendElement('p', ((count($errors) <= 1)
339                             ?_('The following error was detected')
340                             :_('The following errors were detected')).':');
341   $list = $body->appendElement('ul');
342   $list->setAttribute('class', 'flat warn');
343   foreach ($errors as $msg) {
344     $item = $list->appendElement('li', $msg);
345   }
346   $body->appendButton(_('Back'), 'history.back();');
347 }
348
349 // Send HTML to client.
350 print($document->saveHTML());
351
352 // ********** helper functions **********
353
354 function checkPasswordConstraints($new_password, $user_email) {
355   $errors = array();
356   if ($new_password != trim($new_password)) {
357     $errors[] = _('Password must not start or end with a whitespace character like a space.');
358   }
359   if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
360   if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
361   if ((strtolower($new_password) == strtolower($user_email)) ||
362       in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
363     $errors[] = _('The passwort can not be equal to your email or any part of it.');
364   }
365   if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
366     $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
367   }
368   if (preg_match('/^\d+$/', $new_password)) {
369     $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
370   }
371   if (strlen(count_chars($new_password, 3)) < 5) {
372     $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
373   }
374   return $errors;
375 }
376
377 function createTimeCode($session) {
378   // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
379   $valid_seconds = 600; $code_digits = 8;
380   $time = time();
381   $rest = $time % $valid_seconds; // T0, will be sent as part of code to make it valid for the full duration.
382   $counter = floor(($time - $rest) / $valid_seconds);
383   $hmac = mhash(MHASH_SHA1, $counter, $session['sesskey']);
384   $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number.
385   $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit.
386   $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
387   return $rest.'.'.$totp_value;
388 }
389
390 ?>