SQL注入简单代码实现(源码在最后):
图一是用statement的操作
图三是sql注入的运行结果
图四、五 Navicat的查询操作
当与数据库交互时,使用statement可以被SQL注入,在此例中即利用SQL语句的漏洞来实现无需用户名和密码来实现登录操作,所以推荐使用preparedstatement,可以有效防止SQL注入。
分析:在输入用户名时,输入ou ’ or 1=1-- 后,–把之后的SQL语句都注释掉了,之后的语句没作用,可以忽略了,如图四中’and upwd='yes’变灰色了。分析where uname='ou ’ or 1=1 ,where … or …语句,or前后两个条件只要有一个为真,where就为真,此句中1=1为真,就不用管or前面是什么,是否为真,反正where查询条件都成立。所以查询数据库,得到的count就是login表中所有数据的数量,我表中就一个数据,所以count(*)为1.
图六是数据库表,均为varchar类型。
我的程序输入ou ’ or 1=1-- 为用户名时,–后要有空格,不然会报SQL语句错误。
因为一些错误,我写了一些打印用户名和密码的语句来检查,已注释请忽略。
package sqlzhuru;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.naming.NameNotFoundException;
public class SQLzhuru {
public static void sqlzhuru(){
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String URL="jdbc:mysql://localhost:3306/xuexi";
String name="root";
String pwd="YES";
conn=DriverManager.getConnection(URL, name, pwd);
stmt=conn.createStatement();
Scanner in=new Scanner(System.in);
System.out.println("请输入用户名:");
String uname=in.nextLine();
System.out.println("请输入密码:");
String upwd=in.nextLine();
// System.out.println(uname);
// System.out.println(upwd);
// String sql="select * from login";
int count=-1;
String sql="select count(*) from login where uname='"+uname+"' and upwd='"+upwd+"'";
// String sql ="SELECT count(*) FROM `login` where uname='ou ' or 1=1 -- 'and upwd='yes'" ;
rs=stmt.executeQuery(sql);
// stmt.executeQuery(sql);
// while(rs.next()) {
// System.out.print(rs.getString("uname")+" ");
// System.out.println(rs.getString("upwd"));
// }
if(rs.next()) {
count=rs.getInt(1);
}
if(count>0) {
System.out.println("登录成功!");
}else {
System.out.println("登陆失败!");
}
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null) {
try { rs.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null) {
try{stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
sqlzhuru();
}
}