[SalesForce] SOQL Injection Solutions Help – (Used esacapeSingleQuotes(str) – gives error = no viable alternative at character ‘\’ )

I am facing some issues with following SOQL Query :
My Scanner result gave me SOQL Injection Errors, can anyone help in fixing those –

I am going throw lots of Google Search and Stuff, but it will be great if I am able to fix these ASAP.

1)

 String query = 'SELECT Id,Subject,Status,OwnerId,Owner.Name,Owner.IsActive,ActivityDate FROM Task WHERE OwnerId in (SELECT ID FROM User WHERE isActive = true) AND ActivityDate ='+ selected;

2)

myuserid=ApexPages.currentPage().getParameters().get('userid');
        filter =ApexPages.currentPage().getParameters().get('Filter');
 squery = 'SELECT Id,Subject,Status,OwnerId,Owner.Name,Owner.IsActive,Priority,ActivityDate,ReminderDateTime,Whoid,Who.name FROM Task WHERE OwnerId=\'' + myuserid + 
                        '\' AND ActivityDate='+filter;                        

List<Task> lsttask = Database.Query**(String.escapeSingleQuotes(squery));**

ERROR :

System.QueryException: line 1:137 no viable alternative at character
'\'

Best Answer

The salesforce security scanner should of give you some potential mitigation information such as:

To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables. The Mitigations vulnerable example above could 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;
    }
}

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

You can use the escapeSingleQuotes method in the following way:

Database.Query(String.escapeSingleQuotes(squery));

More information on escapeSingleQuotes can be found here

Related Topic