Skip to content

Instantly share code, notes, and snippets.

@rwngwn
Created June 3, 2018 13:13
Show Gist options
  • Save rwngwn/26ece7ae3e97be116464871a811472e6 to your computer and use it in GitHub Desktop.
Save rwngwn/26ece7ae3e97be116464871a811472e6 to your computer and use it in GitHub Desktop.
# goo.gl/bRsdYQ
import ctypes
import os
from multiprocessing import Process
CLONE_NEWUSER = 0x10000000
CLONE_NEWPID = 0x20000000
CLONE_NEWNET = 0x40000000
CLONE_NEWNS = 0x00020000
libc = ctypes.CDLL(None)
get_errno_loc = libc.__errno_location
get_errno_loc.restype = ctypes.POINTER(ctypes.c_int)
def unshare(flag):
rc = libc.unshare(flag)
if rc == -1:
raise Exception(os.strerror(get_errno_loc()[0]))
def unshare_user():
print("I'm %s" % os.getuid()) # 1000
unshare(CLONE_NEWUSER)
with open('/proc/self/uid_map', 'w') as file_:
file_.write("0 1000 1")
print("I'm %s" % os.getuid()) # 0
def containerize():
unshare_user()
unshare(CLONE_NEWNET ^ CLONE_NEWPID ^ CLONE_NEWNS)
process = Process(target=cmd)
process.start()
MS_REC = 0x4000
MS_PRIVATE = 0x40000
MS_BIND = 4096
def mount(special_file, target, fs_type, flags, data):
libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_void_p)
rc = libc.mount(special_file.encode('utf-8'),
target.encode('utf-8'),
fs_type.encode('utf-8') if fs_type else fs_type,
flags,
data)
if rc == -1:
raise Exception(os.strerror(get_errno_loc()[0]))
def cmd():
root = 'rootfs'
mount('none', '/', None, MS_REC ^ MS_PRIVATE, None)
mount(root, root, None, MS_REC ^ MS_BIND, None)
os.chdir(root)
if not os.path.exists('host'):
os.makedirs('host')
pivot_root('.', 'host')
mount_proc()
os.execve('/bin/busybox', ['/bin/busybox', 'sh'], {'PATH': '/bin'})
MS_NODEV = 0x4
MS_NOEXEC = 0x8
MS_NOSUID = 0x2
def mount_proc():
mount('proc', '/proc', 'proc', MS_NODEV ^ MS_NOEXEC ^ MS_NOSUID, None)
def pivot_root(new, old):
libc.pivot_root.argtypes = (ctypes.c_char_p, ctypes.c_char_p)
rc = libc.pivot_root(new.encode('utf-8'), old.encode('utf-8'))
if rc == -1:
raise Exception(os.strerror(get_errno_loc()[0]))
containerize()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment