SlideShare a Scribd company logo
1 of 24
Django Web Application Security By Levi Gross
About Me Blog: http://www.levigross.com/ Twitter:@levigross Email: levi@levigross.com Python for 5 years Django for 2 ½ Computer Security for 8 years Python and Django are amazing!
Who is attacking us Bots Malicious  SEO Steal user info Hackers ScriptKiddies Hackers ÜberHackers We will bankrupt ourselves in the vain search for absolute security. — Dwight D. Eisenhower
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
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
Information Disclosure Your Parts are showing
Attack Surface Admin Site Defaults to /admin Views & URLS Can give someone an intimate view of your application. File Locations REST Use Piston Sentry
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
Input Validation XXS SQL Injection HTTP Response Splitting Directory Traversal CRLF Injection
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
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…
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
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 'apos; AND "secpre_person"."last_name" LIKE %s% ESCAPE 'apos; ) smart_unicode(x).replace("", "").replace("%", "").replace("_", "") NEVER BUILD QUERYIES USING STRING FORMATTING query = 'SELECT * FROM secpre_personWHERE last_name = %s' % lnamePerson.objects.raw(query)  UseParameterizedqueries Person.objects.raw('SELECT * FROM secpre_personWHERE last_name = %s', [lname])
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 OK Content-Type: text/html Content-Length: 19 <html>Control</html>  Server: Apache Content-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 '' in value or '' in value:                 raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
CRLF Injection Hijack email forms to:”me@myaddress.comcc:bill.gates@microsoft.comcc:paul.allen@microsoft.com” Django to the rescue  if '' in val or '' in val:         raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
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
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
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
Cross Site Request Forgery <imgsrc="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 OK Date: Mon, 17 Jan 2011 21:55:14 GMT Server: WSGIServer/0.1 Python/2.7.1 Expires: Mon, 17 Jan 2011 21:55:14 GMT Vary: Cookie Last-Modified: Mon, 17 Jan 2011 21:55:14 GMT ETag: "4030d6e6a6c31292791e61e8bc58b6e8" Cache-Control: max-age=0 Content-Type: text/html; charset=utf-8 Set-Cookie:  csrftoken=9260e87b366dd2be2515bffffec5a746; Max-Age=31449600; Path=/
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
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.
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.
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
Questions?

More Related Content

What's hot

とある診断員と色々厄介な脆弱性達
とある診断員と色々厄介な脆弱性達とある診断員と色々厄介な脆弱性達
とある診断員と色々厄介な脆弱性達zaki4649
 
メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?Takuya Ueda
 
ふつうのcore.async
ふつうのcore.asyncふつうのcore.async
ふつうのcore.asyncTsutomu Yano
 
Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】dcubeio
 
とある診断員とSQLインジェクション
とある診断員とSQLインジェクションとある診断員とSQLインジェクション
とある診断員とSQLインジェクションzaki4649
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Spring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerSpring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerToshiaki Maki
 
捕鯨!詳解docker
捕鯨!詳解docker捕鯨!詳解docker
捕鯨!詳解docker雄哉 吉田
 
Webアプリを並行開発する際のマイグレーション戦略
Webアプリを並行開発する際のマイグレーション戦略Webアプリを並行開発する際のマイグレーション戦略
Webアプリを並行開発する際のマイグレーション戦略Takayuki Shimizukawa
 
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...Lenur Dzhemiliev
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Wangeun Lee
 
이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정Arawn Park
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーyoku0825
 
CyberAgentにおけるMongoDB
CyberAgentにおけるMongoDBCyberAgentにおけるMongoDB
CyberAgentにおけるMongoDBAkihiro Kuwano
 
Bug Bounty #Defconlucknow2016
Bug Bounty #Defconlucknow2016Bug Bounty #Defconlucknow2016
Bug Bounty #Defconlucknow2016Shubham Gupta
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Content Security Policy
Content Security PolicyContent Security Policy
Content Security PolicyAustin Gil
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 

What's hot (20)

とある診断員と色々厄介な脆弱性達
とある診断員と色々厄介な脆弱性達とある診断員と色々厄介な脆弱性達
とある診断員と色々厄介な脆弱性達
 
Mongo sharding
Mongo shardingMongo sharding
Mongo sharding
 
メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?
 
ふつうのcore.async
ふつうのcore.asyncふつうのcore.async
ふつうのcore.async
 
Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】
 
