2

I can chroot with Dir.chroot

Dir.chroot("/var/chroot/mychroot")

But how can I return back from chroot?

2
  • 1
    Uhm, why not use a block? :-) Apr 3, 2012 at 9:16
  • 1
    What do you mean? Dir.chroot(path){ execution } ?
    – fl00r
    Apr 3, 2012 at 9:18

4 Answers 4

4

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']
2
  • How does it work? Is it a real chroot? Or maybe Python's chroot is just garbage? The idea of chroot is to remain in chroot forever.
    – Nowaker
    Dec 29, 2013 at 15:36
  • @DamianNowak: as I explained in the answer, you need to 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.
    – Fred Foo
    Dec 30, 2013 at 11:00
3

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.

1

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
-2

Just save the current path before using Dir.chroot, using Dir.pwd

1
  • The string returned by pwd is useless after chroot, because it alters the filename lookup rules.
    – Fred Foo
    Apr 3, 2012 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.