在登录期间,我使用以下功能设置Cookie和会话
protected function validateUser($userid, $ckey=0, $rememmber=0) {
session_start();
session_regenerate_id(true); //this is a security measure
$_SESSION['user_id'] = $userid;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
if (isset($remember) && $rememmber == 'on') {
setcookie("user_id", $_SESSION['user_id'], time() + 60 * 60 * 24 * COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time() + 60 * 60 * 24 * COOKIE_TIME_OUT, "/");
}
return true;
}
然后在安全用户页面上,使用user_id检查user_id
以从db获取有关用户的所有重要数据
public function protect() {
session_start();
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT'])) {
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])) {
$this->signout();
exit;
}
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id'])) {
if (isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])) {
/* we double check cookie expiry time against stored in database */
$cookie_user_id = $_COOKIE['user_id'];
$stmt = $this->db->prepare("select `ckey`,`ctime` from `users` where `id` =?") or die($this->db->error);
$stmt->bind_param("i", $cookie_user_id) or die(htmlspecialchars($stmt->error));
$stmt->execute() or die(htmlspecialchars($stmt->error));
$stmt->bind_result($ckey, $ctime) or die($stmt->error);
$stmt->close() or die(htmlspecialchars($stmt->error));
// coookie expiry
if ((time() - $ctime) > 60 * 60 * 24 * COOKIE_TIME_OUT) {
$this->signout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login */
if (!empty($ckey) && is_numeric($_COOKIE['user_id']) && $_COOKIE['key'] == sha1($ckey)) {
session_regenerate_id(); //against session fixation attacks.
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
} else {
$this->signout();
}
} else {
if ($page != 'main') {
header('Location:' . wsurl);
exit();
}
}
}
}
我想知道,为了安全起见,是否足以仅将user_id和user_agent存储在cokkies和session中?如果没有,还有什么?
答案 0 :(得分:4)
$rs_ctime = $this->db->query("select `ckey`,`ctime` from `users` where `id` = -> '$cookie_user_id'<-")
这里似乎是SQL注入。如果你将变量从GET,POST,COOKIE直接传递给sql-query,那么它就是注入的标志。
通常只需存储user_id和user_agent即可。但有些支付服务有时会通过电话发送带有一些代码的短信并进行检查来验证。但它通常用于非常安全的服务
答案 1 :(得分:3)
会话存储在服务器上,您已经在登录后立即按照Wikipedia's Session Hacking Prevention重新生成会话密钥,所以我说你只是存储用户代理和用户ID。但是,我不会在每个安全页面视图之后重新生成会话ID(例如,从session_regenerate_id()
函数中删除validateUser()
)。维基百科建议只在登录时执行一次......除此之外的任何事情都有点失控。我也会将session_start()
从函数中移出,然后在代码的最高位置上移动。
祝你好运!