Chapter 55: OpenWrt - Open Source Wireless and Embedded Networking

Learning Objectives

By the end of this chapter, you will be able to: - Deploy OpenWrt in ContainerLab for network simulation - Configure wireless access points and routing with OpenWrt - Implement advanced networking features using OpenWrt - Integrate OpenWrt with enterprise network infrastructure - Customize and extend OpenWrt functionality

Introduction to OpenWrt

What is OpenWrt?

OpenWrt is a Linux-based operating system targeting embedded devices, primarily wireless routers and access points. It provides a fully writable filesystem with package management, enabling users to customize the device through the use of packages to suit any application.

Key OpenWrt Features

  • Linux-based: Full Linux distribution for embedded devices
  • Package Management: opkg package manager with thousands of packages
  • Web Interface: LuCI web configuration interface
  • Wireless Support: Comprehensive 802.11 protocol support
  • Network Services: Routing, switching, firewall, VPN, QoS
  • Extensible: Custom applications and kernel modules
  • Container Ready: Can run in containers for testing and development

OpenWrt Architecture

Core Components

  • Kernel: Linux kernel optimized for embedded devices
  • Base System: Essential system utilities and libraries
  • Network Stack: Advanced networking capabilities
  • Wireless Stack: mac80211 and cfg80211 wireless frameworks
  • Package System: opkg package management
  • Web Interface: LuCI configuration interface
  • UCI: Unified Configuration Interface

OpenWrt Lab Environment

OpenWrt Container Lab Setup

# OpenWrt comprehensive lab
name: openwrt-network-lab
prefix: owrt

topology:
  nodes:
    # OpenWrt routers/APs
    openwrt-main:
      kind: linux
      image: openwrt/rootfs:latest
      mgmt-ipv4: 172.20.20.10
      cmd: /sbin/init
      binds:
        - ./configs/openwrt-main:/etc/config
      env:
        - OPENWRT_HOSTNAME=openwrt-main

    openwrt-ap1:
      kind: linux
      image: openwrt/rootfs:latest
      mgmt-ipv4: 172.20.20.11
      cmd: /sbin/init
      binds:
        - ./configs/openwrt-ap1:/etc/config
      env:
        - OPENWRT_HOSTNAME=openwrt-ap1

    openwrt-ap2:
      kind: linux
      image: openwrt/rootfs:latest
      mgmt-ipv4: 172.20.20.12
      cmd: /sbin/init
      binds:
        - ./configs/openwrt-ap2:/etc/config
      env:
        - OPENWRT_HOSTNAME=openwrt-ap2

    # Core network switch
    core-switch:
      kind: linux
      image: alpine:latest
      mgmt-ipv4: 172.20.20.13
      exec:
        - apk add --no-cache bridge-utils
        - brctl addbr br0
        - brctl stp br0 off
        - ip link set br0 up
        - ip addr add 10.1.1.1/24 dev br0

    # Client devices
    wireless-client1:
      kind: linux
      image: alpine:latest
      mgmt-ipv4: 172.20.20.20
      exec:
        - apk add --no-cache wireless-tools wpa_supplicant dhcpcd
        - ip addr add 192.168.1.100/24 dev eth1

    wireless-client2:
      kind: linux
      image: alpine:latest
      mgmt-ipv4: 172.20.20.21
      exec:
        - apk add --no-cache wireless-tools wpa_supplicant dhcpcd
        - ip addr add 192.168.2.100/24 dev eth1

    wired-client:
      kind: linux
      image: alpine:latest
      mgmt-ipv4: 172.20.20.22
      exec:
        - ip addr add 192.168.10.100/24 dev eth1
        - ip route add default via 192.168.10.1

    # Internet simulation
    internet-gw:
      kind: linux
      image: alpine:latest
      mgmt-ipv4: 172.20.20.100
      exec:
        - ip addr add 203.0.113.1/30 dev eth1
        - ip route add 192.168.0.0/16 via 203.0.113.2
        - apk add --no-cache iperf3 nginx
        - nginx

  links:
    # Core network connections
    - endpoints: ["openwrt-main:eth1", "core-switch:eth1"]
    - endpoints: ["openwrt-ap1:eth1", "core-switch:eth2"]
    - endpoints: ["openwrt-ap2:eth1", "core-switch:eth3"]

    # WAN connection
    - endpoints: ["openwrt-main:eth2", "internet-gw:eth1"]

    # Wired client
    - endpoints: ["openwrt-main:eth3", "wired-client:eth1"]

    # Wireless simulation (using wired for lab)
    - endpoints: ["openwrt-ap1:eth2", "wireless-client1:eth1"]
    - endpoints: ["openwrt-ap2:eth2", "wireless-client2:eth1"]

