Exit from chroot environment - python

chroot() is a useful system call available in most UNIX like operating systems. I have been using chroot to do several hacks for the past few years. Mostly people use chroot for fixing boot loader / GRUB. To fix GRUB, a live cd can be used to boot into a GNU/Linux system, then run:

# chroot /mnt/root_partition

# echo chrooted environment

Then, execute grub-install or any command to update GRUB configs.

Basically chroot makes the environment believe provided path is the root “/” of the filesystem.

We can exit from chrooted environment by pressing Ctrl-D.

chroot can be used to build chroot jail to protect server services for preventing attacker to gain complete access to the server by creating chroot jails.

Last day, I was working on my GSOC project Live Installer for Pardus. It was the first time, I was using chroot() in python. It had to execute a few statements in chroot environment and come back to prevous environment. But exiting from chroot environment found to be difficult and there were no direct methods to exit from it. So I had to do a little hack. I would like to share the hack so that you can reuse it without going for long search on how to do it.

1
2
3
4
5
6
7
8
9
10
import os
real_root = os.open("/", os.O_RDONLY)
os.chroot("/mnt/new_root")
# Chrooted environment
# Put statements to be executed as chroot here
os.fchdir(real_root)
os.chroot(".")

# Back to old root
os.close(real_root)

chroot() is provided by os module The major player of this hack is fchdir() which can take file descriptor has argument and change to that directory as current working directory. We open our real root using real_root = os.open(“/”, os.O_RDONLY) and its file descriptor is stored in real_root. Now chroot to new file system. Execute all the required statements. After that execute fchdir() to change current directory to old_root using real_root descriptor. Then chroot to current directory to switch back to real root.

Happy Hacking :)