Date post: | 21-Dec-2015 |
Category: |
Documents |
Upload: | asher-green |
View: | 213 times |
Download: | 0 times |
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 request to the web server...”
(MITRE CWE)
• Less well understood than other attacks
6
ahurst
●●●●●●●●●
Example Attack BrowserCookie Store
HTTP/1.1 200 OK
Set-Cookie: session=2A7B2F293DC
HTTP response:
7
Example GET Attack
GET /transfer?acct=12345&amount=1000 HTTP/1.1
Cookie: session=2A7B2F293DC
HTTP request:
• Attacker has embedded HTML :
<img src=“http://myinsecurebank.com/ transfer?acct=12345&amount=1000” width=0 height=0>
• No visible rendering
BrowserCookie Store
8
Example POST Attack
• Attacker has embedded HTML:
<form name=“badform" method="post" action="http://myinsecurebank.com/transfer"> <input type="hidden" name=“acct" value=“12345" /> <input type="hidden" name="amount" value="1000" /> </form>
<script type="text/javascript"> document.badform.submit(); </script>
• No visible rendering
9
Launching the attack
Any site:
1. Administrated by attacker
2. Allows HTML posting
3. With cross-site scripting (XSS) vulnerabilities
Finding the victim
• Observed an interesting server request
• Fed malicious links to users• Social media
• Sites with related content
• Scatter-shot…
Attack Vectors
10
CSRF in the Wild
Sept. 2014
Oct. 2011
Sept. 2014
11
Coverity Security Advisor Stats
CSRF XSS RISKY CRYPTO
PATHMANIP-
ULA-TION
SQLI0
200
400
600
800
1000
1200
Nu
mber
Open Source Java Web-apps, All
Detected Vulnerabilities
• Excludes known false positive and intentional defects
Density = 120 per MLoC
12
Coverity Security Advisor Stats
Enterprise Web-apps, Selected
Detected Vulnerabilities
CSRF XSS RISKY CRYPTO
PATHMANIP-
ULA-TION
SQLI
Enterprise Web App 1 Enterprise Web App 2
Nu
mber
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
NotSufficient
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
<form name=“transfer" method="post" action="http://myinsecurebank.com/transfer"> … <input type="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
--- Transfer Money ---
$100.00
Amount
To Account: Mom
Send
How Secret Tokens Foil Attackers
<input type="hidden" name=“anti-csrf" value=“82d920bfc" />
POST /transfer HTTP/1.1
Cookie: session=2A7B2F293D
acct=12345&amount=1000
POST /transfer HTTP/1.1
Cookie: session=2A7B2F293D
acct=12345&amount=1000& anti-csrf=82d920bfc
HTTP request: HTTP request:
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
1. Manual checks
2. Servlet filters (or similar)
3. Use a library
26
Implementation choices
1. Manual checksclass MyServlet extends HttpServlet {
void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
if (!isValidCsrfToken(req.getParameter(“anti-csrf”)) { throw new ServletException(“Invalid request”); }
// handle valid request... }
}
27
Implementation choices
1.Manual checks
Tight coupling of functionality & security
• Fine-grained control of protection
High developer burden
More opportunities for mistakes
-
+
-
ServletContainer
handleRequest
ServletFilter. doFilter
handleRequest
handleRequest
28
2.Servlet Filters (or similar)
Loose coupling of functionality and security
• Need correct behavior in two pieces of code
Implementation choices
ServletContainer
handleRequest
handleRequest
handleRequest
ServletFilter. doFilter
-
29
Implementation choices
3. 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
-
-
+
OWASP CSRFGuard
Spring Security 3.2
Apache csrf-filter
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 obligationGET POST/PUT/DELETE
No side effects Have side effects
Not vulnerable Vulnerable
Developer
SecurityAuditor
33
Don’t : Subvert HTTP verbs
• It’s easy and tempting to do
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") AddToCartItem addToCartItem, BindingResult errors, ModelMap model, HttpServletRequest request) { ... }}
Example Spring MVC 3.0 Controller:
• What about?
@RequestMapping(“/addItem.html”)
34
The alternative isn’t pretty…
35
Avoid : Complex Exception Logic
• Defining a configuration language?
<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>
Example web.xml:
36
Avoid : Complex Exception Logic
URI startsWith(String)?
URI equals(String)?
URI matches(Pattern)?
URI equals(String)?
parameters contain(String)
?
parameters Empty
?
Hard-codedliterals
Properties Files
Properties Files
ParsedXML
Settings
List<String>
ArrayList<String>
List<Pattern>
RequireCSRFToken
BypassCSRFCheck
XML Tree
Y
Y
Y
Y Y
Y
N
N
N
N
N
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
• There method has a side effect. Can you spot where?
• Would you expect a security auditor to find this?
public String doRootContent() throws Exception{ Document doc = DocumentHelper.createDocument(); ContentVO rootContent = ContentController.getContentController() .getRootContentVO(repositoryId, getPrincipal().getName(), true); doc.add(getPlainContentElement(rootContent));}
Example web request handler:
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
StateUpdates
MissingCoverage
CSRFVulnerabilities
41
Coverity Security Advisor: Interface
http://triage:8080/
List of all issues
Source code,Annotated with info
List of all “events”:
Essential elements of vulnerability
42
Coverity Security Advisor
State update
Request handler
Coverity Security Advisor
43
Analysis isinterprocedural
Coverity Security Advisor
44
javax.persistence.EntityManager.merge(…);
45
Coverity Security Advisor
• Remediation advice is critical• Highlights example of valid protection
exploitProtectionService.compareToken(csrfToken);
Example CSRF check
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!
Q&A
https://www.coverity.com
For a free Java software quality evaluation:
https://www.code-spotter.com