You are on page 1of 22
© FOCUSONFORCE User Interface Given a scenario, prevent user interface and data access security vulnerabilities Develop your career with Salesforce Training and Certification Preparation [@ rocusonronce Table of Contents © scoxinecion © Cross Site Request Forgery © cooissie sri © controling Data sccess © secuine Sensive Data © suosscanedvauesin VinalioncePases © scenainsssoutions | rocusonronce After studying this topic, you should be able to: © entity te terent types security uneabttiesin Salesforce apleations @ Determine the recommended techniques and practices to protect users from security attacks, © Anayze various business scenarios and deny how to prevent security vulnerabilities |e rocusonronce 2 Introduction This topic describes the most common security vulnerabilities such as ‘SOQL injection, Cross-Site Scripting (XSS),Cross-Site Request Forgery (CSRF), and athers for applications on the Salesforce platform, Pp Although Salesforce provides bullt-in protection against several types of security risks, developers need to take advantage of Salesforce security features and implement proactive measures to protect custom applications from potential security attacks dependingon the requirements and customization Involved, ‘Application security flaws can result to manipulation or exposure of Salesforce data. The programmatic techniques for preventing security vulnerabilities will be covered inthis topic Security Vulnerabilities Here are the most common security attacks or risks that custom applications developed particularly Using Apex and Visualforce can be vulnerable to. Exel uaa) .@ S0QL Injection © Cross-Site Scripting (X85) © Cross-Site Request Forgery (CSRF) 1@ Data Access Control Issues “@ Third-Party Contentssues |@ rocusontonce ® SOQL Injection =a |e rocusonronce n SOQL Injection ‘SOQ injection is a technique that is used to inject values to manipulate the construction and ‘outcome of a dynamic SOQL query. =a BNL Ealzag Bae erie) eee ‘COMMAND MODIFICATION METHOD S0QL injection can UnlikeSQL.SOQL only Theuserinputcan modify Themethod or approach potentially occur when supports the SELECT the intended SOQL sed in traditional SQL user-supplled inputisused keyword and does not statement and resuitin | Injection are very similar to toconstruct adynamic support commandssuchas unintended harmful howSOQL injection can be SOQL statement. UPDATE or DELETE. This results executed in SOQL. “restriction’ protects SOQL from most attacks. |@ rocusonronce Es] Techniques to Prevent SOQL Injection Salesforce recommends the following techniques for preventing SOQL injection attacks, © BIND VARIABLES ‘An input can be enforced tobe treated asa variable and not an ‘ o ‘executable part of the query @ TYPECAST VARIABLES ito thelr respective ‘Typecasting ls where varlables are casted accor data types (eg, Boolean, Integer) to intentionally throw exceptions when ‘unexpected data types are encountered. © rocusoyronce 4 Techniques to Prevent SOQL Injection © ESCAPE SINGLE QUOTES ‘An escape character can be added tall single quotation characters Using String.escapeSingleQuotes() to ensure thatthe strings are not i @ ALLOWLIST VARIABLES ne °° | = should be avolded. & - ‘SANITIZE INPUT ‘Also known as restricted ls, this approach Involves removing potential bad characters fromuser input. |@ rocusonronce SOQL Injection Example ‘The following demonstrates a Visualforce page for searching partner accounts based on user input received from a form: “peepee cotailePertersontller poblge toss Partneacontreiler¢ rector public Listeecort ores ripen vite 2> Debit Sting rome ( en ee trator mass) re fee sone 2 sete = op : spontorw bite raetteanceesey) { ysting = SECT 18 FROM Ace rg 'cie (ierarter = toe hae fast stabs. uy eet |@ rocusoyronce SOQL Injection Example [Svlng cnritrng = LECT 12 FOU decane WE (Gl Tr aS re EV ESP A ring qurystring = “SLE a FO acoune RE re 0 ane CIE VSS) OR (ave HE VALI Sing quriane = nae + (perpen = (SELECT 14 FRO Lest ERE (fata «true MD ne LE say) |@ rocusonronce Escape Single Quotes Example The below illustrates how the escapeSingleQuotes method adds escape slashes to a string value. SoS acon ene Devt ma fewtae — enoen [tbat we Enter Apex Code ax string @ = "\"aelio Worla\"'y Syatensdebog(e)s String excapedstr = stcing-eacapasinglegsotes(=); 5 Syaton.dabug(escapedstr)+ (Plopen tog Eats | Sate Honahes [Eis Frome Eeseousbie Wi DabugGny Eitan [Cie ee orth og FOCusoNFORCE Cross-Site Request Forgery [@ rocusonronce Cross-Site Request Forgery ee © REDIRECT USERS Anattacker includes a URLon theiesite that performs an action on a second ite. PERFORM ACTIONS tthe user still authenticated to the second site, the action may be successful. i there is no protection. | rocusoyronce =a Cross-Site Request Forgery Below are considerations regarding protection from CSRF. BUILT-IN PROTECTION Salesforce has default protection builtin that validates a token, ACTION TYPES. Possible action types are create arecord, send email logacall,custom Visualforce, update a record, Lightning component, and flow. ‘AVOID STATE CHANGES =a Developers can ensure built-in protection isused by avolding state changing operations. Cross-Site Request Forgery The following shows the built-in CSRF protection configuration in Setup: (Gross-Site Request Forgery (CSRF) Protection Enable CSRF protection on GET requests on non-stup pages Enable CSRF protection on POST roqustson non setup pages, Content Security Policy protection (CoOverise Restriction on Accessing Emal Tempiaos in SalosforceClasic Using Internet Explorer i |@ rocusonronce Cross-Site Request Forgery Salesforce implements builtin anti-CSRF tokens in all its standard controllers and methods. © REQUEST VALIDATION Before executing a command, Salesforce automatically checks this hidden token to verify the authenticity of the page request. @ CUSTOM CONTROLLERS Custom controller can become vulnerable to CSRF attacks. | rocusonronce Cross-Site Request Forgery Example The following Visualforce page is used to delete a contact by passing the id of the record to delete in the URL. This example in its current state is vullerable to CSRF attacks. 11 visualtorce controlier public class myCurtoncontrotler ¢ 11 This method 5 called as soon oe the Visuslforce page 1s Losded public veld initQ) { 17 Retrieve the record based on the Ad paraneter from the URL 1 Ad » Apexdages.currentbage) getParaneters() get '48"); Contact record» (SELECT 10 FROM Cortact MMERE Td = :46); ‘When the Visualforce pageis accessed. the a ee Inti simely rsuied. » los Visualforce page => “apen:poge controller="nyCustonContrel2er” actione"(init)"> Cross-Site Request Forgery Example For example, an attacker can create a web page that contains the element below. When a logged-in org, user lands on this web page, a request to the Visualforce page will be made on behalf of the user. icthe"2* 7 Masqueraded as atx pixel image, the request wil Immediately invoke the nit method and potentially delete _any matching record without the current user's knowledge. @ rocusoyrorce * Cross-Site Request Forgery Example To protect the page against CSRF, for example, the controller's delete logic should be removed from the init action and placed in an action method that is not automatically run when the page loads. cepexiparen nanes"eccountid" valuee'{Irecord.14)” aasignton"(!currPersontd)"/> ‘On the Visualforce page, the action canbe exposed through a button using the commandLink component. In this Implementation, an ant-CSRF token is generated which willbe validated by the system before the action is performed. |@ rocusonronce Cross-Site Scripting (@ rocusonronce Cross-Site Scripting (XSS) Cross-site scripting is when malicious content such as JavaScript / VBScript / HTML is inserted into a web page and executed, USER SESSION The script can take advantage of the user's session and sel tosubmit transactions, read data or alter the page using =a HIML/CSS, © rocusonronce 2| Cross-Site Scripting (XSS) Below are considerations regarding protection from XSS. UU atc Checking user input against that onlythe -Allstandard Visualforce Salesforce hasimplemented defined values appropriate characters are components,whichstart ‘filters that screen out displayed, with have ant-XSS | harmful characters inmost filters in place. ‘output methods as one of the ant-XS5 defences, © rocusonronce al Cross-Site Scripting (XSS) Example Cone example of coss-site scripting isa Visualforce page that receives userinput via tre unt. geciguge cotter iy proritenage’> ents scan petanrty2e (caper arovovt") Sema he Soe pernear at soar 1 aaah Viuatore cneatar, the van of M4 ovtputont vr 11 Seger ee \@ rocusonronce Cross-Site Scripting (SS) Example Then, an attacker can supply the “text” URL parameter with a malicious image tag and render it on the Visuatforce page. iy id paranter-value"» [ing erabe onerror alert Welle Werle TP] ave ‘When an image tag such asthe one above is rendered, the onerror event wil be triggered since the sre attribute contains {an invalid value. The attacker can potentially execute harmful JavaScript code through the onerror attribute, © rocusoyronce 2 Cross-Site Scripting (XSS) Example The onerror event can be prevented by encoding the output coming from Apex. The String class comes with HTML escape and unescape methods, String bodoutput = "cine sr be onerrore’alert(V Hele Horlé\"):°/>"s Syston. cbug( "1 11 Syston debug stp: TIAL cling sresabe onerrare"elert( ‘Mello Mord 11-2. datying srceabe onerroraBquot alert (843 This example shows how an escape method i used toencode astring. |e rocusonronce x Controlling Data Access erocusosonce a Data Access Control ‘Apex class executes in system mode and may expose sensitive data to unintended users. © FULLACCESS ‘Apex does not enforce user permissions and field level security, granting full access to records, © WITH SHARING Using the ‘with sharing’ keyword ensures that the permissions of the ‘currently logged in user are use. @ INHERITED SHARING ‘The lnherited sharing! keyword can be specified on an Apexclass to allow the class torunin the sharing mode ofthe cass that called it |@ rocusonronce Data Access Control © SHARING BEHAVIOR “The Apex class that uses the inherited sharing’ keyword runsas with sharing’ when used as a Visualforce page controller, Apex REST service, ‘or an entry point to an Apex transaction. LIGHTNING COMPONENTS. -] (@AuraEnabled Apex lasses used by Aura components or Lightning web ‘cores opin rod hh @ default to "with sharing" to ensure that Lightning components are secure by default OMITTED DECLARATION Itan Apex class Is used asthe entry point to an Apex transaction, an ‘omitted sharing declaration runs as without sharing Using the “inherited sharing’ keyword ensures that the dfaultistorun as with sharing’ |@ rocusonronce Data Access Control © EXPLICIT DECLARATION Using an explicit inherited sharing’ declaration makes the intent clear, _avoiding ambigulty arising from an omitted declaration or false positives ‘rom security analysis tooling. WITH SECURITY_ENFORCED “The WITH SECURITY. ENFORCED clause, which enforces field and object level security permissions, can be added toa SOQL statement which will ‘cause the query to throw a System.QueryException if the current user {does not have access oa field or object thats referenced in the SOQL statement. SECURITY.STRIPINACCESSIBLE The Securtystripinaccessible Apex method can be used to remove fields from $SOQL query results thatthe current user does not have access to ‘and avold exceptions when a DML operation performed. | rocusonronce WITH SECURITY_ENFORCED Example ‘This clause applies security cheoks in the SELECT or FROM SOQL clauses but not on WHERE or ORDER BY clauses. So, a query cane filtered, for example, using afield that the user does not have access to. LUseccantacty coats [ swiene anual Salary > 200000 coer oyna Stang oes 1 1 staquary example css % 7; evneonjce thee quay expe (act eh et fot opti » [erosion 7 Security.stripInaccessible() Example An AccessType enum value le apectied when using the method to lndleate the typeof fieldevel access check to perform, Valid enum values are CREATABLE, READABLE, UPDATABLE, and UPSERTABLE. eee ssn arty ah | > uote stant vol weeafntean (ts portlets, Sting Sof, acim salen) & scion poten » [SELECT Ifo, Salry_e RON Pitin_e MEE 24» pusctont LUseeeniion 0 positing = on \SnePsitin eo patton 3s (rasta sy Fist tron ta racadh tho the carat cnet fo tat sone to wate Sovjettccenoneision sad = Sewitystiptncces bE UNTER] positon); Upance seteececoras(y /) esception raises te Felt seri oe helets une mnng the ONL stent , | rocusonronce Enforcing Object and Field Permissions Object-level and field-level permissions can be enforced through code by explicitly using sObject and field describe result methods. The following describes some of these methods. OBJECT-LEVEL © IsAccessiblel)-returns true current user can access the object. © isCreateable()- returns trueifcurrent user can create records ofthe object. © IsUpdateable()- returns true current user can update records ofthe object. © IsDeletable()-returns true current user can delete records ofthe object, gs check ifuser has Delete permission on Lead object ‘Schema.sObjectType-Lead isDeletable) |@ rocusontonce Enforcing Object and Field Permissions FIELD-LEVEL ® IsAccessiblel)-returnstrueifcurrent user can access the field of arecord © IsCreateable new record. ® IsUpdateable()- returns true fcurrent user can update the value ofthe held for an existing record, returns trueif current user can set the value of the field for a Exgicheckif user ean update the Company feld on the Lead object: ‘Schema.sObjectType.Leadfields.CompanyisUpdateablel) |e rocusonronce =a Enforcing Object and Field Permissions Note that describe information can be retrieved either from a Describe result or through a token. ‘lie stele ve erptPoieion(tring tite, string nfo, Dine ela) 5 (PonSon_. steep. eedeverite()Scretele() ae false) fe [Object level acess check (io, i (sham snjectype Poneto icresteti() ‘hess yeatonnegtion( carer ser Bn silo 29 Le) flee) @ ioscan ‘ser th tsiionSno.")}-— Plelgrevel access check > 1 (Bsion_eanfa_e.gezeteria() cre Uae ab (cen. sojerioe nition Psa \)-teresaaie() we fee) Sian trisae sean) e deetatabe() | ot alowed tof the Psion sary. "9b > 2 cnostan_esatny_cerecer Uo, ot (sem nino ‘a myaneontcaptlon errant 4 > 1 11 septs $0, proceed to erate the Psion recor |@ rocusonronce Here is an example method that performs preliminary object-level and field-level permission checks. Using ‘With Sharing’ Keyword with sharing declaration of the custom controller. Lv public with sharing class testControlier { 2+ 2 4 Ba © rocusoyronce ‘The Visualforce page below will access records using the sharing rules of the current user due to the 2+ public ListeAccount> getaccounts(){ a ‘“/this will return only Account records that are visible to the current user ‘ return [SELECT Name FROM Account LIMIT 10]; 5} 6) Lv Using 'Inherited Sharing' Keyword The following shows how to declare an Apex class, or in this case, a custom controller, with inherited sharing, 1 //This Apex class uses the ‘inherited sharing’ keyword 2 3 + public inherited sharing class CustomAccountController { 4 public List getAllaccounts() 5+ { 6 List accounts = [SELECT Name FROM Account]; 7 return accounts; 8 + 9 |} |e rocusosronc Using an Inherited Sharing Class in Visualforce ‘An Apex class that is declared with inherited sharing will run as with sharing when used on a Visualforce page such as the below. + +

{laccount .Name}

9 16
|@ rocusoyronce Secure Retrieval and Display of Third-Party Content Visualforce provides methods to safely display third-party content on the page. IMAGE CONTENT When a Visualforce page loads a third-party image outside the o's server itcan initiate a malicious authentication request meant to steal Salesforce usernames and passwords. @ IMAGEPROXYURL FUNCTION ‘The IMAGEPROXYURL function can be used to securely retrieve images ‘and protect users from unauthorized requests. @ USING IMAGEPROXYURL. “The IMAGEPROXYURL function canbe Included on the'sr’ attribute of a tagor the value‘ attribute ofan object. |@ rocusonronce Secure Retrieval and Display of Third-Party Content © HTMLCONTENT HTML static resources can be isolated ona separate domain using iframes to protect Visualforce content from untrusted sources. © $IFRAMERESOURCE static HTML filecan be referenced on a separate domain by using SiFrameResource. as amerge field, where “resource.name'is the name ofthe uploaded static resource. © rocusoyronce ‘The following shows how to safely display an external image on a Visualforce page. © rocusonronce Using the IMAGEPROXYURL Function a Displaying Visualforce Pages in External Domains Visualforce pages can be displayed on trusted external domains using iframes by allowing it in Session Settings in Setup hc Praacton ewe dearer Sate dso nore Vos ero oa (Both options allow framing on trusted external ee ionotropic ee domains and offer elekjack protection, on nr sy eee et Soha ncn 04 etc att | rocusoyronce Securing Sensitive Data [@ rocusonronce a Securing Sensitive Data Salesore provides mupe ops for secringseetve dala such a patewords enon Keys nuh ens ee © DECLARATIVE OPTIONS. Sensitive data can be stored using the declarative features: protected ‘custom metadata types, protected custom settings, encrypted custom fields, and named credentials @ PROGRAMMATIC OPTION Data can be programmatically secured through encryption and «decryption using methads provided by the Crypto Apex class |@ rocusonronce Securing Sensitive Data The Crypto Apex class contains the following encryption and decryption methods. © encrypt{) and decrypt() These method are used when enerypting and decrypting data sing custom nitalization vector. ® encryptWithManagedIV() and decryptWithManagedIV() “These methods ae used for encrypting and decrypting data using an initialization vector (WV) generated by Salesforce | rocusonronce « Securing Sensitive Data NOTE © Aninitistizstion vector in eryptography isan arbitrary number that i used in combination with asecret key to prevent generating a sequence of text thats Identical toa previous sequence. © rocusonronce “ Data Encryption Example ‘The following shows an example which uses the AES (Advanced Encryption Standard) algorithm to ‘encrypt and decrypt data. @ rocusoyrorce E Unescaped Values in Visualforce Pages [@ rocusonronce “ Visualforce Page Output and Formulas Visualforce components with escape attribute set to false or formula expressions evaluated outside a Visualforce component display unfiltered values and pose a security risk. X__[Romeernntoeeigy_Comettneatn we [amzing cotsoer="Contartinueforeoaah™ ightninattyiesbeta="erae™> “apessdapettext sises"48* value" (yoartensage)"?> “pest cetemnabetion evendar=anasetatiogleg™ ; ing: 309%; 2) tee - ERR "fhe ‘netage you entered aloe {Tyourmessuge}” |@ Focusovronce Displaying Unfiltered Values on a Page Here are two examples of how displaying unfiltered values on a Visualforce page exposes vulnerability to cross-site security attacks. © > © @ Montini evades conocer a a ao) segs weak 2 tame ceca ttt © tr © mm Escaping Unfiltered Values Salesforce offers the following functions that can be used onthe isualforce page to escape HTMLENCODE This function encodes text and merge field values to be used in HTML by eo? aa a “ale. @ JSENCODE This function encodes text and merge field values to be used in JavaScript by inserting escape characters before unsafe JavaScript characters. & |e Focusowronce |@ Focusowronce Escaping Unfiltered Values © JSINHTMLENCODE ‘This functions a combination of the HTMLENCODE and JSENCODE functions where the former willbe executed fist and then the later. ® URLENCODE & This function encodes text ane merge eld values for usein URLs by 4 5 replacing legal characters ina URL with code to represent them based on RFC3986, | rocuso\ronce Escaping Unfiltered Values Examples To display secure values, the escape attribute in Visualforce components that suppor it should be set, to true. Also, the necessary functions should be used accordingly such as illustrated below. sel eons cbr ae em en SS SSS] $$» © rocusoyronce No Protection From XSS There are two areas where Salesforce does not implement built-in XSS protection, This is to allow ‘execution of JavaScript code that is actually intended by the developer. J Custom JavaScript code that | JavaScript code that Is donotusefilter functions is includedin the incudeSeript rot protected. component isnot protected. crip |e rocusonronce Scenarios & Solutions [@ rocusoyFonce ss) Scenario & Solution @ SCENARIO rater ent eee ear ee ee -_hr-rr cog alae aes ee Ea rrr public Pagenaference search() { String query = “SELECT Td FROM Account WHERE Name LIKE \"R" + name + °R\""5 ‘queryResult ~ ostabace.query query) return nulls } However, fauserentersavalue suchas nu128* O8 Mane LIKE ',the query returns ll the account records, ‘An appropriate measure is required to prevent this SOQL injection. |@ rocusonronce Scenario & Solution SOLUTION To prevent S0Q_ injection in this scenario, instead of using dynamic SOQL. the search] method should sea staticSOQL query witha bind variable to retrieve the account record, public PageReference search() ( ‘String queryiane = "5" + naa 4°"; ‘ueryResult = [SELECT Ld FROM Account WERE lane LIKE squerytane] y Hauser provides the value of 2118 me LIKE ‘then the SOQL query tries to find account records usingthe comparison Stans IRE 'énull8' CR sane LENE 4" ‘whieh shouldideally not match any records. |e rocusonronce re @ scenario eral eae heme petEennty 4% Soman Sept) tar tectges However, the page is uilerable to cross-site scripting attacks since a user can provide malicious input parameter such yor) $3582F#25, which would result in the executlon of the following code: “seritpocaer. getter 1 ISorgnen. put) Sonerh & “yoert(eroro/"eleesats | rocusonronce Scenario & Solution SOLUTION The XSS attack can be avoided by preventing the execution of potential JavaScript code that i inserted by the attacker. This can be done by using the JSENCODE function such as below socunertgrtEenertyla("{ISconsenent. input}. SonerMTi. = "{IDSEICOE(SturrantPage. prance Smet) ‘The JSENCODE function encodes text and merge field values by automatically inserting escape characters before unsafe JavaScript characters like the double quotation mark |@ rocusonronce Scenario & Solution @ SCENARIO {A Visualforce page allows users to delete a contact by passing the record Id of the contact as a URL parameter, The page and its custom controller contain the following code: sete ylapnaee nani wtd nie fie er rset) et 48 “enece e's [SLE 1a Hon anact ad 2 , > However, the page is vulnerable toa CSRF attack. For example, if user visits the web page ofan attacker while being authenticated with Salesforce the attacker can easily delete a contact record. | rocusonronce |@ rocusonronce SOLUTION Every Visualforce form includes an ant-CSRF token asa hidden form field that can prevent a CSRF attack However, inthis particular case, the inti) method Is called before the Visualforce page's Inorder to prevent the attack, the action attribute should be removed from apexpage. The ‘pexccommaneButton component can be added tothe page so that users are required to click 2 button te delete a particular contact record, The ation attribute can be added tothe component and associated with the Apex method in the custom controller that deletes the contact record apex: conmandbutton actSone"{!init)"/> clapex:pese> Scenario & Solution @ SCENARIO © A developer has defined a quick action forthe Account del page. It invokes a flow that uses an Apex lass to execute ‘operations ke updating the value of some custom fields on all the related contact records. However, these operations are performed forall the records. even ifthe current user does not have the permission to view them, patie cise Fecias ‘emcees The sales director ofthe company would lke to ensure that, atte recieve pro > , |e rocusonronce the operations are performed only for the records that the User can view and update, a |e rocusowronce Scenario & Solution SOLUTION By default, an Apex class has the ability to read and update al the data in the org, regardless ofthe sharing permissions of the current user. In order to ensure that the class uses the security sharing, permissions ofthe current user who is logged in, the ‘with sharing’ keyword can be added tothe definition ofthe Apex lass pubise wlan sharing clase Fou trvocebienethod public static vold process() { > > Learn More @ develonsecure Web Anos @ = Tips for Apex and Visualforce Development @ sccustvGudetines for Aoexand Viualorce Develooment @ secueCodine SOL biection @ secure Coding Cross Site Scriating © secureCosinerossSiteReauestForzry |@ rocusonronce Learn More © securing YourData © dwamkcsoa @ comocis |@ rocusonronce

You might also like