function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC GuestSFDC Guest 

SOQL injection security checkmarx

Hi All,

Can someone please help me resolve this issue.
I am getting error as "SampleClass.cls Method sampleMethod at line 3 of classes\SampleClass.cls gets user input from the strVar element. This element’s value then flows through the code without being properly sanitized or validated, and is eventually used in a database query in method sampleMethod at line 3 of classes\SampleClass.cls. This may enable an SOQL Injection attack. line no: 2, 5, 6" in checkmarx report. Thanks in advance.

Below is code:
 
public class SampleClass {
public String strVar {get; set;};
public void sampleMethod(){
if(strVar != null){     
    strVar = strVar.trim();
    List<String> varList = strVar.split(' ');   
    //logic
    String str1;
    String qString =  'select id, Description FROM Account';
    if(varList.size()==1){
        str1 = varList.get(0);
        queryStr+= ' and (Account.Name like \'%' + str1 + '%\')'; 
    }
}
}
}
Issue at below piece of code:

public String strVar {get; set;};
public void sampleMethod(){
if(strVar != null){
strVar = strVar.trim();
List<String> varList = strVar.split(' ');

 
Team NubesEliteTeam NubesElite
Hi,
Please try this code it may help you
public class SampleClass {
public String strVar {get; set;}
public void sampleMethod(){
if(strVar != null){     
    strVar = strVar.trim();
    List<String> varList = strVar.split(' ');   
    //logic
    String str1;
    String queryStr;
    String qString =  'select id, Description FROM Account';
    if(varList.size()==1){
        str1 = varList.get(0);
       	queryStr += ' and (Account.Name like \'%' + str1 + '%\')'; 
    }
}
}
}



Thank You
www.nubeselite.com
Developement | Training | Consulting


Please mark this as solution if your problem resolved.
Raquib SFRaquib SF
Hello,

To prevent SOQL injection, you can use the below example
String s = '\'Hello Jason\'';
system.debug(s); // Outputs 'Hello Jason'
String escapedStr = String.escapeSingleQuotes(s);
// Outputs \'Hello Jason\'
system.debug(escapedStr); 
// Escapes the string \\\' to string \'
system.assertEquals('\\\'Hello Jason\\\'', escapedStr);

Please let me know if that helps.

Thanks!