Saturday, April 5, 2008

J2EE / ASP.Net XSS Protection

J2EE

We again leverage Hacme Books for an example vulnerable code.

Here the victim requests feedbackitem that may potentially comprise malicious code.

We fix this using output encoding method. Here we use Struts bean:write tag that supports output filtering of dangerous characters in the HTTP Response by default.

As you might have noticed, we did not do any input validation and instead accepted the malicious code in first place. Depending on the use cases or the functional requirements, it might or it might not be required. If needed, Struts Validator class could be used. As a best practice it is always recommended to do input validation as well.

ASP.Net

Below is a vulnerable code Hacme Bank.

string messageSubject = txtSubject.Text;
string messageText = txtText.Text;

Here txtSubject.Text and txtText.Text could be injected with malicious code.

However if we use Microsoft Anti-Cross Site Scripting Library the malicious code would be encoded when displayed to a victim and hence rendered harmless.

string messageSubject = AntiXss.HtmlEncode(txtSubject.Text);
string messageText = AntiXss.HtmlEncode(txtText.Text);

Again we allowed the application to accept malicious input in first place. If threat profiling of use cases necessitate, ASP.Net in-built validation routine called RegularExpressionValidator could be leveraged to filter the unwanted input.

The example below enforces txtSubject.Text and txtText.Text to accept alphabets and numbers only.

1 comment: