2

What I'm trying to do is essentially as follows:

some_function_1();
chroot("/some_other_root");
some_function_2();
//Get back to main root somehow...
some_function_3();

So that only some_function_2() runs in the chroot environment, but other code runs in the normal environment.

Is this sort of thing possible to do within one process? Or will I need to fork into a new process to do this?

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
  • Do you intend to run with root privileges? https://unix.stackexchange.com/questions/105/chroot-jail-what-is-it-and-how-do-i-use-it – Yunnosch Jul 09 '21 at 05:41
  • @Yunnosch You don't need root privileges now that user namespaces exist, although you do have to do an interesting dance sometimes. – o11c Jul 09 '21 at 05:57
  • The link mentions that root can leave the chroot jail. That is why I ask about root privileges and why I think that the comment by @n.1.8e9-where's-my-sharem. is not unconditionally applicable. – Yunnosch Jul 09 '21 at 06:02
  • @Yunnosch you are right, I confused chroot with something else. – n. m. could be an AI Jul 09 '21 at 10:47
  • @n.1.8e9-where's-my-sharem. Thanks for confirming. – Yunnosch Jul 09 '21 at 12:32

1 Answers1

4

The root directory is a property of the process. Each process, in the user area, has two inodes, which are used to start the files search parsing algorithm:

  • The root directory inode is maintained in a reference in the user area of every process that has that directory as the root inode.
  • The current working directory, is maintained also as a reference in the user area.

Both inodes are used as starting points to parse filenames starting with / (from the root inode), and not starting with / (for the current directory inode) respectively.

The change of the current directory requires only that the user has x permission on all the directories that are navigated (using the current root or current dir inodes as starting point) but the chroot() system call requires the user root privileges, so it is not possible to do it on a normal user process.

Anyway, as you have probably guessed already, being a property of a process, a single function inside that process cannot have different root or current directory inodes. So your plan is not possible, from my point of view.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31
  • Thanks, I was able to accomplish what I needed by forking a new process and just running a function in that forked process. – Rocky Pulley Jul 23 '21 at 06:07
  • This is how it’s implemented in the shell. You start a subprocess that execs a program in the chrooted directory. – Luis Colorado Oct 20 '22 at 15:51