JSP uses filters to prevent simple implementation of SQL injection. jsp Filters use SQL Injection

Source: Internet
Author: User

JSP uses filters to prevent simple implementation of SQL injection. jsp Filters use SQL Injection

What is SQL injection attacks? Baidu encyclopedia's explanation:

SQL Injection _ Baidu Encyclopedia:

SQL injection is to insert SQL commands into Web forms to submit or enter query strings for domain names or page requests, and finally fool the server to execute malicious SQL commands. Specifically, it uses existing applications to inject (malicious) SQL commands into the background database engine for execution. It can input (malicious) SQL commands in Web forms) SQL statements get a database on a website with security vulnerabilities, instead of executing SQL statements according to the designer's intent. [1] For example, most of the previous VIP member passwords leaked by many video websites are exposed by submitting query characters through WEB forms. Such forms are particularly vulnerable to SQL injection attacks.

SQL injection attacks are introduced to Web applications by constructing special input as parameters. These inputs are mostly combinations in SQL syntax, attackers can execute SQL statements to perform the operations they want. The main reason is that the program does not carefully filter user input data, resulting in illegal data intrusion into the system.

Filter function:

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

Pre-processing the request before a request arrives at the servlet. You can also process the response when leaving the servlet.

In other words, the filter is actually a "servlet chaining" (servlet chain ). therefore, any request sent by the user must be processed by the filter. We can process the sensitive keywords contained in the request in the filter, and then replace the request or let the page go to the error page to prompt the user, this prevents 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; // Filter public c that filters SQL keywords Lass SqlFilter implements Filter {public void doFilter (ServletRequest request, response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; inclures = (response) response; // obtain all request parameter names Enumeration params = req. getParameterNames (); String SQL = ""; while (params. hasMoreElements () {// obtain the parameter name Strin. G name = params. nextElement (). toString (); // System. out. println ("name ======================" + name + "--"); // obtain the 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) ;}// verify protected static boolean sqlV Alidate (String str) {str = str. toLowerCase (); // convert to lower case // 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 | sel Ect | delete | update | order | by | count | * | "+" chr | mid | master | truncate | char | declare | or |; |-| -- | + |, | like | // |/| % | # "; * // The SQL keyword filtered out. 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 ("matched 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 the above 50th rows are separated by "|", they must be written as follows: String. split ("\ |"), in order to correctly separate, cannot use String. split ("| ");

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

<!-- 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 to which SQL keywords are redirected 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 above filter to your project can simply prevent SQL injection. More effective measures are required to strictly prevent injection.

Similarly, we can also use filters to shield sensitive words. The usage is similar to preventing SQL injection, so we can explore it on our own!

I am a split line

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

More measures to prevent SQL injection:

1. strictly restrict and filter input

2. Restrict valid IP addresses for some applications such as database connections

3. Minimize system calls in CGI programs

4. Use a web scanner to pre-scan the system

5. Download the SQL universal anti-injection system program and use it in the header of the page to prevent injection. <! -- # Include file = "xxx. asp" --> to prevent manual injection tests (for asp webpages)

6. Set a trap account: set two accounts, one being a common Administrator Account and the other being an anti-injection account. The anti-injection account is set like an administrator, such as admin, to attract software detection with the illusion that the password is a Chinese character larger than characters, forces the software analysis account to enter the full load status or even the resources are exhausted and the system crashes.

The simple implementation of the above JSP filter to prevent SQL injection is all the content shared by the editor. I hope to give you a reference, and hope you can provide more support to the customer's house.

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.