Raspberry Pi - hotplug, dnsmasq, NAT

February 23, 2021

Założenia

  1. Konfigurujemy jedną z malinek jako serwer dhcp i router.
  2. Do malinki podłączane są po USB (np. z pomocą huba) pozostałe malinki (skonfigurowane w ten sposób).
  3. Całość działa jako hotplug, po podłączeniu nowych urządzeń otrzymują one adresację IP oraz dostęp do sieci.

bridge-utils

apt install bridge-utils
brctl addbr br0

/etc/network/brusb

#!/bin/sh
if [ "${IFACE}" = '--all' ]; then
	IFACE=`ip -br l | grep usb | colrm 5`
fi
if [ -z `ip -br l | grep br0 | colrm 3` ]; then
	brctl addbr br0	
fi
for i in ${IFACE}; do
	brctl addif br0 "${i}"
done

/etc/network/interfaces

auto /usb*=usb

auto lo br0
iface br0 inet static
	bridge_ports none
	address 192.168.13.1
	netmask 255.255.255.0
	network 192.168.13.0

iface usb inet manual
	post-up /etc/network/brusb

allow-hotplug usb0
allow-hotplug usb1
allow-hotplug usb2
allow-hotplug usb3
allow-hotplug usb4
allow-hotplug usb5
allow-hotplug usb6
allow-hotplug usb7
allow-hotplug usb8
allow-hotplug usb9
allow-hotplug usb10
allow-hotplug usb11
allow-hotplug usb12
allow-hotplug usb13
allow-hotplug usb14
allow-hotplug usb15

iface usb0 inet manual inherits usb
iface usb1 inet manual inherits usb
iface usb2 inet manual inherits usb
iface usb3 inet manual inherits usb
iface usb4 inet manual inherits usb
iface usb5 inet manual inherits usb
iface usb6 inet manual inherits usb
iface usb7 inet manual inherits usb
iface usb8 inet manual inherits usb
iface usb9 inet manual inherits usb
iface usb10 inet manual inherits usb
iface usb11 inet manual inherits usb
iface usb12 inet manual inherits usb
iface usb13 inet manual inherits usb
iface usb14 inet manual inherits usb

Niestety, długaśny konfig, gdyż z jakiegoś niezrozumiałego powodu użycie allow-hotplug /usb*=usb nie działa :-( Zmarnowałem parę godzin na różnych próbach, jeżeli ktoś wie dlaczego to proszę o kontakt.

/etc/dhcpcd.conf

denyinterfaces usb* br0

/usr/lib/dhcpcd5/dhcpcd

Usuwamy static z grepa.

dnsmasq

apt install dnsmasq

/etc/dnsmasq.conf

Dodajemy:

interface=br0
dhcp-range=192.168.13.50,192.168.13.100,12h

/etc/hosts

Dodajemy wpisy do /etc/hosts aby rozwijać nazwy na adresy IP.

for i in {50..100}; do echo "192.168.13.${i} pi${i}" >> /etc/hosts; done

/etc/sysctl.conf

Włączamy routing.

net.ipv4.ip_forward=1

NAT

apt install iptables-persistent
iptables -A FORWARD -o wlan0 -i br0 -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -o eth0 -i br0 -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables-save > /etc/iptables/rules.v4