Presentation is loading. Please wait.

Presentation is loading. Please wait.

Securing Rich Clients and RESTFUL Services Sumit Daryani Vikas Charak Sept 25, 2013.

Similar presentations


Presentation on theme: "Securing Rich Clients and RESTFUL Services Sumit Daryani Vikas Charak Sept 25, 2013."— Presentation transcript:

1 Securing Rich Clients and RESTFUL Services Sumit Daryani Vikas Charak Sept 25, 2013

2 2 Verisign Public Web Development Trends Web UI Architecture Client side security assumptions Most common web client threats and countermeasures Most common REST API threats and counter measures Agenda

3 3 Verisign Public Trends in Web Development [Source: Col 1-4: wikipedia.org] as of Sept 2013 [Source: Col 5 : progammableweb.com]

4 4 Verisign Public Web UI Architecture

5 5 Verisign Public Browser Sandbox Same Origin Policy (Origin = scheme://host:port) Same-origin policy for DOM access Same-origin policy for cookies Same-origin policy for XMLHttpRequest Same-origin policy for Flash/ Java/ Silverlight Same-origin policy with HTML5 Client-side Security Assumptions Making cross domain AJAX requests with modern browsers (http://caniuse.com/cors)  document.domain, img, script, css  cookies consider only host  XHR Level 1  custom policies  XHR Level 2

6 6 Verisign Public A1 Injection A2 Broken Authentication and Session Management A3 Cross-Site Scripting (XSS) A4 Insecure Direct Object References A5 Security Misconfiguration A6 Sensitive Data Exposure A7 Missing Function Level Access Control A8 Cross-Site Request Forgery (CSRF) A9 Using Components with Known Vulnerabilities A10 Unvalidated Redirects and Forwards OWASP Top 10 Web Security Threats for 2013

7 7 Verisign Public DEMO – Client and Server Side Vulnerabilities A1 Injection SQL, DOM, JSON, XML A2 Broken Authentication and Session Management Session fixation and Session sidejacking A3 Cross-Site Scripting (XSS) Non-persistent (reflected), persistent, DOM based A4 Insecure Direct Object References A6 Sensitive Data Exposure Access to data at rest, in transit, in browser A7 Missing Function Level Access Control A8 Cross-Site Request Forgery (CSRF) Malicious request for victim to execute  Client Side  Server Side

8 8 Verisign Public A1 Injection : DOM, JSON DOM Injection: Attacker manipulates the DOM and submits the request Attacker manipulates the response being fed to a function to directly update the DOM Disrupts page flow Countermeasure: Avoid using eval() to control DOM Validate inputs on server-side JSON Injection: Attacker Intercepts and tampers with the data from/ to web server Countermeasure: Validate inputs on server side. Ensure that all transactions are conducted with appropriate authorization Web Server: myapp.com Attacker

9 9 Verisign Public A2 Broken Authentication and Session Management Countermeasure : Use secure, HttpOnly cookies. Do not accept session identifiers from GET / POST variable Regenerating the session id after a successful login Tomcat Server – context.xml Additional checks - IP address matches with last used during that session. Public cafes / Intranet ? } can be configured in web.xml