OpenWrt Configuration Files

Network Configuration

# Create configuration directories
mkdir -p configs/openwrt-main configs/openwrt-ap1 configs/openwrt-ap2

# OpenWrt Main Router Network Configuration
cat > configs/openwrt-main/network << 'EOF'
config interface 'loopback'
    option ifname 'lo'
    option proto 'static'
    option ipaddr '127.0.0.1'
    option netmask '255.0.0.0'

config globals 'globals'
    option ula_prefix 'fd12:3456:789a::/48'

config interface 'lan'
    option type 'bridge'
    option ifname 'eth1 eth3'
    option proto 'static'
    option ipaddr '192.168.10.1'
    option netmask '255.255.255.0'
    option ip6assign '60'

config interface 'wan'
    option ifname 'eth2'
    option proto 'dhcp'

config interface 'wan6'
    option ifname 'eth2'
    option proto 'dhcpv6'

config switch
    option name 'switch0'
    option ports '0 1 2 3 6'
    option blinkrate '2'

config switch_vlan
    option device 'switch0'
    option vlan '1'
    option ports '0 1 2 3 6t'

config switch_vlan
    option device 'switch0'
    option vlan '2'
    option ports '4 6t'
EOF

# OpenWrt AP1 Network Configuration
cat > configs/openwrt-ap1/network << 'EOF'
config interface 'loopback'
    option ifname 'lo'
    option proto 'static'
    option ipaddr '127.0.0.1'
    option netmask '255.0.0.0'

config interface 'lan'
    option ifname 'eth1 eth2'
    option type 'bridge'
    option proto 'static'
    option ipaddr '192.168.1.1'
    option netmask '255.255.255.0'
    option ip6assign '60'

config interface 'uplink'
    option ifname 'eth1'
    option proto 'static'
    option ipaddr '10.1.1.11'
    option netmask '255.255.255.0'
    option gateway '10.1.1.1'
    option dns '8.8.8.8 8.8.4.4'
EOF

Wireless Configuration

# OpenWrt Main Router Wireless Configuration
cat > configs/openwrt-main/wireless << 'EOF'
config wifi-device 'radio0'
    option type 'mac80211'
    option channel '11'
    option hwmode '11g'
    option path 'platform/10180000.wmac'
    option htmode 'HT20'
    option disabled '0'
    option country 'US'
    option txpower '20'

config wifi-iface 'default_radio0'
    option device 'radio0'
    option network 'lan'
    option mode 'ap'
    option ssid 'OpenWrt-Main'
    option encryption 'psk2'
    option key 'SecureWiFiPassword123'
    option hidden '0'
    option isolate '0'

config wifi-device 'radio1'
    option type 'mac80211'
    option channel '36'
    option hwmode '11a'
    option path 'pci0000:00/0000:00:00.0'
    option htmode 'VHT80'
    option disabled '0'
    option country 'US'
    option txpower '23'

config wifi-iface 'default_radio1'
    option device 'radio1'
    option network 'lan'
    option mode 'ap'
    option ssid 'OpenWrt-Main-5G'
    option encryption 'psk2'
    option key 'SecureWiFiPassword123'
    option hidden '0'
    option isolate '0'
EOF

# OpenWrt AP1 Wireless Configuration
cat > configs/openwrt-ap1/wireless << 'EOF'
config wifi-device 'radio0'
    option type 'mac80211'
    option channel '6'
    option hwmode '11g'
    option path 'platform/10180000.wmac'
    option htmode 'HT20'
    option disabled '0'
    option country 'US'
    option txpower '20'

config wifi-iface 'default_radio0'
    option device 'radio0'
    option network 'lan'
    option mode 'ap'
    option ssid 'OpenWrt-Guest'
    option encryption 'psk2'
    option key 'GuestWiFiPassword456'
    option hidden '0'
    option isolate '1'
EOF

Firewall Configuration

# OpenWrt Main Router Firewall Configuration
cat > configs/openwrt-main/firewall << 'EOF'
config defaults
    option syn_flood '1'
    option input 'ACCEPT'
    option output 'ACCEPT'
    option forward 'REJECT'

