Preventing SQL Injection:
Main reason behind sql injection: SQL query acting as a mediator in between the application and database is unable to differentiate the user submitted value and the actual query.
In order to prevent sql injection our query must have a capability to differentiate the user submitted value and the actual query. This can be achieved by using Parametrised query or Stored Procedures instead of ordinary statements.
Illegal Use Of Prepare Statement Makes Your Application Still Vulnerable To SQL Injection.
The below scenario depicts the illegal use of prepare statement.
Preventing XSS Attacks:
XSS — Cross Site Scripting:
XSS involves exploiting the trust that the user have on a company’s website. Example: Any data that is shown on the internet banking site to the user is going to be trusted by the user. If an attacker controls the data that is displayed on the internet banking site then he can lure the user to click malicious links leading to phishing/session hijacking attacks.
There are 3 types of Cross Site Scripting attacks. They are Stored or Persistent XSS attack, Reflected XSS and DOM Based attack. Let us look into the details of each attacks below.
- Stored or Persistent XSS:
2. Reflected XSS:
3. DOM Based XSS:
If an application directly retrieves the data from the url and displays it in the page then it makes the application vulnerable to DOM Based XSS.
HTML characters must be encoded so that the browser will not render and execute the user submitted HTML and script tags.
There is a library package available in OWASP for encoding HTML tags and it can be downloaded from OWASP website. The name of the library file is ESAPI.jar
Once downloaded you have to use it in your application wherever it is required to escape html characters.
Add the jar file in your WEB-INF library folder as shown in the image below
Import the library file in your java file in order to make use of the functions present in the ESAPI jar
Escape the html characters by using the encoder functions in ESAPI jar. Here am going to use ESAPI.encoder().encodeForHTML(arg0) function for escaping the html characters submitted by the user.
Before processing the data here we have escaped all the HTML characters using ESAPI.encoder().encodeForHTML(arg0) which makes our application free from XSS
If an application is vulnerable and multiple scripts have been injected in the database then while retrieving and displaying the data makes the application vulnerable to XSS. Therefore JSP pages has to encode the data and escape the HTML tags before displaying it to the user.
Adding escape functions in JSP Page: