-
-
Save mimi1vx/78cb35931f59754c7c426c20ff449dba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# please run: mkdir /tmp/img ; docker export $(docker create centos) | tar -C /tmp/img/ -xvf - | |
# before this script | |
import os | |
import ctypes | |
from multiprocessing import Process | |
CLONE_NEWUSER = 0x10000000 | |
CLONE_NEWPID = 0x20000000 | |
CLONE_NEWNET = 0x40000000 | |
CLONE_NEWNS = 0x00020000 | |
MS_PRIVATE = 0x40000 | |
MS_REC = 0x4000 | |
MS_NODEV = 0x4 | |
MS_NOEXEC = 0x8 | |
MS_NOSUID = 0x2 | |
MS_SLAVE = 0x80000 | |
MS_BIND = 4096 | |
libc = ctypes.CDLL(None) | |
get_errno_loc = libc.__errno_location | |
get_errno_loc.restype = ctypes.POINTER(ctypes.c_int) | |
def unshare(flags): | |
rc = libc.unshare(flags) | |
if rc == -1: | |
raise Exception(os.strerror(get_errno_loc()[0])) | |
def mount(special_file, target, fs_type, flags, data): | |
rc = libc.mount(special_file, | |
target, | |
fs_type, | |
flags, | |
data) | |
if rc == -1: | |
raise Exception(os.strerror(get_errno_loc()[0])) | |
def unshare_user(): | |
print("I'm %s" % os.getuid()) | |
unshare(CLONE_NEWUSER) | |
with open('/proc/self/uid_map', 'w') as file_: | |
file_.write('0 1000 1') | |
print("I'm %s" % os.getuid()) | |
def containerize(): | |
unshare_user() | |
unshare(CLONE_NEWNET ^ CLONE_NEWPID ^ CLONE_NEWNS) | |
process = Process(target=cmd) | |
process.start() | |
def cmd(): | |
root = ('/tmp/img') | |
host = os.path.join(root, 'host') | |
if not os.path.exists(host): | |
os.makedirs(host) | |
mount('none', '/', None, MS_REC ^ MS_PRIVATE, None) | |
mount(root, root, None, MS_REC ^ MS_BIND, None) | |
os.chdir(root) | |
pivot_root('.', 'host') | |
mount_proc() | |
os.execve('/bin/bash', ['/bin/bash'], {'PATH': os.getenv('PATH')}) | |
def mount_proc(): | |
if not os.path.exists('/proc'): | |
os.makedirs('/proc') | |
mount('proc', '/proc', 'proc', | |
MS_NODEV ^ MS_NOEXEC ^ MS_NOSUID, None) | |
def pivot_root(new, old): | |
rc = libc.pivot_root(new, old) | |
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