Skip to content

Instantly share code, notes, and snippets.

@Pandiora
Forked from dagli/ns-create.sh
Last active December 12, 2018 04:50
Show Gist options
  • Save Pandiora/bafb20d72d5ad3bf1098d89f78723ba9 to your computer and use it in GitHub Desktop.
Save Pandiora/bafb20d72d5ad3bf1098d89f78723ba9 to your computer and use it in GitHub Desktop.
Setup a network namespace with Internet access
#!/usr/bin/env bash
set -x
NS="e1ns"
ETH="eth0"
VETH="veth0"
VPEER="veth1"
VETH_ADDR="10.200.1.1"
VPEER_ADDR="10.200.1.2"
SRC_ADDR="85.xx.xx.xx"
if [[ $EUID -ne 0 ]]; then
echo "You must be root to run this script"
exit 1
fi
# Remove namespace if it exists.
ip netns del $NS &>/dev/null
# Create namespace
ip netns add $NS
# Create veth link.
ip link add ${VETH} type veth peer name ${VPEER}
# Add peer-1 to NS.
ip link set ${VPEER} netns $NS
# Setup IP address of ${VETH}.
ip addr add ${VETH_ADDR}/24 dev ${VETH}
ip link set ${VETH} up
# Setup IP ${VPEER}.
ip netns exec $NS ip addr add ${VPEER_ADDR}/24 dev ${VPEER}
ip netns exec $NS ip link set ${VPEER} up
ip netns exec $NS ip link set lo up
ip netns exec $NS ip route add default via ${VETH_ADDR}
# Enable IP-forwarding.
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush forward rules.
iptables -P FORWARD DROP
iptables -F FORWARD
# Flush nat rules.
iptables -t nat -F
# SNAT to second IP-Address
iptables -t nat -A POSTROUTING -s ${VPEER_ADDR}/24 -o ${ETH} -j SNAT --to-source ${SRC_ADDR}
iptables -A FORWARD -i ${ETH} -o ${VETH} -j ACCEPT
iptables -A FORWARD -o ${ETH} -i ${VETH} -j ACCEPT
# Get into namespace
#ip netns exec ${NS} /bin/bash --rcfile <(echo "PS1=\"${NS}> \"")
mkdir -p /etc/netns/${NS}/
echo 'nameserver 1.1.1.1' > /etc/netns/${NS}/resolv.conf
# create default netns to go back
ln -s /proc/1/ns/net /var/run/netns/default
@Pandiora
Copy link
Author

Pandiora commented Dec 12, 2018

In comparison to other forks this script isn't used to bypass vpn locally for some services. One can use this virtual adapter to start piping programs through IP-Address defined by SRC_ADDR with ip netns exec e1ns COMMAND.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment