Categories
FreeBSD/Unix

Creating virtual ethernet interfaces using ng_eiface and ng_bridge

With generic ethernet interface netgraph node it is possible to create new interfaces that are accessible with ifconfig(8) and with ethernet bridging netgraph node type it is possible to bridge between different ethernet node types. By combining these two types it is possible to create multiple interfaces with different ethernet (MAC) address on a same physical interface. Here is sample script that is modified from the netgraph ether.bridge example script that comes with standard FreeBSD distribution:

#!/bin/sh
#
# Author: Jan Melen-jan(at)melen.org
#
# This script sets up an Ethernet bridging network across multiple
# ng_eiface(4) using the ng_bridge(4) and ng_ether(4) netgraph
# node types.
#

BRIDGE_NAME="bnet0"

VIRTUAL_IFACES="ngeth0 ngeth1 ngeth2"
LOCAL_IFACE="bge0"

# Routine to verify node's existence.
vether_verify() {
	ngctl info ${BRIDGE_NAME}: >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "${BRIDGE_NAME}: bridge network not found"
		exit 1
	fi
}

# Start/restart routine.
vether_start() {

	# Load netgraph KLD's as necessary.
	for KLD in ng_ether ng_bridge; do
		if ! kldstat -v | grep -qw ${KLD}; then
			echo -n "Loading ${KLD}.ko... "
			kldload ${KLD} || exit 1
			echo "done"
		fi
	done

	# Reset all interfaces.
	vether_stop

	# Verify all interfaces exist.
	LINKNUM=2
   ETHERADDR=`ifconfig ${LOCAL_IFACE} ether | grep "ether" | cut -b 8-22`
	for ETHER in ${VIRTUAL_IFACES}; do
		if ! ngctl info ${ETHER}: >/dev/null 2>&1; then
           ngctl mkpeer . eiface hook ether
		fi
       ifconfig ${ETHER} ether ${ETHERADDR}${LINKNUM}
		ifconfig ${ETHER} up || exit 1
		LINKNUM=`expr ${LINKNUM} + 1`
	done

	# Create new ng_bridge(4) node, attached to the first interface.
	ngctl mkpeer ${LOCAL_IFACE}: bridge lower link0 || exit 1
	ngctl name ${LOCAL_IFACE}:lower ${BRIDGE_NAME} || exit 1
   ngctl connect ${LOCAL_IFACE}: ${BRIDGE_NAME}: upper link1 || exit 1

	LINKNUM=2
	# Attach other interfaces as well.
	for ETHER in ${VIRTUAL_IFACES}; do
		if [ ${LINKNUM} != 0 ]; then
			ngctl connect ${ETHER}: ${BRIDGE_NAME}: \
			    ether link${LINKNUM} || exit 1
		fi
		LINKNUM=`expr ${LINKNUM} + 1`
	done

	# Set all interfaces in promiscuous mode and don't overwrite src addr.
	for ETHER in ${LOCAL_IFACE}; do
		ngctl msg ${ETHER}: setpromisc 1
		ngctl msg ${ETHER}: setautosrc 0
	done
}

# Stop routine.
vether_stop() {
	ngctl kill ${BRIDGE_NAME}: >/dev/null 2>&1
	for ETHER in ${VIRTUAL_IFACES} ${LOCAL_IFACE}; do
		ngctl kill ${ETHER}: >/dev/null 2>&1
	done
}

# Main entry point.
case $1 in
	start)
		vether_start
		;;
	stop)
		vether_verify
		vether_stop
		;;
	*)
		echo "usage: $0 [ start | stop ]"
		exit 1
esac