就 XSS 攻击而言,在 php 中回显格式化的 DateTime 是否安全?
Is it safe to echo formatted DateTime in php in terms of XSS attack?
我有一个相当复杂的 Web 应用程序。我需要使用 htmlspecialchars() 函数清理发送到视图(MVC 架构)的所有变量,以防止 XSS 攻击。因为它不仅仅是我发送到视图的原始数据类型,所以我正在实现一个函数,它遍历变量数组并根据它们的类型以不同的方式清理它们中的每一个(我正在使用 gettype() 来区分一下)。
- 使用 htmlspecialchars()
可以简单地清理字符串、整数、布尔值和双精度数
- null 保持为 null
- 数组通过递归过程逐项清理
- 我的自定义 classes 的对象有自己的方法,专门针对每个 class
进行清理
- 日期时间 - ???
我的问题是,当我通过 format() 方法回显它们的内容时,是否需要以某种方式清理 DateTime 对象。 DateTime 对象是否会以某种方式被滥用于 XSS 攻击,或者它们是否被认为是安全的?
我想我应该只将原始数据类型传递给我的视图,但我也有点需要传递对象。
这是我使用的函数:
private function sanitize(array $data)
{
foreach ($data as $propertyName => $propertyValue)
{
if (gettype($propertyValue) === 'array')
{
//Sanitize each element of the array by recursion
$data[$propertyName] = $this->sanitize($data[$propertyName]);
}
else if (gettype($propertyValue) === 'NULL')
{
//NULL can stay NULL
continue;
}
else if ($propertyValue instanceof DatabaseItem)
{
//Sanitize instances of my custom class DatabaseItem
$propertyValue->sanitizeSelf();
}
else if ($propertyValue instanceof DateTime)
{
//TODO - is DateTime safe?
}
else
{
//boolean, integer, double, string
$data[$propertyName] = htmlspecialchars($propertyValue, ENT_QUOTES);
}
}
return $data;
}
短:是的。
如果您的值不是日期,它只会导致错误:
<?php
$d=new DateTime (" <script> malicious </script>");
#test
echo $d->format("y");
/*will cause something like
Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string ( <script> malicious </script>)*/
我有一个相当复杂的 Web 应用程序。我需要使用 htmlspecialchars() 函数清理发送到视图(MVC 架构)的所有变量,以防止 XSS 攻击。因为它不仅仅是我发送到视图的原始数据类型,所以我正在实现一个函数,它遍历变量数组并根据它们的类型以不同的方式清理它们中的每一个(我正在使用 gettype() 来区分一下)。
- 使用 htmlspecialchars() 可以简单地清理字符串、整数、布尔值和双精度数
- null 保持为 null
- 数组通过递归过程逐项清理
- 我的自定义 classes 的对象有自己的方法,专门针对每个 class 进行清理
- 日期时间 - ???
我的问题是,当我通过 format() 方法回显它们的内容时,是否需要以某种方式清理 DateTime 对象。 DateTime 对象是否会以某种方式被滥用于 XSS 攻击,或者它们是否被认为是安全的?
我想我应该只将原始数据类型传递给我的视图,但我也有点需要传递对象。
这是我使用的函数:
private function sanitize(array $data)
{
foreach ($data as $propertyName => $propertyValue)
{
if (gettype($propertyValue) === 'array')
{
//Sanitize each element of the array by recursion
$data[$propertyName] = $this->sanitize($data[$propertyName]);
}
else if (gettype($propertyValue) === 'NULL')
{
//NULL can stay NULL
continue;
}
else if ($propertyValue instanceof DatabaseItem)
{
//Sanitize instances of my custom class DatabaseItem
$propertyValue->sanitizeSelf();
}
else if ($propertyValue instanceof DateTime)
{
//TODO - is DateTime safe?
}
else
{
//boolean, integer, double, string
$data[$propertyName] = htmlspecialchars($propertyValue, ENT_QUOTES);
}
}
return $data;
}
短:是的。 如果您的值不是日期,它只会导致错误:
<?php
$d=new DateTime (" <script> malicious </script>");
#test
echo $d->format("y");
/*will cause something like
Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string ( <script> malicious </script>)*/