在 PHP 中防止会话劫持、XSS 和网络窃听?

Prevent session hijacking, XSS and network eavesdropping in PHP?

我是PHP的新手,不熟悉会话管理。我正在创建一个电子商务网站,所以我需要创建一个防黑客会话。为此,我在谷歌上搜索了很多关于如何防止会话劫持的信息。我阅读的资料表明我在我的代码中包含了这些函数:

\some saying to use this
 session_start();
session_regenerate_id(true);
\some others saying to use this
 session_start();
session_regenerate_id(); 

…以及使用 HTTPS/TLS。在另一个 Whosebug post 中,我遇到了这个东西:

  • use enough random input for generating the session ID (see session.entropy_file, session.entropy_length, and session.hash_function)
  • use HTTPS to protect the session ID during transmission
  • store the session ID in a cookie and not in the URL to avoid leakage though Referer (see session.use_only_cookies)
  • set the cookie with the HttpOnly and Secure attributes to forbid access via JavaScript (in case of XSS vulnerabilities) and to forbid transmission via insecure channel (see session.cookie_httponly and session.cookie_secure)

但是我看不懂那些。这对我来说只是理论;相反,我想要的是一些 PHP 代码来做这些事情——或者任何实现这些事情的网站,我可以看到 PHP 代码,我们作为例子(最好有一些解释一起去吧)。

Session 劫持 - 有人知道您的 session 身份号码,将其提供给服务器,例如,使用您的权限登录。

XSS - 跨站点脚本,它与过滤不当的表单相关联,允许坏人实施他们的 javascript 代码,例如,您的 cookie 文件。 它们是两种不同的攻击形式。

关于防止session劫持的一些小技巧: 1) 设置 php.ini 指令:

session.use_only_cookies = 1 -> for using only cookie based session ids
session.use_trans_sid = 0 -> disable showing PHPSESSID in browser url

2) 关于 sessions

session_start();// -> starts your session. 
//Your browser will accept http header with session id and store it.
//You will be identified by this session id, usually PHPSESSID

看起来像这样:

GET / HTTP/1.1
Host: example.org
User-Agent: Mozilla Compatible (MSIE)
Accept: text/xml, image/png, image/jpeg, image/gif, */*
Cookie: PHPSESSID=1234

当session启动时,您可以向php全局数组$_SESSION提供任何数据,例如

$_SESSION['var'] = 'abc';

如果有人知道您的 PHPSESSID,他可以将相同的 http header 发送到服务器并开始使用它,就像他就是您一样。

所以,避免它的最佳方法是:

a) 每次提供重要数据时使用 session_regenerate_id()。它将删除旧的 session 号码并生成一个新号码。

b) 在 $_SESSION 中保存您的手指:ip 地址 and/or browser-agent。如果他们不同,那么 - 那不是你。例如:

session_start();
if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
     {
         //some code
     }
}
else
{
     $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}

c) 使用 SSL 提供敏感数据。

希望您会发现它有用。