【问题标题】:Filtering URLS for output PHP过滤输出 PHP 的 URL
【发布时间】:2011-08-16 21:27:18
【问题描述】:

我想确保诸如 javascript:alert('a'); 和 vbscript 变体等不允许被列入白名单https?|ftp That's easy enough: ^(?:https?|ftp):// 但是我怎样才能允许相对网址呢? 比如../../../blah和./blah还有/images/img.png

也就是说使用^(?:(?:https?|ftp)://|[./])安全吗?

我已经四处询问,可能的解决方案可能是: 解析网址

如果 !scheme 或 scheme == http 或 scheme == https 或 scheme == ftp 或 scheme == mailto

【问题讨论】:

  • 你到底想做什么,你想保护什么?
  • XSS,我正在尝试过滤 URL 以进入

标签: php security


【解决方案1】:

您可以使用parse_url 代替正则表达式并检查scheme 是否为空或httphttpsftp 之一:

$components = parse_url($url);
if (!isset($url['scheme']) || in_array(strtolower($url['scheme']), array('http', 'https', 'ftp'))) {
    // valid
} else {
    // invalid
}

【讨论】:

  • 是的,我在 5 分钟前将其添加到我的问题中。 :)
  • @John:我没有注意到这一点。 :)
【解决方案2】:

另见:Sanitizing strings to make them URL and filename safe?

我正在尝试过滤 URL 等 进入<a href=""<img src=""

要小心,因为有可能仅使用“开头为”正则表达式“突破”属性。例如,我可以提供http://safeurl.com" onclick="alert('xss attack'),当插入到您的属性中时,您将拥有:

<a href="http://safeurl.com" onclick="alert('xss attack')">

确保urlencode() 值以及您正在执行的任何其他安全措施。

我可能会考虑反对允许../../relative/urls 或者可能像Gumbo 所建议的那样使用 parse_url。

查看OWASP.org 上的信息以获得更多建议。

【讨论】:

  • 谢谢,我打算在将数据放入属性之前使用 hrtmlentities 正确转义数据。我不确定应该使用 urlencode() 吗?
  • 为了安全起见,我会在每个斜线段上使用 urlencode()。这绝对值得为它编写一个函数,一些非常可靠和偏执的东西。
猜你喜欢
  • 2021-12-23
  • 1970-01-01
  • 2011-01-21
  • 2011-08-30
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 2014-06-15
  • 2021-07-02
相关资源
最近更新 更多