A blog on Computer Science, Security, Programming, and more...

HeapSpray Blog » Linux » View Post

18
May
2014

Prevent Program From Accessing The Network in Linux

Written by Matt

I've just recently found out Linux supports namespaces on recent kernels, through the program unshare. As the name implies, it unshares namespaces from the parent and allows you to run programs with restricted access.

The program can simply be used as follows:

# unshare -n -- ping 127.0.0.1
connect: Network is unreachable

The '--' signifies that all arguments beyond that point are no longer arguments to 'unshare' but to the program you want to execute and its arguments. As you can see, ping fails to reach even localhost, because this creates a new network namespace (option -n in unshare) that has no devices and no networking setup - it's totally blank.

One problem with this is that you need to run the command itself as root, because to run 'unshare' you need CAP_SYS_ADMIN capabilities, which is basically equivalent to root, but you may not want to run the restricted process as root and certainly not with CAP_SYS_ADMIN capabilities, for obvious reasons (as it will just be able to choose another namespace itself if it wants to). Therefore, you can run the command as follows:

$ su -c 'unshare -n -- su - YOUR_USER -c "ping 127.0.0.1"'

A little obtuse, but this uses 'su' to run 'unshare' as root, then uses 'su' within unshare's created namespace to demote the privileges down to YOUR_USER, and then runs the command "ping 127.0.0.1" as YOUR_USER. It can be turned into a script for convenience:

#!/bin/bash

if [ "$#" -ne 2 ]; then
    echo "Usage: nonetwork.sh <user> <command>"
    exit
fi

su -c "unshare -n -- su - $1 -c \"$2\""

Save this as nonetwork.sh and place it in /usr/local/bin, and then you can run it as follows:

$ nonetwork.sh USER "ping 127.0.0.1"
Password: [Enter root password]
connect: Network is unreachable

Do note that you need a relatively recent kernel, and your kernel needs to be compiled with CONFIG_NET_NS=y -- from a little research it seems "full" support for these operations was added after kernel version 3.4.x, so it might not work on server distributions like CentOS which still use the 2.6.x series kernel.

Glad to see Linux is getting namespace support. I wonder when it happened?

  • Name and Email fields are optional
  • Your email will not be public, only the administrator can see it
  • You are rate limited to one comment for every 10 minutes