修复J2EE漏洞:2. SQL注入

Heibernate框架

HQL查询
Query query = session.createQuery("from Secret where username=?");  
query.setParameter(0, username);  
//Query query = session.createQuery("from Secret where username=:username");
使用PreparedStatement预编译
PreparedStatement updateSales =  
        conn.prepareStatement(" update goods set sales = ? where good_name like ?");
updateSales.setInt(1, 75);  
updateSales.setString(2, "喜之郎果冻");  
updateSales.executeUpdate();  

Mybatis框架

核心:能用#就不用$

select * from news where tile like concat('%',#{title},'%')  

ESAPI

Oracle
Codec oracleCodec = new OracleCodec();  
String query = "select name from users where id = " + ESAPI.encoder().encoderForSQL(oracleCodec,userId);  
Statement stmt = conn.createStatement(query);  
MySQL
Codec mysqlCodec = new MySQLCodec(MySQLCodec.ANSI_MODE);  

ANSI模式下,对单引号进行转义,对双引号进行过滤

private String encodeCharacterANSI(Character c){  
    if(c == '\'')
        return "\'\'";
    if(c == '\"')
        return "";
    return "" + c;
}
Codec mysqlCodec = new MySQLCodec(MySQLCodec.MYSQL_MODE);  

MYSQL模式通过在字符前面加反斜杠字符来进行转义

其它

ESAPI提供了OracleCodec,MySQLCodec, DB2Codec,[MSSQLCodec, PgSQLCodec],在使用时都是先实例化,再由ESAPI.encoder().encoderForSQL进行过滤/转义操作

欢迎大家加入小密圈,一起交流进步

zhutougg

继续阅读此作者的更多文章