3

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;
}
1
  • So what did it do instead of printing "Hello World"? Commented Mar 15, 2012 at 7:58

3 Answers 3

4

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I just figured it out. It's true that hw.out needs some libraries because I compile it dynamically. After compile it static, it works!
1

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").

3 Comments

Thanks! I should use chdir("\\") to change the working directory. You are right that I dynamically compile the hw.out and don't have the libraries.
You should use chdir with the same absolute path as chroot, and before it. Linux paths don't use the backslash as a directory seperator, but the forward-slash.
And learn to use strace both on your own binaries and on existing executables, to understand the system calls they are doing.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.