Linux namespaces

June 14, 2020 - Reading time: 3 minutes

Linux kernel feature. namespace limits the ability of a process to see a system resource. (c groups limit what you can acess) There are six (6) linux namespaces: User / IPC / UTS / Mount / Network / PID The namespaces are per process and can be listed in /proc/

root@twickenham:/home/# ps aux | grep "[s]shd -D"
root       4514  0.0  0.0  15852  7272 ?        Ss   20:58   0:00 /usr/sbin/sshd -D
root@twickenham:/home/# ll /proc/4514/ns/
total 0
lrwxrwxrwx 1 root root 0 Jan 19 21:37 cgroup -> 'cgroup:[4026531835]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 ipc -> 'ipc:[4026531839]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 mnt -> 'mnt:[4026531840]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 net -> 'net:[4026531992]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 pid -> 'pid:[4026531836]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 pid_for_children -> 'pid:[4026531836]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 user -> 'user:[4026531837]'
lrwxrwxrwx 1 root root 0 Jan 19 21:37 uts -> 'uts:[4026531838]'

All the processes pointing to the same inode are considered to be in the same namespace.

  • User: introduced in kernel 3.8 it's a security feature where each namespace can be given its own UID/GUID
  • IPC: inter process comm. a different queue is created per namespace
  • UTS: unix timesharing space. to isolate hostnames and domain names.
  • mount: filesystem mount points.. similar to creating a different chroot environment.
  • PID: isolation of PID. a new namespace creates a new process tree with root PID 1.
  • network: allows each container to have its own routes.. etc

Adding a new network namespace:

root@twickenham:/home/# ip netns add sample1
root@twickenham:/home/# ip netns list
sample1

Check iptables for my default namespace:

root@twickenham:/home/# iptables -L DOCKER-ISOLATION-STAGE-2
Chain DOCKER-ISOLATION-STAGE-2 (3 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Now.. if I try to list the same chain on my newly created namespace called sample1, I get:

root@twickenham:/home/# ip netns exec sample1   iptables -L DOCKER-ISOLATION-STAGE-2
iptables: No chain/target/match by that name.

The change is more apparent if I start a bash process instead of simply running iptables:

root@twickenham:/home/# ip netns exec sample1 bash
root@twickenham:/home/#  echo $BASHPID
4840

For this new bash, the net namespace is:

root@twickenham:/home/# ll /proc/4840/ns/net
lrwxrwxrwx 1 root root 0 Jan 19 22:19 /proc/4840/ns/net -> 'net:[4026532685]'

and for a different bash:

root@twickenham:/home/# ll /proc/${BASHPID}/ns/net
lrwxrwxrwx 1 root root 0 Jan 19 22:20 /proc/4834/ns/net -> 'net:[4026531992]'