7

I want to run a program without any internet access, e.g.

unshare -n ping 127.0.0.1.

As an unprivileged user, it returns Operation not permitted, as a privileged user, it returns the desired Network is unreachable.

Is there any way to make it work for the unprivileged user, as well?

6

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.

3

Make it setuid (assuming it's already owned by root):

sudo chmod u+s "`which unshare`"

From unshare(1):

NOTES The unshare command drops potential privileges before executing the target program. This allows to setuid unshare.

  • 2
    alternatively: run it in a user namespace in which the user has been granted root authority. – mikeserv Jan 1 '16 at 17:28
  • 2
    There's a patch in newer versions of unshare that removes dropping privs, so beware if you're upgrading. – Mrten Feb 6 '16 at 22:48
  • In the version of unshare that’s installed on my system (2.26.2), this works as an unprivileged user: unshare -n -r ping 127.0.0.1. (Note the addition of -r, which, as @mikeserv had suggested, tweaks the user namespace to run the process as root inside it.) – Amir Jun 11 '17 at 12:38
  • Sounds like putting the key under the doormat and putting a sign on the door showing a key icon and a downwards pointing arrow... – TheDiveO Jul 3 '18 at 17:00
  • @TheDiveO No. Unshare doesn't give you privileges. It allows you to restrict yourself. It might as well be setuid root by default but it probably isn't because of stupid distro policies. There's no security harm in making it setuid root especially since it has a pretty simple source code that lets you check there's no security holes in it. – PSkocik Jul 3 '18 at 21:10
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.