config zone
    option name 'lan'
    list network 'lan'
    option input 'ACCEPT'
    option output 'ACCEPT'
    option forward 'ACCEPT'

config zone
    option name 'wan'
    list network 'wan'
    list network 'wan6'
    option input 'REJECT'
    option output 'ACCEPT'
    option forward 'REJECT'
    option masq '1'
    option mtu_fix '1'

config forwarding
    option src 'lan'
    option dest 'wan'

config rule
    option name 'Allow-DHCP-Renew'
    option src 'wan'
    option proto 'udp'
    option dest_port '68'
    option target 'ACCEPT'
    option family 'ipv4'

config rule
    option name 'Allow-Ping'
    option src 'wan'
    option proto 'icmp'
    option icmp_type 'echo-request'
    option family 'ipv4'
    option target 'ACCEPT'

config rule
    option name 'Allow-IGMP'
    option src 'wan'
    option proto 'igmp'
    option family 'ipv4'
    option target 'ACCEPT'

config rule
    option name 'Allow-DHCPv6'
    option src 'wan'
    option proto 'udp'
    option src_ip 'fc00::/6'
    option dest_ip 'fc00::/6'
    option dest_port '546'
    option family 'ipv6'
    option target 'ACCEPT'

config rule
    option name 'Allow-MLD'
    option src 'wan'
    option proto 'icmp'
    option src_ip 'fe80::/10'
    option icmp_type '130/0 131/0 132/0 143/0'
    option family 'ipv6'
    option target 'ACCEPT'

config rule
    option name 'Allow-ICMPv6-Input'
    option src 'wan'
    option proto 'icmp'
    option icmp_type '128 129 135 136'
    option family 'ipv6'
    option target 'ACCEPT'

config rule
    option name 'Allow-ICMPv6-Forward'
    option src 'wan'
    option dest '*'
    option proto 'icmp'
    option icmp_type '128 129 135 136'
    option family 'ipv6'
    option target 'ACCEPT'

config include
    option path '/etc/firewall.user'
EOF

OpenWrt Network Configuration

Basic Network Setup

# Deploy OpenWrt lab
containerlab deploy -t openwrt-network-lab.yml

# Connect to OpenWrt main router
docker exec -it clab-owrt-openwrt-main sh

# Check network configuration
uci show network
cat /etc/config/network

# Configure network interface
uci set network.lan.ipaddr='192.168.10.1'
uci set network.lan.netmask='255.255.255.0'
uci commit network
/etc/init.d/network restart

# Verify network configuration
ip addr show
ip route show

VLAN Configuration

# Configure VLANs
uci set network.@switch_vlan[0].vlan='10'
uci set network.@switch_vlan[0].ports='0 1 6t'
uci add network switch_vlan
uci set network.@switch_vlan[1].device='switch0'
uci set network.@switch_vlan[1].vlan='20'
uci set network.@switch_vlan[1].ports='2 3 6t'

# Create VLAN interfaces
uci set network.vlan10=interface
uci set network.vlan10.ifname='eth0.10'
uci set network.vlan10.proto='static'
uci set network.vlan10.ipaddr='192.168.10.1'
uci set network.vlan10.netmask='255.255.255.0'

uci set network.vlan20=interface
uci set network.vlan20.ifname='eth0.20'
uci set network.vlan20.proto='static'
uci set network.vlan20.ipaddr='192.168.20.1'
uci set network.vlan20.netmask='255.255.255.0'

uci commit network
/etc/init.d/network restart

# Verify VLAN configuration
swconfig dev switch0 show

Bridge Configuration

# Configure bridge
uci set network.br_lan=interface
uci set network.br_lan.type='bridge'
uci set network.br_lan.proto='static'
uci set network.br_lan.ipaddr='192.168.1.1'
uci set network.br_lan.netmask='255.255.255.0'
uci add_list network.br_lan.ifname='eth1'
uci add_list network.br_lan.ifname='eth2'

# Bridge options
uci set network.br_lan.stp='1'
uci set network.br_lan.forward_delay='2'
uci set network.br_lan.hello_time='1'
uci set network.br_lan.max_age='10'

uci commit network
/etc/init.d/network restart

# Verify bridge
brctl show

OpenWrt Wireless Configuration

Access Point Configuration

# Configure wireless access point
uci set wireless.radio0.disabled='0'
uci set wireless.radio0.channel='11'
uci set wireless.radio0.htmode='HT20'
uci set wireless.radio0.country='US'
uci set wireless.radio0.txpower='20'

