SQL注入是一种安全漏洞,攻击者通过影响Web应用程序的后端数据库执行未授权的SQL命令。
这通常是通过将恶意SQL代码注入到应用程序的输入字段中实现的,例如通过在搜索框中输入
' OR '1'='1
来使得原本的查询语句
SELECT * FROM table WHERE column = '${value}'
变为
SELECT * FROM table WHERE column = '' OR '1'='1'
这将使得无需任何验证就能返回表中的所有记录,甚至能通过sql注入漏洞删除所有数据。在各种安全漏洞中,sql注入漏洞算是高危中的高危。
如何防御sql注入漏洞,Oracle开源的esapi中的encodeForSQL通过注释回答了我们。
/**
* Encode input for use in a SQL query, according to the selected codec
* (appropriate codecs include the MySQLCodec and OracleCodec).
*
* This method is not recommended. The use of the {@code PreparedStatement}
* interface is the preferred approach. However, if for some reason
* this is impossible, then this method is provided as a weaker
* alternative.
*
* The best approach is to make sure any single-quotes are double-quoted.
* Another possible approach is to use the {escape} syntax described in the
* JDBC specification in section 1.5.6.
*
* However, this syntax does not work with all drivers, and requires
* modification of all queries.
*/
String encodeForSQL(Codec codec, String input){
if( input == null ) {
return null;
}
return codec.encode(IMMUNE_SQL, input);
}
解释一下就是:
(1)使用预编译的sql,即PreparedStatement,这是最好的办法。众所周知mybatis也是对jdbc的封装,其中对应的是#{}语法。为什么PreparedStatement能防sql注入,因为第一次执行的时候类似select * from table1 where column1 = ?的sql就已经被数据库编译、优化了,后续传入的参数不会被认为是sql指令,而只是当做一个值注入占位符,由于不存在sql的重新编译,因此也不可能改变其原有的语义,不存在sql注入的可能。
(2)使用白名单(注释中没提,但这也是一种很好的方法)。有时候我们必须要动态的拼接上一些sql指令才能实现特定的功能。典型的比如
select * from table1 where column1 = 'value1' order by column2 ${param}
如果传入的是asc,则对column2进行升序排列;如果是desc,则进行降序排序。类似这样的sql存在sql注入的风险,但我们又必须使用,怎么办?如果能预先知道参数合法的有限的取值返回,就可以使用白名单。比如如果是java代码可以这么写:
public List<Student> getStudents(String acsOrDesc){
HashSet<String> whiteList = new HashSet<String>(Arrays.asList("asc", "desc"));
if (!whiteList.contains(acsOrDesc)){
//参数校验不合法,直接抛出异常
throw new RuntimeException("参数不合法");
}
//如果参数校验合法则继续往下执行...
}
(3)对输入参数进行转义,可以借助一些第三方包,比如esapi
public List<Student> getStudents2(String column,String value){
Encoder encoder = DefaultEncoder.getInstance();
OracleCodec oracleCodec = new OracleCodec();
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("column",encoder.encodeForSQL(oracleCodec, column));
paramMap.put("value",value);
//传入mybatis的sqlMap文件...
}
<select id='queryStudents'>
select * from student where ${column} = #{value}
</select>
这里注意,转义是对传入的参数转义,而非对整个sql语句转义。转义的实质其实也很简单,只需要参数中所有的单引号替换为两个单引号(The best approach is to make sure any single-quotes are double-quoted.)
其他缓解措施包括最小化数据库用户权限等。