better openwrt sub lan control

This commit is contained in:
ari committed 2026-08-26 16:31:48 -04:00
1 parent 07d5bffef2
commit e3866d75a9
15 files changed
+384 -573

No files matched your search

+31 -6
View File
@@ -16,17 +16,39 @@ openwrt/
## How it works
1. The router config lives as an **agenix secret** (e.g. `secrets/glmain.json.age`).
2. `openwrt-deploy` reads the decrypted JSON from stdin, runs `openwrt-gen dnsmasq` and
`openwrt-gen ethers` to render the two target files.
3. It SSHes to the router, shows a **colorized diff** against the current files, and prompts
for confirmation before writing.
4. `dnsmasq.conf` is validated with `dnsmasq --test` on the router and **automatically
reverted** if the new config is invalid.
2. `openwrt-deploy` reads the decrypted JSON from stdin, runs `openwrt-gen dnsmasq`,
`openwrt-gen ethers`, and `openwrt-gen firewall` to render the three target files.
3. It SSHes to the router, shows a **colorized diff** against the current files (for the
firewall, only the `skyg_*`-managed rules are diffed), and prompts for confirmation.
4. On the router it **backs up** the configs it overrides to `/etc/skyg-backups/` with a
timestamp, then applies them. `dnsmasq.conf` is validated with `dnsmasq --test` and the
firewall is committed + reloaded; **any failure auto-restores** from that timestamp's
backups. Backups persist so you can restore later if something breaks:
```sh
cp /etc/skyg-backups/firewall.<ts> /etc/config/firewall
uci commit firewall && /etc/init.d/firewall restart
```
```
age -d secrets/glmain.json.age | openwrt-deploy
```
### Dry run (no router changes)
`openwrt-dry-run` renders the same three configs **locally** and writes them to
`.tmp/openwrt-<router>/` for review — no SSH, no `uci`, no confirm prompt. The router name
comes from the `SKYG_ROUTER` env var (default `glmain`).
```bash
skyg openwrt --dry-run
# → .tmp/openwrt-glmain/dnsmasq.conf
# → .tmp/openwrt-glmain/ethers
# → .tmp/openwrt-glmain/firewall.batch # the exact `uci batch` that would be applied
```
Use this to inspect what a deploy *would* do (especially the firewall rules) before running
the real `skyg openwrt`.
`router.ip` / `router.user` are taken from the `config` passed into `default.nix`.
## Conventions
@@ -35,3 +57,6 @@ age -d secrets/glmain.json.age | openwrt-deploy
- Deploys are interactive and reviewed by a human; the script intentionally requires
confirmation and self-reverts on a bad dnsmasq config.
- `generator/target/` is gitignored Rust build output — ignore it.
- Firewall rules are **managed by name**: the deploy script only touches rules named
`skyg_*`. It deletes existing `skyg_*` rules, adds the newly generated ones, commits, and
reloads — so deploys are idempotent and never clobber hand-written rules.
+91 -17
View File
@@ -7,6 +7,54 @@ let
src = ./generator;
cargoLock.lockFile = ./generator/Cargo.lock;
};
# Remote apply script: backs up the configs it overrides, applies the new
# firewall/dnsmasq/ethers, validates, and auto-restores on failure.
# Run on the router as: TS=<timestamp> bash skyg-apply.sh
# Expects the new files staged at /tmp/skyg_firewall.batch,
# /tmp/dnsmasq.new.conf and /tmp/ethers.new.
applyScript = pkgs.writeText {
name = "skyg-apply.sh";
text = ''
set -euo pipefail
BK=/etc/skyg-backups
mkdir -p "$BK"
cp /etc/config/firewall "$BK/firewall.$TS"
cp /etc/dnsmasq.conf "$BK/dnsmasq.conf.$TS"
cp /etc/ethers "$BK/ethers.$TS" 2>/dev/null || true
# --- Firewall: replace the skyg-managed rules ---
for ref in $(uci show firewall | awk -F. '/\.name=.skyg_/{print $1"."$2}'); do
uci -q del "$ref" || true
done
if ! uci batch < /tmp/skyg_firewall.batch; then
echo 'FIREWALL: uci batch failed, restoring'
cp "$BK/firewall.$TS" /etc/config/firewall
exit 1
fi
if ! uci commit firewall; then
echo 'FIREWALL: uci commit failed, restoring'
cp "$BK/firewall.$TS" /etc/config/firewall
exit 1
fi
/etc/init.d/firewall reload
# --- dnsmasq ---
cp /tmp/dnsmasq.new.conf /etc/dnsmasq.conf
if dnsmasq --test; then
/etc/init.d/dnsmasq restart
else
echo 'dnsmasq config invalid, restoring'
cp "$BK/dnsmasq.conf.$TS" /etc/dnsmasq.conf
exit 1
fi
# --- ethers ---
cp /tmp/ethers.new /etc/ethers
echo 'Done'
'';
};
in
config:
@@ -23,10 +71,16 @@ let
DNSMASQ=$(echo "$CONFIG" | ${generator}/bin/openwrt-gen dnsmasq)
ETHERS=$(echo "$CONFIG" | ${generator}/bin/openwrt-gen ethers)
FIREWALL=$(echo "$CONFIG" | ${generator}/bin/openwrt-gen firewall)
echo "Fetching current config from $SERVER..."
CURRENT_DNSMASQ=$(ssh "$SERVER" 'cat /etc/dnsmasq.conf' 2>/dev/null || echo "")
CURRENT_ETHERS=$(ssh "$SERVER" 'cat /etc/ethers' 2>/dev/null || echo "")
CURRENT_FIREWALL_ALL=$(ssh "$SERVER" 'uci export firewall' 2>/dev/null || echo "")
# Keep only the skyg-managed rule blocks (for the diff)
CURRENT_FIREWALL=$(echo "$CURRENT_FIREWALL_ALL" | awk '/^config /{if(have && block ~ /skyg_/) print block; block=$0; have=1; next}{if(have) block=block ORS $0}END{if(have && block ~ /skyg_/) print block}')
# Drop the header comment from the generated firewall for a clean diff
NEW_FIREWALL=$(echo "$FIREWALL" | tail -n +2)
echo ""
echo "$DNSMASQ"
@@ -34,8 +88,6 @@ let
comm -3 <(echo "$CURRENT_DNSMASQ" | sort) <(echo "$DNSMASQ" | sort) | awk '{if ($0 ~ /^</) print "\033[31m"$0"\033[0m"; else if ($0 ~ /^>/) print "\033[32m"$0"\033[0m"; else print}'
echo "=== dnsmasq.conf diff [END] ==="
echo ""
read -p "Looks good? [y/N] " -n 1 -r < /dev/tty; echo
[[ $REPLY =~ ^[Yy]$ ]] || exit 1
echo "$ETHERS"
echo "=== ethers diff [START] ==="
@@ -43,26 +95,48 @@ let
echo "=== ethers diff [END] ==="
echo ""
echo "$NEW_FIREWALL"
echo "=== firewall (skyg rules) diff [START] ==="
comm -3 <(echo "$CURRENT_FIREWALL" | sort) <(echo "$NEW_FIREWALL" | sort) | awk '{if ($0 ~ /^</) print "\033[31m"$0"\033[0m"; else if ($0 ~ /^>/) print "\033[32m"$0"\033[0m"; else print}'
echo "=== firewall (skyg rules) diff [END] ==="
echo ""
read -p "Deploy to $SERVER? [y/N] " -n 1 -r < /dev/tty; echo
[[ $REPLY =~ ^[Yy]$ ]] || exit 1
echo "$DNSMASQ" | ssh "$SERVER" 'cat > /tmp/dnsmasq.new.conf'
echo "$ETHERS" | ssh "$SERVER" 'cat > /etc/ethers'
TS=$(date +%Y%m%d-%H%M%S)
ssh "$SERVER" '
cp /etc/dnsmasq.conf /tmp/dnsmasq.old.conf
cp /tmp/dnsmasq.new.conf /etc/dnsmasq.conf
if dnsmasq --test; then
/etc/init.d/dnsmasq restart
echo "Done"
else
echo "Config invalid, reverting..."
cp /tmp/dnsmasq.old.conf /etc/dnsmasq.conf
exit 1
fi
'
# Stage the apply script and the new config files on the router
ssh "$SERVER" 'cat > /tmp/skyg_apply.sh' < "${applyScript}"
echo "$DNSMASQ" | ssh "$SERVER" 'cat > /tmp/dnsmasq.new.conf'
echo "$ETHERS" | ssh "$SERVER" 'cat > /tmp/ethers.new'
echo "$FIREWALL" | ssh "$SERVER" 'cat > /tmp/skyg_firewall.batch'
# Back up, apply, validate, auto-restore on failure
ssh "$SERVER" "TS=$TS bash /tmp/skyg_apply.sh"
'';
# Dry-run: render the configs locally and write them to .tmp/openwrt-<router>/
# for review. No SSH, no uci, no router changes. Run from the repo root.
# The router name is taken from $SKYG_ROUTER (default glmain).
dryRunScript = pkgs.writeShellScriptBin "openwrt-dry-run" ''
set -euo pipefail
ROUTER="$'{SKYG_ROUTER:-glmain}"
OUTDIR=".tmp/openwrt-$ROUTER"
mkdir -p "$OUTDIR"
CONFIG=$(cat)
echo "$CONFIG" | ${generator}/bin/openwrt-gen dnsmasq > "$OUTDIR/dnsmasq.conf"
echo "$CONFIG" | ${generator}/bin/openwrt-gen ethers > "$OUTDIR/ethers"
echo "$CONFIG" | ${generator}/bin/openwrt-gen firewall > "$OUTDIR/firewall.batch"
echo "Dry-run configs written to $OUTDIR (no router changes made):"
echo " $OUTDIR/dnsmasq.conf"
echo " $OUTDIR/ethers"
echo " $OUTDIR/firewall.batch"
'';
in
{
inherit deployScript;
inherit deployScript dryRunScript;
}
+23 -4
View File
@@ -15,17 +15,19 @@ generator/
│ ├── config.rs # serde Deserialize structs for the input JSON (+ unit tests)
│ ├── network.rs # process_network — expands per-network device lists
│ └── generators/
│ ├── mod.rs # re-exports dnsmasq + ethers
│ ├── mod.rs # re-exports dnsmasq + ethers + firewall
│ ├── dnsmasq.rs # renders dnsmasq.conf (server= + address= lines)
│ └── ethers.rs # renders /etc/ethers (MAC → name/IP)
│ ├── ethers.rs # renders /etc/ethers (MAC → name/IP)
│ └── firewall.rs # renders UCI firewall rules (internet-only networks)
└── target/ # gitignored Cargo build output — ignore it
```
## Usage
```
openwrt-gen dnsmasq < config.json # prints dnsmasq.conf
openwrt-gen ethers < config.json # prints /etc/ethers
openwrt-gen dnsmasq < config.json # prints dnsmasq.conf
openwrt-gen ethers < config.json # prints /etc/ethers
openwrt-gen firewall < config.json # prints UCI firewall rules (uci batch format)
```
## Input shape (`config.rs`)
@@ -33,6 +35,23 @@ openwrt-gen ethers < config.json # prints /etc/ethers
- `generalMappings`: `[{ ip, domains[] }]` — shared domain→IP records.
- `networks`: `{ <network>: [ { mac, name, id?, domains?, justMac? } ] }` — per-network hosts.
- `dnsResolvers`: `[{ ip, port?, name? }]` — upstream `server=` entries for dnsmasq.
- `internetOnly`: `[<network>, ...]` — networks restricted to internet-only access.
## Internet-only firewall rules (`firewall.rs`)
For each network in `internetOnly`, the generator emits UCI `config rule` blocks that DROP
forwarded traffic from that network to the rest of the LAN (`10.0.0.0/16`):
- **IPv4** — one rule per network matching the whole subnet (catches every device on it).
- **IPv6** — one rule per known device MAC. All subnets share a single ULA /64
(`fd59:de0a:bff5::/48`, see `network::ULA_PREFIX`), so subnets are not distinguishable
in IPv6 and blocking is done per known device. An *unknown* IPv6-only device on those
subnets is **not** blocked (inherent to the flat-L2 topology).
Rules are named `skyg_<network>_drop_lan` (IPv4) and `skyg_<network>_drop_lan_v6` (IPv6) so
the deploy script owns exactly these. They are inserted before port-specific ACCEPT rules
(e.g. the existing `sambasharelan`) so the DROPs win. Reverse direction (LAN → restricted
network) stays open, and within-subnet traffic (e.g. cam→cam) is blocked.
## Conventions
+17
View File
@@ -8,6 +8,9 @@ pub struct Config {
pub networks: BTreeMap<String, Vec<Device>>,
#[serde(default, rename = "dnsResolvers")]
pub dns_resolvers: Vec<DnsResolver>,
/// Networks whose devices may only reach the internet, not the rest of the LAN.
#[serde(default, rename = "internetOnly")]
pub internet_only: Vec<String>,
}
#[derive(Deserialize)]
@@ -82,4 +85,18 @@ mod tests {
assert_eq!(resolver.port, Some(853));
assert_eq!(resolver.name, Some("CF".to_string()));
}
#[test]
fn test_internet_only_parsing() {
let json = r#"{"generalMappings": [], "networks": {}, "internetOnly": ["cam", "apl", "iot"]}"#;
let config: Config = serde_json::from_str(json).unwrap();
assert_eq!(config.internet_only, vec!["cam", "apl", "iot"]);
}
#[test]
fn test_internet_only_defaults_empty() {
let json = r#"{"generalMappings": [], "networks": {}}"#;
let config: Config = serde_json::from_str(json).unwrap();
assert!(config.internet_only.is_empty());
}
}
@@ -60,7 +60,7 @@ mod tests {
domains,
just_mac: false,
}]);
Config { general_mappings: vec![], networks, dns_resolvers: vec![] }
Config { general_mappings: vec![], networks, dns_resolvers: vec![], internet_only: vec![] }
}
#[test]
@@ -80,6 +80,7 @@ mod tests {
}],
networks: BTreeMap::new(),
dns_resolvers: vec![],
internet_only: vec![],
};
let result = generate(&config);
assert!(result.contains("address=/gw.local/192.168.1.1\n"));
@@ -95,6 +96,7 @@ mod tests {
port: Some(853),
name: Some("CF".to_string()),
}],
internet_only: vec![],
};
let result = generate(&config);
assert!(result.contains("server=1.1.1.1#853 # CF\n"));
@@ -106,6 +108,7 @@ mod tests {
general_mappings: vec![],
networks: BTreeMap::new(),
dns_resolvers: vec![],
internet_only: vec![],
};
assert!(generate(&config).is_empty());
}
@@ -40,7 +40,7 @@ mod tests {
domains: None,
just_mac,
}]);
Config { general_mappings: vec![], networks, dns_resolvers: vec![] }
Config { general_mappings: vec![], networks, dns_resolvers: vec![], internet_only: vec![] }
}
#[test]
@@ -69,6 +69,7 @@ mod tests {
general_mappings: vec![],
networks: BTreeMap::new(),
dns_resolvers: vec![],
internet_only: vec![],
};
assert!(generate(&config).is_empty());
}
@@ -0,0 +1,132 @@
use crate::config::Config;
use crate::network::{prefix_for, process_network, ULA_PREFIX};
/// Renders UCI firewall rules (in `uci batch` format) that restrict the networks
/// listed in `config.internet_only` to internet-only access.
///
/// For each restricted network:
/// - IPv4: a single DROP rule matching the whole subnet (catches all devices on it).
/// - IPv6: a DROP rule per known device MAC (all subnets share one /64, so subnets
/// are not distinguishable in IPv6).
///
/// Rules are named `skyg_<network>_drop_lan[_v6]` so the deploy script can manage
/// exactly the rules it owns. They are inserted before port-specific ACCEPT rules
/// (e.g. the existing `sambasharelan`) so the DROPs win.
pub fn generate(config: &Config) -> String {
let mut out = String::new();
out.push_str("# Managed by skyg openwrt — do not edit by hand\n");
for network in &config.internet_only {
let devices = match config.networks.get(network) {
Some(d) => d,
None => continue, // unknown network name; skip
};
// IPv4: block the whole subnet from reaching the rest of the LAN.
let v4_prefix = prefix_for(network);
let v4_subnet = format!("{}.0/24", v4_prefix.trim_end_matches('.'));
out.push_str(&format!(
"config rule\n\
\toption name 'skyg_{net}_drop_lan'\n\
\toption src 'lan'\n\
\toption dest 'lan'\n\
\toption src_ip '{subnet}'\n\
\toption dest_ip '10.0.0.0/16'\n\
\toption target 'DROP'\n\
\toption family 'ipv4'\n",
net = network,
subnet = v4_subnet,
));
// IPv6: block each known device's MAC from reaching the ULA LAN.
for pd in process_network(network, devices) {
out.push_str(&format!(
"config rule\n\
\toption name 'skyg_{net}_drop_lan_v6'\n\
\toption src 'lan'\n\
\toption dest 'lan'\n\
\toption src_mac '{mac}'\n\
\toption dest_ip '{ula}'\n\
\toption target 'DROP'\n\
\toption family 'ipv6'\n",
net = network,
mac = pd.device.mac,
ula = ULA_PREFIX,
));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Config, Device};
use std::collections::BTreeMap;
fn config_with_devices(internet_only: Vec<String>) -> Config {
let mut networks = BTreeMap::new();
networks.insert(
"cam".to_string(),
vec![
Device {
mac: "aa:bb:cc:dd:ee:01".to_string(),
name: "doorbell".to_string(),
id: None,
domains: None,
just_mac: false,
},
Device {
mac: "aa:bb:cc:dd:ee:02".to_string(),
name: "cam2".to_string(),
id: None,
domains: None,
just_mac: false,
},
],
);
Config {
general_mappings: vec![],
networks,
dns_resolvers: vec![],
internet_only,
}
}
#[test]
fn test_no_internet_only_is_empty() {
let config = config_with_devices(vec![]);
let result = generate(&config);
assert!(result.lines().count() == 1); // only the header comment
}
#[test]
fn test_ipv4_subnet_rule() {
let config = config_with_devices(vec!["cam".to_string()]);
let result = generate(&config);
assert!(result.contains("skyg_cam_drop_lan"));
assert!(result.contains("option src_ip '10.0.13.0/24'"));
assert!(result.contains("option dest_ip '10.0.0.0/16'"));
assert!(result.contains("option target 'DROP'"));
assert!(result.contains("option family 'ipv4'"));
}
#[test]
fn test_ipv6_per_mac_rules() {
let config = config_with_devices(vec!["cam".to_string()]);
let result = generate(&config);
assert!(result.contains("skyg_cam_drop_lan_v6"));
assert!(result.contains("option src_mac 'aa:bb:cc:dd:ee:01'"));
assert!(result.contains("option src_mac 'aa:bb:cc:dd:ee:02'"));
assert!(result.contains("option dest_ip 'fd59:de0a:bff5::/48'"));
assert!(result.contains("option family 'ipv6'"));
}
#[test]
fn test_unknown_network_is_skipped() {
let config = config_with_devices(vec!["nonexistent".to_string()]);
let result = generate(&config);
assert!(result.lines().count() == 1); // only the header comment
}
}
@@ -1,2 +1,3 @@
pub mod dnsmasq;
pub mod ethers;
pub mod firewall;
+2 -1
View File
@@ -18,8 +18,9 @@ fn main() {
let output = match cmd.as_str() {
"dnsmasq" => generators::dnsmasq::generate(&config),
"ethers" => generators::ethers::generate(&config),
"firewall" => generators::firewall::generate(&config),
_ => {
eprintln!("usage: openwrt-gen <dnsmasq|ethers>");
eprintln!("usage: openwrt-gen <dnsmasq|ethers|firewall>");
std::process::exit(1);
}
};
+9
View File
@@ -2,6 +2,10 @@ use crate::config::Device;
pub const ROOT_DOMAIN: &str = "internal";
// IPv6 ULA prefix assigned to br-lan (network.lan.ip6prefix). All subnets share
// this single /64, so IPv6 internet-only blocking is done per-device MAC.
pub const ULA_PREFIX: &str = "fd59:de0a:bff5::/48";
pub static IP_PREFIXES: &[(&str, &str)] = &[
("lab", "10.0.10."),
("k3s", "10.0.11."),
@@ -99,4 +103,9 @@ mod tests {
let result = process_network("devices", &devices);
assert!(result[0].just_mac);
}
#[test]
fn test_ula_prefix_constant() {
assert_eq!(ULA_PREFIX, "fd59:de0a:bff5::/48");
}
}