10 10 Verisign Public A3 Cross Site Scripting (XSS) Reflected Injected code in request is reflected in the response by the web application Example, attacker sends the victim a misleading with a link containing malicious JavaScript alert(‘XSS’) Same attack can be Hex encoded. 2%74%28%2018%58%53%53%2019%29%3C%2F%73%63%72%69%70%74% 3E%20 XSS in JSON {"name":"Foo "+alert(‘XSS’)+"Bar“} Some browsers have built-in protection, or extensions available (e.g. NoScript) to prevent reflective XSS Stored Injected code is stored and played back in later page views Example, attacker posts a message containing malicious JavaScript on a blog. Check me out!

11 11 Verisign Public Countermeasure: Validate all input against: headers, cookies, query strings, hidden form fields Encode user supplied data during output. ( e.g. jquery-encoder) Use safer APIs that do not run scripts - JSON.parse, innerText Use anti XSS filters on server. (e.g. HTMLPurifier, ESAPI, OWSAP AntiSamy). Prefer whitelisting to blacklisting Use client-side tools with built-in XSS detection filters Complete list for XSS detection: https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet A3 Cross Site Scripting (XSS)

12 12 Verisign Public A8 Cross-Site Request Forgery (CSRF) Attacker exploits user’s active session to perform action without consent Synonyms: XSRF, Sea Surf, Session Riding, Hostile Linking, One-Click attack 2. Log In 3. Session cookies set 6. Hidden request (REST API) View my Pictures! Blog on vulnerable server 4. Post malicious link 5. Open new tab and click link 1. Open page Web Server: myapp.com Victim 7. Invitation sent confirmation Malicious request for victim to execute Countermeasure: POST instead of GET, secret cookie, page referrer check - does not work Unpredictable token with every request (synchronizer token design pattern) Example, CSRF Guard or ESAPI library Challenge user credentials again Attacker

13 13 Verisign Public A8 Cross-Site Request Forgery (CSRF) Client side: CSRF Countermeasure using tokens

14 14 Verisign Public New Tags and Attributes Cross-Origin Resource Sharing Web Messaging Web Sockets Web Workers Local Storage Geolocation HTML 5 Security Concerns

15 15 Verisign Public New Tags and Attributes Threats: New XSS Vectors Rich content from users Event attributes Bypasses black-list filter Countermeasure: Update existing XSS filters in place. HTML5 XSS cheat sheet - HTML 5 Security Concerns

16 16 Verisign Public Attacker 5. XHR Content-Type : text/plain withCredentials : true Invoke any REST API call Cross-Origin Resource Sharing (CORS) Server-side solution to circumvent the same-origin policy | *") %> Allows XHR Level 2 object to initiate a cross domain request directly Simple Request – GET/HEAD/POST with Content-Type ‘text/plain’ Preflight Request CORS support on browsers (http://caniuse/com/cors) HTML 5 Security Concerns 2. Log In 3. Session cookie 4. Open page 1. Open page Web Server: myapp.com Victim using CORS capable browser Access-Control-Allow-Origin: * REST API Threat: Cross-Site-Request-Forgery $.ajax({ url: 'http://myapp.com/rest/user/invite', type: ‘post’, crossDomain: true, contentType: “text/plain; charset=UTF-8", data: ‘{“user”:“evilUser”}’, beforeSend: function(xhr) { xhr.withCredentials = true; } }); (jQuery )

17 17 Verisign Public Cross-Origin Resource Sharing CSRF Countermeasure: Restrict policy files. Avoid Access-Control-Allow-Origin: * Whitelist the allowed Origins Ensure GET request have no side-effects Use CSRF token Care when using Access-Control-Allow-Credentials: true response header Do not base access control on the origin header - header can be modified by an attacker through sending a faked origin header Configure firewall to block CORS requests if they arrive in a high frequency to prevent DDOS attack HTML 5 Security Concerns

18 18 Verisign Public HTML 5 Security Concerns 2. Respond with news 4. Handle data Web Messaging (Cross-Document Messaging) Allows documents to communicate with each other regardless of their origin using PostMessage API Example: Rich mashup scenarios where components can exchange information and permissions with the parent page 3. postMessage 1. postMessage(“Fetch_News”) iframe src=“http://news.com” receive() receive() 2. XSS attack myapp.com news.com Attacker (payload with XSS) Threat: XSS Injection if one of the trusted servers has been compromised

19 19 Verisign Public HTML 5 Security Concerns var newsFrame = document.getElementById("newsframe").contentWindow; setInterval(function(){ newsFrame.postMessage("Fetch_News", 'http://news.com/'); },5000); window.addEventListener('message', receiver, false); function receiver(e) { if (e.origin == 'http://news.com') { handle(e.data); } window.addEventListener('message', receiver, false); function receiver(e) { if (e.data == 'Fetch_News') { event.source.postMessage("Latest News ", event.origin); } XSS attack can happen here Sanitize data here

20 20 Verisign Public HTML 5 Security Concerns Cross-Document Messaging XSS Countermeasures: Check the origin attribute – accept messages only from indented domains Check the data - source may have been attacked by XSS Sanitize responses before calling eval or innerHTML Accept only certain number of messages per minute – prevent DOS attack

21 21 Verisign Public HTML 5 Security Concerns Web Sockets and Web Workers Web Sockets – enable two-way communication, obey SOP and support CORS Can be used to identify open, close and filtered ports on client’s local intranet. Web Worker – JavaScript code runs in background, independent of other scripts, able to utilize multicore CPU Web Worker – has access to XHR, navigator object, application cache, spawn other workers Threats: Web-based botnets ( spams, distributed password cracking, application level DDos attacks, network scanning) Countermeasure: Fix XSS vulnerabilities Do not allow creating web worker scripts or socket from user supplied input Internal network port scanning

22 22 Verisign Public HTML 5 Security Concerns Local Storage Vulnerable to manipulation from foreign sites alert(window.localStorage.key) Threats: Session Hijacking, confidential data disclosure, user tracking Countermeasure: Just like cookies, don’t store confidential information Encrypt and set expiration date Do not store session identifiers in local storage, use HTTPOnly cookies instead

23 23 Verisign Public HTML 5 Security Concerns Geolocation Provides physical location of user agent Browsers vary on decision to remember location Threats: Privacy issues: user tracking, physical movement tracking, user correlation across domains. Countermeasure: Protect user’s privacy: disclosure, deleting after use Require user input before calling Geolocation API methods

24 24 Verisign Public Insecure Direct Object References Sensitive Data Exposure Handling Exceptions Session Management Unsecured Channels Broken Authentication Missing Function Level Access Control REST API Threats and Counter Measures

25 25 Verisign Public REST - Insecure Direct Object References

26 26 Verisign Public REST- Insecure Direct Object References 1. Exposed endpoints - user may fat finger Ids in the REST URL. It is easy for an attacker to set up a loop and try all urls simply by incrementing a number. Recommendation: Use GUIDs instead of sequence numbers as your IDs vs

27 27 Verisign Public REST - Insecure Direct Object References 2. Importance of Path declarations (Jersey public List HttpServletRequest final int final int toRecord) public List HttpServletRequest final String final String toRecord) Injection: vs Recommendation: Be as specific as possible with your parameter/path data types

28 28 Verisign Public REST- Insecure Direct Object References 3. Validating input parameters for REST endpoints is very important. Clients can always get these REST end points from your user interface [using tools like firebug etc.] and invoke these directly. Example, a end point shown below is possibly designed to be used by user interface for pagination. Injection: could cause your server to go down. Recommendation: Other than your normal logic validations, pay attention to Limits and Range checks. Validation is done programmatically or some frame works like RestEasy from JBoss lets you define your validators. Jersey2.0 has support for bean validations.

29 29 Verisign Public REST - Insecure Direct Object References For large datasets, use @Path("/liststream/from/{from}/to/{size}") public Response getStreamList() { StreamingOutput stream = new StreamingOutput() public void write(OutputStream out) throws IOException { for (int i = from; i <= to; i++) { String data=getData(i); out.write(data.getBytes()); out.flush(); } ….. close stream etc.. }; return Response.ok(stream).build(); } }

30 30 Verisign Public REST - Sensitive Data Exposure Be careful on the output of REST end points. Protect sensitive information from being displayed. Recommendation: Filter out columns of POJO you need for internal logic from being written out. Example, if using jackson json, you can do public class User { } ObjectMapper mapper = new ObjectMapper(); FilterProvider fltrProvider = new SimpleFilterProvider().addFilter("userFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); OR FilterProvider fltrProvider = new SimpleFilterProvider().addFilter( "userFilter", SimpleBeanPropertyFilter.serializeAllExcept("ssn")); String json = mapper.filteredWriter(fltrProvider).writeValueAsString(userList);

31 31 Verisign Public REST - Handling Exceptions Do not allow stack trace exposure to the end user. Recommendation : Catch all exceptions and print user friendly messages You can use global message handler like public class ExceptionHandler implements ExceptionMapper public Response toResponse(Exception ex) { ex.printStackTrace(); return Response.status(404).entity("An error occurred while processing your request.").type("text/plain").build(); } }

32 32 Verisign Public REST – Session Management Best practice - no sessions at all for RESTful services. Avoiding sessions reduces memory foot prints of REST calls but that will mean you need to authenticate each request A user interface using RESTful calls will need session, as you do not want to authenticate user with each call Recommendation: Option 1: Pass a custom header while making a REST call from your user interface. Server can check for the existence of this header and then create a session for an authenticated user. JQuery example: $.ajaxSetup({ headers:{“some-client”, “userinterface”}}) Option 2: Create separate users for user interface and direct API calls. Based on user type you may choose to create a session. This introduces user management. Option 3: API Tokens : Issuing tokens for API calls. For example, separate token for READ operation and separate token for ADD operation etc.

33 33 Verisign Public REST - Unsecured Channels Data transport over unsecured layer. Recommendation: Never send sensitive information without SSL. Encrypt communication between client and server. Option: One-Way SSL/TLS Client validates the server. Shared secret key to encrypt communication between client and server. Some HTTPD directives: SSLCertificateFile my.crt (Server PEM-encoded X.509 Certificate file) SSLCertificateKeyFile my.key (Server PEM-encoded Private Key file)

34 34 Verisign Public REST - Unsecured Channels Option: Two-Way SSL/TLS Client validates the server. Server validates the client. Shared secret key to encrypt communication between client and server. Some HTTPD directives: SSLCertificateFile my.crt (Server PEM-encoded X.509 Certificate file) SSLCertificateKeyFile my.key (Server PEM-encoded Private Key file) # AUTHORIZED CLIENTS SSLVerifyClient require SSLCACertificateFile clients.crt (PEM-encoded CA Certificates for Client Auth)

