Skip to main content

Code reviews rule: Vulnerable code to SOQL/SOSL injections

Written by David Martin
Updated this week

Vulnerable code to SOQL/SOSL injections

Why is this an issue?

SOQL and SOSL injection is a Security vulnerability that occurs when user-supplied input is concatenated directly into a database query string without proper sanitization. An attacker can manipulate the query logic by injecting malicious characters, potentially gaining unauthorized access to records they should not be able to view.

For example, if a search feature builds a SOQL query by concatenating a user-provided string, an attacker could input ' OR Name LIKE '% to bypass intended filters and retrieve all records.

Examples

Example of incorrect code: The following code takes user input and concatenates it directly into the query.

public List<Account> searchAccounts(String userInput) {
String query = 'SELECT Id, Name FROM Account WHERE Name LIKE \'%' + userInput + '%\'';
return Database.query(query);
}

Example of correct code: Use bind variables with static SOQL. They automatically handle escaping strings.

public List<Account> searchAccounts(String userInput) {
String searchPattern = '%' + userInput + '%';
return [SELECT Id, Name FROM Account WHERE Name LIKE :searchPattern];
}

How can I fix violations?

To fix this vulnerability:

  1. Use bind variables: Where possible, use static SOQL with bind variables (:variableName) instead of dynamic queries to avoid concatenating untrusted input into query strings.

  2. Avoid dynamic queries with user input: If the query structure doesn't need to change at runtime, prefer static SOQL over Database.query().

  3. Use String.escapeSingleQuotes(): Wrap any user-supplied string with this method before concatenating it into a dynamic query. This escapes single quotes that could be used to break out of string literals.

When should I disable this rule?

You may need to dismiss specific violations if your code uses a custom sanitization method that the static analysis cannot recognise. In such cases, ensure your sanitization is robust and well-tested.

Resources

Did this answer your question?