开发者

How to escape insecure content in form in order to prevent XSS?

I know that it might stupid but how to escape 开发者_高级运维user input when I show it in a form. I do not mean any output, but especially in the form inputs. Like for example if I have input tag and put the user text in the value.

<input type="text" value="'test' "test" <script>alert('hacked');</script>" />

When I leave it like that it appears correctly

'test' "test" <script>alert('hacked');</script>

no XSS happens, but I do not feel secure cause with other code it could break eventually. Is there something like a browser build-in methods for preventing XSS when putting data in the form or I am missing something?

Edit: I did not say the entire story. Sorry about that. When I use htmlentities or htmlspecialchars I get the escaped data which I do not want. I see this in the input, which is not what was entered :(

'test' &quot;test&quot; &lt;script&gt;alert('hacked');&lt;/script&gt;

I want to prevent XSS and to show the content without changing it at the same time. Is it possible in this case.

How to escape insecure content in form in order to prevent XSS?


You should HTML encode the text, so that it ends up like this:

<input type="text" value="'test' &quot;test&quot; &lt;script&gt;alert('hacked');&lt;/script&gt;" />

You should use the server language to do this. There is no built in support for this in Javascript, so you would have to build a function for that yourself.

In ASP.NET MVC for example it could look like this:

<input type="text" value="<%= Server.HtmlEncode(Model.UserInput) %>" />

MVC 2 also has the <%: %> tag that automatically encodes the text:

<input type="text" value="<%: Model.UserInput %>" />

Edit:

Examine the source of the page in the browser to see what the result is.

It looks like you are escaping the text twice, so that for example " is escaped into &quot; and then into &amp;quot;.


In PHP, use htmlspecialchars() to escape XSS characters in any GET or POST content (for example, if your data is called $_POST['data'], escape that like this: $variable = htmlspecialchars($_POST['data']);). Also, if you're using a database use addslashes() to escape quotes and apostrophes.

Hope this helps.


How are you putting the user text? If you have control, from the server side all languages support encoding the output prior to rendering it on the browser.

As long as you sanitize the output. You can basically allow the user to enter anything that they wish. Then when displaying the content, you just need to encode it so that the browser will not execute it. This can be done from any language PHP, JScript, ASP, VB, C#, etc...


Since the quote mark is used to break out of the input attribute, simply replace all quote marks with &quot;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