SQL注入漏洞过程实例及解决方案
时间:2021-01-18 14:47:19|栏目:Mysql|点击: 次
代码示例:
public class JDBCDemo3 { public static void demo3_1(){ boolean flag=login("aaa' OR ' ","1651561"); //若已知用户名,用这种方式便可不用知道密码就可登陆成功 if (flag){ System.out.println("登陆成功"); }else{ System.out.println("登陆失败"); } } public static boolean login(String username,String password){ Connection conn=null; Statement stat=null; ResultSet rs=null; boolean flag=false; try { conn=JDBCUtils.getConnection(); String sql="SELECT * FROM user WHERE username='"+username+"'AND password='"+password+"'"; //此处是SQL注入漏洞的关键,因为是字符串的拼接,会使查询语句变为:SELECT * FROM user WHERE username='aaa' OR '' AND password='1651561',此查询语句是可得到结果集的,便出现此漏洞 stat=conn.createStatement(); rs=stat.executeQuery(sql); if(rs.next()){ flag=true; }else{ flag=false; } } catch (SQLException e) { e.printStackTrace(); } return flag; }
解决方法,使用PrepareStatment:
public static void demo3_1(){ boolean flag=login1("aaa' OR ' ","1651561"); if (flag){ System.out.println("登陆成功"); }else{ System.out.println("登陆失败"); } } public static boolean login1(String username,String password){ Connection conn=null; PreparedStatement pstat=null; ResultSet rs=null; boolean flag=false; try { conn=JDBCUtils.getConnection(); String sql="SELECT * FROM user WHERE username=? AND password=?"; //使用?代替参数,预先设置好sql格式,就算在输入sql关键字也不会被sql识别 pstat=conn.prepareStatement(sql); pstat.setString(1,username); //设置问号的值 pstat.setString(2,password); rs=pstat.executeQuery(); if(rs.next()){ flag=true; }else{ flag=false; } } catch (SQLException e) { e.printStackTrace(); } return flag; } }
使用以上解决办法就无法通过SQL注入漏洞登陆用户成功。