verifyCode() public method

Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
public verifyCode ( string $secret, string $code, integer $discrepancy = 1, integer | null $currentTimeSlice = null ) : boolean
$secret string
$code string
$discrepancy integer This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
$currentTimeSlice integer | null time slice if we want use other that time()
return boolean
Example #1
3
 /**
  * Melde den spezifizierte User mit dem angegebenen Benutername / Passwort an
  * @param string $username
  * @param string $password
  * @param string $googleAuthCode
  */
 public function loginPerson(string $username, string $password, string $googleAuthCode)
 {
     $user = $this->model->load($username);
     $passwordCorrect = password_verify($password, $user['password']);
     if ($passwordCorrect) {
         $secret = $user['secret'];
         //If Secret is set
         if ($secret) {
             $authenticator = new PHPGangsta_GoogleAuthenticator();
             $result = $authenticator->verifyCode($user['secret'], $googleAuthCode, 2);
             // 2 = 2*30sec clock tolerance
             //Entered Code correct
             if ($result) {
                 $this->saveUser($user);
                 return;
             }
             //Code wrong
             $this->loginError();
             return;
         }
         $this->saveUser($user);
         return;
     }
     //Password wrong
     $this->loginError();
 }
 public function updateSettings(string $newUsername, string $newName, string $newSurname, string $newMail, string $newPassword, string $newRepPassword, string $secret, string $authenticatorCode)
 {
     $valuesValid = Register::inputValid($newUsername, $newPassword, $newRepPassword, $newSurname, $newName, $newMail);
     //Password can be empty or must be valid
     $allValid = $valuesValid[0] && ($newPassword == "" || $valuesValid[1]) && $valuesValid[2] && $valuesValid[3] && $valuesValid[4];
     //Authenticator
     $authenticator = new PHPGangsta_GoogleAuthenticator();
     $codeCorrect = $authenticator->verifyCode($secret, $authenticatorCode);
     if ($allValid) {
         $this->model->update($newUsername, $newName, $newSurname, $newMail, $allValid[1] ? $newPassword : null, $codeCorrect ? $secret : null);
         //Reload User from Database
         $changedUser = $this->loginModel->load($newUsername);
         $this->session->setCurrentUser($changedUser);
         return;
     }
     http_response_code(500);
 }
Example #3
0
<?php

require_once 'twofactorauth.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$secret = "S7PVGLOXTXFDNT5S";
/*
Wichtige kommandos:
$secret = $ga->createSecret();
*/
$qrCodeUrl = $ga->getQRCodeGoogleUrl('username', $secret, 'Synchro');
echo "<img src='" . $qrCodeUrl . "'></img>";
/*
$checkResult = $ga->verifyCode($secret, $oneCode, 2);
*/
if (!isset($_GET["auth"])) {
    ?>
<form action="test.php?auth" method="post">
<input type="text" name="code">
<input type="submit">
</form>
<?php 
} else {
    $checkResult = $ga->verifyCode($secret, $_POST["code"], 2);
    // 2 = 2*30sec clock tolerance
    if ($checkResult) {
        echo 'OK';
    } else {
        echo 'FAILED';
    }
}
Example #4
0
<?php

require_once '../PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$secret = $ga->createSecret();
echo "Secret is: " . $secret . "\n\n";
$qrCodeUrl = $ga->getQRCodeGoogleUrl('Blog', $secret);
echo "Google Charts URL for the QR-Code: " . $qrCodeUrl . "\n\n";
$oneCode = $ga->getCode($secret);
echo "Checking Code '{$oneCode}' and Secret '{$secret}':\n";
$checkResult = $ga->verifyCode($secret, $oneCode, 2);
// 2 = 2*30sec clock tolerance
if ($checkResult) {
    echo 'OK';
} else {
    echo 'FAILED';
}
 private function __checkCode($code, $secret = null)
 {
     $ga = new PHPGangsta_GoogleAuthenticator();
     return $ga->verifyCode($secret ? $secret : self::__getSecret(), $code, 2);
     // 2 = 2*30sec clock tolerance
 }
Example #6
0
<?php

