SoFunction
Updated on 2025-03-08

Several ways Java projects prevent SQL injection

PreparedStatement prevents SQL injection

PreparedStatement has precompiled function, taking the above SQL as an example

The precompiled SQL using PreparedStatement is:

delete from table1 where id= ?

At this time, the SQL statement structure is fixed, regardless of "?" is replaced by any parameter. The SQL statement only believes that there is only one condition after where. When 1001 or  1 = 1 is passed in, the statement will report an error, thereby achieving the effect of preventing SQL injection

#{} in mybatis prevents SQL injection

#{} expression in mybatis prevents SQL injection similar to PreparedStatement, both precompiling SQL statements

Notice

#{} : Parameter placeholder

${}: splicing substitution characters cannot prevent SQL injection, and are generally used for

  • Pass in database objects (such as: database name, table name)

  • order by  the condition after

Filter sensitive vocabulary of requested parameters

Here is the way to write springboot, as follows:

import ;
import .*;
import ;
import ;
import ;
 
/**
  * @Auther: Pikachu
  * @Date: 2023/12/25
  * @Description: sql anti-injection filter
  */
@WebFilter(urlPatterns = "/*",filterName = "sqlFilter")
 @Configuration
 public class SqlFilter implements Filter {
 
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {}
 
     /**
      * @description sql injection filtering
      */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest request = servletRequest;
        ServletResponse response = servletResponse;
        // Get all request parameter names        Enumeration<String> names = ();
        String sql = "";
        while (()){
            // Get the parameter name            String name = ().toString();
            // Get the corresponding value of the parameter            String[] values = (name);
            for (int i = 0; i < ; i++) {
                sql += values[i];
            }
        }
        if (sqlValidate(sql)) {
            //TODO This is the exception being thrown directly. In the front-end interactive project, please encapsulate the error message as the "VO returned by data" object in the front-end and back-end interactive project.            throw new IOException("The parameter in your request contains illegal characters");
        } else {
            (request,response);
        }
    }
 
    /**
      * @description Matching validation
      */
    protected static boolean sqlValidate(String str){
        // Convert to lowercase uniformly        String s = ();
        // Filtered SQL keywords, special characters need to be escaped by adding \\ in front of them.        String badStr =
                "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|"+
                        "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
                        "information_schema.columns|table_schema|union|where|order|by|" +
                        "'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";
        //Use regular expressions for matching        boolean matches = (badStr);
        return matches;
    }
 
    @Override
    public void destroy() {}
}

nginx reverse proxy prevents SQL injection

More and more websites use nginx for reverse proxying, and we can also prevent SQL injection configurations from being configured.

