The SQL injection example that appears in MyBatis SQL is used:
To simulate a simple login scenario:
Page code:
functionLogin () {//SQL injection varuser ={username:"' Li Xuelei 3 ' or 1=1", Password:"' ab0715 '",} $.ajax ({URL:'/api/test/login.json ', type:"POST", data:JSON.stringify (user),//serializes an object into a JSON stringDataType: "JSON", ContentType:' Application/json;charset=utf-8 ',//Set Request header informationAsyncfalse, Success:function(Result) {Debugger; $("#dis"). HTML (result.data); }, Error:function(XHR, ajaxoptions, thrownerror) {Debugger; Alert ("Something went wrong."); } })}
<Type= "button" onclick= "Login ()" value= "Login" name= "SUNMITBTN" >
Controller
@RequestMapping ("/login") @ResponseBody Publicbaseresponse Login (httpservletrequest request, httpservletresponse response, @RequestBody Userparam userparam) { Try{User User=Userservice.selectbycon (Userparam); if(User! =NULL){ returnBaseresponse.successcustom (). SetData ("Login Successful"). build (); } returnBaseresponse.successcustom (). SetData ("Login Failed"). build (); //return Baseresponse.successcustom (). SetData (ReturnVal). build ();}Catch(Exception e) {e.printstacktrace (); returnBaseresponse.failedcustom ("System Exception"). build (); } }
Service Interface:
User Selectbycon (Userparam userparam);
Service Implementation class:
@Override Public User Selectbycon (Userparam userparam) { = Usermapper.selectbycon (userparam); return user; }
Mapper Interface:
User Selectbycon (Userparam userparam);
Mapper.xml file:
Use SQL for $:
<SelectID= "Selectbycon"Resultmap= "Baseresultmap">Select<includerefID= "Base_column_list" />From User2 where 1=1<ifTest= "Username! = NULL" >and username = ${username}</if> <offTest= "Password! = null" >and password = ${password}</if> </Select>
Database user table User2 data:
To run the program:
Post-compilation sql:
select username, PASSWORD from user2 where 1 = 1 and username = " Li Xuelei 3 " or 1 = 1 and PASSWORD = " ab0715 "
Execution Result:
Login success:
Exploited the SQL injection vulnerability to cheat the password and log on successfully. If the account is correct, the password can be successfully logged in whatever it is entered.
Description
If you use SQL for write, we can exploit the SQL injection vulnerability to attack. It would be devastating if the table was deleted and the data was modified by SQL injection, and the database was not backed up by data.
=============================================
SQL using #:
<SelectID= "Selectbycon"Resultmap= "Baseresultmap">Select<includerefID= "Base_column_list" />From User2 where 1=1<ifTest= "Username! = NULL" >and username = #{username}</if> <ifTest= "Password! = null" >and password = #{password}</if> </Select>
To run the program:
Post-compilation sql:
SELECT username, PASSWORDfrom user2WHERE 1= 1 and = ? and = ?
Add parameters and translate to:
SELECTusername, PASSWORD fromUser2WHERE 1 = 1 andUsername="'Leilei 3' or 1=1" andPASSWORD="'ab0715'"
Execution Result:
Description
Using # SQL for pre-compilation, with? Accept parameters. If the argument is a string, the "" double quotation marks are used to effectively prevent SQL injection.
=========================================
Add:
Pre-compilation Benefits:
There are two choices when executing SQL commands: You can use the PreparedStatement object, or you can use the statement object.
The heroes who are familiar with JDBC programming will choose to use the PreparedStatement object, mainly because of the following advantages when using precompiled object PreparedStatement:
1. High Efficiency
PreparedStatement can improve the performance of accessing the database as much as possible, we all know that the database has a precompiled process when processing the SQL statement, and the precompiled object is to compile some fixed-format SQL and store it in the memory pool as the database buffer pool. When we execute the same SQL statement again, we don't need a precompiled procedure, just the DBMS running the SQL statement. So when you need to execute statement object multiple times, the PreparedStatement object will greatly reduce the running time, especially in the large database, it can effectively also speed up the speed of access to the database.
2, greatly improve the readability and maintainability of the Code
For example, we are inserting data into the database:
One is to use the statement object
Java.sql.Statement stmt=conn.createstatement ();
Stmt.executeupdate ("INSERT into student (Name,id,number,count) VALUES ('" +var1+ "', '" +var2+ "'," +var3+ ", '" +var4+ "')") ; The other is to use the PreparedStatement object
String sql = "INSERT into student values (null,?,?,?)";
Java.sql.PreparedStatement pstmt=conn.preparedstatement (SQL);
Pstmt.setstring (1,VAR1); Pstmt.setstring (2,VAR2); Pstmt.setstring (3,VAR3); Pstmt.setstring (4,VAR4); Pstmt.executeupdate ();
Use placeholders? Replace
Separating the arguments from the SQL statement makes it easy to change and extend the program, as well as to reduce unnecessary errors.
3, open source to prevent SQL injection (the most important )
When do I use a precompiled statement?
A precompiled statement is typically used when a SQL statement needs to be reused repeatedly, and the precompiled statements are often used in a fo R or while loop, which is repeated by setting the arguments repeatedly to use the SQL statement. To prevent SQL injection vulnerabilities, precompiled statements are also used in some data operations.
SQL Injection example is used in SQL MyBatis