No Results
Search Tips:
- Please consider misspellings
- Try different search keywords
Newer Version Available
SOQL Injection
In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own database query language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks are much lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection. In summary SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application into performing unintended commands.
SOQL Injection Vulnerability in Apex
1<apex:page controller="SOQLController" >
2 <apex:form>
3 <apex:outputText value="Enter Name" />
4 <apex:inputText value="{!name}" />
5 <apex:commandButton value="Query" action="{!query}“ />
6 </apex:form>
7</apex:page>
8
9public class SOQLController {
10 public String name {
11 get { return name;}
12 set { name = value;}
13 }
14 public PageReference query() {
15 String qryString = 'SELECT Id FROM Contact WHERE ' +
16 '(IsDeleted = false and Name like \'%' + name + '%\')';
17 queryResult = Database.query(qryString);
18 return null;
19 }
20}1// User supplied value: name = Bob
2// Query string
3SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')1// User supplied value for name: test%') OR (Name LIKE '1SELECT Id FROM Contact WHERE (IsDeleted = false AND Name LIKE '%test%') OR (Name LIKE '%')Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended logic of any vulnerable query.
SOQL Injection Defenses
1public class SOQLController {
2 public String name {
3 get { return name;}
4 set { name = value;}
5 }
6 public PageReference query() {
7 String queryName = '%' + name + '%';
8 queryResult = [SELECT Id FROM Contact WHERE
9 (IsDeleted = false and Name like :queryName)];
10 return null;
11 }
12}If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.