SlideShare a Scribd company logo
Unwanted Code Injection
Possible security risks that may occur when evaluating data
from untrusted sources.
Cosmin Poieana – Student @ FII,
Malware Researcher @ Bitdefender
Code execution
● Most popular scripting languages: JavaScript, Python,
Perl, Ruby.
● And others: ECMAScript, ActionScript, Lisp, PHP, Lua,
PostScript, D, ColdFusion, Ruby, Forth, BASIC, etc.
● It's not a vulnerability and it doesn't affect certain versions
of interpreters or operating systems under they run.
● It simply executes (malicious) code (plain/compiled).
Real-world usage
Adequate uses
● web frameworks (web2py, cherrypy, django, flask),
dynamic code manipulation, compiled bytecode
optimizations, mathematical plotters (Lybniz)
Usual programmer (bad)
● improper data deserialization (json), foreign code
execution, loading config files, statements redundancy,
obfuscation techniques
How it works?
● The programmer is too lazy to build a proper parser.
● Unverified data content or source.
● Bad programming practices (code-based
configs/plugins).
● Other functions that implies code execution.
● Runtime code embedding to ease some specific tasks.
Python
Linux, Python 2.x
● eval(source[, globals[, locals]]) -> value
● exec …
● input([prompt]) -> value
● compile(source, filename, mode[, flags[, dont_inherit]])
-> code object
● execfile(filename[, globals[, locals]])
Python - examples
>>> eval("1+2")
3
>>> exec "import os; os.system('pwd')"
/home/cmin/Desktop/pysec
>>> number = input("Number: ")
Number: exit()
>>> op = compile("a=1;b=2;c=(a*b)**(a+b)", "<string>", "single")
>>> eval(op)
>>> c
8
Python - tricks
● eval (function) evaluates expressions, but exec (statement)
executes code, remember?
● How about “eval”-ing multiple statements...
>>> code = """
... import sys
... print sys.version
... """
>>> cobj = compile(code, "<string>", "exec")
>>> eval(cobj)
2.7.4 (default, Sep 26 2013, 03:20:56)
[GCC 4.7.3]
Python – interpreter
● eval vs. exec
● Using functions instead of statements (import)
● Namespaces (globals/locals)
● Replacing `__builtins__` (whitelisting)
Example I
Bad practice
● String evaluation instead of type converting for numeric
values.
Solution
● Alter the namespace with empty builtins.
● Replace input() with int(raw_input()).
Python - hacks
>>> eval("__import__('os')", {"__builtins__": {}})
...
NameError: name '__import__' is not defined
>>> eval("[x for x in
(1).__class__.__base__.__subclasses__() if x.__name__ ==
'catch_warnings'][0]()._module.__builtins__['__import__']
('os')", {"__builtins__": {}})
<module 'os' from '/usr/lib/python2.7/os.pyc'>
Example II
Bad practice
● Wrong and bogus (de)serialization methods.
Solution
● Use pickle or json library for this kind of work.
Example III
Bad practice
● Executing code from untrusted sources without checking
it.
Solution
● Verify the input in both the front and the back end.
● Use pkgutil library for module manipulation.
Python – crash
#! /usr/bin/env python
s = """(lambda fc=(lambda n: [c for c in
().__class__.__bases__[0].__subclasses__() if c.__name__ == n]
[0]): fc("function")(
fc("code")(
0,0,0,0,"random",(),(),(),"","",0,""), {})()
)()"""
eval(s, {"__builtins__": {}})
Segmentation fault (core dumped)
Python 3.x
● Crash (segmentation fault) – add one more `0` and replace some
strings with bytes:
>>> s = '(lambda fc=(lambda n: [c for c in
().__class__.__bases__[0].__subclasses__() if c.__name__ == n][0] ):fc("function")
(fc("code")(0,0,0,0,0,b"random",(),(),(),"","",0,b""),{})())()'
eval(s, {"__builtins__": {}})
Segmentation fault (core dumped)
● Builtins restore:
>>> s = "[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ ==
'Pattern'][0].__init__.__globals__['__builtins__']['print']('Works!')"
>>> eval(s, {"__builtins__": {}})
Works!
Protection
● Avoid these functions at all.
● Use only trusted encapsulated sources.
● Double-check input data.
● Sandbox or chroot.
Resources
● Many thanks to floyd and to his research:
http://www.floyd.ch/?p=584
● Ned Batchelder (builtins search tool):
http://nedbatchelder.com/blog/201302/finding_python_3_builtins.html
● Armin Ronacher:
http://lucumr.pocoo.org/2011/2/1/exec-in-python/
● Others:
http://lybniz2.sourceforge.net/safeeval.html
http://en.wikipedia.org/wiki/Eval
Questions?

More Related Content

What's hot

PHP Basics
PHP BasicsPHP Basics
PHP Basics
Henry Osborne
 
Donetconf2016: The Future of C#
Donetconf2016: The Future of C#Donetconf2016: The Future of C#
Donetconf2016: The Future of C#
Jacinto Limjap
 
Next .NET and C#
Next .NET and C#Next .NET and C#
Next .NET and C#
Bertrand Le Roy
 
History of C#
History of C#History of C#
History of C#
aschlapsi
 
Testing with Mock Objects
Testing with Mock ObjectsTesting with Mock Objects
Testing with Mock Objects
Ben Carey
 
Effective PHP. Part 2
Effective PHP. Part 2Effective PHP. Part 2
Effective PHP. Part 2
Vasily Kartashov
 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
Sumit Kumar
 
Effective PHP. Part 5
Effective PHP. Part 5Effective PHP. Part 5
Effective PHP. Part 5
Vasily Kartashov
 
Doppl development iteration #7
Doppl development   iteration #7Doppl development   iteration #7
Doppl development iteration #7
Diego Perini
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
Vasily Kartashov
 
Effective PHP. Part 6
Effective PHP. Part 6Effective PHP. Part 6
Effective PHP. Part 6
Vasily Kartashov
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10
Combell NV
 
PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)
Andrea Telatin
 
Control hijacking
Control hijackingControl hijacking
Control hijacking
G Prachi
 

What's hot (15)

PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Donetconf2016: The Future of C#
Donetconf2016: The Future of C#Donetconf2016: The Future of C#
Donetconf2016: The Future of C#
 
Next .NET and C#
Next .NET and C#Next .NET and C#
Next .NET and C#
 
History of C#
History of C#History of C#
History of C#
 
Testing with Mock Objects
Testing with Mock ObjectsTesting with Mock Objects
Testing with Mock Objects
 
Effective PHP. Part 2
Effective PHP. Part 2Effective PHP. Part 2
Effective PHP. Part 2
 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
 
Effective PHP. Part 5
Effective PHP. Part 5Effective PHP. Part 5
Effective PHP. Part 5
 
Doppl development iteration #7
Doppl development   iteration #7Doppl development   iteration #7
Doppl development iteration #7
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
 
Effective PHP. Part 6
Effective PHP. Part 6Effective PHP. Part 6
Effective PHP. Part 6
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10
 
PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)
 
Control hijacking
Control hijackingControl hijacking
Control hijacking
 

Viewers also liked

How A Web Page Is Seen
How A Web Page Is SeenHow A Web Page Is Seen
How A Web Page Is Seen
bwebster719
 
Crew, Foia, Documents 010156 - 010573
Crew, Foia, Documents  010156 - 010573Crew, Foia, Documents  010156 - 010573
Crew, Foia, Documents 010156 - 010573
Obama White House
 
F I L O S O F I A2
F I L O S O F I A2F I L O S O F I A2
F I L O S O F I A2
filosoficos01
 
Social Story Roshen
Social Story   RoshenSocial Story   Roshen
Social Story Roshen
guest4e0e609e
 
BDM Brochure
BDM BrochureBDM Brochure
BDM Brochure
BDM Consulting Inc.
 
La apatía
La apatíaLa apatía
La apatía
campir
 
normativa minedu
normativa minedu normativa minedu
normativa minedu
Anita S
 
Another Introduce to Redis
Another Introduce to RedisAnother Introduce to Redis
Another Introduce to Redisjiaqing zheng
 
Facebook Dorkbot
Facebook DorkbotFacebook Dorkbot
Facebook Dorkbot
Vivien Schilis
 
Tuesday - A Wild Stand - God Is Unmatchable
Tuesday - A  Wild  Stand - God Is  UnmatchableTuesday - A  Wild  Stand - God Is  Unmatchable
Tuesday - A Wild Stand - God Is Unmatchable
Jason Loveless
 
What Is Literary Criticism[1]2
What Is Literary Criticism[1]2What Is Literary Criticism[1]2
What Is Literary Criticism[1]2makeefer
 
Amazingbeautifullandscapes 090611232859 Phpapp02
Amazingbeautifullandscapes 090611232859 Phpapp02Amazingbeautifullandscapes 090611232859 Phpapp02
Amazingbeautifullandscapes 090611232859 Phpapp02
fauzanmuslim
 
Client Samples
Client SamplesClient Samples
Client Samples
joshuacrispin
 
