且构网

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

HtmlTextWriter的和跨站点脚本

更新时间:2023-01-08 16:15:52

是的,它并写入到一个HTML文档时,保护你免受XSS然而 HtmlTextWriter.WriteEn codedText 必须使用的方法。

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;

流中。

请注意,使用&LT;%: WriteEn codedText 只适合输出到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.JavaScriptStringEn$c$c$c$c>应使用(与&LT;%=%GT; 括号prevent正确HTML编码太)。这个功能也正常连接codeS特殊字符,所以如果&LT; / SCRIPT&GT; 是在脚本标记中呈现,试图关闭HTML脚本标记准备为XSS攻击,它会被渲染为:

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/script\u003e

这是正确编码JavaScript来把它理解为&LT; / SCRIPT&GT; ,但没有浏览器间preting其当作文字结束脚本标签。有些天真地写的JavaScript编码程序不会转换,是因为该序列中不包含 \\ 字符。我只是想我会提一些preventing 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>

其在浏览器中呈现为

which the renders in the browser as

<script type="text/javascript">

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

</script>

和浏览器会间preT在结束脚本标签警报('&LT; / SCRIPT&GT; 键,只需执行什么是在新的脚本标记

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

随着 JavaScriptStringEn code 的功能,这是安全的,因为它呈现为:

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

<script type="text/javascript">

alert('\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e');

</script>

不包含&LT; / SCRIPT&GT; 为浏览器间preT