Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

howto Enter into chroot environment from C?

Tags:

c

linux

what i am try to do is to get my program to enter chroot environment and do some commands and then exit.

For 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, it will get me in the chroot environment however it will not fire func2 until i exit form the chroot environment. What i need is to get my code to do func1 and then func2 in chroot environment and then exit.I know what i am doing in my code is horribly wrong, however, i hope i could get some directions .

Any help would be much appreciated.

like image 825
Face Avatar asked Oct 15 '10 20:10

Face


People also ask

How do you enter chroot environment?

The -i option given to the env command will clear all variables of the chroot environment. After that, only the HOME , TERM , PS1 , and PATH variables are set again. The TERM=$TERM construct will set the TERM variable inside chroot to the same value as outside chroot.

Where is chroot located?

What is a Chroot Environment? A chroot environment is an operating system call that will change the root location temporarily to a new folder. Typically, the operating system's conception of the root directory is the actual root located at “ / ”.


1 Answers

If you're in C and you want to enter a chroot you can do so 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 don't set the current directory before chrooting it's possible to break out of the chroot.

like image 157
Anthony Towns Avatar answered Oct 13 '22 01:10

Anthony Towns