htmltextwriter and cross site scripting

匆匆过客 提交于 2019-12-02 06:48:06
SilverlightFox

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()

will output

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

to the stream.

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>

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

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>

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

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>

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

just tried it sadly it does not protect you from cross site scripting I made an aspx page and in the code behind I put

 protected void Page_Load(object sender, EventArgs e)
    {
        StringWriter stringWriter = new StringWriter();
        using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) {
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write(
            " < script > alert('.Net and the Terrible, Horrible, No Good, Very Bad Script');</ script > ");                   
            writer.RenderEndTag();
        }
        Response.Write(stringWriter);
    }

I ran the page and the javascript alert popped up so I guess htmltextwriter doesn't protect you from cross site scipting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!