Serverside validation to block or restrict special / bad characters of all input fields of a web page in Java Example

 XSS (Cross-site Scripting) is one of the most common attack on web application. One of the solution for this XSS vulnerability is client and server side validation to block the special (bad) characters like < > ! {} , etc and keywords like script , xp_ , truncate , etc. As Javascript/ client side validation may be bypassed, server side validation is mandatory. So how to block bad characters for the whole web application? It is easy to write a method (in our example checkSplChrs(String str)) to check whether a field contains bad characters or not. But web application may have lot of pages and each page may have lot of input fields. So it is better to create a servlet filter class to call the above method so that each parameters in the request can be validated.

Now let us write code for servlet filter class and checkSplChrs method.

Filter Class (SpecialFilter.java)
package Filters;

import java.util.Iterator;
import java.util.Map;

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

public class SpecialFilter implements Filter {
	private FilterConfig config;

	public SpecialFilter() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
		config.getServletContext().log("Filter  started");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws java.io.IOException, ServletException {
		HttpServletRequest req = null;
		boolean splchr_flag = false;

		Map inputFields = null;

		inputFields = request.getParameterMap();

		if (inputFields != null) {

			Iterator field_iter = inputFields.keySet().iterator();

			while (field_iter.hasNext())

			{

				String param_name = (String) field_iter.next();

				String[] param_value = (String[]) inputFields.get(param_name);

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

					System.out.println("Field=" + param_name + " Entered Value"
							+ param_value[i]);

					if (checkSplChrs(param_value[i])) {

						splchr_flag = true;

						break;

					}

				}

				if (splchr_flag) {
					break;
				}

			}

		}

		if (splchr_flag) {

			try {

				request.getRequestDispatcher("/splCharactersError.jsp").forward(request, response);

			} catch (Exception ex) {

				ex.printStackTrace();

			}

		} else
			chain.doFilter(request, response);
	}

	public void destroy() {
	}

	// function to check a parameter value contains special characters or not

	public static boolean checkSplChrs(String inputStr) {
		System.out.println("inputstr" + inputStr);

		boolean splchr_flag = false;

		String[] splChrs = { "<", ">", "script", "alert", "truncate", "delete",
				"insert", "drop", "null", "xp_", "<>", "!", "{", "}", "`",
				"input" }; // include spl characters as per your
							// requirement

		for (int i = 0; i < splChrs.length; i++) {
			System.out.println("spl chr" + splChrs[i]);

			if (inputStr.indexOf(splChrs[i]) >= 0) {

				splchr_flag = true; // bad character are available

				break;

			}

		}

		return splchr_flag;

	}

}

Don’t forget to add the following lines in web.xml for filter class

web.xml
	<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Serverside Validation</display-name>
	
	<filter>

		<filter-name>SpecialFilter</filter-name>

		<filter-class>Filters.SpecialFilter</filter-class>

	</filter>

	<filter-mapping>

		<filter-name>SpecialFilter</filter-name>

		<url-pattern>/*</url-pattern>

	</filter-mapping>
</web-app>
JSPs for Input, Result and Error Page:
InputPage.jsp

The below page contains two input fields that accept name and address

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Input Page</title>
</head>
<body>
	<form action="ProcessInput">
		<div>
			Enter Name: <input name="name" type="text" />
			Enter Address: <textarea name="address"></textarea>
			 <input	type="submit" />
		</div>
	</form>
</body>
</html>
ProcessInput.java

This below servlet  (ProcessInput.java) and result page (result.jsp) are called when all the  input fields in the input page does not contain any bad/special characters

package javaonline;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Process
 */
@WebServlet("/ProcessInput")
public class ProcessInput extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProcessInput() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = request.getParameter("name");

		System.out.println("Name = " + name);
		request.getRequestDispatcher("/result.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		doGet(request, response);

	}

}
result.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result</title>
</head>
<body>
	<div>
		Name:
		<%=request.getParameter("name")%>
	</div>

</body>
</html>
splCharactersError.jsp

If any input field contains bad/special character, then the below  error page is  called.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error</title>
</head>
<body>
	<div>Special characters / Keywords like <, >, drop, insert,
		script, alert, null, truncate, delete, xp_, ,<>, !, {, } are not
		allowed as input.</div>

</body>
</html>

For running the application for eg. TestWeb

call the URL

http://localhost:8080/TestWeb/InputPage.jsp

server validation input

Submitting the above input page results the error page as given below because the address field in the input page contains special characters (<>)

server validation error

 

 

 

Leave a Reply