Writing Secure Code on the Force.com Platform
Developers
Brendan O’Connor: Product Security Director, salesforce.com
Safe HarborSafe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of intellectual property and other litigation, risks associated with possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year ended January 31, 2010. This documents and others are available on the SEC Filings section of the Investor Information section of our Web site.
Any unreleased services or features referenced in this or other press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Agenda
Browser Basics
Cross-site Scripting (XSS)
Cross Site Request Forgery (CSRF)
SQL/SOQL Injection
Access Control Violations
Browser Basics – Session Cookies
The user is the session
Usernames and passwords are only used to create
sessions• You only log in once
Sessions can time out if they are not used
Sessions stay alive as long as someone is using it
If an attacker steals your session cookies, the website thinks the attacker is you.
Browser Basics – Tools of the Trade
Local Proxy– BurpSuite Pro
– Paros Proxy
– Web Scarab
Firefox Plugins– Tamper Data
– FireBug
XSS – Cross-Site Scripting
XSS – What is Cross-site Scripting?
Location, Location, Location
Break out of Data and in to Code
– Data - B
– Code - <B>
Reflective XSS
– Requires user interaction
Stored (Persistent) XSS
– Triggers every time the vulnerable page is viewed
Same Origin Policy – XSS inherits the security context of the
vulnerable site
XSS – Reflective XSS Example
Request:
Response:
XSS Request:
XSS Response:
1 http://www.domain.com/MyPage?fname=John&lname=Smith&[email protected]
1 Send an Email to: <a href= “mailto:[email protected] “> John Smith </a>
1 http://www.domain.com/[email protected]” onclick=alert(‘XSS!’); nosuch=“
1 <a href= “mailto:[email protected] “ onclick=alert(‘XSS!’); nosuch=“” > John Smith </a>
XSS – Delivery
Cross-site Scripting can be delivered through:– Email
– Pop-ups
– Malicious web pages
– Hidden Iframes
– URL Shortners
XSS – Visualforce Character Encoding
Visualforce has built-in protections against XSS attacks:– Special characters encoded to HTML safe equivalents
– Context sensitive
• <apex:outputText> < becomes < " is not escaped
• <apex:outputLink> < becomes %3C " becomes %22
– Escape = “False”
• Disables character encoding for that field
<apex:outputText escape="false" >
XSS – Visualforce Exceptions
Script Blocks
Formula Tags
On* Events
*Style Parameters
Insert swf file
<script> var foo = ' {!foo.name} ' </script>
<title> {!$Request.title} </title>
<apex:inputText onclick="{!$CurrentPage.parameters.myEvent}">
<apex:actionStatus Style="{!$CurrentPage.parameters.myStyle}">
XSS – Visualforce Encoding Functions
Context sensitive encoding functions:– HTMLENCODE: escapes < and > characters to < and >
– JSENCODE: uses backslash \ to escape unsafe characters
such as ‘
– JSINHTMLENCODE: escapes for JavaScript and HTML
characters
Correct:
Incorrect:
<script> var foo = ' {!JSENCODE($foo.name)} ' </script>
<script> var foo = ' {!foo.name} ' </script>
XSS – Why is This Important?
XSS can be used to alter forms or re-write the page,
tricking users in to giving sensitive information to an
attacker
XSS attacks can steal session cookies to impersonate a
user
XSS allows an attacker access to any data on the page
XSS – Conclusions
Visualforce will perform automatic HTML escaping in
almost every case <apex: > is used. – See the "Exceptions" slide for details.
Don't call escape="false" on un-trusted input.
JavaScript is not escaped automatically.
Use the encoding functions for the correct contexts.– JSINHTMLENCODE is always a safe choice
CSRF – Cross-Site Request Forgery
CSRF – Cross-site Request Forgery
How it works:– Tricks your browser into doing something you didn't intend
– Can perform actions with your privilege level if you are logged
in
– Relies on the Browser to automatically send cookies
CSRF – Vulnerable Page
1 public void init() { 2 String Item = ApexPages.currentPage().getParameters().get('Item');
3 String Action = ApexPages.currentPage().getParameters(). get('Action');4 if (Action == 'Delete') {5 ToDoList__c list = [Select Item__c ,Description__c from ToDoList__c where Item__c = :Item];
6 delete list;
7 return ; 8 }
9 }
https://na1.salesforce.com/ToDoList?Item=1&Action=Delete
CSRF – Attack
https://na1.salesforce.com/ToDoList?Item=1&Action=Delete
– If the victim is logged in, the session cookie gets sent with the request
– It looks like a legitimate request to the Web application
1 <HTML>
2 ......
3 <img src="https://na1.salesforce.com/ToDoList?Item=1 &Action=Delete">
4 <img src="https://na1.salesforce.com/ToDoList?Item=2 &Action=Delete">
5 <img src="https://na1.salesforce.com/ToDoList?Item=3 &Action=Delete">
6 ......
7 </HTML>
1 <HTML>
2 ......
3 <img src="https://na1.salesforce.com/ToDoList?Item=1 &Action=Delete">
4 <img src="https://na1.salesforce.com/ToDoList?Item=2 &Action=Delete">
5 <img src="https://na1.salesforce.com/ToDoList?Item=3 &Action=Delete">
6 ......
7 </HTML>
CSRF – Targeting CSRF Attacks
CSRF attacks can be targeted
Links that have been recently visited appear as a different color in the
browser
– The color can be inspected through the use of
getPropertyValue(“color”)
1 if (document.getElementById(link.id).currentStyle)
var color = document.getElementById(link.id).currentStyle
["color"];
2 if (window.getComputedStyle)var color2 =
document.defaultView.getComputedStyle(link,null) .getPropertyValue("color");document.body.removeChild(link);
3 if ((color == '#ff0000') || (color2 == "rgb(255, 0, 0)")) {
var item = document.createElement('li');
item.appendChild(link);document.getElementById ('visited').appendChild(item);
4 }
CSRF – Visualforce CSRF Protection
Visualforce has automatic protection against CSRF– Hidden parameters in ViewState have a CSRF token
– Token is tied to the user’s session and Visualforce page
CSRF – Other Request Types
GET Requests do not have CSRF Protection– Don’t Create, Update, or Modify data from the Query string
API Requests– The API ignores the Browser cookies
– Looks for Session ID in the SOAP Envelope
CSRF – Why is This Important?
CSRF tricks a user’s browser into making requests it
did not intend to make
CSRF can be used to force a user to create, update, or
delete data on the attacker’s behalf
The requests look like they came from an authorized
user
CSRF – Conclusions
Visualforce has built-in protections for Post requests
The Force.com APIs ignore the Browser cookies
Get requests do not have CSRF protection
Avoid data manipulation based on Get requests– Creates
– Updates
– Deletes
SQL / SOQL Injection
SQL Injection – What is SQL Injection?
Location, Location, Location
Similar to XSS, SQL Injection attacks break out of the data portion
of a statement and into code.
string username = request.getParameter("username");string password = request.getParameter("password");
…
string bad_select = "SELECT user_name, user_id FROM UsersTable WHERE username = '" + username + "' AND password = '" + password + "'";
SQL Injection – The Classic Example
username = [email protected]
password = MyPassword123
username = [email protected]
password = ' OR 1=1 --
SELECT user_name, user_id FROM UsersTable WHERE username = '[email protected]' AND password = 'MyPassword123';
SELECT user_name, user_id FROM UsersTable WHERE
username = '[email protected]' AND password = ' ' OR 1=1 -- ';
SQL Injection – Other Platforms
In traditional database platforms, attackers can do a lot
of damage by:– Using the UNION operator
– Terminating a SQL statement with ; and write an arbitrary
statement
– Using comment characters to disregard the existing query.
– Calling default stored procedures like xp_cmdshell and
xp_regwrite
With the Force.com Platform, SOQL and SOSL syntax
prevents many of these attacks
SOQL Injection – Force.com
Attackers may be able to view or modify data
Escalation of privilege if Apex is running in System mod
1 public class SOQLController {
2 public String name { 3 get { return name;} 4 set { name = value;} 5 } 6 public PageReference query() { 7 String qryString = 'SELECT Id FROM Contact WHERE (IsPrivate__c = false and Name like \'%' + name + '%\') ‘ ; queryResult = Database.query(qryString);
8 return null;
8 } 9 }
SOQL Injection – Force.com Example
name = Bob
name = NoSuch%') or (Name like ‘
queryString = SELECT Id FROM Contact WHERE (IsPrivate__c = false and Name like '%Bob%')
queryString = SELECT Id FROM Contact WHERE (IsPrivate__c = false and Name like '%NoSuch%') or (Name like '%')
SOQL Injection – Preventing Injection Attacks
Using bind variables prevents SOQL injection attacks
name = Bob
Should Be:
name = Bob
queryString = SELECT Id FROM Contact WHERE (IsPrivate__c = false and Name like '%Bob%')
String queryName = '%' + name + '%’
queryResult = [SELECT Id FROM Contact WHERE (IsPrivate__c = false
and Name like :queryName)]
SOQL Injection – Why is This Important?
SOQL Injection alters database queries
It can give attackers access to data they should not see
It can bypass access controls when run in System
mode
SQL/SOQL Injection – Conclusions
Always use bound variables when possible—they
prevent SOQL Injection
Be careful when using Dynamic SOQL– If you must use Dynamic SOQL, call
escapeSingleQuotes() on untrusted input
The SOQL language helps limit the damage of injection
attacks– No UNION operator
– No chaining of independent statements
– No calls to default Stored Procedures
Access Control
Access Control
Force.com Access Control– CRUD
• Create
• Read
• Update
• Delete
– Field Level Security (FLS)
– Sharing Rules
• Public vs. Private
Apex with Sharing
By default Apex runs in system mode
Use the with sharing keywords on your class to use with
sharing rules
With inner class Inheritance, sharing does not apply, unless
you specifically declare it
1 Public with sharing Class MyController {
... With Sharing is Applied ...
2 Public Class MyInnerClass {
... With Sharing is not applied to this class ...
3 }
4 }
Visualforce: CRUD and FLS
If the object is on the Visualforce page, CRUD and FLS
will be enforced
If the object is de-referenced, CRUD and FLS will NOT
be enforced
– If a String is used instead of an SObject, CRUD and FLS will
not be enforced.
1 Public Class MyController {
2 Public String myAccount { get; set; }
... qryAccount = [SELECT Name FROM Account WHERE Name = :myAccount)]; ...
3 }
4 <apex:outputText value=“{!myAccount}” /> //CRUD/FLS Not enforced
<apex:outputField value=“{!account.Name}” /> //CRUD/FLS enforced
Access Control Methods
A user’s permissions can be checked manually
<sObject>.sObjectType.getDescribe()– isCreateable()
– isAccessible()
– isUpdateable()
– isDeletable()1 Public Class MyController {
2Public String getmyAccount {
3 if (!Account.sObjectType.getDescribe().isAccessible()) {
4 return ‘’;
5 }
6 ...
7 }
Access Control Methods
Field Level Security can also be checked in Apex code
Schema.sObjectType.<sObject>.fields.<field>– isAccessible()
– isUpdateable()
1 Public Class MyController {
2Public String getmyAccount {
3 if (!Schema.sObjectType.Account.fields.Name.isAccessible()) {
4 return ‘’;
5 }
6 ...
7 }
Access Control Methods
Force.com ESAPI– http://www.owasp.org
Simplifies Access Control checks– setSharingMode() Methods for granular Sharing control
– AsUser() Methods that enforce CRUD and FLS
• insertAsUser()
• updateAsUser()
• deleteAsUser()
Why is This Important?
Improper Access Control can expose data that should
be hidden
It can allow users to create, update, or delete data to
which they should not have access
You must perform checks yourself if you use a String,
or the SObject is not bound to the Visualforce page
Access Control Conclusions
Use the with sharing keywords on Apex classes.
Inner classes do not inherit with sharing
CRUD and FLS is automatically enforced when bound
to a Visualforce page
Call isCreatable(), isAccessible(),
isUpdateable(), or isDeletable() to perform
access checks– Or the Force.com ESAPI
More Information
For more information, please visit:
http://security.force.com
http://wiki.developerforce.com/index.php/Security
For more information on the Apex methods mentioned in this
course, check out the Apex Code Developer’s Guide
http://wiki.developerforce.com/index.php/Documentation
Writing Secure Code on the Force.com Platform
D I S C O V E R
Visit the Developer Training and Support Booth in Force.com Zone
Discover
Developer
Learning Paths
Developer training, certification and support resources
S U C C E S SFind us in the Partner Demo Area of
Force.com Zone 2nd Floor Moscone West
that help you achieve
Learn about Developer
Certifications
How Could Dreamforce Be Better? Tell Us!
Log in to the Dreamforce app to submit
surveys for the sessions you attendedUse the
Dreamforce Mobile app to submit
surveysEvery session survey you submit is
a chance to win an iPod nano!
OR
Top Related