[SalesForce] SOQL Injection Vulnerability

In security scan am getting error as "SOQL Injection Vulnerability" and also the note as "The query is user controllable"

string query = 'SELECT '+ queryFields +' From '+MFNameSpaceUtil.PrependNS('MobiForm_Field__c')+' WHERE ';
    return query;

This is my query and doesn't have any idea what would cause the SOQL injection here. Any suggestions will be helpful

Best Answer

Long Story:

Quoting examples from apex documentation:

// User supplied value: name = Bob 
// Query string
SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')

However, what if the user provides unexpected input, such as:

// User supplied value for name: test%') OR (Name LIKE '

SELECT Id FROM Contact WHERE (IsDeleted = false AND Name LIKE '%test%') OR (Name LIKE '%')

To fix this you can either use static SOQL and re-write your SOQL as below

To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables. The vulnerable example above can be re-written using static SOQL as follows:

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; 

For dynamic SOQL use String strEsc = String.escapeSingleQuotes(str);//str is your searchspec from UI

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.

For your use case:

You seem to be constructing the SOQL dynamically. your issue could be with your where clause if the bind variable for it comes from UI.