SlideShare a Scribd company logo
Django Web Application SecurityByLevi Gross
About MeBlog: http://www.levigross.com/Twitter:@levigrossEmail: levi@levigross.comPython for 5 yearsDjango for 2 ½Computer Security for 8 yearsPython and Django are amazing!
Who is attacking usBotsMalicious SEOSteal user infoHackersScriptKiddiesHackersÜberHackersWe 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 $ 9595556c4f693158c232f0885d266fe30671ca8aTake that Gawker!Secure session frameworkAutomatic variable escapingXXSSQL InjectionCSRF (Cross Site Request Forgery) ProtectionProtection against Email Header injectionProtection 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 VulnerabilitiesInformation DisclosureInput ValidationClick JackingSession HijackingCSRFPasswordsDenial of Service0 daysIn 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 DisclosureYour Parts are showing
Attack SurfaceAdmin SiteDefaults to /adminViews & URLSCan give someone an intimate view of your application.File LocationsRESTUse PistonSentry
How to protect yourselfNever deploy with the default settingsLong URLS are the best (but your not out of the woods)Change the file name/location of user contentValidate uploadsRemove unneeded softwareif not chroot
Input ValidationXXSSQL InjectionHTTP Response SplittingDirectory TraversalCRLF Injection
Cross Site ScriptingDjango Protects us by autoescaping outputreturn 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 deprivationMy Template CodeSecure:<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 QuotesUse Sanitizerslxmlhtml5libUse WhitelistsUse Markdown
SQL InjectionPython protects usParameterized queries according to PEP 249Django’s ORM Protects usparameterized queriesPerson.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 FORMATTINGquery = 'SELECT * FROM secpre_personWHERE last_name = %s' % lnamePerson.objects.raw(query) UseParameterizedqueriesPerson.objects.raw('SELECT * FROM secpre_personWHERE last_name = %s', [lname])
HTTP Response SplittingNew Lines in the HTTP HeadersHTTP/1.1 302 Moved TemporarilyDate: Wed, 24 Dec 2003 15:26:41 GMT Location: http://10.1.1.1/someview/?lang=foobarContent-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 weekKudos to Neal Poole from MatasanoDjango 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 InjectionHijack email formsto:”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/passwdDjango should never serve static filesYour webserver should serve all static files and be locked into the web root directoryNever allow users to dictate what happendsDjango Static Serve isn’t powerlessdrive, part = os.path.splitdrive(part)        head, part = os.path.split(part)        if part in (os.curdir, os.pardir):            # Strip '.' and '..' in path.            continue
Click JackingUse X-FRAMEHTTP header X-FRAME-OPTIONS: DENYhttps://github.com/paulosman/django-xframeoptionsUse a Framekiller<script type="text/javascript">                                                                      if(top != self) top.location.replace(location);                                              </script> Beware of sites that you visit
Session HijackingFireSheepCookie info not sent over HTTPSPass the hashSESSION_COOKIE_SECURE = TrueSESSION_COOKIE_HTTPONLY = TrueSessionsNever store private data in clear textNever 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 worksDjango 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=/
Denial Of ServiceEverything is vulnerable Impossible to defend against every variantHarden your serverRate limitingDo this on a server levelIf you need to do this on a view levelhttps://gist.github.com/719502Fine tune access methods for your viewsrestrict the HTTP method to the appropriate view
PasswordsPasswords are your biggest nightmareDon’t trust themMake sure that you are using SHA1Even though it works md5 and crypt shouldn’t be used. crypt should NEVER be used!!! Rate limitingUse Django-axeshttp://code.google.com/p/django-axes/Never rely on just a passwordIf you can use 2 factor authentication do it.
0 Day ProtectionRun for the hillsGood security is like a big onionMany layersBitterLimit your exposureServer monitoringRemember a good programmer looks both ways before crossing a one way street.
Security TipsBe wary of updatesUpdate on security releasesBeware of 3rd party appsSeparate work from playDon’t rely on passwordsFail2BanStick with DjangoBe careful where you strayScan oftenSkipfish
Questions?

More Related Content

What's hot

Prometheus course
Prometheus coursePrometheus course
Prometheus course
Jorn Jambers
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
Niyas Nazar
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
John Lynch
 
