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

+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");
}
}