diff --git a/configs/netns b/configs/netns index a9ec1a9..992ac48 100644 --- a/configs/netns +++ b/configs/netns @@ -23,3 +23,11 @@ # If you need static MAC #MACADDR=00:11:22:33:44:55 + +#NAT Accepting traffic back from the NetNS +#By default, if the root NS contact a service +#in the created NS, it won't get a response. +# +#Setting this setting to 1 add a iptable rule +#to accept returning traffic +#NAT_ACCEPT_TRAFFIC=1 diff --git a/scripts/netnsinit b/scripts/netnsinit index 15b5d7c..47b04b9 100755 --- a/scripts/netnsinit +++ b/scripts/netnsinit @@ -4,7 +4,7 @@ set -e display_usage() { echo "Auto configuration for systemd-named-netns." - echo -e "\nUsage:\n\t$0 network-type ns-name \n" + echo -e "\nUsage:\n\t$0 network-type ns-name [optional params]\n" echo "Note: you may need root privileges for this." } @@ -27,19 +27,39 @@ autoconfigure_tunnel() { } autoconfigure_nat() { + # add default route if gateway undefined if [ -z "${GATEWAY}" -a -n "${IPADDR_OUTSIDE}" ]; then /bin/ip route add default via ${IPADDR_OUTSIDE%%/*} fi + return 0 # additional precation against "set -e" in case of future mods of this function } +autoconfigure_nat-access() { + + if [ "${NAT_ACCEPT_TRAFFIC}" != "1" ]; then + return 0 + fi + if [ "$3" == "up" ]; then + #Accept related traffic + iptables -I INPUT -i ${DEVNAME_OUTSIDE} -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + + elif [ "$3" == "down" ]; then + iptables -D INPUT -i ${DEVNAME_OUTSIDE} -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + fi + + + return 0 # additional precation against "set -e" in case of future mods of this function +} autoconfigure() { local NSTYPE=$1 local NSNAME=$2 echo "Starting autoconfigure for $NSTYPE ${NSNAME}" DEVNAME_INSIDE=vn-${NSNAME}1 + DEVNAME_OUTSIDE=vn-${NSNAME}0 + source /etc/default/netns ! source "/etc/default/netns-${NSNAME}" @@ -60,7 +80,7 @@ case "$1" in display_usage exit 0 ;; - "tunnel"|"bridge"|"nat") + "tunnel"|"bridge"|"nat"|"nat-access") autoconfigure "$@" exit 0 ;; diff --git a/services/netns-nat@.service b/services/netns-nat@.service index a3ffff3..536eff5 100644 --- a/services/netns-nat@.service +++ b/services/netns-nat@.service @@ -22,9 +22,11 @@ EnvironmentFile=-/etc/default/netns-%I ExecStart=/usr/bin/env iptables -t nat -A POSTROUTING -s ${IPADDR_OUTSIDE} -j MASQUERADE ExecStart=/usr/bin/env iptables -A FORWARD -i ${DEVNAME_OUTSIDE} -j ACCEPT ExecStart=/usr/bin/env iptables -A FORWARD -o ${DEVNAME_OUTSIDE} -j ACCEPT +ExecStart=/usr/bin/env netnsinit nat-access %I up ExecStart=/usr/bin/env ip netns exec %I /usr/bin/env netnsinit nat %I ExecStop=/usr/bin/env iptables -D FORWARD -o ${DEVNAME_OUTSIDE} -j ACCEPT ExecStop=/usr/bin/env iptables -D FORWARD -i ${DEVNAME_OUTSIDE} -j ACCEPT ExecStop=/usr/bin/env iptables -t nat -D POSTROUTING -s ${IPADDR_OUTSIDE} -j MASQUERADE +ExecStop=/usr/bin/env netnsinit nat-access %I down