Introducing Vault
Introducing VaultIntroducing Vault
Introducing Vault
Ramit Surana
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
bilcorry
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
Bo-Yi Wu
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
George Shuklin
 
Vault 101
Vault 101Vault 101
Vault 101
Hazzim Anaya
 
Hashicorp Vault ppt
Hashicorp Vault pptHashicorp Vault ppt
Hashicorp Vault ppt
Shrey Agarwal
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versions
neexemil
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
Scott Hurrey
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
Suresh Kumar
 
Docker Container Security
Docker Container SecurityDocker Container Security
Docker Container Security
Suraj Khetani
 
XXE: How to become a Jedi
XXE: How to become a JediXXE: How to become a Jedi
XXE: How to become a Jedi
Yaroslav Babin
 
F5 BIG-IP Misconfigurations
F5 BIG-IP MisconfigurationsF5 BIG-IP Misconfigurations
F5 BIG-IP Misconfigurations
Denis Kolegov
 
Cypress-vs-Playwright: Let the Code Speak
Cypress-vs-Playwright: Let the Code SpeakCypress-vs-Playwright: Let the Code Speak
Cypress-vs-Playwright: Let the Code Speak
Applitools
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
Mikhail Egorov
 
Thick client pentesting_the-hackers_meetup_version1.0pptx
Thick client pentesting_the-hackers_meetup_version1.0pptxThick client pentesting_the-hackers_meetup_version1.0pptx
Thick client pentesting_the-hackers_meetup_version1.0pptx
Anurag Srivastava
 

What's hot (20)

Prometheus course
Prometheus coursePrometheus course
Prometheus course
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Introducing Vault
Introducing VaultIntroducing Vault
Introducing Vault
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Vault 101
Vault 101Vault 101
Vault 101
 
Hashicorp Vault ppt
Hashicorp Vault pptHashicorp Vault ppt
Hashicorp Vault ppt
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versions
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Docker Container Security
Docker Container SecurityDocker Container Security
Docker Container Security
 
XXE: How to become a Jedi
XXE: How to become a JediXXE: How to become a Jedi
XXE: How to become a Jedi
 
F5 BIG-IP Misconfigurations
F5 BIG-IP MisconfigurationsF5 BIG-IP Misconfigurations
F5 BIG-IP Misconfigurations
 
Cypress-vs-Playwright: Let the Code Speak
Cypress-vs-Playwright: Let the Code SpeakCypress-vs-Playwright: Let the Code Speak
Cypress-vs-Playwright: Let the Code Speak
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
 
Thick client pentesting_the-hackers_meetup_version1.0pptx
Thick client pentesting_the-hackers_meetup_version1.0pptxThick client pentesting_the-hackers_meetup_version1.0pptx
Thick client pentesting_the-hackers_meetup_version1.0pptx
 

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 think
Erlend Oftedal
 
dJango
dJangodJango
dJango
Bob Chao
 
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
Avădănei Andrei
 
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
Romanian Cyber Conference
 
Pentesting for startups
Pentesting for startupsPentesting for startups
Pentesting for startups
levigross
 
PHP Security
PHP SecurityPHP Security
PHP Security
Mindfire Solutions
 
You wanna crypto in AEM
You wanna crypto in AEMYou wanna crypto in AEM
You wanna crypto in AEM
Damien Antipa
 
Ajax to the Moon
Ajax to the MoonAjax to the Moon
Ajax to the Moon
davejohnson
 
Cqcon2015
Cqcon2015Cqcon2015
Cqcon2015
Antonio Sanso
 
Spyware
SpywareSpyware
Spyware
guest6fde72
 
Spyware
SpywareSpyware
Javascript Security
Javascript SecurityJavascript Security
Javascript Security
jgrahamc
 
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
alsmola
 
&lt;img src="xss.com">
&lt;img src="xss.com">&lt;img src="xss.com">
&lt;img src="xss.com">
"&lt;u>aaa&lt;/u>
 
Fav
FavFav
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
Saumil 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 attacks
Pietro 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

RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
SynapseIndia
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
CiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.pptCiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.ppt
moinahousna
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
maigasapphire
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
Safe Software
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Torry Harris
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
alexjohnson7307
 
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
digitalxplive
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes..."Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
Anant Gupta
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Nicolás Lopéz
 

