Prevent sql injection when using mybatis

1. Where condition like injection
  error code example: select id, name from user where name like '${name}%'
  Injection method 1: directly write the value corresponding to name in the text box as %, then the back-end sql directly becomes select id,name from user where name '%%' will check out all the data.
  Injection method 2: Change the error example code to select id,name from user where name like '${name}%'and id=1 and directly write the value corresponding to name in the text box as %' or '1'='1 , then the back-end sql directly becomes select id, name from user where name '%%' will check out all the data.
  Solution: change sql to
select id,name from user where name like CONCAT(#{name},'%’)或select id,name from user where name like #{name}||’%’
, but this can only avoid the vulnerability of injection method 2. It is also necessary to judge whether the name is empty or whether it contains %, and if it does not contain the like statement.

2. In conditional injection
  error code example: select id, name from user where id in (${ids})
  Injection method: directly set ids to 1) or (1=1 to complete the injection, sql will become select id ,name from user where id in (1) or (1=1), will find out all the data
  Solution: change sql to pass foreach structure, such as:

select id,name from user
  <where>  
    id in  
    <foreach item="item" collection="list" separator="," open="(" close=")" index="">  
      #{item.id, jdbcType=NUMERIC}  
    </foreach>  
  </where>  


3. Column name, table name, and order by injection
  can only use the format of ${param}. After testing and data review, there is no good solution for the time being. It is recommended to avoid
  using the dynamic form of $ when writing. For variables, if there are not many tables, you can copy several identical SQLs to replace the table names. For sub-tables, you need to verify and match the dynamic variables.
  The column names and the column names after order by are the same. In addition, avoid passing these data in the front-end page.
  These types of sql injection methods are as follows:
  1. Column name injection method: select ${column} name from user, assign the column value to (select sleep(5)), and sql becomes select (select sleep(5)) from user ; or if other column names are known, change the column to pwd, and sql to select pwd name from user;
  2. Table name injection: select name, age from ${table} , assign the column to (select pwd name, prex age from dept) b, then sql becomes select name, age from (select pwd name, prex age from dept) b, and another known table is used to disguise as a normal table to return data.
4. There is a risk of sql injection
  in ${}. You can use this as much as possible with #{}, and ${} is prohibited in normal where conditions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326261957&siteId=291194637