createSecret() public method

16 characters, randomly chosen from the allowed base32 characters.
public createSecret ( integer $secretLength = 16 ) : string
$secretLength integer
return string
Example #1
0
 public function display()
 {
     include_once $this->root_path . 'libraries/twofactor/googleAuthenticator.class.php';
     $ga = new PHPGangsta_GoogleAuthenticator();
     $secret = $ga->createSecret();
     $this->tpl->assign_vars(array('TWOFACTOR_KEY' => $secret, 'TWOFACTOR_QR' => $ga->getQRCodeGoogleUrl(str_replace(' ', '_', 'EQdkpPlus ' . $this->config->get('guildtag')), $secret), 'TWOFACTOR_KEY_ENCR' => rawurlencode(register('encrypt')->encrypt($secret))));
     $this->core->set_vars(array('page_title' => "", 'header_format' => "simple", 'template_file' => 'twofactor_init.html', 'display' => true));
 }
Example #2
0
 public function get_ga_settings($username = '')
 {
     $data = array('ga_enabled' => 0, 'ga_secret' => '');
     if ($username == "") {
         return $data;
     }
     $GA = new PHPGangsta_GoogleAuthenticator();
     $query = $this->db->query("SELECT ga_enabled, ga_secret FROM " . TABLE_USER_SETTINGS . " WHERE username=?", array($username));
     if (isset($query->row['ga_enabled'])) {
         $data['ga_enabled'] = $query->row['ga_enabled'];
         $data['ga_secret'] = $query->row['ga_secret'];
         if ($data['ga_secret'] == '') {
             $data['ga_secret'] = $GA->createSecret();
             $this->update_ga_secret($username, $data['ga_secret']);
         }
     } else {
         $query = $this->db->query("INSERT INTO " . TABLE_USER_SETTINGS . " (username, ga_enabled, ga_secret) VALUES(?,0,?)", array($username, $GA->createSecret()));
     }
     return $data;
 }
Example #3
0
 public function get_account()
 {
     $secret = register('encrypt')->decrypt(rawurldecode($this->in->get('secret')));
     $code = $this->in->get('code');
     if ($secret == "" || $code == "") {
         return false;
     }
     include_once $this->root_path . 'libraries/twofactor/googleAuthenticator.class.php';
     $ga = new PHPGangsta_GoogleAuthenticator();
     $checkResult = $ga->verifyCode($secret, $code, 5);
     // 2 = 2*30sec clock tolerance
     if ($checkResult) {
         return register('encrypt')->encrypt(serialize(array('secret' => $secret, 'emergency_token' => $ga->createSecret(8))));
     }
     return false;
 }
Example #4
0
 /**
  * @param $oServer
  * @return mixed
  */
 public function AjaxTwoFactorAuthenticationSettings($oServer)
 {
     $bStatus = trim(stripcslashes($oServer->getParamValue('Enable', 'false'))) === 'true' ? true : false;
     $iAccountId = $oServer->GetDefaultAccount()->IdAccount;
     $oApiUsers = \CApi::Manager('users');
     $oAccount = $oApiUsers->getAccountById($iAccountId);
     $aResult['Action'] = 'TwoFactorAuthenticationSettings';
     if ($bStatus === true) {
         $oGoogle = new PHPGangsta_GoogleAuthenticator();
         $sSecret = $this->getCode($oAccount) ? $this->getCode($oAccount) : $oGoogle->createSecret();
         $aResult['Result'] = array('Code' => $sSecret, 'QRcode' => $oGoogle->getQRCodeGoogleUrl($_SERVER['SERVER_NAME'], $sSecret), 'Enabled' => $this->getCode($oAccount) ? true : false);
     } else {
         $this->removeDataValue($oAccount);
         $aResult['Result'] = false;
     }
     return $aResult;
 }
Example #5
0
 public function action_2step()
 {
     $action = $this->request->param('id');
     if ($action == 'enable') {
         //load library
         require Kohana::find_file('vendor', 'GoogleAuthenticator');
         $ga = new PHPGangsta_GoogleAuthenticator();
         $this->user->google_authenticator = $ga->createSecret();
         //set cookie
         Cookie::set('google_authenticator', $this->user->id_user, Core::config('auth.lifetime'));
         Alert::set(Alert::SUCCESS, __('2 Step Authentication Enabled'));
     } elseif ($action == 'disable') {
         $this->user->google_authenticator = '';
         Cookie::delete('google_authenticator');
         Alert::set(Alert::INFO, __('2 Step Authentication Disabled'));
     }
     try {
         $this->user->save();
     } catch (Exception $e) {
         //throw 500
         throw HTTP_Exception::factory(500, $e->getMessage());
     }
     $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit')));
 }
