-1

アップデート:

  • 4月9日:

問題がどこにあるかを確認しました。

まず、process_login.php にエコーを追加し、header('location...protected_pa​​ge.php) を削除しました。$_SESSION['user_id']login 関数 (functions.php 内) が彼の仕事を行い、正しい:と同様に$_SESSION['username']and を書き込みます$_SESSION['login_string']

次に、process_login.php のエコーを削除し、header('location.. to protected_pa​​ge.php.(元のコードに戻します) を書き直しました。その後、login_check にエコーを追加してから、if の前にいくつかのエコーを追加しました。 function login_check($mysqli) { echo "<br>userid:".$_SESSION['user_id']; echo "<br>username:".$_SESSION['username']; echo "<br>loginstring:".$_SESSION['login_string'];

結果は空白なので、SESSION 変数は関数 login で正しく書き込まれますが、protected_pa​​ge へのヘッダーの後、変数が削除されているように見えます。もしかして sec_session_start() 関数がうまく動いていないのでしょうか? とにかく、私は @Manikiran のアドバイスに従い、作業を続け、暗号化などを削除します.... @Manikiran と @lps に感謝します

元の質問:

私は基本的なログインシステムをやろうとしています。しかし、私がやったことはうまくいきません。システムは基本的に、資格情報を入力する index.php であり、php はユーザーが存在するかどうか、およびパスワードが正しいかどうかを確認します。次に、ユーザーは protected_pa​​ge.php にリダイレクトされます。ユーザーとパスワードが正しい場合、Web ページは protected_pa​​ge.php にリダイレクトし、ユーザーとパスワードが正しくない場合、ページはそのように通知します。

さて、問題: protected_pa​​ge.php には明らかにセッション「チェッカー」があります。つまり、ユーザーとパスワードで正しく接続した場合、ページには個人的な HTML 情報が表示されます。接続していない場合、ページは表示されません。あなたに何かを見せてください。これは機能しません。ユーザーと正しく接続しているにもかかわらず、ページにはログインしていないことが示されます.... (注: index.php には、どちらも機能しない保護された html も含まれています)

コード: (注: sec_session_starts() は、セッションのハイジャックを防ぐ方法であると想定されており、もちろん session_start() が含まれています)

index.php: (必要に応じて protected_pa​​ge() にリダイレクトするため、問題なく動作すると思います。セッション データを設定する部分の login(...) 関数に問題がある可能性があります... ) .

 <?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();

if (login_check($mysqli) == true) {
    $logged = 'in';
} else {
    $logged = 'out';
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Secure Login: Log In</title>

        <script type="text/JavaScript" src="js/sha512.js"></script> 
        <script type="text/JavaScript" src="js/forms.js"></script> 
    </head>
    <body>
        <?php
        if (isset($_GET['error'])) {
            echo '<p class="error">Error Logging In!</p>';
        }
        ?> 
        <form action="includes/process_login.php" method="post" name="login_form">                      
            Email: <input type="text" name="email" />
            Password: <input type="password" 
                             name="password" 
                             id="password"/>
            <input type="button" 
                   value="Login" 
                   onclick="formhash(this.form, this.form.password);" /> 
        </form>

<?php
        if (login_check($mysqli) == true) {
                        echo '<p>Currently logged ' . $logged . ' as ' . htmlentities($_SESSION['username']) . '.</p>';

            echo '<p>Do you want to change user? <a href="includes/logout.php">Log out</a>.</p>';
        } else {
                        echo '<p>Currently logged ' . $logged . '.</p>';
                        echo "<p>If you don't have a login, please <a href='register.php'>register</a></p>";
                }
?>      
    </body>
</html>

process_login.php (正常に動作すると思います)

<?php
include_once 'db_connect.php';
include_once 'functions.php';

sec_session_start(); // Our custom secure way of starting a PHP session.

if (isset($_POST['email'], $_POST['p'])) {
    $email = $_POST['email'];
    $password = $_POST['p']; // The hashed password.

    if (login($email, $password, $mysqli) == true) {
        // Login success 
        header('Location: ../protected_page.php');
    } else {
        // Login failed 
        header('Location: ../index.php?error=1');
    }
} else {
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request';
}

functions.php:

<?php
include_once 'psl-config.php';
require_once 'passwordLib.php';


function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = true;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id(true);    // regenerated the session, delete the old one. 
}


function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, username, password 
        FROM members
       WHERE email = ?
        LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password);
        $stmt->fetch();

        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 

            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted. We are using
                // the password_verify function to avoid timing attacks.
                if (password_verify($password, $db_password)) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $username);
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', 
                              $db_password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', '$now')");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time 
                             FROM login_attempts 
                             WHERE user_id = ? 
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}