とある診断員とSQLインジェクション
とある診断員とSQLインジェクションとある診断員とSQLインジェクション
とある診断員とSQLインジェクション
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerSpring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & Micrometer
 
捕鯨!詳解docker
捕鯨!詳解docker捕鯨!詳解docker
捕鯨!詳解docker
 
Webアプリを並行開発する際のマイグレーション戦略
Webアプリを並行開発する際のマイグレーション戦略Webアプリを並行開発する際のマイグレーション戦略
Webアプリを並行開発する際のマイグレーション戦略
 
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계
 
이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキー
 
CyberAgentにおけるMongoDB
CyberAgentにおけるMongoDBCyberAgentにおけるMongoDB
CyberAgentにおけるMongoDB
 
Bug Bounty #Defconlucknow2016
Bug Bounty #Defconlucknow2016Bug Bounty #Defconlucknow2016
Bug Bounty #Defconlucknow2016
 
Implementing SSH in Java
Implementing SSH in JavaImplementing SSH in Java
Implementing SSH in Java
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Content Security Policy
Content Security PolicyContent Security Policy
Content Security Policy
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 

Viewers also liked

Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultMohammed ALDOUB
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesSpin Lai
 
Ruby on Rails Penetration Testing
Ruby on Rails Penetration TestingRuby on Rails Penetration Testing
Ruby on Rails Penetration Testing3S Labs
 
Django book20 security
Django book20 securityDjango book20 security
Django book20 securityShih-yi Wei
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST FrameworkLoad Impact
 
How to secure your web applications with NGINX
How to secure your web applications with NGINXHow to secure your web applications with NGINX
How to secure your web applications with NGINXWallarm
 

Viewers also liked (6)

Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by Default
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best Practices
 
Ruby on Rails Penetration Testing
Ruby on Rails Penetration TestingRuby on Rails Penetration Testing
Ruby on Rails Penetration Testing
 
Django book20 security
Django book20 securityDjango book20 security
Django book20 security
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
 
How to secure your web applications with NGINX
How to secure your web applications with NGINXHow to secure your web applications with NGINX
How to secure your web applications with NGINX
 

Similar to Django Web Application Security

Avoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkAvoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkErlend Oftedal
 
Xss is more than a simple threat
Xss is more than a simple threatXss is more than a simple threat
Xss is more than a simple threatAvădănei Andrei
 
Pentesting for startups
Pentesting for startupsPentesting for startups
Pentesting for startupslevigross
 
You wanna crypto in AEM
You wanna crypto in AEMYou wanna crypto in AEM
You wanna crypto in AEMDamien Antipa
 
Ajax to the Moon
Ajax to the MoonAjax to the Moon
Ajax to the Moondavejohnson
 
Javascript Security
Javascript SecurityJavascript Security
Javascript Securityjgrahamc
 
Top Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.NetTop Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.Netalsmola
 
Teflon - Anti Stick for the browser attack surface
Teflon - Anti Stick for the browser attack surfaceTeflon - Anti Stick for the browser attack surface
Teflon - Anti Stick for the browser attack surfaceSaumil Shah
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
Roberto Bicchierai - Defending web applications from attacks
Roberto Bicchierai - Defending web applications from attacksRoberto Bicchierai - Defending web applications from attacks
Roberto Bicchierai - Defending web applications from attacksPietro Polsinelli
 
Defeating Cross-Site Scripting with Content Security Policy (updated)
Defeating Cross-Site Scripting with Content Security Policy (updated)Defeating Cross-Site Scripting with Content Security Policy (updated)
Defeating Cross-Site Scripting with Content Security Policy (updated)Francois Marier
 
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...Start Pad
 

Similar to Django Web Application Security (20)

Avoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkAvoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might think
 
dJango
dJangodJango
dJango
 
Xss is more than a simple threat
Xss is more than a simple threatXss is more than a simple threat
Xss is more than a simple threat
 
Xss is more than a simple threat
Xss is more than a simple threatXss is more than a simple threat
Xss is more than a simple threat
 
Pentesting for startups
Pentesting for startupsPentesting for startups
Pentesting for startups
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
You wanna crypto in AEM
You wanna crypto in AEMYou wanna crypto in AEM
You wanna crypto in AEM
 
Ajax to the Moon
Ajax to the MoonAjax to the Moon
Ajax to the Moon
 
Cqcon2015
Cqcon2015Cqcon2015
Cqcon2015
 
Spyware
SpywareSpyware
Spyware
 
Spyware
SpywareSpyware
Spyware
 
