Newer Version Available
SOQL Injection Due to Insecure Database Query Construction
SOQL injection is a vulnerability in which a user directly controls portions of a SOQL database query. SOQL queries executed in Apex don’t respect user permissions. Therefore, SOQL injections can be used to elevate users’ privileges and allow them to access to data beyond their user permissions.
The two types of SOQL injection vulnerabilities require different protection approaches.
In the first type, the user supplies an incorrect table or field name to query against. When user data identifies a field or table name, you must verify that the user has permission to access the named table or field. Keep in mind that this type isn’t a quoted context.
In the second type, the user supplies a portion of a quoted WHERE clause. When user data is inserted into a quoted string context, the data can break out of the quoted context. The preferred protection approach is to use bind variables. Alternatively, you can use EscapeSingleQuotes(). Both of these approaches prevent the user data from breaking out of the quoted context.
Never allow users to supply portions of SOQL queries other than field names, table names, and WHERE clause inputs.
Avoid executing user-generated queries in Apex, where they run in system mode. If you must generate more complex client-side SOQL, use the REST or SOAP API, which make SOQL calls safely.
To learn more about SOQL injection and how to prevent it in your code, check out the Secure Server-Side Development module on Trailhead.