USART
USARTUSART
USART
Ankit D
 
AGUILAS 2009
AGUILAS 2009AGUILAS 2009
AGUILAS 2009
paobazzi
 
Post-It Girl
Post-It GirlPost-It Girl
Post-It Girl
LitWorld
 
Alfresco企业内容管理标准方案
Alfresco企业内容管理标准方案Alfresco企业内容管理标准方案
Alfresco企业内容管理标准方案
huluboy social marketing
 
Towards An Integrated Ecosystem Based Management
Towards An Integrated Ecosystem Based ManagementTowards An Integrated Ecosystem Based Management
Towards An Integrated Ecosystem Based Management
University of Tasmania
 
Wine Star
Wine StarWine Star
Wine Star
Peter.Schulz
 

Viewers also liked (20)

How A Web Page Is Seen
How A Web Page Is SeenHow A Web Page Is Seen
How A Web Page Is Seen
 
Krecenje
KrecenjeKrecenje
Krecenje
 
Crew, Foia, Documents 010156 - 010573
Crew, Foia, Documents  010156 - 010573Crew, Foia, Documents  010156 - 010573
Crew, Foia, Documents 010156 - 010573
 
F I L O S O F I A2
F I L O S O F I A2F I L O S O F I A2
F I L O S O F I A2
 
Social Story Roshen
Social Story   RoshenSocial Story   Roshen
Social Story Roshen
 
BDM Brochure
BDM BrochureBDM Brochure
BDM Brochure
 
La apatía
La apatíaLa apatía
La apatía
 
normativa minedu
normativa minedu normativa minedu
normativa minedu
 
Another Introduce to Redis
Another Introduce to RedisAnother Introduce to Redis
Another Introduce to Redis
 
Facebook Dorkbot
Facebook DorkbotFacebook Dorkbot
Facebook Dorkbot
 
Tuesday - A Wild Stand - God Is Unmatchable
Tuesday - A  Wild  Stand - God Is  UnmatchableTuesday - A  Wild  Stand - God Is  Unmatchable
Tuesday - A Wild Stand - God Is Unmatchable
 
What Is Literary Criticism[1]2
What Is Literary Criticism[1]2What Is Literary Criticism[1]2
What Is Literary Criticism[1]2
 
Amazingbeautifullandscapes 090611232859 Phpapp02
Amazingbeautifullandscapes 090611232859 Phpapp02Amazingbeautifullandscapes 090611232859 Phpapp02
Amazingbeautifullandscapes 090611232859 Phpapp02
 
Client Samples
Client SamplesClient Samples
Client Samples
 
USART
USARTUSART
USART
 
AGUILAS 2009
AGUILAS 2009AGUILAS 2009
AGUILAS 2009
 
Post-It Girl
Post-It GirlPost-It Girl
Post-It Girl
 
Alfresco企业内容管理标准方案
Alfresco企业内容管理标准方案Alfresco企业内容管理标准方案
Alfresco企业内容管理标准方案
 
Towards An Integrated Ecosystem Based Management
Towards An Integrated Ecosystem Based ManagementTowards An Integrated Ecosystem Based Management
Towards An Integrated Ecosystem Based Management
 
Wine Star
Wine StarWine Star
Wine Star
 

Similar to Pysec

TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
Eelco Visser
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Nguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s view
Nguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s viewNguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s view
Nguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s view
Security Bootcamp
 
Anatomy of PHP Shells
Anatomy of PHP ShellsAnatomy of PHP Shells
Anatomy of PHP Shells
Vedran Krivokuca
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
Andrey Karpov
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean code
Eman Mohamed
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
Mithun Hunsur
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
Php Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimizationPhp Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimization
Vladimir Reznichenko
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual Studio
Ahasan Habib
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
Birol Efe
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
Sanjeev Kumar Jaiswal
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
Tharindu Weerasinghe
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
Itzik Kotler
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
JoshCasas1
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
Possibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented ProgrammingPossibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented Programming
kozossakai
 
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
CODE BLUE
 

Similar to Pysec (20)

TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Nguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s view
Nguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s viewNguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s view
Nguyen Huu Trung - Building a web vulnerability scanner - From a hacker’s view
 
Anatomy of PHP Shells
Anatomy of PHP ShellsAnatomy of PHP Shells
Anatomy of PHP Shells
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean code
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Php Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimizationPhp Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimization
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual Studio
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Possibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented ProgrammingPossibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented Programming
 
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
 

Recently uploaded

Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 

Recently uploaded (20)

Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 

