验证cookie是否匹配硬编码值列表


Validate cookie matches a list of hard-coded values

根据之前的问题,我有一个基本的脚本,通过更新使用的CSS来重新主题我的网站,但这样做是在一个不安全的方式,echo的值是开放的XSS攻击:

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是否与硬编码值列表匹配。

我假设要做到这一点,我需要更新现有的php语句:

<?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.
}

不知道如何正确地写这个语句…

您需要确保用户输入的cookie值等于您的硬编码值之一,因此只需确保它在您的数组中:

$required = array('classic', 'holiday', 'normal');
$style_name = 'normal';
if(!empty($_COOKIE['style']) && in_array( $_COOKIE['style'] , $required ))
  $style_name = $_COOKIE['style'];

现在,$style_name变量包含一个经过验证的样式表名称,您可以在链接标记echo语句中使用它。