]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - share/examples/jails/jib
Adjust MAC allocation algo to support layering
[FreeBSD/FreeBSD.git] / share / examples / jails / jib
1 #!/bin/sh
2 #-
3 # Copyright (c) 2016 Devin Teske
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 # 1. Redistributions of source code must retain the above copyright
10 #    notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 #    notice, this list of conditions and the following disclaimer in the
13 #    documentation and/or other materials provided with the distribution.
14 #
15 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 # ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 # SUCH DAMAGE.
26 #
27 # $FreeBSD$
28 #
29 ############################################################ IDENT(1)
30 #
31 # $Title: if_bridge(4) management script for vnet jails $
32 #
33 ############################################################ INFORMATION
34 #
35 # Use this tool with jail.conf(5) (or rc.conf(5) ``legacy'' configuration) to
36 # manage `vnet' interfaces for jails. Designed to automate the creation of vnet
37 # interface(s) during jail `prestart' and destroy said interface(s) during jail
38 # `poststop'.
39 #
40 # In jail.conf(5) format:
41 #
42 # ### BEGIN EXCERPT ###
43 #
44 # xxx {
45 #       host.hostname = "xxx.yyy";
46 #       path = "/vm/xxx";
47
48 #       #
49 #       # NB: Below 2-lines required
50 #       # NB: The number of eNb_xxx interfaces should match the number of
51 #       #     arguments given to `jib addm xxx' in exec.prestart value.
52 #       #
53 #       vnet;
54 #       vnet.interface = "e0b_xxx e1b_xxx ...";
55
56 #       exec.clean;
57 #       exec.system_user = "root";
58 #       exec.jail_user = "root";
59
60 #       #
61 #       # NB: Below 2-lines required
62 #       # NB: The number of arguments after `jib addm xxx' should match
63 #       #     the number of eNb_xxx arguments in vnet.interface value.
64 #       #
65 #       exec.prestart += "jib addm xxx em0 em1 ...";
66 #       exec.poststop += "jib destroy xxx";
67
68 #       # Standard recipe
69 #       exec.start += "/bin/sh /etc/rc";
70 #       exec.stop = "/bin/sh /etc/rc.shutdown";
71 #       exec.consolelog = "/var/log/jail_xxx_console.log";
72 #       mount.devfs;
73 #
74 #       # Optional (default off)
75 #       #allow.mount;
76 #       #allow.set_hostname = 1;
77 #       #allow.sysvipc = 1;
78 #       #devfs_ruleset = "11"; # rule to unhide bpf for DHCP
79 # }
80 #
81 # ### END EXCERPT ###
82 #
83 # In rc.conf(5) ``legacy'' format (used when /etc/jail.conf does not exist):
84 #
85 # ### BEGIN EXCERPT ###
86 #
87 # jail_enable="YES"
88 # jail_list="xxx"
89 #
90 # #
91 # # Global presets for all jails
92 # #
93 # jail_devfs_enable="YES"       # mount devfs
94 #
95 # #
96 # # Global options (default off)
97 # #
98 # #jail_mount_enable="YES"              # mount /etc/fstab.{name}
99 # #jail_set_hostname_allow="YES"        # Allow hostname to change
100 # #jail_sysvipc_allow="YES"             # Allow SysV Interprocess Comm.
101
102 # # xxx
103 # jail_xxx_hostname="xxx.shxd.cx"               # hostname
104 # jail_xxx_rootdir="/vm/xxx"                    # root directory
105 # jail_xxx_vnet_interfaces="e0b_xxx e1bxxx ..." # vnet interface(s)
106 # jail_xxx_exec_prestart0="jib addm xxx em0 em1 ..."    # bridge interface(s)
107 # jail_xxx_exec_poststop0="jib destroy xxx"     # destroy interface(s)
108 # #jail_xxx_mount_enable="YES"                  # mount /etc/fstab.xxx
109 # #jail_xxx_devfs_ruleset="11"                  # rule to unhide bpf for DHCP
110 #
111 # ### END EXCERPT ###
112 #
113 # Note that the legacy rc.conf(5) format is converted to
114 # /var/run/jail.{name}.conf by /etc/rc.d/jail if jail.conf(5) is missing.
115 #
116 # ASIDE: dhclient(8) inside a vnet jail...
117 #
118 # To allow dhclient(8) to work inside a vnet jail, make sure the following
119 # appears in /etc/devfs.rules (which should be created if it doesn't exist):
120 #
121 #       [devfsrules_jail=11]
122 #       add include $devfsrules_hide_all
123 #       add include $devfsrules_unhide_basic
124 #       add include $devfsrules_unhide_login
125 #       add include $devfsrules_unhide_bpf
126 #
127 # And set ether devfs.ruleset="11" (jail.conf(5)) or
128 # jail_{name}_devfs_ruleset="11" (rc.conf(5)).
129 #
130 # NB: While this tool can't create every type of desirable topology, it should
131 # handle most setups, minus some which considered exotic or purpose-built.
132 #
133 ############################################################ GLOBALS
134
135 pgm="${0##*/}" # Program basename
136
137 #
138 # Global exit status
139 #
140 SUCCESS=0
141 FAILURE=1
142
143 ############################################################ FUNCTIONS
144
145 usage()
146 {
147         local action usage descr
148         exec >&2
149         echo "Usage: $pgm action [arguments]"
150         echo "Actions:"
151         for action in \
152                 addm            \
153                 show            \
154                 show1           \
155                 destroy         \
156         ; do
157                 eval usage=\"\$jib_${action}_usage\"
158                 [ "$usage" ] || continue
159                 eval descr=\"\$jib_${action}_descr\"
160                 printf "\t%s\n\t\t%s\n" "$usage" "$descr"
161         done
162         exit $FAILURE
163 }
164
165 action_usage()
166 {
167         local usage action="$1"
168         eval usage=\"\$jib_${action}_usage\"
169         echo "Usage: $pgm $usage" >&2
170         exit $FAILURE
171 }
172
173 mustberoot_to_continue()
174 {
175         if [ "$( id -u )" -ne 0 ]; then
176                 echo "Must run as root!" >&2
177                 exit $FAILURE
178         fi
179 }
180
181 jib_addm_usage="addm [-b BRIDGE_NAME] NAME interface0 [interface1 ...]"
182 jib_addm_descr="Creates e0b_NAME [e1b_NAME ...]"
183 jib_addm()
184 {
185         local OPTIND=1 OPTARG flag bridge=bridge
186         while getopts b: flag; do
187                 case "$flag" in
188                 b) bridge="${OPTARG:-bridge}" ;;
189                 *) action_usage addm # NOTREACHED
190                 esac
191         done
192         shift $(( $OPTIND - 1 ))
193
194         local name="$1"
195         [ "${name:-x}" = "${name#*[!0-9a-zA-Z_]}" -a $# -gt 1 ] ||
196                 action_usage addm # NOTREACHED
197         shift 1 # name
198
199         mustberoot_to_continue
200
201         local iface iface_devid eiface_devid_a eiface_devid_b
202         local new num quad i=0
203         for iface in $*; do
204
205                 # 1. Make sure the interface doesn't exist already
206                 ifconfig "e${i}a_$name" > /dev/null 2>&1 && continue
207
208                 # 2. Bring the interface up
209                 ifconfig $iface up || return
210
211                 # 3. Make sure the interface has been bridged
212                 if ! ifconfig "$iface$bridge" > /dev/null 2>&1; then
213                         new=$( ifconfig bridge create ) || return
214                         ifconfig $new addm $iface || return
215                         ifconfig $new name "$iface$bridge" || return
216                 fi
217
218                 # 4. Create a new interface to the bridge
219                 new=$( ifconfig epair create ) || return
220                 ifconfig "$iface$bridge" addm $new || return
221
222                 # 5. Rename the new interface
223                 ifconfig $new name "e${i}a_$name" || return
224                 ifconfig ${new%a}b name "e${i}b_$name" || return
225
226                 #
227                 # 6. Set the MAC address of the new interface using a sensible
228                 # algorithm to prevent conflicts on the network.
229                 #
230                 # The formula I'm using is ``SP:SS:SI:II:II:II'' where:
231                 # + S denotes 16 bits of sum(1) data, split because P (below).
232                 # + P denotes the special nibble whose value, if one of
233                 #   2, 6, A, or E (but usually 2) denotes a privately
234                 #   administered MAC address (while remaining routable).
235                 # + I denotes bits that are inherited from parent interface.
236                 #
237                 # The S bits are a CRC-16 checksum of NAME, allowing the jail
238                 # to change the epair(4) generation order without affecting the
239                 # MAC address. Meanwhile, if the jail NAME changes (e.g., it
240                 # was duplicated and given a new name with no other changes),
241                 # the underlying network interface changes, or the jail is
242                 # moved to another host, the MAC address will be recalculated
243                 # to a new, similarly unique value preventing conflict.
244                 #
245                 iface_devid=$( ifconfig $iface ether | awk '/ether/,$0=$2' )
246                 eiface_devid_a=${iface_devid#??:??:?}
247                 eiface_devid_b=${iface_devid#??:??:?}
248                 num=$( set -- `echo -n $name | sum` && echo $1 )
249                 quad=$(( $num & 15 ))
250                 case "$quad" in
251                 10) quad=a ;; 11) quad=b ;; 12) quad=c ;;
252                 13) quad=d ;; 14) quad=e ;; 15) quad=f ;;
253                 esac
254                 eiface_devid_a=:$quad$eiface_devid_a
255                 eiface_devid_b=:$quad$eiface_devid_b
256                 num=$(( $num >> 4 ))
257                 quad=$(( $num & 15 ))
258                 case "$quad" in
259                 10) quad=a ;; 11) quad=b ;; 12) quad=c ;;
260                 13) quad=d ;; 14) quad=e ;; 15) quad=f ;;
261                 esac
262                 eiface_devid_a=$quad$eiface_devid_a
263                 eiface_devid_b=$quad$eiface_devid_b
264                 num=$(( $num >> 4 ))
265                 quad=$(( $num & 15 ))
266                 case "$quad" in
267                 10) quad=a ;; 11) quad=b ;; 12) quad=c ;;
268                 13) quad=d ;; 14) quad=e ;; 15) quad=f ;;
269                 esac
270                 case "$iface_devid" in
271                 ?2:*|?6:*)
272                         eiface_devid_a=a:$quad$eiface_devid_a
273                         eiface_devid_b=e:$quad$eiface_devid_b
274                         ;;
275                 *)
276                         eiface_devid_a=2:$quad$eiface_devid_a
277                         eiface_devid_b=6:$quad$eiface_devid_b
278                 esac
279                 num=$(( $num >> 4 ))
280                 quad=$(( $num & 15 ))
281                 case "$quad" in
282                 10) quad=a ;; 11) quad=b ;; 12) quad=c ;;
283                 13) quad=d ;; 14) quad=e ;; 15) quad=f ;;
284                 esac
285                 eiface_devid_a=$quad$eiface_devid_a
286                 eiface_devid_b=$quad$eiface_devid_b
287                 ifconfig "e${i}a_$name" ether $eiface_devid_a > /dev/null 2>&1
288                 ifconfig "e${i}b_$name" ether $eiface_devid_b > /dev/null 2>&1
289
290                 i=$(( $i + 1 )) # on to next e{i}b_name
291         done # for iface
292 }
293
294 jib_show_usage="show"
295 jib_show_descr="List possible NAME values for \`show NAME'"
296 jib_show1_usage="show NAME"
297 jib_show1_descr="Lists e0b_NAME [e1b_NAME ...]"
298 jib_show2_usage="show [NAME]"
299 jib_show()
300 {
301         local OPTIND=1 OPTARG flag
302         while getopts "" flag; do
303                 case "$flag" in
304                 *) action_usage show2 # NOTREACHED
305                 esac
306         done
307         shift $(( $OPTIND - 1 ))
308         if [ $# -eq 0 ]; then
309                 ifconfig | awk '
310                         /^[^:[:space:]]+:/ {
311                                 iface = $1
312                                 sub(/:.*/, "", iface)
313                                 next
314                         }
315                         $1 == "groups:" {
316                                 for (n = split($0, group); n > 1; n--) {
317                                         if (group[n] != "bridge") continue
318                                         print iface
319                                         next
320                                 }
321                         }' |
322                         xargs -rn1 ifconfig |
323                         awk '$1 == "member:" &&
324                                 sub(/^e[[:digit:]]+a_/, "", $2), $0 = $2' |
325                         sort -u
326                 return
327         fi
328         ifconfig | awk -v name="$1" '
329                 match($0, /^e[[:digit:]]+a_/) && sub(/:.*/, "") &&
330                         substr($1, RSTART + RLENGTH) == name
331         ' | sort
332 }
333
334 jib_destroy_usage="destroy NAME"
335 jib_destroy_descr="Destroy e0b_NAME [e1b_NAME ...]"
336 jib_destroy()
337 {
338         local OPTIND=1 OPTARG flag
339         while getopts "" flag; do
340                 case "$flag" in
341                 *) action_usage destroy # NOTREACHED
342                 esac
343         done
344         shift $(( $OPTIND -1 ))
345         local name="$1"
346         [ "${name:-x}" = "${name#*[!0-9a-zA-Z_]}" -a $# -eq 1 ] ||
347                 action_usage destroy # NOTREACHED
348         mustberoot_to_continue
349         jib_show "$name" | xargs -rn1 -I eiface ifconfig eiface destroy
350 }
351
352 ############################################################ MAIN
353
354 #
355 # Command-line arguments
356 #
357 action="$1"
358 [ "$action" ] || usage # NOTREACHED
359
360 #
361 # Validate action argument
362 #
363 if [ "$BASH_VERSION" ]; then
364         type="$( type -t "jib_$action" )" || usage # NOTREACHED
365 else
366         type="$( type "jib_$action" 2> /dev/null )" || usage # NOTREACHED
367 fi
368 case "$type" in
369 *function)
370         shift 1 # action
371         eval "jib_$action" \"\$@\"
372         ;;
373 *) usage # NOTREACHED
374 esac
375
376 ################################################################################
377 # END
378 ################################################################################