first step in making the authorize target work correctly, move check for secure conne...
[authserver.git] / index.php
index 2a560e8928dd54abb9096aa223d12112e690e97e..841333bb3433ab70ab766878341819cd3d1d0cd5 100644 (file)
--- a/index.php
+++ b/index.php
@@ -19,10 +19,7 @@ $head->appendJSFile('authsystem.js');
 $title->appendText('KaiRo.at Authentication Server');
 $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server');
 
-$running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
-if (($_SERVER['SERVER_PORT'] != 443) && !$running_on_localhost) {
-  $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
-}
+$errors += $utils->checkForSecureConnection();
 
 $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
 $para->setAttribute('id', 'jswarning');
@@ -44,7 +41,7 @@ if (!count($errors)) {
       if (array_key_exists('logout', $_GET)) {
         $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
         if (!$result->execute(array(':sessid' => $session['id']))) {
-          // XXXlog: Unexpected logout failure!
+          $utils->log('logout_failure', 'session: '.$session['id']);
           $errors[] = _('The email address is invalid.');
         }
         $session['logged_in'] = 0;
@@ -53,27 +50,31 @@ if (!count($errors)) {
         if (!preg_match('/^[^@]+@[^@]+\.[^@]+$/', $_POST['email'])) {
           $errors[] = _('The email address is invalid.');
         }
-        elseif (AuthUtils::verifyTimeCode(@$_POST['tcode'], $session)) {
+        elseif ($utils->verifyTimeCode(@$_POST['tcode'], $session)) {
           $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash` FROM `auth_users` WHERE `email` = :email;');
           $result->execute(array(':email' => $_POST['email']));
           $user = $result->fetch(PDO::FETCH_ASSOC);
           if ($user['id'] && array_key_exists('pwd', $_POST)) {
             // existing user, check password
-            if (($user['status'] == 'ok') && password_verify(@$_POST['pwd'], $user['pwdhash'])) {
+            if (($user['status'] == 'ok') && $utils->pwdVerify(@$_POST['pwd'], $user)) {
               // Check if a newer hashing algorithm is available
               // or the cost has changed
-              if (password_needs_rehash($user['pwdhash'], PASSWORD_DEFAULT, $pwd_options)) {
+              if ($utils->pwdNeedsRehash($user)) {
                 // If so, create a new hash, and replace the old one
-                $newHash = password_hash($_POST['pwd'], PASSWORD_DEFAULT, $pwd_options);
+                $newHash = $utils->pwdHash($_POST['pwd']);
                 $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash WHERE `id` = :userid;');
                 if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $user['id']))) {
-                  // XXXlog: Failed to update user hash!
+                  $utils->log('user_hash_save_failure', 'user: '.$user['id']);
+                }
+                else {
+                  $utils->log('pwd_rehash_success', 'user: '.$user['id']);
                 }
               }
 
               // Log user in - update session key for that, see https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Login
-              $sesskey = AuthUtils::createSessionKey();
-              setcookie('sessionkey', $sesskey, 0, "", "", !$running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
+              $utils->log('login', 'user: '.$user['id']);
+              $sesskey = $utils->createSessionKey();
+              setcookie('sessionkey', $sesskey, 0, "", "", !$utils->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
               // If the session has a user set, create a new one - otherwise take existing session entry.
               if (intval($session['user'])) {
                 $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
@@ -86,14 +87,14 @@ if (!count($errors)) {
                   $session = $row;
                 }
                 else {
-                  // XXXlog: Unexpected failure to create session!
+                  $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$user['id']);
                   $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.');
                 }
               }
               else {
                 $result = $db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
                 if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
-                  // XXXlog: Unexpected login failure!
+                  $utils->log('login_failure', 'session: '.$session['id'].', user: '.$user['id']);
                   $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
                 }
               }
@@ -101,7 +102,7 @@ if (!count($errors)) {
               if (strlen(@$user['verify_hash'])) {
                 $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\' WHERE `id` = :userid;');
                 if (!$result->execute(array(':userid' => $user['id']))) {
-                  // XXXlog: verify_hash could not be emptied!
+                  $utils->log('empty_vhash_failure', 'user: '.$user['id']);
                 }
                 else {
                   $user['verify_hash'] = '';
@@ -115,16 +116,16 @@ if (!count($errors)) {
           else {
             // new user: check password, create user and send verification; existing users: re-send verification or send password change instructions
             if (array_key_exists('pwd', $_POST)) {
-              $errors += AuthUtils::checkPasswordConstraints(strval($_POST['pwd']), $_POST['email']);
+              $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $_POST['email']);
             }
             if (!count($errors)) {
               // Put user into the DB
               if (!$user['id']) {
-                $newHash = password_hash($_POST['pwd'], PASSWORD_DEFAULT, $pwd_options);
-                $vcode = AuthUtils::createVerificationCode();
+                $newHash = $utils->pwdHash($_POST['pwd']);
+                $vcode = $utils->createVerificationCode();
                 $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, \'unverified\', :vcode);');
                 if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':vcode' => $vcode))) {
-                  // XXXlog: User insertion failure!
+                  $utils->log('user_insert_failure', 'email: '.$_POST['email']);
                   $errors[] = _('Could not add user. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
                 }
                 $user = array('id' => $db->lastInsertId(),
@@ -132,6 +133,7 @@ if (!count($errors)) {
                               'pwdhash' => $newHash,
                               'status' => 'unverified',
                               'verify_hash' => $vcode);
+                $utils->log('new_user', 'user: '.$user['id'].', email: '.$user['email']);
               }
               if ($user['status'] == 'unverified') {
                 // Send email for verification and show message to point to it.
@@ -145,7 +147,7 @@ if (!count($errors)) {
                 $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'),
                                           $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
                 $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n");
-                $mail->addMailText(($running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true)
+                $mail->addMailText(($utils->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true)
                                   .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n");
                 $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");
                 $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n");
@@ -157,19 +159,21 @@ if (!count($errors)) {
                   $pagetype = 'verification_sent';
                 }
                 else {
+                  $utils->log('verify_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
                   $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.');
                 }
               }
               else {
                 // Password reset requested with "Password forgotten?" function.
-                $vcode = AuthUtils::createVerificationCode();
+                $vcode = $utils->createVerificationCode();
                 $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
                 if (!$result->execute(array(':vcode' => $vcode, ':userid' => $user['id']))) {
-                  // XXXlog: User insertion failure!
+                  $utils->log('vhash_set_failure', 'user: '.$user['id']);
                   $errors[] = _('Could not initiate reset request. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
                 }
                 else {
-                  $resetcode = $vcode.dechex($user['id'] + $session['id']).'_'.AuthUtils::createTimeCode($session, null, 60);
+                  $utils->log('pwd_reset_request', 'user: '.$user['id'].', email: '.$user['email']);
+                  $resetcode = $vcode.dechex($user['id'] + $session['id']).'_'.$utils->createTimeCode($session, null, 60);
                   // Send email with instructions for resetting the password.
                   $mail = new email();
                   $mail->setCharset('utf-8');
@@ -181,7 +185,7 @@ if (!count($errors)) {
                   $mail->addMailText(sprintf(_('A request for setting a new password for this email address, %s, has been submitted on "%s".'),
                                             $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
                   $mail->addMailText(_('You can set a new password by clicking the following link (or calling it up in your browser):')."\n");
-                  $mail->addMailText(($running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true)
+                  $mail->addMailText(($utils->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true)
                                     .'?email='.rawurlencode($user['email']).'&reset_code='.rawurlencode($resetcode)."\n\n");
                   $mail->addMailText(_('If you do not call this confirmation link within 1 hour, this link expires and the existing password is being kept in place.')."\n\n");
                   $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
@@ -191,6 +195,7 @@ if (!count($errors)) {
                     $pagetype = 'resetmail_sent';
                   }
                   else {
+                    $utils->log('pwd_reset_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
                     $errors[] = _('The email with password reset instructions could not be sent to you. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
                   }
                 }
@@ -208,7 +213,7 @@ if (!count($errors)) {
           $result->execute(array(':userid' => $session['user']));
           $user = $result->fetch(PDO::FETCH_ASSOC);
           if (!$user['id']) {
-            // XXXlog: Unexpected failure to fetch user data!
+            $utils->log('reset_user_read_failure', 'user: '.$session['user']);
           }
           $pagetype = 'resetpwd';
         }
@@ -224,7 +229,7 @@ if (!count($errors)) {
         if ($user['id']) {
           $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\', `status` = \'ok\' WHERE `id` = :userid;');
           if (!$result->execute(array(':userid' => $user['id']))) {
-            // XXXlog: Unexpected failure to save verification!
+            $utils->log('verification_save_failure', 'user: '.$user['id']);
             $errors[] = _('Could not save confirmation. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
           }
           $pagetype = 'verification_done';
@@ -248,16 +253,16 @@ if (!count($errors)) {
             if ($row) {
               $tcode_session = $row;
               if (($regs[1] == $user['verify_hash']) &&
-                  AuthUtils::verifyTimeCode($regs[3], $session, 60)) {
+                  $utils->verifyTimeCode($regs[3], $session, 60)) {
                 // Set a new verify_hash for the actual password reset.
-                $user['verify_hash'] = AuthUtils::createVerificationCode();
+                $user['verify_hash'] = $utils->createVerificationCode();
                 $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
                 if (!$result->execute(array(':vcode' => $user['verify_hash'], ':userid' => $user['id']))) {
-                  // XXXlog: Unexpected failure to reset verify_hash!
+                  $utils->log('vhash_reset_failure', 'user: '.$user['id']);
                 }
                 $result = $db->prepare('UPDATE `auth_sessions` SET `user` = :userid WHERE `id` = :sessid;');
                 if (!$result->execute(array(':userid' => $user['id'], ':sessid' => $session['id']))) {
-                  // XXXlog: Unexpected failure to update session!
+                  $utils->log('reset_session_set_user_failure', 'session: '.$session['id']);
                 }
                 $pagetype = 'resetpwd';
                 $reset_fail = false;
@@ -274,7 +279,7 @@ if (!count($errors)) {
         $result->execute(array(':userid' => $session['user']));
         $user = $result->fetch(PDO::FETCH_ASSOC);
         if (!$user['id']) {
-          // XXXlog: Unexpected failure to fetch user data!
+          $utils->log('user_read_failure', 'user: '.$session['user']);
         }
         // Password reset requested.
         if (array_key_exists('pwd', $_POST) && array_key_exists('reset', $_POST) && array_key_exists('tcode', $_POST)) {
@@ -287,15 +292,15 @@ if (!count($errors)) {
             $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
           }
           // Check validity of time code.
-          if (!count($errors) && !AuthUtils::verifyTimeCode($_POST['tcode'], $session)) {
+          if (!count($errors) && !$utils->verifyTimeCode($_POST['tcode'], $session)) {
             $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
           }
-          $errors += AuthUtils::checkPasswordConstraints(strval($_POST['pwd']), $user['email']);
+          $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $user['email']);
           if (!count($errors)) {
-            $newHash = password_hash($_POST['pwd'], PASSWORD_DEFAULT, $pwd_options);
+            $newHash = $utils->pwdHash($_POST['pwd']);
             $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash, `verify_hash` = \'\' WHERE `id` = :userid;');
             if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $session['user']))) {
-              // XXXlog: Password reset failure!
+              $utils->log('pwd_reset_failure', 'user: '.$session['user']);
               $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
             }
             else {
@@ -308,8 +313,8 @@ if (!count($errors)) {
   }
   if (is_null($session)) {
     // Create new session and set cookie.
-    $sesskey = AuthUtils::createSessionKey();
-    setcookie('sessionkey', $sesskey, 0, "", "", !$running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
+    $sesskey = $utils->createSessionKey();
+    setcookie('sessionkey', $sesskey, 0, "", "", !$utils->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
     $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
     $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
     // After insert, actually fetch the session row from the DB so we have all values.
@@ -320,7 +325,7 @@ if (!count($errors)) {
       $session = $row;
     }
     else {
-      // XXXlog: Unexpected failure to create session!
+      $utils->log('session_create_failure', 'key: '.$sesskey);
       $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.');
     }
   }
@@ -339,7 +344,7 @@ if (!count($errors)) {
   elseif ($pagetype == 'resetstart') {
     $para = $body->appendElement('p', _('If you forgot your password or didn\'t receive the registration confirmation, please enter your email here.'));
     $para->setAttribute('class', '');
-    $form = $body->appendForm('?reset', 'POST', 'resetform');
+    $form = $body->appendForm('./?reset', 'POST', 'resetform');
     $form->setAttribute('id', 'loginform');
     $form->setAttribute('class', 'loginarea hidden');
     $ulist = $form->appendElement('ul');
@@ -350,13 +355,13 @@ if (!count($errors)) {
     $inptxt->setAttribute('required', '');
     $inptxt->setAttribute('placeholder', _('Email'));
     $litem = $ulist->appendElement('li');
-    $litem->appendInputHidden('tcode', AuthUtils::createTimeCode($session));
+    $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
     $submit = $litem->appendInputSubmit(_('Send instructions to email'));
   }
   elseif ($pagetype == 'resetpwd') {
     $para = $body->appendElement('p', sprintf(_('You can set a new password for %s here.'), $user['email']));
     $para->setAttribute('class', '');
-    $form = $body->appendForm('?', 'POST', 'newpwdform');
+    $form = $body->appendForm('./', 'POST', 'newpwdform');
     $form->setAttribute('id', 'loginform');
     $form->setAttribute('class', 'loginarea hidden');
     $ulist = $form->appendElement('ul');
@@ -373,7 +378,7 @@ if (!count($errors)) {
     $inptxt->setAttribute('class', 'login');
     $litem = $ulist->appendElement('li');
     $litem->appendInputHidden('reset', '');
-    $litem->appendInputHidden('tcode', AuthUtils::createTimeCode($session));
+    $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
     if (!$session['logged_in'] && strlen(@$user['verify_hash'])) {
       $litem->appendInputHidden('vcode', $user['verify_hash']);
     }
@@ -391,9 +396,9 @@ if (!count($errors)) {
     $ulist = $div->appendElement('ul');
     $ulist->setAttribute('class', 'flat');
     $litem = $ulist->appendElement('li');
-    $link = $litem->appendLink('?logout', _('Log out'));
+    $link = $litem->appendLink('./?logout', _('Log out'));
     $litem = $ulist->appendElement('li');
-    $litem->appendLink('?reset', _('Set new password'));
+    $litem->appendLink('./?reset', _('Set new password'));
   }
   else { // not logged in
     if ($pagetype == 'verification_done') {
@@ -404,7 +409,7 @@ if (!count($errors)) {
       $para = $body->appendElement('p', _('Your password has successfully been reset. You can log in now with the new password.'));
       $para->setAttribute('class', 'resetinfo done');
     }
-    $form = $body->appendForm('?', 'POST', 'loginform');
+    $form = $body->appendForm('./', 'POST', 'loginform');
     $form->setAttribute('id', 'loginform');
     $form->setAttribute('class', 'loginarea hidden');
     $ulist = $form->appendElement('ul');
@@ -421,7 +426,7 @@ if (!count($errors)) {
     $inptxt->setAttribute('placeholder', _('Password'));
     $inptxt->setAttribute('class', 'login');
     $litem = $ulist->appendElement('li');
-    $litem->appendLink('?reset', _('Forgot password?'));
+    $litem->appendLink('./?reset', _('Forgot password?'));
     $litem = $ulist->appendElement('li');
     $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
     $cbox->setAttribute('class', 'logincheck');
@@ -429,7 +434,7 @@ if (!count($errors)) {
     $label->setAttribute('id', 'rememprompt');
     $label->setAttribute('class', 'loginprompt');
     $litem = $ulist->appendElement('li');
-    $litem->appendInputHidden('tcode', AuthUtils::createTimeCode($session));
+    $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
     $submit = $litem->appendInputSubmit(_('Log in / Register'));
     $submit->setAttribute('class', 'loginbutton');
   }