xref: /freebsd/share/examples/jails/jib (revision 7899f917b1c0ea178f1d2be0cfb452086d079d23)
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#
28############################################################ IDENT(1)
29#
30# $Title: if_bridge(4) management script for vnet jails $
31#
32############################################################ INFORMATION
33#
34# Use this tool with jail.conf(5) (or rc.conf(5) ``legacy'' configuration) to
35# manage `vnet' interfaces for jails. Designed to automate the creation of vnet
36# interface(s) during jail `prestart' and destroy said interface(s) during jail
37# `poststop'.
38#
39# In jail.conf(5) format:
40#
41# ### BEGIN EXCERPT ###
42#
43# xxx {
44# 	host.hostname = "xxx.yyy";
45# 	path = "/vm/xxx";
46#
47# 	#
48# 	# NB: Below 2-lines required
49# 	# NB: The number of eNb_xxx interfaces should match the number of
50# 	#     arguments given to `jib addm xxx' in exec.prestart value.
51# 	#
52# 	vnet;
53# 	vnet.interface = e0b_xxx, e1b_xxx, ...;
54#
55# 	exec.clean;
56# 	exec.system_user = "root";
57# 	exec.jail_user = "root";
58#
59# 	#
60# 	# NB: Below 2-lines required
61# 	# NB: The number of arguments after `jib addm xxx' should match
62# 	#     the number of eNb_xxx arguments in vnet.interface value.
63# 	#
64# 	exec.prestart += "jib addm xxx em0 em1 ...";
65# 	exec.poststop += "jib destroy xxx";
66#
67# 	# Standard recipe
68# 	exec.start += "/bin/sh /etc/rc";
69# 	exec.stop = "/bin/sh /etc/rc.shutdown jail";
70# 	exec.consolelog = "/var/log/jail_xxx_console.log";
71# 	mount.devfs;
72#
73# 	# Optional (default off)
74# 	#allow.mount;
75# 	#allow.set_hostname = 1;
76# 	#allow.sysvipc = 1;
77# 	#devfs_ruleset = "11"; # rule to unhide bpf for DHCP
78# }
79#
80# ### END EXCERPT ###
81#
82# In rc.conf(5) ``legacy'' format (used when /etc/jail.conf does not exist):
83#
84# ### BEGIN EXCERPT ###
85#
86# jail_enable="YES"
87# jail_list="xxx"
88#
89# #
90# # Global presets for all jails
91# #
92# jail_devfs_enable="YES"	# mount devfs
93#
94# #
95# # Global options (default off)
96# #
97# #jail_mount_enable="YES"		# mount /etc/fstab.{name}
98# #jail_set_hostname_allow="YES"	# Allow hostname to change
99# #jail_sysvipc_allow="YES"		# Allow SysV Interprocess Comm.
100#
101# # xxx
102# jail_xxx_hostname="xxx.shxd.cx"		# hostname
103# jail_xxx_rootdir="/vm/xxx"			# root directory
104# jail_xxx_vnet_interfaces="e0b_xxx e1bxxx ..."	# vnet interface(s)
105# jail_xxx_exec_prestart0="jib addm xxx em0 em1 ..."	# bridge interface(s)
106# jail_xxx_exec_poststop0="jib destroy xxx"	# destroy interface(s)
107# #jail_xxx_mount_enable="YES"			# mount /etc/fstab.xxx
108# #jail_xxx_devfs_ruleset="11"			# rule to unhide bpf for DHCP
109#
110# ### END EXCERPT ###
111#
112# Note that the legacy rc.conf(5) format is converted to
113# /var/run/jail.{name}.conf by /etc/rc.d/jail if jail.conf(5) is missing.
114#
115# ASIDE: dhclient(8) inside a vnet jail...
116#
117# To allow dhclient(8) to work inside a vnet jail, make sure the following
118# appears in /etc/devfs.rules (which should be created if it doesn't exist):
119#
120# 	[devfsrules_jail=11]
121# 	add include $devfsrules_hide_all
122# 	add include $devfsrules_unhide_basic
123# 	add include $devfsrules_unhide_login
124# 	add path 'bpf*' unhide
125#
126# And set ether devfs.ruleset="11" (jail.conf(5)) or
127# jail_{name}_devfs_ruleset="11" (rc.conf(5)).
128#
129# NB: While this tool can't create every type of desirable topology, it should
130# handle most setups, minus some which considered exotic or purpose-built.
131#
132############################################################ GLOBALS
133
134pgm="${0##*/}" # Program basename
135
136#
137# Global exit status
138#
139SUCCESS=0
140FAILURE=1
141
142############################################################ FUNCTIONS
143
144usage()
145{
146	local action usage descr
147	exec >&2
148	echo "Usage: $pgm action [arguments]"
149	echo "Actions:"
150	for action in \
151		addm		\
152		show		\
153		show1		\
154		destroy		\
155	; do
156		eval usage=\"\$jib_${action}_usage\"
157		[ "$usage" ] || continue
158		eval descr=\"\$jib_${action}_descr\"
159		printf "\t%s\n\t\t%s\n" "$usage" "$descr"
160	done
161	exit $FAILURE
162}
163
164action_usage()
165{
166	local usage descr action="$1"
167	eval usage=\"\$jib_${action}_usage\"
168	echo "Usage: $pgm $usage" >&2
169	eval descr=\"\$jib_${action}_descr\"
170	printf "\t%s\n" "$descr"
171	exit $FAILURE
172}
173
174derive_mac()
175{
176	local OPTIND=1 OPTARG __flag
177	local __mac_num= __make_pair=
178	while getopts 2n: __flag; do
179		case "$__flag" in
180		2) __make_pair=1 ;;
181		n) __mac_num=${OPTARG%%[^0-9]*} ;;
182		esac
183	done
184	shift $(( $OPTIND - 1 ))
185
186	if [ ! "$__mac_num" ]; then
187		eval __mac_num=\${_${iface}_num:--1}
188		__mac_num=$(( $__mac_num + 1 ))
189		eval _${iface}_num=\$__mac_num
190	fi
191
192	local __iface="$1" __name="$2" __var_to_set="$3" __var_to_set_b="$4"
193	local __iface_devid __new_devid __num __new_devid_b
194	#
195	# Calculate MAC address derived from given iface.
196	#
197	# The formula I'm using is ``NP:SS:SS:II:II:II'' where:
198	# + N denotes 4 bits used as a counter to support branching
199	#   each parent interface up to 15 times under the same jail
200	#   name (see S below).
201	# + P denotes the special nibble whose value, if one of
202	#   2, 6, A, or E (but usually 2) denotes a privately
203	#   administered MAC address (while remaining routable).
204	# + S denotes 16 bits, the sum(1) value of the jail name.
205	# + I denotes bits that are inherited from parent interface.
206	#
207	# The S bits are a CRC-16 checksum of NAME, allowing the jail
208	# to change link numbers in ng_bridge(4) without affecting the
209	# MAC address. Meanwhile, if...
210	#   + the jail NAME changes (e.g., it was duplicated and given
211	#     a new name with no other changes)
212	#   + the underlying network interface changes
213	#   + the jail is moved to another host
214	# the MAC address will be recalculated to a new, similarly
215	# unique value preventing conflict.
216	#
217	__iface_devid=$( ifconfig $__iface ether | awk '/ether/,$0=$2' )
218	# ??:??:??:II:II:II
219	__new_devid=${__iface_devid#??:??:??} # => :II:II:II
220	# => :SS:SS:II:II:II
221	__num=$( set -- `echo -n "$__name" | sum` && echo $1 )
222	__new_devid=$( printf :%02x:%02x \
223		$(( $__num >> 8 & 255 )) $(( $__num & 255 )) )$__new_devid
224	# => P:SS:SS:II:II:II
225	case "$__iface_devid" in
226	   ?2:*) __new_devid=a$__new_devid __new_devid_b=e$__new_devid ;;
227	?[Ee]:*) __new_devid=2$__new_devid __new_devid_b=6$__new_devid ;;
228	      *) __new_devid=2$__new_devid __new_devid_b=e$__new_devid
229	esac
230	# => NP:SS:SS:II:II:II
231	__new_devid=$( printf %x $(( $__mac_num & 15 )) )$__new_devid
232	__new_devid_b=$( printf %x $(( $__mac_num & 15 )) )$__new_devid_b
233
234	#
235	# Return derivative MAC address(es)
236	#
237	if [ "$__make_pair" ]; then
238		if [ "$__var_to_set" -a "$__var_to_set_b" ]; then
239			eval $__var_to_set=\$__new_devid
240			eval $__var_to_set_b=\$__new_devid_b
241		else
242			echo $__new_devid $__new_devid_b
243		fi
244	else
245		if [ "$__var_to_set" ]; then
246			eval $__var_to_set=\$__new_devid
247		else
248			echo $__new_devid
249		fi
250	fi
251}
252
253mustberoot_to_continue()
254{
255	if [ "$( id -u )" -ne 0 ]; then
256		echo "Must run as root!" >&2
257		exit $FAILURE
258	fi
259}
260
261jib_addm_usage="addm [-b BRIDGE_NAME] NAME [!]iface0 [[!]iface1 ...]"
262jib_addm_descr="Creates e0b_NAME [e1b_NAME ...]"
263jib_addm()
264{
265	local OPTIND=1 OPTARG flag bridge=bridge
266	while getopts b: flag; do
267		case "$flag" in
268		b) bridge="${OPTARG:-bridge}" ;;
269		*) action_usage addm # NOTREACHED
270		esac
271	done
272	shift $(( $OPTIND - 1 ))
273
274	local name="$1"
275	[ "${name:-x}" = "${name#*[!0-9a-zA-Z_]}" -a $# -gt 1 ] ||
276		action_usage addm # NOTREACHED
277	shift 1 # name
278
279	mustberoot_to_continue
280
281	local iface eiface_devid_a eiface_devid_b
282	local new no_derive num quad i=0
283	for iface in $*; do
284
285		no_derive=
286		case "$iface" in
287		!*) iface=${iface#!} no_derive=1 ;;
288		esac
289
290		# Make sure the interface doesn't exist already
291		if ifconfig "e${i}a_$name" > /dev/null 2>&1; then
292			i=$(( $i + 1 ))
293			continue
294		fi
295
296		# Bring the interface up
297		ifconfig $iface up || return
298
299		# Make sure the interface has been bridged
300		if ! ifconfig "$iface$bridge" > /dev/null 2>&1; then
301			new=$( ifconfig bridge create ) || return
302			ifconfig $new addm $iface || return
303			ifconfig $new name "$iface$bridge" || return
304			ifconfig "$iface$bridge" up || return
305		fi
306
307		# Create a new interface to the bridge
308		new=$( ifconfig epair create ) || return
309		ifconfig "$iface$bridge" addm $new || return
310
311		# Rename the new interface
312		ifconfig $new name "e${i}a_$name" || return
313		ifconfig ${new%a}b name "e${i}b_$name" || return
314		ifconfig "e${i}a_$name" up || return
315		ifconfig "e${i}b_$name" up || return
316
317		#
318		# Set the MAC address of the new interface using a sensible
319		# algorithm to prevent conflicts on the network.
320		#
321		eiface_devid_a= eiface_devid_b=
322		[ "$no_derive" ] || derive_mac -2 $iface "$name" \
323			eiface_devid_a eiface_devid_b
324		if [ "$eiface_devid_a" -a "$eiface_devid_b" ]; then
325			ifconfig "e${i}a_$name" ether $eiface_devid_a
326			ifconfig "e${i}b_$name" ether $eiface_devid_b
327		fi > /dev/null 2>&1
328
329		i=$(( $i + 1 ))
330	done # for iface
331}
332
333jib_show_usage="show"
334jib_show_descr="List possible NAME values for \`show NAME'"
335jib_show1_usage="show NAME"
336jib_show1_descr="Lists e0b_NAME [e1b_NAME ...]"
337jib_show2_usage="show [NAME]"
338jib_show()
339{
340	local OPTIND=1 OPTARG flag
341	while getopts "" flag; do
342		case "$flag" in
343		*) action_usage show2 # NOTREACHED
344		esac
345	done
346	shift $(( $OPTIND - 1 ))
347	if [ $# -eq 0 ]; then
348		ifconfig | awk '
349			/^[^:[:space:]]+:/ {
350				iface = $1
351				sub(/:.*/, "", iface)
352				next
353			}
354			$1 == "groups:" {
355				for (n = split($0, group); n > 1; n--) {
356					if (group[n] != "bridge") continue
357					print iface
358					next
359				}
360			}' |
361			xargs -rn1 ifconfig |
362			awk '$1 == "member:" &&
363				sub(/^e[[:digit:]]+a_/, "", $2), $0 = $2' |
364			sort -u
365		return
366	fi
367	ifconfig | awk -v name="$1" '
368		match($0, /^e[[:digit:]]+a_/) && sub(/:.*/, "") &&
369			substr($1, RSTART + RLENGTH) == name
370	' | sort
371}
372
373jib_destroy_usage="destroy NAME"
374jib_destroy_descr="Destroy e0b_NAME [e1b_NAME ...]"
375jib_destroy()
376{
377	local OPTIND=1 OPTARG flag
378	while getopts "" flag; do
379		case "$flag" in
380		*) action_usage destroy # NOTREACHED
381		esac
382	done
383	shift $(( $OPTIND -1 ))
384	local name="$1"
385	[ "${name:-x}" = "${name#*[!0-9a-zA-Z_]}" -a $# -eq 1 ] ||
386		action_usage destroy # NOTREACHED
387	mustberoot_to_continue
388	jib_show "$name" | xargs -rn1 -I eiface ifconfig eiface destroy
389}
390
391############################################################ MAIN
392
393#
394# Command-line arguments
395#
396action="$1"
397[ "$action" ] || usage # NOTREACHED
398
399#
400# Validate action argument
401#
402if [ "$BASH_VERSION" ]; then
403	type="$( type -t "jib_$action" )" || usage # NOTREACHED
404else
405	type="$( type "jib_$action" 2> /dev/null )" || usage # NOTREACHED
406fi
407case "$type" in
408*function)
409	shift 1 # action
410	eval "jib_$action" \"\$@\"
411	;;
412*) usage # NOTREACHED
413esac
414
415################################################################################
416# END
417################################################################################
418