SlideShare una empresa de Scribd logo
1 de 16
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?

Más contenido relacionado

La actualidad más candente

Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
Sumit Kumar
 

La actualidad más candente (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
 

Destacado

Another Introduce to Redis
Another Introduce to RedisAnother Introduce to Redis
Another Introduce to Redis
jiaqing zheng
 
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]2
makeefer
 
Amazingbeautifullandscapes 090611232859 Phpapp02
Amazingbeautifullandscapes 090611232859 Phpapp02Amazingbeautifullandscapes 090611232859 Phpapp02
Amazingbeautifullandscapes 090611232859 Phpapp02
fauzanmuslim
 
AGUILAS 2009
AGUILAS 2009AGUILAS 2009
AGUILAS 2009
paobazzi
 
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
 

Destacado (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 a 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
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
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
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual Studio
Ahasan Habib
 
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
 
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
 

Similar a 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 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...
 
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
 

Último

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Último (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

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?