Ajax request and filter Match case resolution _AJAX related

Source: Internet
Author: User
Tags auth chr lowercase sql injection

Case Introduction

Now there is a problem, is to submit a large text comment, the front desk to send the data back to the background of the AJAX request, and then there is a background to prevent SQL injection filter, this filter to get the data from the front desk, to verify the legality, if there is no verification of success, Then jump to the error.jsp page to display the error message. Now let's see how we can achieve this requirement.

Idea One: Request forwarding implementation

Ajax request

$.ajax ({method
: ' Post ',
URL: ' Servlet/demoservlet ',
dataType: ' json ',
data:{
' userName ': UserName,
' PassWord ':p assword,
' text ': Text
},
success:function (data) {
//After successful logic
} ,
error:function () {
//After error logic
}
});

Prevent SQL injection Filter

Package com.yiyexiaoyuan.filter;
Import java.io.IOException;
Import java.util.Enumeration;
Import Javax.security.auth.message.callback.PrivateKeyCallback.Request;
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;
Import Net.sf.json.JSONObject;  Filtering the 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;
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 +//"--");
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 ("Submit Method:" +req.getmethod ());
System.out.println ("Matched string:" + sql); 
if (sqlvalidate (SQL)) {//Request forwarding Req.getrequestdispatcher ("error.jsp"). Forward (req, res); 
else {String Request_uri = Req.getrequesturi ();
Chain.dofilter (request, response); }//Checksum protected static Boolean sqlvalidate (String str) {str = str.tolowercase ();//unified to lowercase//String badstr = "And|exe
C "; 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|//|/|%|#";
*///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 Unsupportedoperationexception ("Not Su
pported yet. ");} public void Destroy () {//throw new unsupportedoperationexception (' not supported yet. ');}

Web.xml Configuration

<filter>
<display-name>SQLFilter</display-name>
<filter-name>sqlfilter</ filter-name>
<filter-class>com.yiyexiaoyuan.filter.SQLFilter</filter-class>
</filter >
<filter-mapping>
<filter-name>SQLFilter</filter-name>
<url-pattern>/ servlet/*</url-pattern>
</filter-mapping>
<filter>

Analysis, Ajax request Demoservlet, then request to be prevented from SQL injection filter filter First, then filter to the request parameters to form a matching string, and then check whether it is malicious code, if so, request forwarding. But unfortunately, logically this is true, but the AJAX request is partially refreshed, and finally to the AJAX request initiated by this page, so request forwarding will not be implemented, we look at the next implementation logic.

Idea two: The return value is judged

The logic of this idea is this: when filter out the information, the AJAX request to send back a JSON data, and then return to the front desk, the foreground to take this data to determine whether it is malicious code and good code. Then proceed to the next process.

Ajax request

$.ajax ({method
: ' Post ',
URL: ' Servlet/demoservlet ',
dataType: ' json ',
data:{
' userName ': UserName,
' PassWord ':p assword,
' text ': Text
},
success:function (data) {
//successful logic
if ( Data.mssage!= "") {
//execute logic for handling malicious code
}
else{
}
},
error:function () {
//Error
}
});

filter to prevent SQL injection

Package com.yiyexiaoyuan.filter;
Import java.io.IOException;
Import java.util.Enumeration;
Import Javax.security.auth.message.callback.PrivateKeyCallback.Request;
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;
Import Net.sf.json.JSONObject;  Filtering the 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;
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 +//"--");
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 ("Submit Method:" +req.getmethod ());
System.out.println ("Matched string:" + sql); if (sqlvalidate (SQL)) {//Transmit JSON data jsonobject JSON = new Jsonobject (); Json.accumulate ("message", "Malicious Code injection"); Res.getwrite 
R (). Print (json.tostring ()); 
else {String Request_uri = Req.getrequesturi ();
Chain.dofilter (request, response); }//Checksum protected static Boolean sqlvalidate (String str) {str = str.tolowercase ();//unified to lowercase//String badstr = "And|exe
C "; 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|//|/|%|
#";
*///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 Unsupportedoperationexception ("Not Su
pported yet. ");} public void Destroy () {//throw new unsupportedoperationexception (' not supported yet. ');}

Idea three: Exception + jump implementation

The logic of this idea is this. The background filter filters out the malicious injection code, throws RuntimeException (), and then causes the AJAX request to fail, and then callback the AJAX request error method. But how do we send the data from the wrong page to the past? After my serious thinking, we can do so, in the session save a Error_messgae value, and then the AJAX request error method to jump to the error page, and then take the value rendering error page.

Ajax request

$.ajax ({method
: ' Post ',
URL: ' Servlet/demoservlet ',
dataType: ' json ',
data:{
' userName ': UserName,
' PassWord ':p assword,
' text ': Text
},
success:function (data) {
//successful logic
},
error:function () {
window.location.href= "error.jsp";
}
});

Prevent SQL injection Filter

Package com.yiyexiaoyuan.filter;
Import java.io.IOException;
Import java.util.Enumeration;
Import Javax.security.auth.message.callback.PrivateKeyCallback.Request;
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;
Import Net.sf.json.JSONObject;  Filtering the 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;
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 +//"--");
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 ("Submit Method:" +req.getmethod ());
System.out.println ("Matched string:" + sql); 
if (sqlvalidate (SQL)) {req.getsession (). setattribute ("Error_message", "maliciously injected");
throw new RuntimeException ("malicious injection"); 
else {String Request_uri = Req.getrequesturi ();
Chain.dofilter (request, response); }//Checksum protected static Boolean sqlvalidate (String str) {str = str.tolowercase ();//unified to lowercase//String badstr = "And|exe
C "; 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|//|/|%|
#";
*///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 Unsupportedoperationexception ("Not Su
pported yet. ");} public void Destroy () {//throw new unsupportedoperationexception (' not supported yet. ');}

Error.jsp Implementation

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib prefix= "C" uri= "http://"
Java.sun.com/jsp/jstl/core "%> <% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

This is very clever to achieve the filter blocking and friendly hints.

The above is a small set to introduce the AJAX request and filter with case resolution, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.