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