Expected bahaviour of os.chroot and os.getcwd

Nobody nobody at nowhere.com
Tue Sep 14 12:19:57 CEST 2010


On Mon, 13 Sep 2010 19:04:53 +0100, r0g wrote:

> i.e. So do I always have to change directory after changing into a chroot?

You don't *have* to change the directory, but not doing so probably
defeats the point of performing a chroot().

> The reason I ask is because an app I was running inside the chrooted 
> environment (specifically: apt-get) was trying to access files outside 
> the chroot and erroring when it couldn't. I figured it must be doing a 
> getcwd() and getting the cwd of the script that initialized the chroot. 
> I just wanted to confirm that's how it's supposed to work so I'd 
> appreciate it if anyone either knows or can point me to the docs that 
> explain in more detail than http://docs.python.org/library/os.html

See the relevant manpages. os.chroot, os.chdir and os.getcwd are
relatively thin interfaces to the underlying OS functions.

> Also, out of curiosity... If it does work (and should work) the way I 
> think it does how come os.chroot doesn't set the cwd to "/" for you? 

Because os.chroot just calls the OS' chroot(), which doesn't perform an
implicit chdir(). I don't know whether there is any deep reason for the
behaviour (beyond the Unix philosophy of "do what I say, not what you
think I mean"), but it's been that way forever and isn't likely to change.

> It's not a costly operation and it could prevent errors of ignorance 
> such as my own. Are there any good reasons why a person (who isn't a 
> hacker / cracker / kludger) would want chrooted processes to be able to 
> see the calling script's cwd anyway? Maybe I'm having a failure of 
> imagination today but the only things I can think that info could be 
> useful for are jailbreaking, nefarious reconnaissance and real ugly 
> hacks. Maybe someone here can enlighten me :)

chroot() wasn't designed as a security mechanism. It simply allows you to
control a parameter of the filename resolution algorithm (i.e. the root
directory).

If you want to use it as a security mechanism, you have to perform
additional work, i.e. ensuring that there are no other ways of escaping
the chroot (cwd, descriptors, etc). Oh, and you need to lose the ability
to perform a further chroot (root privilege or CAP_SYS_CHROOT), otherwise
you can just do e.g.:

	os.chdir("/")
	os.mkdir("foo")
	os.chroot("foo")
	os.chdir("..")

Making Python's os.chroot() call os.chdir() wouldn't help from a security
standpoint, as the code can still achieve the "raw" behaviour with e.g.
ctypes or os.system("chroot ...").




More information about the Python-list mailing list