def mount_procfs(target_dir_func): target_proc = target_dir_func('/proc') if not os.path.exists(target_proc): os.makedirs(target_proc, mode=0o755) mount('proc', target_proc, 'proc', MS_NOEXEC | MS_NODEV | MS_NOSUID, None) for path in ('sysrq-trigger', 'sys', 'irq', 'bus'): abs_path = os.path.join(target_proc, path) bind_mount(abs_path, abs_path) bind_mount(abs_path, abs_path, readonly=True)
def mount_root_fs(target, overlayfs_layers): if overlayfs_layers is None: overlayfs_layers = [] if overlayfs_layers and len(overlayfs_layers) != 2: raise NotImplementedError("Stacked overlayfs not supported (yet)") if overlayfs_layers: for layer in overlayfs_layers: if not os.path.exists(layer): os.makedirs(layer) lower, upper = overlayfs_layers mount('overlayfs', target, 'overlayfs', 0, 'lowerdir={0},upperdir={1}'.format(lower, upper)) else: # make target a mount point, for pivot_root bind_mount(target, target)
def mount_etc_files(target_dir_func): tmpfs = tempfile.mkdtemp(prefix='.etc', dir=target_dir_func('/')) mount('tmpfs', tmpfs, 'tmpfs', MS_NOEXEC | MS_NODEV | MS_NOSUID, 'size=1m') def write_and_mount_file(path, content): tmpfile = os.path.join(tmpfs, os.path.basename(path)) with open(tmpfile, 'w') as fp: fp.write(content) target = target_dir_func(path) if not os.path.exists(target): open(target, 'w').close() bind_mount(tmpfile, target) for etc_path in ('/etc/resolv.conf', '/etc/hosts'): etc_content = open(etc_path).read() write_and_mount_file(etc_path, etc_content) write_and_mount_file('/etc/hostname', socket.gethostname() + '\n') umount(tmpfs) os.rmdir(tmpfs)
def mount_devices(target_dir_func): devpts = target_dir_func('/dev/pts') ptmx = target_dir_func('/dev/ptmx') if not os.path.exists(devpts): os.makedirs(devpts, mode=0o755) try: mount('devpts', devpts, 'devpts', MS_NOEXEC | MS_NOSUID, 'newinstance,gid=5,mode=0620,ptmxmode=0666') except OSError: mount('devpts', devpts, 'devpts', MS_NOEXEC | MS_NOSUID, 'newinstance,mode=0620,ptmxmode=0666') if not os.path.exists(ptmx): os.symlink('pts/ptmx', ptmx) elif not os.path.islink(ptmx): bind_mount(os.path.join(devpts, 'ptmx'), ptmx) devshm = target_dir_func('/dev/shm') if os.path.exists(devshm): mount('devshm', devshm, 'tmpfs', MS_NOEXEC | MS_NODEV | MS_NOSUID, None) devices = ('null', 'zero', 'tty', 'random', 'urandom') for dev in devices: makedev(target_dir_func, '/dev/' + dev)