前言
SQL注入攻击是黑客对数据库进行攻击常用的手段之一,随着B/S模式应用开发的发展,使用这种模式编写应用程序的程序员也越来越多。但是由于程序员的水平及经验参差不齐,相当大一部分程序员在编写代码的时候,没有对用户输入数据的合法性进行判断,使应用程序存在安全隐患。用户可以提交一段数据库查询代码,根据程序返回的结果,获得某些他想获取的数据,这就是所谓的SQL Injection,即SQL注入。
一 背景
假如某高校开发了一个网课系统,要求学生选课后完成学习,数据库中有一张表course
,这张表存放着每个学生的选课信息及完成情况,具体设计如下:
数据如下:
本系统采用mysql做为数据库,使用Jdbc来进行数据库的相关操作。系统提供了一个功能查询该学生的课程完成情况,代码如下。
@RestController public class Controller { @Autowired SqlInject sqlInject; @GetMapping("list") public List<Course> courseList(@RequestParam("studentId") String studentId){ List<Course> orders = sqlInject.orderList(studentId); return orders; } }
@Service public class SqlInject { @Autowired private JdbcTemplate jdbcTemplate; public List<Course> orderList(String studentId){ String sql = "select id,course_id,student_id,status from course where student_id = "+ studentId; return jdbcTemplate.query(sql,new BeanPropertyRowMapper(Course.class)); } }
二 注入攻击演示
1. 正常情况下查询一个学生所选课程及完成情况只需要传入student_id,便可以查到相关数据。
根据响应结果,我们很快便能写出对应的sql,如下:
select id,course_id,student_id,status from course where student_id = 4
2. 如果我们想要获取这张表的所有数据,只需要保证上面这个sql的where条件恒真就可以了。
select id,course_id,student_id,status from course where student_id = 4 or 1 = 1
请求接口的时候将studendId 设置为4 or 1 = 1,这样这条sql的where条件就恒真了。sql也就等同于下面这样
select id,course_id,student_id,status from course
请求结果如下,我们拿到了这张表的所有数据
3. 查询mysql版本号,使用union拼接sql
union select 1,1,version(),1
4. 查询数据库名
union select 1,1,database(),1
5. 查询mysql当前用户的所有库
union select 1,1, (SELECT GROUP_CONCAT(schema_name) FROM information_schema.schemata) schemaName,1
看完上面这些演示后,你害怕了吗?你所有的数据配置都完全暴露出来了,除此之外,还可以完成很多操作,更新数据、删库、删表等等。
三 如何防止sql注入
1. 代码层防止sql注入攻击的最佳方案就是sql预编译
public List<Course> orderList(String studentId){ String sql = "select id,course_id,student_id,status from course where student_id = ?"; return jdbcTemplate.query(sql,new Object[]{studentId},new BeanPropertyRowMapper(Course.class)); }有效防止sql注入的方法演示
扫一扫手机访问