function login_check($mysqli) {
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], 
                        $_SESSION['username'], 
                        $_SESSION['login_string'])) {

        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM members 
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if (hash_equals($login_check, $login_string) ){
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&amp;', '&#038;', $url);
    $url = str_replace("'", '&#039;', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

protected_pa​​ge.php: (または、セッション データをチェックする login_check に問題がある可能性があります

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();

?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Secure Login: Protected Page</title>
        <link rel="stylesheet" href="styles/main.css" />
    </head>
    <body>

        <?php if (login_check($mysqli) == true) : ?>
            <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
            <p>
                This is an example protected page.  To access this page, users
                must be logged in.  At some stage, we'll also check the role of
                the user, so pages will be able to determine the type of user
                authorised to access the page.
            </p>
            <p>Return to <a href="index.php">login page</a></p>
        <?php else : ?>
            <p>
                <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login</a>.
            </p>
        <?php endif; ?>
    </body>
</html>

psl-config と db_connect はデータベースに接続し、正常に動作していると思います。私のサーバーにはphp 5.4があり、php 5関数を使用しているため、passwordLib.phpはライブラリです。このライブラリは、パスワードの暗号化などに役立つはずであり、問​​題はここにもないと思います。とにかく私はコードを入れます:

<?php
/**
 * PHP 5.5-like password hashing functions
 *
 * Provides a password_hash() and password_verify() function as appeared in PHP 5.5.0
 * 
 * See: http://php.net/password_hash and http://php.net/password_verify
 * 
 * @link https://github.com/Antnee/phpPasswordHashingLib
 */

require_once('passwordLibClass.php');

if (!function_exists('password_hash')){
    function password_hash($password, $algo=PASSWORD_DEFAULT, $options=array()){
        $crypt = NEW Antnee\PhpPasswordLib\PhpPasswordLib;
        $crypt->setAlgorithm($algo);

        $debug  = isset($options['debug'])
                ? $options['debug']
                : NULL;

        $password = $crypt->generateCryptPassword($password, $options, $debug);

        return $password;
    }
}

if (!function_exists('password_verify')){
    function password_verify($password, $hash){
        return (crypt($password, $hash) === $hash);
    }
}

if (!function_exists('password_needs_rehash')){
    function password_needs_rehash($hash, $algo, $options=array()){
        $crypt = NEW Antnee\PhpPasswordLib\PhpPasswordLib;
        return !$crypt->verifyCryptSetting($hash, $algo, $options);
    }
}

if (!function_exists('password_get_info')){
    function password_get_info($hash){
        $crypt = NEW Antnee\PhpPasswordLib\PhpPasswordLib;
        return $crypt->getInfo($hash);
    }
}

passwordlibclass.php:

<?php
/**
 * PHP 5.5-like password hashing functions
 *
 * Provides a password_hash() and password_verify() function as appeared in PHP 5.5.0
 * 
 * See: http://php.net/password_hash and http://php.net/password_verify
 * 
 * @link https://github.com/Antnee/phpPasswordHashingLib
 */


namespace Antnee\PhpPasswordLib;

if (!defined('PASSWORD_BCRYPT')) define('PASSWORD_BCRYPT', 1);

// Note that SHA hashes are not implemented in password_hash() or password_verify() in PHP 5.5
// and are not recommended for use. Recommend only the default BCrypt option
if (!defined('PASSWORD_SHA256')) define('PASSWORD_SHA256', -1);
if (!defined('PASSWORD_SHA512')) define('PASSWORD_SHA512', -2);

if (!defined('PASSWORD_DEFAULT')) define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);

class PhpPasswordLib{

    CONST BLOWFISH_CHAR_RANGE = './0123456789ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    CONST BLOWFISH_CRYPT_SETTING = '$2a$'; 
    CONST BLOWFISH_CRYPT_SETTING_ALT = '$2y$'; // Available from PHP 5.3.7
    CONST BLOWFISH_ROUNDS = 10;
    CONST BLOWFISH_NAME = 'bcrypt';

    // Note that SHA hashes are not implemented in password_hash() or password_verify() in PHP 5.5
    // and are not recommended for use. Recommend only the default BCrypt option
    CONST SHA256_CHAR_RANGE = './0123456789ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    CONST SHA256_CRYPT_SETTING = '$5$';
    CONST SHA256_ROUNDS = 5000;
    CONST SHA256_NAME = 'sha256';

    CONST SHA512_CHAR_RANGE = './0123456789ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    CONST SHA512_CRYPT_SETTING = '$6$';
    CONST SHA512_ROUNDS = 5000;
    CONST SHA512_NAME = 'sha512';


    /**
     * Default Crypt Algorithm
     * 
     * @var INT
     */
    private $algorithm = PASSWORD_BCRYPT;


    /**
     * Name of the current algorithm
     *
     * @var STRING
     */
    private $algoName;


    /**
     * Setting for PHP Crypt function, defines algorithm
     * 
     * Default setting is '$2a$' : BCrypt
     * 
     * @var STRING
     */
    protected $cryptSetting;


    /**
     * Setting for PHP Crypt function, defines processing cost
     * 
     * Default setting is '08$' for BCrypt rounds
     * 
     * @var INT
     */
    protected $rounds;


    /**
     * Salt Character Count for Crypt Functions
     * 
     * @var INT
     */
    protected $addSaltChars;


    /**
     * Salt Character Range for Crypt Functions
     * 
     * @var STRING 
     */
    protected $saltCharRange;


    /**
     * Class Constructor
     */
    public function __construct(){
        // Initialise default algorithm
        $this->setAlgorithm($this->algorithm);
    }


    /**
     * Generate Crypt Password
     * 
     * @param STRING $password The password to encode
     * @param ARRAY $options Cost value, and Salt if required
     * @param BOOL $debug If true will return time to calculate hash
     * @return STRING The encoded password
     */
    public function generateCryptPassword($password, $options = array(), $debug = FALSE){
        $startTime  = microtime(TRUE);
        if (isset($options['cost'])) $this->setCost($options['cost']);
        $salt       = $this->cryptSalt(@$options['salt']);
        $crypt      = crypt($password, $salt);
        $endTime    = microtime(TRUE);
        if ($debug){
            $calcTime = $endTime - $startTime;
            return $calcTime;
        }
        return $crypt;
    }


    /**
     * Generate Crypt Salt
     * 
     * Generates a salt suitable for Crypt using the defined crypt settings
     * 
     * @param STRING $salt Override random salt with predefined value
     * @return STRING
     */
    public function cryptSalt($salt=NULL){
        if (empty($salt)){
            for ($i = 0; $i<$this->addSaltChars; $i++){
                $salt .= $this->saltCharRange[rand(0,(strlen($this->saltCharRange)-1))];
            }
        }
        $salt = $this->cryptSetting.$this->rounds.$salt.'$';
        return $salt;
    }


    /**
     * Set Crypt Setting
     * 
     * @param type $setting
     * @return \Antnee\PhpPasswordLib\PhpPasswordLib
     */
    public function cryptSetting($setting){
        $this->cryptSetting = $setting;
        return $this;
    }




       /**
         * Salt Character Count
         * 
         * @param INT $count Number of characters to set
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib|boolean
         */
        public function addSaltChars($count){
            if (is_int($count)){
                $this->addSaltChars = $count;
                return $this;
            } else {
                return FALSE;
            }
        }


        /**
         * Salt Character Range
         * 
         * @param STRING $chars
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib|boolean
         */
        public function saltCharRange($chars){
            if (is_string($chars)){
                $this->saltCharRange = $chars;
                return $this;
            } else {
                return FALSE;
            }
        }


        /**
         * Set Crypt Algorithm
         * 
         * @param INT $algo
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib
         */
        public function setAlgorithm($algo=NULL){
            switch ($algo){
                case PASSWORD_SHA256:
                    $this->algorithm = PASSWORD_SHA256;
                    $this->cryptSetting(self::SHA256_CRYPT_SETTING);
                    $this->setCost(self::SHA256_ROUNDS);
                    $this->addSaltChars(16);
                    $this->saltCharRange(self::SHA256_CHAR_RANGE);
                    $this->algoName = self::SHA256_NAME;
                    break;
                case PASSWORD_SHA512:
                    $this->algorithm = PASSWORD_SHA512;
                    $this->cryptSetting(self::SHA512_CRYPT_SETTING);
                    $this->setCost(self::SHA512_ROUNDS);
                    $this->addSaltChars(16);
                    $this->saltCharRange(self::SHA512_CHAR_RANGE);
                    $this->algoName = self::SHA512_NAME;
                    break;
                case PASSWORD_BCRYPT:
                default:
                    $this->algorithm = PASSWORD_BCRYPT;
                    if (version_compare(PHP_VERSION, '5.3.7') >= 1){
                        // Use improved Blowfish algorithm if supported
                        $this->cryptSetting(self::BLOWFISH_CRYPT_SETTING_ALT);
                    } else {
                        $this->cryptSetting(self::BLOWFISH_CRYPT_SETTING);
                    }
                    $this->setCost(self::BLOWFISH_ROUNDS);
                    $this->addSaltChars(22);
                    $this->saltCharRange(self::BLOWFISH_CHAR_RANGE);
                    $this->algoName = self::BLOWFISH_NAME;
                    break;
            }
            return $this;
        }


        /**
         * Set Cost
         * 
         * @todo implement
         * 
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib
         */
        public function setCost($rounds){
            switch ($this->algorithm){
                case PASSWORD_BCRYPT:
                    $this->rounds = $this->setBlowfishCost($rounds);
                    break;
                case PASSWORD_SHA256:
                case PASSWORD_SHA512:
                    $this->rounds = $this->setShaCost($rounds);
                    break;
            }
            return $this;
        }


        /**
         * Set Blowfish hash cost
         * 
         * Minimum 4, maximum 31. Value is base-2 log of actual number of rounds, so
         * 4 = 16, 8 = 256, 16 = 65,536 and 31 = 2,147,483,648
         * Defaults to 8 if value is out of range or incorrect type
         * 
         * @param int $rounds
         * @return STRING
         */
        private function setBlowfishCost($rounds){
            if (!is_int($rounds) || $rounds < 4 || $rounds > 31){
                $rounds = $rounds = self::BLOWFISH_ROUNDS;
            }
            return sprintf("%02d", $rounds)."$";
        }


        /**
         * Set SHA hash cost
         * 
         * Minimum 1000, maximum 999,999,999
         * Defaults to 5000 if value is out of range or incorrect type
         * 
         * @param INT $rounds
         * @return STRING
         */
        private function setShaCost($rounds){
            if (!is_int($rounds) || $rounds < 1000 || $rounds > 999999999){
                switch ($this->algorithm){
                    case PASSWORD_SHA256:
                        $rounds = self::SHA256_ROUNDS;
                    case PASSWORD_SHA512:
                    default:
                        $rounds = self::SHA512_ROUNDS;
                }
            }
            return "rounds=" . $rounds ."$";
        }


        /**
         * Get hash info
         *
         * @param STRING $hash
         * @return ARRAY
         */
        public function getInfo($hash){
            $params = explode("$", $hash);
            if (count($params) < 4) return FALSE;

            switch ($params['1']){
                case '2a':
                case '2y':
                case '2x':
                    $algo = PASSWORD_BCRYPT;
                    $algoName = self::BLOWFISH_NAME;
                    break;
                case '5':
                    $algo = PASSWORD_SHA256;
                    $algoName = self::SHA256_NAME;
                    break;
                case '6':
                    $algo = PASSWORD_SHA512;
                    $algoName = self::SHA512_NAME;
                    break;
                default:
                    return FALSE;
            }

            $cost = preg_replace("/[^0-9,.]/", "", $params['2']);

            return array(
                'algo' => $algo,
                'algoName' => $algoName,
                'options' => array(
                    'cost' => $cost
                ),
            );
        }


        /**
         * Verify Crypt Setting
         * 
         * Checks that the hash provided is encrypted at the current settings or not,
         * returning BOOL accordingly
         * 
         * @param STRING $hash
         * @return BOOL
         */
        public function verifyCryptSetting($hash, $algo, $options=array()){
            $this->setAlgorithm($algo);
            if (isset($options['cost'])) $this->setCost($options['cost']);

            $setting = $this->cryptSetting.$this->rounds;

            return (substr($hash, 0, strlen($setting)) === $setting);
        }
    }

最終コメント:私はたくさん検索したことを約束しますが、他の質問でこの特定の問題は見つかりませんでした. ありがとうございました。

4

1 に答える 1

0

問題は、比較された 2 つの変数がまったく同じであるにもかかわらず、hash_equals() がうまく機能せず、その関数が false を返すことです。私はそれを別のライブラリに変更しようとしましたが、どうしようもありません。(私のホストには php 5.4 があり、password_hash() 関数を使用できないことを覚えています。

唯一の解決策は、それを変更するか、password_hash() を正しく置き換えるライブラリを見つけることです。

于 2016-04-28T10:16:07.780 に答える