Wednesday, March 10, 2021

Handling Cross-Site Scripting (XSS) in Java

Cross-site scripting (XSS) is a type of security vulnerability in web applications where an attacker injects malicious scripts through some kind of user input (like input boxes, URL parameters, HTML headers, etc)

It is important to prevent XSS attacks to safeguard the confidentiality, integrity, and availability of the information of the web application. The two main cross-site scripting flaws are reflected and stored:

Reflected XSS

Malicious content from a user request is displayed to the user or it is written into the page after from server response. For instance, in the next screenshot, the credit card number field is vulnerable. After the number, there is a script to be injected:

<script src="data:text/javascript;base64,YWxlcnQoJ215IGphdmFzY3JpcHQgaGVyZScp" defer=""></script> 

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

When the purchase button is clicked, the alert windows is displayed:

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

A patch to the flaw in Java


When you have a String RequestParam, avoid handling it without sanitization:

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

The OWASP Java encoder has a method called forHtml for that purpose:

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

Stored XSS


The payload is persisted. For example, in the next screenshot, you can see that a script is added as a comment. When the page is loaded the script is executed and printed as part of the code.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

A patch to the flaw in Java


The solution is to sanitize the RequestBody before handling it:

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

Now, the comment is printed as text, but it is not executed:

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Prep

Source: javacodegeeks.com

Related Posts

0 comments:

Post a Comment