JSP uses filters to prevent SQL injection from simple implementation _jsp programming

Source: Internet
Author: User
Tags chr sql injection sql injection attack

What is a SQL injection attack? Citing Baidu Encyclopedia explanation:

SQL injection _ Baidu Encyclopedia:

SQL injection is a query string that inserts a SQL command into a Web form to submit or enter a domain name or page request, and eventually a malicious SQL command that deceives the server. Specifically, it is the ability to inject (malicious) SQL commands into the back-end database engine to execute with an existing application, and it can get a database on a Web site with a security vulnerability by typing (malicious) SQL statements into a Web form, rather than executing the SQL statement as the designer intended. [1] For example, many of the previous video site leaked VIP membership password is mostly through the Web Form submit query characters, such forms are particularly vulnerable to SQL injection attacks.

An SQL injection attack is an incoming Web application by building a special input as a parameter. Most of these inputs are in the SQL syntax of some combination, through the execution of SQL statements to carry out the operation of the attacker, the main reason is that the program does not carefully filter the user input data, resulting in illegal data intrusion system.

Filter function:

It allows users to change a request and modify a response. Filter is not a servlet, it cannot produce a response, it can

Preprocessing the request before a request arrives in the servlet, or you can handle response when you leave the servlet.

To put it another way, filter is actually a "servlet chaining" (servlet chain). Therefore, any request issued by the user must be filtered, we will be in the filter to handle the user request contains the sensitive keywords, and then replace or let the page go to the error page to prompt the user, so that it is good to prevent SQL injection.

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; Filtering the SQL Keyword filter public class Sqlfilter implements filter {public void Dofilter (ServletRequest request, Servletres Ponse response, Filterchain chain) throws IOException, servletexception {httpservletrequest req = (httpservletrequ 
    EST) request; 
    HttpServletResponse res = (httpservletresponse) response; 
 
    Gets all request parameter names enumeration params = Req.getparameternames (); 
    String sql = ""; 
      while (Params.hasmoreelements ()) {//Get parameter name String name = Params.nextelement (). toString (); 
      System.out.println ("name===========================" + name + "--"); Getparameter corresponding value 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); }//Checksum protected static Boolean sqlvalidate (String str) {str = str.tolowercase ();//unified to lowercase//string b
    Adstr = "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|" + "infor mation_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*| "+" Chr|mid|master|truncat e|char|declare|or|;| -|--|+|,|like|//|/|%|  #"; 
    *///filter out the SQL keyword, you can manually add 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 unsupportedoperationexceptio 
  N ("not supported yet."); 
  public void Destroy () {//throw The new unsupportedoperationexception ("not supported yet."); } 
}

Note the 50th line above if you use "|" As a separate word, must be written as follows: String.Split ("\\|"), so that the correct separation, can not use String.Split ("|");

/yourproject/webcontent/web-inf/web.xml (filter add filter configuration 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 (the page where the SQL keyword jumps to) is 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" >
 
 

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

Similarly, we can use filters to implement the masking function of sensitive words, use and prevent SQL injection similar, explore!

I'm a split line.

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

More steps to prevent SQL injection:

1. Strict restrictions and filtration of input

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

3. Minimizing system calls in CGI programs

4. Pre-scan system using Web scanners

5. Download the SQL Universal Anti-injection System program, in the need to prevent injection of the page head with <!--# include file= "xxx.asp"-> To prevent others from manual injection test (for ASP Web pages)

6. Set Trap account: Set up two accounts, one is the ordinary administrator account number, one is the anti-injected account. The anti-injected account is set up very much like the administrator, such as admin, to create an illusion to attract software detection, and the password is greater than thousands of characters in Chinese characters, forcing the software analysis account to enter the full load state or even resource depletion and panic.

The above JSP use filter to prevent SQL injection of simple implementation is small series to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.