# Configure wireless interface
uci set wireless.default_radio0.ssid='OpenWrt-Lab'
uci set wireless.default_radio0.encryption='psk2'
uci set wireless.default_radio0.key='SecurePassword123'
uci set wireless.default_radio0.network='lan'
uci set wireless.default_radio0.mode='ap'
uci set wireless.default_radio0.hidden='0'

uci commit wireless
wifi reload

# Verify wireless configuration
iwconfig
iw dev

Guest Network Configuration

# Create guest network interface
uci set network.guest=interface
uci set network.guest.proto='static'
uci set network.guest.ipaddr='192.168.100.1'
uci set network.guest.netmask='255.255.255.0'

# Create guest wireless interface
uci set wireless.guest=wifi-iface
uci set wireless.guest.device='radio0'
uci set wireless.guest.mode='ap'
uci set wireless.guest.ssid='OpenWrt-Guest'
uci set wireless.guest.encryption='psk2'
uci set wireless.guest.key='GuestPassword456'
uci set wireless.guest.network='guest'
uci set wireless.guest.isolate='1'

uci commit network
uci commit wireless
/etc/init.d/network restart
wifi reload

# Configure guest network firewall
uci add firewall zone
uci set firewall.@zone[-1].name='guest'
uci add_list firewall.@zone[-1].network='guest'
uci set firewall.@zone[-1].input='REJECT'
uci set firewall.@zone[-1].output='ACCEPT'
uci set firewall.@zone[-1].forward='REJECT'

# Allow guest to WAN
uci add firewall forwarding
uci set firewall.@forwarding[-1].src='guest'
uci set firewall.@forwarding[-1].dest='wan'

# Block guest to LAN
uci add firewall rule
uci set firewall.@rule[-1].name='Block-Guest-to-LAN'
uci set firewall.@rule[-1].src='guest'
uci set firewall.@rule[-1].dest='lan'
uci set firewall.@rule[-1].target='REJECT'

uci commit firewall
/etc/init.d/firewall restart

Wireless Security

# Configure WPA3 security
uci set wireless.default_radio0.encryption='sae'
uci set wireless.default_radio0.key='SecureWPA3Password123'

# Configure enterprise security (WPA2-Enterprise)
uci set wireless.default_radio0.encryption='wpa2'
uci set wireless.default_radio0.server='192.168.1.100'
uci set wireless.default_radio0.port='1812'
uci set wireless.default_radio0.key='RadiusSecret123'

# MAC address filtering
uci set wireless.default_radio0.macfilter='allow'
uci add_list wireless.default_radio0.maclist='aa:bb:cc:dd:ee:ff'
uci add_list wireless.default_radio0.maclist='11:22:33:44:55:66'

uci commit wireless
wifi reload

OpenWrt Routing Configuration

Static Routing

# Configure static routes
uci add network route
uci set network.@route[-1].interface='wan'
uci set network.@route[-1].target='192.168.200.0'
uci set network.@route[-1].netmask='255.255.255.0'
uci set network.@route[-1].gateway='203.0.113.1'

# Policy-based routing
uci add network rule
uci set network.@rule[-1].src='192.168.10.0/24'
uci set network.@rule[-1].lookup='100'

uci add network route
uci set network.@route[-1].interface='wan'
uci set network.@route[-1].target='0.0.0.0'
uci set network.@route[-1].netmask='0.0.0.0'
uci set network.@route[-1].gateway='203.0.113.1'
uci set network.@route[-1].table='100'

uci commit network
/etc/init.d/network restart

# Verify routing
ip route show
ip rule show

Dynamic Routing with BIRD

# Install BIRD routing daemon
opkg update
opkg install bird2 bird2-client

# Configure BIRD for OSPF
cat > /etc/bird.conf << 'EOF'
log syslog all;

router id 1.1.1.1;

protocol device {
    scan time 10;
}

protocol kernel {
    ipv4 {
        import none;
        export all;
    };
}

protocol static {
    ipv4;
    route 192.168.10.0/24 via "br-lan";
}

protocol ospf v2 {
    ipv4 {
        import all;
        export all;
    };

    area 0.0.0.0 {
        interface "eth1" {
            cost 10;
            hello 5;
            dead 20;
        };
        interface "br-lan" {
            stub yes;
        };
    };
}
EOF

# Start BIRD
/etc/init.d/bird enable
/etc/init.d/bird start

# Verify BIRD
birdc show protocols
birdc show route

