unshare -n (updates)

September 5, 2015

As I noted in an update to a previous post, On Debian Jessie or other newer Linux distributions, unshare no longer drops root.

I’ve thrown together a kludge using sudo to drop permissions:

$ sudo unshare -n sudo -u pipeep -g pipeep sh -c 'sudo -K; echo spawned; ping google.com'

Where -u pipeep and -g pipeep represent the user and group to run the command as.

sudo -K is used to ensure the cached credentials are dropped before running the subsequent program. Otherwise, the potentially less-trusted subcommand could get passwordless root. If you want to run the command as a different user than the current user, you can drop sudo -K, eg:

$ sudo unshare -n sudo -u nobody -g nobody ping google.com

You can even turn this into a nice function for your .bashrc or .zshrc:

# use `unshare -n` as root, but dropping permissions once spawned
unshare-network() {
    sudo unshare -n sudo -u "$(whoami)" -g "$(id -g -n)" sh -c \
        "sudo -K && echo 'disconnected network, spawing subprocess...' && $@"

The views expressed on this site are my own and do not reflect those of my employer.