微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何在没有SSL的情况下保护身份验证cookie

我正在创建一个使用两个会话的登录系统(对于那些不允许使用cookie的人(同意cookie法律……我使用网站http://www.cookielaw.org/the-cookie-law.aspx作为参考)

现在,我有这个系统用于我的cookie身份验证

function GenerateString(){
        $length = mt_rand(0,25);
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';

        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(5, strlen($characters) -1)];
        }
        return $string;
}
$RandomString = GenerateString();

$CookieAuth = $DB->prepare("INSERT INTO cookieauth (Username,RandomString) VALUES (?,?)");
$CookieAuth->bind_param('ss',$_POST['Username'],$RandomString); 
$CookieAuth->execute(); // Insert the Authentication Methods into the database 
$CookieAuth->close(); // Allow another query/statement

$GetInsertID = $DB->prepare("SELECT ID FROM CookieAuth WHERE RandomString=?");
$GetInsertID->bind_param('s',$Randomstring);
$GetInsertID->execute();
$GetInsertID->bind_result($RowID);
$GetInsertID->fetch();
$GetInsertID->close(); 

setcookie("Auth[ID]",$RowID);
setcookie("Auth[UName],$_POST['Username']);
setcookie("Auth[RandomString]",$RandomString);

然后处理cookie:

if(isset($_COOKIE['Auth'])){
   $Authenticate = $DB->prepare("SELECT Username,RandomString FROM cookieauth WHERE ID=?");
   $Authenticate->bind_param('i',$_COOKIE['Auth']['ID']);
   $Authenticate->execute();
   $Authenticate->bind_result($RowUsername,$RowString);
   $Authenticate->fetch();
   $Authenticate->close();

if ($_Cookie['Auth']['UName'] == $RowUsername){
    if ($_COOKIE['Auth']['RandomString'] == $RowString){
        header("Location: LoggedIn.PHP");
    }else{
        die("Possible Cookie Manipulation, Autologin Cannot Continue");
    }
}else{
    die("Possible Cookie Manupulation, Autologin Cannot Continue!");
}

我的总体目标是使用cookie提供自动登录功能.因为人们应该知道它们本质上是作为纯文本存储在硬盘驱动器上的.所以如果我包含一个随机生成的字符串,每次进一步处理时会更改(然后更新cookie以匹配数据库)这是一种相当安全的方式完成任务?我的意思是,我知道这不是100%安全,因为一些用户可能会尝试操纵随机字符串,所以我可以使用salt,随机密钥然后使用hash_hmac来sha512 salt密钥并将其保存为cookie. .

我的整体问题是,我提供了一种通过cookie处理自动登录的半安全方法的块,并且可以最大限度地减少一些坏人操纵密钥以获得所需数据的可能性?

解决方法:

介绍

为什么要在会话进行时确认cookie?如果您想更改ID,可以使用session_regenerate_id轻松实现,如@marcB指出的那样.

我的假设

我想假设我没有清楚地理解这个问题,可能这就是你想要实现的目标

>将值存储到Cookie
>知道这些值是否已被修改

你已经解决

I Could resort to a salt, random key then use hash_hmac to sha512 the salt+key and save that as the cookie…

这正是解决方案,但您需要注意这一点

>会议可能会被劫持
> PHP有更好的方法生成随机字符串
>想象一下,每次会话都可以轻松地为您完成更新MysqL表的开销
>使用hash_hmac 512将生成126十六进制格式你需要了解有Browser Cookie Limits所以我建议你把它减少到256

您的解决方案已修

如果我们要使用您的解决方案,我们需要一些修改

session_start();

// Strong private key stored Securly stored
// Used SESSION For demo
$privateKey = isset($_SESSION['key']) ? $_SESSION['key'] : mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);

$my = new SignedCookie($privateKey);
$my->setCookie("test", "hello world", time() + 3600);
echo $my->getCookie("test");

产量

  hello world 

但数据存储如下:

这只是使用hash_hmac来签署和验证你的值,并使用随机变量来确保坏人无法构建可能值的表,因为他们真的不必破坏哈希..可以只研究它可以也使用以前使用过的有效例如.

10 Cookies = AAAA
1 Cookie = BBBB

他可以使用有效会话登录并将cookie从BBBB更改为AAAA,因此即使您不存储到数据库,也始终包含随机参数

你还可以删除这样的cookie:

 $my->setCookie("test", null, time() - 3600);

使用简单类

class SignedCookie {
    private $prifix = '$x$';
    private $privateKey;

    function __construct($privateKey) {
        $this->privateKey = $privateKey;
    }

    function setCookie($name, $value, $expire, $path = null, $domain = null, $secure = null, $httponly = null) {
        $value = $value === null ? $value : $this->hash($value, mcrypt_create_iv(2, MCRYPT_DEV_URANDOM));
        return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    }

    function getCookie($name, $ignore = false) {
        if (! isset($_COOKIE[$name]) || empty($_COOKIE[$name]))
            return null; // does not exist

        if ($ignore === false) {
            if (substr($_COOKIE[$name], 0, 3) !==  $this->prifix)
                return - 1; // modified

            $data = pack("H*", substr($_COOKIE[$name], 3)); // Unpack hex

            $value = substr($data, 32, - 2); // Get Value
            $rand = substr($data, - 2, 2); // Get Random prifix

            if ($this->hash($value, $rand) !== $_COOKIE[$name])
                return - 1; // modified

            return $value;
        }
        return $_COOKIE[$name];
    }

    function hash($value, $suffix) {
        // Added random suffix to help the hash keep changing
        return $this->prifix . bin2hex(hash_hmac('sha256', $value . $suffix, $this->privateKey, true) . $value . $suffix);
    }
}

结论

您不是安全专家Just Use所以只需使用SSL(SSL also has its issues but far better)或查找现有的安全身份验证服务. @ircmaxell最近让我想起了Schneier’s Law

@Baba: “surprise” is the enemy of security. The ONLY thing that should be secret is the private key. Remember Schneier’s Law: Anyone can invent an encryption scheme that they themselves can’t break. My answer is based on tried and true cryptographic principles.

我认为你也应该接受这个建议.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