OpenWrt Services Configuration

DHCP Server

# Configure DHCP server
uci set dhcp.lan.start='100'
uci set dhcp.lan.limit='150'
uci set dhcp.lan.leasetime='12h'
uci add_list dhcp.lan.dhcp_option='6,8.8.8.8,8.8.4.4'
uci add_list dhcp.lan.dhcp_option='3,192.168.10.1'

# Static DHCP reservations
uci add dhcp host
uci set dhcp.@host[-1].name='server1'
uci set dhcp.@host[-1].mac='aa:bb:cc:dd:ee:ff'
uci set dhcp.@host[-1].ip='192.168.10.100'

# DHCP for guest network
uci set dhcp.guest=dhcp
uci set dhcp.guest.interface='guest'
uci set dhcp.guest.start='50'
uci set dhcp.guest.limit='50'
uci set dhcp.guest.leasetime='2h'

uci commit dhcp
/etc/init.d/dnsmasq restart

# Verify DHCP
cat /var/dhcp.leases

DNS Configuration

# Configure DNS
uci add_list dhcp.@dnsmasq[0].server='8.8.8.8'
uci add_list dhcp.@dnsmasq[0].server='1.1.1.1'
uci set dhcp.@dnsmasq[0].domain='local.lan'
uci set dhcp.@dnsmasq[0].local='/local.lan/'

# DNS filtering
uci add_list dhcp.@dnsmasq[0].address='/ads.example.com/127.0.0.1'
uci add_list dhcp.@dnsmasq[0].address='/malware.example.com/127.0.0.1'

# Custom DNS entries
echo "192.168.10.100 server1.local.lan server1" >> /etc/hosts

uci commit dhcp
/etc/init.d/dnsmasq restart

# Verify DNS
nslookup server1.local.lan
dig @127.0.0.1 google.com

VPN Services

OpenVPN Server

# Install OpenVPN
opkg update
opkg install openvpn-openssl openvpn-easy-rsa luci-app-openvpn

# Generate certificates
cd /etc/easy-rsa
./easyrsa init-pki
./easyrsa build-ca nopass
./easyrsa gen-req server nopass
./easyrsa sign-req server server
./easyrsa gen-dh

# Configure OpenVPN server
cat > /etc/openvpn/server.conf << 'EOF'
port 1194
proto udp
dev tun
ca /etc/easy-rsa/pki/ca.crt
cert /etc/easy-rsa/pki/issued/server.crt
key /etc/easy-rsa/pki/private/server.key
dh /etc/easy-rsa/pki/dh.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
push "route 192.168.10.0 255.255.255.0"
push "dhcp-option DNS 192.168.10.1"
keepalive 10 120
comp-lzo
persist-key
persist-tun
status openvpn-status.log
verb 3
EOF

# Start OpenVPN
/etc/init.d/openvpn enable
/etc/init.d/openvpn start

# Configure firewall for VPN
uci add firewall rule
uci set firewall.@rule[-1].name='Allow-OpenVPN'
uci set firewall.@rule[-1].src='wan'
uci set firewall.@rule[-1].dest_port='1194'
uci set firewall.@rule[-1].proto='udp'
uci set firewall.@rule[-1].target='ACCEPT'

uci commit firewall
/etc/init.d/firewall restart

WireGuard VPN

# Install WireGuard
opkg update
opkg install wireguard-tools kmod-wireguard luci-app-wireguard

# Generate keys
wg genkey | tee /etc/wireguard/server_private.key | wg pubkey > /etc/wireguard/server_public.key
wg genkey | tee /etc/wireguard/client_private.key | wg pubkey > /etc/wireguard/client_public.key

# Configure WireGuard interface
uci set network.wg0=interface
uci set network.wg0.proto='wireguard'
uci set network.wg0.private_key="$(cat /etc/wireguard/server_private.key)"
uci add_list network.wg0.addresses='10.9.0.1/24'

# Add WireGuard peer
uci add network wireguard_wg0
uci set network.@wireguard_wg0[-1].public_key="$(cat /etc/wireguard/client_public.key)"
uci add_list network.@wireguard_wg0[-1].allowed_ips='10.9.0.2/32'
uci add_list network.@wireguard_wg0[-1].allowed_ips='192.168.100.0/24'

uci commit network
/etc/init.d/network restart

