【问题标题】:How to secure an authentication cookie without SSL如何在没有 SSL 的情况下保护身份验证 cookie
【发布时间】:2013-04-21 22:08:45
【问题描述】:

我正在创建一个使用两个会话的登录系统(对于那些不允许使用 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% 安全的,因为某些用户可能会尝试操纵随机字符串,所以我可以使用盐随机密钥,然后使用 hash_hmac 对盐 + 密钥进行 sha512 处理并将其保存为饼干...

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

【问题讨论】:

  • 如果有人能猜出一个有效的 PHP 会话 ID(假设标准会话 ID 长度/复杂性设置),那么您就无法阻止他们。当 PHP 已经在生成随机代码时,生成自己的代码是没有意义的。
  • 随机生成或密钥将更改网站每个条目上的cookie,更新我的数据库和cookie以匹配,每个用户行将不同,每个用户的每个密钥将不同..所以我猜想实现某种算法可能有助于提高安全性?
  • 会话也可以这样做... session_regenerate_id()。您主要是在尝试重新发明轮子。
  • 您可能会发现以下链接很有帮助:web.archive.org/web/20130214051957/http://jaspan.com/…
  • 完全重复:stackoverflow.com/q/5459682/338665stackoverflow.com/q/2336678/338665(我会将其标记为第二个)...

标签: php authentication cookies


【解决方案1】:

简介

当这正是会话正在进行的时候,你为什么要对 cookie 进行身份验证?如果您想更改ID,您可以使用@MarcB 指出的session_regenerate_id 轻松实现。

我的假设

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

  • 将值存储到 Cookie
  • 了解这些值是否已被修改

你已经解决了

我可以使用盐随机密钥,然后使用 hash_hmac 对 salt+key 进行 sha512 处理并将其保存为 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);
    }
}

结论

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

@Baba:“惊喜”是安全的敌人。唯一应该保密的是私钥。记住施奈尔定律:任何人都可以发明一种他们自己无法破解的加密方案。我的回答是基于久经考验的真实密码学原理。

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

【讨论】:

  • 我真的很喜欢这个答案,感谢您抽出时间发布这样的内容。另一个离题的问题是您使用什么应用程序来查看 cookie 数据?
  • F12 in chromeFirebug in Firefox .. 周围有很多工具
猜你喜欢
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2020-01-10
  • 2020-12-08
  • 1970-01-01
  • 2018-07-23
相关资源
最近更新 更多