Bind programs to a specific network interface attachment
mouse 2783 · person cloud · link
Last update
2022-10-28
2022
10-28
«eg: encapsualte vpn in a netns»
1
2
3
4
5
6
7
8
9
10
11
12
13
# create a new network namespace:
ip netns add test_ns

# exclusively assign an interface to the namespace
ip link set eth0 netns test_ns

# run commans inside the namespace:
ip netns exec test_ns    ip link set eth0 up  # bring up interface
ip netns exec test_ns    dhclient eth0        # assign IP via dhcp

# test network in the namespace
ip netns exec test_ns    ping www.google.com
ip netns exec test_ns    firefox

Tutorial su adkubuntu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# enable forwarding
sysctl -w net.ipv4.ip_forward=1

# create the network namespace
ip netns add chrome

# create the virtual nic and it's peer
ip link add chrome type veth peer name chrome-peer

# assign the peer to the network namespace
ip link set chrome-peer netns chrome

# assign an ip address
ip addr add 192.0.2.1/24 dev chrome

# bring up interface
ip link set chrome up

# similar network setup for network namespace
ip netns exec chrome ip link set lo up
ip netns exec chrome ip addr add 192.0.2.2/24 dev chrome-peer
ip netns exec chrome ip route add default via 192.0.2.1
ip netns exec chrome ip link set chrome-peer up

# allow forwarding and add enable NAT
iptables -I FORWARD -s 192.0.2.0/24 -j ACCEPT
iptables -t nat -I POSTROUTING -s 192.0.2.0/24 -o tun1 -j MASQUERADE

# pop a shell in the namespace
ip netns exec chrome bash

# check that you're in the namespace
ip netns identify

# run the browser as your local user
runuser -u Barry google-chrome

Source: Stackexchange, ip netns manpage

See also: SuperUser, LD_PRELOAD fix via bind.c