Best Practice - Prevent SOQL Injection in Salesforce

SQL (Structured Query Language) injection is a common application security flaw that results from insecure construction of database queries with user-supplied data. When queries are built directly with user data inlined or concatenated directly with the query text, instead of using type-safe bind parameters, malicious input may be able to change the structure of the query to bypass or change application logic. SQL injection flaws are extremely serious. A single flaw anywhere in your application may allow an attacker to read, modify or delete your entire database.

Apex does not use SQL, but its own database query language, SOQL (Salesforce Object Query Language). SOQL was designed to give you most of the power of SQL, while also protecting against most attacks. For example, in SOQL you cannot update or delete, you can only use SELECT. Because of this, the most dangerous operations, such as deleting or modifying data, are not possible. . Therefore, the risks are much lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection.


How to prevent SOQL Injection ? 

  • Avoid using dynamic SOQL where possible, instead use static queries and binding variables
  • If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input.

Here is an example of moving from a dynamic query to a static query with binding variables:


Dynamic Query

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class SOQLController {
    public String name {
        get { return name;}
        set { name = value;}
    } 
    public PageReference query() {
        String qryString = 'SELECT Id FROM Contact WHERE ' +
        '(IsDeleted = false and Name like \'%' + name + '%\')';
        queryResult = Database.query(qryString);
        return null;
    }
}


Static Query

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class SOQLController { 
    public String name { 
        get { return name;} 
        set { name = value;} 
    } 
    public PageReference query() { 
        String queryName = '%' + name + '%';
        queryResult = [SELECT Id FROM Contact WHERE 
           (IsDeleted = false and Name like :queryName)];
        return null; 
    } 
} 

Source : stackexchange

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 

Post a Comment

2 Comments