c++chrootexecl

Why my code works without chroot function, but fail with chroot function?


I try to make my code work under chroot('/root/test1'), but it doesn't work correctly.

But when I delete chroot('/root/test1'), and modify execl("/test2", "test2", NULL) to execl("/root/test1/test2", "test2", NULL), it will work very well as expected. Why is that?

In addition, I would like to ask that if I set fp redirect to stdin, and then use execl function to work another program, the child program will get input at fp whether or not?

The file in '/root/test1/':

test2
test2.cpp
test3
test3.cpp

The value return by execl funtion is -1 and errno is 2.

test3.cpp

int main() {
    FILE *fp;
    errno = 0;
    fp = fopen("log.txt", "r");
    dup2(fileno(fp), fileno(stdin));
    cout << chdir("/root/test1") << endl;
    cout << chroot("/root/test1") << endl;

    DIR *dir = opendir("/");
    dirent *list;
    while ((list = readdir(dir)) != NULL) {
        cout << list -> d_name << "  ";
    }
    cout << endl;
    closedir(dir);
    errno = 0;
    cout << execl("/test2", "test2", NULL) << endl;
    cout << errno << endl;
    cout << strerror(errno) << endl;
    return 0;
}

test2.cpp

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
    int a,b;
    cin >> a;
    scanf("%d",&b);
    cout << a+b << endl;
    printf("%d",a+b);
    return 0;
}

log.txt

111 222

output*

0
0
.  test3.cpp  test3  ..  test2  test2.cpp  log.txt
-1
2
No such file or directory

Solution

  • Copy /usr /lib /lib64 and /bin/bash to /root/test1