Skip to content

Instantly share code, notes, and snippets.

@raylu
Created June 14, 2018 22:54
Show Gist options
  • Save raylu/d48a8d9070667da1babe095a82021fb6 to your computer and use it in GitHub Desktop.
Save raylu/d48a8d9070667da1babe095a82021fb6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import ctypes
import ctypes.util
import errno
import os
import signal
libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
CLONE_NEWNS = 0x00020000 # New mount namespace group
CLONE_NEWCGROUP = 0x02000000 # New cgroup namespace
CLONE_NEWUTS = 0x04000000 # New utsname namespace
CLONE_NEWIPC = 0x08000000 # New ipc namespace
CLONE_NEWUSER = 0x10000000 # New user namespace
CLONE_NEWPID = 0x20000000 # New pid namespace
CLONE_NEWNET = 0x40000000 # New network namespace
MS_MGC_VAL = 0xC0ED0000
MS_REC = 16384
MS_UNBINDABLE = (1<<17) # change to unbindable
MS_PRIVATE = (1<<18) # change to private
MS_SLAVE = (1<<19) # change to slave
MS_SHARED = (1<<20) # change to shared
def exc(r):
if r != 0:
no = ctypes.get_errno()
raise Exception(r, errno.errorcode.get(no, no))
r = libc.unshare(CLONE_NEWNS | CLONE_NEWPID)
exc(r)
if os.fork() == 0:
r = libc.mount(None, b'/', None, MS_PRIVATE, None)
exc(r)
r = libc.mount(b'proc', b'/home/raylu/rootfs/proc', b'proc', 0, None)
exc(r)
os.execvp('chroot', ['chroot', 'rootfs', '/bin/bash'])
else:
os.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment