问题描述
一个基本脚本,该脚本通过更新所用的CSS来重新设置我的网站的主题,但是这样做的方式不安全,以至于echo值容易受到XSS攻击:
As per a previous question I've got a basic script which re-themes my site by updating the CSS used, but does so in an insecure way that echo's a value that's open to an XSS attack:
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Theme Test</title>
<link rel="stylesheet" type="text/css" href="<?php echo (!isset($_COOKIE['style'])?'normal':$_COOKIE['style']) ?>.css" />
</head>
<body>
<form action="changestyle.php" method="post">
<select name="choice">
<option value="classic" selected>Classic View</option>
<option value="holiday">Holiday View</option>
<option value="normal">Normal View</option>
</select>
<input type="submit" value="Go">
</form>
</body>
</html>
changestyle.php
<?php
$year = 31536000 + time();
setcookie('style', $_POST['choice'], $year);
header('Location: index.php');
exit();
?>
我被告知,规避此类攻击的最佳方法是在 index.php
来验证Cookie是否与硬编码值列表匹配。
I've been advised that the best way to circumvent such an attack is to perform a check in index.php
to verify the cookie matches a list of hard-coded values.
我假设要这样做,我需要更新现有的php语句:
I'm assuming to do this I need to update the existing php statement:
<?php echo (!isset($_COOKIE['style'])?'normal':$_COOKIE['style']) ?>
到类似这样的东西:
$required = array('classic', 'holiday', 'normal');
if(!isset($_COOKIE['style'])) {
echo 'normal';
} else {
// If cookie 'style' matches $required perform echo.
}
虽然不知道如何正确编写此语句。
No idea how to write this statement correctly though..
推荐答案
您需要确保用户输入的Cookie值等于您的硬编码值之一,因此只需确保它在您的数组中:
You need to make sure the user-inputed cookie value is equal to one of your hard-coded values, so just make sure it's in your array:
$required = array('classic', 'holiday', 'normal');
$style_name = 'normal';
if(!empty($_COOKIE['style']) && in_array( $_COOKIE['style'] , $required ))
$style_name = $_COOKIE['style'];
现在 $ style_name
变量包含一个已验证您可以在链接标记echo语句中使用的样式表名称。
Now the $style_name
variable contains a validated stylesheet name which you can use in your link tag echo statement.
这篇关于验证Cookie是否与硬编码值列表匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!