回首当年我们犯下的错误——存在sql注入式攻击的最差实践代码(Java新手注意了)

来源:互联网 发布:linux python ssh模块 编辑:程序博客网 时间:2024/05/16 07:30
下面是自己以前初学JDBC时候写的代码,存在sql注入漏洞。
不安全因素:statement。。。应该用Preparedstatement来代替statement,这样我们就可以使用占位符作为实参来定义sql语句,从而避免sql注入的攻击。
        当然也可以用statement,你得注意你的sql的写法,要是下例肯定不行。还得对url恶意传入参数进行过滤(SQL元字符处理)。。。这样就比较麻烦了,而且也无法保证绝对的安全。
        我们在用hibernate等框架的时候(hql语句),避免sql注入攻击也是一样的,关键是不要用string来构造sql语句,不管什么框架,还是纯JDBC,只要用Preparedstatement就OK。。。一定要用占位符作为实参来构造sql(或hql)语句。
package cn.zhd;import java.io.*;import org.apache.log4j.*;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.sql.ResultSet;public class LoginDemo {        public void execute(String user,String pass){        boolean foo=false;        try{            Class.forName("com.mysql.jdbc.Driver");            Connection con=DriverManager.getConnection("jdbc:mysql://localhost/students","root","");            Statement stam=con.createStatement();            //存在注入攻击漏洞:select * from login where user='' or'x'='x' or 'x'='' and '1'            ResultSet rs=stam.executeQuery("select * from login where user='" + user + "' and pass='"+ pass + "'");            while(rs.next()){                    foo=true;                            }            if(foo){                System.out.println("登陆成功");            }            else            {                System.out.println("用户名密码错误");            }        }catch(ClassNotFoundException e){            e.printStackTrace();        }catch(SQLException e){            e.printStackTrace();        }            }    public static void main(String[] args){        Logger log=Logger.getLogger(LoginDemo.class);        try{            LoginDemo ld=new LoginDemo();            BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));            log.info("请输入用户名");            String bf_str=bf.readLine();            log.info("请输入密码");            String bf2_str=bf.readLine();            bf.close();            ld.execute(bf_str,bf2_str);        }catch(IOException e){            e.printStackTrace();        }            }}

当输入用户名的时候输入:' or 'x'='x' or '2'='
密码随便输.....
成功登陆了吧.....

原文出自
原创粉丝点击