Recently uploaded (20)

RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
CiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.pptCiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.ppt
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
 
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes..."Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
 

Django Web Application Security

  • 1. Django Web Application SecurityByLevi Gross
  • 2. About MeBlog: http://www.levigross.com/Twitter:@levigrossEmail: levi@levigross.comPython for 5 yearsDjango for 2 ½Computer Security for 8 yearsPython and Django are amazing!
  • 3. Who is attacking usBotsMalicious SEOSteal user infoHackersScriptKiddiesHackersÜberHackersWe 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 $ 9595556c4f693158c232f0885d266fe30671ca8aTake that Gawker!Secure session frameworkAutomatic variable escapingXXSSQL InjectionCSRF (Cross Site Request Forgery) ProtectionProtection against Email Header injectionProtection 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 VulnerabilitiesInformation DisclosureInput ValidationClick JackingSession HijackingCSRFPasswordsDenial of Service0 daysIn 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
  • 7. Attack SurfaceAdmin SiteDefaults to /adminViews & URLSCan give someone an intimate view of your application.File LocationsRESTUse PistonSentry
  • 8. How to protect yourselfNever deploy with the default settingsLong URLS are the best (but your not out of the woods)Change the file name/location of user contentValidate uploadsRemove unneeded softwareif not chroot
  • 9. Input ValidationXXSSQL InjectionHTTP Response SplittingDirectory TraversalCRLF Injection
  • 10. Cross Site ScriptingDjango Protects us by autoescaping outputreturn 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 deprivationMy Template CodeSecure:<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 QuotesUse Sanitizerslxmlhtml5libUse WhitelistsUse Markdown
  • 13. SQL InjectionPython protects usParameterized queries according to PEP 249Django’s ORM Protects usparameterized queriesPerson.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 FORMATTINGquery = 'SELECT * FROM secpre_personWHERE last_name = %s' % lnamePerson.objects.raw(query) UseParameterizedqueriesPerson.objects.raw('SELECT * FROM secpre_personWHERE last_name = %s', [lname])
  • 14. HTTP Response SplittingNew Lines in the HTTP HeadersHTTP/1.1 302 Moved TemporarilyDate: Wed, 24 Dec 2003 15:26:41 GMT Location: http://10.1.1.1/someview/?lang=foobarContent-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 weekKudos to Neal Poole from MatasanoDjango 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 InjectionHijack email formsto:”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/passwdDjango should never serve static filesYour webserver should serve all static files and be locked into the web root directoryNever allow users to dictate what happendsDjango Static Serve isn’t powerlessdrive, 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 JackingUse X-FRAMEHTTP header X-FRAME-OPTIONS: DENYhttps://github.com/paulosman/django-xframeoptionsUse a Framekiller<script type="text/javascript"> if(top != self) top.location.replace(location); </script> Beware of sites that you visit
  • 18. Session HijackingFireSheepCookie info not sent over HTTPSPass the hashSESSION_COOKIE_SECURE = TrueSESSION_COOKIE_HTTPONLY = TrueSessionsNever store private data in clear textNever 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 worksDjango 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=/
  • 20. Denial Of ServiceEverything is vulnerable Impossible to defend against every variantHarden your serverRate limitingDo this on a server levelIf you need to do this on a view levelhttps://gist.github.com/719502Fine tune access methods for your viewsrestrict the HTTP method to the appropriate view
  • 21. PasswordsPasswords are your biggest nightmareDon’t trust themMake sure that you are using SHA1Even though it works md5 and crypt shouldn’t be used. crypt should NEVER be used!!! Rate limitingUse Django-axeshttp://code.google.com/p/django-axes/Never rely on just a passwordIf you can use 2 factor authentication do it.
  • 22. 0 Day ProtectionRun for the hillsGood security is like a big onionMany layersBitterLimit your exposureServer monitoringRemember a good programmer looks both ways before crossing a one way street.
  • 23. Security TipsBe wary of updatesUpdate on security releasesBeware of 3rd party appsSeparate work from playDon’t rely on passwordsFail2BanStick with DjangoBe careful where you strayScan oftenSkipfish

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.