require_once '../include/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php';
require_once '../include/db_connection.inc';
require 'variables.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$error = 0;
// Passwords match
if ($repeatPassword != $selectedPassword) {
    $error = 1;
}
// Google Authenticator is correct
if (!$ga->verifyCode($googleAuthenticatorSecret, $googleAuthenticatorCode, 2)) {
    $error = 2;
}
// Password is correct
if (!preg_match($passwordRegularExpression, $selectedPassword)) {
    $error = 3;
}
// Username is correct
if (strlen($selectedUsername) >= 40 || strlen($selectedUsername) <= 1) {
    $error = 4;
}
// No Errors
if ($error == 0) {
    $db = $_SESSION['DBConnection'];
    $options = ['cost' => 11, 'salt' => $googleAuthenticatorSecret . 'i<34u2'];
    $hashedPassword = password_hash($selectedPassword, PASSWORD_BCRYPT, $options);
    $query = "INSERT INTO user(username, firstname, lastname, password, secret) VALUES(?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($db, $query);
    $stmt->bind_param('sssss', $selectedUsername, $selectedFirstName, $selectedLastName, $hashedPassword, $googleAuthenticatorSecret);
Example #7
0
<?php

require_once './PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
echo $ga->createSecret(16);
exit;
$secret = 'QEOODZHBTPE6ZJI7';
echo "Secret is: " . $secret . "\n\n";
$qrCodeUrl = $ga->getQRCodeGoogleUrl('trungphc', $secret, urlencode('Mecorp - Inside'));
echo "Google Charts URL for the QR-Code: " . $qrCodeUrl . "\n\n";
$oneCode = $ga->getCode($secret);
echo "Checking Code '{$oneCode}' and Secret '{$secret}':\n";
$checkResult = $ga->verifyCode($secret, '178922', 0);
// 2 = 2*30sec clock tolerance
if ($checkResult) {
    echo 'OK';
} else {
    echo 'FAILED';
}
$checkResult = $ga->verifyCode($secret, $oneCode, 0);
// 2 = 2*30sec clock tolerance
if ($checkResult) {
    echo 'OK';
} else {
    echo 'FAILED';
}
Example #8
0
$cgi_u_name = $row_user[name];
$cgi_u_type = $row_user[type];
$cgi_u_priv = $row_user[priv];
$cgi_u_allproj = $row_user[allproj];
$db_pwd = $row_user[passwd];
$salt = $row_user[salt];
if (md5($pwd . $salt) != $db_pwd) {
    $sqlstr = "update user set f_times=f_times+1 where login='******'";
    $res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
    sys_exit("用户 {$admin} 密码错误");
}
//  google-authenticator 验证
$ga = new PHPGangsta_GoogleAuthenticator();
$db_secret = $row_user['secret'];
//$one_code = $ga->getCode($db_secret); //服务端计算"一次性验证码"
$checkResult = $ga->verifyCode($db_secret, $g_code, 2);
if (!$checkResult) {
    $sqlstr = "update user set f_times=f_times+1 where login='******'";
    $res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
    sys_exit("用户验证码错误");
}
$ck_u_priv = "";
$sqlstr = "select p_id from user_priv where u_id='{$cgi_u_id}'";
$res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
while ($row = mysql_fetch_array($res)) {
    $ck_u_priv .= ",{$row['p_id']}";
}
$sqlstr = "select p_id from proj where u_id='{$cgi_u_id}'";
$res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
while ($row = mysql_fetch_array($res)) {
    $ck_u_priv .= ",{$row['p_id']}";
#!/usr/local/bin/php
<?php 
require_once 'googleauth.php';
$shortopts = "";
$shortopts .= "c:";
$shortopts .= "p:";
// Required value
$shortopts .= "v::";
$shortopts .= "t::";
// Optional value
$longopts = array("command:", "privatekey:", "title::");
$options = getopt($shortopts, $longopts);
$ga = new PHPGangsta_GoogleAuthenticator();
$options['p'] = $ga->setSecret($options['p']);
switch ($options['c']) {
    case "qr":
        echo $ga->getQRCodeGoogleUrl($options['t'], $options['p']);
        break;
    case "verify":
        if ($ga->verifyCode($options['p'], $options['v'], 1)) {
            echo "true";
            exit(0);
        } else {
            echo "false";
            exit(255);
        }
        break;
    case "qr_text":
        echo $ga->getURI($options['t'], $options['p']);
        break;
}
 /**
  * 	This module authenticates against a time-based code.
  */
 public function processLogin($code, $user = null)
 {
     $ga = new PHPGangsta_GoogleAuthenticator();
     $expiry = $this->_getSharedConfig("generatorexpiry");
     $secret = $this->_settingGet("secret", '', $user);
     return $ga->verifyCode($secret, $code, $expiry);
 }
Example #11
0
    unlink("data/twofactorauth");
    $secret = $ga->createSecret();
    $myfile = fopen("data/twofactorauth", "w") or die("It seems like synchro hasn't enought file permissions to do this.");
    $txt = $secret;
    fwrite($myfile, $txt);
    fclose($myfile);
    write2logfile("Regenerated Two-Factor-Authentication Code", "twofacauth.php");
}
if (!file_exists("data/twofactorauth")) {
    $exists = false;
} else {
    $exists = true;
}
if (isset($_POST['test'])) {
    $secret = file_get_contents("data/twofactorauth");
    $checkResult = $ga->verifyCode($secret, $_POST['test'], 2);
    if ($checkResult) {
        $tested = "<font color='green'>It works!</font><br>";
    } else {
        $tested = "<font color='red'>Thats now right!</font><br>";
    }
    $firsttime = true;
    write2logfile("User just tested Two-Factor-Authentication", "twofacauth.php");
}
$myfile = fopen("data/username.txt", "r");
$username = fgets($myfile);
fclose($myfile);
?>
<!DOCTYPE html>
<html lang="en">
  <head>
Example #12
0
    header('Location: index.php');
}
//
include_once 'config.php';
include_once 'funciones.php';
require_once 'GoogleAuthenticator.php';
$tokenIn = $_POST['token'];
$usuario = $_POST['usuario'];
//Conexion a DB
$conexion = conectarDB($parametrosGlobales['db']);
$resultado = $conexion->query("SELECT token FROM usuario WHERE user='******'");
if ($resultado->num_rows > 0) {
    //extraigo el secreto de la DB para regenerar el Token
    $fila = $resultado->fetch_assoc();
    $secreto = $fila["token"];
    //llamo a función, le paso el secreto y el token ingesado y los comparo
    $ga = new PHPGangsta_GoogleAuthenticator();
    $checkResult = $ga->verifyCode($secreto, $tokenIn, 3);
    // 2 = 2*30sec clock tolerance
    if ($checkResult) {
        //si el token generado al del usuario son idénticos, la variable de sesión "validado" pasa a true y se redirige a la pagina de usuario
        session_start();
        $_SESSION['validado'] = true;
        header('Location: bienvenido.php');
    } else {
        echo 'TOKEN NO VALIDO <br>';
    }
} else {
    echo 'No existe el usuario <br>';
}
echo "<br><br><a href='formToken.php?user={$usuario}'>Intentar Nuevamente </a>";
Example #13
0
     if ($user['username'] == $_POST['username']) {
         $userdetails = $user;
     }
 }
 if (is_array($userdetails) && md5($_POST['password']) == $userdetails['password']) {
     if ($userdetails['2fo'] && !isset($userdetails['2fo'])) {
         header('Location: index.php?login=failed&pwfail');
         die;
     }
     if (isset($userdetails['2fo']) && $userdetails['2fo'] == 'true') {
         if (!isset($_POST['2fokey'])) {
             $_POST['2fokey'] = 0;
         }
         require $config['path'] . '/libs/googleauthenticator/GoogleAuthenticator.php';
         $ga = new PHPGangsta_GoogleAuthenticator();
         if (!$ga->verifyCode($userdetails['2fokey'], $_POST['2fokey'], 2)) {
             header('Location: index.php?login=failed&2fofail');
             die;
         }
     }
     foreach ($acls as $acl) {
         if ($acl['id'] == $user['acl']) {
             $_SESSION['acl'] = $acl['perms'];
         }
     }
     $_SESSION['user'] = $_POST['username'];
     $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
     $_SESSION['time'] = time();
     logevent('User ' . $_SESSION['user'] . ' logged in', 'activity');
     header('Location: index.php');
     die;
Example #14
0
/* 导入头文件 */
require_once 'header.php';
require_once 'Library/GoogleAuthenticator/GoogleAuthenticator.php';
/**
 * 登陆处理
 */
$username = htmlspecialchars($_POST['username']);
$password = $_POST['password'];
// 动态令牌码
// 参数不完整
if (!$username || !$password) {
    $result = array('ret_code' => -1, 'err_msg' => '参数错误');
    ajaxReturn($result);
}
# 验证动态令牌
$ga = new PHPGangsta_GoogleAuthenticator();
$secret = $UserInfo[$username];
// 最后一个参数 为容差时间,这里是2 那么就是 2* 30 sec 一分钟.默认为1
$checkResult = $secret ? $ga->verifyCode($secret, $password, 1) : false;
if ($checkResult) {
    $_SESSION["username"] = $username;
    $result = array('ret_code' => 1, 'suc_msg' => '登陆成功');
    ajaxReturn($result);
    /**
     * @todo  因为没有限制尝试次数,所以后期会发送进行登陆发送通知邮件给管理员和用户.
     */
} else {
    $result = array('ret_code' => -1, 'err_msg' => '用户名或密码错误,请检查后重试');
    ajaxReturn($result);
}
Example #15
0
 // Test whether it's a recovery code
 $recovery = false;
 $codes = my_unserialize($admin_options['recovery_codes']);
 if (!empty($codes) && in_array($mybb->get_input('code'), $codes)) {
     $recovery = true;
     $ncodes = array_diff($codes, array($mybb->input['code']));
     // Removes our current code from the codes array
     $db->update_query("adminoptions", array("recovery_codes" => $db->escape_string(my_serialize($ncodes))), "uid='{$mybb->user['uid']}'");
     if (count($ncodes) == 0) {
         flash_message($lang->my2fa_no_codes, "error");
     }
 }
 // Validate the code
 require_once MYBB_ROOT . "inc/3rdparty/2fa/GoogleAuthenticator.php";
 $auth = new PHPGangsta_GoogleAuthenticator();
 $test = $auth->verifyCode($admin_options['authsecret'], $mybb->get_input('code'));
 // Either the code was okay or it was a recovery code
 if ($test === true || $recovery === true) {
     // Correct code -> session authenticated
     $db->update_query("adminsessions", array("authenticated" => 1), "sid='" . $db->escape_string($mybb->cookies['adminsid']) . "'");
     $admin_session['authenticated'] = 1;
     $db->update_query("adminoptions", array("loginattempts" => 0, "loginlockoutexpiry" => 0), "uid='{$mybb->user['uid']}'");
     my_setcookie('acploginattempts', 0);
     // post would result in an authorization code mismatch error
     $mybb->request_method = "get";
 } else {
     // Wrong code -> close session (aka logout)
     $db->delete_query("adminsessions", "sid='" . $db->escape_string($mybb->cookies['adminsid']) . "'");
     my_unsetcookie('adminsid');
     // Now test whether we need to lock this guy completly
     $db->update_query("adminoptions", array("loginattempts" => "loginattempts+1"), "uid='{$mybb->user['uid']}'", '', true);
Example #16
0
 /**
  * Login user
  * Check provided details against the database. Add items to error array on fail, create session if success
  * @param string $email
  * @param string $pass
  * @param bool $remember
  * @return bool Indicates successful login.
  */
 public function login($identifier, $pass, $remember = FALSE, $totp_code = NULL)
 {
     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);
     }
     if ($this->config_vars['login_with_name'] == TRUE) {
         if (!$identifier or strlen($pass) < $this->config_vars['min'] or strlen($pass) > $this->config_vars['max']) {
             $this->error($this->CI->lang->line('aauth_error_login_failed_name'));
             return FALSE;
         }
         $db_identifier = 'name';
     } else {
         if (!valid_email($identifier) or strlen($pass) < $this->config_vars['min'] or strlen($pass) > $this->config_vars['max']) {
             $this->error($this->CI->lang->line('aauth_error_login_failed_email'));
             return FALSE;
         }
         $db_identifier = 'email';
     }
     /*
      *
      * User Verification
      *
      * Removed or !ctype_alnum($pass) from the IF statement
      * It was causing issues with special characters in passwords
      * and returning FALSE even if the password matches.
      */
     $query = null;
     $query = $this->aauth_db->where($db_identifier, $identifier);
     $query = $this->aauth_db->get($this->config_vars['users']);
     $row = $query->row();
     // only email found and login attempts exceeded
     if ($query->num_rows() > 0 && $this->config_vars['ddos_protection'] && !$this->update_login_attempts($row->email)) {
         $this->error($this->CI->lang->line('aauth_error_login_attempts_exceeded'));
         return FALSE;
     }
     //recaptcha login_attempts check
     $query = null;
     $query = $this->aauth_db->where($db_identifier, $identifier);
     $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']) {
         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
     $query = null;
     $query = $this->aauth_db->where($db_identifier, $identifier);
     $query = $this->aauth_db->where('banned', 1);
     $query = $this->aauth_db->where('verification_code !=', '');
     $query = $this->aauth_db->get($this->config_vars['users']);
     if ($query->num_rows() > 0) {
         $this->error($this->CI->lang->line('aauth_error_account_not_verified'));
         return FALSE;
     }
     // to find user id, create sessions and cookies
     $query = $this->aauth_db->where($db_identifier, $identifier);
     $query = $this->aauth_db->get($this->config_vars['users']);
     if ($query->num_rows() == 0) {
         $this->error($this->CI->lang->line('aauth_error_login_failed'));
         return FALSE;
     }
     $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);
     // Database stores pasword hashed password
     $query = $this->aauth_db->where('pass', $this->hash_password($pass, $user_id, $type = 'login'));
     $query = $this->aauth_db->where('banned', 0);
     $query = $this->aauth_db->get($this->config_vars['users']);
     $row = $query->row();
     // if email and pass matches and not banned
     if ($query->num_rows() != 0) {
         // If email and pass matches
         // create session
         $data = array('id' => $row->id, 'fullname' => $row->fullname, 'name' => $row->name, 'email' => $row->email, 'phone' => $row->phone, 'loggedin' => TRUE);
         $this->CI->session->set_userdata($data);
         // if remember selected
         if ($remember) {
             $expire = $this->config_vars['remember'];
             $today = date("Y-m-d");
             $remember_date = date("Y-m-d", strtotime($today . $expire));
             $random_string = random_string('alnum', 16);
             $this->update_remember($row->id, $random_string, $remember_date);
             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']) {
             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
         $this->update_last_login($row->id);
         $this->update_activity();
         $this->reset_login_attempts($row->id);
         return TRUE;
     } else {
         $this->error($this->CI->lang->line('aauth_error_login_failed'));
         return FALSE;
     }
 }