Put the following Nginx configuration file code into the server block, and then restart Nginx

 if ($request_method !~* GET|POST) { return 444; }
 #Using the 444 error code can reduce the load pressure of the server even more. #Prevent SQL injection if ($query_string ~* (\$|'|--|[+|(%20)]union[+|(%20)]|[+|(%20)]insert[+|(%20)]|[+|(%20)]drop[+|(%20)]|[+|(%20)]truncate[+|(%20)]|[+|(%20)]update[+|(%20)]|[+|(%20)]from[+|(%20)]|[+|(%20)]grant[+|(%20)]|[+|(%20)]exec[+|(%20)]|[+|(%20)]where[+|(%20)]|[+|(%20)]select[+|(%20)]|[+|(%20)]and[+|(%20)]|[+|(%20)]or[+|(%20)]|[+|(%20)]count[+|(%20)]|[+|(%20)]exec[+|(%20)]|[+|(%20)]chr[+|(%20)]|[+|(%20)]mid[+|(%20)]|[+|(%20)]like[+|(%20)]|[+|(%20)]iframe[+|(%20)]|[\<|%3c]script[\>|%3e]|javascript|alert|webscan|dbappsecurity|style|confirm\(|innerhtml|innertext)(.*)$) { return 555; }
 if ($uri ~* (/~).*) { return 501; }
 if ($uri ~* (\\x.)) { return 501; }
 #Prevent SQL injection if ($query_string ~* "[;'<>].*") { return 509; }
 if ($request_uri ~ " ") { return 509; }
 if ($request_uri ~ (\/\.+)) { return 509; }
 if ($request_uri ~ (\.+\/)) { return 509; }
 #if ($uri ~* (insert|select|delete|update|count|master|truncate|declare|exec|\*|\')(.*)$ ) { return 503; }
 #Prevent SQL injection if ($request_uri ~* "(cost\()|(concat\()") { return 504; }
 if ($request_uri ~* "[+|(%20)]union[+|(%20)]") { return 504; }
 if ($request_uri ~* "[+|(%20)]and[+|(%20)]") { return 504; }
 if ($request_uri ~* "[+|(%20)]select[+|(%20)]") { return 504; }
 if ($request_uri ~* "[+|(%20)]or[+|(%20)]") { return 504; }
 if ($request_uri ~* "[+|(%20)]delete[+|(%20)]") { return 504; }
 if ($request_uri ~* "[+|(%20)]update[+|(%20)]") { return 504; }
 if ($request_uri ~* "[+|(%20)]insert[+|(%20)]") { return 504; }
 if ($query_string ~ "(<|%3C).*script.*(>|%3E)") { return 505; }
 if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") { return 505; }
 if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") { return 505; }
 if ($query_string ~ "proc/self/environ") { return 505; }
 if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") { return 505; }
 if ($query_string ~ "base64_(en|de)code\(.*\)") { return 505; }
 if ($query_string ~ "[a-zA-Z0-9_]=http://") { return 506; }
 if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") { return 506; }
 if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") { return 506; }
 if ($query_string ~ "b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)b") { return 507; }
 if ($query_string ~ "b(erections|hoodia|huronriveracres|impotence|levitra|libido)b") {return 507; }
 if ($query_string ~ "b(ambien|bluespill|cialis|cocaine|ejaculation|erectile)b") { return 507; }
 if ($query_string ~ "b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)b") { return 507; }
 # Here, everyone adds and deletes the above judgment parameters according to their own situation. Blocking such as cURL and wget is a bit extreme, but "it is better to kill a thousand by mistake than to let one go." if ($http_user_agent ~* YisouSpider|ApacheBench|WebBench|Jmeter|JoeDog|Havij|GetRight|TurnitinBot|GrabNet|masscan|mail2000|github|wget|curl|Java|python) { return 508; }
 #Same as above, everyone adds and deletes the following blocking and interception parameters based on the actual situation of their site. if ($http_user_agent ~* "Go-Ahead-Got-It") { return 508; }
 if ($http_user_agent ~* "GetWeb!") { return 508; }
 if ($http_user_agent ~* "Go!Zilla") { return 508; }
 if ($http_user_agent ~* "Download Demon") { return 508; }
 if ($http_user_agent ~* "Indy Library") { return 508; }
 if ($http_user_agent ~* "libwww-perl") { return 508; }
 if ($http_user_agent ~* "Nmap Scripting Engine") { return 508; }
 if ($http_user_agent ~* "~") { return 508; }
 if ($http_user_agent ~* "WebBench*") { return 508; }
 if ($http_user_agent ~* "spider") { return 508; } #This will affect some domestic search engine crawlers, such as: Sogou # To intercept UAs for malicious requests, you can analyze site log files or waf logs as reference configuration. if ($http_referer ~* ) { return 509; }
 #Intercept the requests of the site's speed test nodes, so Mingyue has always said that the data of these speed test websites is for reference only and cannot be taken seriously. if ($http_referer ~* WebBench*") { return 509; }
 #InterceptWebBenchOr similar stress testing tools,Other tools only need to change their names。

This is the end of this article about several ways to prevent SQL injection in Java projects. For more related Java prevention of SQL injection, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!