java-sql注入攻击

注射式攻击的原理

SQL注射能使攻击者绕过认证机制,完全控制远程服务器上的数据库。SQL是结构化查询语言的简称,它是访问数据库的事实标准。目前,大多数Web应用都使用SQL数据库来存放应用程序的数据。几乎所有的Web应用在后台都使用某种SQL数据库。跟大多数语言一样,SQL语法允许数据库命令和用户数据混杂在一起的。如果开发人员不细心的话,用户数据就有可能被解释成命令,这样的话,远程用户就不仅能向Web应用输入数据,而且还可以在数据库上执行任意命令了。

看下面的代码:

public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("账号:");
        String uid = sc.nextLine();
        System.out.println("密码:");
        String pwd = sc.nextLine();
        
        Class.forName("com.mysql.jdbc.Driver");
        
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK","root","");
        
        Statement state = conn.createStatement();
        
        String sql = "select * from users where user ='"+uid+"' and password ='"+pwd+"' ";
        ResultSet rs = state.executeQuery(sql);
        boolean ok = rs.next();
        if(ok){
            System.out.println("欢迎"+rs.getString(3)+"回来");
        }
        else{
            System.out.println("您输入的账号密码错误");
        }
        
        conn.close();

    }

我们正常输入账号密码是运行正确的,但是当我们账号输入:kjaskj' or 1=1 #  密码输入:klkjl;  就会出现以下的结果:

欢迎张三回来

这里,关键在  账号里面的那个单引号 “ ‘ ’”和后面 or 1=1以及#号(我们这里用的是mysql,oracle后面用 --)。这样查询语句就变成了:

select * from users where user ='kjaskj'or1=1#' and password ='"+pwd+"' 
该双划符号#告诉SQL解析器,右边的东西全部是注释,所以不必理会。这样,查询字符串相当于:

select * from users where user =''OR1=1.   这样输出的就是ture。  就能不用账号密码直接进入。



当然这里也有办法阻止此类事件的发生。

在代码中间插入一个替换一句,将该方法中所有的单引号替换成双引号,就不会发生类似的事情。代码如下:
public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("账号:");
        String uid = sc.nextLine();
        System.out.println("密码:");
        String pwd = sc.nextLine();
        
        Class.forName("com.mysql.jdbc.Driver");
        
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK","root","");
        
        Statement state = conn.createStatement();
        uid=uid.replace("\'", "\"");//替换单双引号
        String sql = "select * from users where user ='"+uid+"' and password ='"+pwd+"' ";
        ResultSet rs = state.executeQuery(sql);
        boolean ok = rs.next();
        if(ok){
            System.out.println("欢迎"+rs.getString(3)+"回来");
        }
        else{
            System.out.println("您输入的账号密码错误");
        }
        
        conn.close();

    }

 

 

转载于:https://www.cnblogs.com/kuangwong/p/6250165.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值