# Configure firewall
uci add firewall zone
uci set firewall.@zone[-1].name='wg'
uci add_list firewall.@zone[-1].network='wg0'
uci set firewall.@zone[-1].input='ACCEPT'
uci set firewall.@zone[-1].output='ACCEPT'
uci set firewall.@zone[-1].forward='ACCEPT'

uci add firewall forwarding
uci set firewall.@forwarding[-1].src='wg'
uci set firewall.@forwarding[-1].dest='lan'

uci commit firewall
/etc/init.d/firewall restart

OpenWrt Quality of Service

Traffic Shaping

# Install QoS packages
opkg update
opkg install tc kmod-sched-core kmod-ifb luci-app-qos

# Configure QoS
uci set qos.wan=interface
uci set qos.wan.classgroup='Default'
uci set qos.wan.enabled='1'
uci set qos.wan.upload='1000'
uci set qos.wan.download='10000'

# QoS rules
uci add qos rule
uci set qos.@rule[-1].target='Priority'
uci set qos.@rule[-1].proto='tcp'
uci set qos.@rule[-1].ports='22,53,80,443'

uci add qos rule
uci set qos.@rule[-1].target='Express'
uci set qos.@rule[-1].proto='udp'
uci set qos.@rule[-1].ports='53,123'

uci add qos rule
uci set qos.@rule[-1].target='Bulk'
uci set qos.@rule[-1].proto='tcp'
uci set qos.@rule[-1].ports='20,21,25,110,143,993,995'

uci commit qos
/etc/init.d/qos enable
/etc/init.d/qos start

# Verify QoS
tc qdisc show
tc class show dev eth2

Bandwidth Monitoring

# Install monitoring tools
opkg install luci-app-statistics collectd-mod-interface collectd-mod-iwinfo

# Configure statistics collection
uci set luci_statistics.collectd.Hostname='OpenWrt-Main'
uci set luci_statistics.collectd.BaseDir='/tmp/rrd'
uci set luci_statistics.collectd.Include='/etc/collectd/conf.d'
uci set luci_statistics.collectd.PIDFile='/var/run/collectd.pid'
uci set luci_statistics.collectd.PluginDir='/usr/lib/collectd'
uci set luci_statistics.collectd.TypesDB='/usr/share/collectd/types.db'
uci set luci_statistics.collectd.Interval='60'
uci set luci_statistics.collectd.ReadThreads='2'

# Enable interface monitoring
uci set luci_statistics.collectd_interface.enable='1'
uci add_list luci_statistics.collectd_interface.Interfaces='br-lan'
uci add_list luci_statistics.collectd_interface.Interfaces='eth2'

uci commit luci_statistics
/etc/init.d/luci_statistics enable
/etc/init.d/luci_statistics start

OpenWrt Security Features

Firewall Advanced Configuration

# Advanced firewall rules
uci add firewall rule
uci set firewall.@rule[-1].name='Block-Tor'
uci set firewall.@rule[-1].src='lan'
uci set firewall.@rule[-1].dest='wan'
uci set firewall.@rule[-1].dest_port='9001,9030'
uci set firewall.@rule[-1].target='REJECT'

# Rate limiting
uci add firewall rule
uci set firewall.@rule[-1].name='SSH-Rate-Limit'
uci set firewall.@rule[-1].src='wan'
uci set firewall.@rule[-1].dest_port='22'
uci set firewall.@rule[-1].proto='tcp'
uci set firewall.@rule[-1].extra='--limit 3/min --limit-burst 5'
uci set firewall.@rule[-1].target='ACCEPT'

# Port knocking
uci add firewall rule
uci set firewall.@rule[-1].name='Port-Knock-1'
uci set firewall.@rule[-1].src='wan'
uci set firewall.@rule[-1].dest_port='1234'
uci set firewall.@rule[-1].proto='tcp'
uci set firewall.@rule[-1].extra='-m recent --name knock1 --set'
uci set firewall.@rule[-1].target='DROP'

uci commit firewall
/etc/init.d/firewall restart

Intrusion Detection

# Install Suricata IDS
opkg update
opkg install suricata

# Configure Suricata
cat > /etc/suricata/suricata.yaml << 'EOF'
vars:
  address-groups:
    HOME_NET: "[192.168.0.0/16,10.0.0.0/8,172.16.0.0/12]"
    EXTERNAL_NET: "!$HOME_NET"

af-packet:
  - interface: eth2
    cluster-id: 99
    cluster-type: cluster_flow

rule-files:
  - suricata.rules

