500 likes | 704 Views
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.
E N D
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
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!
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
Example Attack Browser Cookie Store ahurst HTTP response: ●●●●●●●●● HTTP/1.1 200 OK Set-Cookie: session=2A7B2F293DC
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
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
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
CSRF in the Wild Sept. 2014 Sept. 2014 Oct. 2011
Coverity Security Advisor Stats Detected Vulnerabilities Open Source Java Web-apps, All Density = 120 per MLoC • Excludes known false positive and intentional defects
Coverity Security Advisor Stats Detected Vulnerabilities Enterprise Web-apps, Selected
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
Dispelling Bad Memes • POST requests • HTTPS • More complex session identifiers • Multiple cookies • Length or randomness • Expiration • “Are you sure?” dialogs Not Sufficient
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
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!
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>
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
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" />
Protection in Practice • What to protect? • How to protect?
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
There need to be holes • Not everything should be protected… • Landing pages • Stateless requests • Unauthenticated form submissions • Bookmark-able pages
Implementation choices • Manual checks • Servlet filters (or similar) • Use a library
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... } }
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 -
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 -
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 + - -
What are the challenges? • Implementing the exceptions • Requires security and development expertise • Organizational roles may not overlap • Retrofitting an existing system is hard
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
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”)
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>
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
Do : Verify • Enforce that HTTP verbs are used properly • Carefully evaluate any exceptions • Are the requests handlers changing server state? • How to even tell?
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
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
Coverity Security Advisor: Interface List of all issues List of all “events”: Essential elements of vulnerability http://triage:8080/ Source code, Annotated with info
Coverity Security Advisor Request handler State update
Coverity Security Advisor Analysis is interprocedural
Coverity Security Advisor javax.persistence.EntityManager.merge(…);
Coverity Security Advisor • Remediation advice is critical • Highlights example of valid protection Example CSRF check exploitProtectionService.compareToken(csrfToken);
Coverity Security Advisor @RequestMapping(value = “/saveReview.htm”, method = {RequestMethod.GET})
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!
Q&Ahttps://www.coverity.comFor a free Java software quality evaluation:https://www.code-spotter.com