log failures and some other actions
authorRobert Kaiser <kairo@kairo.at>
Thu, 27 Oct 2016 00:54:33 +0000 (02:54 +0200)
committerRobert Kaiser <kairo@kairo.at>
Thu, 27 Oct 2016 00:54:33 +0000 (02:54 +0200)
authsystem.inc.php
authutils.php-class
index.php

index 322e17faf74d615bed3c27f5d495b49fa6c58b9c..2c98f6dd46ccf1d8f53a0ad023801b1b0c3ee841 100644 (file)
@@ -18,13 +18,14 @@ require_once('../kairo/include/cbsm/util/document.php-class');
 require_once('../kairo/include/classes/email.php-class');
 // Class for sending emails
 require_once(__DIR__.'/authutils.php-class');
 require_once('../kairo/include/classes/email.php-class');
 // Class for sending emails
 require_once(__DIR__.'/authutils.php-class');
-$utils = new AuthUtils($settings);
 
 bindtextdomain('kairo_auth', 'en'); // XXX: Should negotiate locale.
 bind_textdomain_codeset('kairo_auth', 'utf-8');
 
 // Connect to our MySQL DB
 $db = new PDO($dbdata['dsn'], $dbdata['username'], $dbdata['password']);
 
 bindtextdomain('kairo_auth', 'en'); // XXX: Should negotiate locale.
 bind_textdomain_codeset('kairo_auth', 'utf-8');
 
 // Connect to our MySQL DB
 $db = new PDO($dbdata['dsn'], $dbdata['username'], $dbdata['password']);
+// Instantiate auth utils.
+$utils = new AuthUtils($settings, $db);
 
 /* Creating the DB tables:
 CREATE TABLE `auth_sessions` (
 
 /* Creating the DB tables:
 CREATE TABLE `auth_sessions` (
@@ -47,6 +48,15 @@ CREATE TABLE `auth_users` (
  PRIMARY KEY (`id`),
  UNIQUE (`email`)
 );
  PRIMARY KEY (`id`),
  UNIQUE (`email`)
 );
+CREATE TABLE `auth_log` (
+ `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
+ `code` VARCHAR(100) NOT NULL ,
+ `info` TEXT NULL DEFAULT NULL ,
+ `ip_addr` VARCHAR(50) NULL DEFAULT NULL ,
+ `time_logged` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
+ PRIMARY KEY (`id`),
+ INDEX (`time_logged`)
+);
 */
 
 // include our OAuth2 Server object
 */
 
 // include our OAuth2 Server object