35 35 Verisign Public REST - Unsecured Channels Option: Signing REST API requests SSL/TLS is slow. Clients can initially use secure channel to obtain a key and then rest of the calls could be on a non-secure channel. 1.Client uses secure channel to obtain a key based on CLIENT_ID from your server. One time process. You can also have keys expire after certain time [few months]. curl –u javaone:javaone https://examle.com/restsec/getapikey Lets say key=javaone 2.Client assembles the REST call for non-secure channel. Signing requests example code: String static final HMAC_ALGO = "HmacSHA1"; String static final CLIENT_KEY= ”javaone"; String REST_CALL_PART= /user/list"; ….. Key keySpec = new SecretKeySpec(CLIENT_KEY.getBytes(), HMAC_SHA1_ALGORITHM); Mac macInstance = Mac.getInstance(HMAC_ALGO); macInstance.init(keySpec); byte[] restCall= macInstance.doFinal(REST_CALL.getBytes()); String signature= Base64.encodeBase64String(restCall);

36 36 Verisign Public REST - Unsecured Channels 3.Client signs the request using the above key and adds CLIENT_ID and CLIENT_SIG in the http header. curl –H “CLIENT_ID:1234” –H “CLIENT_SIG:IBt4yL+Gz1kGtcFwtS6aMFP2kUc=” http//example.com/restsec/user/list/from/1/size/ Server recalculates the signature (Hash of the request) based on your CLIENT_ID and the corresponding key it has for that CLIENT_ID. 5.Server matches both signatures, if a match is found you are authorized.

37 37 Verisign Public REST - Unsecured Channels Issue: The request can be replayed by an attacker if the data is sent over non- secure channel. Recommendation: Use secure channel but this is slow. Clients can use time stamp as part of rest call and server can expire the call with in specific period. This narrows the attack window. String timeStamp= “ts:”+System.currentTimeMillis(); String signature= Base64.encodeBase64String(restCall+”:”+timeStamp);

38 38 Verisign Public REST - Broken Authentication Users can essentially invoke REST end points directly and if all end points are not authenticated, they can get access to unauthorized resources. Recommendation: 1.Always use HTTPS for Basic Authentication. Client GET curl –u javaone:javaone https://localhost:8080/restsec/user/list/from/1/size/3000 Server side: request.getHeader("authorization”) = “Basic amF2YW9uZTpqYXZhb25l” auth=“amF2YW9uZTpqYXZhb25l” Base64.decode(auth)= javaone:javaone

39 39 Verisign Public REST - Broken Authentication 2. Always intercept all REST calls for authentication, authorization and possibly logging. Intercepting REST calls using servlet filter in web.xml: restFilter com.javaone.demo.sec.RestSecurityFilter whitelist publicresources/ reportSecurityFilter /* Intercepting REST calls using ContainerRequestFilter [Jersey] in web.xml: Rest Web Application com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.spi.container.ContainerRequestFilters com.javaone.demo.sec.MyContainerRequestFilter

40 40 Verisign Public REST - Broken Authentication 3. You could use SSO. OATH: RFC6749 The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf. Ref: SAML: RFC6595 XML is used to exchange authentication and authorization messages between SAML Identity Provider and Relying Party. When a user requests a resource from Relying Party(RP), RP redirects the user to Identity Provider (IP) for authentication of the user and authorization of the resource requested. User authenticates and possibly authorizes any information about the user itself. IP redirects the user back to RP with saml assertion. RP gets user identity information and proceeds accordingly. RP may establish a session with the user. Ref:

41 41 Verisign Public REST - Missing Function Level Access Control A malicious authorized user, could simple change the URL and may try to gain access to more privileged functions. Recommendation: Make sure authenticated user gets access to resources which belong to his/her account. Injection: Make sure authenticated user can invoke end points based on his access level. (A url meant for Admin user only)

42 42 Verisign Public Q&A

43 Thank You Copyright © 2013 VeriSign, Inc. All rights reserved. The VERISIGN word mark, the Verisign logo, and other Verisign trademarks, service marks, and designs that may appear herein are registered or unregistered trademarks or service marks of VeriSign, Inc., and its subsidiaries in the United States and foreign countries. All other trademarks, service marks, and designs are property of their respective owners. Verisign has made efforts to ensure the accuracy and completeness of the information in this document. However, Verisign makes no warranties of any kind (whether express, implied or statutory) with respect to the information contained herein. Verisign assumes no liability to any party for any loss or damage (whether direct or indirect) caused by any errors, omissions, or statements of any kind contained in this document. Further, Verisign assumes no liability arising from the application or use of any information described or referenced herein.


Download ppt "Securing Rich Clients and RESTFUL Services Sumit Daryani Vikas Charak Sept 25, 2013."

Similar presentations


Ads by Google