简体   繁体   中英

check input for SQL-Injection with Mybatis

I'd like to check my input string for potential SQL-Injection.

Here is my class, method and query:

public class UserNamesQuery {

   public static String getUserNames(Map<String, Object> params) {
       String userNames = (String) params.get("userNames");
       return "SELECT * FROM users WHERE name IN (" + userNames + ") ";
   }

}

Is there a tool or a quick way to validate that userNames is without SQL-Injection?

Notice that I use Mybatis

No. There is no way. And no need.

To be frank, there is no such thing like "SQL injection". There is only an exploit of improperly formatted query .

So, instead of hunting down whatever "injections" you have to format your queries properly, by means of using prepared statements.

Any data, depends on context, could be either a potential injection or a harmless chunk of text. So, with whatever filtering function there will be too much false positives. Worse yet, whatever filtering is a "black list" implementation, means it will always be incomplete - it's just impossible to filter out all the codes used to exploit an injection.

On the other hand, prepared statement is a relatively simple solution that will be immune to any type of injection without even knowing them. Just because it won't let the data to interfere with the query.

Sanitizing input is not the way to prevent injections like this. Using prepared statements is the way to go.

PreparedStatement ps = connection.prepareStatement("SELECT * FROM users WHERE username IN (?)"); //Add however many ?'s you want, if you have an array you can use a StringBuilder for this to add more ?'s
ps.setString(1, userName);
ResultSet rs = ps.executeQuery();

This will set the ? in the code to your string. The database driver then handles the rest. If you have multiple values in the IN clause, use a StringBuilder and a loop to add more Questionmarks.

Also notice how the indexing starts with 1 instead of 0.

mybatis sql template may be a good choose. FYI:

<sql id="orderTypeSql">
    <trim prefix=" ">
        <if test="orderType=='desc'">desc</if>
    </trim>
</sql>

<sql id="oderColumnSql">
    <trim prefix="order by " suffix="" >
        <choose>
            <when test="orderColumn==null or orderColumn==''"></when>
            <when test="orderColumn=='id'">
                id<include refid="orderTypeSql"/>
            </when>
            <when test="orderColumn=='name'">
                `name`<include refid="orderTypeSql"/>
            </when>
        </choose>
    </trim>
</sql>

<select id="testOrderBy" resultType="User">
    select
    id,
    `name`
    from t_user
    <include refid="oderColumnSql"/>
    limit 0, 10
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM