1 / 50

Securing Against Cross-Site Request Forgery …in a Way You Won’t Regret Later

Securing Against Cross-Site Request Forgery …in a Way You Won’t Regret Later. JavaOne 2014 Aaron Hurst. Goals. Understand an attack Protection schemes: what works and why Implementation for Java web-apps Future-proofing your protection How vulnerabilities still arise.

yanka
Download Presentation

Securing Against Cross-Site Request Forgery …in a Way You Won’t Regret Later

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Securing Against Cross-Site Request Forgery …in a Way You Won’t Regret Later JavaOne 2014 Aaron Hurst

  2. Goals • Understand an attack • Protection schemes: what works and why • Implementation for Java web-apps • Future-proofing your protection • How vulnerabilities still arise

  3. What’s my experience here? • Coverity is the leader in development testing • We report OWASP top 10 vulnerabilities • CSRF, XSS, Injection, Sensitive Data Exposure ... • Principal Engineer for Java web-app security • I spend a lot of time looking at Java security vulnerabilities!

  4. Anatomy of an Attack

  5. Introduction • Cross-site Request Forgery? (CSRF or “sea-surf”) “…attacker to trick a client into making an unintentional requestto the web server...” (MITRE CWE) • Less well understood than other attacks

  6. Example Attack Browser Cookie Store ahurst HTTP response: ●●●●●●●●● HTTP/1.1 200 OK Set-Cookie: session=2A7B2F293DC

  7. Example GET Attack Browser Cookie Store HTTP request: GET /transfer?acct=12345&amount=1000 HTTP/1.1 Cookie: session=2A7B2F293DC • Attacker has embedded HTML : • <imgsrc=“http://myinsecurebank.com/ • transfer?acct=12345&amount=1000” • width=0 height=0> • No visible rendering

  8. Example POST Attack • Attacker has embedded HTML: • <formname=“badform" method="post" • action="http://myinsecurebank.com/transfer"> • <inputtype="hidden" name=“acct" value=“12345" /> • <inputtype="hidden" name="amount" value="1000" /> </form> • <scripttype="text/javascript"> • document.badform.submit(); • </script> • No visible rendering

  9. Attack Vectors Finding the victim • Observed an interesting server request • Fed malicious links to users • Social media • Sites with related content • Scatter-shot… Launching the attack Any site: • Administrated by attacker • Allows HTML posting • With cross-site scripting (XSS) vulnerabilities

  10. CSRF in the Wild Sept. 2014 Sept. 2014 Oct. 2011

  11. Coverity Security Advisor Stats Detected Vulnerabilities Open Source Java Web-apps, All Density = 120 per MLoC • Excludes known false positive and intentional defects

  12. Coverity Security Advisor Stats Detected Vulnerabilities Enterprise Web-apps, Selected

  13. Recovering from an attack • Difficult to distinguish real and forged requests • Both come from the client’s browser • Hard to automatically “unwind” a large attack > cat /var/log/tomcat7/my.access.log 10.0.0.1[01/Oct/2014:10:32] “GET /transfer&acct=12345?amount=1000” 10.0.0.1[01/Oct/2014:10:34] “GET /transfer&acct=12345?amount=1000” Legitimate Forged

  14. An Ounce of Protection

  15. Dispelling Bad Memes • POST requests • HTTPS • More complex session identifiers • Multiple cookies • Length or randomness • Expiration • “Are you sure?” dialogs Not Sufficient

  16. Header Validation Referrer validation • Header is not always present! • Privacy-sensitive users and organizations may strip • HTTPS to HTTP requests • Be lenient and insecure? Strict and inaccessible? HTTP request: GET /transfer HTTP/1.1 Referer: http://secure_site.com

  17. Header Validation Custom headers • Must always use JavaScript XMLHttpRequest • Won’t work with HTML forms • Relies on the browser’s same-origin policy HTTP request: POST /transfer HTTP/1.1 X-My-Header: trust me!

  18. Protection 101 • Most general solution: secret tokens • Server generates a shared secret token • Included as a hidden form parameter • Server checks token validity for protected requests • <formname=“transfer" method="post" • action="http://myinsecurebank.com/transfer"> • … • <inputtype="hidden" name=“anti-csrf" • value=“93B87CE82F9A00A" /> • </form>

  19. Protection 101 • Relies on the browser’s same-origin policy: • DOM is inaccessible to pages from another site • Token is unguessable • Cryptographically secure random value • Token is temporary • Session lifetime is typical • Shorter lifetimes may interfere with browsing

  20. How Secret Tokens Foil Attackers HTTP request: POST /transfer HTTP/1.1 Cookie: session=2A7B2F293D acct=12345&amount=1000 HTTP request: POST /transfer HTTP/1.1 Cookie: session=2A7B2F293D acct=12345&amount=1000& anti-csrf=82d920bfc --- Transfer Money --- To Account: Mom $100.00 Amount Send <inputtype="hidden" name=“anti-csrf" value=“82d920bfc" />

  21. Implementation

  22. Protection in Practice • What to protect? • How to protect?

  23. What’s vulnerable? • Protect requests that modify the web-app state: • Database updates • Setting session attributes • Writing to the file-system • Login pages • Integration with other back-end services

  24. There need to be holes • Not everything should be protected… • Landing pages • Stateless requests • Unauthenticated form submissions • Bookmark-able pages

  25. Implementation choices • Manual checks • Servlet filters (or similar) • Use a library

  26. Implementation choices • Manual checks class MyServlet extends HttpServlet { void doPost(HttpServletRequestreq, HttpServletResponseresp) throws ServletException { if (!isValidCsrfToken(req.getParameter(“anti-csrf”)) { throw new ServletException(“Invalid request”); } // handle valid request... } }

  27. Implementation choices Servlet Container • Manual checks Tight coupling of functionality & security • Fine-grained control of protection High developer burden More opportunities for mistakes ServletFilter. doFilter handleRequest + handleRequest - handleRequest -

  28. Implementation choices • Servlet Filters (or similar) Loose coupling of functionality and security • Need correct behavior in two pieces of code handleRequest ServletFilter. doFilter Servlet Container handleRequest handleRequest -

  29. Implementation choices • Anti-CSRF Libraries Avoid errors in token generation and management Limited configuration of coverage pattern Known security weaknesses • Example: exposing tokens during cross-domain requests • Apache csrf-filter • OWASP CSRFGuard • Spring Security 3.2 + - -

  30. Challenges

  31. What are the challenges? • Implementing the exceptions • Requires security and development expertise • Organizational roles may not overlap • Retrofitting an existing system is hard

  32. Best Practice: Use correct HTTP verbs • REST-fulness makes CSRF protection much easier • HTTP verbs are a language that: • Is meaningful to developers • Capture the security obligation Developer Security Auditor

  33. Don’t : Subvert HTTP verbs • It’s easy and tempting to do Example Spring MVC 3.0 Controller: public class AbstractCartController { /* The addItem method adds a product items with one or more * quantity to the cart by adding thes * item to a list and calling the addItems method. */ @RequestMapping(value = "/addItem.htm", method = {RequestMethod.GET, RequestMethod.POST}) public String addItem(@RequestParam(required=false) Boolean ajax, @ModelAttribute("addToCartItem") AddToCartItemaddToCartItem, BindingResult errors, ModelMap model, HttpServletRequest request) { ... } } • What about? • @RequestMapping(“/addItem.html”)

  34. The alternative isn’t pretty…

  35. Avoid : Complex Exception Logic • Defining a configuration language? Example web.xml: <filter-name>MyCSRFFilter</filter-name> <init-param> <param-name>exceptions</param-name> <param-value> ,/,/index.jsp,/login.jsp,/organizations,/wafs,/configuration,/reports,     /j_spring_security_check,/j_spring_security_logout,/images/*,     /styles/*,/scripts/*,/jasper/*,/rest/*, regex ^/rest/, regex ^/organizations/[0-9]+/applications/[0-9]+/scans/new/ajax_cwe$, regex ^/organizations/[0-9]+/applications/[0-9]+/scans/new/ajax_url$, regex ^/organizations/[0-9]+/applications/[0-9]+/table$, regex ^/organizations/[0-9]+/applications/[0-9]+/defectTable$, regex ^/organizations/[0-9]+/applications/jsontest$, regex ^/organizations/[0-9]+/applications/[0-9]+/scans/[0-9]+/table$ regex ^/organizations/[0-9]+/applications/[0-9]+/falsepositives/table$ regex ^/organizations/[0-9]+/applications/[0-9]+/scans/[0-9]+/unmappedTable$ </param-value> </init-param>

  36. Avoid : Complex Exception Logic URI startsWith(String) ? Hard-coded literals ArrayList<String> Y N URI equals(String) ? Properties Files List<String> Y N Require CSRF Token URI matches(Pattern) ? Properties Files List<Pattern> Y N URI equals(String) ? parameters contain(String) ? Parsed XML Settings XML Tree Y Y N N parameters Empty ? Bypass CSRF Check Y N

  37. Do : Verify • Enforce that HTTP verbs are used properly • Carefully evaluate any exceptions • Are the requests handlers changing server state? • How to even tell?

  38. Don’t : Hidden Behaviors Example web request handler: • There method has a side effect. Can you spot where? • Would you expect a security auditor to find this? public StringdoRootContent() throws Exception { Document doc = DocumentHelper.createDocument(); ContentVOrootContent = ContentController.getContentController()          .getRootContentVO(repositoryId, getPrincipal().getName(), true); doc.add(getPlainContentElement(rootContent)); } Writes to DB

  39. Can we make our lives easier?

  40. Tools can be helpful Static analysis approach: • Automatically identify methods that update state • Automatically computes coverage patterns • Filter URIs • Manual protection • Library set-up CSRF Vulnerabilities State Updates Missing Coverage

  41. Coverity Security Advisor: Interface List of all issues List of all “events”: Essential elements of vulnerability http://triage:8080/ Source code, Annotated with info

  42. Coverity Security Advisor Request handler State update

  43. Coverity Security Advisor Analysis is interprocedural

  44. Coverity Security Advisor javax.persistence.EntityManager.merge(…);

  45. Coverity Security Advisor • Remediation advice is critical • Highlights example of valid protection Example CSRF check exploitProtectionService.compareToken(csrfToken);

  46. Were you paying attention?

  47. Coverity Security Advisor @RequestMapping(value = “/saveReview.htm”, method = {RequestMethod.GET})

  48. Conclusions

  49. Conclusions • Sound CSRF protection is hard • Keep it simple! • HTTP verbs provide a common language • Captures security obligations • Be clear about side effects • Verification is important!

  50. Q&Ahttps://www.coverity.comFor a free Java software quality evaluation:https://www.code-spotter.com

More Related