One can use overlayfs
to avoid duplication. If it's temporary, everything can be done using /tmp
. Combined with a mount namespace, this can then be made to affect a single application. To be prepared from root (it does work with an user+mount namespace where a normal user is mapped as root, but without privileged assistance and/or recent kernel for pid translation, user mappings wouldn't help to do something useful).
- create a new mount namespace
- create an
overlayfs
in this mount namespace
- bind mount this overlayfs back over
/etc
- change contents (eg delete the
/etc/resolv.conf
symlink then create the regular file /etc/resolv.conf
with custom content)
- run application, still from this mount namespace
Example:
mkdir /tmp/upper /tmp/work /tmp/fake_etc
unshare -m
next commands are run in the new mount namespace:
mount -t overlay -olowerdir=/etc,upperdir=/tmp/upper,workdir=/tmp/work overlay_etc /tmp/fake_etc
then just cover /etc
with the one used to fake its contents:
mount --bind /tmp/fake_etc /etc
and do changes (affecting only the overlayfs in the mount namespace):
rm /etc/resolv.conf
echo nameserver 192.0.2.2 > /etc/resolv.conf
AFAIK can't mount a mount namespace to keep a reference. If needed one can use instead a PID reference from the mount namespace:
# echo $$
325304
Either in the same shell or in a separate (root) shell by running this:
nsenter -t 325304 --mount
then following the previous example (with a nameserver 192.0.2.2 that isn't reachable):
# su - -c 'ping stackexchange.com' someuser
ping: stackexchange.com: Name or service not known
While anywhere else ping
will work as usual.
mount --bind newresolv /tmp/mnt/etc/resolv.conf
it will follow the link path or, in my case where the link path is nonexistent, it fails with an errormount point is a symbolic link to nowhere
– ZAB Jul 21 '19 at 19:03unshare
, see duplicate. There is probably a way to do it without root privileges (maybe fuse). – ctrl-alt-delor Jul 21 '19 at 22:24fopen()
with aLD_PRELOAD
hack will not work when/etc/resolv.conf
is opened by the resolver (ie viagetaddrinfo()
), and the way to reliably use unshare + bind mount with a "dynamic" symlink like/etc/resolv.conf
needs to be explained more (at least for me, it's not at all obvious how that could be done; assuming that this Q is linux-only, despite no [linux] tag). – Jul 22 '19 at 03:11