how从C进入chroot环境?

Fac*_*ace 5 c linux

我尝试做的是让我的程序进入chroot环境并执行一些命令,然后退出.

例如

#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;
}
Run Code Online (Sandbox Code Playgroud)

这段代码的问题是,它会让我进入chroot环境,但是在我退出chroot环境之前它不会触发func2.我需要的是让我的代码在chroot环境中执行func1然后执行func2然后退出.我知道我在代码中所做的事情是非常错误的,但是,我希望我能得到一些指示.

任何帮助将非常感激.

Ant*_*wns 8

如果您在C中并且想要输入chroot,则可以使用chroot()函数直接输入:

#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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果在chroot之前没有设置当前目录,则可能会突破chroot.

  • 另请注意,使用“chroot”而不删除超级用户权限(使用“setresuid”)通常是一个坏主意。 (2认同)