Example #6
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>';
}
 private function __createSecret()
 {
     $ga = new PHPGangsta_GoogleAuthenticator();
     return $ga->createSecret();
 }
 /**
  * Process any user configuration.
  */
 public function processProfileForm()
 {
     global $INPUT;
     $ga = new PHPGangsta_GoogleAuthenticator();
     $oldmysecret = $this->_settingGet("secret");
     if ($oldmysecret !== null) {
         if ($INPUT->bool('googleauth_disable', false)) {
             $this->_settingDelete("secret");
             // Also delete the seenqrcode attribute.  Otherwise the system will still expect the user to login with GA.
             $this->_settingDelete("verified");
             return true;
         } else {
             $otp = $INPUT->str('googleauth_verify', '');
             if ($otp) {
                 // The user will use GA.
                 $checkResult = $this->processLogin($otp);
                 // If the code works, then flag this account to use GA.
                 if ($checkResult === false) {
                     return 'failed';
                 } else {
                     $this->_settingSet("verified", true);
                     return 'verified';
                 }
             }
         }
     } else {
         if ($INPUT->bool('googleauth_enable', false)) {
             // Only make a code if one is not set.
             $mysecret = $ga->createSecret();
             $this->_settingSet("secret", $mysecret);
             return true;
         }
     }
     return null;
 }
Example #9
0
if ($ck_u_type !== "0") {
    exit("无权限进行此操作");
}
$nav_str .= " &gt <a href=userlist.php>用户列表</a> &gt 添加用户";
$cgi = getCGI();
gsql_esc($cgi);
$username = $cgi[username];
$login = $cgi[login];
$passwd = $cgi[passwd];
$note = $cgi[note];
$type = $cgi[type];
if ($username && $login && $type && $passwd) {
    $salt = getSalt();
    $passwd = md5($passwd . $salt);
    $ga = new PHPGangsta_GoogleAuthenticator();
    $secret = $ga->createSecret();
    $sqlstr = sprintf("insert into user set name='%s', login='******', passwd='%s', type='%s', note='%s',c_id=%s,secret='%s',salt='%s',createdt=now()", $username, $login, $passwd, $type, $note, $ck_u_id, $secret, $salt);
    $res = mysql_query($sqlstr, $pub_mysql) or exit(mysql_error() . "\n" . $sqlstr);
    header("Location: userlist.php");
    exit;
}
?>


<html>
<head>
<title>adduser</title>
<meta http-equiv="Content-Type" content="text/html; charset=<?php 
echo HTML_CHARSET;
?>
">
Example #10
0
    $table->output($lang->recovery_codes);
    $page->output_footer();
}
if (!$mybb->input['action']) {
    require_once MYBB_ROOT . "inc/3rdparty/2fa/GoogleAuthenticator.php";
    $auth = new PHPGangsta_GoogleAuthenticator();
    $plugins->run_hooks("admin_home_preferences_start");
    if ($mybb->request_method == "post") {
        $query = $db->simple_select("adminoptions", "permissions, defaultviews, authsecret, recovery_codes", "uid='{$mybb->user['uid']}'");
        $adminopts = $db->fetch_array($query);
        $secret = $adminopts['authsecret'];
        // Was the option changed? empty = disabled so ==
        if ($mybb->input['2fa'] == empty($secret)) {
            // 2FA was enabled -> create secret and log
            if ($mybb->input['2fa']) {
                $secret = $auth->createSecret();
                // We don't want to close this session now
                $db->update_query("adminsessions", array("authenticated" => 1), "sid='" . $db->escape_string($mybb->cookies['adminsid']) . "'");
                log_admin_action("enabled");
            } else {
                $secret = "";
                $adminopts['recovery_codes'] = "";
                log_admin_action("disabled");
            }
        }
        $sqlarray = array("notes" => $db->escape_string($mybb->input['notes']), "cpstyle" => $db->escape_string($mybb->input['cpstyle']), "cplanguage" => $db->escape_string($mybb->input['cplanguage']), "permissions" => $db->escape_string($adminopts['permissions']), "defaultviews" => $db->escape_string($adminopts['defaultviews']), "uid" => $mybb->user['uid'], "codepress" => $mybb->get_input('codepress', MyBB::INPUT_INT), "authsecret" => $db->escape_string($secret), "recovery_codes" => $db->escape_string($adminopts['recovery_codes']));
        $db->replace_query("adminoptions", $sqlarray, "uid");
        $plugins->run_hooks("admin_home_preferences_start_commit");
        flash_message($lang->success_preferences_updated, 'success');
        admin_redirect("index.php?module=home-preferences");
    }
Example #11
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 #12
0
<?php

require_once "config.php";
require DIR_SYSTEM . "/startup.php";
$loader = new Loader();
$language = new Language();
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PREFIX);
Registry::set('db', $db);
$loader->model('user/prefs');
$loader->helper('phpqrcode/qrlib');
$loader->helper('PHPGangsta_GoogleAuthenticator');
$p = new ModelUserPrefs();
if (isset($_GET['refresh'])) {
    $GA = new PHPGangsta_GoogleAuthenticator();
    $new_secret = $GA->createSecret();
    $p->update_ga_secret($session->get('username'), $new_secret);
    print "{$new_secret} <a href=\"#\" onclick=\"Piler.new_qr(); return false;\">" . $language->data['text_refresh_qr_code'] . "</a><br /><img src=\"qr.php?ts=" . microtime(true) . "\" />\n";
    exit;
} else {
    if (isset($_GET['toggle'])) {
        $p->toggle_ga($session->get('username'), $_GET['toggle']);
    }
}
$ga = $p->get_ga_settings($session->get('username'));
QRcode::png("otpauth://totp/" . SITE_NAME . "?secret=" . $ga['ga_secret'], false, "L", 4, 2);
Example #13
0
<?php

