{{appName}}

Video - What is Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS)?

  • When an attacker can insert unauthorized JavaScript or other active content into a web page.
  • When other users view the page, the malicious code executes and affects/attacks the user
  • Happens when user-supplied input is reflected in the HTML of a web page and the user input is executed as code
  • A malicious script can:
    • Hijack the user’s session,
    • Submit unauthorized transactions as the user
    • Steal confidential information
    • Simply deface the page.
  • The poor separation between code (the HTML) and user data (the message) means the injected JavaScript is treated as HTML/JavaScript code and the browser executes it

Types of XSS

  • DOM-based XSS: Attack payload is executed as a result of modifying the web page’s document object model (DOM) in the victim user’s browser. Web application’s server or database is not involved here.
  • Stored XSS: Malicious input is permanently stored on a server ( stored in database and retrieved ) and reflected back to the user in a vulnerable web application.
  • Reflected XSS: Malicious input is sent to a server and reflected back to the user on the response page.
    • Attacker needs to convince the user to click a link that has the malicious input in it
    • Link shorteners, which obfuscate the underlying URL are used to implement this attack
    •                      https://badsite.com?c=<script>document.cookie()</script> 
                        

Impact of XSS

  • An attacker can use XSS to send requests that appear to be from the victim to the web server.
  • XSS can prompt the user to download malware. Since the prompt looks like a legitimate request from the site, the user may be more likely to trust the request and actually install the malware.
  • The attacker can monitor and log keyboard entries, possibly finding usernames and passwords to access accounts at later dates

Common XSS Mitigations

  • Input Filtering: If the user inputs <b>Bad</b> page strips or blocks the code, then no unauthorized code run:
    • Blacklisting:Specific “bad” characters or combinations of characters are banned, meaning they can’t be entered or stored. The developer creates a list of known bad characters (such as HTML or script tags) and throws an error if any bad characters are in the input.
    • Whitelisting (more secured): Only characters or words from a known list of entries are permitted, preventing malicious input. For example, if the user enters anything besides numbers in a phone number field, the application throws an error.
  • Ouput Encoding: Prevents malicious payloads already in the system from executing:
    • Server takes all characters that are meaningful in a specific context (HTML, JavaScript, URL) and replaces them with characters that represent its text version.
    • In the case of the "<" character, you can replace it with the characters "<"
    • Browser will understand that you want the text version of "<", not the HTML version.

XSS prevention in Visualforce and Apex

  • Automatic HTML encoding provided by the platform
  • Always encode as close to the rendering context as possible (like in Visualforce)
  • Visualforce: 3 main encoding functions that developers can use to neutralize potential XSS threats:
    1. HTMLENCODE - value is going to be parsed by the HTML parser Hello {!HTMLENCODE(Account.Name)}
    2. JSENCODE - value is going to be parsed by the JavaScript parser var x = '{!JSENCODE($CurrentPage.parameters.userInput)}';
    3. JSINHTMLENCODE : value is combination of both {!JSINHTMLENCODE(Account.Name)}
  • Apex using ESAPI - Lightning Platform ESAPI: ESAPI.encoder().SFDC_HTMLENCODE(person.Title__c)

SOQL Injection Prevention

  • Static queries with bind variables:
                  
        queryResult = [select id from contact where firstname =:var];
        // With a bind variable, the attacker isn’t able to break out and control the SOQL query
                  
                
  • String.escapeSingleQuotes(): prevent all forms of SOQL injection
                  
        whereClause += 'Title__c like  \'%'+ String.escapeSingleQuotes(textualTitle) +'%\' ';
        whereclause_records = database.query(query+' where '+whereClause);
                  
                

SOQL Injection Prevention - 2

  • Type casting - only effective against non-string input
                  
    whereClause +='Age__c >'+string.valueOf(textualAge)+'';
    database.query(query+' where '+ whereClause);
                  
                
  • Replacing characters
                    
    // The code to remove all spaces from a string can be written as follows
    String query = 'select id from user where isActive='+ var.replaceAll('[^\w]','');
                    
                  

SOQL Injection Prevention - 3

  • Whitelisting: Create a list of all “known good” values that the user is allowed to supply. If the user enters anything else, you reject the response.

Cross-Site Request Forgery (CSRF)

  • A malicious application causes a user’s client to perform an unwanted action on a trusted site for which the user is currently authenticated
  • CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.
  • By sending a link via email or chat, an attacker may trick the users of a web application into executing actions of the attacker's choosing.
  • For a normal user: A successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth
  • If the victim is an administrative account, CSRF can compromise the entire web application

Sequence

  • The attacker got the user’s client (the browser) to perform an unwanted actions

Prevention - CSRF

  • CSRF requires the targeted user to visit the attack page while authenticated with the targeted service, which often requires coordinated deception on the part of the attacker (this is mostly commonly seen in phishing campaigns).
  • For this attack to succeed, the attacker had to know the exact name of the parameters and also supply the associated values
  • If you made the token parameter value a random, unique value that changed on every request, this make it next to impossible for an attacker to guess the current value, preventing the attack
    1. All sensitive state changing requests (anything performing database operations) must include the token.
    2. The token must be unique to the request or user’s session.
    3. The token must be difficult to predict (long and random).
    4. The token must be validated by the server to ensure the request originated by the intended user

Salesforce OOTB CSRF prevention

  • Platform includes a com.salesforce.visualforce.ViewStateCSRF parameter in the form, and that token is validated on submission.

Additional tips

  • To make this com.salesforce.visualforce.ViewStateCSRF paramter kick in: we’ll need to change any outputLink to a commandButton (so the random form parameter will kick in) so when the user clicks the link, it executes Apex code rather than refreshing the page.

Clickjacking

  • On a clickjacked page, the attacker displays some benign content to the user while it loads another page on top in a transparent layer. On the clickjacked page, the users think they are clicking buttons corresponding to the bottom layer, while they are actually performing actions on the hidden page on top.

Clickjacking - Prevention

  • Use Frame-Busting Scripts: Prevents an attacker from loading your website in an iFrame. The script attempts to detect if the page is loaded in a frame. If detected, it will prevent the page from loading.
                           if (top != self) top.location = self.location; 
                        
  • Use X-Frame Options: X-FRAME-OPTIONS:
    • DENY — Prevents the page from loading in a frame completely.
    • SAMEORIGIN — Allows framing only if the origin is the same as the content (for example, Salesforce.com versus evilsite.com).
    • ALLOW-FROM — Enables framing only from a specific URL.

Common uses of Clickjacking

  • Tricking users into enabling their webcam and microphone through Flash (also known as Cursorjacking).
  • Tricking users into making their social networking profile information public.
  • Downloading and running malware, enabling a remote attacker to take control of others’ computers.
  • Making users follow someone on Twitter.
  • Sharing or liking links on Facebook (also known as Likejacking).
  • Clicking Google AdSense ads to generate pay-per-click revenue.
  • Playing YouTube videos to gain views.
  • Following someone on Facebook.

Using Salesforce Clickjacking Protection

  • Salesforce leverages both frame-busting scripts and the X-Frame Options header as standard clickjacking protection.
  • By default all standard Salesforce pages are protected against clickjacking; however, as a developer you can extend this protection to your custom Visualforce pages.

References