Search code examples
pythonchroot

python os.chroot : unexpected output after exiting chroot


I have the following code:

#! /usr/bin/python

import os
import subprocess

def run_subprocess(cmd):
    print 'Starting : {}'.format(cmd)
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    odata, edata = p.communicate()
    print 'Done : {}'.format(cmd)
    if odata:
        print 'Output : {}'.format(odata)
    if edata:
        print 'Error : {}'.format(edata)
    return odata

LS_CMD = 'ls'
run_subprocess(LS_CMD)  # output 1
x_cwd = os.getcwd()
root_fd =os.open('/', os.O_RDONLY)
os.chroot('/mnt/mnt_sda5')
os.chdir('/')
os.fchdir(root_fd)
os.close(root_fd)
os.chdir(x_cwd)
run_subprocess(LS_CMD)  # output 2
print os.getcwd()

I chroot into a different directory and came back to the present working directory.

I was expecting both output1 and output2 matching. The output1 is what I expect to see. The output2 is empty.

Could you please explain the reason why ?

Thanks


Solution

  • Immediately before your os.chdir(x_cwd) you need os.chroot('.') to change the root back to the original '/' path that you've now changed to with fchdir. So those lines become:

    os.fchdir(root_fd)
    os.chroot('.')
    os.close(root_fd)
    

    There are some detail on this here - http://www.bpfh.net/simes/computing/chroot-break.html