Pysec

  • 1. Unwanted Code Injection Possible security risks that may occur when evaluating data from untrusted sources. Cosmin Poieana – Student @ FII, Malware Researcher @ Bitdefender
  • 2. Code execution ● Most popular scripting languages: JavaScript, Python, Perl, Ruby. ● And others: ECMAScript, ActionScript, Lisp, PHP, Lua, PostScript, D, ColdFusion, Ruby, Forth, BASIC, etc. ● It's not a vulnerability and it doesn't affect certain versions of interpreters or operating systems under they run. ● It simply executes (malicious) code (plain/compiled).
  • 3. Real-world usage Adequate uses ● web frameworks (web2py, cherrypy, django, flask), dynamic code manipulation, compiled bytecode optimizations, mathematical plotters (Lybniz) Usual programmer (bad) ● improper data deserialization (json), foreign code execution, loading config files, statements redundancy, obfuscation techniques
  • 4. How it works? ● The programmer is too lazy to build a proper parser. ● Unverified data content or source. ● Bad programming practices (code-based configs/plugins). ● Other functions that implies code execution. ● Runtime code embedding to ease some specific tasks.
  • 5. Python Linux, Python 2.x ● eval(source[, globals[, locals]]) -> value ● exec … ● input([prompt]) -> value ● compile(source, filename, mode[, flags[, dont_inherit]]) -> code object ● execfile(filename[, globals[, locals]])
  • 6. Python - examples >>> eval("1+2") 3 >>> exec "import os; os.system('pwd')" /home/cmin/Desktop/pysec >>> number = input("Number: ") Number: exit() >>> op = compile("a=1;b=2;c=(a*b)**(a+b)", "<string>", "single") >>> eval(op) >>> c 8
  • 7. Python - tricks ● eval (function) evaluates expressions, but exec (statement) executes code, remember? ● How about “eval”-ing multiple statements... >>> code = """ ... import sys ... print sys.version ... """ >>> cobj = compile(code, "<string>", "exec") >>> eval(cobj) 2.7.4 (default, Sep 26 2013, 03:20:56) [GCC 4.7.3]
  • 8. Python – interpreter ● eval vs. exec ● Using functions instead of statements (import) ● Namespaces (globals/locals) ● Replacing `__builtins__` (whitelisting)
  • 9. Example I Bad practice ● String evaluation instead of type converting for numeric values. Solution ● Alter the namespace with empty builtins. ● Replace input() with int(raw_input()).
  • 10. Python - hacks >>> eval("__import__('os')", {"__builtins__": {}}) ... NameError: name '__import__' is not defined >>> eval("[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__['__import__'] ('os')", {"__builtins__": {}}) <module 'os' from '/usr/lib/python2.7/os.pyc'>
  • 11. Example II Bad practice ● Wrong and bogus (de)serialization methods. Solution ● Use pickle or json library for this kind of work.
  • 12. Example III Bad practice ● Executing code from untrusted sources without checking it. Solution ● Verify the input in both the front and the back end. ● Use pkgutil library for module manipulation.
  • 13. Python – crash #! /usr/bin/env python s = """(lambda fc=(lambda n: [c for c in ().__class__.__bases__[0].__subclasses__() if c.__name__ == n] [0]): fc("function")( fc("code")( 0,0,0,0,"random",(),(),(),"","",0,""), {})() )()""" eval(s, {"__builtins__": {}}) Segmentation fault (core dumped)
  • 14. Python 3.x ● Crash (segmentation fault) – add one more `0` and replace some strings with bytes: >>> s = '(lambda fc=(lambda n: [c for c in ().__class__.__bases__[0].__subclasses__() if c.__name__ == n][0] ):fc("function") (fc("code")(0,0,0,0,0,b"random",(),(),(),"","",0,b""),{})())()' eval(s, {"__builtins__": {}}) Segmentation fault (core dumped) ● Builtins restore: >>> s = "[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'Pattern'][0].__init__.__globals__['__builtins__']['print']('Works!')" >>> eval(s, {"__builtins__": {}}) Works!
  • 15. Protection ● Avoid these functions at all. ● Use only trusted encapsulated sources. ● Double-check input data. ● Sandbox or chroot.
  • 16. Resources ● Many thanks to floyd and to his research: http://www.floyd.ch/?p=584 ● Ned Batchelder (builtins search tool): http://nedbatchelder.com/blog/201302/finding_python_3_builtins.html ● Armin Ronacher: http://lucumr.pocoo.org/2011/2/1/exec-in-python/ ● Others: http://lybniz2.sourceforge.net/safeeval.html http://en.wikipedia.org/wiki/Eval Questions?