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. I could write a program that does this that would look something like:
uid = LookupUser(args[username]) // no /etc/passwd in jail
chroot(args[newroot])
cd("/")
setuids(uid)
execve(args[exe:])
Is that my best bet or is there a standard tool that does that for me?
I rolled my own here:
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 ;)
来源:https://stackoverflow.com/questions/3737008/how-to-run-a-command-in-a-chroot-jail-not-as-root-and-without-sudo