# Firewall and NAT Domain Model Reference This document describes the domain representations, rule structures, port specifications, and safety invariants for packet filtering and NAT in `nx9-wg`. --- ## 1. Domain Entities ### A. Firewall Rule (`FirewallRule`) Represents an individual packet filtering rule in the database: | Field | Type | Description | | :--- | :--- | :--- | | `id` | `Uuid` | Unique identifier (Primary Key) | | `name` | `String` | Human-readable identifier (e.g., `allow-dns-udp`) | | `direction` | `FirewallDirection` | `In`, `Out`, or `Forward` | | `protocol` | `FirewallProtocol` | `Tcp`, `Udp`, `TcpUdp`, `Icmp`, or `Any` | | `action` | `FirewallAction` | `Accept`, `Drop`, or `Reject` | | `source` | `Option` | Source CIDR or IP (e.g., `10.100.0.0/24`) | | `destination` | `Option` | Destination CIDR or IP | | `source_port` | `Option` | Specific source port | | `destination_port`| `Option` | Specific destination port | | `port_range` | `Option` | Single port, list, or range (`53`, `80,443`, `8000-8100`) | | `interface_id` | `Option` | Optional interface association | | `peer_id` | `Option` | Optional cryptographic peer association | | `priority` | `i32` | Rule evaluation priority (lower numbers evaluate first) | | `enabled` | `bool` | Active state flag | --- ## 2. Port Specification Syntax The `port_range` field supports three RFC-compliant formats: 1. **Single Port**: `80` $\rightarrow$ Evaluates as `dport 80` 2. **Multi-Port Comma List**: `80,443,8080` $\rightarrow$ Evaluates as `dport { 80, 443, 8080 }` 3. **Port Range**: `8000-8100` $\rightarrow$ Evaluates as `dport 8000-8100` --- ## 3. Protocol Grouping - **`Tcp`**: Filters IPv4/IPv6 TCP packets. - **`Udp`**: Filters IPv4/IPv6 UDP packets. - **`TcpUdp`**: Translates to `{ tcp, udp }` protocol match in a single atomic rule. - **`Icmp`**: Translates to `icmp` (IPv4) or `icmpv6` (IPv6). - **`Any`**: Omits protocol match, applying action to all transport protocols. --- ## 4. NAT Masquerade Domain Configuration NAT masquerading is governed by key-value appliance settings in SQLite: - **`enable_nat`**: Boolean string (`"true"` / `"false"`). When enabled, all active managed WireGuard subnets are masqueraded outbound to the host WAN interface. - **Dynamic Subnet Calculation**: The reconciliation engine queries enabled Interface address CIDRs and enabled Subnet Network CIDRs, then generates dedicated masquerade rules for each unique subnet. Interface addresses remain the WireGuard transport identity; Network CIDRs are the peer allocation domains. --- ## 5. Domain Validation & Invariants 1. **Priority Uniqueness & Ordering**: Rules are sorted by `priority ASC, created_at ASC` ensuring determinism. 2. **CIDR Validation**: Source and destination values must parse as valid IPv4 or IPv6 CIDRs. 3. **Port Bounds**: Port numbers must fall within standard bounds (`1..=65535`). In ranges `A-B`, `A <= B` is strictly enforced.