验证cookie与硬编码值列表匹配

时间:2014-07-02 13:39:16

标签: php cookies xss

As per a previous question我有一个基本脚本,它通过更新所使用的CSS来重新定位我的网站,但是以一种不安全的方式这样做,以回应一个值得开放的价值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.
}

不知道如何正确编写此声明..

1 个答案:

答案 0 :(得分:1)

您需要确保用户输入的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语句中使用该名称。

相关问题