Recipe Name:
SQL Injection: SQLiteQueryBuilder#buildQuery
Description:
This method is vulnerable to SQL injection. Consider writing the query instead of relying on builders.
Level:
error
Language:
  • java
Tags:
  • security
  • framework specific
  • mobile
  • injection
  • SQL
  • Android
  • OWASP Top 10
Documentation

Out of Android best practices and secure coding guidelines, recommendations were abstracted which state that queries need to be parametrized. Concatenation of parameters is highly discouraged.

A parametrized query needs to be built first. Next, the parameter variables should be added. The following functions are available and are in line with Android best practices. These functions can be used to execute queries against the database. It is highly discouraged to use the method buildQuery as it does not lend itself to be used correctly. It is highly encouraged to use true parameterized queries instead of the appendWhereEscapeString() method.

Class information:
package android.database.sqlite.SQLiteDatabase;
    public SQLiteStatement compileStatement(String sql);
package android.database.sqlite.SQLiteProgram;
    public void bindString(int index, String value);
package android.database.sqlite.SQLiteStatement;
    public void execute();
Correct code example:
import android.database.sqlite.*;
...
SQLiteDatabase  sampleDB;
String sqlQuery = "INSERT INTO db (id, name) VALUES (?,?)";
SQLiteStatement sqlStmt = sampleDB.compileStatement(sqlQuery);
sqlStmt.bindString(1, id);
sqlStmt.bindString(2, name);
sqlStmt.execute();
Recipe
id: scw:android:sqlite-buildQuery-SQLi
version: 10
metadata:
  name: 'SQL Injection: SQLiteQueryBuilder#buildQuery'
  shortDescription: This method is vulnerable to SQL injection. Consider writing the query instead of relying on builders.
  level: error
  language: java
  scwCategory: injection:sql
  cweCategory: 89
  enabled: true
  comment: ""
  descriptionFile: descriptions/java_android_secure_database_queries.html
  tags: security;framework specific;mobile;injection;SQL;Android;OWASP Top 10
search:
  methodcall:
    name:
      anyOf:
      - is: buildQuery
      - is: buildQueryString
      - is: buildUnionQuery
      - is: buildUnionSubQuery
    type: android.database.sqlite.SQLiteQueryBuilder
availableFixes:
- name: Enable strict mode on the builder to validate input
  actions:
  - rewrite:
      to: |-
        {{{qualifier}}}.setStrict(true);
        {{{.}}}
      target: self