Howto Entering a chroot environment from C?

what I'm trying to do is get my program to enter the chroot environment and execute some commands and then exit.

Example

#include <stdlib.h> #include <stdio.h> #include <string.h> #define ChRoot "sudo chroot \"/\" /usr/bin/env -i HOME=/root TERM=\"$TERM\" PATH=/bin:/usr/bin:/sbin:/usr/sbin:/bin /bin/bash --login +h" void func1(){ //enter the chroot environment char line[130]; FILE *fp; fp = popen(ChRoot, "r"); while(fgets( line, sizeof line, fp)){ printf ("%s\n",line); } pclose(fp); } void func2(){ //run a command in the chroot environment char line[130]; FILE *fp; fp = popen("ls", "r"); while(fgets( line, sizeof line, fp)){ printf ("%s\n",line); } pclose(fp); } int main() { func1(); func2(); return 0; } 

The problem with this code is that it will be me in the chroot environment, but it will not run func2 until I exit the chroot environment. I need my code to execute func1 and then func2 in a chroot environment and then exit. I know what I am doing in my code, this is terribly wrong, however I hope I can get some guidance.

Any help would be greatly appreciated.

+4
source share
2 answers

If you are in C and want to enter chroot, you can do this directly using the chroot () function:

 #include <stdio.h> #include <unistd.h> int main(void) { FILE *f; /* chroot */ chdir("/tmp"); if (chroot("/tmp") != 0) { perror("chroot /tmp"); return 1; } /* do something after chrooting */ f = fopen("/etc/passwd", "r"); if (f == NULL) { perror("/etc/passwd"); return 1; } else { char buf[100]; while (fgets(buf, sizeof(buf), f)) { printf("%s", buf); } } return 0; } 

Note that if you do not set the current directory before chrooting, it is possible to break out of chroot.

+7
source

There is a chroot system call that does what you want. In fact, the chroot command-line utility itself uses this first and then spawns a shell.

+1
source

All Articles