24
Django Web Application Security By Levi Gross

Django Web Application Security

  • View
    5.239

  • Download
    1

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Django Web Application Security

Django Web Application Security

ByLevi Gross

Page 2: Django Web Application Security

About Me

• Blog: http://www.levigross.com/• Twitter:@levigross• Email: [email protected] • Python for 5 years• Django for 2 ½• Computer Security for 8 years• Python and Django are amazing!

Page 3: Django Web Application Security

Who is attacking us

• Bots– Malicious – SEO– Steal user info

• Hackers– ScriptKiddies – Hackers– Über Hackers

We will bankrupt ourselves in the vain search for absolute security. — Dwight D. Eisenhower

Page 4: Django Web Application Security

Django from a security standpoint

Django Rocks!

• Salted SHA1 Hashes (Yummy)– sha1 $ e3164 $ 9595556c4f693158c232f0885d266fe30671ca8a– Take that Gawker!

• Secure session framework• Automatic variable escaping

– XXS– SQL Injection

• CSRF (Cross Site Request Forgery) Protection• Protection against Email Header injection• Protection against Directory Traversal attacks

“If you think technology can solve your security problems, then you don’t understand the problems and you don’t understand the technology”. — Bruce Schneier

Page 5: Django Web Application Security

Web Vulnerabilities

• Information Disclosure• Input Validation• Click Jacking• Session Hijacking• CSRF• Passwords• Denial of Service• 0 days

In theory, one can build provably secure systems. In theory, theory can be applied to practice but in practice, it can't. — M. Dacier, Eurecom Institute

Page 6: Django Web Application Security

Information Disclosure

Your Parts are showing

Page 7: Django Web Application Security

Attack Surface

• Admin Site– Defaults to /admin

• Views & URLS– Can give someone an intimate view of your

application.• File Locations• REST– Use Piston

• Sentry

Page 8: Django Web Application Security

How to protect yourself

• Never deploy with the default settings– Long URLS are the best (but your not out of the

woods)• Change the file name/location of user content• Validate uploads• Remove unneeded software– if not chroot

Page 9: Django Web Application Security

Input Validation

• XXS• SQL Injection• HTTP Response Splitting• Directory Traversal• CRLF Injection

Page 10: Django Web Application Security

Cross Site Scripting

• Django Protects us by autoescaping output

return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace(' " ', '&quot;').replace(" ' ", '&#39;'))

• |safe/{% autoescape off %} is not Safe

Page 11: Django Web Application Security

Here comes the sleep deprivation

My Template Code

Secure:<span class={{value}}>{{ value }}</span>Not Secure:<span class="{{value|safe}}">{{value|safe}}</span>

Using this value -> " onclick=alert(document.cookie) type="

Secure: <span class=&quot; onclick=alert(document.cookie) type=&quot;>&quot; onclick=alert(document.cookie) type=&quot;</span>

Not Secure:<span class="" onclick=alert(document.cookie) type="">" onclick=alert(document.cookie) type="</span>

Oops…

Page 12: Django Web Application Security

How to protect yourself

• Use the ESAPI (Enterprise Security API)– " onclick=alert(document.cookie) type="– '&quot; onclick&#x3d;alert&#x28;document.cookie&#x29; type&#x3d;&quot; ’– http://code.google.com/p/owasp-esapi-python/

• Use Quotes• Use Sanitizers– lxml– html5lib

• Use Whitelists• Use Markdown

Page 13: Django Web Application Security

SQL Injection• Python protects us

– Parameterized queries according to PEP 249• Django’s ORM Protects us

– parameterized queries– Person.objects.filter(first_name__icontains=fname,last_name__icontains=lname)– fname = % \ output -> \% \\– SELECT "secpre_person"."id", "secpre_person"."first_name", "secpre_person"."last_name" FROM