Example #17
0
 /**
  * User-Login
  *
  * @param $strUsername
  * @param $strPassword
  * @param $boolUseHash Use Hash for comparing
  * @return bool/array	
  */
 public function login($strUsername, $strPassword, $boolUseHash = false)
 {
     $user = unserialize(register('encrypt')->decrypt($this->in->get('twofactor_data')));
     $code = $this->in->get('twofactor_code');
     $blnLoginResult = false;
     if ($user == "" || $code == "") {
         return false;
     }
     if ($user && $user != ANONYMOUS) {
         $arrAuthAccounts = $this->pdh->get('user', 'auth_account', array($user));
         if ($arrAuthAccounts['twofactor'] != "") {
             $data = unserialize(register('encrypt')->decrypt($arrAuthAccounts['twofactor']));
             if ($data) {
                 if ($code === $data['emergency_token']) {
                     $this->pdh->put('user', 'delete_authaccount', array($user, "twofactor"));
                     $userdata = $this->pdh->get('user', 'data', array($user));
                     if ($userdata) {
                         list($strPwdHash, $strSalt) = explode(':', $userdata['user_password']);
                         if ($this->in->get('twofactor_cookie', 0)) {
                             set_cookie("twofactor", register('encrypt')->encrypt(serialize(array('secret' => $data['secret'], 'user_id' => $userdata['user_id']))), time() + 60 * 60 * 24 * 30);
                         }
                         return array('status' => 1, 'user_id' => $userdata['user_id'], 'password_hash' => $strPwdHash, 'autologin' => true, 'user_login_key' => $userdata['user_login_key']);
                     }
                 }
                 //Check Code
                 if (!$blnLoginResult) {
                     include_once $this->root_path . 'libraries/twofactor/googleAuthenticator.class.php';
                     $ga = new PHPGangsta_GoogleAuthenticator();
                     $checkResult = $ga->verifyCode($data['secret'], $code, 5);
                     // 2 = 2*30sec clock tolerance
                     if ($checkResult) {
                         $blnLoginResult = true;
                         $userdata = $this->pdh->get('user', 'data', array($user));
                         if ($userdata) {
                             list($strPwdHash, $strSalt) = explode(':', $userdata['user_password']);
                             if ($this->in->get('twofactor_cookie', 0)) {
                                 set_cookie("twofactor", register('encrypt')->encrypt(serialize(array('secret' => $data['secret'], 'user_id' => $userdata['user_id']))), time() + 60 * 60 * 24 * 30);
                             }
                             return array('status' => 1, 'user_id' => $userdata['user_id'], 'password_hash' => $strPwdHash, 'autologin' => true, 'user_login_key' => $userdata['user_login_key']);
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
Example #18
0
 }
 if ($settings['2factor']) {
     if ($_SESSION['2factor'] == 0) {
         if ($settings['force2factor'] == 'steam') {
             if (!$_SESSION['steamsignon']) {
                 $_SESSION['2factor'] == 5;
             }
         } elseif ($settings['force2factor'] == 'all') {
             $_SESSION['2factor'] == 5;
         }
         $page = 'views/core/2factor.php';
     } elseif ($_SESSION['2factor'] == 1 || $_SESSION['2factor'] == 3) {
         if (isset($_POST['code'])) {
             $sql = "SELECT `twoFactor` FROM `users` WHERE `user_id` = '" . $_SESSION['user_id'] . "';";
             $user = $db_connection->query($sql)->fetch_object();
             if ($gauth->verifyCode($user->twoFactor, $_POST['code'])) {
                 $_SESSION['2factor'] = 2;
             } else {
                 $sql = "SELECT `backup` FROM `users` WHERE `user_id` = '" . $_SESSION['user_id'] . "';";
                 $user = $db_connection->query($sql)->fetch_object();
                 if ($user->backup == $_POST['code']) {
                     $_SESSION['2factor'] = 2;
                 } else {
                     $_SESSION['2factor'] = 3;
                     $page = 'views/core/2factor.php';
                 }
             }
         } else {
             $page = 'views/core/2factor.php';
         }
     }
Example #19
0
<?php

require_once '../include/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php';
require_once '../include/db_connection.inc';
require 'variables.php';
$query = 'SELECT * FROM user WHERE username = ? LIMIT 1';
$stmt = mysqli_prepare($db, $query);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$user = mysqli_fetch_array($result);
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($user['secret'], $googleAuthenticatorCode, 2);
// 2 = 2*30sec clock tolerance
$passwordCorrect = password_verify($password, $user['password']);
if ($checkResult && $passwordCorrect) {
    $_SESSION['CurrentUser'] = $user;
    header('Location: ../index.php?action=welcome');
} else {
    $error = 132;
    header('Location: ../index.php?action=welcome&error=' . $error);
}
 /**
  * @param string $sSecret
  * @param string $sCode
  * 
  * @return bool
  */
 public function VerifyCode($sSecret, $sCode)
 {
     include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHPGangsta/GoogleAuthenticator.php';
     $oGoogleAuthenticator = new \PHPGangsta_GoogleAuthenticator();
     return $oGoogleAuthenticator->verifyCode($sSecret, $sCode);
 }
Example #21
0
 /**
  * @param $oServer
  * @return mixed
  */
 public function AjaxVerifyUserToken($oServer)
 {
     $sEmail = trim(stripcslashes($oServer->getParamValue('Email', null)));
     $sCode = intval(trim(stripcslashes($oServer->getParamValue('Code', null))));
     $bSignMe = $oServer->getParamValue('SignMe') === 'true' ? true : false;
     try {
         $oApiUsers = \CApi::Manager('users');
         $oAccount = $oApiUsers->getAccountByEmail($sEmail);
         $sDataValue = $this->getCode($oAccount);
         $oGoogle = new PHPGangsta_GoogleAuthenticator();
         $oStatus = $oGoogle->verifyCode($sDataValue, $sCode, $this->discrepancy);
         if ($oStatus) {
             $this->_writeLogs($sDataValue . ' is valid');
             $oApiIntegratorManager = \CApi::Manager('integrator');
             $oApiIntegratorManager->SetAccountAsLoggedIn($oAccount, $bSignMe);
             $aResult['Result'] = true;
         } else {
             $this->_writeLogs($sDataValue . ' is not valid');
             $aResult['Result'] = false;
             $aResult['ErrorMessage'] = $this->I18N('AUTHENTICATION_PLUGIN/WRONG_CODE');
         }
     } catch (Exception $oEx) {
         $aResult['Result'] = false;
         $aResult['ErrorMessage'] = $oEx->getMessage();
     }
     return $aResult;
 }
Example #22
0
function oath_output($vars)
{
    if ($_GET['qr']) {
        require_once './../modules/addons/oath/phpqrcode/qrlib.php';
        $company = get_query_val('tblconfiguration', 'value', "setting = 'CompanyName'");
        QRcode::png('otpauth://totp/' . urlencode(str_replace(' ', '', $company)) . 'Admin?secret=' . $_GET['secret']);
        exit(0);
    }
    echo '<div style="text-align: center;">';
    $secret = get_query_val('mod_oath_admin', 'secret', "adminid = '{$_SESSION['adminid']}'");
    require_once './../modules/addons/oath/GoogleAuthenticator.php';
    $gauth = new PHPGangsta_GoogleAuthenticator();
    if ($vars['enable_admins'] == 'No') {
        echo 'Two-factor authentication is currently disabled for administrators.';
    } elseif (!$secret && $_POST['enable']) {
        if ($_POST['secret']) {
            if ($gauth->verifyCode($_POST['secret'], $_POST['code'], $vars['discrepancy'])) {
                insert_query('mod_oath_admin', array('adminid' => $_SESSION['adminid'], 'secret' => $_POST['secret']));
                $_SESSION['twofactoradmin'] = $_SESSION['adminid'];
                header('Location: ' . $vars['modulelink']);
                exit(0);
            } else {
                echo '<p><b>Your code was incorrect.</b></p>';
                $secret = $_POST['secret'];
            }
        } else {
            $secret = $gauth->createSecret();
        }
        echo '<p>Please scan this QR code with your mobile authenticator app.</p>';
        echo '<img src="' . $vars['modulelink'] . '&qr=1&secret=' . $secret . '" />';
        echo '<p>If you are unable to scan, use this secret:<br />' . $secret . '</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '">';
        echo '<input type="hidden" name="secret" value="' . $secret . '" />';
        echo '<input type="text" name="code" placeholder="Enter your code" autocomplete="off" /><br /><br />';
        echo '<input type="submit" name="enable" value="Verify Code" class="btn btn-primary" />';
        echo '</form>';
    } elseif (!$secret && $vars['enable_admins'] == 'Required') {
        echo '<b>You must enable two-factor authentication to proceed.</b><br /><br />';
        echo '<form method="post" action="' . $vars['modulelink'] . '"><input type="submit" name="enable" value="Enable Two-Factor Authentication" class="btn btn-primary" /></form>';
    } elseif ($secret && $_SESSION['twofactoradmin'] != $_SESSION['adminid']) {
        if ($_POST['code']) {
            if ($gauth->verifyCode($secret, $_POST['code'], $vars['discrepancy'])) {
                $_SESSION['twofactoradmin'] = $_SESSION['adminid'];
                $redirectURI = !empty($_SESSION['original_request_uri']) ? htmlspecialchars_decode($_SESSION['original_request_uri']) : 'index.php';
                header('Location: ' . $redirectURI);
                unset($_SESSION['original_request_uri']);
                exit(0);
            } else {
                echo '<p style="color: red;"><b>Your code was incorrect.</b></p>';
            }
        }
        echo '<p>Please enter the code generated by your mobile authenticator app.</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '">';
        echo '<input type="text" name="code" placeholder="Enter your code" autocomplete="off" /><br /><br />';
        echo '<input type="submit" name="enable" value="Validate Login" class="btn btn-primary" />';
        echo '</form>';
    } elseif ($secret && $_POST['disable']) {
        full_query("DELETE FROM `mod_oath_admin` WHERE adminid = '{$_SESSION['adminid']}'");
        unset($_SESSION['twofactoradmin']);
        header('Location: ' . $vars['modulelink']);
        exit(0);
    } elseif ($secret) {
        echo '<p>You have two-factor authentication enabled.</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '"><input type="submit" name="disable" value="Disable Two-Factor Authentication" class="btn btn-danger" /></form>';
    } else {
        echo '<p>You do not have two-factor authentication enabled.</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '"><input type="submit" name="enable" value="Enable Two-Factor Authentication" class="btn btn-primary" /></form>';
    }
    echo '</div>';
}
Example #23
0
 /**
  * 2step verification form
  * 
  */
 public function action_2step()
 {
     // 2step disabled or trying to access directly
     if (!Auth::instance()->logged_in() or Core::config('general.google_authenticator') == FALSE) {
         $this->redirect(Route::get('oc-panel')->uri());
     }
     //template header
     $this->template->title = __('2 Step Authentication');
     $this->template->content = View::factory('pages/auth/2step');
     //if user loged in redirect home
     if (Auth::instance()->logged_in() and (Cookie::get('google_authenticator') == $this->user->id_user or $this->user->google_authenticator == '')) {
         $this->redirect(Route::get('oc-panel')->uri());
     } elseif (core::post('code') and CSRF::valid('2step')) {
         //load library
         require Kohana::find_file('vendor', 'GoogleAuthenticator');
         $ga = new PHPGangsta_GoogleAuthenticator();
         if ($ga->verifyCode($this->user->google_authenticator, core::post('code'), 2)) {
             //set cookie
             Cookie::set('google_authenticator', $this->user->id_user, Core::config('auth.lifetime'));
             // redirect to the url we wanted to see
             Auth::instance()->login_redirect();
         } else {
             Form::set_errors(array(__('Invalid Code')));
         }
     }
 }
Example #24
-1
 public function index()
 {
     $this->id = "content";
     $this->template = "login/ga.tpl";
     $this->layout = "common/layout-empty";
     $request = Registry::get('request');
     $session = Registry::get('session');
     $db = Registry::get('db');
     $this->load->model('user/auth');
     $this->load->model('user/user');
     $this->load->model('user/prefs');
     if (ENABLE_SAAS == 1) {
         $this->load->model('saas/ldap');
         $this->load->model('saas/customer');
     }
     require DIR_BASE . 'system/helper/PHPGangsta_GoogleAuthenticator.php';
     $this->data['title'] = $this->data['text_login'];
     $this->data['title_prefix'] = TITLE_PREFIX;
     $this->data['failed_login_count'] = $this->model_user_auth->get_failed_login_count();
     if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate() == true) {
         $GA = new PHPGangsta_GoogleAuthenticator();
         $settings = $this->model_user_prefs->get_ga_settings($session->get('username'));
         if (strlen($this->request->post['ga_code']) > 5 && $GA->verifyCode($settings['ga_secret'], $this->request->post['ga_code'], 2)) {
             $session->set("ga_block", "");
             $this->model_user_prefs->get_user_preferences($session->get('username'));
             if (ENABLE_SAAS == 1) {
                 $this->model_saas_customer->online($session->get('email'));
             }
             LOGGER('logged in');
             if (isAdminUser() == 1) {
                 header("Location: " . SITE_URL . "index.php?route=health/health");
                 exit;
             }
             header("Location: " . SITE_URL . "search.php");
             exit;
         } else {
             $this->model_user_auth->increment_failed_login_count($this->data['failed_login_count']);
             $this->data['failed_login_count']++;
         }
         $this->data['x'] = $this->data['text_invalid_pin_code'];
     }
     $this->render();
 }