This post is a cheatsheet for myself in case I need to fuck around with network namespaces again.
NB: most of the commands should be ran as root.
Create a new netns
1
2
3
4
|
$ ip netns add testns
# Check it works
$ ip netns ls
testns
|
Exec a command inside a netns
1
2
3
|
$ ip netns exec testns ip link show
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
|
Connect the namespace from the outside
Choose what we want to make as a network setup
We want the following:
- The netns interface will have the
10.69.69.2/24
address
- It should be able to talk to the outside
- It will do so via a bridge on the host with the
10.69.69.1/24
address
- Traffic to the outside will me SNATed
Setup the outside of the network namespace
First let’s create the network interfaces we need, we want to have a bridge and a veth pair.
1
2
3
|
$ ip link add br-netns type bridge
# Create a veth pair with one of the interfaces in out netns
$ ip link add veth0 type veth peer name veth1 netns testns
|
Now set veth0’s master as the bridge
1
|
$ ip link set master br-netns dev veth0
|
Setup the bridge address
1
|
$ ip address add 10.69.69.1/24 dev br-netns
|
Make the bridge and veth up
1
2
|
$ ip link set up dev br-netns
$ ip link set up dev veth0
|
Finally setup iptables
1
2
3
|
$ iptables -I FORWARD -i br-netns -o enx0050b6f2bc54 -j ACCEPT
$ iptables -I FORWARD -o br-netns -i enx0050b6f2bc54 -j ACCEPT
$ iptables -t nat -I POSTROUTING -s 10.69.69.0/24 -j MASQUERADE
|
Setup the inside of the network namespace
Let us enter the namespace
1
|
$ ip netns exec testns bash
|
Configure the interface’s address and turn it on
1
2
|
$ ip address add 10.69.69.2/24 dev veth1
$ ip link set up dev veth1
|
Set the default route
1
|
$ ip route add default via 10.69.69.1
|
Check it works
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$ ping 8.8.8.8 -c 10
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=115 time=14.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=115 time=12.9 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=115 time=10.0 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=115 time=13.1 ms
64 bytes from 8.8.8.8: icmp_seq=5 ttl=115 time=10.2 ms
64 bytes from 8.8.8.8: icmp_seq=6 ttl=115 time=10.3 ms
64 bytes from 8.8.8.8: icmp_seq=7 ttl=115 time=27.4 ms
64 bytes from 8.8.8.8: icmp_seq=8 ttl=115 time=9.77 ms
64 bytes from 8.8.8.8: icmp_seq=9 ttl=115 time=11.2 ms
64 bytes from 8.8.8.8: icmp_seq=10 ttl=115 time=11.2 ms
--- 8.8.8.8 ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 9012ms
rtt min/avg/max/mdev = 9.774/13.055/27.416/5.009 ms
|
Tada!