MOHAMED
MOHAMED

Reputation: 43558

How to execute commands in chroot?

In my source code I make chroot and then have some code doing some staff then I want to execute linux command. But the command does not work since I changed the root with chroot.

here after the source code:

int main(void)
{

    if (chroot("/tmp") < 0)
        printf("error in chroot\n");

        /* some source code doing staffs */

    system("ls > /logloglog.txt"); // command failed

    return 0;
}

How to execute command in chroot?

Or is it possible to exit from chrood then execute the command and then back to the chroot again?

Upvotes: 3

Views: 3255

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754570

If you use chroot(), you have to consider the consequences of what you do. One of the major consequences is that many (most, all) of the commands normally available are not available unless you make them available in the chroot()'d environment.

Doing that job properly is non-trivial. You may need parts of /dev, /bin, /etc, /usr, /lib (and probably others too) installed appropriately under the new root directory. Symlinks back to 'outside the chroot() environment' won't work, in general. You have to make copies of what's important. One side effect of all this: /tmp is very rarely an appropriate place to create a fully operational chroot() environment. You might get away with a limited access sub-directory under /tmp, but putting a user in /tmp doesn't isolate them from other users, or other users from them, very well.

One other major possibility: you do not give the user access to other commands after you've done chroot(). That is, you do not try to use system() in your code; and you don't give the victim user access to a shell or shell utilities.

Using chroot() is not something you do casually, in other words. To do a good job takes quite a lot of careful thought and preparation.

Would you be better off with a container or virtual machine of some sort instead?

Do use Google or any other search engine to search for terms such as:

  • 'chroot jail escape'
  • 'chroot jail setup'
  • 'chroot jail vs docker'

Is it possible to exit from chroot then execute the command and then back to the chroot again?

Not really. You might be able have a controlling program that forks a child that does chroot() and processes material and then terminates, so that the controlling program can do its job (execute the command) and then you could fork another child that goes back into the chroot() jail. But that's not the same as the current process getting out of jail — it would make chroot() totally ineffective if any program could cancel its jail time on a whim and resume unjailed activity.

Upvotes: 3

Daniel Lazar
Daniel Lazar

Reputation: 111

What about:

system("chroot /tmp /bin/bash -c \"<COMMAND>\"");

You can just run chroot using system directly and with -c execute command inside /tmp environment

Upvotes: -1

Related Questions