logging:
  default-log-level: notice
  outputs:
    - console:
        enabled: yes
    - file:
        enabled: yes
        filename: /var/log/suricata/suricata.log
    - syslog:
        enabled: yes
        facility: local5
        format: "[%i] <%d> -- "
EOF

# Start Suricata
/etc/init.d/suricata enable
/etc/init.d/suricata start

# Monitor alerts
tail -f /var/log/suricata/fast.log

OpenWrt Monitoring and Management

System Monitoring

# System information
cat /proc/version
cat /proc/cpuinfo
cat /proc/meminfo
df -h

# Network monitoring
ip addr show
ip route show
iptables -L -n
iwconfig

# Process monitoring
top
ps aux
netstat -tulpn

Remote Management

# SSH configuration
uci set dropbear.@dropbear[0].Port='2222'
uci set dropbear.@dropbear[0].PasswordAuth='off'
uci set dropbear.@dropbear[0].RootPasswordAuth='off'

# Add SSH key
echo "ssh-rsa AAAAB3NzaC1yc2E... user@host" >> /etc/dropbear/authorized_keys

uci commit dropbear
/etc/init.d/dropbear restart

# SNMP configuration
opkg install snmpd
uci set snmpd.agent.agentaddress='UDP:161'
uci set snmpd.com2sec.secname='ro'
uci set snmpd.com2sec.source='default'
uci set snmpd.com2sec.community='public'

uci commit snmpd
/etc/init.d/snmpd enable
/etc/init.d/snmpd start

Backup and Recovery

# Configuration backup
sysupgrade -b /tmp/backup-$(date +%Y%m%d).tar.gz

# System backup
tar -czf /tmp/system-backup.tar.gz /etc /root

# Restore configuration
sysupgrade -r /tmp/backup-20231201.tar.gz

# Factory reset
firstboot && reboot

OpenWrt Automation

UCI Scripting

#!/bin/sh
# openwrt_config_script.sh

# Function to configure basic network
configure_network() {
    local lan_ip="$1"
    local lan_mask="$2"

    uci set network.lan.ipaddr="$lan_ip"
    uci set network.lan.netmask="$lan_mask"
    uci commit network
    /etc/init.d/network restart
}

# Function to configure wireless
configure_wireless() {
    local ssid="$1"
    local password="$2"
    local channel="$3"

    uci set wireless.radio0.disabled='0'
    uci set wireless.radio0.channel="$channel"
    uci set wireless.default_radio0.ssid="$ssid"
    uci set wireless.default_radio0.encryption='psk2'
    uci set wireless.default_radio0.key="$password"
    uci commit wireless
    wifi reload
}

# Function to configure firewall rule
add_firewall_rule() {
    local name="$1"
    local src="$2"
    local dest_port="$3"
    local proto="$4"
    local target="$5"

    uci add firewall rule
    uci set firewall.@rule[-1].name="$name"
    uci set firewall.@rule[-1].src="$src"
    uci set firewall.@rule[-1].dest_port="$dest_port"
    uci set firewall.@rule[-1].proto="$proto"
    uci set firewall.@rule[-1].target="$target"
    uci commit firewall
    /etc/init.d/firewall restart
}

# Usage examples
configure_network "192.168.1.1" "255.255.255.0"
configure_wireless "MyNetwork" "SecurePassword123" "11"
add_firewall_rule "Allow-HTTP" "wan" "80" "tcp" "ACCEPT"

API Integration

#!/usr/bin/env python3
# openwrt_api_client.py
import requests
import json
import base64

class OpenWrtAPI:
    def __init__(self, host, username, password):
        self.host = host
        self.username = username
        self.password = password
        self.session = requests.Session()
        self.token = None
        self.login()

    def login(self):
        """Login to OpenWrt LuCI"""
        auth_data = {
            'luci_username': self.username,
            'luci_password': self.password
        }

        response = self.session.post(
            f"http://{self.host}/cgi-bin/luci/admin/uci",
            data=auth_data
        )

        if response.status_code == 200:
            print("Login successful")
        else:
            print("Login failed")

    def uci_get(self, config, section=None, option=None):
        """Get UCI configuration"""
        url = f"http://{self.host}/cgi-bin/luci/admin/uci/{config}"
        if section:
            url += f"/{section}"
        if option:
            url += f"/{option}"

        response = self.session.get(url)
        return response.json() if response.status_code == 200 else None

    def uci_set(self, config, section, option, value):
        """Set UCI configuration"""
        data = {
            'config': config,
            'section': section,
            'option': option,
            'value': value
        }

        response = self.session.post(
            f"http://{self.host}/cgi-bin/luci/admin/uci",
            data=data
        )

        return response.status_code == 200

    def uci_commit(self, config):
        """Commit UCI changes"""
        data = {'config': config}
        response = self.session.post(
            f"http://{self.host}/cgi-bin/luci/admin/uci/commit",
            data=data
        )
        return response.status_code == 200

    def get_system_info(self):
        """Get system information"""
        response = self.session.get(f"http://{self.host}/cgi-bin/luci/admin/status/overview")
        return response.json() if response.status_code == 200 else None

