#702 Implement SHA256 php registration

- Refactor Bcrypt and Sha256 examples to use common abstract parent class
- Implement hashing logic for Sha256
This commit is contained in:
ljacqu 2016-05-19 21:44:24 +02:00
parent 14002ee75c
commit 383820cd22
7 changed files with 213 additions and 238 deletions

View File

@ -0,0 +1,126 @@
<?php
/*****************************************************************************
* AuthMe website integration logic *
* ------------------------------------------------------------------------- *
* Allows interaction with the AuthMe database (registration, password *
* verification). Don't forget to update the AUTHME_TABLE value and your *
* database credentials in getAuthmeMySqli(). *
* *
* Source: https://github.com/AuthMe-Team/AuthMeReloaded/ *
*****************************************************************************/
abstract class AuthMeController {
const AUTHME_TABLE = 'authme';
/**
* Entry point function to check supplied credentials against the AuthMe database.
*
* @param string $username the username
* @param string $password the password
* @return bool true iff the data is correct, false otherwise
*/
function checkPassword($username, $password) {
if (is_scalar($username) && is_scalar($password)) {
$hash = $this->getHashFromDatabase($username);
if ($hash) {
return $this->isValidPassword($password, $hash);
}
}
return false;
}
/**
* Returns whether the user exists in the database or not.
*
* @param string $username the username to check
* @return bool true if the user exists; false otherwise
*/
function isUserRegistered($username) {
$mysqli = $this->getAuthmeMySqli();
if ($mysqli !== null) {
$stmt = $mysqli->prepare('SELECT 1 FROM ' . self::AUTHME_TABLE . ' WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
return $stmt->fetch();
}
// Defensive default to true; we actually don't know
return true;
}
/**
* Registers a player with the given username.
*
* @param string $username the username to register
* @param string $password the password to associate to the user
* @return bool whether or not the registration was successful
*/
function register($username, $password) {
$mysqli = $this->getAuthmeMySqli();
if ($mysqli !== null) {
$hash = $this->hash($password);
$stmt = $mysqli->prepare('INSERT INTO ' . self::AUTHME_TABLE . ' (username, realname, password, ip) '
. 'VALUES (?, ?, ?, ?)');
$username_low = strtolower($username);
$stmt->bind_param('ssss', $username, $username_low, $hash, $_SERVER['REMOTE_ADDR']);
return $stmt->execute();
}
return false;
}
/**
* Hashes the given password.
*
* @param $password string the clear-text password to hash
* @return string the resulting hash
*/
protected abstract function hash($password);
/**
* Checks whether the given password matches the hash.
*
* @param $password string the clear-text password
* @param $hash string the password hash
* @return boolean true if the password matches, false otherwise
*/
protected abstract function isValidPassword($password, $hash);
/**
* Returns a connection to the database.
*
* @return mysqli|null the mysqli object or null upon error
*/
private function getAuthmeMySqli() {
// CHANGE YOUR DATABASE DETAILS HERE BELOW: host, user, password, database name
$mysqli = new mysqli('localhost', 'root', '', 'authme');
if (mysqli_connect_error()) {
printf('Could not connect to AuthMe database. Errno: %d, error: "%s"',
mysqli_connect_errno(), mysqli_connect_error());
return null;
}
return $mysqli;
}
/**
* Retrieves the hash associated with the given user from the database.
*
* @param string $username the username whose hash should be retrieved
* @return string|null the hash, or null if unavailable (e.g. username doesn't exist)
*/
private function getHashFromDatabase($username) {
// Add here your database host, username, password and database name
$mysqli = $this->getAuthmeMySqli();
if ($mysqli !== null) {
$stmt = $mysqli->prepare('SELECT password FROM ' . self::AUTHME_TABLE . ' WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($password);
if ($stmt->fetch()) {
return $password;
}
}
return null;
}
}

View File

@ -0,0 +1,20 @@
<?php
/***********************************************************
* AuthMe website integration logic for BCrypt *
* ------------------------------------------------------- *
* See AuthMeController for details. *
* *
* Source: https://github.com/AuthMe-Team/AuthMeReloaded/ *
***********************************************************/
class Bcrypt extends AuthMeController {
protected function hash($password) {
return password_hash($password, PASSWORD_BCRYPT);
}
protected function isValidPassword($password, $hash) {
return password_verify($password, $hash);
}
}

View File

@ -0,0 +1,48 @@
<?php
/***********************************************************
* AuthMe website integration logic for SHA256 *
* ------------------------------------------------------- *
* See AuthMeController for details. *
* *
* Source: https://github.com/AuthMe-Team/AuthMeReloaded/ *
***********************************************************/
class Sha256 extends AuthMeController {
/** @var string[] range of characters for salt generation */
private $CHARS;
const SALT_LENGTH = 16;
public function __construct() {
$this->CHARS = self::initRandomChars();
}
protected function isValidPassword($password, $hash) {
// $SHA$salt$hash, where hash := sha256(sha256(password) . salt)
$parts = explode('$', $hash);
return count($parts) === 4 && $parts[3] === hash('sha256', hash('sha256', $password) . $parts[2]);
}
protected function hash($password) {
$salt = $this->generateSalt();
return '$SHA$' . $salt . '$' . hash('sha256', hash('sha256', $password) . $salt);
}
/**
* @return string randomly generated salt
*/
private function generateSalt() {
$maxCharIndex = count($this->CHARS) - 1;
$salt = '';
for ($i = 0; $i < self::SALT_LENGTH; ++$i) {
$salt .= $this->CHARS[mt_rand(0, $maxCharIndex)];
}
return $salt;
}
private static function initRandomChars() {
return array_merge(range('0', '9'), range('a', 'f'));
}
}

View File

@ -1,107 +0,0 @@
<?php
/*****************************************************************************
* AuthMe website integration logic for BCrypt *
* -------------------------------- *
* Check with authme_check_password() whether the received username and *
* password match the AuthMe MySQL database. Don't forget to adjust the *
* database info in authme_get_hash(). *
* *
* Source: https://github.com/AuthMe-Team/AuthMeReloaded/ *
*****************************************************************************/
/** The name of the authme MySQL table. */
define('AUTHME_TABLE', 'authme');
/**
* Entry point function to check supplied credentials against the AuthMe database.
*
* @param string $username the username
* @param string $password the password
* @return bool true iff the data is correct, false otherwise
*/
function authme_check_password($username, $password) {
if (is_scalar($username) && is_scalar($password)) {
$hash = authme_get_hash($username);
if ($hash) {
return password_verify($password, $hash);
}
}
return false;
}
/**
* Returns a connection to the database.
*
* @return mysqli|null the mysqli object or null upon error
*/
function authme_get_mysqli() {
$mysqli = new mysqli('localhost', 'root', '', 'authme');
if (mysqli_connect_error()) {
printf('Could not connect to AuthMe database. Errno: %d, error: "%s"',
mysqli_connect_errno(), mysqli_connect_error());
return null;
}
return $mysqli;
}
/**
* Retrieves the hash associated with the given user from the database.
*
* @param string $username the username whose hash should be retrieved
* @return string|null the hash, or null if unavailable (e.g. username doesn't exist)
*/
function authme_get_hash($username) {
// Add here your database host, username, password and database name
$mysqli = authme_get_mysqli();
if ($mysqli !== null) {
$stmt = $mysqli->prepare('SELECT password FROM ' . AUTHME_TABLE . ' WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($password);
if ($stmt->fetch()) {
return $password;
}
}
return null;
}
/**
* Returns whether the user exists in the database or not.
*
* @param string $username the username to check
* @return bool true if the user exists; false otherwise
*/
function authme_has_user($username) {
$mysqli = authme_get_mysqli();
if ($mysqli !== null) {
$stmt = $mysqli->prepare('SELECT 1 FROM ' . AUTHME_TABLE . ' WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
return $stmt->fetch();
}
// Defensive default to true; we actually don't know
return true;
}
/**
* Registers a player with the given username.
*
* @param string $username the username to register
* @param string $password the password to associate to the user
* @return bool whether or not the registration was successful
*/
function authme_register($username, $password) {
$mysqli = authme_get_mysqli();
if ($mysqli !== null) {
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('INSERT INTO ' . AUTHME_TABLE . ' (username, realname, password, ip) '
. 'VALUES (?, ?, ?, ?)');
$username_low = strtolower($username);
$stmt->bind_param('ssss', $username, $username_low, $hash, $_SERVER['REMOTE_ADDR']);
return $stmt->execute();
}
return false;
}

View File

@ -1,6 +1,6 @@
<!--
This is a demo page for AuthMe website integration with BCrypt.
See integration.php for the PHP code you need.
This is a demo page for AuthMe website integration.
See AuthMeController.php and the extending classes for the PHP code you need.
-->
<!DOCTYPE html>
<html lang="en">
@ -12,17 +12,24 @@
<?php
error_reporting(E_ALL);
require 'AuthMeController.php';
// Change this to the file of the hash encryption you need, e.g. Bcrypt.php or Sha256.php
require 'Sha256.php';
// The class name must correspond to the file you have in require above! e.g. require 'Sha256.php'; and new Sha256();
$authme_controller = new Sha256();
$action = get_from_post_or_empty('action');
$user = get_from_post_or_empty('username');
$pass = get_from_post_or_empty('password');
$was_successful = false;
if ($action && $user && $pass) {
require_once('integration.php');
require_once('Bcrypt.php');
if ($action === 'Log in') {
$was_successful = process_login($user, $pass);
$was_successful = process_login($user, $pass, $authme_controller);
} else if ($action === 'Register') {
$was_successful = process_register($user, $pass);
$was_successful = process_register($user, $pass, $authme_controller);
}
}
@ -50,11 +57,11 @@ function get_from_post_or_empty($index_name) {
// Login logic
function process_login($user, $pass) {
if (authme_check_password($user, $pass)) {
function process_login($user, $pass, AuthMeController $controller) {
if ($controller->checkPassword($user, $pass)) {
printf('<h1>Hello, %s!</h1>', htmlspecialchars($user));
echo 'Successful login. Nice to have you back!'
. '<br /><a href="form.php">Back to form</a>';
. '<br /><a href="index.php">Back to form</a>';
return true;
} else {
echo '<h1>Error</h1> Invalid username or password.';
@ -63,15 +70,15 @@ function process_login($user, $pass) {
}
// Register logic
function process_register($user, $pass) {
if (authme_has_user($user)) {
function process_register($user, $pass, AuthMeController $controller) {
if ($controller->isUserRegistered($user)) {
echo '<h1>Error</h1> This user already exists.';
} else {
// Note that we don't validate the password or username at all in this demo...
$register_success = authme_register($user, $pass);
$register_success = $controller->register($user, $pass);
if ($register_success) {
printf('<h1>Welcome, %s!</h1>Thanks for registering', htmlspecialchars($user));
echo '<br /><a href="form.php">Back to form</a>';
echo '<br /><a href="index.php">Back to form</a>';
return true;
} else {
echo '<h1>Error</h1>Unfortunately, there was an error during the registration.';

View File

@ -1,52 +0,0 @@
<!--
This is a demo page for AuthMe website integration with SHA256.
See integration.php for the PHP code you need.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<title>AuthMe Integration Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
error_reporting(E_ALL);
$user = get_from_post_or_empty('username');
$pass = get_from_post_or_empty('password');
$was_successful = false;
if ($user && $pass) {
require_once('integration.php');
if (authme_check_password($user, $pass)) {
printf('<h1>Hello, %s!</h1>', htmlspecialchars($user));
echo 'Successful login. Nice to have you back!'
. '<br /><a href="form.php">Back to form</a>';
$was_successful = true;
} else {
echo '<h1>Error</h1> Invalid username or password.';
}
}
if (!$was_successful) {
echo '<h1>Login sample</h1>
This is a demo form for AuthMe website integration. Enter your AuthMe login details
into the following form to test it.
<form method="post">
<table>
<tr><td>Name</td><td><input type="text" value="' . htmlspecialchars($user) . '" name="username" /></td></tr>
<tr><td>Pass</td><td><input type="password" value="' . htmlspecialchars($pass) . '" name="password" /></td></tr>
<tr><td colspan="2"><input type="submit" value=" Log in " /></td></tr>
</table>
</form>';
}
function get_from_post_or_empty($index_name) {
return trim(
filter_input(INPUT_POST, $index_name, FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW)
?: '');
}
?>
</body>
</html>

View File

@ -1,67 +0,0 @@
<?php
/*****************************************************************************
* AuthMe website integration logic for SHA256 *
* -------------------------------- *
* Check with authme_check_password() whether the received username and *
* password match the AuthMe MySQL database. Don't forget to adjust the *
* database info in authme_get_hash(). *
* *
* Source: https://github.com/AuthMe-Team/AuthMeReloaded/ *
*****************************************************************************/
/**
* Entry point function to check supplied credentials against the AuthMe database.
*
* @param string $username the username
* @param string $password the password
* @return bool true iff the data is correct, false otherwise
*/
function authme_check_password($username, $password) {
if (is_scalar($username) && is_scalar($password)) {
$hash = authme_get_hash($username);
if ($hash) {
return authme_check_hash($password, $hash);
}
}
return false;
}
/**
* Retrieves the hash associated with the given user from the database.
*
* @param string $username the username whose hash should be retrieved
* @return string|null the hash, or null if unavailable (e.g. username doesn't exist)
*/
function authme_get_hash($username) {
// Add here your database host, username, password and database name
$mysqli = new mysqli('HOST', 'USER', 'PWD', 'DB');
$authme_table = 'authme';
if (mysqli_connect_error()) {
printf('Could not connect to AuthMe database. Errno: %d, error: "%s"',
mysqli_connect_errno(), mysqli_connect_error());
} else {
$stmt = $mysqli->prepare("SELECT password FROM $authme_table WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($password);
if ($stmt->fetch()) {
return $password;
}
}
return null;
}
/**
* Checks the given clear-text password against the hash.
*
* @param string $password the clear-text password to check
* @param string $hash the hash to check the password against
* @return bool true iff the password matches the hash, false otherwise
*/
function authme_check_hash($password, $hash) {
// $SHA$salt$hash, where hash := sha256(sha256(password) . salt)
$parts = explode('$', $hash);
return count($parts) === 4
&& $parts[3] === hash('sha256', hash('sha256', $password) . $parts[2]);
}