"secpre_person" WHERE ("secpre_person"."first_name" LIKE %\% \\% ESCAPE '\' AND "secpre_person"."last_name" LIKE %s% ESCAPE '\' )

– smart_unicode(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")

• NEVER BUILD QUERYIES USING STRING FORMATTING– query = 'SELECT * FROM secpre_person WHERE last_name = %s' % lname Person.objects.raw(query)

• Use Parameterized queries – Person.objects.raw('SELECT * FROM secpre_person WHERE last_name = %s', [lname])

Page 14: Django Web Application Security

HTTP Response Splitting• New Lines in the HTTP Headers

HTTP/1.1 302 Moved Temporarily Date: Wed, 24 Dec 2003 15:26:41 GMT Location: http://10.1.1.1/someview/?lang=foobar Content-Length: 0 HTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 19 <html>Control</html> Server: ApacheContent-Type: text/html

– This was just found on Reddit last week• Kudos to Neal Poole from Matasano

• Django to the rescue – Every HttpResponse object has this code if '\n' in value or '\r' in value: raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))

Page 15: Django Web Application Security

CRLF Injection

• Hijack email forms– to:”[email protected]\ncc:[email protected]\

rcc:[email protected]

• Django to the rescue

if '\n' in val or '\r' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))

Page 16: Django Web Application Security

Directory Traversal

• ../../../../../../../../../etc/passwd• Django should never serve static files– Your webserver should serve all static files and be

locked into the web root directory– Never allow users to dictate what happends

• Django Static Serve isn’t powerless

drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue

Page 17: Django Web Application Security

Click Jacking

• Use X-FRAME– HTTP header X-FRAME-OPTIONS: DENY• https://github.com/paulosman/django-xframeoptions

• Use a Framekiller– <script type="text/javascript">

if(top != self) top.location.replace(location); </script>

• Beware of sites that you visit

Page 18: Django Web Application Security

Session Hijacking

• FireSheep– Cookie info not sent over HTTPS– Pass the hash

• SESSION_COOKIE_SECURE = True• SESSION_COOKIE_HTTPONLY = True• Sessions– Never store private data in clear text– Never display session data without escaping it

Page 19: Django Web Application Security

Cross Site Request Forgery• <img src="http://bank.example.com/withdraw?account=bob&amount=1000000&for=mallory">

• We are logged in so it works• Django protects us (unless we are really

stupid)HTTP/1.0 200 OKDate: Mon, 17 Jan 2011 21:55:14 GMTServer: WSGIServer/0.1 Python/2.7.1Expires: Mon, 17 Jan 2011 21:55:14 GMTVary: CookieLast-Modified: Mon, 17 Jan 2011 21:55:14 GMTETag: "4030d6e6a6c31292791e61e8bc58b6e8"Cache-Control: max-age=0Content-Type: text/html; charset=utf-8Set-Cookie: csrftoken=9260e87b366dd2be2515bffffec5a746; Max-Age=31449600; Path=/

Page 20: Django Web Application Security

Denial Of Service

• Everything is vulnerable • Impossible to defend against every variant• Harden your server• Rate limiting– Do this on a server level– If you need to do this on a view level

• https://gist.github.com/719502

• Fine tune access methods for your views– restrict the HTTP method to the appropriate view

Page 21: Django Web Application Security

Passwords

• Passwords are your biggest nightmare– Don’t trust them

• Make sure that you are using SHA1– Even though it works md5 and crypt shouldn’t be used. – crypt should NEVER be used!!!

• Rate limiting• Use Django-axes

– http://code.google.com/p/django-axes/

• Never rely on just a password– If you can use 2 factor authentication do it.

Page 22: Django Web Application Security

0 Day Protection

• Run for the hills• Good security is like a big onion– Many layers– Bitter

• Limit your exposure• Server monitoring• Remember a good programmer looks both

ways before crossing a one way street.

Page 23: Django Web Application Security

Security Tips

• Be wary of updates– Update on security releases

• Beware of 3rd party apps• Separate work from play• Don’t rely on passwords• Fail2Ban• Stick with Django– Be careful where you stray

• Scan often– Skipfish

Page 24: Django Web Application Security

Questions?