# Usage example
if __name__ == '__main__':
    api = OpenWrtAPI('192.168.1.1', 'root', 'password')

    # Get network configuration
    network_config = api.uci_get('network')
    print("Network config:", json.dumps(network_config, indent=2))

    # Set wireless SSID
    api.uci_set('wireless', 'default_radio0', 'ssid', 'NewSSID')
    api.uci_commit('wireless')

    # Get system info
    system_info = api.get_system_info()
    print("System info:", json.dumps(system_info, indent=2))

OpenWrt Best Practices

Security Hardening

# Change default passwords
passwd root

# Disable WPS
uci set wireless.radio0.wps_pushbutton='0'
uci commit wireless

# Enable strong wireless encryption
uci set wireless.default_radio0.encryption='sae'
uci commit wireless

# Disable unnecessary services
/etc/init.d/uhttpd disable
/etc/init.d/telnet disable

# Configure automatic updates
opkg update
opkg install auc
echo "0 4 * * * /usr/bin/auc -c" >> /etc/crontabs/root

Performance Optimization

# Optimize wireless settings
uci set wireless.radio0.txpower='20'
uci set wireless.radio0.htmode='HT40'
uci set wireless.radio0.noscan='1'

# Optimize network buffers
echo 'net.core.rmem_max = 134217728' >> /etc/sysctl.conf
echo 'net.core.wmem_max = 134217728' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_rmem = 4096 87380 134217728' >> /etc/sysctl.conf

# Enable hardware acceleration
uci set network.@device[0].multicast_querier='1'
uci set network.@device[0].igmp_snooping='1'

Maintenance Procedures

# Regular maintenance script
#!/bin/sh
# maintenance.sh

# Update package lists
opkg update

# Clean temporary files
rm -rf /tmp/*

# Rotate logs
logrotate /etc/logrotate.conf

# Check filesystem
fsck.ext4 -f /dev/sda1

# Restart services if needed
/etc/init.d/network restart
/etc/init.d/firewall restart
/etc/init.d/dnsmasq restart

echo "Maintenance completed at $(date)"

Summary

OpenWrt provides a powerful, flexible platform for network infrastructure with extensive customization capabilities. Its open-source nature, comprehensive package ecosystem, and container compatibility make it an excellent choice for learning, prototyping, and production deployments in various network scenarios.

Key concepts covered: - OpenWrt architecture and configuration system (UCI) - Network and wireless configuration - Routing protocols and services - Security features and VPN services - Quality of Service and monitoring - Automation and API integration - Best practices for deployment and maintenance

In the next chapter, we’ll explore Mininet, a network emulator that creates realistic virtual networks for research and education.

Review Questions

  1. What are the main advantages of OpenWrt over commercial router firmware?
  2. How does the UCI configuration system work in OpenWrt?
  3. What wireless security options are available in OpenWrt?
  4. How do you configure VPN services on OpenWrt?
  5. What are best practices for OpenWrt security hardening?

Hands-on Exercises

Exercise 1: Basic OpenWrt Deployment

  1. Deploy the OpenWrt network lab
  2. Configure basic network and wireless settings
  3. Set up DHCP and DNS services
  4. Test connectivity and wireless functionality

Exercise 2: Advanced Networking Features

  1. Configure VLANs and bridging
  2. Set up guest networks with isolation
  3. Implement QoS and traffic shaping
  4. Configure dynamic routing with BIRD

Exercise 3: Security Implementation

  1. Configure zone-based firewall
  2. Set up VPN services (OpenVPN and WireGuard)
  3. Implement intrusion detection
  4. Apply security hardening measures

Exercise 4: Automation and Management

  1. Create UCI configuration scripts
  2. Develop API integration tools
  3. Implement monitoring and alerting
  4. Build automated deployment procedures

Additional Resources