xss谝:
CSP:设置白名单,只允许特定来源的脚本和资源加载,阻止不在白名单中的脚本执行
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:;
XSS 保护头
X-XSS-Protection: 1; mode=block
php中使用 htmlspecialchars
设置 SameSite Cookie
SameSite=Strict
html转义:
function escapeHTML(str) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
过滤
function escapeAttribute(attr) {
return attr
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
移除
function stripHTMLTags(str) {
return str.replace(/<\/?[^>]+(>|$)/g, "");
}
使用 DOMPurify
越权防御:
身份验证
权限检查
数据加密
会话重新生成
session_set_cookie_params([
'httponly' => true,
'secure' => isset($_SERVER['HTTPS']),
'samesite' => 'Strict'
]);
session_start();
CSRF
cookie添加签名:
// 设置 Cookie 时
$cookieValue = "user_data";
$secretKey = "your-secret-key";
$signature = hash_hmac('sha256', $cookieValue, $secretKey);
setcookie("auth_cookie", $cookieValue . '.' . $signature);
// 读取 Cookie 时验证
list($value, $signature) = explode('.', $_COOKIE['auth_cookie']);
$expectedSignature = hash_hmac('sha256', $value, $secretKey);
if (hash_equals($expectedSignature, $signature)) {
// 验证成功
} else {
// Cookie 被篡改
setcookie("auth_cookie", "", time() - 3600); // 删除无效 Cookie
exit("Invalid cookie.");
}
标签:网络安全,src,渗透,replace,Cookie,signature,cookie,div,写法
From: https://www.cnblogs.com/mengluo/p/18517145