index 0b7d4b1e2acd4328e7ec0b25cc8160d119dae91e..729a2e900ab087d7447295ab5bda628e790e4588 100755 (executable)
@@ -7,8 +7,13 @@ class AuthUtils {
   // KaiRo.at authentication utilities PHP class
   // This class contains helper functions for the authentication system.
   //
   // KaiRo.at authentication utilities PHP class
   // This class contains helper functions for the authentication system.
   //
-  // function __construct()
+  // function __construct($settings, $db)
   //   CONSTRUCTOR
   //   CONSTRUCTOR
+  //   Settings are an associative array with a numeric pwd_cost field and an array pwd_nonces field.
+  //   The DB is a PDO object.
+  //
+  // public $db
+  //   A PDO database object for interaction.
   //
   // private $pwd_cost
   //   The cost parameter for use with PHP password_hash function.
   //
   // private $pwd_cost
   //   The cost parameter for use with PHP password_hash function.
@@ -17,6 +22,9 @@ class AuthUtils {
   //   The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used.
   //     Generate a nonce with this command: |openssl rand -base64 48|
   //
   //   The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used.
   //     Generate a nonce with this command: |openssl rand -base64 48|
   //
+  // function log($code, $additional_info)
+  //   Log an entry for admin purposes, with a code and some additional info.
+  //
   // function checkPasswordConstraints($new_password, $user_email)
   //   Check password constraints and return an array of error messages (empty if all constraints are met).
   //
   // function checkPasswordConstraints($new_password, $user_email)
   //   Check password constraints and return an array of error messages (empty if all constraints are met).
   //
@@ -44,19 +52,28 @@ class AuthUtils {
   // function pwdNeedsRehash($user)
   //   Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
 
   // function pwdNeedsRehash($user)
   //   Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
 
-  function __construct($settings) {
+  function __construct($settings, $db) {
     // *** constructor ***
     // *** constructor ***
-    if (array_key_exists('pwd_nonces', $settings)) {
-      $this->pwd_nonces = $settings['pwd_nonces'];
-    }
+    $this->db = $db;
     if (array_key_exists('pwd_cost', $settings)) {
       $this->pwd_cost = $settings['pwd_cost'];
     }
     if (array_key_exists('pwd_cost', $settings)) {
       $this->pwd_cost = $settings['pwd_cost'];
     }
+    if (array_key_exists('pwd_nonces', $settings)) {
+      $this->pwd_nonces = $settings['pwd_nonces'];
+    }
   }
 
   }
 
+  public $db = null;
   private $pwd_cost = 10;
   private $pwd_nonces = array();
 
   private $pwd_cost = 10;
   private $pwd_nonces = array();
 
+  function log($code, $info) {
+    $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
+    if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
+      // print($result->errorInfo()[2]);
+    }
+  }
+
   function checkPasswordConstraints($new_password, $user_email) {
     $errors = array();
     if ($new_password != trim($new_password)) {
   function checkPasswordConstraints($new_password, $user_email) {
     $errors = array();
     if ($new_password != trim($new_password)) {
index 9a6e74fc795d47575b13156110bea1724b5c9186..94812dc4a7d8dea4e0afe2f2c34a36923e0d8776 100644 (file)
--- a/index.php
+++ b/index.php
@@ -44,7 +44,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']))) {
       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;
           $errors[] = _('The email address is invalid.');
         }
         $session['logged_in'] = 0;
@@ -67,11 +67,15 @@ if (!count($errors)) {
                 $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']))) {
                 $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
                 }
               }
 
               // Log user in - update session key for that, see https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Login
+              $utils->log('login', 'user: '.$user['id']);
               $sesskey = $utils->createSessionKey();
               setcookie('sessionkey', $sesskey, 0, "", "", !$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.
               $sesskey = $utils->createSessionKey();
               setcookie('sessionkey', $sesskey, 0, "", "", !$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.
@@ -86,14 +90,14 @@ if (!count($errors)) {
                   $session = $row;
                 }
                 else {
                   $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']))) {
                   $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.');
                 }
               }
                   $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
                 }
               }
@@ -101,7 +105,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']))) {
               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'] = '';
                 }
                 else {
                   $user['verify_hash'] = '';
@@ -124,7 +128,7 @@ if (!count($errors)) {
                 $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))) {
                 $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(),
                   $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 +136,7 @@ if (!count($errors)) {
                               'pwdhash' => $newHash,
                               'status' => 'unverified',
                               'verify_hash' => $vcode);
                               '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.
               }
               if ($user['status'] == 'unverified') {
                 // Send email for verification and show message to point to it.
@@ -157,6 +162,7 @@ if (!count($errors)) {
                   $pagetype = 'verification_sent';
                 }
                 else {
                   $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.');
                 }
               }
                   $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.');
                 }
               }
@@ -165,10 +171,11 @@ if (!count($errors)) {
                 $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']))) {
                 $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 {
                   $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 {
+                  $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();
                   $resetcode = $vcode.dechex($user['id'] + $session['id']).'_'.$utils->createTimeCode($session, null, 60);
                   // Send email with instructions for resetting the password.
                   $mail = new email();
@@ -191,6 +198,7 @@ if (!count($errors)) {
                     $pagetype = 'resetmail_sent';
                   }
                   else {
                     $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.');
                   }
                 }
                     $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 +216,7 @@ if (!count($errors)) {
           $result->execute(array(':userid' => $session['user']));
           $user = $result->fetch(PDO::FETCH_ASSOC);
           if (!$user['id']) {
           $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';
         }
           }
           $pagetype = 'resetpwd';
         }
@@ -224,7 +232,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']))) {
         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';
             $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';
@@ -253,11 +261,11 @@ if (!count($errors)) {
                 $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']))) {
                 $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']))) {
                 }
                 $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;
                 }
                 $pagetype = 'resetpwd';
                 $reset_fail = false;
@@ -274,7 +282,7 @@ if (!count($errors)) {
         $result->execute(array(':userid' => $session['user']));
         $user = $result->fetch(PDO::FETCH_ASSOC);
         if (!$user['id']) {
         $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)) {
         }
         // Password reset requested.
         if (array_key_exists('pwd', $_POST) && array_key_exists('reset', $_POST) && array_key_exists('tcode', $_POST)) {
@@ -295,7 +303,7 @@ if (!count($errors)) {
             $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']))) {
             $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 {
               $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
             }
             else {
@@ -320,7 +328,7 @@ if (!count($errors)) {
       $session = $row;
     }
     else {
       $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.');
     }
   }
       $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.');
     }
   }