SQL注入

        一提起SQL注入,大家想到的肯定是不安全,有漏洞,需要避免,但是今天这个文章是要记录一下我在学习过程中遇到的需要使用SQL注入的场景。

首先先来简单看一下SQL注入所带来的安全漏洞:

package com.xzh.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*
    模拟实现用户登录功能
 */
public class Test01 {
    public static void main(String[] args) {
        // 初始化界面
        Map<String,String> userLoginInfo = initUI();
        // 验证用户名和密码
        boolean loginSuccess = login(userLoginInfo);
        // 输出最后结果
        System.out.println(loginSuccess ? "登录成功" : "登录失败");
    }

    /**
     * 用户登录
     * @param userLoginInfo 用户登录信息
     * @return true表示登录成功,false表示登录失败
     */
    private static boolean login(Map<String, String> userLoginInfo) {
        boolean loginSuccess = false;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xzh","root","333");
            // 3、获取数据库操作对象
            stmt = conn.createStatement();
            // 4、执行sql语句
            String sql = "select * from t_user where loginName = '"+ userLoginInfo.get("userName")+ "' and loginPwd = '" + userLoginInfo.get("userPassword")+ "'";
            // 以上代码完成了sql语句的拼接,以下代码是将拼接好的sql语句发送给DBMS进行sql编译
            rs = stmt.executeQuery(sql);
            // 5、处理结果集
            if(rs.next()) {
                loginSuccess = true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 6、释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return loginSuccess;
    }


    /**
     * 初试化界面
     * @return 用户输入的用户名和密码等登录信息
     */
    private static Map<String, String> initUI() {
        Scanner s = new Scanner(System.in);

        System.out.print("请输入用户:");
        String userName = s.nextLine();
        System.out.print("请输入密码:");
        String userPassword = s.nextLine();

        Map<String,String> userLoginInfo = new HashMap<>();
        userLoginInfo.put("userName",userName);
        userLoginInfo.put("userPassword",userPassword);

        return userLoginInfo;
    }
}

output:

可以看到, 利用SQL注入成功绕过了登录验证。原因是因为什么呢,首先来看一下具体执行的sql语句:

select * from t_user where loginName='123' or 1=1 #' and loginPwd =

根据Mysql 的语法规则,#以后的内容会被忽略,而1 = 1是一个永真式,所以会返回登录成功。

原理是因为用户输入的信息中含有sql语句的关键字,并且他们拼接到了sql语句当中参与了编译的过程,导致sql语句的原意被扭曲,才造成了SQL注入的后果。所以只需要不让用户输入的信息参与编译过程就可以避免SQL注入。

// 4、执行sql语句
String sql = "select * from t_user where loginName = '"+ userLoginInfo.get("userName")+ "' and loginPwd = '" + userLoginInfo.get("userPassword")+ "'";
// 以上代码完成了sql语句的拼接,以下代码是将拼接好的sql语句发送给DBMS进行sql编译
rs = stmt.executeQuery(sql);

防止SQL注入的代码:

package com.xzh.jdbc;

import com.sun.xml.internal.fastinfoset.tools.StAX2SAXReader;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 防止sql注入
 */
public class login {
    public static void main(String[] args) {
        Map<String, String> loginMap = init();

        boolean loginSuccess = login(loginMap);
        System.out.println(loginSuccess ? "登录成功" : "登录失败");

    }


    /**
     * 登录方法
     */
    private static boolean login(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet res = null;

        boolean loginSuccess = false;

        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xzh", "root", "333");
            // 3、获取预编译数据库操作对象
            String sql = "select * from t_user where loginName = ? and loginPwd = ?";
            // 程序执行到此处,会发送sql语句的框架给DBMS,然后DBMS对sql语句进行预编译
            ps = conn.prepareStatement(sql);
            // 传值
            ps.setString(1, username);
            ps.setString(2, password);
            // 4、执行sql语句
            res = ps.executeQuery();

            // 5处理结果集
            if (res.next()) {
                loginSuccess = true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 6.释放资源
            if (res != null) {
                try {
                    res.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return loginSuccess;

    }



    /**
     * 登录界面
     * @return
     */
    private static Map<String, String> init() {
        Scanner s = new Scanner(System.in);

        System.out.println("用户名:");
        String username = s.next();

        System.out.println("密码:");
        String password = s.next();

        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);

        return map;

    }
}

output:

 避免了SQL注入。

这里避免SQL注入是使用了PreparedStatement,用户输入的信息将不会再参与sql语句的编译过程,即使用户提供的信息里包含sql语句的关键字,但是因为没有参与编译,所以也不会起作用。

PreparedStatement属于预编译的数据库操作对象,原理是预先对SQL语句的框架进行编译,然后再进行传值。

            // 3、获取预编译数据库操作对象
            String sql = "select * from t_user where loginName = ? and loginPwd = ?";
            // 程序执行到此处,会发送sql语句的框架给DBMS,然后DBMS对sql语句进行预编译
            ps = conn.prepareStatement(sql);
            // 传值
            ps.setString(1, username);
            ps.setString(2, password);

需要使用SQL注入的场景

最常见的例子就是某宝上的商品可以升序和降序排列。

代码如下:

package com.xzh.jdbc;

import java.sql.*;
import java.util.Scanner;

public class Test03 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("请输入desc或者asc");
        String keyWords = s.nextLine();

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xzh","root","333");

            stmt = conn.createStatement();

            String sql = "select ename from emp order by ename " + keyWords;

            rs = stmt.executeQuery(sql);

            while(rs.next()){
                System.out.print(rs.getString("ename") + " ");
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

output:

 

如果你想更深入更全面的了解SQL注入,可以看一下这篇文章。

sql注入基础原理(超详细) - 简书

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值