I can chroot with Dir.chroot
Dir.chroot("/var/chroot/mychroot")
But how can I return back from chroot?
The point of a chroot
is that you can't get out. However, if you don't chdir
to /var/chroot/mychroot
, then you can still access the outside filesystem using .
, and ..
I don't know much Ruby, but here's the trick in Python:
/tmp$ sudo python
>>> import os
>>> os.chroot("/var")
>>> os.listdir("/") # list our new root
['backups', 'log', 'opt', 'cache', 'spool', 'lib', 'local', 'run', 'lock', 'games', 'mail', 'tmp']
>>> os.listdir(".") # list a directory outside our jail
['.X0-lock', '.ICE-unix', '.X11-unix']
>>> os.listdir("..") # list the outside root
['lost+found', 'bin', 'mnt', 'boot', 'opt', 'scratch', 'var', 'proc', 'usr', 'etc', 'lib', 'srv', 'sys', 'media', 'root', 'selinux', 'vmlinuz', 'dev', 'tmp', 'home', 'sbin']
chdir
into the chroot
for it to take effect. You also need to close file descriptors on outside directories. chroot
is not a magic bullet, it should be used with care.
Before chroot save a reference to current root directory as a file descriptor.
To return set current working directory to the file descriptor, then chroot to .
.
Example python session:
$ unshare -r python3
Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> f = os.open("/", os.O_PATH)
>>> os.chdir("/mnt")
>>> os.chroot(".")
>>> os.listdir(".")
[]
>>> os.listdir("/")
[]
>>> os.chdir(f)
>>> os.chroot(".")
>>> os.listdir("/")
['bin', 'lib', 'lib64', 'sbin', 'boot', 'btrfs', 'btrfs_ssd', 'cdrom', 'dev', 'etc', 'home', 'media', 'mnt', 'opt', 'proc', 'root', 'run', 'snap', 'srv', 'sys', 'tmp', 'usr', 'var', 'secure']
Alternatively leave the current working directory set to the old root directory.
If you are running as root, another option is mounting /proc
and exiting via /proc/1/cwd/
. Example using shell commands:
whoami # Should be root
mount -t proc proc /proc
chroot /proc/1/cwd/ $SHELL
Just save the current path before using Dir.chroot, using Dir.pwd
pwd
is useless after chroot
, because it alters the filename lookup rules.
Dir.chroot(path){ execution }
?