diff --git a/README.md b/README.md index 09e87fc..901c2bc 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Aauth is a User Authorization Library for CodeIgniter 2.x, which aims to make ea * Login DDoS Protection * Updated functions (check documentation for details) * Bugs fixes +* TOTP (Time-based One-time Password) ### Migration *** diff --git a/application/config/aauth.php b/application/config/aauth.php index 4e6cb40..285cc2d 100644 --- a/application/config/aauth.php +++ b/application/config/aauth.php @@ -11,7 +11,7 @@ // if user don't have permisssion to see the page he will be // redirected the page spesificed below -$config['aauth']['no_permission'] = '/'; +$config['aauth']['no_permission'] = FALSE; //name of admin group $config['aauth']['admin_group'] = 'admin'; //name of default group, the new user is added in it @@ -48,7 +48,7 @@ $config['aauth']['max'] = 13; $config['aauth']['min'] = 5; // non alphanumeric characters that are allowed in a name -$config['aauth']['valid_chars'] = array(' ', '\''); +$config['aauth']['valid_chars'] = array(); // ddos protection, //if it is true, the user will be banned temporary when he exceed the login 'try' @@ -59,6 +59,9 @@ $config['aauth']['recaptcha_login_attempts'] = 4; $config['aauth']['recaptcha_siteKey'] = ''; $config['aauth']['recaptcha_secret'] = ''; +$config['aauth']['totp_active'] = false; +$config['aauth']['totp_only_on_ip_change'] = false; +$config['aauth']['totp_reset_over_reset_password'] = false; // login attempts time interval // default 20 times in one hour $config['aauth']['max_login_attempt'] = 10; @@ -67,6 +70,7 @@ $config['aauth']['max_login_attempt'] = 10; $config['aauth']['verification'] = false; $config['aauth']['login_with_name'] = false; +$config['aauth']['use_cookies'] = false; // system email. $config['aauth']['email'] = 'admin@admin.com'; diff --git a/application/helpers/googleauthenticator_helper.php b/application/helpers/googleauthenticator_helper.php new file mode 100644 index 0000000..7424d0b --- /dev/null +++ b/application/helpers/googleauthenticator_helper.php @@ -0,0 +1,208 @@ +_getBase32LookupTable(); + unset($validChars[32]); + + $secret = ''; + for ($i = 0; $i < $secretLength; $i++) { + $secret .= $validChars[array_rand($validChars)]; + } + return $secret; + } + + /** + * Calculate the code, with given secret and point in time + * + * @param string $secret + * @param int|null $timeSlice + * @return string + */ + public function getCode($secret, $timeSlice = null) + { + if ($timeSlice === null) { + $timeSlice = floor(time() / 30); + } + + $secretkey = $this->_base32Decode($secret); + + // Pack time into binary string + $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice); + // Hash it with users secret key + $hm = hash_hmac('SHA1', $time, $secretkey, true); + // Use last nipple of result as index/offset + $offset = ord(substr($hm, -1)) & 0x0F; + // grab 4 bytes of the result + $hashpart = substr($hm, $offset, 4); + + // Unpak binary value + $value = unpack('N', $hashpart); + $value = $value[1]; + // Only 32 bits + $value = $value & 0x7FFFFFFF; + + $modulo = pow(10, $this->_codeLength); + return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT); + } + + /** + * Get QR-Code URL for image, from google charts + * + * @param string $name + * @param string $secret + * @param string $title + * @return string + */ + public function getQRCodeGoogleUrl($name, $secret, $title = null) { + $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.''); + if(isset($title)) { + $urlencoded .= urlencode('&issuer='.urlencode($title)); + } + return 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl='.$urlencoded.''; + } + + /** + * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now + * + * @param string $secret + * @param string $code + * @param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after) + * @param int|null $currentTimeSlice time slice if we want use other that time() + * @return bool + */ + public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null) + { + if ($currentTimeSlice === null) { + $currentTimeSlice = floor(time() / 30); + } + + for ($i = -$discrepancy; $i <= $discrepancy; $i++) { + $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i); + if ($calculatedCode == $code ) { + return true; + } + } + + return false; + } + + /** + * Set the code length, should be >=6 + * + * @param int $length + * @return PHPGangsta_GoogleAuthenticator + */ + public function setCodeLength($length) + { + $this->_codeLength = $length; + return $this; + } + + /** + * Helper class to decode base32 + * + * @param $secret + * @return bool|string + */ + protected function _base32Decode($secret) + { + if (empty($secret)) return ''; + + $base32chars = $this->_getBase32LookupTable(); + $base32charsFlipped = array_flip($base32chars); + + $paddingCharCount = substr_count($secret, $base32chars[32]); + $allowedValues = array(6, 4, 3, 1, 0); + if (!in_array($paddingCharCount, $allowedValues)) return false; + for ($i = 0; $i < 4; $i++){ + if ($paddingCharCount == $allowedValues[$i] && + substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) return false; + } + $secret = str_replace('=','', $secret); + $secret = str_split($secret); + $binaryString = ""; + for ($i = 0; $i < count($secret); $i = $i+8) { + $x = ""; + if (!in_array($secret[$i], $base32chars)) return false; + for ($j = 0; $j < 8; $j++) { + $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); + } + $eightBits = str_split($x, 8); + for ($z = 0; $z < count($eightBits); $z++) { + $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:""; + } + } + return $binaryString; + } + + /** + * Helper class to encode base32 + * + * @param string $secret + * @param bool $padding + * @return string + */ + protected function _base32Encode($secret, $padding = true) + { + if (empty($secret)) return ''; + + $base32chars = $this->_getBase32LookupTable(); + + $secret = str_split($secret); + $binaryString = ""; + for ($i = 0; $i < count($secret); $i++) { + $binaryString .= str_pad(base_convert(ord($secret[$i]), 10, 2), 8, '0', STR_PAD_LEFT); + } + $fiveBitBinaryArray = str_split($binaryString, 5); + $base32 = ""; + $i = 0; + while ($i < count($fiveBitBinaryArray)) { + $base32 .= $base32chars[base_convert(str_pad($fiveBitBinaryArray[$i], 5, '0'), 2, 10)]; + $i++; + } + if ($padding && ($x = strlen($binaryString) % 40) != 0) { + if ($x == 8) $base32 .= str_repeat($base32chars[32], 6); + elseif ($x == 16) $base32 .= str_repeat($base32chars[32], 4); + elseif ($x == 24) $base32 .= str_repeat($base32chars[32], 3); + elseif ($x == 32) $base32 .= $base32chars[32]; + } + return $base32; + } + + /** + * Get array with all 32 characters for decoding from/encoding to base32 + * + * @return array + */ + protected function _getBase32LookupTable() + { + return array( + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 7 + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15 + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23 + 'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31 + '=' // padding char + ); + } +} diff --git a/application/language/english/aauth_lang.php b/application/language/english/aauth_lang.php index b6b3f3a..c6b7bbb 100644 --- a/application/language/english/aauth_lang.php +++ b/application/language/english/aauth_lang.php @@ -25,6 +25,9 @@ $lang['aauth_error_email_invalid'] = 'Invalid e-mail address'; $lang['aauth_error_password_invalid'] = 'Invalid password'; $lang['aauth_error_username_invalid'] = 'Invalid Username'; $lang['aauth_error_username_required'] = 'Username required'; +$lang['aauth_error_totp_code_required'] = 'TOTP Code required'; +$lang['aauth_error_totp_code_invalid'] = 'Invalid TOTP Code'; + // Account update errors $lang['aauth_error_update_email_exists'] = 'Email address already exists on the system. Please enter a different email address.'; @@ -38,7 +41,6 @@ $lang['aauth_error_login_failed_name'] = 'Username and Password do not match.'; $lang['aauth_error_login_attempts_exceeded'] = 'You have exceeded your login attempts, your account has now been locked.'; $lang['aauth_error_recaptcha_not_correct'] = 'Sorry, the reCAPTCHA text entered was incorrect.'; - // Misc. errors $lang['aauth_error_no_user'] = 'User does not exist'; $lang['aauth_error_account_not_verified'] = 'Your account has not been verified. Please check your e-mail and verify your account.'; diff --git a/application/libraries/Aauth.php b/application/libraries/Aauth.php index 84f3fac..c893deb 100644 --- a/application/libraries/Aauth.php +++ b/application/libraries/Aauth.php @@ -22,7 +22,6 @@ * https://github.com/emreakay/CodeIgniter-Aauth * * @todo separate (on some level) the unvalidated users from the "banned" users - * @todo add configuration to not use cookies if sessions are enabled. */ class Aauth { @@ -102,6 +101,7 @@ class Aauth { $this->CI->load->helper('email'); $this->CI->load->helper('language'); $this->CI->load->helper('recaptchalib'); + $this->CI->load->helper('googleauthenticator_helper'); $this->CI->lang->load('aauth'); // config/aauth.php @@ -129,17 +129,19 @@ class Aauth { * @param bool $remember * @return bool Indicates successful login. */ - public function login($identifier, $pass, $remember = FALSE) { + public function login($identifier, $pass, $remember = FALSE, $totp_code = NULL) { - // Remove cookies first - $cookie = array( - 'name' => 'user', - 'value' => '', - 'expire' => time()-3600, - 'path' => '/', - ); + if($this->config_vars['use_cookies'] == TRUE){ + // Remove cookies first + $cookie = array( + 'name' => 'user', + 'value' => '', + 'expire' => time()-3600, + 'path' => '/', + ); + $this->CI->input->set_cookie($cookie); + } - $this->CI->input->set_cookie($cookie); if( $this->config_vars['login_with_name'] == TRUE){ @@ -184,13 +186,17 @@ class Aauth { $query = $this->aauth_db->get($this->config_vars['users']); $row = $query->row(); if($query->num_rows() > 0 && $this->config_vars['ddos_protection'] && $this->config_vars['recaptcha_active'] && $row->login_attempts >= $this->config_vars['recaptcha_login_attempts']){ - $reCAPTCHA_cookie = array( - 'name' => 'reCAPTCHA', - 'value' => 'true', - 'expire' => time()+7200, - 'path' => '/', - ); - $this->CI->input->set_cookie($reCAPTCHA_cookie); + if($this->config_vars['use_cookies'] == TRUE){ + $reCAPTCHA_cookie = array( + 'name' => 'reCAPTCHA', + 'value' => 'true', + 'expire' => time()+7200, + 'path' => '/', + ); + $this->CI->input->set_cookie($reCAPTCHA_cookie); + }else{ + $this->CI->session->set_tempdata('reCAPTCHA', 'true', 7200); + } } // if user is not verified @@ -215,7 +221,63 @@ class Aauth { } $user_id = $query->row()->id; - + + if( ($this->config_vars['use_cookies'] == TRUE && $this->CI->input->cookie('reCAPTCHA', TRUE) == 'true') || ($this->config_vars['use_cookies'] == FALSE && $this->CI->session->tempdata('reCAPTCHA') == 'true') ){ + $reCaptcha = new ReCaptcha( $this->config_vars['recaptcha_secret']); + $resp = $reCaptcha->verifyResponse( $this->CI->input->server("REMOTE_ADDR"), $this->CI->input->post("g-recaptcha-response") ); + + if(!$resp->success){ + $this->error($this->CI->lang->line('aauth_error_recaptcha_not_correct')); + return FALSE; + } + } + + if($this->config_vars['totp_active'] == TRUE AND $this->config_vars['totp_only_on_ip_change'] == FALSE){ + $query = null; + $query = $this->aauth_db->where($db_identifier, $identifier); + $query = $this->aauth_db->get($this->config_vars['users']); + $totp_secret = $query->row()->totp_secret; + if ($query->num_rows() > 0 AND !$totp_code) { + $this->error($this->CI->lang->line('aauth_error_totp_code_required')); + return FALSE; + }else { + if(!empty($totp_secret)){ + $ga = new PHPGangsta_GoogleAuthenticator(); + $checkResult = $ga->verifyCode($totp_secret, $totp_code, 0); + if (!$checkResult) { + $this->error($this->CI->lang->line('aauth_error_totp_code_invalid')); + return FALSE; + } + } + } + } + + if($this->config_vars['totp_active'] == TRUE AND $this->config_vars['totp_only_on_ip_change'] == TRUE){ + $query = null; + $query = $this->aauth_db->where($db_identifier, $identifier); + $query = $this->aauth_db->get($this->config_vars['users']); + $totp_secret = $query->row()->totp_secret; + $ip_address = $query->row()->ip_address; + $current_ip_address = $this->CI->input->ip_address(); + if ($query->num_rows() > 0 AND !$totp_code) { + if($ip_address != $current_ip_address ){ + $this->error($this->CI->lang->line('aauth_error_totp_code_required')); + return FALSE; + } + }else { + if(!empty($totp_secret)){ + if($ip_address != $current_ip_address ){ + $ga = new PHPGangsta_GoogleAuthenticator(); + $checkResult = $ga->verifyCode($totp_secret, $totp_code, 0); + if (!$checkResult) { + $this->error($this->CI->lang->line('aauth_error_totp_code_invalid')); + return FALSE; + } + } + } + } + } + $query = null; $query = $this->aauth_db->where($db_identifier, $identifier); @@ -226,18 +288,9 @@ class Aauth { $query = $this->aauth_db->get($this->config_vars['users']); $row = $query->row(); - if($this->CI->input->cookie('reCAPTCHA', TRUE) == 'true'){ - $reCaptcha = new ReCaptcha( $this->config_vars['recaptcha_secret']); - $resp = $reCaptcha->verifyResponse( $this->CI->input->server("REMOTE_ADDR"), $this->CI->input->post("g-recaptcha-response") ); - if(!$resp->success){ - $this->error($this->CI->lang->line('aauth_error_recaptcha_not_correct')); - return FALSE; - } - } - // if email and pass matches and not banned - if ( $query->num_rows() > 0 ) { + if ( $query->num_rows() != 0 ) { // If email and pass matches // create session @@ -258,24 +311,32 @@ class Aauth { $random_string = random_string('alnum', 16); $this->update_remember($row->id, $random_string, $remember_date ); - $cookie = array( - 'name' => 'user', - 'value' => $row->id . "-" . $random_string, - 'expire' => time() + 99*999*999, - 'path' => '/', - ); - - $this->CI->input->set_cookie($cookie); + if($this->config_vars['use_cookies'] == TRUE){ + $cookie = array( + 'name' => 'user', + 'value' => $row->id . "-" . $random_string, + 'expire' => time() + 99*999*999, + 'path' => '/', + ); + + $this->CI->input->set_cookie($cookie); + }else{ + $this->CI->session->set_userdata('remember', $row->id . "-" . $random_string); + } } if($this->config_vars['recaptcha_active']){ - $reCAPTCHA_cookie = array( - 'name' => 'reCAPTCHA', - 'value' => 'false', - 'expire' => time()-3600, - 'path' => '/', - ); - $this->CI->input->set_cookie($reCAPTCHA_cookie); + if($this->config_vars['use_cookies'] == TRUE){ + $reCAPTCHA_cookie = array( + 'name' => 'reCAPTCHA', + 'value' => 'false', + 'expire' => time()-3600, + 'path' => '/', + ); + $this->CI->input->set_cookie($reCAPTCHA_cookie); + }else{ + $this->CI->session->unset_tempdata('reCAPTCHA'); + } } // update last login @@ -306,37 +367,67 @@ class Aauth { // cookie control else { - if( ! $this->CI->input->cookie('user', TRUE) ){ - return FALSE; - } else { - $cookie = explode('-', $this->CI->input->cookie('user', TRUE)); - if(!is_numeric( $cookie[0] ) OR strlen($cookie[1]) < 13 ){return FALSE;} - else{ - $query = $this->aauth_db->where('id', $cookie[0]); - $query = $this->aauth_db->where('remember_exp', $cookie[1]); - $query = $this->aauth_db->get($this->config_vars['users']); - - $row = $query->row(); - - if ($query->num_rows() < 1) { - $this->update_remember($cookie[0]); - return FALSE; - }else{ - - if(strtotime($row->remember_time) > strtotime("now") ){ - $this->login_fast($cookie[0]); - return TRUE; + if($this->config_vars['use_cookies'] == TRUE){ + if( ! $this->CI->input->cookie('user', TRUE) ){ + return FALSE; + } else { + $cookie = explode('-', $this->CI->input->cookie('user', TRUE)); + if(!is_numeric( $cookie[0] ) OR strlen($cookie[1]) < 13 ){return FALSE;} + else{ + $query = $this->aauth_db->where('id', $cookie[0]); + $query = $this->aauth_db->where('remember_exp', $cookie[1]); + $query = $this->aauth_db->get($this->config_vars['users']); + + $row = $query->row(); + + if ($query->num_rows() < 1) { + $this->update_remember($cookie[0]); + return FALSE; + }else{ + + if(strtotime($row->remember_time) > strtotime("now") ){ + $this->login_fast($cookie[0]); + return TRUE; + } + // if time is expired + else { + return FALSE; + } } - // if time is expired - else { + } + } + }else{ + if(!$this->CI->session->has_userdata('remember')){ + return FALSE; + }else{ + $session = explode('-', $this->CI->session->userdata('remember')); + if(!is_numeric( $session[0] ) OR strlen($session[1]) < 13 ){return FALSE;} + else{ + $query = $this->aauth_db->where('id', $session[0]); + $query = $this->aauth_db->where('remember_exp', $session[1]); + $query = $this->aauth_db->get($this->config_vars['users']); + + $row = $query->row(); + + if ($query->num_rows() < 1) { + $this->update_remember($session[0]); return FALSE; + }else{ + + if(strtotime($row->remember_time) > strtotime("now") ){ + $this->login_fast($session[0]); + return TRUE; + } + // if time is expired + else { + return FALSE; + } } } } } } - return FALSE; } @@ -376,15 +467,16 @@ class Aauth { */ public function logout() { - $cookie = array( - 'name' => 'user', - 'value' => '', - 'expire' => time()-3600, - 'path' => '/', - ); - - $this->CI->input->set_cookie($cookie); - + if($this->config_vars['use_cookies'] == TRUE){ + $cookie = array( + 'name' => 'user', + 'value' => '', + 'expire' => time()-3600, + 'path' => '/', + ); + $this->CI->input->set_cookie($cookie); + } + return $this->CI->session->sess_destroy(); } @@ -487,6 +579,10 @@ class Aauth { 'pass' => $this->hash_password($pass, $user_id) ); + if($this->config_vars['totp_active'] == TRUE AND $this->config_vars['totp_reset_over_reset_password'] == TRUE){ + $data['totp_secret'] = NULL; + } + $row = $query->row(); $email = $row->email; @@ -859,12 +955,10 @@ class Aauth { * Delete user * Delete a user from database. WARNING Can't be undone * @param int $user_id User id to delete + * @return bool Delete fails/succeeds */ public function delete_user($user_id) { - $this->aauth_db->where('id', $user_id); - $this->aauth_db->delete($this->config_vars['users']); - // delete from perm_to_user $this->aauth_db->where('user_id', $user_id); $this->aauth_db->delete($this->config_vars['perm_to_user']); @@ -876,6 +970,11 @@ class Aauth { // delete user vars $this->aauth_db->where('user_id', $user_id); $this->aauth_db->delete($this->config_vars['user_variables']); + + // delete user + $this->aauth_db->where('id', $user_id); + return $this->aauth_db->delete($this->config_vars['users']); + } //tested @@ -1553,7 +1652,7 @@ class Aauth { $query = $this->aauth_db->get($this->config_vars['perms']); if ($query->num_rows() == 0) - return NULL; + return FALSE; $row = $query->row(); return $row->id; @@ -1656,11 +1755,12 @@ class Aauth { if ($query->num_rows() < 1) { $this->error( $this->CI->lang->line('aauth_error_no_pm') ); + return FALSE; } if ($set_as_read) $this->set_as_read_pm($pm_id); - return $query->result(); + return $query->row(); } //tested @@ -2138,14 +2238,46 @@ class Aauth { public function generate_recaptcha_field(){ $content = ''; - if($this->config_vars['ddos_protection'] && $this->config_vars['recaptcha_active'] && $this->CI->input->cookie('reCAPTCHA', TRUE) == 'true'){ - $content .= ""; - $siteKey = $this->config_vars['recaptcha_siteKey']; - $content .= "
"; + if($this->config_vars['ddos_protection'] && $this->config_vars['recaptcha_active']){ + if( ($this->config_vars['use_cookies'] == TRUE && $this->CI->input->cookie('reCAPTCHA', TRUE) == 'true') || ($this->config_vars['use_cookies'] == FALSE && $this->CI->session->tempdata('reCAPTCHA') == 'true') ){ + $content .= ""; + $siteKey = $this->config_vars['recaptcha_siteKey']; + $content .= ""; + } } return $content; } + public function update_user_totp_secret($user_id = FALSE, $secret) { + + if ($user_id == FALSE) + $user_id = $this->CI->session->userdata('id'); + + $data['totp_secret'] = $secret; + + $this->aauth_db->where('id', $user_id); + return $this->aauth_db->update($this->config_vars['users'], $data); + } + + public function generate_unique_totp_secret(){ + $ga = new PHPGangsta_GoogleAuthenticator(); + $stop = false; + while (!$stop) { + $secret = $ga->createSecret(); + $query = $this->aauth_db->where('totp_secret', $secret); + $query = $this->aauth_db->get($this->config_vars['users']); + if ($query->num_rows() == 0) { + return $secret; + $stop = true; + } + } + } + + public function generate_totp_qrcode($secret){ + $ga = new PHPGangsta_GoogleAuthenticator(); + return $ga->getQRCodeGoogleUrl($this->config_vars['name'], $secret); + } + } // end class // $this->CI->session->userdata('id') diff --git a/sql/Aauth_v2.sql b/sql/Aauth_v2.sql index 008d6ad..86f9520 100644 --- a/sql/Aauth_v2.sql +++ b/sql/Aauth_v2.sql @@ -117,6 +117,7 @@ CREATE TABLE `aauth_users` ( `remember_time` datetime DEFAULT NULL, `remember_exp` text COLLATE utf8_general_ci, `verification_code` text COLLATE utf8_general_ci, + `totp_secret` varchar(16) COLLATE utf8_general_ci DEFAULT NULL, `ip_address` text COLLATE utf8_general_ci, `login_attempts` int(11) DEFAULT '0', PRIMARY KEY (`id`)