且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

htmltextwriter 和跨站点脚本

更新时间:2023-01-08 16:03:35

是的,它确实可以在写入 HTML 文档时保护您免受 XSS 的侵害,但是 HtmlTextWriter.WriteEncodedText 方法必须使用.

Yes, it does protect you from XSS when writing into a HTML document, however the HtmlTextWriter.WriteEncodedText method must be used.

' Assign a value to a string variable, 
' encode it, and write it to a page.
colHeads = "<custID> & <invoice#>" 
writer.WriteEncodedText(colHeads)
writer.WriteBreak()

会输出

&lt;custID&gt; &amp; &lt;invoice#&gt;

到流.

请注意,使用 WriteEncodedText 仅适用于输出到 HTML 上下文.当输出到 JavaScript 时,它们应该被使用:

Note that using <%: and WriteEncodedText are only suitable for outputting to a HTML context. They should not be used when outputting into JavaScript:

<script>
var myVariable = '<%: thisIsWrong %>';
</script>

在这种情况下,应该使用 HttpUtility.JavaScriptStringEncode(与 括号也可以防止错误的 HTML 编码).此函数还正确编码特殊字符,因此如果 </script> 将在脚本标签中呈现以尝试关闭准备进行 XSS 攻击的 HTML 脚本标签,它将呈现为:

In this context HttpUtility.JavaScriptStringEncode should be used (with <%= %> brackets to prevent incorrectly HTML encoding too). This function also correctly encodes special characters, so if </script> was to be rendered in a script tag in an attempt to close the HTML script tag ready for an XSS attack, it would be rendered as:

u003c/scriptu003e

这是 JavaScript 将其理解为 </script> 的正确编码,但浏览器不会将其解释为文字结束脚本标记.一些天真的编写的 JavaScript 编码例程不会转换它,因为序列不包含 "' 字符.我只是想我会为找到此帖子的其他人提及防止 XSS 的一些细微差别.

which is the correct encoding for JavaScript to understand it as </script>, but without the browser interpreting it as a literal closing script tag. Some naively written JavaScript encoding routines would not convert this because the sequence does not contain , " or ' characters. I just thought I'd mention some of the nuances of preventing XSS for other people finding this post.

如果你不确保关闭脚本标签没有被渲染,那么像这样的攻击是可能的

If you don't make sure that closing script tags are not rendered, then an attack like so is possible

</script><script>alert(1)</script>

在浏览器中呈现为

<script type="text/javascript">

alert('</script><script>alert(1)</script>');

</script>

浏览器将解释以 alert('</script> 结尾的脚本标签,并简单地执行新脚本标签中的内容.

and the browser will interpret the script tag ending at alert('</script> and simply execute what is in the new script tag.

使用 JavaScriptStringEncode 函数,这是安全的,因为它呈现为:

With the JavaScriptStringEncode function this is safe as it is rendered as:

<script type="text/javascript">

alert('u003c/scriptu003eu003cscriptu003ealert(1)u003c/scriptu003e');

</script>

不包含供浏览器解释的</script>.

which does not contain </script> for the browser to interpret.