include_once 'config.php';
include_once 'funciones.php';
include_once 'View.php';
require_once 'GoogleAuthenticator.php';
$usuario = $_POST['user'];
$clave = sha1($_POST['pass']);
$ga = new PHPGangsta_GoogleAuthenticator();
$token = $ga->createSecret();
$coneccion = conectarDB($parametrosGlobales['db']);
$resultado = $coneccion->query("INSERT INTO usuario (`user`, `pass`, `token`) VALUES ('{$usuario}', '{$clave}', '{$token}')");
if (!$resultado) {
    echo "Falló la creación del usuario: (" . $coneccion->errno . ") " . $coneccion->error;
} else {
    $ultimoID = $coneccion->insert_id;
    header("Location: verUsuario.php?id={$ultimoID}");
}
?>

<br><br><br><a href="index.php">Ir al Login</a>



 /**
  * @return string
  */
 public function CreateSecret()
 {
     include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHPGangsta/GoogleAuthenticator.php';
     $oGoogleAuthenticator = new \PHPGangsta_GoogleAuthenticator();
     return $oGoogleAuthenticator->createSecret();
 }
Example #15
0
<?php

/**
 * Created by PhpStorm.
 * User: Alain
 * Date: 22.03.2016
 * Time: 13:31
 */
require_once "../controller/CustomSession.php";
require_once "../external/GoogleAuthenticator.php";
$user = CustomSession::getInstance()->getCurrentUser();
$ga = new PHPGangsta_GoogleAuthenticator();
//Secret already exists => Use it. Else => Create one
$secret = $user['secret'] ? $user['secret'] : $ga->createSecret();
?>

<div id="content">

    <h1>Einstellungen</h1>

    <form onsubmit="applySettings(); return false;" id="settingsForm">
        <div id="settingsLeft">
            <label for="Username" class="SettingsLabel">Benutzername</label> <br/>
            <input type="text" id="Username" name="Username" class="ContentInput" required="required"
                   value="<?php 
echo $user['username'];
?>
"> <br/>

            <label for="Name" class="SettingsLabel">Name</label> <br/>
            <input type="text" id="Name" name="Name" class="ContentInput" required="required"
Example #16
0
 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;
         }
     }
 }
Example #17
0
} else {
    if (count(get_included_files()) == 0) {
        die;
    }
}
if (!defined('FILEACCESS')) {
    die;
}
checkacl('upaccess');
$users = json_decode(file_get_contents($config['path'] . '/db/db-users.json'), true);
$acls = json_decode(file_get_contents($config['path'] . '/db/db-acl.json'), true);
if (isset($_REQUEST['users'])) {
    if ($_REQUEST['users'] == '2focreatekey') {
        require $config['path'] . '/libs/googleauthenticator/GoogleAuthenticator.php';
        $ga = new PHPGangsta_GoogleAuthenticator();
        echo $ga->createSecret();
        die;
    } elseif ($_REQUEST['users'] == 'generateqr' && isset($_REQUEST['generateqr'])) {
        require $config['path'] . '/libs/googleauthenticator/GoogleAuthenticator.php';
        $ga = new PHPGangsta_GoogleAuthenticator();
        echo '<img src="' . $ga->getQRCodeGoogleUrl('CDP.me', $_REQUEST['generateqr']) . '" alt="QR Code">';
        die;
    } elseif ($_REQUEST['users'] == 'add' && isset($_REQUEST['username']) && isset($_REQUEST['password']) && isset($_REQUEST['acl'])) {
        checkacl('adduser');
        if (!isset($_REQUEST['2fokey'])) {
            $_REQUEST['2fokey'] = null;
        }
        $users[count($users)] = array('id' => count($users) + 1, 'username' => trim($_REQUEST['username']), 'password' => md5($_REQUEST['password']), 'acl' => $_REQUEST['acl'], '2fo' => $_REQUEST['2fo'], '2fokey' => $_REQUEST['2fokey']);
        file_put_contents($config['path'] . '/db/db-users.json', json_encode($users));
        logevent('User ' . $_SESSION['user'] . ' added user ' . $_REQUEST['username'], 'activity');
        header('Location: index.php?action=users');