Simple implementation of JSP using filters to prevent SQL injection

  • 2021-11-10 10:28:25
  • OfStack

What is an SQL injection attack? Quote Baidu Encyclopedia's explanation:

sql injection _ Baidu Encyclopedia:

The so-called SQL injection is to deceive the server to execute the malicious SQL command by inserting the SQL command into the query string submitted by the Web form or entering the domain name or page request. Specifically, it is the ability to inject (malicious) SQL commands into the background database engine for execution by using existing applications. It can get a database on a website with security vulnerabilities by entering (malicious) SQL statements in Web forms, instead of executing SQL statements according to the designer's intention. [1] For example, many previous film and television websites leaked VIP member passwords, and most of them burst through the query characters submitted by WEB forms, which are particularly vulnerable to SQL injection attacks.

SQL injection attack refers to passing special inputs into Web application programs as parameters, and most of these inputs are combinations of SQL syntax, and then executing SQL statements to perform the operations required by attackers. The main reason is that the programs do not filter the data input by users carefully, resulting in illegal data intrusion into the system.

filter Features:

It allows the user to change an request and modify an response. Filter is not an servlet, it cannot produce an response, it can

request can be pretreated before one request arrives at servlet, and response can also be processed when leaving servlet.

To put it another way, filter is actually an "servlet chaining" (servlet chain). Therefore, any request issued by the user must be processed by filter. We will process the sensitive keywords contained in the user request in filter, and then replace will drop or let the page go to the error page to prompt the user, so that sql injection can be well prevented.

Specific implementation code:

/YourProject/src/com/SqlFilter.java


package com;
import java.io.IOException; 
import java.util.Enumeration; 
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; 
 
// Filter sql Keyword Filter 
public class SqlFilter implements Filter { 
 
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
 
    HttpServletRequest req = (HttpServletRequest) request; 
    HttpServletResponse res = (HttpServletResponse) response; 
    // Get all request parameter names  
    Enumeration params = req.getParameterNames(); 
 
    String sql = ""; 
    while (params.hasMoreElements()) { 
      // Get the parameter name  
      String name = params.nextElement().toString(); 
      //System.out.println("name===========================" + name + "--"); 
      // Get the corresponding value of the parameter  
      String[] value = req.getParameterValues(name); 
      for (int i = 0; i < value.length; i++) { 
        sql = sql + value[i]; 
      } 
    } 
    System.out.println(" Matched string: "+sql); 
    if (sqlValidate(sql)) { 
      res.sendRedirect("error.jsp");  
    } else { 
      chain.doFilter(req, res); 
    } 
  } 
 
  // Calibration 
  protected static boolean sqlValidate(String str) { 
    str = str.toLowerCase();// Unified 1 Convert to lowercase 
    //String badStr = "and|exec";
    String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like"; 
    /*String badStr = "'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" + 
        "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" + 
        "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";  */  // Filtered out sql Keyword, which can be added manually  
    String[] badStrs = badStr.split("\\|"); 
    for (int i = 0; i < badStrs.length; i++) {
      if (str.indexOf(badStrs[i]) !=-1) { 
        System.out.println(" Match to: "+badStrs[i]);
        return true; 
      } 
    } 
    return false; 
  } 
 
  public void init(FilterConfig filterConfig) throws ServletException { 
    //throw new UnsupportedOperationException("Not supported yet."); 
  } 
 
  public void destroy() { 
    //throw new UnsupportedOperationException("Not supported yet."); 
  } 
}

Note that if line 50 above is separated by "", it must be written as follows: String. split ("\"), so that it can be separated correctly, not String. split ("");

/YourProject/WebContent/WEB-INF/web. xml (add filter configuration to filter in web. xml):


<!-- sql Filter -->
   <filter>
    <filter-name>SqlFilter</filter-name>
    <filter-class>com.SqlFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SqlFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

/YourProject/WebContent/error. jsp (page to which sql keywords are detected):


<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!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=utf-8">
<title>error</title>
</head>
<body>
<div align="center">
<br>
<h4> Illegal importation </h4>
<p><input type="button" name="back" value=" Return " onclick="javascript:history.go(-1);"/>
</div>
</body>
</html>

Adding the above filter to your own project can simply prevent SQL injection, and more effective measures should be taken to strictly prevent injection.

Similarly, we can also use filters to achieve sensitive word shielding function, usage and prevent SQL injection similar, self-exploration!

I am the dividing line

-----------------------------------------

More measures to prevent SQL injection:

1. Strictly limit and filter input

2. Valid IP qualification for connections to applications such as databases

3. Minimize system calls in CGI programs

4. Pre-scan system using web scanner

5. Download the program of SQL general anti-injection system, and use it at the head of the page that needs to prevent injection < ! --# include file = "xxx. asp"-- > To prevent others from performing manual injection tests (for asp web pages)

6. Set trap account: Set two accounts, one is an ordinary administrator account and one is an anti-injection account. The anti-injection account is set like an administrator, such as admin, to create an illusion to attract software detection, while the password is more than 1,000 Chinese characters, forcing the software to enter a full-load state when analyzing the account or even run out of resources and crash.


Related articles: