问题
Is it possible to start a process in Linux, and restrict its access to certain files/directories? For example:
$ start-process --enable-dir=./sandbox --exec="some-script.sh"
some-script.sh
won't be able to do anything outside of ./sandbox
.
回答1:
You can use chroot to set the root directory of your process tree. This means however, that all dependencies of that process must be available in it's new root.
There are a number of packages that can help you setup chroot-environments for your needs. Google is your friend ;)
Some pointers on building a chroot environment
When builing a chroot for some program or daemon you have to have a complete environment for the program you want to chroot. This means you have to provide a minimum system in a directory. That might contain:
- A shell and some shell utilities, or a variant of busybox. (this encompasses the next step too, if you aren't planning on deploying one single static executable that is).
- Libc and other dependent shared libraries.
- You need to check shared library dependencies using
ldd
orobjdump
. Every library that appears has to be in your private root directory. This step might be repeated several times for every executable and library you need. Note that some libraries, which are linked explicitly at runtime usingdlopen
need to be checked separately.
- You need to check shared library dependencies using
- Depending on what you plan to chroot a minimal
/dev
tree.- If you plan to chroot a daemon process this may well be needing some minimal files in
/dev
such asrandom
orzero
. You can create those with themknod
command. Please refer to themknod
documentation, as well as the linux documentation on which major/minor numbers which device should have.
- If you plan to chroot a daemon process this may well be needing some minimal files in
- Also depending on what you plan to chroot is a minimal
/etc
. Files needed therein are:- A minimal passwd and shadow (not your system passwd/shadow).
- A minimal
mtab
containing/
. - A minimal
group
(again, not your system group file).
You have to start somewhere, so it's best to start with the prerequisites for you program. Refer to your documentation for specifics.
回答2:
Typically you want to chroot
the process, so that it can only access a directory and its sub-directories, and only execute some defined commands.
See How to chroot.
来源:https://stackoverflow.com/questions/4518334/can-i-restrict-access-to-certain-files-for-a-certain-process