Many of us would have performed reflect XSS attack while performing application security assessments. A reflected XSS vulnerability is one of the most predominant vulnerabilities that occur due to a bad way of handling and reflecting the user input.
Cross-site scripting attack has 3 different categories:
- Reflected XSS
- Stored XSS
- DOM based XSS
In this blog, I would like to demonstrate how a reflected XSS attack occurs and how to prevent the vulnerability by following standard secure coding practices. The examples which are provided here are simple and will be helpful to understand the mitigation process step by step
I have created “xss.html” page to get the input from the user.Below is the html page.
Below is the browser view of the “XSS.html page”
Whatever input is provided by the user, the same will be reflected in output as well. Below is the backend java coding to handle the input.
As you can see in “XSS.html”, once the user provides the input and clicks on submit button, a post request will be made and the “CrossSiteScripting” servlet page will be called automatically.
CrossSiteScripting servlet:
I have provided detailed explanation in “Image3” to understand the code flow.
dataReflector Servlet:
Since there is no protection mechanism followed in the coding, it is vulnerable to HTML injection and XSS attack.
Example: XSS attack
As seen above, the attacker is able to produce an alert box on the webpage. As we know, there are many implications of XSS attack. Now, I would like to talk about the mitigation strategy to be implemented in the code.
Mitigations:
Input sanitization:
You can check out the Input sanitization block. As per the code block, only alphanumeric values are accepted in input values. If the condition is not met then automatically “error.html” page will be called.
Example: <script>alert(1)</script> value is provided in input
For invalid input, the application shows error. Thus, we are able to achieve whitelisting the input. Whitelisting the input might vary depends upon the requirement of the developer.
HTML tag escaping or output encoding:
Another way of securing the code is via HTML tag escaping. By implementing this method, all html tag values will be encoded as stated below so that the javascript execution will not occur.
<
renders as<
>
renders as>
&
renders as&
"
renders as"
'
renders as'
Example: <script>alert(1)</script> value is given in input field
As shown above, all the script tags are escaped properly and the end-user will get what he/she has fed. There is no javascript execution here.
Similarly, the developer needs to integrate such a secure coding mechanism based on their use cases.
If you do like this blog, please share and support it.
If you like the content, please follow me on medium and LinkedIn
LinkedIn: https://www.linkedin.com/in/pravin-r-p-oscp-28497712b/