How to run a command in a chroot jail not as root and without sudo?

后端 未结 5 489
北海茫月
北海茫月 2020-12-07 22:56

I\'m setting up a minimal chroot and want to avoid having sudo or su in it but still run my processes as non-root. This is a bit of a trick as running chroot requiers root.

相关标签:
5条回答
  • 2020-12-07 23:51

    If you invoke chroot from root, the chroot option --userspec=USER:GROUP will run the command under the non-root UID/GID.

    By the way, the option '--userspec' is first introduced in coreutils-7.5 according to a git repository git://git.sv.gnu.org/coreutils.

    0 讨论(0)
  • 2020-12-07 23:54

    fakechroot, in combination with fakeroot, will allow you to do this. They'll make all programs that are running act as if they're being run in a chroot as root but they'll actually be running as you.

    See also fakechroot's man page.

    0 讨论(0)
  • 2020-12-07 23:56

    A custom chrooter isn't at all hard to write:

    #define _BSD_SOURCE
    #include <stdio.h>
    #include <unistd.h>
    const char newroot[]="/path/to/chroot";
    int main(int c, char **v, char **e) {
        int rc; const char *m;
        if ( (m="chdir" ,rc=chdir(newroot)) == 0
          && (m="chroot",rc=chroot(newroot)) == 0
          && (m="setuid",rc=setuid(getuid())) == 0 )
                m="execve", execve(v[1],v+2,e);
        perror(m);
        return 1;
    }
    

    Make that setuid root and owned by a custom group you add your favored user to (and no 'other' access).

    0 讨论(0)
  • 2020-12-07 23:58

    You could use Linux Containers to create a chroot environment that is in a totally different namespace (IPC, filesytem, and even network)

    There is even LXD which is able to manage the creation of image-based containers and configure them to run as unprivileged users so that if the untrusted code manages to somehow escape the container, it will only be able to execute code as the unprivileged user and not as the system's root.

    Search 'Linux Containers' and 'LXD' on your favorite search engine ;)

    0 讨论(0)
  • 2020-12-08 00:02

    You can make use of linux capabilities to give your binary the ability to call chroot() w/o being root. As an example, you can do this to the chroot binary. As non-root, normally you'd get this:

    $ chroot /tmp/
    chroot: cannot change root directory to /tmp/: Operation not permitted
    

    But after you run the setcap command:

    sudo setcap cap_sys_chroot+ep /usr/sbin/chroot 
    

    It will let you do the chroot call.

    I don't recommend you do this to the system's chroot, that you instead do it to your own program and call chroot. That way you have more control over what is happening, and you can even drop the cap_sys_chroot privilege after you call it, so successive calls to chroot in your program will fail.

    0 讨论(0)
提交回复
热议问题