Sub topic 3
How SOQL Injection Works and What an Attacker Can Change
This chapter assumes you can read and write basic Apex classes, and that you know static SOQL with WHERE, ORDER BY and LIMIT. It also assumes you know that Apex strings and collections work like those in other languages, and that Salesforce enforces sharing rules and field-level security (FLS). The earlier chapters showed how to build a query at run time. This one shows how that goes wrong when the query text contains untrusted input.
The root cause: data becomes query structure
SOQL injection happens when text from a user is concatenated into a query string and the SOQL parser reads that text as part of the query's structure. The parser cannot tell which characters you wrote and which the user typed. It sees one string.
Static SOQL does not have this problem. In a static query, the compiler fixes the structure before any user input arrives. Dynamic SOQL passes a string to Database.query at run time, so the string is the only record of what you meant.
A first example: breaking out of a string literal
Here is the vulnerable method from the plan. It builds a query that looks for an account by exact name.
public with sharing class AccountSearch {
// VULNERABLE: user input is concatenated into the query string.
public static List<Account> findByName(String name) {
String soql = 'SELECT Id, Name FROM Account WHERE Name = \'' + name + '\'';
return Database.query(soql);
}
}With a normal input such as Acme, the query is:
SELECT Id, Name FROM Account WHERE Name = 'Acme'Now suppose the input is ' OR Name != '. The string concatenation produces:
SELECT Id, Name FROM Account WHERE Name = '' OR Name != ''Follow what the parser does. The first quote in the input closes the string literal that the template opened. That leaves Name = '', a valid comparison with an empty string. The text OR Name != is now an operator and a field, so it is parsed as SOQL. The last quote of the input opens a new literal, and the closing quote from your template closes it. The template's final quote is what balances the query, so the attacker only needs to arrange the input so that the quotes pair up.
The WHERE clause is now true for every account whose name is not empty. The method was meant to return at most the matching accounts, and now it returns every account the running user can see.
What the attacker controls
The attacker controls the text at the point where their input lands, and nothing else. That limit defines the damage. The attacker cannot edit the rest of your code, but they can often change what the query selects, filters, and sorts.
Filters in the WHERE clause
This is the most common outcome. A query often has a security-relevant filter next to the user-controlled one. Consider a search that is meant to return only the current user's accounts:
public with sharing class MyAccountSearch {
// VULNERABLE: the term is concatenated after a filter on the owner.
public static List<Account> search(String term) {
String soql = 'SELECT Id, Name FROM Account'
+ ' WHERE OwnerId = \'' + UserInfo.getUserId() + '\''
+ ' AND Name LIKE \'%' + term + '%\'';
return Database.query(soql);
}
}An attacker sends x%' OR Name != '%. The query becomes:
SELECT Id, Name FROM Account WHERE OwnerId = '005...' AND Name LIKE '%x%' OR Name != '%'SOQL, like SQL, evaluates AND before OR. The condition reads as (OwnerId = me AND Name LIKE '%x%') OR Name != '%'. The second branch is true for nearly every row, so the owner filter no longer limits anything. Your own filter was bypassed by the injected OR.
Numbers and other unquoted values
Escaping quotes does nothing when the value is not inside quotes. Look at this method:
public with sharing class RevenueSearch {
// VULNERABLE: a numeric value is concatenated without quotes.
public static List<Account> findAbove(String minRevenue) {
String soql = 'SELECT Id, Name FROM Account WHERE AnnualRevenue > ' + minRevenue;
return Database.query(soql);
}
}The input 0 OR Name != '' produces this query, and no quote escaping could have stopped it:
SELECT Id, Name FROM Account WHERE AnnualRevenue > 0 OR Name != ''The field list, FROM, ORDER BY and LIMIT
Any part of the query that comes from user text is an injection point. Here is a method that lets the caller choose which field to return:
public with sharing class FieldPicker {
// VULNERABLE: the field name comes straight from the caller.
@AuraEnabled
public static List<Account> getAccounts(String fieldName) {
return Database.query('SELECT Id, ' + fieldName + ' FROM Account LIMIT 50');
}
}The caller can pass AnnualRevenue, or Name, Phone, AnnualRevenue, or a child subquery such as (SELECT LastName, Email FROM Contacts). The method wanted one harmless field and returned whatever the caller asked for. Because the method returns sObjects to the client, those values reach the attacker.
The same idea applies elsewhere:
| Injection point | Example of vulnerable code | What an attacker can do |
|---|---|---|
| String literal in WHERE | `'... WHERE Name = \'' + input + '\''` | Close the literal, add `OR` conditions, widen the result set |
| Unquoted number or Id | `'... WHERE AnnualRevenue > ' + input` | Append conditions with no quote at all |
| Field list | `'SELECT Id, ' + input + ' FROM Account'` | Read extra fields or child records |
| Object name | `'SELECT Id FROM ' + input` | Query another object |
| ORDER BY | `'... ORDER BY ' + input` | Sort on fields that leak information, or trigger query errors |
| LIMIT | `'... LIMIT ' + input` | Request more rows than intended, consuming governor limits |
For ORDER BY, the effect is smaller than for WHERE. The sort order can reveal facts about hidden fields, for example by sorting on a field the user should not see and observing the order of rows. Errors thrown by an invalid field name also tell an attacker which fields exist.
What an attacker cannot do
Understanding the limits keeps your risk assessment honest. SOQL is a read-only language. It has no UPDATE, DELETE, INSERT or DROP statement, and Database.query runs a single query. A string such as '; DELETE FROM Account is not valid SOQL, so it fails with a QueryException instead of deleting data. The classic SQL attack of stacking a destructive statement after a semicolon does not apply.
That does not make SOQL injection harmless. The damage is a loss of confidentiality and of access control: reading records, fields and objects that the code never meant to expose. A query that returns too many rows can also exhaust governor limits and break a feature for every user.
Why sharing and security mode raise the stakes
How much an attacker can see depends on the context in which the query runs.
- A class declared
with sharingenforces record-level sharing. Injection can only widen results to records the running user can already see. That matches the first example: "every account the running user can see." - A class declared
without sharing, or one that runs in system context, returns records regardless of the user's sharing access. Injection can then reach records the user was never allowed to see. - By default,
Database.queryruns in system mode. It does not enforce object permissions or FLS, even in awith sharingclass. Thewith sharingkeyword controls only record visibility. A caller who injects a field name can therefore read a field they have no FLS access to.
Running the query in user mode, covered later in this tutorial, limits the damage because the platform enforces permissions on whatever the final query contains. It reduces the damage but does not remove the injection. The attacker still changes which accessible records and fields the query returns.
Seeing the injected query for yourself
You can examine the query text without any records or tools. Run this class in Anonymous Apex or a scratch org. It builds the query string and prints it, so you see what the parser would receive.
public class QueryShowcase {
public static String buildQuery(String name) {
return 'SELECT Id, Name FROM Account WHERE Name = \'' + name + '\'';
}
public static void demo() {
System.debug(buildQuery('Acme'));
System.debug(buildQuery('\' OR Name != \''));
}
}After saving the class, run QueryShowcase.demo(); in Anonymous Apex and open the debug log. The second line of output is:
SELECT Id, Name FROM Account WHERE Name = '' OR Name != ''Printing the final query string is also a useful habit when you debug dynamic SOQL. If you can read the injected condition in the log, so can the parser.
Recognizing the pattern in code review
Look for these signs when reviewing Apex:
- A call to
Database.queryorDatabase.countQuerywhose argument is built with+,String.format, or string interpolation from a variable. - A variable that originates in an
@AuraEnabledmethod, a@RemoteAction, a REST resource, a Visualforce page parameter, or any other value the caller controls. - A query fragment where the user's value appears next to a security-relevant filter, such as owner, record type, or a status flag.
- A string that is assembled in one method and executed in another, which hides the connection between the input and the query.
Taint can travel through several method calls. A parameter that looks internal may come from an outside caller three methods up the stack, so trace the origin of each value rather than judging by its name.
The fixes follow in the next chapters. The most important rule starts here: keep the value out of the query text. Bind variables send the value to the query engine separately, so it cannot change the query's structure.
Exercise
A method runs Database.query('SELECT Id FROM Case WHERE Priority = \'' + priority + '\' AND OwnerId = \'' + UserInfo.getUserId() + '\''). The caller passes priority as x' OR Subject != '. Write the resulting query, then explain why the owner filter no longer protects the results.
Show answer
The query is SELECT Id FROM Case WHERE Priority = 'x' OR Subject != '' AND OwnerId = '005...'. Because AND binds tighter than OR, it means Priority = 'x' OR (Subject != '' AND OwnerId = me). This still limits the second branch to the user's cases, but the attacker controls the first branch. A better payload, such as x' OR Subject != '' OR Priority = ', makes the whole WHERE clause true for any row, so the owner filter is bypassed. Either way, the user's input rewrote the query's conditions, so the filter no longer guarantees that only the user's cases are returned.
Exercise
A developer says that SOQL injection is harmless because SOQL cannot delete data. Give two concrete harms that remain.
Show answer
First, an attacker can widen a filter or add fields and read records or fields the code never meant to return, which breaks confidentiality and access control, especially when the query runs in system mode or in a without sharing class. Second, an injected query can return so many rows that it consumes governor limits and breaks the feature, or lead code that acts on the returned records to update or delete data the attacker selected.