Rocky Pulley
Rocky Pulley

Reputation: 23321

How do I run in chroot environment temporarily in a C program?

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?

Upvotes: 2

Views: 713

Answers (1)

Luis Colorado
Luis Colorado

Reputation: 12698

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.

Upvotes: 4

Related Questions