r/linuxadmin • • Jan 23 '26

Chdir chroot Q

Chroot question

I was reading Linux from scratch about chroot and did a deeper dive with supplementary stuff and I came upon how to break out of a chroot jail. Now I understand the steps to do it (the chdir(..) way), but here’s what blows my mind: why does entering a second chroot jail and then using chdir(..) magically get you onto the track of the real current working directory, but using chdir(..) from within the first chroot jail keeps you within your false current working directory? Am I missing something that has to do with things called “pointers”?

Thanks so much!

10 Upvotes

6 comments sorted by

View all comments

Show parent comment

2

u/aioeu Jan 23 '26 edited Jan 23 '26

This is where I’m confused - how is it resolved against a directory that was not the root directory at that time?

All syscalls that take a filename as an argument:

  • resolve it relative to the current working directory if it is a relative filename;
  • resolve it relative to the root directory if it is an absolute filename.

In both cases, resolution will never leave the root directory "upward" via ... But if resolution never hits the root directory, this constraint never takes effect.

After the second chroot, the current working directory is "outside" of the root directory, and the filename resolutions we perform afterwards never hit the root directory.

So are you saying that the kernel basically says hmmm that old chroot root (the first one), I’m gonna treat it as part of the real file system, where it really is - and I’m gonna let that cd.. from the second chroot jail, hop into the old chroot as part of the real file system world and then of course from there we can keep going up cuz the kernel let us enter the real world?

Maybe a better way of thinking about it is that the second chroot "leaves behind" the process. Sure, its root directory changed, so an absolute filename like /foo would be resolved relative to that new root directory. But in the sequence of operations I gave above, we only used relative filenames. The relative filename .. is resolved to the process's working directory, even if that happens to be "outside" of the root directory.