一、概念
SQL注入即是指web应用程序对用户输入数据的合法性没有判断或过滤不严,攻击者可以在web应用程序中事先定义好的查询语句的结尾上添加额外的SQL语句,在管理员不知情的情况下实现非法操作,以此来实现欺骗数据库服务器执行非授权的任意查询,从而进一步得到相应的数据信息。
二、通过 Statement 来表现SQL注入
实体类:
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
dao接口和实现类:
public interface UserDao {
/**
* 登录功能
* @param u 用户对象
*/
public void login(User u);
}
public class UserDaoImpl implements UserDao {
public void login(User u){
try {
Connection conn = DBUtil.getConnection();
Statement stmt = conn.createStatement();
String sql = "select * from t_user where `username` = '"+u.getUsername()+"' && `password` = '"+u.getPassword()+"'";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试类:
之所以能够注入成功,就是对SQL语句额外拼接,比如在原语句后加入 or 1 = 1,直接当场去世!
public class Test {
public static void main(String[] args) {
/**
* 使用 123' or 1='1 作为密码,注入成功
*
* select * from t_user where `username` = 'admin' && `password` = '' or 1='1'
*/
User u = new User("admin", "123' or 1='1");
UserDaoImpl impl = new UserDaoImpl();
impl.login(u);
}
}