Bin Wang
Bin Wang

Reputation: 2747

How to use chroot function in C programming?

I know that use the command "chroot" in linux need some files or directories such as usr, bin and so on. But when I use the function chroot() in C, do I need these files?

Here is my code, which "hw.out" is a binary file which just print "Hello, world". I compiled it and run it as root, but it was failed to print "Hello, world". What else should I do? Thank you!

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int result = chroot(".");

    if(result == 0)
        printf("Chroot Succese.\n");

    char *arrays[]={"./hw.out",NULL};
    execvp("./hw.out", arrays);
    return 0;
}

Upvotes: 2

Views: 3346

Answers (3)

Ed Heal
Ed Heal

Reputation: 60017

Make sure that hw.out is in the correct direct. Perhaps it is easier to have it statically linked if it is using libraries. Otherwise need to enable after chroot that it can access the dynamic libraries.

Upvotes: 0

Dima Tisnek
Dima Tisnek

Reputation: 11779

Please test that your hw.out works with command line chroot.

Perhaps hw.out is dynamically linked and is missing some libraries or ld-linux.so in the chroot directory.

Nitpicks 1, what's the point of return 0 after execvp? it never gets executed unless there is an error. I would rather have perror("can't exec"); return 1;

Nitpick 2, chroot() doesn't change working directory, although it works in your case, as you are chrooting to ".", it won't work as you expect if you later change it to chroot("somedir").

Upvotes: 1

Mat
Mat

Reputation: 206851

execvp is most likely failing, probably with ENOENT: no such file or directory, if hw.out is a dynamically linked executable.

For that to work, all the libraries required by hw.out need to be findable in the chrooted environment.

Try linking hw.out statically, and it should work. (And add error checking after execvp to see what errno is set to after the call if it returns.)

Upvotes: 4

Related Questions