JavaBlog.fr / Java.lu DEVELOPMENT,Java,WEB Java / Security : Cross Site Scripting (XSS) and SQL injection

Java / Security : Cross Site Scripting (XSS) and SQL injection

Hi,

A simple post concerning the Cross Site Scripting (XSS) and SQL injection which are types of security vulnerability used in Web applications. In SQL-Injection the vulnerability is exploited by injecting SQL Queries as user inputs. In XSS, Javascript code is injected (basically client side scripting) to the remote server (persistente or non-persistent). For more information, Wikipedia is a good source http://en.wikipedia.org/wiki/Cross-site_scripting and http://en.wikipedia.org/wiki/SQL_injection.

Cross Site Scripting (XSS)
XSS injects executable code via the GET or POST parameters in HTTP requests. So, here, I would present an example of special characters (<, >, ‘, …) transformation into their HTML code in order to not be executed by the browser.

An example of XSS attack could be filling javascript code in in form’s field:

"/><script>alert(xss attack);</script>

SQL injection
SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution.
A best-pratice is no use the concatenation of SQL queries and variables like:

"SELECT id, name FROM TABLE_PERSON WHERE id="+myIdVariable;"

…instead, use the parametrized queries via the PreparedStatement.

An example of SQL injection could be:

.../mycontext/myservice.do?name=12&id=123' AND '1'=='1'--

Solution and implementation
First, we create HTTP filter RequestWrappingFilter in order to intercept the HTTP request configured in the web.xml file:

<filter>
<filter-name>RequestWrappingFilter</filter-name>
<filter-class>com.huo.filter.RequestWrappingFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>RequestWrappingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

… the goal of this filter is to wrapper the request into an own-coded wrapper MyHttpRequestWrapper which transforms:

package com.huo.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletReponse;
import javax.servlet.http.HttpServletRequest;

public class RequestWrappingFilter implements Filter{

	public void doFilter(ServletRequest req, ServletReponse res, FilterChain chain) throws IOException, ServletException{
		chain.doFilter(new MyHttpRequestWrapper(req), res);
	}

	public void init(FilterConfig config) throws ServletException{
	}

	public void destroy() throws ServletException{
	}
}
package com.huo.filter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.StringEscapeUtils;

public class MyHttpRequestWrapper extends HttpServletRequestWrapper{
	private Map<String, String[]> escapedParametersValuesMap = new HashMap<String, String[]>();

	public MyHttpRequestWrapper(HttpServletRequest req){
		super(req);
	}

	@Override
	public String getParameter(String name){
		String[] escapedParameterValues = escapedParametersValuesMap.get(name);
		String escapedParameterValue = null; 
		if(escapedParameterValues!=null){
			escapedParameterValue = escapedParameterValues[0];
		}else{
			String parameterValue = super.getParameter(name);

			// HTML transformation characters
			escapedParameterValue = org.springframework.web.util.HtmlUtils.htmlEscape(parameterValue);
			
			// SQL injection characters
			escapedParameterValue = StringEscapeUtils.escapeSql(escapedParameterValue);
			
			escapedParametersValuesMap.put(name, new String[]{escapedParameterValue});
		}//end-else
		
		return escapedParameterValue;
	}

	@Override
	public String[] getParameterValues(String name){
		String[] escapedParameterValues = escapedParametersValuesMap.get(name);
		if(escapedParameterValues==null){
			String[] parametersValues = super.getParameterValues(name);
			escapedParameterValue = new String[parametersValues.length];

			// 
			for(int i=0; i<parametersValues.length; i++){
				String parameterValue = parametersValues[i];
				String escapedParameterValue = parameterValue;
				
				// HTML transformation characters
				escapedParameterValue = org.springframework.web.util.HtmlUtils.htmlEscape(parameterValue);
			
				// SQL injection characters
				escapedParameterValue = StringEscapeUtils.escapeSql(escapedParameterValue);
			
				escapedParameterValues[i] = escapedParameterValue;
			}//end-for
			
			escapedParametersValuesMap.put(name, escapedParameterValues);
		}//end-else
		
		return escapedParameterValues;
	}
}

That’s all.

Best regards,

Huseyin OZVEREN

8 thoughts on “Java / Security : Cross Site Scripting (XSS) and SQL injection”

  1. Hi,
    If we need to store data in DB doing encoding at this HTTP request level will not allow us to store the data. Can you please provide workaround for if we need to store data
    .

    Regards,
    Siva.

      1. Hi Ozveren,
        As you mentioned the HTTP parameters with special characters (, ‘, …) into HTML codes via the htmlescape. In this scenario if we are doing htmlescape in http request which carries data that need to be stored in database , then storing the values which have been converted wouldn’t be a problem ?.

        I have doubt with following code , I think we are missing an else loop
        if(escapedParameterValues==null){

        String[] parametersValues = super.getParameterValues(name);

        escapedParameterValue = new String[parametersValues.length];

        do we need to close the if loop and start a new one for else ?

        for(int i=0; i<parametersValues.length; i++)
        {

        }//end-for
        60

        61
        escapedParametersValuesMap.put(name, escapedParameterValues);
        62
        }//end-else
        63

        64
        return escapedParameterValues;
        65
        }

      2. As you mentioned the HTTP parameters with special characters (, ‘, …) into HTML codes via the htmlescape. In this scenario if we are doing htmlescape in http request which carries data that need to be stored in database , then storing the values which have been converted wouldn’t be a problem ?.

        I have doubt with following code , I think we are missing an else loop
        if(escapedParameterValues==null){

        String[] parametersValues = super.getParameterValues(name);

        escapedParameterValue = new String[parametersValues.length];

        do we need to close the if loop and start a new one for else ?

        for(int i=0; i<parametersValues.length; i++)
        {

        }//end-for
        60

        61
        escapedParametersValuesMap.put(name, escapedParameterValues);
        62
        }//end-else
        63

        64
        return escapedParameterValues;
        65
        }

        1. Hi,

          In the “getParameterValues” method, it is not necessary to close the “if” instruction and start a new “else” instruction, because the value of “escapedParameterValues” variable is not null and is already transformed:
          l.42 : String[] escapedParameterValues = escapedParametersValuesMap.get(name);
          l.43 : if(escapedParameterValues==null){….

          For your question concerning the data which modified for the insertion in database, you could use the org.springframework.web.util.HtmlUtils.unescapeHtml(…) method
          in order to transform the HTML codes into special characters (<, >, ‘, …),
          but the characters modified in order to prevent the SQL injection must not be modified.

          Kind regards,

          1. Does the above applicable for spring framework as we will be passing all datas as in viewmodel in post request

    1. You are right, HttpServletRequestWrapper is class (not an interface), I have changed the example in article (quick copy/paste).

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post