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

此生再无相见时 提交于 2019-11-28 04:33:34
kamae

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.

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.

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!