Java filter prevents SQL injection attacks

Source: Internet
Author: User

Principle, filter all requests containing illegal characters, such as:, & < Select Delete and other keywords, hackers can use these characters for injection attacks, the principle is the background implementation using stitching strings, Case:
The SQL query code for login verification for a web site is

strSQL = "SELECT * from users WHERE (name = '" + userName + "') and (pw = '" + PassWord + "');"

Malicious filling in

userName = "' or ' 1 ' = ' 1"; with password = "' or ' 1 ' = ' 1"; Causes the original SQL string to be filled in as

strSQL = "SELECT * from users WHERE (name = ' or ' 1 ' = ' 1 ') and (pw = ' or ' 1 ' = ' 1 ');"

That is, the SQL command that actually runs becomes the following

strSQL = "SELECT * from Users;"

Therefore, no account password is reached and can be logged into the network station. So SQL injection attacks are commonly known as the hacker's fill-in game.

Achieve three steps:

1, Write Filter

2, configuration XML

3, Configuration error.jsp

Filter code;


Package cn.kepu.filter;

Import java.io.IOException;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Set;

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;
Import Javax.servlet.http.HttpServletResponse;
/**
* Prevent SQL injection, custom filter www.2cto.com
* Cn.kepu.filter.SqlInjectFilter.java
* @author FFR
* Created at 2012-7-12
*/
public class Sqlinjectfilter implements Filter {

private static list<string> Invalidsql = new arraylist<string> ();
private static String error = "/error.jsp";
private static Boolean debug = FALSE;

public void Destroy () {

}
public void DoFilter (ServletRequest req, servletresponse Res,
Filterchain FC) throws IOException, Servletexception {
if (Debug) {
SYSTEM.OUT.PRINTLN ("Prevent SQL Inject filter works");
}
HttpServletRequest request = (httpservletrequest) req;
HttpServletResponse response = (httpservletresponse) res;
map<string, string> params = Request.getparametermap ();
set<string> keys = Params.keyset ();
for (String Key:keys) {
String value = Request.getparameter (key);
if (Debug) {
SYSTEM.OUT.PRINTLN ("Process params <key, Value>: <" +key+ "," +value+ ">");
}
for (String Word:invalidsql) {
if (word.equalsignorecase (value) | | value.contains (word)) {
if (Value.contains ("<")) {
Value = Value.replace ("<", "<");
}
if (Value.contains (">")) {
Value = Value.replace (">", ">");
}
Request.getsession (). SetAttribute ("Sqlinjecterror", "the request parameter \" "+value+" \ "contains keyword: \" "+word+" \"");
Response.sendredirect (Request.getcontextpath () +error);
Return
}
}
}
Fc.dofilter (req, res);
}
public void init (Filterconfig conf) throws Servletexception {
String sql = Conf.getinitparameter ("Invalidsql");
String errorpage = conf.getinitparameter ("error");
String de = Conf.getinitparameter ("Debug");
if (errorpage! = null) {
Error = ErrorPage;
}
if (SQL! = null) {
Invalidsql = Arrays.aslist (Sql.split (""));
}
if (de! = null && boolean.parseboolean (DE)) {
debug = true;
System.out.println ("Preventsqlinject Filter staring ...");
System.out.println ("Print filter Details");
SYSTEM.OUT.PRINTLN ("Invalid words as Fllows (split with blank):");
for (String S:invalidsql) {
System.out.print (s+ "");
}
System.out.println ();
SYSTEM.OUT.PRINTLN ("error page as Fllows");
SYSTEM.OUT.PRINTLN (Error);
System.out.println ();
}
}
}
The following configuration is added to the 2.web.xml:

[HTML]
<filter>
<filter-name>PreventSqlInject</filter-name>
<filter-class>cn.kepu.filter.SqlInjectFilter</filter-class>
<!--filter word, split with blank--
<init-param>
<param-name>invalidsql</param-name>
<param-value>select Insert Delete from update create Destory drop alter and OR like exec Count Chr mid master Trunca Te Char declare; -'% < ></param-value>
</init-param>
<!--error page-
<init-param>
<param-name>error</param-name>
<param-value>/error.jsp</param-value>
</init-param>
<!--Debug--
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PreventSqlInject</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

3, add error.jsp in root directory
[Plain]
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
<%
String path = Request.getcontextpath ();
%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title> anti-SQL injection Systems </title>

<body>
This is an anti-SQL injection system that automatically filters your request, please replace the request string.
<%=session.getattribute ("Sqlinjecterror")%>
<p><a href= "<%=path%>" > click here to return </a></p>
</body>

Java filter prevents SQL injection attacks

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.