Why label x = txtName.Text; comes under XSS attack

2020-06-23 01:38发布

问题:

I have the following code:

label x = txtName.Text; 

When the security team analyzed the dll they said it was possible to perform an XSS attack on the above code. I know the textbox Text property does not prevent an XSS attack, so what should I do now?

Will the following amendment resolve the issue?

label x = Server.HtmlEncode(txtName.Text); 

回答1:

I am assuming you are talking about a WebForms Label - it is not clear from the question (post real code!)

This is a problem with the design of ASP.NET WebForms. Many elements have a property called Text, but the property does different things depending on the element.

You would hope that setting Text on a control would set its plain textual content. This safe operation is what the name would seem to imply. And that is the case on these controls:

  • TextBox
  • Button
  • ImageButton
  • ListItem

Unfortunately, on a bunch of other controls, the property of the same name actually sets the HTML markup in the element. So if you have a text string with <b> in it, you get some bold text instead of the letter b in some angle brackets. And if the text has strings such as <script> in it, code will be executed on the browser, resulting in security problems.

Some of these unfortunate unsafe controls are:

  • Label
  • HyperLink
  • LinkButton
  • RadioButton
  • Checkbox
  • TableCell

To use these safely, you must HTML-encode all content you write to the Text property.

Finally there is one control that swings both ways:

  • Literal

By default this sets HTML markup (boo!), but if you set the Mode="Encode" property, it sets text instead.

This is of course all very confusing and no way to design a web framework, but that's what we've got to work with.



回答2:

I don't think label x = txtName.Text; is valid C#. I assume you meant x.Text = txtName.Text; where x is the ID of a Label.

This is a problem because what if I entered <script>alert('XSS!')</script> in the Textbox? My input could be rendered to the page and executed as script. That simple of an example may not work, but there are many tricks to getting XSS to work.

You can fix this by encoding the input before displaying on the page, and I would recommend Microsoft AntiXSS for that task. I also agree with the comment that you should ask your security team how to fix it.