Javascript Security
Javascript SecurityJavascript Security
Javascript Security
 
Top Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.NetTop Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.Net
 
&lt;img src="xss.com">
&lt;img src="xss.com">&lt;img src="xss.com">
&lt;img src="xss.com">
 
Fav
FavFav
Fav
 
Teflon - Anti Stick for the browser attack surface
Teflon - Anti Stick for the browser attack surfaceTeflon - Anti Stick for the browser attack surface
Teflon - Anti Stick for the browser attack surface
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
Roberto Bicchierai - Defending web applications from attacks
Roberto Bicchierai - Defending web applications from attacksRoberto Bicchierai - Defending web applications from attacks
Roberto Bicchierai - Defending web applications from attacks
 
Defeating Cross-Site Scripting with Content Security Policy (updated)
Defeating Cross-Site Scripting with Content Security Policy (updated)Defeating Cross-Site Scripting with Content Security Policy (updated)
Defeating Cross-Site Scripting with Content Security Policy (updated)
 
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
 

Recently uploaded

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Recently uploaded (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

Django Web Application Security

  • 1. Django Web Application Security By Levi Gross
  • 2. About Me Blog: http://www.levigross.com/ Twitter:@levigross Email: levi@levigross.com Python for 5 years Django for 2 ½ Computer Security for 8 years Python and Django are amazing!
  • 3. Who is attacking us Bots Malicious SEO Steal user info Hackers ScriptKiddies Hackers ÜberHackers We will bankrupt ourselves in the vain search for absolute security. — Dwight D. Eisenhower
  • 4. 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
  • 5. 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
  • 6. Information Disclosure Your Parts are showing
  • 7. Attack Surface Admin Site Defaults to /admin Views & URLS Can give someone an intimate view of your application. File Locations REST Use Piston Sentry
  • 8. 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
  • 9. Input Validation XXS SQL Injection HTTP Response Splitting Directory Traversal CRLF Injection
  • 10. 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
  • 11. 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…
  • 12. 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
  • 13. 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 'apos; AND "secpre_person"."last_name" LIKE %s% ESCAPE 'apos; ) smart_unicode(x).replace("", "").replace("%", "").replace("_", "") NEVER BUILD QUERYIES USING STRING FORMATTING query = 'SELECT * FROM secpre_personWHERE last_name = %s' % lnamePerson.objects.raw(query) UseParameterizedqueries Person.objects.raw('SELECT * FROM secpre_personWHERE last_name = %s', [lname])
  • 14. 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 OK Content-Type: text/html Content-Length: 19 <html>Control</html> Server: Apache Content-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 '' in value or '' in value: raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
  • 15. CRLF Injection Hijack email forms to:”me@myaddress.comcc:bill.gates@microsoft.comcc:paul.allen@microsoft.com” Django to the rescue if '' in val or '' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. Cross Site Request Forgery <imgsrc="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 OK Date: Mon, 17 Jan 2011 21:55:14 GMT Server: WSGIServer/0.1 Python/2.7.1 Expires: Mon, 17 Jan 2011 21:55:14 GMT Vary: Cookie Last-Modified: Mon, 17 Jan 2011 21:55:14 GMT ETag: "4030d6e6a6c31292791e61e8bc58b6e8" Cache-Control: max-age=0 Content-Type: text/html; charset=utf-8 Set-Cookie: csrftoken=9260e87b366dd2be2515bffffec5a746; Max-Age=31449600; Path=/
  • 20. 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
  • 21. 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.
  • 22. 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.
  • 23. 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

Editor's Notes

  1. Salted hashes make it harder to guess the password by making each password unique. They are immune to rainbow table (pre-generated hashes) attacks.
  2. Don’t try to create your own version of REST. Use something like Django-Piston which has a proven track record. Also never use your object ID’s in urls. If needed use UUID’s
  3. The regular Django auto escape helps in almost every case. However you need to protect yourself in every case. That’s why using the ESAPI is one of the best solutions to the overall problem.
  4. The Django ORM is escaping my LIKE query using the function on the bottom. All other queries are parameterized.
  5. SESSION_COOKIE_HTTPONLY should be set if you don’t want JavaScript to touch your cookie.
  6. Without that cookie you get a 403 if you want to post to that form.
  7. Easy 2 factor auth is sending a SMS to a persons cellphone. If your going to use OAUTH then remember to send everything secure (HTTPS).
  8. Django has a lot of security built in so if you ever replace any part of it make sure it’s secure enough to be on your website.