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

Shiny, Let's Be Bad Guys: Exploiting and Mitiga...

Shiny, Let's Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulnerabilities -- 2014 edition

Slides from the Pycon 2014 presentation of our tutorial that walks through the OWASP Top 10 web application vulnerabilities.

Mike Pirnat

April 10, 2014
Tweet

More Decks by Mike Pirnat

Other Decks in Technology

Transcript

  1. Shiny Text Let’s Be Bad Guys! Exploiting and Mitigating the

    Top 1 0 Web App Vulnerabilities Mike Pirnat David Stanek - @mpirnat - @dstanek
  2. Schedule • This session will run 1:20 PM - 4:40

    PM • 20-minute break at 3:30 PM
  3. Volunteering Opportunities • Low-commitment! Fun! • SWAG bagging: Thursday 3-7

    PM • Exhibit Hall 220C – 2nd floor of conference center • Just do 10 bags! (~1/2 hr) • Registration Desk: any time • 1-2 hours helps • Friday => meet everyone!
  4. Shiny Text Let’s Be Bad Guys! Exploiting and Mitigating the

    Top 1 0 Web App Vulnerabilities Mike Pirnat David Stanek - @mpirnat - @dstanek
  5. OWASP • http://www.owasp.org • Open Web Application Security Project •

    Non-profit focused on improving software security • Documentation and tools to help learn about security and protect your apps
  6. OWASP Top Ten • Based on risk data from 8

    firms • Over 500,000 vulnerabilities, hundreds of orgs, thousands of apps • Selected & prioritized by prevalence data combined with estimates of exploitability, detectability, and impact • Updated in 2013
  7. Today • Background on a type of vulnerability • Exploit

    it! • Discuss prevention • Django-specific advice where possible • Light examples where we have time
  8. Setup: 2 & 3 (Offline/USB) • Extract the project: $

    mkdir src $ unzip /Volumes/BADGUYS/project/ badguys.zip -d src/ • Install dependencies: $ cd src $ pip install -r requirements.txt -i file:///Volumes/BADGUYS/software
  9. Injection Attacks • When an application sends untrusted data to

    an interpreter • Can result in data loss/corruption, lack of accountability, denial of access • Can lead to complete host takeover
  10. Attack Vectors • GET parameters • POST parameters • PATH_INFO

    • Some HTTP headers: Cookie, Host • Uploaded Files
  11. Possible Consequences • Creation of malicious SQL (or other queries)

    • Accessing private files on disk • Arbitrary code execution
  12. SQL Injection • Unescaped user input causes the premature end

    of a SQL query and allows a malicious query to be executed... """ select * from users where username='%s'; """ • http://localhost:8000/injection/sql
  13. Accessing Private Files • File system access + unvalidated user

    input allows attackers to navigate the file system • http://localhost:8000/injection/file- access
  14. Arbitrary Code Execution • Unsafe input is dynamically evaluated or

    executed • http://localhost:8000/injection/code- execution
  15. Prevention • Validate ALL user input • Sign cookies, don’t

    accept if signature is bogus/missing • Use ORMs or bind variables when talking to the database • Don’t use eval or exec, beware of pickle, user-supplied YAML, etc.
  16. Django Advice • Make sure data types for your model

    are tight • Use Forms instead of ModelForms for stronger validation • Make new validators as needed for your application • Make sure your URL regexes for dynamic URLs are tight
  17. Django Advice • Use the ORM when you can •

    When you can’t, use extreme caution! • Bind variables • No string concatenation/formatting of anything that came from the client
  18. Without the ORM # If it's a basic select: MyModel.objects.raw("SELECT

    ... WHERE foo = %s", params={'foo': ...}) # If it's more complicated: from django.db import connection cursor = connection.cursor() cursor.execute("UPDATE bar set bar = 1 WHERE foo < %s", [foo]) row = cursor.fetchall()
  19. Broken Auth & Session Management • Attacker uses leaks or

    flaws in authentication or session management to impersonate users • Roll-your-own solutions contribute to the difficulty of finding these flaws
  20. Prevention • Hash or encrypt passwords • Don’t let credentials

    be easily overwritten • Don’t put session IDs in URLs • Allow session IDs to timeout/log out • Rotate session IDs after successful login • TLS connections for passwords, session IDs
  21. Django Advice • Use django.contrib.auth • Consider https://github.com/yourlabs/ django-session-security middleware

    for timing out sessions • We’ll talk about transport layer security later on...
  22. XSS Attacks • Cross-Site Scripting (XSS) • The most prevalent

    web app security flaw • App includes user-supplied data in content sent to the browser without properly validating or sanitizing it
  23. XSS Attacks • Stored: injected code permanently stored in database,

    message forum, comment, etc. • Reflected: injected code in live request to server, reflected back in error message or search result • DOM: injected code in browser DOM environment that causes scripts to run in unexpected ways (eg, reading from URL)
  24. Possible Consequences • Execute scripts in a victim’s browser •

    Hijack sessions • Deface sites • Insert hostile content • Redirect users • Hijack browser (install malware)
  25. Most Often Seen... • Places where user-created text is displayed

    to other users (comments, messages) • Form inputs where value is populated with user-supplied data • Script tags where user-supplied data is populated into script variables
  26. XSS in Dynamic URLs • Part of the URL path

    is variable, isn’t validated, and gets included into the page • http://localhost:8000/cross-site- scripting/path-matching/your-path- here
  27. XSS in Query String Parameters • Unvalidated user input from

    a query string parameter is included in the page • http://localhost:8000/cross-site- scripting/query-params?qs=awesome
  28. XSS in Form Fields • The value part of an

    input is prematurely terminated, allowing Javascript to be injected into the element (eg, adding an onclick) • http://localhost:8000/cross-site- scripting/form-field
  29. Prevention • Escape all untrusted data based on the HTML

    context the data will be placed into • Whitelist input validation • Consider auto-sanitization libraries for rich content (eg, OWASP’s AntiSamy) • Update your parents’/in-laws’ browsers!
  30. Django Advice • Be careful with the safe filter, django.utils.safestring,

    etc. • Use form.as_p, form.as_table, form.as_ul when displaying a form in a template • Be careful with your own template tags; django.utils.html.escape is your friend!
  31. Insecure Direct Object Reference • Expose a reference to an

    internal implementation object without verifying authorization • Attacker changes URL or GET/POST parameters, cookies
  32. Possible Consequences • Compromise of all data that can be

    referenced by the vulnerable parameter • Unless the namespace is sparse, an attacker can easily access all available data of that type
  33. Exercises • Manipulate parameters in the URL to access data

    that doesn’t belong to you • http://localhost:8000/direct-object- references
  34. Prevention • Implement access controls on any direct references to

    restricted resources • Implement per-user or per-session indirect object references
  35. Django Advice • Use permissions architecture to lock down views

    • Customize queryset for looking up objects that involve user ownership
  36. Custom Queryset # In models.py... class ThingyManager(models.Manager): def for_user(self, user):

    return self.get_query_set().filter(user=user) class Thingy(models.Model): objects = ThingyManager() # In views.py... class ThingyUpdateView(UpdateView): def get_queryset(self): return Thingy.objects.for_user( self.request.user)
  37. Possible Consequences • Unauthorized access to some system data or

    functionality • Potential complete system compromise
  38. Prevention • Have a repeatable hardening process • Have a

    process for keeping on top of updates and patches • Architecture that provides secure separation between components • Periodic scans and audits
  39. Django Advice • Don’t run in debug mode in production

    • Keep your SECRET_KEY secret! • Keep Python code out of webserver’s root • Don’t run admin publicly (if you can help it) • Don’t use the built-in admin for normal user admin tasks
  40. Sensitive Data Exposure • Failure to properly protect credit cards,

    tax ids, authentication credentials, etc. • Sensitive data deserves extra protection such as encryption at rest or in transit, special precautions when exchanged with the browser
  41. Insecure Cryptographic Storage • Not encrypting worthy data • Unsafe

    key generation & storage, failure to rotate keys • Weak algorithms • Weak or unsalted hashes
  42. Insufficient Transport Layer Protection • May not authenticate, encrypt, and

    protect the confidentiality and integrity of sensitive network traffic • May use weak algorithms • May use expired or invalid certificates • May use certificates incorrectly
  43. Possible Consequences • Compromise of all data that should have

    been encrypted • This can be highly sensitive information: credentials, credit cards, personal data, health records, etc.
  44. Possible Consequences • Expose individual users’ data • Account theft

    • Compromise an admin account?! • Poor SSL setup can facilitate phishing and man-in-the-middle attacks
  45. Attack Vectors • Attacker monitors network traffic of your users

    • Maybe in public places (Starbucks, conference wi-fi, etc.) • Maybe back end connections • Maybe inside your network (!!!)
  46. Prevention • Encrypt sensitive data at rest • Encrypt offsite

    backups; manage keys separately • Use strong standard algorithms, strong keys • Hash passwords with strong standard algorithm & use appropriate salt • Protect passwords & keys from unauthorized access
  47. Prevention • Require SSL for all sensitive pages; redirect non-SSL

    requests to SSL • Set the “secure” flag on sensitive cookies • Use only strong SSL algorithms • Ensure your cert is valid, not expired, not revoked, and matches your domain • SSL/encryption on the back end too
  48. Django Advice • Use django.contrib.auth for proper password salting and

    hashing • Require SSL in Apache or Nginx • Require SSL using middleware: • https://github.com/rdegges/django-sslify • http://www.redrobotstudios.com/blog/2010/02/06/ requiring-https-for-certain-paths-in-django/ • http://djangosnippets.org/snippets/2833/ • http://djangosnippets.org/snippets/1467/
  49. Missing Function Level Access Control • Application doesn’t protect its

    functions properly • Misconfiguration • Forgot proper code checks
  50. Attack Vectors • Authorized user changes a URL or parameter

    to a privileged function • Anonymous users could access private functions that aren’t protected
  51. Exercises • Manipulate the URL to access privileged functionality •

    http://localhost:8000/missing-access- control
  52. Prevention • Consider every page; public or private? • If

    authentication is required, make sure that checks are in place • If additional authorization is required, make sure that checks are in place • Deny all by default; explicitly grant access to users or roles
  53. Django Advice • Use the permissions architecture to lock down

    views • Don’t use the built-in admin for normal user admin tasks
  54. CSRF Attacks • Cross-Site Request Forgery (CSRF) • Attacker tricks

    victim into submitting forged HTTP requests • Attack succeeds if user is authorized/ authenticated
  55. Attack Vectors • Image tags • Cross-Site Scripting (XSS) •

    Fake buttons • Phishing forms • Other techniques
  56. Possible Consequences • Cause victim to change any data the

    victim is allowed to change • Cause victim to perform any function the victim is authorized to use • Impact varies based on victim’s role • Think of some possibilities...
  57. CSRF via Image • Craft an “image” link that triggers

    some site functionality • http://localhost:8000/csrf/image
  58. CSRF via Form Post • Create an innocuous-looking form that

    POSTs to a vulnerable location • http://localhost:8000/csrf/third-party- site
  59. Prevention • Don’t “do” things on a GET • Include

    a unique token in a hidden field (often used in concert with a cookie) • Validate token to make sure the request is from on-site • Avoid putting the token into a query string
  60. Django Advice • Don’t change the built-in settings! • Do

    use the CSRF middleware and template tag in forms • Be VERY CAREFUL about deactivating it (csrf_exempt decorator) • Be careful about APIs (Tastypie, oauth); http://codrspace.com/vote539/csrf- protection-in-django-tastypie/
  61. Components with Known Vulnerabilities • Libraries, frameworks, and other modules

    almost always run with full privilege • Hard to stay up to date on everything • Do you even know all the components in use, let alone their versions? • Components with known problems can be identified & exploited with automated tools
  62. Attack Vectors • Attacker identifies a weak component through scanning

    or manual analysis • Customize exploit as needed • More difficult the deeper the component is in the application
  63. Possible Consequences • Full range of weaknesses are possible •

    Impact could be minimal, or... • Complete host takeover! • Data compromise!
  64. Prevention • Don’t use components you don’t write (unrealistic) •

    Keep components up to date • Identify all components and versions • Monitor security of these components
  65. Redirection Abuse • Attacker tricks user into visiting a URL

    that redirects or forwards the request without validating the redirect location • Users prone to click because the link is to a legitimate site
  66. External Redirection • Use a redirection URL to redirect to

    an external location • http://localhost:8000/redirects-and- forwards/redirects
  67. Forwards • Manipulate a forward parameter to gain access to

    privileged functionality • http://localhost:8000/redirects-and- forwards/forwards
  68. Prevention • Don’t use redirects or forwards • Don’t involve

    user-supplied data to build the redirect location • Ensure the supplied value is valid and authorized for the user
  69. Django Advice • Use django.utils.http.is_safe_url to check redirect URLs •

    Used by django.contrib.auth internally • Consider wrapping is_safe_url if you have to allow other off-domain URLs
  70. Checking Redirects from django.shortcuts import redirect from django.utils.http import is_safe_url

    def my_view(request): ... url = 'http://www.example.com/foo/bar' if is_safe_url(url, host='www.example.com'): return redirect(url) else: ...
  71. Allowing Multiple Safe Hosts from django.utils.http import is_safe_url def is_whitelisted_url(url,

    hosts): for host in hosts: if is_safe_url(url, host=host): return True return False >>> url = 'http://us.pycon.org' >>> whitelist = ['us.pycon.org', 'pycon.org', ...] >>> is_whitelisted_url(url, whitelist) True