未引用的 HTML 属性中的 encodeURIComponent

信息安全 xss javascript html
2021-09-07 09:34:24

我的直觉是以下内容应该是可攻击的:

$("<td><a href=somefile.php?url="+encodeURIComponent(somevar)+">Download Here</a></td>");

相比之下

$("<td><a href=\"somefile.php?url="+encodeURIComponent(somevar)+"\">Download Here</a></td>");

对于跨站点脚本攻击,如果用户可以控制somevar,但我似乎无法找到具体的攻击。我弄错了吗?

1个回答

来自MDN

encodeURIComponent 转义除以下字符外的所有字符:字母、十进制数字、

- _ . ! ~ * ' ( )

您通常需要一个空格字符来添加另一个属性(例如onclick),不幸的是这将被编码为 URI 的一部分。

但是,来自OWASP XSS(跨站点脚本)预防备忘单

不带引号的属性可以用许多字符分解,包括 [space] % * + , - / ; < = > ^ and |

因此,您可能想尝试使用-or*字符来尝试创建新属性。

例如设置somevarhttp://www.example.com-onclick=alert('xss')http://www.example.com*onclick=alert('xss')

您的里程可能因浏览器而异,不幸的是,=仍然是 URL 编码的,因此您也需要克服这个障碍。因此,即使该值没有被引用或正确编码,也可能无法将此编码缺陷转化为 XSS 漏洞利用。

您的第二个示例更安全,尽管该值实际上应该是 HTML 编码的:

$("<td><a href=somefile.php?url=\""+htmlEscape(encodeURIComponent(somevar))+"\">Download Here</a></td>");

哪里htmlEscape是:-

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}