Question

Using Microsoft's AntiXssLibrary, how do you handle input that needs to be edited later?

For example:

User enters: <i>title</i>

Saved to the database as: <i>title</i>

On an edit page, in a text box it displays something like: &lt;i&gt;title&lt;/i&gt; because I've encoded it before displaying in the text box.

User doesn't like that.

Is it ok not to encode when writing to an input control?

Update:

I'm still trying to figure this out. The answers below seem to say to decode the string before displaying, but wouldn't that allow for XSS attacks?

The one user who said that decoding the string in an input field value is ok was downvoted.

Was it helpful?

Solution

Looks like you're encoding it more than once. In ASP.NET, using Microsoft's AntiXss Library you can use the HtmlAttributeEncode method to encode untrusted input:

<input type="text" value="<%= AntiXss.HtmlAttributeEncode("<i>title</i>") %>" />

This results in

<input type="text" value="&#60;i&#62;title&#60;&#47;i&#62;" />
in the rendered page's markup and is correctly displayed as <i>title</i> in the input box.

OTHER TIPS

Your problem appears to be double-encoding; the HTML needs to be escaped once (so it can be inserted into the HTML on the page without issue), but twice leads to the encoded version appearing literally.

You can call HTTPUtility.HTMLDecode(MyString) to get the text back to the unencoded form.

If you are allowing users to enter HTML that will then be rendered on the site, you need to do more than just Encode and Decode it.

Using AntiXss prevents attacks by converting script and markup to text. It does not do anything to "clean" markup that will be rendered directly. You're going to have to manually remove script tags, etc. from the user's input to be fully protected in that scenario.

You'll need to strip out script tags as well as JavaScript attributes on legal elements. For example, an attacker could inject malicious code into the onclick or onmouseover attributes.

Yes, the code inside input boxes is safe from scripting attacks and does not need to be encoded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top