31f1b528c80bdab325c17631adf5c6245c745895
[newns] / newns
1 #!/bin/bash
2 # Copyright (C) 2017 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16
17 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
18
19 if [[ ! $ERRHANDLE_PATH ]]; then
20 ERRHANDLE_PATH=$(readlink -f "${BASH_SOURCE}")
21 ERRHANDLE_PATH=$(readlink -f ${ERRHANDLE_PATH%/*}/../errhandle)
22 fi
23 err_sourced=true
24 for p in $ERRHANDLE_PATH/{errcatch-function,bash-trace-function}; do
25 if [[ -e $p ]]; then
26 source $p
27 else
28 err_sourced=false
29 fi
30 done
31 if $err_sourced; then
32 errcatch
33 else
34 set -eE -o pipefail
35 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
36 fi
37
38 usage() {
39 cat <<EOF
40 usage: ${0##*/} [OPTS] start|stop NETNS_NAME
41 Setup new or systemd created network namespace with nat and mount namespace
42
43 -c, --create Create network namespace. For running outside systemd private net.
44 -h, --help Show this help and exit.
45
46 From within systemd network namespace, nat it to the outside. If given
47 -c, or if in the default network namespace, create a named network
48 namepace natted to the current netns.
49
50 Uses /24 network, finding the first locally unused one starting at
51 10.173.0.
52
53 Also create a named mount namespace under /root/mount_namespaces, so we
54 can alter some system config for this namespace. Subsequent systemd
55 command lines would be prefixed with:
56
57 /usr/bin/nsenter --mount=/root/mount_namespaces/NETNS_NAME
58
59 Note, this means that they can't run as unpriveledged users, but once
60 systemd 233 comes out, it will have a bind mount option from within unit
61 files, so the mount namespace won't be needed for most use cases, and I
62 will update the script to that the mount namespace not created unless a
63 flag is passed in. Patch welcome to add that flag before then.
64
65 A recommmended dependency of this script is my other repo named "errhandle",
66 which prints stack trace on error, and calls a cleanup function:
67 https://iankelling.org/git/?p=errhandle, set ERRHANDLE_PATH, or put it
68 in a directory adjacent to the absolute, resolved directory this file is
69 in.
70
71 Background: "ip netns new ..." also does a mount namespace, then bind
72 mounts each file/dir in /etc/netns/NETNS_NAME to /etc/NETNS_NAME. Note,
73 for openvpn having it's own resolv.conf by using it's user script which
74 calls resolvconf, this doesn't help much. What we actually want to do is
75 copy /run/resolvconf somehwere then bind mount it on top of
76 /run/resolvconf.
77
78 Please email me if you have a patches, bugs, feedback, or republish this
79 somewhere else: Ian Kelling <ian@iankelling.org>.
80 EOF
81 exit ${1:-0}
82 }
83
84
85 ## begin arg parsing ##
86 create=false
87 temp=$(getopt -l help,create hc "$@") || usage 1
88 eval set -- "$temp"
89 while true; do
90 case $1 in
91 -c|--create) create=true; shift ;;
92 -h|--help) usage ;;
93 --) shift; break ;;
94 *) echo "$0: Internal error!" ; exit 1 ;;
95 esac
96 done
97 if (( $# != 2 )); then
98 usage 1
99 fi
100
101 action=$1
102 nn=$2 # network namespace / namespace name
103 ## end arg parsing ##
104
105 ## begin sanity checking ##
106
107 install_error=false
108 if ! type -p ip &>/dev/null; then
109 echo "please install the iproute2 package"
110 install_error=true
111 fi
112 if ! type -p iptables &>/dev/null; then
113 echo "please install the iptables package"
114 install_error=true
115 fi
116 if $install_error; then
117 exit 1
118 fi
119
120 ## end sanity checking ##
121
122
123 v0=veth0-$nn
124 v1=veth1-$nn
125 ip_base=10.173
126
127 if ! $create && [[ $(readlink /proc/self/ns/net) == "$(readlink /proc/1/ns/net)" ]]; then
128 create=true
129 fi
130
131 target=/run/netns/default
132 if [[ ! -e $target && ! -L $target ]]; then
133 mkdir -p /run/netns
134 # make the default network namespace be named
135 ln -s /proc/1/ns/net $target
136 fi
137
138
139 ipd() { ip -n default "$@"; }
140 if $create; then
141 ipnn() { ip -n $nn "$@"; }
142 else
143 # we are already in the network namespace and it's unnamed.
144 ipnn() { ip "$@"; }
145 fi
146 dexec() { ip netns exec default "$@"; }
147
148
149 # head -n1 is defensive. Not sure if there is some weird feature
150 # for 2 routes to be 0/0.
151 gateway_if=$(ipd route list exact 0/0 | head -n1| sed -r 's/.*\s(\S+)\s*$/\1/')
152 nat() { dexec iptables -t nat $1 POSTROUTING -o $gateway_if -j MASQUERADE \
153 -m comment --comment "systemd network namespace nat"; }
154
155 find_network() {
156 found=false
157 existing=false
158 ips="$(ipd addr show | awk '$1 == "inet" {print $2}')"
159 for ((i=0; i <= 254; i++)); do
160 network=$ip_base.$i
161 if printf "%s\n" "$ips" | grep "^${network//./\\.}" >/dev/null; then
162 existing=true
163 else
164 found=true
165 break
166 fi
167 done
168 }
169
170 start() {
171
172 find_network
173 if ! $found; then
174 echo "$0: error: no open network found"
175 exit 1
176 fi
177
178 mkdir -p /root/mount_namespaces
179 if ! mountpoint /root/mount_namespaces >/dev/null; then
180 mount --bind /root/mount_namespaces /root/mount_namespaces
181 mount --make-private /root/mount_namespaces
182 fi
183 if [[ ! -e /root/mount_namespaces/$nn ]]; then
184 touch /root/mount_namespaces/$nn
185 fi
186 if ! mountpoint /root/mount_namespaces/$nn >/dev/null; then
187 unshare --mount=/root/mount_namespaces/$nn
188 fi
189
190
191 if $create; then
192 ip netns add $nn
193 ip -n $nn link set dev lo up
194 fi
195
196
197
198 echo 1 | dexec dd of=/proc/sys/net/ipv4/ip_forward 2>/dev/null
199
200 _errcatch_cleanup=stop
201 ipnn link add $v0 type veth peer name $v1
202 ipnn link set $v0 netns default
203 ipd addr add $network.1/24 dev $v0
204 ipd link set $v0 up
205 nat -C &>/dev/null || nat -A
206 ipnn addr add $network.2/24 dev $v1
207 ipnn link set $v1 up
208 ipnn route add default via $network.1
209
210 }
211
212 stop() {
213 if ipd link list $v0 &>/dev/null; then
214 # this also deletes $v1 and the route we added.
215 ipd link del $v0
216 fi
217 find_network
218 if ! $existing; then
219 if nat -C &>/dev/null; then nat -D; fi
220 fi
221 if $create; then
222 ip netns del $nn
223 fi
224 if mountpoint /root/mount_namespaces/$nn >/dev/null; then
225 umount /root/mount_namespaces/$nn
226 fi
227 }
228
229 case $action in
230 start|stop)
231 $action
232 ;;
233 *)
234 echo "$0: error: unsupported action"
235 exit 1
236 ;;
237 esac