Is it possible to run 'unshare -n [program]' as an unprivileged user?
In later versions of util-linux, unshare
gained the --map-root-user
option. Quoting from unshare(1)
version 2.26.2:
-r, --map-root-user
Run the program only after the current effective user and group IDs have been mapped to the superuser UID and GID in the newly created user namespace. This makes it possible to conveniently gain capabilities needed to manage various aspects of the newly created namespaces (such as configuring interfaces in the network namespace or mounting filesystems in the mount namespace) even when run unprivileged. As a mere convenience feature, it does not support more sophisticated use cases, such as mapping multiple ranges of UIDs and GIDs. This option implies --setgroups=deny.
So, on newer systems, you can run:
unshare -n -r ping 127.0.0.1
And this will yield the expected Network is unreachable
.
On Debian systems you might still get an Operation not permitted
error, then you have to enable unprivileged user namespaces first by running:
sudo sysctl -w kernel.unprivileged_userns_clone=1
Note: for a wider range of use cases, the more sophisticated bwrap --unshare-net
may be considered, as described briefly in a different answer.
You could use the setcap
utility to setup unshare.
sudo setcap cap_sys_admin+ep /usr/bin/unshare
After this you can use unshare -n ping 127.0.0.1
I can't explain it any further and I do not know if this is a good idea, but it works and whoami
does not show root
as user name.