diff --git a/GOTCHAS.md b/GOTCHAS.md index 2c351167c..6103a5b4d 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -203,6 +203,7 @@ An OPNsense migration can move a legacy element into an `` model and d - **Instance (fixed):** OPNsense 26.1 moved the IPv6, offload and VLAN filter settings from `` into `` (`Interfaces/Migrations/SET1_0_0.php`), turning `ipv6allow` into the inverted `disableipv6`. On a migrated config all five fields read as off, so FIREWALL-006 passed on firewalls with IPv6 enabled. `applyInterfaceSettings` reads the block now. OPNsense 26.1 and later read only the block, so it wins over anything left in ``. Without the block the converter falls back to ``, which is right for older configs but can disagree with a 26.1.0 config whose migration failed (a `yes` broke it until 26.1.1); OPNsense then treats IPv6 as allowed and offloading as on. - **Instance (fixed):** OPNsense 24.1 moved gateways from `` into `` (`Routing/Migrations/M1_0_0.php`) and deleted the originals, so a config whose gateways had migrated exported none. `convertGatewayItems` reads the model when it holds a gateway and `` otherwise, the rule the vendor's `gatewayIterator` follows; a `` with no child element does not count (§3.4). Legacy gateways left beside a model that holds one, as after a failed migration or a hand edit, are ignored with a Medium warning naming them, as the converter warns wherever it ignores something the config says (§3.6). Gateway groups stayed under ``. The model writes `defaultgw` and `monitor_disable` as `0` where the 23.7 page left the element out, and `common.Gateway` keeps both as text, so `gatewayFlag` reduces them to `1` or empty for either store. Copied as they stand, every gateway that is not the default would export `"defaultGw":"0"`. The stores read an absent `monitor_disable` differently: the model defaults it to `1`, which turns monitoring off, and `gatewayIterator` fills in `0` for a legacy gateway, so `Gateway.MonitorDisable` is a pointer (§3.2). `convertGateways` fills in `weight` and `ipprotocol` when they are empty, as current releases read them: the model defaults them to `1` and `inet`, OPNsense fills in `inet` for a legacy gateway with an absent or empty `ipprotocol` from 20.1.7, and gateway groups read an empty weight as `1` from 19.7. Before those releases such a legacy gateway had no address family and an empty weight stayed empty, and the export shows `inet` and `1` for them too. The exception is an empty `` in the model, which stays empty on the firewall and which opnDossier cannot tell from an absent one; OPNsense never writes one, as the field is required. The model's default `interface` of `wan` is applied to a model item that leaves the element out, and not to a legacy gateway, to which `gatewayIterator` gives none. An empty `` in the model stays empty on the firewall and reads as `wan` here, the same approximation as for `ipprotocol`, since the field is required and OPNsense never writes one. `fargw` goes through `modelFlagSet` as well: the firewall tested it with `isset()` up to 24.1.7 and with `!empty()` from 24.1.8, and the two differ only on `0` and an empty element. `disabled` does in the model only: `GatewayModelItem.Disabled` shadows the `BoolFlag` on the type pfSense shares with a `*string`. The firewall reads it with `!empty()`, which a `BoolFlag` reads the reverse of for an empty ``, and the pointer keeps an empty `` apart from an absent one, so that it is written back. Whether an item holding only `` is a gateway is decided by `Gateway.HasChildElement` (§3.4), not by this field. Under `` it is still the `BoolFlag`, so hand-written text can read the reverse of the firewall's `!empty()`, as `` and `no` do. The model keeps its items by uuid, so of two with one uuid the firewall holds the later, at the place of the earlier, and `modelGateways` does the same with a warning. An item with no uuid attribute gets a fresh one on every release. An empty uuid or `0` depends on the release: from 25.7 the loader tests `empty()`, which holds for both, and gives the item a fresh uuid, while through 25.1.12 it tests `isset()` and uses the attribute as the key, so two such items collide and the firewall holds the later. The model version is `1.0.0` on both sides, so `modelGateways` keeps both with a warning, which over-reports on the older releases. `GatewayModelItem.UUID` is a pointer to keep absent apart from empty (§3.2). The uuid is on `GatewayModelItem` rather than `Gateway` because `gatewayIterator` ignores one under ``, and because an item with a uuid and no child element must stay a placeholder. +- **Instance (fixed): an element can outlive every reader.** OPNsense core stopped running an SNMP agent at 17.1, the os-snmp plugin that went on reading the legacy top-level `` was removed at 19.1, and os-net-snmp, which replaced it, reads only ``. Every factory default up to 25.7 still wrote `public`, and nothing removes it, so most upgraded configs carry a block that no release starts an agent from: each agent that read it also required ``, which the default never had. Read as live, the block failed FIREWALL-045, FIREWALL-046 and STIG V-206690 on firewalls with no agent, while, on a config without the legacy block, a net-snmp agent answering `public` on WAN passed all three because its model was never read. `convertSNMP` reports net-snmp when its `` is `1`, and otherwise a legacy block only when it carries ``, with a Low warning, since the config does not record whether the release still runs that agent. A plugin's model is not in the core tree: take its mount, versions and element names from the plugin repository, and take what an absent element means from the plugin's templates, which read the raw config, rather than from its model defaults. Consumers ask `SNMPConfig.IsEnabled()` instead of testing the community, since an SNMPv3-only agent has none. Text that names community authentication still tests the community: red mode tells a WAN-exposed agent with none neither to migrate to SNMPv3 nor that it relies on a community. - **Detection:** for each OPNsense release, check what its migrations do to the elements the schema reads: a `post()` that unsets a legacy path (`src/opnsense/mvc/app/models/OPNsense/*/Migrations/`), or a model whose `` went up and whose field list lost or renamed a field, since the migration replaces the model's whole node. Test the migrated shape by rewriting a fixture the way the migration does, as `TestConverter_InterfaceSettings_ReadFromMigratedBlock` does, rather than generating XML from the schema. - **Pin the model version.** The new block's element names belong to its model version, so the converter warns on a `version` attribute it does not recognize, as it does for Unbound. See §18.1 for the risk. @@ -370,6 +371,7 @@ Only `blue` mode runs `RunComplianceChecks`. Red mode ignores `SelectedPlugins` - **Findings vs. metadata split:** Only three of the five methods append to `report.Findings`. `addWANExposedServices` (the primary producer: one Finding + `AttackSurface` per WAN-reachable WebGUI/SSH/SNMP service), `addWeakNATRules` (WAN-reachable inbound NAT port-forwards), and `addAttackSurfaces` (WAN-reachable shared-engine hygiene observations reframed as exposure, de-duped by `Component`). `addAdminPortals` and `addEnumerationData` emit **structured metadata only** (portal inventory tagged by reachability; recon counts) — deliberately NOT Findings, to avoid double-counting an exposure already surfaced by a Finding-producing method. Every WAN exposure still lands in Findings, but via the method that owns that exposure class: firewall-local management-service exposure (WebGUI/SSH/SNMP) via `addWANExposedServices`, and inbound NAT port-forward exposure independently via `addWeakNATRules`. The metadata-only methods never introduce an exposure that one of those two does not already surface as a Finding. - **WAN-exposed = correlation, not enabled-alone:** a firewall-local management service (WebGUI/SSH/SNMP) is WAN-reachable only when enabled AND a WAN-reachable firewall pass rule permits its port (`wanRulePermitsPort` / `analysis.RulePortPermits`, which the security score's `hasManagementOnWAN` shares). Port matching biases to over-report (empty/`any`/ranges/lists match by containment; an unresolvable port *alias* is treated as permitting — never under-report a possible exposure). - **NAT rules never correlate against firewall-local services:** `wanRulePermitsPort` (used only by `serviceReachability` for WebGUI/SSH/SNMP) deliberately never counts `device.NAT.InboundRules` as exposure. An inbound NAT rule forwards WAN traffic to `InboundNATRule.InternalIP`, normally a different host than the firewall itself, so a NAT rule sharing an external port with a management service is never evidence that the firewall's OWN service is exposed. A forward can target the firewall, but the evidence is then the filter rule that passes it, never the forward. An earlier version correlated NAT rules here too, producing a false positive: a NAT rule forwarding WAN port 22 to an unrelated internal host's SSH would flag the firewall's own SSH daemon (also on port 22) as WAN-exposed even with no pass rule ever targeting the firewall directly. NAT-forward exposure is reported separately and correctly by `addWeakNATRules`. See `TestRedMode_NATForward_DoesNotExposeFirewallLocalService`. The filter rule a port forward stores for itself does not count either: pf matches it after rdr, against the forward's target, so `wanRulePermitsPort` skips a rule whose destination is a forward's `InternalIP` when that target is a literal address or network holding no loopback address, interface address, DHCP alias address or virtual IP (`forwardsToAnotherHost`). The destination is the whole test, so it covers the same rule with no link, as OPNsense's "Add unassociated filter rule" wrote it up to 25.7, and `AssociatedRuleID` is not read: from 26.1 deleting a forward leaves its rule behind with the link, so a link alone proves nothing. A network that holds one of those addresses keeps the rule, since traffic to that address passes the rule too, so a forward to a directly attached network still reads as exposing the service. A rule to an alias is skipped when a forward targets that alias, since both vendors copy an alias target onto the rule as it stands, unless a member of the alias, or of an alias it names, is or spans one of those addresses (`aliasHoldsFirewallAddress`). That walk reads `Members` directly rather than through `Resolve`, which stops on a network group (§23.1). The members the config holds are the only evidence: an alias whose members are fetched at runtime, such as a URL table, has none to test and is skipped, and a hostname with a domain tells nothing. A wildcard network such as `192.168.0.1/0.0.255.0` is read bit by bit, as OPNsense's `net_wildcard_iterator` expands it. A name no alias defines keeps the rule, both as a `` and as a member of a host, network or network group alias (`namesUnstoredTable`). OPNsense generates `__lan_network`, which holds the firewall's own address, and static tables such as `bogons`, and writes none of them to `config.xml`, so such a member can hold anything. A hostname with no domain has the same shape and is over-reported the same way. The inbound rules can only take a rule away there, never add one. A rule of its own to an address, network or alias no forward targets still counts, since the firewall may hold an address the config does not record, such as a DHCP lease. An address the config records anywhere but on an interface or as a virtual IP, such as a tunnel's inner address, is not read, so a forward to it reads as one to another host. pfSense virtual IPs are not converted yet (`pfsense.KnownGaps`), so on pfSense a forward to a CARP or IP alias address reads the same way. A forward that stores no filter rule (the Pass association, which pf gets as `rdr pass`, and on the 26.1 model `` set to `pass` or `rule`) gives `wanRulePermitsPort` nothing to read, so one to the firewall's own address reports no exposure at all. +- **A port forward can keep a loopback SNMP agent's verdict:** the bullet above holds for `wanRulePermitsPort`, but one step outside it reads `device.NAT.InboundRules` too. An os-net-snmp agent bound only to loopback is set Local after every other step (`applySNMPListen`), unless an enabled forward that can redirect UDP port 161 targets a loopback address or a network or range spanning one, `(self)` (This Firewall, which pf reads as every address of every interface, those of `lo0` included), an alias that may hold one, the net or address of an interface whose own address is a loopback address, such as `lo0`, or a name no alias or interface defines that has the shape of an alias name (`forwardsToLoopback`). pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. An alias that may hold one includes a URL alias, a URL table, a URL table in JSON format and an external alias, whose addresses OPNsense gets at runtime, a host alias holding a hostname, which OPNsense resolves through DNS when it loads the alias (`resolvedThroughDNS`), and an alias naming one at any depth (`aliasNamesRuntimeTable`). The read above treats such an alias the other way, as holding no address of the firewall, and `aliasHoldsFirewallAddress` keeps that reading for it. The net or address of any other interface, such as `lan` or `lanip`, does not count: pf redirects such a forward to that interface's network or address, where the agent does not listen. That reading of a target is the one `ForwardRule.php` applies from 26.1.2. Through 26.1.1 it maps a target only when an alias of that name exists, of any type, and disables a forward to any other name that is no address or network as an invalid target, `(self)` and interface names among them, so on those releases a forward to `(self)`, or to `lo0` when no alias has that name, keeps the verdict although it redirects nothing, which over-reports. The forward never makes the agent reachable by itself: it only keeps the agent from being set Local, and the agent keeps the reachability the earlier steps gave it. Neither the forward's interface, nor ``, nor whether the target's address family is one the agent listens on is read there, so a LAN forward (`TestSNMPAgent_ForwardInterfaceIsNotRead`), a forward on a firewall with packet filtering off, or a forward to `::1` for an agent bound to `127.0.0.1` keeps the verdict too, which over-reports. The key and `ip` form is matched for every interface, although OPNsense maps it only for wan, lan and optN and disables a forward to any other such name no alias defines as an invalid target, so a forward to `lo0ip` keeps the verdict too, which also over-reports. Do not remove `forwardsToLoopback` as a regression of the bullet above: without it, a WAN forward of UDP 161 to loopback with the rule that passes it reports no exposure, and `TestSNMPAgent_PortForwardToLoopbackKeepsWANExposure` fails. - **Web GUI port comes from the unified model, not a hardcode:** `common.WebGUI.Port` carries the configured web-configurator port. Both the OPNsense and pfSense parsers populate it from `` when the element is present in `config.xml`; the 443/80 protocol default applies only when the configured port is absent (either vendor). Red analysis reads `device.System.WebGUI.Port` via `parsePort` rather than assuming 443/80, so a box on a custom GUI port is analyzed correctly regardless of vendor. New device parsers should populate this field when the platform exposes a GUI port. - **ExploitNotes safety:** red `ExploitNotes` carry impact/context only (never weaponized/step-by-step guidance). Enforced by `FindInstructionalContent` (`exploit_notes_safety.go`) run over the actual generated notes plus a golden-file gate — not authoring discipline. `--audit-blackhat` selects the sharper-tone variant (red mode only; rejected in `PreRunE` for blue mode) and adjusts tone only — the denylist safety invariant holds for both tone variants. - **NAT correlation is an intentional over-report:** an inbound NAT rule is treated as WAN-reachable when any enabled WAN pass rule exists (not one correlated by port to that specific forward). This is a deliberate safe-direction choice — precise per-rule correlation would risk under-reporting a real exposure, the wrong failure mode for a security audit. diff --git a/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md b/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md index c0e527d7b..4874b2875 100644 --- a/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md +++ b/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md @@ -2,6 +2,8 @@ **Date**: 2026-06-27 **Status**: accepted **Deciders**: UncleSp1d3r (maintainer), Claude Code (Opus 4.8) +> Updated 2026-11-13: the OPNsense findings below are corrected, and the plugin namespace is now parsed. See [Update (2026-11-13)](#update-2026-11-13). + ## Context opnDossier redacts the SNMP community string in statistics and exports. A scope question (deduplicating that redaction) raised a follow-on: should redaction also cover SNMPv3 authentication and privacy secrets? Answering responsibly required examining the upstream OPNsense and pfSense source to determine exactly where SNMP credentials are persisted in `config.xml`. This ADR records those verified findings so future SNMP parser, statistics, and sanitizer work starts from facts rather than assumptions. The findings are the durable artifact here; the scoping choice they enabled is a consequence, not the decision. @@ -56,6 +58,15 @@ Scope opnDossier's SNMP credential handling to what the vendor source actually p - **Schema version drift.** The plugin model element names/versions can change across OPNsense releases (general v1.0.5, user v1.0.1 at time of writing). Re-verify against a real `config.xml` when implementing ingestion (cf. GOTCHAS §18.1 version-pinning). +## Update (2026-11-13) + +Two findings above were incomplete, and the parser now reads the plugin namespace. + +- OPNsense core has not run an SNMP agent since 17.1. From 17.1 to 18.7 the `os-snmp` plugin (`net-mgmt/snmp`, removed in 19.1) ran `bsnmpd` from the legacy `` block, and like core before it, only when `` was set. From 19.1 the only agent is `os-net-snmp`. Factory defaults kept writing `public` without `` up to 25.7, so upgraded configs carry a block no agent reads. +- opnDossier now parses `` (`pkg/schema/opnsense/netsnmp.go`), pins general model versions 1.0.0, 1.0.1 and 1.0.3 to 1.0.7 and user model versions 1.0.0 and 1.0.1, and maps an enabled agent into `SNMPConfig`, including SNMPv3 usernames and read-write access. A model carrying any other version, including general 1.0.2, which the plugin never used, is still read and draws a Medium conversion warning. The `password` and `enckey` elements are not bound in the schema, so model-based features never see them. +- pfSense, like OPNsense up to 18.7, starts bsnmpd only when `` is present (`config_path_enabled('snmpd')`, an `isset()` test). Both converters now report an `` block only when it carries ``, and set `SNMPConfig.Enabled` for a running agent. +- The consequence above that the namespace "remains unparsed" no longer holds; the decision on which credentials exist is unchanged, and SNMPv3 secrets are still kept out of the model. + ## Sources - `opnsense/plugins` — `net-mgmt/net-snmp/src/opnsense/mvc/app/models/OPNsense/Netsnmp/General.xml`, `.../User.xml`; template target `snmpd_usercredentials.conf` diff --git a/docs/compliance-standards.md b/docs/compliance-standards.md index cb85d0d2e..f20ae15f0 100644 --- a/docs/compliance-standards.md +++ b/docs/compliance-standards.md @@ -221,10 +221,10 @@ The following controls are organized by security domain and represent the full p ##### SNMP Security -| Control ID | Title | Severity | Implementability | Description | -| ------------ | ---------------------------- | -------- | ---------------- | ----------------------------------------------------------------------------- | -| FIREWALL-045 | SNMP Disabled if Unused | Medium | Full | SNMP service disabled if `ROCommunity` is empty and no operational need | -| FIREWALL-046 | No Default Community Strings | High | Full | SNMP community strings changed from well-known defaults ("public", "private") | +| Control ID | Title | Severity | Implementability | Description | +| ------------ | ---------------------------- | -------- | ---------------- | ------------------------------------------------------------------------------- | +| FIREWALL-045 | SNMP Disabled if Unused | Medium | Full | Fails whenever an SNMP agent is enabled; operational need is not assessed | +| FIREWALL-046 | No Default Community Strings | High | Full | The running agent's community is not a well-known default ("public", "private") | ##### VPN Configuration @@ -306,7 +306,7 @@ The audit engine performs the following checks per plugin: 2. **Packet Filtering (V-206674)** - Scans pass rules for overly broad source/destination addresses (any, 0.0.0.0/0, ::/0, RFC 1918 ranges) and flags rules without specific port restrictions. -3. **Service Hardening (V-206690)** - Checks for SNMP with community strings, Unbound DNS with DNSSEC stripping, more than 2 DHCP interfaces, and configured load balancer services. +3. **Service Hardening (V-206690)** - Checks for an enabled SNMP agent, more than 2 DHCP interfaces, and configured load balancer services. 4. **Logging Configuration (V-206682)** - Analyzes syslog configuration for system and auth logging. Returns comprehensive, partial, not-configured, or unable-to-determine status. Finds non-compliant when syslog is disabled, logging is only partial, or logging status cannot be determined (e.g., rules exist but syslog is not configured). diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 76e6b7f74..568711dfb 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -336,6 +336,26 @@ DHCP scopes are a flat array with one entry per interface. | `Hostname` | `string` | `dhcp[].staticLeases[].hostname` | Assigned hostname | | `Description` | `string` | `dhcp[].staticLeases[].description` | Description | +### SNMP + +Both converters fill these fields only for an agent they report as running, and leave the struct empty otherwise. On OPNsense that is the os-net-snmp plugin when `` is `1`, and otherwise a legacy `` block that carries ``, which only OPNsense up to 18.7 starts and which is reported with a conversion warning because the config does not record the release; a legacy block without ``, which factory defaults wrote up to 25.7, starts no agent. On pfSense it is an `` block that carries ``. `SNMPConfig.IsEnabled()` also counts a community alone, for a hand-built device that sets only `ROCommunity`. + +| Field | Type | JSON Key | Description | +| ----------------- | ------------ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ROCommunity` | `string` | `snmp.roCommunity` | Read-only community (v1/v2c); redacted with `--redact` | +| `SysLocation` | `string` | `snmp.sysLocation` | System location | +| `SysContact` | `string` | `snmp.sysContact` | System contact | +| `Enabled` | `bool` | `snmp.enabled` | An SNMP agent runs | +| `ListenAddresses` | `[]string` | `snmp.listenAddresses` | Bound addresses, filled only for the OPNsense os-net-snmp agent, where empty means its default: every IPv4 address and the IPv6 loopback. No bind address is read for an `` agent. Red mode does not report an os-net-snmp agent bound only to loopback as WAN-exposed unless an enabled port forward that can redirect UDP port 161, where that agent answers SNMP, targets a loopback address, a network spanning one, or a name that may hold one (GOTCHAS.md section 8.4 lists them); an `` agent is judged by the firewall rules alone | +| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | + +#### SNMPUser + +| Field | Type | JSON Key | Description | +| ----------- | -------- | ------------------------ | ----------------- | +| `Username` | `string` | `snmp.users[].username` | SNMPv3 user name | +| `ReadWrite` | `bool` | `snmp.users[].readWrite` | Read-write access | + ### DNS (Unbound) | Field | Type | JSON Key | Description | diff --git a/docs/development/xml-structure-research.md b/docs/development/xml-structure-research.md index f43da0d8c..907c153e9 100644 --- a/docs/development/xml-structure-research.md +++ b/docs/development/xml-structure-research.md @@ -41,6 +41,7 @@ Element existing = true, absent = false. Content is irrelevant. | `` | `` (OPNsense filter, legacy and model) | `parseBool,quick` (`!empty`): content matters, `` is not quick. Both `FirewallFilterRule.Quick` and the legacy `Rule.Quick` are `*string` (#976) | | `` | `` | config.xml.sample: self-closing | | `` | `` | config.xml.sample: self-closing | +| `` | `` | `isset()` (OPNsense up to 18.7), `config_path_enabled('snmpd')` (pfSense); `Snmpd.Enable` is `*string` | | `` | `` (filter) | `isset($rule['tcpflags_any'])` | | `` | `` (filter) | `isset($rule['nopfsync'])` | | `` | `` (filter) | `$filterent['allowopts'] = true` | @@ -78,6 +79,8 @@ Element contains `1`, `yes`, or a specific value. Absent or empty = false. | ------------------------ | ------------------------ | ------ | ---------- | ------------------------------------------------------------------------------------------- | | `` | `` | `1` | varies | pfSense: presence-based (see §1a). OPNsense: value-based. pfSense parser uses BoolFlag fork | | `` | `` | `1` | varies | pfSense: presence-based (see §1a). OPNsense: value-based. pfSense parser uses BoolFlag fork | +| `` | `` | `1` | `string` | os-net-snmp agent and users; raw `1` only, absent or empty is off | +| `` | `` | `1` | `string` | SNMPv3 user read-write access; raw `1` only | | `` | `` | `1` | `string` | Block private networks | | `` | `` | `1` | `string` | Block bogon networks | | `` | `` | `1` | `BoolFlag` | Allow DNS override (migrated from int) | diff --git a/docs/firewall-security-controls-reference.md b/docs/firewall-security-controls-reference.md index d2134ae37..a69f2dad5 100644 --- a/docs/firewall-security-controls-reference.md +++ b/docs/firewall-security-controls-reference.md @@ -407,10 +407,12 @@ The following controls are planned for future releases, organized by security do ### SNMP Security -| Control ID | Title | Severity | Description | -| ------------ | ---------------------------- | -------- | ------------------------------------------------------ | -| FIREWALL-045 | SNMP Disabled if Unused | Medium | SNMP service disabled when no operational need | -| FIREWALL-046 | No Default Community Strings | High | SNMP community strings changed from "public"/"private" | +| Control ID | Title | Severity | Description | +| ------------ | ---------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| FIREWALL-045 | SNMP Disabled if Unused | Medium | Fails whenever an SNMP agent is enabled (`SNMP.IsEnabled()`); operational need is not assessed | +| FIREWALL-046 | No Default Community Strings | High | The running agent's community is not "public"/"private" | + +Both controls read the agent the converter reports. On OPNsense that is the os-net-snmp plugin when `1` is set, and otherwise a legacy `` block that carries ``. Only OPNsense up to 18.7 starts such a block, but the config does not record the release, so the converter reports it as a running agent and adds a conversion warning. On pfSense it is `` with ``. A `` block with a community and no ``, such as the one OPNsense factory defaults wrote up to 25.7, starts no agent, so both controls pass unless another agent is enabled. An agent with SNMPv3 users and no community fails FIREWALL-045 and passes FIREWALL-046. ### VPN Configuration diff --git a/docs/solutions/logic-errors/wan-exposure-nat-inbound-rules-wrongly-correlated-with-firewall-service.md b/docs/solutions/logic-errors/wan-exposure-nat-inbound-rules-wrongly-correlated-with-firewall-service.md index 8b7725768..710a36575 100644 --- a/docs/solutions/logic-errors/wan-exposure-nat-inbound-rules-wrongly-correlated-with-firewall-service.md +++ b/docs/solutions/logic-errors/wan-exposure-nat-inbound-rules-wrongly-correlated-with-firewall-service.md @@ -41,6 +41,8 @@ Caught by CodeRabbit on PR #695. > **Later change:** `wanRulePermitsPort` reads `device.NAT.InboundRules` again, through `forwardsToAnotherHost`, to recognize the filter rule a port forward stores for itself. The rules there can only take a pass rule out of the count, never add one, so a NAT rule is still never evidence of exposure and the invariant on this page holds. Do not remove that read as a regression of this bug. The code and comments quoted below are as they stood in #695; `GOTCHAS.md` §8.4 has the current behavior. +> **Another read:** what the note above concludes holds for the read through `forwardsToAnotherHost` only. `applySNMPListen` reads `device.NAT.InboundRules` too, through `forwardsToLoopback`. An enabled forward that can redirect UDP port 161 and may target loopback (`GOTCHAS.md` section 8.4 lists the targets that count) keeps an os-net-snmp agent bound only to loopback from being set Local, since pf rewrites the destination before the packet is delivered. The forward never makes the agent reachable by itself: the agent keeps the reachability the earlier steps gave it, such as from a WAN pass rule for UDP 161. For that agent, though, the forward is what lets that rule count, so here a NAT rule does bear on whether a firewall-local service is reported as exposed. Do not remove that read as a regression of this bug either. + Before, `wanRulePermitsPort` iterated both `device.FirewallRules` and `device.NAT.InboundRules`: ```go diff --git a/docs/user-guide/device-support-matrix.md b/docs/user-guide/device-support-matrix.md index 1d3a6bb42..751daf99d 100644 --- a/docs/user-guide/device-support-matrix.md +++ b/docs/user-guide/device-support-matrix.md @@ -55,6 +55,8 @@ If a pfSense feature area is listed as **Not yet supported**, opnDossier warns y ## What this means in practice +SNMP is reported only for an agent the configuration starts. On OPNsense that is the os-net-snmp plugin when it is enabled; on both platforms an `` block counts only when it carries ``, so a leftover community such as the old OPNsense default `public` is not reported as a running agent. + When you process an **OPNsense** configuration, you can expect the broadest coverage across system, networking, security, and service sections. When you process a **pfSense** configuration, you can still rely on opnDossier for the major day-to-day areas most operators care about, including interfaces, VLANs, firewall rules, NAT, DHCP, DNS, VPN, routing, certificates, users, groups, syslog, cron jobs, and revision history. diff --git a/docs/xml-field-reference.md b/docs/xml-field-reference.md index 10d2de9c9..05f2ffb40 100644 --- a/docs/xml-field-reference.md +++ b/docs/xml-field-reference.md @@ -170,6 +170,46 @@ The `max-src-conn-rate` field uses the format `connections/seconds` (e.g., `15/5 ``` +## SNMP Agent + +On OPNsense from 19.1 the SNMP agent is the os-net-snmp plugin. opnDossier reads it from ``, pinned to the general model versions the plugin has shipped, 1.0.0, 1.0.1 and 1.0.3 to 1.0.7 (it never used 1.0.2), and to user model versions 1.0.0 and 1.0.1. The agent runs only with `1`, compared as raw text, so an absent or empty element is off. A user is loaded only with its own `1`, and `1` gives it read-write access. `` and `` are not read. + +```xml + + + + 1 + s3cret + rack 4 + noc + 192.0.2.1,2001:db8::1 + + + + + 1 + monitor + ... + ... + 0 + + + + + +``` + +The legacy top-level `` starts an agent only when it carries ``, tested for presence, so `` counts. That holds on pfSense and on OPNsense up to 18.7; OPNsense 19.1 and later run nothing from it, and opnDossier still reports it there, with a warning, when net-snmp is not enabled. + +```xml + + + + public + + +``` + ## NAT Rule Enhancements **Outbound NAT with port preservation:** diff --git a/internal/analysis/statistics.go b/internal/analysis/statistics.go index 64a1ea1b5..d159b2a74 100644 --- a/internal/analysis/statistics.go +++ b/internal/analysis/statistics.go @@ -158,7 +158,7 @@ func populateServiceStats(stats *common.Statistics, cfg *common.CommonDevice) { serviceCount++ } - if cfg.SNMP.ROCommunity != "" { + if cfg.SNMP.IsEnabled() { stats.EnabledServices = append(stats.EnabledServices, ServiceNameSNMP) stats.ServiceDetails = append(stats.ServiceDetails, common.ServiceStatistics{ Name: ServiceNameSNMP, diff --git a/internal/analysis/statistics_redact.go b/internal/analysis/statistics_redact.go index 483afb036..852dbd26a 100644 --- a/internal/analysis/statistics_redact.go +++ b/internal/analysis/statistics_redact.go @@ -18,9 +18,9 @@ const serviceDetailRedactedValue = "[REDACTED]" // snmpSensitiveDetailKeys lists the keys in ServiceStatistics.Details (for the // SNMP service entry) whose values must be redacted on export. Adding a new -// sensitive key — for example, an SNMPv3 authentication password surfaced once -// the OPNsense net-snmp plugin namespace is parsed — is a one-line append here, -// shared by every caller of RedactServiceDetails. +// sensitive key is a one-line append here, shared by every caller of +// RedactServiceDetails. SNMPv3 passwords and privacy keys are deliberately +// never parsed, so none can reach these details. // // When adding a key here, also verify the sanitizer's password/private_key // FieldPatterns in internal/sanitizer/rules.go cover the corresponding raw XML diff --git a/internal/audit/exploit_notes.go b/internal/audit/exploit_notes.go index fe83e6b3b..56c187506 100644 --- a/internal/audit/exploit_notes.go +++ b/internal/audit/exploit_notes.go @@ -9,8 +9,13 @@ const ( exploitKindWebGUI exploitNoteKind = "webgui" // exploitKindSSH is the remote administrative shell service. exploitKindSSH exploitNoteKind = "ssh" - // exploitKindSNMP is the SNMP network-management service. + // exploitKindSNMP is the SNMP network-management service with a + // community configured. exploitKindSNMP exploitNoteKind = "snmp" + // exploitKindSNMPNoCommunity is the SNMP network-management service with + // no community configured, such as an os-net-snmp agent that answers only + // SNMPv3 users. Its text does not name community authentication. + exploitKindSNMPNoCommunity exploitNoteKind = "snmp-no-community" // exploitKindPortForward is an inbound NAT port-forward to an internal host. exploitKindPortForward exploitNoteKind = "port-forward" // exploitKindConfigWeakness is a shared-engine hygiene observation reframed @@ -50,6 +55,10 @@ var exploitNoteTemplates = map[exploitNoteKind]exploitNoteTemplate{ standard: "Network-management access reachable from untrusted networks can leak device and topology detail and, with community-based authentication, offers weak protection against unauthorized queries. Disclosed information helps an attacker map the environment.", blackhat: "The management protocol is reachable from the internet and leaks configuration and topology detail. Community-based authentication provides little resistance, making the device an easy reconnaissance source.", }, + exploitKindSNMPNoCommunity: { + standard: "Network-management access reachable from untrusted networks places the agent's authentication within reach of the internet, and anything the agent answers can leak device and topology detail. Disclosed information helps an attacker map the environment.", + blackhat: "The management protocol is reachable from the internet. The agent's authentication is an open target, and any answer it gives leaks configuration and topology detail that makes the device a reconnaissance source.", + }, exploitKindPortForward: { standard: "This port forward publishes an internal host and service to untrusted networks, extending the attack surface past the firewall to a system that may not be hardened for direct exposure. The forwarded host inherits all of the internet's unsolicited traffic.", blackhat: "A path straight through the firewall to an internal host is open. The exposed service is reachable from anywhere, and the internal target is often softer than the perimeter itself.", diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index 84e473b1f..1143b8427 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -73,15 +73,31 @@ type exposedService struct { } // serviceExposures enumerates the in-scope management services present on the -// device (WebGUI is always present; SSH when enabled; SNMP when a read-only -// community is configured) and classifies each as WAN-reachable or LAN-only by -// correlating its port against WAN-reachable rules. Local-only services are not +// device (WebGUI is always present; SSH and SNMP when enabled) and classifies +// each as WAN-reachable or LAN-only by correlating its port against +// WAN-reachable rules. An os-net-snmp agent bound only to loopback, when no +// port forward can redirect UDP port 161 to loopback, is the one +// exception: it is Local (applySNMPListen). For any other service Local is not // possible here — a configured management service is at least LAN-reachable. func serviceExposures(device *common.CommonDevice) []exposedService { if device == nil { return nil } + services := managementServices(device) + + // The SNMP agent's bind address is applied last, after every other + // reachability decision: an agent bound only to loopback answers no other + // host, whatever the firewall passes, unless a port forward can redirect + // UDP port 161 to loopback (forwardsToLoopback). + applySNMPListen(device, services) + + return services +} + +// managementServices builds the list serviceExposures returns, before the SNMP +// agent's bind address is applied. +func managementServices(device *common.CommonDevice) []exposedService { services := make([]exposedService, 0, maxManagementServices) // WebGUI is always listening; the only question is its reachability. Both @@ -122,17 +138,27 @@ func serviceExposures(device *common.CommonDevice) []exposedService { }) } - if device.SNMP.ROCommunity != "" { + if device.SNMP.IsEnabled() { + // An agent with no community, such as an os-net-snmp agent that + // answers only SNMPv3 users, is not told to migrate to SNMPv3, and its + // note does not name community authentication. + kind := exploitKindSNMP + recommendation := "Restrict SNMP to management networks, migrate to SNMPv3 with authPriv, or disable SNMP if unused." + if device.SNMP.ROCommunity == "" { + kind = exploitKindSNMPNoCommunity + recommendation = "Restrict SNMP to management networks, or disable SNMP if unused." + } + services = append(services, exposedService{ - kind: exploitKindSNMP, - name: "snmp", + kind: kind, + name: serviceNameSNMP, displayName: "SNMP Management Service", severity: analysis.SeverityHigh, component: "snmpd", port: portSNMP, reachability: serviceReachability(device, portSNMP), description: "The SNMP management service is reachable from a WAN interface, exposing device and topology information to untrusted networks.", - recommendation: "Restrict SNMP to management networks, migrate to SNMPv3 with authPriv, or disable SNMP if unused.", + recommendation: recommendation, vulnerabilities: []string{"exposed-snmp"}, }) } diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go new file mode 100644 index 000000000..1fcff9053 --- /dev/null +++ b/internal/audit/red_snmp_listen.go @@ -0,0 +1,254 @@ +package audit + +import ( + "net/netip" + "slices" + "strconv" + "strings" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" +) + +// serviceNameSNMP is the exposedService name of the SNMP agent. +const serviceNameSNMP = "snmp" + +// loopbackAddresses are what a port forward's target is checked against, so +// that a network or range spanning loopback counts as well as one inside it. +var loopbackAddresses = []netip.Addr{netip.MustParseAddr("127.0.0.1"), netip.IPv6Loopback()} + +// The OPNsense alias types for a URL table and a URL table in JSON format. The +// model has no constant for either, and the converter keeps the vendor type. +const ( + aliasTypeURLTable common.NamedObjectType = "urltable" + aliasTypeURLJSON common.NamedObjectType = "urljson" +) + +// runtimeAliasTypes are the OPNsense alias types whose addresses the firewall +// fetches, or is given by another process, at runtime: a URL alias, a URL +// table, a URL table in JSON format, and an external alias. +var runtimeAliasTypes = []common.NamedObjectType{ + common.NamedObjectTypeURL, aliasTypeURLTable, aliasTypeURLJSON, common.NamedObjectTypeExternal, +} + +// applySNMPListen marks the SNMP agent in services as Local when the +// os-net-snmp plugin binds it only to loopback and no port forward can +// redirect its traffic to loopback. Such an agent answers no other host, so it +// is Local whatever reachability services already gives it, and +// serviceExposures calls this last. pf rewrites a forward's destination before +// the packet is delivered, so a forward of UDP port 161 to loopback can reach +// an agent bound there, and the agent then keeps the reachability services +// gives it (forwardsToLoopback). A list holding any other address, or an empty list, +// leaves the agent as it is too, judged as the other services are: an +// os-net-snmp agent with no listen address binds every IPv4 address and the +// IPv6 loopback, and for an agent no bind address is read. +func applySNMPListen(device *common.CommonDevice, services []exposedService) { + if !listensOnLoopbackOnly(device.SNMP.ListenAddresses) || forwardsToLoopback(device) { + return + } + + for i := range services { + if services[i].name == serviceNameSNMP { + services[i].reachability = analysis.Local + } + } +} + +// forwardsToLoopback reports whether an enabled port forward that redirects +// traffic can redirect UDP to port 161 (forwardCanReachSNMPPort) and has a +// target that is, spans or may hold a loopback address, such as a URL table +// (targetHoldsLoopback). A forward to loopback that cannot, such as a DNS +// redirect to port 53 or a transparent proxy's TCP forward, leaves the agent +// Local. The forward's interface is not read, nor whether pf runs (with +// set, pf is off and no forward redirects anything), +// nor whether the target's address family is one the agent listens on, so a +// forward to ::1 counts for an agent bound only to 127.0.0.1. Each can +// over-report, the safe direction. +func forwardsToLoopback(device *common.CommonDevice) bool { + return slices.ContainsFunc(device.NAT.InboundRules, func(nat common.InboundNATRule) bool { + return !nat.Disabled && !nat.NoRDR && forwardCanReachSNMPPort(nat) && + targetHoldsLoopback(nat.InternalIP, device) + }) +} + +// forwardCanReachSNMPPort reports whether a port forward can redirect UDP to +// port 161, where the os-net-snmp template binds each agent address. OPNsense +// reads a forward's ports only for tcp, udp and tcp/udp, so a forward with no +// protocol or any, which matches every protocol, redirects every port and keeps +// it, and one for another named protocol, tcp among them, redirects no UDP. +// Without a local port pf keeps the destination port, which must then permit +// 161. With one, pf rewrites each port the forward matches to the local port +// when the destination port is a single number or any port, so the local port +// decides; another destination port, such as a range, is read as reaching the +// agent. A port alias, or another port analysis.RulePortPermits cannot read, +// is read as permitting 161. +func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { + if analysis.IsAnyProtocol(nat.Protocol) { + return true + } + + if proto := strings.ToLower(strings.TrimSpace(nat.Protocol)); proto != "udp" && proto != "tcp/udp" { + return false + } + + if nat.LocalPort == "" { + return analysis.RulePortPermits(nat.Destination.Port, portSNMP) + } + + destination := strings.TrimSpace(nat.Destination.Port) + if _, err := strconv.Atoi(destination); err != nil && !analysis.IsAnyPort(destination) { + return true + } + + return analysis.RulePortPermits(nat.LocalPort, portSNMP) +} + +// targetHoldsLoopback reports whether a port forward's target is, spans or may +// hold a loopback address. It reads the target as ForwardRule.php does from +// OPNsense 26.1.2. The target (self), This Firewall on the forward page, +// counts: pf reads it as every address of every interface, lo0's among them. +// OPNsense accepts an alias other than a port alias as the target, and pf then +// redirects to the addresses it holds, so a target such an alias defines +// counts when a member of the alias, or of an alias it names, holds one +// (aliasHoldsFirewallAddress, which also counts a member naming a table the +// config does not store), or when the alias, or an alias it names, gets its +// addresses at runtime, as a URL table does, and as a host alias does for a +// hostname it holds (aliasNamesRuntimeTable). +// aliasHoldsFirewallAddress alone reads such an alias as holding no address, +// which forwardsToAlias relies on. OPNsense also accepts an interface: its key +// for the interface's network, and for wan, lan and optN the key and "ip" for +// its address. A target that is an interface's key, or its key and "ip", counts +// only when that interface's own address is a loopback address, as on lo0, so a +// forward to lanip or to the lan net leaves the agent Local. OPNsense maps the +// interfaces first and then every alias but a port alias (loadAliasMap in +// Rule.php), so an alias named like an interface is read in its place. A port +// alias holds ports and no address, and is not read: one named like an +// interface leaves that interface's reading in place, and one named like no +// interface does not count, since OPNsense disables a forward to a name the map +// does not hold, if it is no address or network, as an invalid target. The key +// and "ip" is matched for every interface, so lo0ip counts beside a lo0 that +// holds loopback, although OPNsense maps that form only for wan, lan and optN +// and disables a forward to any other such name no alias defines as an invalid +// target: the wider match can only over-report. A name no alias or interface +// defines counts when it has the shape of an alias name, since it can name a +// table the config does not store. A target that is a hostname with a domain +// does not count, since OPNsense disables a forward to it as an invalid +// target. Through 26.1.1 ForwardRule.php maps a target only when an +// alias of that name exists, of any type, and disables a forward to any other +// name that is no address or network as an invalid target, (self) and +// interface names among them, so on those releases the readings of (self) and +// of an interface can only over-report. +func targetHoldsLoopback(target string, device *common.CommonDevice) bool { + if target == "(self)" { + return true + } + + object, defined := device.NamedObjects[target] + if defined && object.Type != common.NamedObjectTypePort { + return aliasHoldsFirewallAddress(device.NamedObjects, target, loopbackAddresses) || + aliasNamesRuntimeTable(device.NamedObjects, target) + } + + for _, iface := range device.Interfaces { + if target == iface.Name || target == iface.Name+"ip" { + return isLoopbackEntry(iface.IPAddress) || isLoopbackEntry(iface.IPv6Address) + } + } + + if defined { + return false + } + + return holdsFirewallAddress(target, loopbackAddresses) || aliasNamePattern.MatchString(target) +} + +// aliasNamesRuntimeTable reports whether the alias name, or an alias it names +// at any depth, gets its addresses at runtime: it is of a type in +// runtimeAliasTypes, or it is a host alias holding a member that names no +// alias and that OPNsense resolves through DNS when it loads the alias, such +// as a hostname (resolvedThroughDNS). OPNsense loads every address a fetched +// list or a DNS answer holds, loopback addresses included, so such an alias may +// hold one. A host, network or network group alias can name an alias of any +// type. The walk follows each member that names an alias, as +// aliasHoldsFirewallAddress does, and seen ends a nesting loop. +func aliasNamesRuntimeTable(objects common.NamedObjects, name string) bool { + seen := map[string]bool{name: true} + pending := []string{name} + + for len(pending) > 0 { + last := len(pending) - 1 + object := objects[pending[last]] + pending = pending[:last] + + if slices.Contains(runtimeAliasTypes, object.Type) { + return true + } + + for _, member := range object.Members { + _, defined := objects[member] + + switch { + case !defined && object.Type == common.NamedObjectTypeHost && resolvedThroughDNS(member): + return true + case defined && !seen[member]: + seen[member] = true + pending = append(pending, member) + } + } + } + + return false +} + +// resolvedThroughDNS reports whether member, an entry of an OPNsense host alias +// that names no alias, is one the alias loader resolves through DNS: an entry +// that is no address and no first-last range of addresses (iter_addresses in +// OPNsense's alias/base.py), such as a hostname with or without a domain. An +// entry with "/" is read as a network or a wildcard network, or dropped, and +// the alias page accepts "!" only before an address, so neither is resolved. +func resolvedThroughDNS(member string) bool { + if member == "" || strings.ContainsAny(member, "/!") { + return false + } + + from, to, isRange := strings.Cut(member, "-") + _, errFrom := netip.ParseAddr(from) + _, errTo := netip.ParseAddr(to) + + return errFrom != nil || (isRange && errTo != nil) +} + +// listensOnLoopbackOnly reports whether addresses is non-empty and every entry +// is a loopback address, or a network inside the loopback range. An entry that +// does not parse counts as reachable, so it never hides an exposure. +func listensOnLoopbackOnly(addresses []string) bool { + if len(addresses) == 0 { + return false + } + + for _, entry := range addresses { + if !isLoopbackEntry(entry) { + return false + } + } + + return true +} + +func isLoopbackEntry(entry string) bool { + if addr, err := netip.ParseAddr(entry); err == nil { + return addr.Unmap().IsLoopback() + } + + prefix, err := netip.ParsePrefix(entry) + if err != nil { + return false + } + + network := prefix.Masked().Addr().Unmap() + if network.Is4() { + return network.IsLoopback() && prefix.Bits() >= 8 + } + + return network.IsLoopback() && prefix.Bits() == 128 +} diff --git a/internal/audit/red_snmp_listen_test.go b/internal/audit/red_snmp_listen_test.go new file mode 100644 index 000000000..f8447aa9b --- /dev/null +++ b/internal/audit/red_snmp_listen_test.go @@ -0,0 +1,84 @@ +package audit + +import ( + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/stretchr/testify/assert" +) + +// TestApplySNMPListen_OverridesEarlierReachability checks that an agent bound +// only to loopback, on a device with no port forward, is Local whatever +// reachability the list already gives it, WAN-reachable included, so no +// decision made before applySNMPListen can report it as exposed. The SNMP +// entry is second, ahead of SSH, and the other services keep their +// reachability. Any other listen list leaves every entry as it was. +func TestApplySNMPListen_OverridesEarlierReachability(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + listen []string + before analysis.Reachability + want analysis.Reachability + }{ + { + name: "IPv4 loopback, WAN-reachable", listen: []string{"127.0.0.1"}, + before: analysis.WANReachable, want: analysis.Local, + }, + { + name: "IPv6 loopback, WAN-reachable", listen: []string{"::1"}, + before: analysis.WANReachable, want: analysis.Local, + }, + { + name: "both loopbacks, LAN-only", listen: []string{"127.0.0.1", "::1"}, + before: analysis.LANOnly, want: analysis.Local, + }, + { + name: "loopback and a LAN address", listen: []string{"127.0.0.1", "192.168.1.1"}, + before: analysis.WANReachable, want: analysis.WANReachable, + }, + { + name: "no listen address", + before: analysis.WANReachable, want: analysis.WANReachable, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{SNMP: common.SNMPConfig{Enabled: true, ListenAddresses: tc.listen}} + services := []exposedService{ + {kind: exploitKindWebGUI, name: "webgui", reachability: analysis.WANReachable}, + {kind: exploitKindSNMPNoCommunity, name: serviceNameSNMP, reachability: tc.before}, + {kind: exploitKindSSH, name: "ssh", reachability: analysis.WANReachable}, + } + + applySNMPListen(device, services) + + assert.Equal(t, analysis.WANReachable, services[0].reachability, "webgui") + assert.Equal(t, tc.want, services[1].reachability, "snmp") + assert.Equal(t, analysis.WANReachable, services[2].reachability, "ssh") + }) + } +} + +// TestApplySNMPListen_NoAgentChangesNothing checks that a loopback listen list +// with no SNMP entry in the list, as when the agent is not running, marks no +// other service Local. +func TestApplySNMPListen_NoAgentChangesNothing(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{SNMP: common.SNMPConfig{ListenAddresses: []string{"127.0.0.1"}}} + services := []exposedService{ + {kind: exploitKindWebGUI, name: "webgui", reachability: analysis.WANReachable}, + {kind: exploitKindSSH, name: "ssh", reachability: analysis.LANOnly}, + } + + applySNMPListen(device, services) + + assert.Equal(t, analysis.WANReachable, services[0].reachability, "webgui") + assert.Equal(t, analysis.LANOnly, services[1].reachability, "ssh") +} diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go new file mode 100644 index 000000000..fa08443b3 --- /dev/null +++ b/internal/audit/snmp_agent_test.go @@ -0,0 +1,330 @@ +package audit + +import ( + "slices" + "strings" + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// snmpAgentConfig is an OPNsense config whose WAN passes UDP 161 to the +// firewall, with the given SNMP elements spliced in at the top level and +// under . +func snmpAgentConfig(topLevel, model string) string { + return ` + + + fw + example.com + + + + 1 + vtnet0 + dhcp + + + 1 + vtnet1 + 192.168.1.1 + 24 + + + + + pass + wan + inet + udp + + + + + wanip + 161 + + monitoring + + ` + topLevel + ` + ` + model + ` + +` +} + +const ( + // snmpStaleLegacy is the factory default's legacy block, which starts no + // agent on any release. + snmpStaleLegacy = ` + + + + public + ` + + snmpNetsnmpDisabled = ` + + + 0 + public + + + + + ` + + snmpNetsnmpPublic = ` + + + 1 + public + + + + + + ` + + snmpNetsnmpV3Only = ` + + + 1 + + + + + + 1 + monitor + MonitorPass123 + MonitorKey12345 + 0 + + + + ` +) + +// TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts drives OPNsense configs +// through parse, convert, the FIREWALL and STIG plugins and red mode. The +// verdicts follow the agent the config starts: the os-net-snmp model when it +// is enabled, a legacy block with when it is not, and never +// the legacy block the factory default left behind without . +func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + topLevel string + model string + // running is whether an agent runs; defaultCommunity whether it + // answers "public". + running bool + defaultCommunity bool + }{ + {name: "stale legacy block only", topLevel: snmpStaleLegacy}, + {name: "stale legacy block and net-snmp disabled", topLevel: snmpStaleLegacy, model: snmpNetsnmpDisabled}, + {name: "net-snmp enabled with public", model: snmpNetsnmpPublic, running: true, defaultCommunity: true}, + {name: "net-snmp enabled with SNMPv3 users only", model: snmpNetsnmpV3Only, running: true}, + { + name: "legacy block with enable and net-snmp disabled", + topLevel: ` + + legacycomm + + `, + model: snmpNetsnmpDisabled, + running: true, + }, + } + + logger := newTestLogger(t) + pm := NewPluginManager(logger, nil) + require.NoError(t, pm.InitializePlugins(t.Context())) + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpAgentConfig(tc.topLevel, tc.model)) + assert.Equal(t, tc.running, device.SNMP.IsEnabled()) + + services := analysis.ComputeStatistics(device).EnabledServices + assert.Equal(t, tc.running, slices.Contains(services, analysis.ServiceNameSNMP), "enabled services") + + results, err := pm.GetRegistry().RunComplianceChecks(device, []string{"firewall", "stig"}, logger) + require.NoError(t, err) + + assert.Equal(t, !tc.running, results.Compliance["firewall"]["FIREWALL-045"], "FIREWALL-045") + assert.Equal(t, !tc.defaultCommunity, results.Compliance["firewall"]["FIREWALL-046"], "FIREWALL-046") + assert.Equal(t, !tc.running, results.Compliance["stig"]["V-206690"], "V-206690") + + report := newRedReport(device) + runRedAnalysis(report) + _, exposed := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + assert.Equal(t, tc.running, exposed, "red-mode SNMP exposure") + }) + } +} + +// TestSNMPAgent_ListenAddressesDecideWANExposure keeps the WAN rule passing +// UDP 161 and varies the agent's listen list. With no port forward to +// loopback, an agent bound only to loopback answers no other host: it stays +// among the services red mode considers, as local, and draws no WAN exposure. +// Any other address, an unparseable one, or an empty list (every IPv4 address +// and the IPv6 loopback) is still judged by the rule. +func TestSNMPAgent_ListenAddressesDecideWANExposure(t *testing.T) { + t.Parallel() + + tests := []struct { + listen string + want analysis.Reachability + }{ + {listen: "", want: analysis.WANReachable}, + {listen: "127.0.0.1", want: analysis.Local}, + {listen: "127.0.0.1,::1", want: analysis.Local}, + {listen: "127.0.0.0/8", want: analysis.Local}, + {listen: "::1/128", want: analysis.Local}, + // ::1/127 also holds ::, the unspecified address, so it is not loopback. + {listen: "::1/127", want: analysis.WANReachable}, + {listen: "127.0.0.1,192.168.1.1", want: analysis.WANReachable}, + {listen: "0.0.0.0", want: analysis.WANReachable}, + {listen: "localhost", want: analysis.WANReachable}, + } + + for _, tc := range tests { + t.Run("listen="+tc.listen, func(t *testing.T) { + t.Parallel() + + model := strings.Replace(snmpNetsnmpPublic, "", ""+tc.listen+"", 1) + device := parseConfig(t, snmpAgentConfig("", model)) + + services := serviceExposures(device) + idx := slices.IndexFunc(services, func(s exposedService) bool { return s.name == "snmp" }) + require.GreaterOrEqual(t, idx, 0, "snmp missing from the services red mode considers: %+v", services) + assert.Equal(t, tc.want, services[idx].reachability) + + report := newRedReport(device) + runRedAnalysis(report) + + _, exposed := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + assert.Equal(t, tc.want == analysis.WANReachable, exposed, "red-mode SNMP exposure") + }) + } +} + +// TestSNMPAgent_LoopbackOnlyAgentStaysLocalWithPacketFilteringDisabled sets +// , which turns pf off, and varies the agent's listen +// list. With no port forward to loopback, an agent bound only to loopback +// answers no other host with or without pf, so it stays local and draws no WAN +// exposure, with or without a WAN rule passing UDP 161. The cases with any +// other listen list keep that rule, and they are reported as WAN-exposed. +func TestSNMPAgent_LoopbackOnlyAgentStaysLocalWithPacketFilteringDisabled(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + listen string + wanRule bool + local bool + }{ + {name: "IPv4 loopback, no rule", listen: "127.0.0.1", local: true}, + {name: "IPv6 loopback, no rule", listen: "::1", local: true}, + {name: "IPv4 loopback, WAN rule", listen: "127.0.0.1", wanRule: true, local: true}, + {name: "both loopbacks, WAN rule", listen: "127.0.0.1,::1", wanRule: true, local: true}, + {name: "loopback and a LAN address, WAN rule", listen: "127.0.0.1,192.168.1.1", wanRule: true}, + {name: "no listen address, WAN rule", wanRule: true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + model := strings.Replace(snmpNetsnmpPublic, "", ""+tc.listen+"", 1) + config := strings.Replace(snmpAgentConfig("", model), + "", "\n enabled", 1) + if !tc.wanRule { + start := strings.Index(config, "") + end := strings.Index(config, "") + len("") + config = config[:start] + "" + config[end:] + } + + device := parseConfig(t, config) + + services := serviceExposures(device) + idx := slices.IndexFunc(services, func(s exposedService) bool { return s.name == "snmp" }) + require.GreaterOrEqual(t, idx, 0, "snmp missing from the services red mode considers: %+v", services) + assert.Equal(t, tc.local, services[idx].reachability == analysis.Local, + "reachability %s", services[idx].reachability) + + report := newRedReport(device) + runRedAnalysis(report) + + _, exposed := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + assert.Equal(t, !tc.local, exposed, "red-mode SNMP exposure") + }) + } +} + +// TestSNMPAgent_SnmpdBindAddressIsNotRead pins what the model reference says +// of an agent: no bind address is read for it, so it is judged by the +// firewall rules alone. pfSense binds bsnmpd to , an address or +// an interface name, and an agent bound there to loopback is still reported as +// WAN-exposed when a WAN rule passes UDP 161. That over-reports. +func TestSNMPAgent_SnmpdBindAddressIsNotRead(t *testing.T) { + t.Parallel() + + for _, bindip := range []string{"127.0.0.1", "lo0"} { + t.Run("bindip="+bindip, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, ` + + 23.3 + + pf + example.com + + + + + vtnet0 + dhcp + + + + + pass + wan + inet + udp + + + + + wanip + 161 + + monitoring + + + + pfcomm + + `+bindip+` + 4 + +`) + require.True(t, device.SNMP.Enabled, "the agent runs") + assert.Empty(t, device.SNMP.ListenAddresses, "no bind address is read for an agent") + + report := newRedReport(device) + runRedAnalysis(report) + + _, exposed := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + assert.True(t, exposed, "judged by the WAN rule alone") + }) + } +} diff --git a/internal/audit/snmp_exposure_text_test.go b/internal/audit/snmp_exposure_text_test.go new file mode 100644 index 000000000..009fc86a8 --- /dev/null +++ b/internal/audit/snmp_exposure_text_test.go @@ -0,0 +1,60 @@ +package audit + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestSNMPAgent_ExposureTextFollowsTheCommunity checks the text red mode gives +// a WAN-exposed SNMP agent, in both tones. An agent with a community is told to +// migrate to SNMPv3, and its note names community authentication. An agent +// with none, such as an os-net-snmp agent that answers only SNMPv3 users, gets +// neither, and neither does a legacy agent with and no community. +func TestSNMPAgent_ExposureTextFollowsTheCommunity(t *testing.T) { + t.Parallel() + + const legacyEnabledNoCommunity = ` + + closet + ops + + ` + + tests := []struct { + name string + topLevel string + model string + community bool + }{ + {name: "net-snmp enabled with public", model: snmpNetsnmpPublic, community: true}, + {name: "net-snmp enabled with SNMPv3 users only", model: snmpNetsnmpV3Only}, + {name: "legacy block with enable and no community", topLevel: legacyEnabledNoCommunity}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpAgentConfig(tc.topLevel, tc.model)) + require.True(t, device.SNMP.IsEnabled()) + assert.Equal(t, tc.community, device.SNMP.ROCommunity != "") + + for _, blackhat := range []bool{false, true} { + report := newRedReport(device) + report.addWANExposedServices(serviceExposures(device), blackhat) + + finding, ok := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + require.True(t, ok, "blackhat=%v: no SNMP exposure", blackhat) + require.NotEmpty(t, finding.ExploitNotes, "blackhat=%v", blackhat) + + assert.Equal(t, tc.community, strings.Contains(finding.Recommendation, "SNMPv3"), + "blackhat=%v recommendation: %q", blackhat, finding.Recommendation) + assert.Equal(t, tc.community, strings.Contains(strings.ToLower(finding.ExploitNotes), "community"), + "blackhat=%v note: %q", blackhat, finding.ExploitNotes) + } + }) + } +} diff --git a/internal/audit/snmp_forward_hostname_alias_test.go b/internal/audit/snmp_forward_hostname_alias_test.go new file mode 100644 index 000000000..51375889b --- /dev/null +++ b/internal/audit/snmp_forward_hostname_alias_test.go @@ -0,0 +1,192 @@ +package audit + +import ( + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestTargetHoldsLoopback_HostnameMembers checks a forward's target that is, or +// names, a host alias holding a hostname. OPNsense resolves such a member +// through DNS when it loads the alias and keeps every address the answer +// holds, so the alias may hold a loopback address and counts, with or without +// a domain in the hostname, and so does a network group naming it. A member +// that is an address, a range of addresses, an IPv6 address, an address +// excluded with "!", or the name of another alias is not resolved, and a +// network alias holding a LAN network holds no loopback, so none of those +// counts. A target that is itself a hostname does not count either, since +// OPNsense disables a forward to it as an invalid target. +func TestTargetHoldsLoopback_HostnameMembers(t *testing.T) { + t.Parallel() + + alias := func(name string, aliasType common.NamedObjectType, members ...string) common.NamedObject { + return common.NamedObject{Name: name, Type: aliasType, Members: members} + } + + objects := common.NamedObjects{ + "LAN_HOST": alias("LAN_HOST", common.NamedObjectTypeHost, "192.168.1.50"), + "FQDN_HOST": alias("FQDN_HOST", common.NamedObjectTypeHost, "192.168.1.51", "snmp.example.com"), + "SHORT_HOST": alias("SHORT_HOST", common.NamedObjectTypeHost, "192.168.1.52", "snmp-agent"), + "HOST_GROUP": alias("HOST_GROUP", aliasTypeNetworkGroup, "LAN_HOST", "FQDN_HOST"), + "RANGE_HOST": alias("RANGE_HOST", common.NamedObjectTypeHost, "192.168.1.60-192.168.1.70"), + "V6_HOST": alias("V6_HOST", common.NamedObjectTypeHost, "2001:db8:1::50"), + "EXCLUDED_HOST": alias("EXCLUDED_HOST", common.NamedObjectTypeHost, "192.168.1.0", "!192.168.1.53"), + "NESTING_HOST": alias("NESTING_HOST", common.NamedObjectTypeHost, "192.168.1.54", "LAN_HOST"), + "LAN_NET": alias("LAN_NET", common.NamedObjectTypeNetwork, "192.168.1.0/24"), + } + + interfaces := []common.Interface{ + {Name: "wan", IPAddress: "198.51.100.2"}, + {Name: "lan", IPAddress: "192.168.1.1"}, + } + + tests := []struct { + name string + target string + want bool + }{ + {name: "host alias holding a hostname with a domain second", target: "FQDN_HOST", want: true}, + {name: "host alias holding a hostname with a hyphen and no domain second", target: "SHORT_HOST", want: true}, + {name: "network group naming that host alias second", target: "HOST_GROUP", want: true}, + {name: "host alias holding a LAN address", target: "LAN_HOST"}, + {name: "host alias holding a range of addresses", target: "RANGE_HOST"}, + {name: "host alias holding an IPv6 address", target: "V6_HOST"}, + {name: "host alias holding an address excluded with !", target: "EXCLUDED_HOST"}, + {name: "host alias naming another host alias second", target: "NESTING_HOST"}, + {name: "network alias holding a LAN network", target: "LAN_NET"}, + {name: "hostname with a domain as the target", target: "snmp.example.com"}, + {name: "hostname with a hyphen as the target", target: "snmp-agent"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{Interfaces: interfaces, NamedObjects: objects} + assert.Equal(t, tc.want, targetHoldsLoopback(tc.target, device)) + }) + } +} + +// TestResolvedThroughDNS checks which entries of a host alias that name no +// alias OPNsense's alias loader resolves through DNS: every entry that is no +// address and no range of addresses, and none with "/" or "!". +func TestResolvedThroughDNS(t *testing.T) { + t.Parallel() + + tests := []struct { + member string + want bool + }{ + {member: "snmp.example.com", want: true}, + {member: "snmp.example.com.", want: true}, + {member: "snmp-agent", want: true}, + {member: "localhost", want: true}, + {member: "my-host.example.com", want: true}, + {member: "snmp-10.0.0.1", want: true}, + {member: "192.168.1.10-snmp", want: true}, + {member: ""}, + {member: "192.168.1.10"}, + {member: "127.0.0.1"}, + {member: "2001:db8::10"}, + {member: "192.168.1.10-192.168.1.20"}, + {member: "2001:db8::10-2001:db8::20"}, + {member: "192.168.1.0/24"}, + {member: "192.168.0.1/0.0.255.0"}, + {member: "!192.168.1.10"}, + {member: "!snmp.example.com"}, + } + + for _, tc := range tests { + t.Run(tc.member, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tc.want, resolvedThroughDNS(tc.member)) + }) + } +} + +// TestSNMPAgent_ForwardToHostnameAlias drives OPNsense configs with a net-snmp +// agent bound only to 127.0.0.1 through parse, convert and red mode. A WAN rule +// passes UDP 161 to any destination, which reaches the agent only if a forward +// can redirect that traffic to loopback. A WAN forward of UDP 161 to a host +// alias holding a hostname, or to a network group naming one, may do so, since +// the hostname may resolve to a loopback address, so the agent keeps the +// exposure the rule gives it. With the rule to the host alias itself instead, +// the rule is the forward's own and is not read (forwardsToAnotherHost), so the +// agent keeps the LAN reachability it has without a WAN rule. A forward to a +// host alias holding only a LAN address leaves the agent Local. +func TestSNMPAgent_ForwardToHostnameAlias(t *testing.T) { + t.Parallel() + + aliases := snmpForwardAlias("f6f6f6f6-0000-4000-8000-000000000001", "LAN_HOST", "host", "192.168.1.50") + + snmpForwardAlias("f6f6f6f6-0000-4000-8000-000000000002", "FQDN_HOST", "host", + "192.168.1.51\nsnmp.example.com") + + snmpForwardAlias("f6f6f6f6-0000-4000-8000-000000000003", "HOST_GROUP", "networkgroup", + "LAN_HOST\nFQDN_HOST") + + anyRule := snmpForwardAnyRule() + + tests := []struct { + name string + target string + rules string + forwards string + want analysis.Reachability + }{ + { + name: "rule to any, forward to a host alias holding a hostname", + target: "FQDN_HOST", + rules: anyRule, + forwards: snmpLegacyForward("FQDN_HOST", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to any, 26.1 forward to a host alias holding a hostname", + target: "FQDN_HOST", + rules: anyRule, + forwards: snmpModelForward("FQDN_HOST", "0"), + want: analysis.WANReachable, + }, + { + name: "rule to any, forward to a network group naming that host alias second", + target: "HOST_GROUP", + rules: anyRule, + forwards: snmpLegacyForward("HOST_GROUP", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to the host alias, forward to the host alias", + target: "FQDN_HOST", + rules: snmpForwardRule("FQDN_HOST", "nat_1"), + forwards: snmpLegacyForward("FQDN_HOST", "nat_1", ""), + want: analysis.LANOnly, + }, + { + name: "rule to any, forward to a host alias holding a LAN address", + target: "LAN_HOST", + rules: anyRule, + forwards: snmpLegacyForward("LAN_HOST", "", ""), + want: analysis.Local, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpForwardConfig("127.0.0.1", tc.rules, tc.forwards, aliases)) + require.Equal(t, []string{"127.0.0.1"}, device.SNMP.ListenAddresses) + require.Equal(t, []string{"192.168.1.51", "snmp.example.com"}, device.NamedObjects["FQDN_HOST"].Members, + "host alias members") + require.Equal(t, common.NamedObjectTypeHost, device.NamedObjects["FQDN_HOST"].Type, "host alias type") + require.Len(t, device.NAT.InboundRules, 1) + require.Equal(t, tc.target, device.NAT.InboundRules[0].InternalIP, "target") + + assertSNMPReachability(t, device, tc.want) + }) + } +} diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go new file mode 100644 index 000000000..10a23c7fc --- /dev/null +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -0,0 +1,299 @@ +package audit + +import ( + "slices" + "strings" + "testing" + + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// snmpLoopbackInterface is the lo0 interface as OPNsense writes it into +// , then the closing tag it replaces. +const snmpLoopbackInterface = ` + + 1 + Loopback + 1 + lo0 + 127.0.0.1 + ::1 + 8 + 128 + none + 1 + + ` + +// snmpForwardNetworkRule is snmpForwardRule, linked to the forward nat_1, with +// the destination written as a network element, the form a filter rule to an +// interface net or address takes. +func snmpForwardNetworkRule(network string) string { + return strings.Replace(snmpForwardRule(network, "nat_1"), + "
"+network+"
", ""+network+"", 1) +} + +// TestSNMPAgent_ForwardToInterfaceTarget drives OPNsense configs with a +// net-snmp agent bound only to loopback through parse, convert and red mode, +// each with a WAN forward of UDP 161 and the rule that passes it. From 26.1.2 +// OPNsense maps an interface's net (lan) or address (lanip) as a forward's +// target, and pf then redirects to that interface, where the agent does not +// listen, so the agent stays Local. lo0 holds loopback, so a forward to it +// keeps the agent exposed whether or not the config holds the lo0 interface, as +// do a forward to 127.0.0.1, to an alias holding it, and to a name no alias +// defines. So does a forward to This Firewall, (self), which pf reads as every +// address of every interface, lo0's ::1 among them. Through 26.1.1 OPNsense +// disables a forward to (self), or to an interface name no alias defines, as an +// invalid target, so there the lo0 and (self) cases over-report. +func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { + t.Parallel() + + const loopHost = `127.0.0.1` + + aliases := snmpForwardAlias("d4d4d4d4-0000-4000-8000-000000000001", "LOOP_HOST", "host", loopHost) + + tests := []struct { + name string + target string + // network writes the rule's destination as a network element, and + // listen replaces the agent's listen list of 127.0.0.1. + network bool + listen string + lo0 bool + exposed bool + }{ + {name: "forward to lanip", target: "lanip", network: true}, + {name: "forward to wanip", target: "wanip", network: true}, + {name: "forward to the lan net", target: "lan", network: true}, + {name: "forward to lanip with the lo0 interface", target: "lanip", network: true, lo0: true}, + { + name: "forward to lanip, agent bound to 127.0.0.1 and ::1", + target: "lanip", network: true, listen: "127.0.0.1,::1", lo0: true, + }, + { + name: "forward to the lo0 net with the lo0 interface", + target: "lo0", network: true, lo0: true, exposed: true, + }, + { + name: "forward to the lo0 net, agent bound to ::1", + target: "lo0", network: true, listen: "::1", lo0: true, exposed: true, + }, + {name: "forward to the lo0 net without the lo0 interface", target: "lo0", network: true, exposed: true}, + { + name: "forward to (self), agent bound to ::1", + target: "(self)", network: true, listen: "::1", lo0: true, exposed: true, + }, + {name: "forward to 127.0.0.1 with the lo0 interface", target: loopHost, lo0: true, exposed: true}, + {name: "forward to an alias holding 127.0.0.1", target: "LOOP_HOST", lo0: true, exposed: true}, + {name: "forward to a name no alias defines", target: "GONE", exposed: true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + rule := snmpForwardRule(tc.target, "nat_1") + if tc.network { + rule = snmpForwardNetworkRule(tc.target) + } + + listen := loopHost + if tc.listen != "" { + listen = tc.listen + } + + config := snmpForwardConfig(listen, rule, snmpLegacyForward(tc.target, "nat_1", ""), aliases) + if tc.lo0 { + config = strings.Replace(config, "\n ", snmpLoopbackInterface, 1) + } + + device := parseConfig(t, config) + require.Equal(t, strings.Split(listen, ","), device.SNMP.ListenAddresses) + require.Len(t, device.NAT.InboundRules, 1) + require.Equal(t, tc.target, device.NAT.InboundRules[0].InternalIP, "target") + require.Equal(t, tc.lo0, slices.ContainsFunc(device.Interfaces, func(iface common.Interface) bool { + return iface.Name == "lo0" && iface.IPAddress == loopHost + }), "lo0 interface") + + assertSNMPForwardExposure(t, device, tc.exposed) + }) + } +} + +// TestTargetHoldsLoopback_InterfaceTargets checks how a forward's target that +// names an interface is read. It counts only when the interface's own IPv4 or +// IPv6 address is a loopback address, whatever the place of the interface in +// the list. An interface with a dynamic address, or none, holds no loopback. +// lo0ip counts beside a lo0 holding loopback, although OPNsense maps the key +// and "ip" only for wan, lan and optN, which over-reports. A name that matches +// no interface exactly, including one in another case, falls back to the +// alias-name reading and counts, as does lo0 on a config without the lo0 +// interface. An alias named like an interface is read in place of the +// interface, as OPNsense's alias map from 26.1.2 adds every alias but a port +// alias after the interfaces, so it counts only when its members hold +// loopback, whatever the interface holds. A port alias is not in that map, so +// one named like an interface leaves the interface's reading in place, and one +// named like no interface does not count, since from 26.1.2 OPNsense disables +// a forward to it as an invalid target. +func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { + t.Parallel() + + lan := common.Interface{Name: "lan", IPAddress: "192.168.1.1", IPv6Address: "2001:db8:1::1"} + wanDHCP := common.Interface{Name: "wan", IPAddress: "dhcp", IPv6Address: "dhcp6"} + trackOnly := common.Interface{Name: "opt1", IPv6Address: "track6"} + lo0 := common.Interface{Name: "lo0", IPAddress: "127.0.0.1", IPv6Address: "::1"} + lo0IPv6Only := common.Interface{Name: "lo0", IPv6Address: "::1"} + loopbackDevice := common.Interface{Name: "opt2", IPAddress: "127.0.0.2"} + + objects := common.NamedObjects{ + "LOOP_HOST": {Name: "LOOP_HOST", Type: common.NamedObjectTypeHost, Members: []string{"127.0.0.1"}}, + } + + // aliasesNamedLikeInterfaces holds an alias named like the lo0 interface + // that holds no loopback, and aliases named like the lan interface and its + // address that hold 127.0.0.1. + aliasesNamedLikeInterfaces := common.NamedObjects{ + "lo0": {Name: "lo0", Type: common.NamedObjectTypeHost, Members: []string{"192.0.2.10"}}, + "lan": {Name: "lan", Type: common.NamedObjectTypeHost, Members: []string{"127.0.0.1"}}, + "lanip": {Name: "lanip", Type: common.NamedObjectTypeHost, Members: []string{"127.0.0.1"}}, + } + + // portAliases holds port aliases named like the lo0 interface, like the + // lan address, and like no interface. + portAliases := common.NamedObjects{ + "lo0": {Name: "lo0", Type: common.NamedObjectTypePort, Members: []string{"161"}}, + "lanip": {Name: "lanip", Type: common.NamedObjectTypePort, Members: []string{"161"}}, + "SNMP_PORTS": {Name: "SNMP_PORTS", Type: common.NamedObjectTypePort, Members: []string{"161"}}, + } + + tests := []struct { + name string + target string + interfaces []common.Interface + // objects replaces the device's aliases when set. + objects common.NamedObjects + want bool + }{ + {name: "lan net", target: "lan", interfaces: []common.Interface{lo0, lan}}, + {name: "lan address", target: "lanip", interfaces: []common.Interface{lo0, lan}}, + {name: "DHCP wan address", target: "wanip", interfaces: []common.Interface{wanDHCP, lo0}}, + {name: "DHCP wan net", target: "wan", interfaces: []common.Interface{wanDHCP}}, + {name: "interface with no IPv4 address", target: "opt1ip", interfaces: []common.Interface{trackOnly}}, + {name: "lo0 net", target: "lo0", interfaces: []common.Interface{lan, lo0}, want: true}, + {name: "lo0 holding only ::1", target: "lo0", interfaces: []common.Interface{lan, lo0IPv6Only}, want: true}, + {name: "lo0 without the lo0 interface", target: "lo0", interfaces: []common.Interface{lan}, want: true}, + { + name: "address of an assigned loopback device", + target: "opt2ip", + interfaces: []common.Interface{lan, loopbackDevice}, + want: true, + }, + { + name: "lo0 address, a name OPNsense does not map", + target: "lo0ip", + interfaces: []common.Interface{lan, lo0}, + want: true, + }, + {name: "interface name in another case", target: "LANip", interfaces: []common.Interface{lan}, want: true}, + {name: "127.0.0.1", target: "127.0.0.1", interfaces: []common.Interface{lan, lo0}, want: true}, + {name: "alias holding 127.0.0.1", target: "LOOP_HOST", interfaces: []common.Interface{lan}, want: true}, + {name: "name no alias or interface defines", target: "GONE", interfaces: []common.Interface{lan}, want: true}, + { + name: "alias named like lo0 holding no loopback", + target: "lo0", + interfaces: []common.Interface{lan, lo0}, + objects: aliasesNamedLikeInterfaces, + }, + { + name: "alias named like lan holding 127.0.0.1", + target: "lan", + interfaces: []common.Interface{lo0, lan}, + objects: aliasesNamedLikeInterfaces, + want: true, + }, + { + name: "alias named like lanip holding 127.0.0.1", + target: "lanip", + interfaces: []common.Interface{lo0, lan}, + objects: aliasesNamedLikeInterfaces, + want: true, + }, + { + name: "port alias named like lo0", + target: "lo0", + interfaces: []common.Interface{lan, lo0}, + objects: portAliases, + want: true, + }, + { + name: "port alias named like lanip", + target: "lanip", + interfaces: []common.Interface{lo0, lan}, + objects: portAliases, + }, + { + name: "port alias named like no interface", + target: "SNMP_PORTS", + interfaces: []common.Interface{lan, lo0}, + objects: portAliases, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{Interfaces: tc.interfaces, NamedObjects: objects} + if tc.objects != nil { + device.NamedObjects = tc.objects + } + + assert.Equal(t, tc.want, targetHoldsLoopback(tc.target, device)) + }) + } +} + +// TestSNMPAgent_ForwardToPortAliasName drives OPNsense configs with a net-snmp +// agent bound only to 127.0.0.1 and the lo0 interface through parse, convert +// and red mode, each with a WAN forward of UDP 161 to a name a port alias +// defines and a WAN rule passing UDP 161 to any destination. From 26.1.2 +// OPNsense leaves port aliases out of the names a forward's target maps to, so +// a port alias named lo0 leaves the forward to the lo0 net, which keeps the +// agent exposed, and a forward to a port alias named like no interface is +// disabled as an invalid target, which leaves the agent Local. Through 26.1.1 +// OPNsense maps a target to any alias of its name, port aliases included, so +// there the forward in the first case does not reach the lo0 net, and that +// case over-reports. +func TestSNMPAgent_ForwardToPortAliasName(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + target string + exposed bool + }{ + {name: "port alias named like the lo0 interface", target: "lo0", exposed: true}, + {name: "port alias named like no interface", target: "SNMP_PORTS"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + rule := strings.Replace(snmpForwardRule(tc.target, ""), + "
"+tc.target+"
", "1", 1) + alias := snmpForwardAlias("d4d4d4d4-0000-4000-8000-000000000002", tc.target, "port", "161") + config := strings.Replace(snmpForwardConfig("127.0.0.1", rule, snmpLegacyForward(tc.target, "", ""), alias), + "\n ", snmpLoopbackInterface, 1) + + device := parseConfig(t, config) + require.Equal(t, common.NamedObjectTypePort, device.NamedObjects[tc.target].Type, "alias type") + require.Len(t, device.NAT.InboundRules, 1) + require.Equal(t, tc.target, device.NAT.InboundRules[0].InternalIP, "target") + + assertSNMPForwardExposure(t, device, tc.exposed) + }) + } +} diff --git a/internal/audit/snmp_forward_interface_test.go b/internal/audit/snmp_forward_interface_test.go new file mode 100644 index 000000000..ef77c4a93 --- /dev/null +++ b/internal/audit/snmp_forward_interface_test.go @@ -0,0 +1,47 @@ +package audit + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestSNMPAgent_ForwardInterfaceIsNotRead pins what GOTCHAS.md section 8.4 +// says of forwardsToLoopback: the forward's interface is not read. A LAN +// forward of UDP 161 to loopback lets LAN hosts reach an agent bound only to +// 127.0.0.1, and it also keeps the agent from being set Local, so a WAN rule +// passing UDP 161 to the firewall reports the agent as WAN-exposed. No WAN +// packet is redirected to the agent, so that over-reports, the safe direction. +func TestSNMPAgent_ForwardInterfaceIsNotRead(t *testing.T) { + t.Parallel() + + const loopHost = `127.0.0.1` + + lanForward := strings.Replace(snmpLegacyForward(loopHost, "", ""), + "wan", "lan", 1) + + tests := []struct { + name string + rules string + }{ + {name: "WAN rule to 127.0.0.1 of its own", rules: snmpForwardRule(loopHost, "")}, + {name: "WAN rule to the WAN address", rules: snmpWANAddressRule()}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpForwardConfig(loopHost, tc.rules, lanForward, "")) + require.Equal(t, []string{loopHost}, device.SNMP.ListenAddresses) + require.Len(t, device.NAT.InboundRules, 1) + forward := device.NAT.InboundRules[0] + require.Equal(t, []string{"lan"}, forward.Interfaces, "interfaces") + require.Equal(t, "udp", forward.Protocol, "protocol") + require.Equal(t, loopHost, forward.InternalIP, "target") + + assertSNMPForwardExposure(t, device, true) + }) + } +} diff --git a/internal/audit/snmp_forward_port_test.go b/internal/audit/snmp_forward_port_test.go new file mode 100644 index 000000000..a0083ac08 --- /dev/null +++ b/internal/audit/snmp_forward_port_test.go @@ -0,0 +1,233 @@ +package audit + +import ( + "strings" + "testing" + + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// snmpDNSForward is a port forward sending LAN DNS queries to the firewall's +// resolver: TCP/UDP 53 on the LAN address to target port 53, in the shape +// snmpLegacyForward writes. +func snmpDNSForward(target string) string { + return strings.NewReplacer( + "wan", "lan", + "udp", "tcp/udp", + "161", "53", + "wanip", "lanip", + "161", "53", + ).Replace(snmpLegacyForward(target, "", "")) +} + +// snmpWANAddressRule is a WAN pass rule for UDP 161 to the WAN address. +func snmpWANAddressRule() string { + return strings.Replace(snmpForwardRule("", ""), "
", "wanip", 1) +} + +// TestSNMPAgent_ForwardProtocolAndPortsDecideExposure drives OPNsense configs +// with a net-snmp agent bound only to 127.0.0.1 through parse, convert and red +// mode, with port forwards to 127.0.0.1 that differ in protocol and ports. Only +// a forward that can redirect UDP to port 161 reaches the agent and leaves it +// to the WAN rule; a DNS redirect to loopback, such as one sending LAN queries +// to the local resolver, leaves it local. +func TestSNMPAgent_ForwardProtocolAndPortsDecideExposure(t *testing.T) { + t.Parallel() + + const loopHost = `127.0.0.1` + + tests := []struct { + name string + rules string + forwards string + // protocol, port and local are what the forward must convert to, so + // a case cannot pass on a field the parser did not read. + protocol, port, local string + exposed bool + }{ + { + name: "WAN forward of UDP 1161 to 127.0.0.1 port 161", + protocol: "udp", port: "1161", local: "161", + rules: snmpForwardRule(loopHost, "nat_1"), + forwards: strings.Replace( + snmpLegacyForward(loopHost, "nat_1", ""), "161<", "1161<", 1), + exposed: true, + }, + { + // OPNsense drops the ports of a forward with no protocol, so it + // redirects UDP 161 to loopback with the port kept. + name: "26.1 forward of any protocol to 127.0.0.1", + rules: snmpForwardRule(loopHost, "nat_1"), + forwards: strings.NewReplacer( + "udp", "", + "161", "", + "161", "", + ).Replace(snmpModelForward(loopHost, "0")), + exposed: true, + }, + { + name: "rule to 127.0.0.1 of its own, LAN forward of TCP/UDP 53 to 127.0.0.1 port 53", + protocol: "tcp/udp", port: "53", local: "53", + rules: snmpForwardRule(loopHost, ""), + forwards: snmpDNSForward(loopHost), + }, + { + name: "rule to the WAN address, LAN forward of TCP/UDP 53 to 127.0.0.1 port 53", + protocol: "tcp/udp", port: "53", local: "53", + rules: snmpWANAddressRule(), + forwards: snmpDNSForward(loopHost), + }, + { + name: "rule to 127.0.0.1 of its own, WAN forward of UDP 161 to 127.0.0.1 port 1161", + protocol: "udp", port: "161", local: "1161", + rules: snmpForwardRule(loopHost, ""), + forwards: strings.Replace( + snmpLegacyForward(loopHost, "", ""), "161<", "1161<", 1), + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpForwardConfig(loopHost, tc.rules, tc.forwards, "")) + require.Equal(t, []string{loopHost}, device.SNMP.ListenAddresses) + require.Len(t, device.NAT.InboundRules, 1) + forward := device.NAT.InboundRules[0] + require.False(t, forward.Disabled, "disabled") + require.Equal(t, tc.protocol, forward.Protocol, "protocol") + require.Equal(t, tc.port, forward.Destination.Port, "destination port") + require.Equal(t, tc.local, forward.LocalPort, "local port") + + assertSNMPForwardExposure(t, device, tc.exposed) + }) + } +} + +// TestForwardCanReachSNMPPort checks which port forwards can redirect UDP to +// port 161, where the os-net-snmp agent listens. OPNsense reads a forward's +// ports only for tcp, udp and tcp/udp, so a forward with no protocol reaches +// the agent whatever ports it names, and one for another protocol never does. +// For udp and tcp/udp the destination port decides without a local port, and +// the local port decides with one when the destination port is a single number +// or any port. A port alias is read as reaching the agent, as is a range +// mapped to a local port. +func TestForwardCanReachSNMPPort(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + protocol, dstPort, locPort string + want bool + }{ + {name: "no protocol, no ports", want: true}, + {name: "no protocol, DNS ports", dstPort: "53", locPort: "53", want: true}, + {name: "any protocol, DNS port", protocol: "any", dstPort: "53", want: true}, + {name: "ANY protocol", protocol: "ANY", dstPort: "53", want: true}, + {name: "udp to 161", protocol: "udp", dstPort: "161", want: true}, + {name: "UDP to 161 kept as 161", protocol: "UDP", dstPort: "161", locPort: "161", want: true}, + {name: "udp with surrounding space", protocol: " udp ", dstPort: "161", want: true}, + {name: "tcp/udp to 161", protocol: "tcp/udp", dstPort: "161", locPort: "161", want: true}, + {name: "TCP/UDP DNS redirect", protocol: "TCP/UDP", dstPort: "53", locPort: "53"}, + {name: "tcp to 161", protocol: "tcp", dstPort: "161", locPort: "161"}, + {name: "icmp", protocol: "icmp"}, + {name: "udplite to 161", protocol: "udplite", dstPort: "161"}, + {name: "udp, any destination port", protocol: "udp", want: true}, + {name: "udp, destination port any", protocol: "udp", dstPort: "any", want: true}, + {name: "udp to 53", protocol: "udp", dstPort: "53"}, + {name: "udp to a range holding 161", protocol: "udp", dstPort: "100-200", want: true}, + {name: "udp to a range below 161", protocol: "udp", dstPort: "1-100"}, + {name: "udp to a port alias", protocol: "udp", dstPort: "SNMP_PORTS", want: true}, + {name: "udp to the snmp service name", protocol: "udp", dstPort: "snmp", want: true}, + {name: "udp 1161 to local port 161", protocol: "udp", dstPort: "1161", locPort: "161", want: true}, + {name: "udp 161 to local port 1161", protocol: "udp", dstPort: "161", locPort: "1161"}, + {name: "udp 161 to local port 53", protocol: "udp", dstPort: "161", locPort: "53"}, + {name: "udp, any destination port, to local port 53", protocol: "udp", locPort: "53"}, + { + name: "udp, destination port any, to local port 161", + protocol: "udp", + dstPort: "any", + locPort: "161", + want: true, + }, + {name: "udp range mapped from local port 53", protocol: "udp", dstPort: "1000-2000", locPort: "53", want: true}, + {name: "udp alias mapped to local port 53", protocol: "udp", dstPort: "SNMP_PORTS", locPort: "53", want: true}, + {name: "udp 53 to a local port alias", protocol: "udp", dstPort: "53", locPort: "SNMP_PORTS", want: true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + nat := common.InboundNATRule{ + Protocol: tc.protocol, + Destination: common.RuleEndpoint{Port: tc.dstPort}, + LocalPort: tc.locPort, + } + + assert.Equal(t, tc.want, forwardCanReachSNMPPort(nat)) + }) + } +} + +// TestForwardsToLoopback_PortAndTargetOnOneForward checks that the forward +// which can reach port 161 must also be the one whose target holds loopback: a +// DNS redirect to loopback beside an SNMP forward to a LAN host does not count, +// in either order, and an SNMP forward to loopback counts beside a DNS redirect +// to loopback, in either order. +func TestForwardsToLoopback_PortAndTargetOnOneForward(t *testing.T) { + t.Parallel() + + dnsToLoopback := common.InboundNATRule{ + Protocol: "tcp/udp", + Destination: common.RuleEndpoint{Port: "53"}, + InternalIP: "127.0.0.1", + LocalPort: "53", + } + snmpToLAN := common.InboundNATRule{ + Protocol: "udp", + Destination: common.RuleEndpoint{Port: "161"}, + InternalIP: "192.168.1.50", + LocalPort: "161", + } + snmpToLoopback := snmpToLAN + snmpToLoopback.InternalIP = "127.0.0.1" + + tests := []struct { + name string + forwards []common.InboundNATRule + want bool + }{ + {name: "DNS redirect to loopback alone", forwards: []common.InboundNATRule{dnsToLoopback}}, + { + name: "DNS redirect to loopback, then SNMP forward to a LAN host", + forwards: []common.InboundNATRule{dnsToLoopback, snmpToLAN}, + }, + { + name: "SNMP forward to a LAN host, then DNS redirect to loopback", + forwards: []common.InboundNATRule{snmpToLAN, dnsToLoopback}, + }, + { + name: "DNS redirect to loopback, then SNMP forward to loopback", + forwards: []common.InboundNATRule{dnsToLoopback, snmpToLoopback}, + want: true, + }, + { + name: "SNMP forward to loopback, then DNS redirect to loopback", + forwards: []common.InboundNATRule{snmpToLoopback, dnsToLoopback}, + want: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{NAT: common.NATConfig{InboundRules: tc.forwards}} + + assert.Equal(t, tc.want, forwardsToLoopback(device)) + }) + } +} diff --git a/internal/audit/snmp_forward_runtime_alias_test.go b/internal/audit/snmp_forward_runtime_alias_test.go new file mode 100644 index 000000000..f5380344a --- /dev/null +++ b/internal/audit/snmp_forward_runtime_alias_test.go @@ -0,0 +1,223 @@ +package audit + +import ( + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestTargetHoldsLoopback_RuntimeAliases checks a forward's target that is, or +// names, an alias whose addresses OPNsense gets at runtime: a URL alias, a URL +// table, a URL table in JSON format, or an external alias. Its members in the +// config are URLs or nothing, so they cannot show what it holds, and it may +// hold a loopback address. Such a target counts, as does an alias that names +// one at any depth, an alias of that name read in place of an interface, and a +// disabled one. A GeoIP alias holds country networks, which no loopback address +// is in, and a network group naming only it and a LAN host holds no loopback, +// so neither counts, and a nesting loop among aliases with no such alias ends. +func TestTargetHoldsLoopback_RuntimeAliases(t *testing.T) { + t.Parallel() + + alias := func(name string, aliasType common.NamedObjectType, members ...string) common.NamedObject { + return common.NamedObject{Name: name, Type: aliasType, Members: members} + } + + objects := common.NamedObjects{ + "URL_LIST": alias("URL_LIST", common.NamedObjectTypeURL, "https://example.com/list.txt"), + "URL_TABLE": alias("URL_TABLE", aliasTypeURLTable, "https://example.com/table.txt"), + "URL_JSON": alias("URL_JSON", aliasTypeURLJSON, "https://example.com/table.json"), + "EXTERNAL": alias("EXTERNAL", common.NamedObjectTypeExternal), + "OFF_TABLE": { + Name: "OFF_TABLE", + Type: aliasTypeURLTable, + Members: []string{"https://example.com/off.txt"}, + Disabled: true, + }, + "COUNTRIES": alias("COUNTRIES", common.NamedObjectTypeGeoIP, "NL"), + "LAN_HOST": alias("LAN_HOST", common.NamedObjectTypeHost, "192.168.1.50"), + "TABLE_GROUP": alias("TABLE_GROUP", aliasTypeNetworkGroup, "LAN_HOST", "URL_TABLE"), + "OUTER_GROUP": alias("OUTER_GROUP", aliasTypeNetworkGroup, "LAN_HOST", "TABLE_GROUP"), + "JSON_HOST": alias("JSON_HOST", common.NamedObjectTypeHost, "192.168.1.51", "URL_JSON"), + "URL_NET": alias("URL_NET", common.NamedObjectTypeNetwork, "192.168.2.0/24", "URL_LIST"), + "GEO_GROUP": alias("GEO_GROUP", aliasTypeNetworkGroup, "LAN_HOST", "COUNTRIES"), + "LOOP_A": alias("LOOP_A", aliasTypeNetworkGroup, "LAN_HOST", "LOOP_B"), + "LOOP_B": alias("LOOP_B", aliasTypeNetworkGroup, "LOOP_A"), + "lan": alias("lan", aliasTypeURLTable, "https://example.com/lan.txt"), + } + + interfaces := []common.Interface{ + {Name: "wan", IPAddress: "198.51.100.2"}, + {Name: "lan", IPAddress: "192.168.1.1"}, + } + + tests := []struct { + name string + target string + want bool + }{ + {name: "URL alias", target: "URL_LIST", want: true}, + {name: "URL table", target: "URL_TABLE", want: true}, + {name: "URL table in JSON format", target: "URL_JSON", want: true}, + {name: "external alias", target: "EXTERNAL", want: true}, + {name: "disabled URL table", target: "OFF_TABLE", want: true}, + {name: "network group naming the URL table second", target: "TABLE_GROUP", want: true}, + {name: "network group naming that group second", target: "OUTER_GROUP", want: true}, + {name: "host alias naming the JSON table second", target: "JSON_HOST", want: true}, + {name: "network alias naming the URL alias second", target: "URL_NET", want: true}, + {name: "URL table named like the lan interface", target: "lan", want: true}, + {name: "address of the lan interface", target: "lanip"}, + {name: "GeoIP alias", target: "COUNTRIES"}, + {name: "network group naming a LAN host and a GeoIP alias", target: "GEO_GROUP"}, + {name: "nesting loop with no runtime alias", target: "LOOP_A"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{Interfaces: interfaces, NamedObjects: objects} + assert.Equal(t, tc.want, targetHoldsLoopback(tc.target, device)) + }) + } +} + +// TestSNMPAgent_ForwardToRuntimeAlias drives OPNsense configs with a net-snmp +// agent bound only to 127.0.0.1 through parse, convert and red mode. A WAN rule +// passes UDP 161 to any destination, which reaches the agent only if a forward +// can redirect that traffic to loopback. A WAN forward of UDP 161 to an alias +// whose addresses OPNsense gets at runtime, or to a network group naming one, +// may do so, so the agent keeps the exposure the rule gives it. With the rule +// to the URL table itself instead, the rule is the forward's own and is not +// read (forwardsToAnotherHost), so no rule passes WAN traffic to the agent, and +// the forward keeps the LAN reachability it has without one. A forward to a +// GeoIP alias, or no forward, leaves the agent Local. +func TestSNMPAgent_ForwardToRuntimeAlias(t *testing.T) { + t.Parallel() + + aliases := snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000001", "LAN_HOST", "host", "192.168.1.50") + + snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000002", "URL_TABLE", "urltable", + "https://example.com/table.txt") + + snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000003", "URL_LIST", "url", + "https://example.com/list.txt") + + snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000004", "URL_JSON", "urljson", + "https://example.com/table.json") + + snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000005", "EXTERNAL", "external", "") + + snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000006", "COUNTRIES", "geoip", "NL") + + snmpForwardAlias("e5e5e5e5-0000-4000-8000-000000000007", "TABLE_GROUP", "networkgroup", + "LAN_HOST\nURL_TABLE") + + anyRule := snmpForwardAnyRule() + + tests := []struct { + name string + target string + rules string + forwards string + want analysis.Reachability + }{ + { + name: "rule to any, forward to a URL table", + target: "URL_TABLE", + rules: anyRule, + forwards: snmpLegacyForward("URL_TABLE", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to any, 26.1 forward to a URL table", + target: "URL_TABLE", + rules: anyRule, + forwards: snmpModelForward("URL_TABLE", "0"), + want: analysis.WANReachable, + }, + { + name: "rule to any, forward to a network group naming the URL table second", + target: "TABLE_GROUP", + rules: anyRule, + forwards: snmpLegacyForward("TABLE_GROUP", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to any, forward to a URL alias", + target: "URL_LIST", + rules: anyRule, + forwards: snmpLegacyForward("URL_LIST", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to any, forward to a URL table in JSON format", + target: "URL_JSON", + rules: anyRule, + forwards: snmpLegacyForward("URL_JSON", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to any, forward to an external alias", + target: "EXTERNAL", + rules: anyRule, + forwards: snmpLegacyForward("EXTERNAL", "", ""), + want: analysis.WANReachable, + }, + { + name: "rule to the URL table, forward to the URL table", + target: "URL_TABLE", + rules: snmpForwardRule("URL_TABLE", "nat_1"), + forwards: snmpLegacyForward("URL_TABLE", "nat_1", ""), + want: analysis.LANOnly, + }, + { + name: "rule to any, forward to a GeoIP alias", + target: "COUNTRIES", + rules: anyRule, + forwards: snmpLegacyForward("COUNTRIES", "", ""), + want: analysis.Local, + }, + { + name: "rule to any, no forward", + rules: anyRule, + want: analysis.Local, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpForwardConfig("127.0.0.1", tc.rules, tc.forwards, aliases)) + require.Equal(t, []string{"127.0.0.1"}, device.SNMP.ListenAddresses) + require.Equal(t, aliasTypeURLTable, device.NamedObjects["URL_TABLE"].Type, "URL table type") + require.Equal(t, aliasTypeURLJSON, device.NamedObjects["URL_JSON"].Type, "JSON table type") + + if tc.target == "" { + require.Empty(t, device.NAT.InboundRules) + } else { + require.Len(t, device.NAT.InboundRules, 1) + require.Equal(t, tc.target, device.NAT.InboundRules[0].InternalIP, "target") + } + + assertSNMPReachability(t, device, tc.want) + }) + } +} + +// snmpForwardAnyRule is a WAN pass rule for UDP 161 to any destination, with +// no link to a forward. +func snmpForwardAnyRule() string { + return ` + + pass + wan + inet + udp + + 1 + + + 1 + 161 + + snmp + ` +} diff --git a/internal/audit/snmp_loopback_forward_test.go b/internal/audit/snmp_loopback_forward_test.go new file mode 100644 index 000000000..5141e5179 --- /dev/null +++ b/internal/audit/snmp_loopback_forward_test.go @@ -0,0 +1,454 @@ +package audit + +import ( + "slices" + "strings" + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// snmpForwardConfig is an OPNsense config with a net-snmp agent answering +// "public" on the given listen list, with the given filter rules, port +// forwards and aliases. +func snmpForwardConfig(listen, rules, forwards, aliases string) string { + return ` + + + fw + example.com + + + + 1 + vtnet0 + 198.51.100.2 + 24 + + + 1 + vtnet1 + 192.168.1.1 + 24 + + + ` + rules + ` + + + + automatic + ` + forwards + ` + + + + + ` + aliases + ` + + + + + + 1 + public + ` + listen + ` + + + + + + +` +} + +// snmpForwardRule is a WAN pass rule for UDP 161 to dest. A non-empty assoc +// links it to the port forward that stores it. +func snmpForwardRule(dest, assoc string) string { + return ` + + pass + ` + assoc + ` + wan + inet + udp + + 1 + + +
` + dest + `
+ 161 +
+ snmp +
` +} + +// snmpLegacyForward is a port forward as OPNsense wrote it up to 25.7, from +// UDP 161 on the WAN address to target, with any extra elements appended. +func snmpLegacyForward(target, assoc, extra string) string { + return ` + + udp + wan + inet + snmp forward + ` + assoc + ` + ` + target + ` + 161 + + 1 + + + wanip + 161 + ` + extra + ` + ` +} + +// snmpProxyForward is a transparent web proxy's port forward: TCP 80 on the +// LAN to target port 3128, in the shape snmpLegacyForward writes. +func snmpProxyForward(target string) string { + return strings.NewReplacer( + "wan", "lan", + "udp", "tcp", + "161", "3128", + "161", "80", + ).Replace(snmpLegacyForward(target, "", "")) +} + +// snmpModelForward is the same port forward as OPNsense 26.1 and later write +// it, with every flag element present. +func snmpModelForward(target, disabled string) string { + return ` + + 100 + ` + disabled + ` + 0 + wan + inet + udp + + + + 0 + + + wanip + 161 + 0 + + ` + target + ` + 161 + snmp forward + + + ` +} + +// snmpForwardAlias is an alias of the given type with newline-separated +// members. +func snmpForwardAlias(uuid, name, aliasType, members string) string { + return ` + + ` + name + ` + ` + aliasType + ` + ` + members + ` + ` +} + +// TestSNMPAgent_PortForwardToLoopbackKeepsWANExposure drives OPNsense configs +// with a net-snmp agent bound only to 127.0.0.1 through parse, convert and red +// mode. pf rewrites a forward's destination before delivery, so a WAN forward +// of UDP 161 to loopback reaches that agent, and the filter rule passing it +// decides the agent's reachability as for any other listen list. Without such +// a forward, a WAN rule to 127.0.0.1 of its own delivers nothing to the agent, +// so it stays local, as it does when the only forward to loopback cannot reach +// UDP 161. The cases vary what the forward targets, its flags in both stored +// shapes, its place in the list, and the service it forwards. +func TestSNMPAgent_PortForwardToLoopbackKeepsWANExposure(t *testing.T) { + t.Parallel() + + const ( + loopHost = `127.0.0.1` + lanHost = `192.168.1.50` + ) + + aliases := snmpForwardAlias("c3c3c3c3-0000-4000-8000-000000000001", "LOOP_HOST", "host", loopHost) + + snmpForwardAlias("c3c3c3c3-0000-4000-8000-000000000002", "LAN_HOST", "host", lanHost) + + snmpForwardAlias("c3c3c3c3-0000-4000-8000-000000000003", "SNMP_GROUP", "networkgroup", "LAN_HOST\nLOOP_HOST") + + tests := []struct { + name string + rules string + forwards string + // disabled and noRDR are what the last forward must convert to, so a + // case cannot pass on a flag the parser did not read. + disabled, noRDR bool + exposed bool + }{ + { + name: "forward to 127.0.0.1", + rules: snmpForwardRule(loopHost, "nat_1"), + forwards: snmpLegacyForward(loopHost, "nat_1", ""), + exposed: true, + }, + { + name: "forward to an alias holding 127.0.0.1", + rules: snmpForwardRule("LOOP_HOST", "nat_1"), + forwards: snmpLegacyForward("LOOP_HOST", "nat_1", ""), + exposed: true, + }, + { + name: "forward to a network group naming that alias second", + rules: snmpForwardRule("SNMP_GROUP", "nat_1"), + forwards: snmpLegacyForward("SNMP_GROUP", "nat_1", ""), + exposed: true, + }, + { + name: "forward to a LAN host first, to 127.0.0.1 second", + rules: snmpForwardRule(lanHost, "nat_0") + snmpForwardRule(loopHost, "nat_1"), + forwards: snmpLegacyForward(lanHost, "nat_0", "") + snmpLegacyForward(loopHost, "nat_1", ""), + exposed: true, + }, + { + name: "26.1 forward to 127.0.0.1, not disabled", + rules: snmpForwardRule(loopHost, "nat_1"), + forwards: snmpModelForward(loopHost, "0"), + exposed: true, + }, + { + // pf reads (self) as every address of the firewall, lo0's among + // them. + name: "forward to (self)", + rules: snmpForwardNetworkRule("(self)"), + forwards: snmpLegacyForward("(self)", "nat_1", ""), + exposed: true, + }, + { + name: "26.1 forward to (self)", + rules: snmpForwardNetworkRule("(self)"), + forwards: snmpModelForward("(self)", "0"), + exposed: true, + }, + { + // A transparent proxy's TCP forward to loopback cannot reach the + // agent on UDP 161. + name: "rule to 127.0.0.1 of its own, LAN forward of TCP 80 to 127.0.0.1 port 3128", + rules: snmpForwardRule(loopHost, ""), + forwards: snmpProxyForward(loopHost), + }, + { + name: "rule to 127.0.0.1 of its own, no forward", + rules: snmpForwardRule(loopHost, ""), + }, + { + name: "rule to 127.0.0.1 of its own, forward to a LAN host", + rules: snmpForwardRule(loopHost, "") + snmpForwardRule(lanHost, "nat_0"), + forwards: snmpLegacyForward(lanHost, "nat_0", ""), + }, + { + name: "rule to 127.0.0.1 of its own, forward to an alias holding a LAN host", + rules: snmpForwardRule(loopHost, "") + snmpForwardRule("LAN_HOST", "nat_0"), + forwards: snmpLegacyForward("LAN_HOST", "nat_0", ""), + }, + { + name: "rule to 127.0.0.1 of its own, disabled forward to 127.0.0.1", + rules: snmpForwardRule(loopHost, ""), + forwards: snmpLegacyForward(loopHost, "", "\n 1"), + disabled: true, + }, + { + name: "rule to 127.0.0.1 of its own, no-RDR forward naming 127.0.0.1", + rules: snmpForwardRule(loopHost, ""), + forwards: snmpLegacyForward(loopHost, "", "\n 1"), + noRDR: true, + }, + { + name: "rule to 127.0.0.1 of its own, disabled 26.1 forward to 127.0.0.1", + rules: snmpForwardRule(loopHost, ""), + forwards: snmpModelForward(loopHost, "1"), + disabled: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := parseConfig(t, snmpForwardConfig(loopHost, tc.rules, tc.forwards, aliases)) + require.Equal(t, []string{loopHost}, device.SNMP.ListenAddresses) + require.Len(t, device.NAT.InboundRules, strings.Count(tc.forwards, "")) + if len(device.NAT.InboundRules) > 0 { + last := device.NAT.InboundRules[len(device.NAT.InboundRules)-1] + require.Equal(t, tc.disabled, last.Disabled, "disabled") + require.Equal(t, tc.noRDR, last.NoRDR, "no-RDR") + } + + assertSNMPForwardExposure(t, device, tc.exposed) + }) + } +} + +// assertSNMPForwardExposure checks that red mode gives the SNMP agent on device +// the reachability exposed implies, and reports it as WAN-exposed exactly when +// exposed is true. +func assertSNMPForwardExposure(t *testing.T, device *common.CommonDevice, exposed bool) { + t.Helper() + + want := analysis.Local + if exposed { + want = analysis.WANReachable + } + + assertSNMPReachability(t, device, want) +} + +// assertSNMPReachability checks that red mode gives the SNMP agent on device +// the reachability want, and reports it as WAN-exposed exactly when want is +// WAN-reachable. +func assertSNMPReachability(t *testing.T, device *common.CommonDevice, want analysis.Reachability) { + t.Helper() + + services := serviceExposures(device) + idx := slices.IndexFunc(services, func(s exposedService) bool { return s.name == serviceNameSNMP }) + require.GreaterOrEqual(t, idx, 0, "snmp missing from the services red mode considers: %+v", services) + assert.Equal(t, want, services[idx].reachability) + + report := newRedReport(device) + runRedAnalysis(report) + + _, reported := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + assert.Equal(t, want == analysis.WANReachable, reported, "red-mode SNMP exposure") +} + +// TestForwardsToLoopback_TargetsAndFlags checks which port forwards count as +// redirecting traffic to loopback. A target counts when it is, or spans, a +// loopback address, in either family or IPv4-mapped; when it is (self), which +// pf reads as every address of the firewall, while (SELF) is no target OPNsense +// redirects to and does not count; when it is an alias, or names one, that +// holds one or gets its addresses at runtime, as a URL table does; and when it +// is a name no alias defines that has the shape of an alias name. A disabled +// or no-RDR forward never counts, and the counting forward may sit anywhere in +// the list. +func TestForwardsToLoopback_TargetsAndFlags(t *testing.T) { + t.Parallel() + + objects := common.NamedObjects{ + "LOOP_HOST": {Name: "LOOP_HOST", Type: common.NamedObjectTypeHost, Members: []string{"127.0.0.1"}}, + "LAN_HOST": {Name: "LAN_HOST", Type: common.NamedObjectTypeHost, Members: []string{"192.168.1.50"}}, + "SPAN_RANGE": { + Name: "SPAN_RANGE", + Type: common.NamedObjectTypeHost, + Members: []string{"126.255.255.250-127.0.0.5"}, + }, + "UNSTORED": {Name: "UNSTORED", Type: common.NamedObjectTypeHost, Members: []string{"bogons"}}, + "URL_TABLE": { + Name: "URL_TABLE", + Type: aliasTypeURLTable, + Members: []string{"https://example.com/list.txt"}, + }, + "TABLE_GROUP": {Name: "TABLE_GROUP", Type: aliasTypeNetworkGroup, Members: []string{"LAN_HOST", "URL_TABLE"}}, + "SNMP_GROUP": {Name: "SNMP_GROUP", Type: aliasTypeNetworkGroup, Members: []string{"LAN_HOST", "LOOP_HOST"}}, + "LAN_GROUP": {Name: "LAN_GROUP", Type: aliasTypeNetworkGroup, Members: []string{"LAN_HOST"}}, + } + + forward := func(target string) common.InboundNATRule { + return common.InboundNATRule{Interfaces: []string{"wan"}, Protocol: "udp", InternalIP: target} + } + + tests := []struct { + name string + forwards []common.InboundNATRule + want bool + }{ + {name: "IPv4 loopback", forwards: []common.InboundNATRule{forward("127.0.0.1")}, want: true}, + {name: "another IPv4 loopback address", forwards: []common.InboundNATRule{forward("127.0.0.2")}, want: true}, + {name: "IPv6 loopback", forwards: []common.InboundNATRule{forward("::1")}, want: true}, + {name: "IPv4-mapped loopback", forwards: []common.InboundNATRule{forward("::ffff:127.0.0.1")}, want: true}, + {name: "loopback network", forwards: []common.InboundNATRule{forward("127.0.0.0/8")}, want: true}, + {name: "network spanning loopback", forwards: []common.InboundNATRule{forward("0.0.0.0/0")}, want: true}, + {name: "the firewall itself", forwards: []common.InboundNATRule{forward("(self)")}, want: true}, + {name: "the firewall itself in upper case", forwards: []common.InboundNATRule{forward("(SELF)")}}, + {name: "LAN host", forwards: []common.InboundNATRule{forward("192.168.1.50")}}, + {name: "IPv6 host", forwards: []common.InboundNATRule{forward("2001:db8::50")}}, + {name: "no target", forwards: []common.InboundNATRule{forward("")}}, + {name: "hostname with a domain", forwards: []common.InboundNATRule{forward("snmp.example.com")}}, + {name: "name no alias defines", forwards: []common.InboundNATRule{forward("DELETED_ALIAS")}, want: true}, + {name: "alias holding loopback", forwards: []common.InboundNATRule{forward("LOOP_HOST")}, want: true}, + {name: "alias holding a LAN host", forwards: []common.InboundNATRule{forward("LAN_HOST")}}, + { + name: "alias holding a range spanning loopback", + forwards: []common.InboundNATRule{forward("SPAN_RANGE")}, + want: true, + }, + { + name: "alias naming a table the config does not store", + forwards: []common.InboundNATRule{forward("UNSTORED")}, + want: true, + }, + {name: "URL table alias", forwards: []common.InboundNATRule{forward("URL_TABLE")}, want: true}, + { + name: "network group naming the URL table second", + forwards: []common.InboundNATRule{forward("TABLE_GROUP")}, + want: true, + }, + { + name: "network group naming the loopback alias second", + forwards: []common.InboundNATRule{forward("SNMP_GROUP")}, + want: true, + }, + {name: "network group naming a LAN alias", forwards: []common.InboundNATRule{forward("LAN_GROUP")}}, + { + name: "disabled forward to loopback", + forwards: []common.InboundNATRule{func() common.InboundNATRule { + f := forward("127.0.0.1") + f.Disabled = true + + return f + }()}, + }, + { + name: "no-RDR forward naming loopback", + forwards: []common.InboundNATRule{func() common.InboundNATRule { + f := forward("127.0.0.1") + f.NoRDR = true + + return f + }()}, + }, + { + name: "forward to a LAN host, then to loopback", + forwards: []common.InboundNATRule{forward("192.168.1.50"), forward("127.0.0.1")}, + want: true, + }, + {name: "no forward"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{ + NAT: common.NATConfig{InboundRules: tc.forwards}, + NamedObjects: objects, + } + + assert.Equal(t, tc.want, forwardsToLoopback(device)) + + // The forward decides whether a loopback-only agent is Local. + device.SNMP = common.SNMPConfig{Enabled: true, ListenAddresses: []string{"127.0.0.1"}} + services := []exposedService{ + {kind: exploitKindSNMP, name: serviceNameSNMP, reachability: analysis.WANReachable}, + } + applySNMPListen(device, services) + + want := analysis.Local + if tc.want { + want = analysis.WANReachable + } + + assert.Equal(t, want, services[0].reachability) + }) + } +} diff --git a/internal/audit/testdata/golden/exploit_notes.golden b/internal/audit/testdata/golden/exploit_notes.golden index db9eacdeb..50391e024 100644 --- a/internal/audit/testdata/golden/exploit_notes.golden +++ b/internal/audit/testdata/golden/exploit_notes.golden @@ -16,6 +16,12 @@ Network-management access reachable from untrusted networks can leak device and === kind=snmp blackhat=true === The management protocol is reachable from the internet and leaks configuration and topology detail. Community-based authentication provides little resistance, making the device an easy reconnaissance source. +=== kind=snmp-no-community blackhat=false === +Network-management access reachable from untrusted networks places the agent's authentication within reach of the internet, and anything the agent answers can leak device and topology detail. Disclosed information helps an attacker map the environment. + +=== kind=snmp-no-community blackhat=true === +The management protocol is reachable from the internet. The agent's authentication is an open target, and any answer it gives leaks configuration and topology detail that makes the device a reconnaissance source. + === kind=ssh blackhat=false === A remote administrative shell reachable from untrusted networks is a persistent authentication target. Compromise grants command-line administrative access to the device and a foothold into the networks it protects. diff --git a/internal/converter/builder/builder_services.go b/internal/converter/builder/builder_services.go index f07a8ba46..45eb9a84c 100644 --- a/internal/converter/builder/builder_services.go +++ b/internal/converter/builder/builder_services.go @@ -91,6 +91,7 @@ func (b *MarkdownBuilder) writeServicesSection(md *markdown.Markdown, data *comm md.PlainTextf("%s: %s", markdown.Bold("Read-Only Community"), formatters.EscapeMarkdownValue(data.SNMP.ROCommunity)). LF() } + writeSNMPAgentDetails(md, data.SNMP) md.H3("NTP") if data.NTP.PreferredServer != "" { diff --git a/internal/converter/builder/builder_snmp.go b/internal/converter/builder/builder_snmp.go new file mode 100644 index 000000000..492472757 --- /dev/null +++ b/internal/converter/builder/builder_snmp.go @@ -0,0 +1,40 @@ +package builder + +import ( + "strings" + + "github.com/EvilBit-Labs/opnDossier/internal/converter/formatters" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/nao1215/markdown" +) + +// writeSNMPAgentDetails writes the agent state, its listen addresses and its +// SNMPv3 users. A v3-only agent has no community, so without these lines the +// SNMP section would read as empty while an agent runs. +func writeSNMPAgentDetails(md *markdown.Markdown, snmp common.SNMPConfig) { + if snmp.Enabled { + md.PlainTextf("%s: %s", markdown.Bold(labelEnabled), formatters.FormatBool(snmp.Enabled)).LF() + } + + if len(snmp.ListenAddresses) > 0 { + md.PlainTextf("%s: %s", markdown.Bold("Listen Addresses"), + formatters.EscapeMarkdownValue(strings.Join(snmp.ListenAddresses, ", "))).LF() + } + + if len(snmp.Users) == 0 { + return + } + + users := make([]string, 0, len(snmp.Users)) + for _, user := range snmp.Users { + access := "read-only" + if user.ReadWrite { + access = "read-write" + } + + users = append(users, formatters.EscapeMarkdownValue(user.Username)+" ("+access+")") + } + + md.PlainTextf("%s:", markdown.Bold("SNMPv3 Users")).LF() + md.BulletList(users...) +} diff --git a/internal/converter/builder/builder_snmp_test.go b/internal/converter/builder/builder_snmp_test.go new file mode 100644 index 000000000..b94636be6 --- /dev/null +++ b/internal/converter/builder/builder_snmp_test.go @@ -0,0 +1,44 @@ +package builder + +import ( + "strings" + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/converter/formatters" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" +) + +// TestBuildServicesSection_SNMPAgentDetails checks that an agent with no +// community still shows in the SNMP section, through its state, listen +// addresses and SNMPv3 users. +func TestBuildServicesSection_SNMPAgentDetails(t *testing.T) { + t.Parallel() + + out := NewMarkdownBuilder().BuildServicesSection(&common.CommonDevice{ + SNMP: common.SNMPConfig{ + Enabled: true, + ListenAddresses: []string{"192.0.2.1", "2001:db8::1"}, + Users: []common.SNMPUser{ + {Username: "poller"}, + {Username: "config_push", ReadWrite: true}, + }, + }, + }) + + for _, want := range []string{ + "**Enabled**: " + formatters.FormatBool(true), + "**Listen Addresses**: 192.0.2.1, 2001:db8::1", + "**SNMPv3 Users**:", + "- poller (read-only)", + `- config\_push (read-write)`, + } { + if !strings.Contains(out, want) { + t.Errorf("services section missing %q:\n%s", want, out) + } + } + + empty := NewMarkdownBuilder().BuildServicesSection(&common.CommonDevice{}) + if strings.Contains(empty, "SNMPv3 Users") || strings.Contains(empty, "Listen Addresses") { + t.Errorf("services section without an agent shows agent details:\n%s", empty) + } +} diff --git a/internal/plugins/firewall/checks_dispatch.go b/internal/plugins/firewall/checks_dispatch.go index 9c24175d4..0e1c5ec33 100644 --- a/internal/plugins/firewall/checks_dispatch.go +++ b/internal/plugins/firewall/checks_dispatch.go @@ -226,8 +226,8 @@ func (fp *Plugin) newChecksTable() []newCheckEntry { }, { controlID: "FIREWALL-045", checkFn: (*Plugin).checkSNMPDisabledIfUnused, - title: "SNMP Enabled", description: "SNMP is configured with a community string", - recommendation: "Remove SNMP community string if SNMP is not required", + title: "SNMP Enabled", description: "An SNMP agent is enabled", + recommendation: "Disable the SNMP agent if SNMP is not required", component: "snmp-config", tags: []string{"snmp-security", "attack-surface", "firewall-controls"}, }, { diff --git a/internal/plugins/firewall/checks_encryption.go b/internal/plugins/firewall/checks_encryption.go index a5b13b6f6..50bebf156 100644 --- a/internal/plugins/firewall/checks_encryption.go +++ b/internal/plugins/firewall/checks_encryption.go @@ -124,15 +124,14 @@ func (fp *Plugin) checkTimezoneConfiguration(device *common.CommonDevice) checkR return checkResult{Result: device.System.Timezone != "", Known: true} } -// checkSNMPDisabledIfUnused checks that SNMP is disabled when not needed. -// An empty ROCommunity string indicates SNMP is not configured (good). -// Any non-empty value means SNMP is in use and may increase attack surface. +// checkSNMPDisabledIfUnused checks that no SNMP agent runs, since one adds +// attack surface whether it answers a community or only SNMPv3 users. func (fp *Plugin) checkSNMPDisabledIfUnused(device *common.CommonDevice) checkResult { if device == nil { return checkResult{Result: true, Known: true} } - return checkResult{Result: device.SNMP.ROCommunity == "", Known: true} + return checkResult{Result: !device.SNMP.IsEnabled(), Known: true} } // checkNoDefaultCommunityStrings checks that SNMP community strings are not diff --git a/internal/plugins/firewall/controls.go b/internal/plugins/firewall/controls.go index f2cc5e689..042717965 100644 --- a/internal/plugins/firewall/controls.go +++ b/internal/plugins/firewall/controls.go @@ -379,7 +379,7 @@ func newControlDefinitions() []compliance.Control { Category: "SNMP Security", Severity: "medium", Rationale: "SNMP exposes device information and can be exploited for reconnaissance", - Remediation: "Remove SNMP community string if SNMP monitoring is not required", + Remediation: "Disable the SNMP agent if SNMP monitoring is not required", Tags: []string{"snmp-security", "attack-surface", "firewall-controls"}, }, { diff --git a/internal/plugins/stig/stig.go b/internal/plugins/stig/stig.go index a7426f708..b5e4f19ba 100644 --- a/internal/plugins/stig/stig.go +++ b/internal/plugins/stig/stig.go @@ -438,14 +438,13 @@ func (sp *Plugin) hasOverlyPermissiveRules(device *common.CommonDevice) bool { } // hasUnnecessaryServices checks whether the device has network services enabled that -// increase the attack surface, including SNMP with community strings, insecure DNS -// settings, excessive DHCP interfaces, or load balancer configurations. +// increase the attack surface: an enabled SNMP agent, more than two DHCP scopes, or +// load balancer configurations. func (sp *Plugin) hasUnnecessaryServices(device *common.CommonDevice) bool { // Check for unnecessary network services - // Check SNMP configuration - SNMP with community strings can be a security risk - if device.SNMP.ROCommunity != "" { - // SNMP is enabled with community string - could be unnecessary + // An SNMP agent could be unnecessary + if device.SNMP.IsEnabled() { return true } diff --git a/pkg/model/services.go b/pkg/model/services.go index 5e2b98c7a..ecc25d28b 100644 --- a/pkg/model/services.go +++ b/pkg/model/services.go @@ -397,6 +397,37 @@ type SNMPConfig struct { SysLocation string `json:"sysLocation,omitempty" yaml:"sysLocation,omitempty"` // SysContact is the SNMP system contact. SysContact string `json:"sysContact,omitempty" yaml:"sysContact,omitempty"` + + // Enabled reports that the config starts an SNMP agent. Both converters + // set it, and fill the other fields only when they do, so a settings + // block no agent reads leaves the whole struct empty. A hand-built device + // may set only ROCommunity; use IsEnabled rather than this field to ask + // whether an agent runs. + Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` + + // ListenAddresses lists the addresses the agent binds. Only the OPNsense + // os-net-snmp agent fills it; empty there means the agent's default, + // every IPv4 address and the IPv6 loopback. No bind address is read for + // an agent, on either vendor, so its list is always empty. + ListenAddresses []string `json:"listenAddresses,omitempty" yaml:"listenAddresses,omitempty"` + + // Users lists the SNMPv3 users the agent loads. Their passwords and + // privacy keys are never carried. + Users []SNMPUser `json:"users,omitempty" yaml:"users,omitempty"` +} + +// IsEnabled reports whether an SNMP agent runs: Enabled is set, or a +// community is configured, which is how a hand-built device may report one. +func (c SNMPConfig) IsEnabled() bool { + return c.Enabled || c.ROCommunity != "" +} + +// SNMPUser is an SNMPv3 user of the SNMP agent. +type SNMPUser struct { + // Username is the SNMPv3 security name. + Username string `json:"username" yaml:"username"` + // ReadWrite reports read-write access; false is read-only. + ReadWrite bool `json:"readWrite,omitempty" yaml:"readWrite,omitempty"` } // LoadBalancerConfig contains load balancer configuration. diff --git a/pkg/parser/opnsense/converter_services.go b/pkg/parser/opnsense/converter_services.go index 26d8c2998..8fcb0b7df 100644 --- a/pkg/parser/opnsense/converter_services.go +++ b/pkg/parser/opnsense/converter_services.go @@ -934,15 +934,6 @@ func (c *converter) convertNTP(doc *schema.OpnSenseDocument) common.NTPConfig { } } -// convertSNMP maps doc.Snmpd to common.SNMPConfig. -func (c *converter) convertSNMP(doc *schema.OpnSenseDocument) common.SNMPConfig { - return common.SNMPConfig{ - ROCommunity: doc.Snmpd.ROCommunity, - SysLocation: doc.Snmpd.SysLocation, - SysContact: doc.Snmpd.SysContact, - } -} - // convertLoadBalancer maps doc.LoadBalancer.MonitorType to common.LoadBalancerConfig. func (c *converter) convertLoadBalancer(doc *schema.OpnSenseDocument) common.LoadBalancerConfig { monitors := doc.LoadBalancer.MonitorType diff --git a/pkg/parser/opnsense/converter_snmp.go b/pkg/parser/opnsense/converter_snmp.go new file mode 100644 index 000000000..75c2727ae --- /dev/null +++ b/pkg/parser/opnsense/converter_snmp.go @@ -0,0 +1,138 @@ +package opnsense + +import ( + "slices" + "strings" + + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + schema "github.com/EvilBit-Labs/opnDossier/pkg/schema/opnsense" +) + +// netsnmpGeneralVersions lists every version Netsnmp/General.xml has carried +// in the os-net-snmp plugin, from 1.0.0 (2018) to 1.0.7 as of 26.7.9; the +// plugin's history skips 1.0.2. The elements convertSNMP reads kept their +// names in each. +var netsnmpGeneralVersions = strings.Fields("1.0.0 1.0.1 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7") + +// netsnmpUserVersions lists every version Netsnmp/User.xml has carried; 1.0.1 +// added . +var netsnmpUserVersions = strings.Fields("1.0.0 1.0.1") + +const ( + // netsnmpOn is the value the plugin's templates compare the general + // , a user's and a user's with. The + // templates, which write snmpd.conf and decide whether rc.d starts the + // agent, read the raw config, so an absent element is off, and so is an + // empty one, although User.xml defaults a user's to 1. + netsnmpOn = "1" + + snmpLegacyPath = "SNMP.Snmpd" + snmpNetsnmpPath = "SNMP.Netsnmp" +) + +// convertSNMP reports the SNMP agent the config starts, or an empty +// SNMPConfig when it starts none. +// +// OPNsense has had three agents. Core ran bsnmpd from the legacy top-level +// up to 16.7, and the os-snmp plugin did the same from 17.1 to 18.7, +// both only when was set (isset()). The plugin was removed in +// 19.1, leaving os-net-snmp, which reads and starts only +// when is 1. The factory default shipped +// public without through +// 25.7, and no migration removes it, so most upgraded configs carry a legacy +// block that starts nothing. +// +// The config does not record the release, so a legacy block with is +// reported as running unless net-snmp is enabled: on 19.1 and later that +// over-reports an agent, which is the safe direction. +func (c *converter) convertSNMP(doc *schema.OpnSenseDocument) common.SNMPConfig { + legacy := doc.Snmpd + netsnmp := doc.OPNsense.Netsnmp + if netsnmp != nil { + c.checkNetsnmpVersions(netsnmp) + } + + if netsnmp != nil && netsnmp.General.Enabled == netsnmpOn { + if legacy.Enable != nil { + c.addWarning(snmpLegacyPath+".Enable", *legacy.Enable, + "legacy agent not reported: the os-net-snmp agent is enabled, "+ + "and OPNsense 19.1 and later run no agent from ", + common.SeverityLow) + } + + return netsnmpConfig(netsnmp) + } + + if legacy.Enable != nil { + c.addWarning(snmpLegacyPath+".Enable", *legacy.Enable, + "legacy agent reported as running: OPNsense up to 18.7 starts it, "+ + "OPNsense 19.1 and later do not", + common.SeverityLow) + + return common.SNMPConfig{ + Enabled: true, + ROCommunity: legacy.ROCommunity, + SysLocation: legacy.SysLocation, + SysContact: legacy.SysContact, + } + } + + // A legacy block without starts nothing on any release, so + // leaving it out needs no warning: it is the factory default's leftover. + return common.SNMPConfig{} +} + +// netsnmpConfig maps an enabled os-net-snmp agent. A disabled user is left +// out, as the agent's templates skip it; passwords and keys are never read. +func netsnmpConfig(netsnmp *schema.Netsnmp) common.SNMPConfig { + general := netsnmp.General + cfg := common.SNMPConfig{ + Enabled: true, + ROCommunity: general.Community, + SysLocation: general.SysLocation, + SysContact: general.SysContact, + } + + for entry := range strings.SplitSeq(general.Listen, ",") { + if address := strings.TrimSpace(entry); address != "" { + cfg.ListenAddresses = append(cfg.ListenAddresses, address) + } + } + + for _, user := range netsnmp.User.Users { + if user.Enabled != netsnmpOn { + continue + } + + cfg.Users = append(cfg.Users, common.SNMPUser{ + Username: user.Username, + ReadWrite: user.ReadWrite == netsnmpOn, + }) + } + + return cfg +} + +// checkNetsnmpVersions warns when either os-net-snmp model carries a version +// convertSNMP has not been checked against, since a renamed element would +// read as an agent that is off (GOTCHAS 18.1). +func (c *converter) checkNetsnmpVersions(netsnmp *schema.Netsnmp) { + versions := []struct { + path string + version string + known []string + }{ + {snmpNetsnmpPath + ".General.Version", netsnmp.General.Version, netsnmpGeneralVersions}, + {snmpNetsnmpPath + ".User.Version", netsnmp.User.Version, netsnmpUserVersions}, + } + + for _, v := range versions { + if v.version == "" || slices.Contains(v.known, v.version) { + continue + } + + c.addWarning(v.path, v.version, + "unrecognized os-net-snmp model version; element mapping may be stale", + common.SeverityMedium) + } +} diff --git a/pkg/parser/opnsense/converter_snmp_test.go b/pkg/parser/opnsense/converter_snmp_test.go new file mode 100644 index 000000000..4307b8b1d --- /dev/null +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -0,0 +1,373 @@ +package opnsense_test + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/EvilBit-Labs/opnDossier/internal/cfgparser" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/EvilBit-Labs/opnDossier/pkg/parser" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// staleLegacySNMP is the block OPNsense factory defaults wrote from 16.7 to +// 25.7. It has no , so no release starts an agent from it. +const staleLegacySNMP = ` + + + + public + ` + +// netsnmpBlock renders as the os-net-snmp plugin saves +// it, with the general model's enabled and community values and the given +// user items. +func netsnmpBlock(version, enabled, community, listen, users string) string { + return ` + + + + ` + enabled + ` + ` + community + ` + rack 4 + noc + 0 + 0 + 0 + 0 + ` + listen + ` + + + ` + users + ` + + + ` +} + +// snmpUsers holds a disabled read-write user first and an enabled one second, +// each with the cleartext secrets the model stores. +const snmpUsers = ` + + 0 + retired + RetiredPass123 + RetiredKey12345 + 1 + + + 1 + monitor + MonitorPass123 + MonitorKey12345 + 1 + ` + +func snmpConfig(body string) string { + return ` + + + fw + example.com + ` + body + ` +` +} + +func convertSNMPConfig(t *testing.T, body string) (*common.CommonDevice, []common.ConversionWarning) { + t.Helper() + + device, warnings, err := parser.NewFactory(cfgparser.NewXMLParser()).CreateDevice( + context.Background(), strings.NewReader(snmpConfig(body)), common.DeviceTypeUnknown, false) + require.NoError(t, err) + + var snmpWarnings []common.ConversionWarning + for _, w := range warnings { + if strings.HasPrefix(w.Field, "SNMP.") { + snmpWarnings = append(snmpWarnings, w) + } + } + + return device, snmpWarnings +} + +func TestConverter_SNMP_AgentTheConfigStarts(t *testing.T) { + t.Parallel() + + enabledAgent := common.SNMPConfig{ + Enabled: true, + ROCommunity: "public", + SysLocation: "rack 4", + SysContact: "noc", + ListenAddresses: []string{"192.0.2.1", "2001:db8::1"}, + Users: []common.SNMPUser{{Username: "monitor", ReadWrite: true}}, + } + + tests := []struct { + name string + body string + want common.SNMPConfig + wantWarnings []string + }{ + { + name: "net-snmp enabled beside the stale legacy block", + body: staleLegacySNMP + netsnmpBlock("1.0.7", "1", "public", "192.0.2.1, 2001:db8::1", snmpUsers), + want: enabledAgent, + }, + { + name: "net-snmp enabled with SNMPv3 users only", + body: netsnmpBlock("1.0.7", "1", "", "", snmpUsers), + want: common.SNMPConfig{ + Enabled: true, + SysLocation: "rack 4", + SysContact: "noc", + Users: []common.SNMPUser{{Username: "monitor", ReadWrite: true}}, + }, + }, + { + name: "net-snmp disabled beside the stale legacy block", + body: staleLegacySNMP + netsnmpBlock("1.0.7", "0", "public", "", snmpUsers), + want: common.SNMPConfig{}, + }, + { + name: "net-snmp enabled element empty", + body: netsnmpBlock("1.0.7", "", "public", "", ""), + want: common.SNMPConfig{}, + }, + { + name: "stale legacy block alone", + body: staleLegacySNMP, + want: common.SNMPConfig{}, + }, + { + name: "legacy block with an empty enable element", + body: ` + + closet + ops + s3cretcomm + + `, + want: common.SNMPConfig{ + Enabled: true, + ROCommunity: "s3cretcomm", + SysLocation: "closet", + SysContact: "ops", + }, + wantWarnings: []string{"SNMP.Snmpd.Enable"}, + }, + { + name: "legacy enable beside an enabled net-snmp agent", + body: ` + + legacycomm + 1 + ` + netsnmpBlock("1.0.7", "1", "public", "192.0.2.1,2001:db8::1", snmpUsers), + want: enabledAgent, + wantWarnings: []string{"SNMP.Snmpd.Enable"}, + }, + { + name: "unrecognized general model version", + body: netsnmpBlock("1.0.8", "1", "public", "192.0.2.1,2001:db8::1", snmpUsers), + want: enabledAgent, + wantWarnings: []string{"SNMP.Netsnmp.General.Version"}, + }, + { + name: "first released general model version", + body: netsnmpBlock("1.0.0", "1", "public", "192.0.2.1,2001:db8::1", snmpUsers), + want: enabledAgent, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device, warnings := convertSNMPConfig(t, tc.body) + assert.Equal(t, tc.want, device.SNMP) + assert.Equal(t, tc.want.Enabled, device.SNMP.IsEnabled()) + + fields := make([]string, 0, len(warnings)) + for _, w := range warnings { + fields = append(fields, w.Field) + } + assert.ElementsMatch(t, tc.wantWarnings, fields) + }) + } +} + +// TestConverter_SNMP_LegacyEnableBesideNetsnmpOff pins the fallback for a +// legacy block with beside an os-net-snmp block that is +// present but does not start the agent: the legacy agent is reported, with a +// Low warning, and nothing is taken from the net-snmp block. An unknown model +// version still warns at Medium beside it. +func TestConverter_SNMP_LegacyEnableBesideNetsnmpOff(t *testing.T) { + t.Parallel() + + legacy := func(enable string) string { + return ` + + closet + ops + legacycomm + ` + enable + ` + ` + } + + legacyAgent := common.SNMPConfig{ + Enabled: true, + ROCommunity: "legacycomm", + SysLocation: "closet", + SysContact: "ops", + } + legacyWarning := "SNMP.Snmpd.Enable/" + string(common.SeverityLow) + + tests := []struct { + name string + body string + wantWarnings []string + }{ + { + name: "net-snmp enabled is 0", + body: legacy("") + netsnmpBlock("1.0.7", "0", "public", "192.0.2.1", ""), + wantWarnings: []string{legacyWarning}, + }, + { + name: "net-snmp enabled is empty", + body: legacy("1") + netsnmpBlock("1.0.7", "", "public", "192.0.2.1", ""), + wantWarnings: []string{legacyWarning}, + }, + { + name: "net-snmp enabled is absent", + body: legacy("") + strings.Replace( + netsnmpBlock("1.0.7", "1", "public", "192.0.2.1", ""), "1", "", 1), + wantWarnings: []string{legacyWarning}, + }, + { + name: "net-snmp block is empty", + body: legacy("1") + ` + + + `, + wantWarnings: []string{legacyWarning}, + }, + { + name: "net-snmp off with an unknown general model version", + body: legacy("") + netsnmpBlock("1.0.8", "0", "public", "192.0.2.1", ""), + wantWarnings: []string{ + legacyWarning, + "SNMP.Netsnmp.General.Version/" + string(common.SeverityMedium), + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device, warnings := convertSNMPConfig(t, tc.body) + assert.Equal(t, legacyAgent, device.SNMP) + + got := make([]string, 0, len(warnings)) + for _, w := range warnings { + got = append(got, w.Field+"/"+string(w.Severity)) + } + assert.ElementsMatch(t, tc.wantWarnings, got) + }) + } +} + +// TestConverter_SNMP_UserDefaults pins the raw-value reading the agent's +// templates apply: a user loads only with 1, and read-write +// access only with 1, so an absent element means +// neither, although the model's own default for is 1. +func TestConverter_SNMP_UserDefaults(t *testing.T) { + t.Parallel() + + users := ` + + noenabled + 1 + + + 1 + readonly + ` + + device, warnings := convertSNMPConfig(t, netsnmpBlock("1.0.7", "1", "", "", users)) + assert.Empty(t, warnings) + assert.Equal(t, []common.SNMPUser{{Username: "readonly"}}, device.SNMP.Users) +} + +// TestConverter_SNMP_SecretsNeverExported checks that the SNMPv3 passwords +// and privacy keys the plugin stores never reach the device model. +func TestConverter_SNMP_SecretsNeverExported(t *testing.T) { + t.Parallel() + + device, _ := convertSNMPConfig(t, netsnmpBlock("1.0.7", "1", "public", "", snmpUsers)) + + raw, err := json.Marshal(device) + require.NoError(t, err) + + for _, secret := range []string{"RetiredPass123", "RetiredKey12345", "MonitorPass123", "MonitorKey12345"} { + assert.NotContains(t, string(raw), secret) + } + assert.Contains(t, string(raw), `"username":"monitor"`) +} + +// TestConverter_SNMP_ModelVersionPins checks every version each os-net-snmp +// model has carried converts without a warning, and that an unknown version, +// general 1.0.2 among them, warns whether or not the agent is enabled: a +// renamed would read as an agent that is off, so the check cannot +// wait for an enabled one. +func TestConverter_SNMP_ModelVersionPins(t *testing.T) { + t.Parallel() + + for version := range strings.FieldsSeq("1.0.0 1.0.1 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7") { + _, warnings := convertSNMPConfig(t, netsnmpBlock(version, "1", "public", "", "")) + assert.Empty(t, warnings, "general model %s", version) + } + + for _, version := range []string{"1.0.0", "1.0.1"} { + body := strings.Replace(netsnmpBlock("1.0.7", "1", "public", "", ""), + ``, ``, 1) + _, warnings := convertSNMPConfig(t, body) + assert.Empty(t, warnings, "user model %s", version) + } + + tests := []struct { + name string + body string + wantField string + }{ + { + name: "unknown general version with the agent off", + body: netsnmpBlock("1.0.8", "0", "public", "", ""), + wantField: "SNMP.Netsnmp.General.Version", + }, + { + // The plugin's history skips general 1.0.2, so it is not pinned. + name: "general version 1.0.2, which the plugin never used", + body: netsnmpBlock("1.0.2", "1", "public", "", ""), + wantField: "SNMP.Netsnmp.General.Version", + }, + { + name: "unknown user version", + body: strings.Replace(netsnmpBlock("1.0.7", "1", "public", "", ""), + ``, ``, 1), + wantField: "SNMP.Netsnmp.User.Version", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, warnings := convertSNMPConfig(t, tc.body) + require.Len(t, warnings, 1) + assert.Equal(t, tc.wantField, warnings[0].Field) + assert.Equal(t, common.SeverityMedium, warnings[0].Severity) + }) + } +} diff --git a/pkg/parser/opnsense/converter_test.go b/pkg/parser/opnsense/converter_test.go index bb1763665..57ec07654 100644 --- a/pkg/parser/opnsense/converter_test.go +++ b/pkg/parser/opnsense/converter_test.go @@ -948,13 +948,17 @@ func TestConverter_SNMP(t *testing.T) { t.Parallel() doc := schema.NewOpnSenseDocument() + enable := "" + doc.Snmpd.Enable = &enable doc.Snmpd.ROCommunity = "public" doc.Snmpd.SysLocation = "Server Room" doc.Snmpd.SysContact = "admin@example.com" device, warnings, err := opnsense.ConvertDocument(doc) require.NoError(t, err) - assert.Empty(t, warnings) + require.Len(t, warnings, 1) + assert.Equal(t, "SNMP.Snmpd.Enable", warnings[0].Field) + assert.True(t, device.SNMP.Enabled) assert.Equal(t, "public", device.SNMP.ROCommunity) assert.Equal(t, "Server Room", device.SNMP.SysLocation) assert.Equal(t, "admin@example.com", device.SNMP.SysContact) diff --git a/pkg/parser/pfsense/converter_services.go b/pkg/parser/pfsense/converter_services.go index f05c8a575..01f8a2a33 100644 --- a/pkg/parser/pfsense/converter_services.go +++ b/pkg/parser/pfsense/converter_services.go @@ -180,9 +180,18 @@ func (c *converter) convertDNS(doc *pfsense.Document) common.DNSConfig { } } -// convertSNMP maps doc.Snmpd to common.SNMPConfig. +// convertSNMP maps doc.Snmpd to common.SNMPConfig when it starts an agent. +// services_snmpd_configure starts bsnmpd only when config_path_enabled('snmpd') +// holds, which is isset() on , so any element counts +// and a block without one, like the default's community "public", starts +// nothing. func (c *converter) convertSNMP(doc *pfsense.Document) common.SNMPConfig { + if doc.Snmpd.Enable == nil { + return common.SNMPConfig{} + } + return common.SNMPConfig{ + Enabled: true, ROCommunity: doc.Snmpd.ROCommunity, SysLocation: doc.Snmpd.SysLocation, SysContact: doc.Snmpd.SysContact, diff --git a/pkg/parser/pfsense/converter_snmp_test.go b/pkg/parser/pfsense/converter_snmp_test.go new file mode 100644 index 000000000..65f65b388 --- /dev/null +++ b/pkg/parser/pfsense/converter_snmp_test.go @@ -0,0 +1,61 @@ +package pfsense_test + +import ( + "context" + "os" + "strings" + "testing" + + common "github.com/EvilBit-Labs/opnDossier/pkg/model" + "github.com/EvilBit-Labs/opnDossier/pkg/parser/pfsense" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestConverter_SNMP_EnableGatesTheAgent drives both pfSense fixtures through +// the parser as shipped, with community "public" and no , and again +// with added in the two shapes isset() accepts. pfSense starts +// bsnmpd only when config_path_enabled('snmpd') holds, so only the second +// pass reports an agent. +func TestConverter_SNMP_EnableGatesTheAgent(t *testing.T) { + t.Parallel() + + fixtures := map[string]common.SNMPConfig{ + "../../../testdata/pfsense/config-pfSense.xml": {Enabled: true, ROCommunity: "public"}, + "../../../testdata/pfsense/config-2.7.x.xml": { + Enabled: true, + ROCommunity: "public", + SysLocation: "Server Room", + SysContact: "admin@edge.local", + }, + } + + for path, enabled := range fixtures { + raw, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, 1, strings.Count(string(raw), ""), path) + require.NotContains(t, string(raw), "", path) + + cases := []struct { + name string + enable string + want common.SNMPConfig + }{ + {name: "as shipped", want: common.SNMPConfig{}}, + {name: "empty enable", enable: "", want: enabled}, + {name: "enable with body", enable: "yes", want: enabled}, + } + + for _, tc := range cases { + t.Run(path+"/"+tc.name, func(t *testing.T) { + t.Parallel() + + config := strings.Replace(string(raw), "", ""+tc.enable, 1) + device, _, err := pfsense.NewParser(nil).Parse(context.Background(), strings.NewReader(config)) + require.NoError(t, err) + assert.Equal(t, tc.want, device.SNMP) + assert.Equal(t, tc.want.Enabled, device.SNMP.IsEnabled()) + }) + } + } +} diff --git a/pkg/parser/pfsense/parser_test.go b/pkg/parser/pfsense/parser_test.go index 2eb9681fe..7ff782c8e 100644 --- a/pkg/parser/pfsense/parser_test.go +++ b/pkg/parser/pfsense/parser_test.go @@ -1180,7 +1180,8 @@ func TestParser_ParseFixture_2_7_x(t *testing.T) { assert.True(t, device.DNS.Unbound.Enabled) assert.True(t, device.DNS.Unbound.DNSSEC) assert.NotNil(t, device.Cron) - assert.Equal(t, "public", device.SNMP.ROCommunity) + // The fixture's has a community but no , so no agent runs. + assert.False(t, device.SNMP.IsEnabled()) } func TestConverter_VLANs(t *testing.T) { @@ -1205,14 +1206,17 @@ func TestConverter_SNMP(t *testing.T) { t.Parallel() doc := pfsenseSchema.NewDocument() + enable := "" doc.Snmpd = opnsense.Snmpd{ ROCommunity: "public", SysLocation: "Server Room", SysContact: "admin@test.local", + Enable: &enable, } device, _, err := pfsense.ConvertDocument(doc) require.NoError(t, err) + assert.True(t, device.SNMP.Enabled) assert.Equal(t, "public", device.SNMP.ROCommunity) assert.Equal(t, "Server Room", device.SNMP.SysLocation) assert.Equal(t, "admin@test.local", device.SNMP.SysContact) @@ -1347,8 +1351,8 @@ func TestParser_ParseFixture_ConfigPfSense(t *testing.T) { require.NotNil(t, device.Cron) assert.NotEmpty(t, device.Cron.Jobs) - // SNMP - assert.Equal(t, "public", device.SNMP.ROCommunity) + // SNMP: the fixture's has a community but no . + assert.False(t, device.SNMP.IsEnabled()) // Revision assert.Contains(t, device.Revision.Username, "admin") diff --git a/pkg/parser/testdata/api-snapshots/pkg-model.golden b/pkg/parser/testdata/api-snapshots/pkg-model.golden index ec6519140..2996fbfa4 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-model.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-model.golden @@ -2413,9 +2413,38 @@ type SNMPConfig struct { SysLocation string `json:"sysLocation,omitempty" yaml:"sysLocation,omitempty"` // SysContact is the SNMP system contact. SysContact string `json:"sysContact,omitempty" yaml:"sysContact,omitempty"` + + // Enabled reports that the config starts an SNMP agent. Both converters + // set it, and fill the other fields only when they do, so a settings + // block no agent reads leaves the whole struct empty. A hand-built device + // may set only ROCommunity; use IsEnabled rather than this field to ask + // whether an agent runs. + Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` + + // ListenAddresses lists the addresses the agent binds. Only the OPNsense + // os-net-snmp agent fills it; empty there means the agent's default, + // every IPv4 address and the IPv6 loopback. No bind address is read for + // an agent, on either vendor, so its list is always empty. + ListenAddresses []string `json:"listenAddresses,omitempty" yaml:"listenAddresses,omitempty"` + + // Users lists the SNMPv3 users the agent loads. Their passwords and + // privacy keys are never carried. + Users []SNMPUser `json:"users,omitempty" yaml:"users,omitempty"` } SNMPConfig contains SNMP service configuration. +func (c SNMPConfig) IsEnabled() bool + IsEnabled reports whether an SNMP agent runs: Enabled is set, or a community + is configured, which is how a hand-built device may report one. + +type SNMPUser struct { + // Username is the SNMPv3 security name. + Username string `json:"username" yaml:"username"` + // ReadWrite reports read-write access; false is read-only. + ReadWrite bool `json:"readWrite,omitempty" yaml:"readWrite,omitempty"` +} + SNMPUser is an SNMPv3 user of the SNMP agent. + type SSH struct { // Enabled indicates whether the SSH service is active. Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` diff --git a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden index 621d71036..82774addd 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -1564,6 +1564,61 @@ type Nat struct { wrote them there, and from 26.1 the Destination NAT model is mounted on the same path, so no release nests them in a container. +type Netsnmp struct { + General NetsnmpGeneral `xml:"general" json:"general" yaml:"general"` + User NetsnmpUsers `xml:"user" json:"user" yaml:"user"` +} + Netsnmp is the os-net-snmp plugin's configuration, stored + under . The plugin's two MVC models mount at + //OPNsense/netsnmp/general and //OPNsense/netsnmp/user, so each carries its + own version attribute. From 19.1 this plugin is the only SNMP agent OPNsense + ships: core dropped its own agent at 17.1, and the os-snmp plugin that took + over the legacy element was removed in 19.1. + + Every leaf is a string: the agent's templates compare the raw values with + "1", and the converter does the same. + +type NetsnmpGeneral struct { + Version string `xml:"version,attr,omitempty" json:"version,omitempty" yaml:"version,omitempty"` + Enabled string `xml:"enabled" json:"enabled" yaml:"enabled"` + // Community is the agent's read-only community, a credential, so it is + // kept out of JSON and YAML. + Community string `xml:"community" json:"-" yaml:"-"` + SysLocation string `xml:"syslocation" json:"syslocation" yaml:"syslocation"` + SysContact string `xml:"syscontact" json:"syscontact" yaml:"syscontact"` + L3Visibility string `xml:"l3visibility" json:"l3visibility" yaml:"l3visibility"` + VersionOID string `xml:"versionoid" json:"versionoid" yaml:"versionoid"` + EnableAgentX string `xml:"enableagentx" json:"enableagentx" yaml:"enableagentx"` + EnableObservium string `xml:"enableobservium" json:"enableobservium" yaml:"enableobservium"` + // Listen is a comma-separated list of addresses; empty means every IPv4 + // address and IPv6 loopback. + Listen string `xml:"listen" json:"listen" yaml:"listen"` +} + NetsnmpGeneral is the general model of the os-net-snmp plugin + (Netsnmp/General.xml). No element it binds was renamed or removed in any + model version the plugin shipped, 1.0.0, 1.0.1 and 1.0.3 to 1.0.7: 1.0.1 + and 1.0.3 to 1.0.5 each added an element, and 1.0.6 and 1.0.7 changed field + types and options. The converter warns on a version it has not been checked + against. + +type NetsnmpUser struct { + UUID string `xml:"uuid,attr,omitempty" json:"uuid,omitempty" yaml:"uuid,omitempty"` + Enabled string `xml:"enabled" json:"enabled" yaml:"enabled"` + Username string `xml:"username" json:"username" yaml:"username"` + ReadWrite string `xml:"readwrite" json:"readwrite" yaml:"readwrite"` +} + NetsnmpUser is one SNMPv3 user. The model also stores the user's + authentication password and privacy key in cleartext; they are deliberately + not bound, so nothing that reads this type can carry them into a report or + an export. + +type NetsnmpUsers struct { + Version string `xml:"version,attr,omitempty" json:"version,omitempty" yaml:"version,omitempty"` + Users []NetsnmpUser `xml:"users>user" json:"users,omitempty" yaml:"users,omitempty"` +} + NetsnmpUsers is the user model of the os-net-snmp plugin (Netsnmp/User.xml), + which holds the SNMPv3 users. + type NetworkConfig struct { Interfaces Interfaces `json:"interfaces" yaml:"interfaces,omitempty" validate:"required"` VLANs []VLANConfig `json:"vlans,omitempty" yaml:"vlans,omitempty"` @@ -1616,6 +1671,9 @@ type OPNsense struct { // Monitoring components - now using references Monit *Monit `xml:"monit,omitempty" json:"monit,omitempty"` + // Netsnmp is nil when the os-net-snmp plugin never saved its settings. + Netsnmp *Netsnmp `xml:"netsnmp,omitempty" json:"netsnmp,omitempty"` + // Network components Interfaces struct { Text string `xml:",chardata" json:"text,omitempty"` @@ -2205,6 +2263,11 @@ type Snmpd struct { SysLocation string `xml:"syslocation"` SysContact string `xml:"syscontact"` ROCommunity string `xml:"rocommunity"` + + // Enable is nil when the element is absent. pfSense, and OPNsense up to + // 18.7, test it with isset(), so any element, empty or not, + // starts the agent (GOTCHAS 3.2). + Enable *string `xml:"enable,omitempty"` } Snmpd contains the SNMP daemon configuration, including system location, contact, and read-only community string. The ROCommunity field is a diff --git a/pkg/schema/opnsense/netsnmp.go b/pkg/schema/opnsense/netsnmp.go new file mode 100644 index 000000000..9fa6d7b82 --- /dev/null +++ b/pkg/schema/opnsense/netsnmp.go @@ -0,0 +1,56 @@ +package opnsense + +// Netsnmp is the os-net-snmp plugin's configuration, stored under +// . The plugin's two MVC models mount at +// //OPNsense/netsnmp/general and //OPNsense/netsnmp/user, so each carries its +// own version attribute. From 19.1 this plugin is the only SNMP agent +// OPNsense ships: core dropped its own agent at 17.1, and the os-snmp plugin +// that took over the legacy element was removed in 19.1. +// +// Every leaf is a string: the agent's templates compare the raw values with +// "1", and the converter does the same. +type Netsnmp struct { + General NetsnmpGeneral `xml:"general" json:"general" yaml:"general"` + User NetsnmpUsers `xml:"user" json:"user" yaml:"user"` +} + +// NetsnmpGeneral is the general model of the os-net-snmp plugin +// (Netsnmp/General.xml). No element it binds was renamed or removed in any +// model version the plugin shipped, 1.0.0, 1.0.1 and 1.0.3 to 1.0.7: 1.0.1 and +// 1.0.3 to 1.0.5 each added an element, and 1.0.6 and 1.0.7 changed field +// types and options. The converter warns on a version it has not been checked +// against. +type NetsnmpGeneral struct { + Version string `xml:"version,attr,omitempty" json:"version,omitempty" yaml:"version,omitempty"` + Enabled string `xml:"enabled" json:"enabled" yaml:"enabled"` + // Community is the agent's read-only community, a credential, so it is + // kept out of JSON and YAML. + Community string `xml:"community" json:"-" yaml:"-"` + SysLocation string `xml:"syslocation" json:"syslocation" yaml:"syslocation"` + SysContact string `xml:"syscontact" json:"syscontact" yaml:"syscontact"` + L3Visibility string `xml:"l3visibility" json:"l3visibility" yaml:"l3visibility"` + VersionOID string `xml:"versionoid" json:"versionoid" yaml:"versionoid"` + EnableAgentX string `xml:"enableagentx" json:"enableagentx" yaml:"enableagentx"` + EnableObservium string `xml:"enableobservium" json:"enableobservium" yaml:"enableobservium"` + // Listen is a comma-separated list of addresses; empty means every IPv4 + // address and IPv6 loopback. + Listen string `xml:"listen" json:"listen" yaml:"listen"` +} + +// NetsnmpUsers is the user model of the os-net-snmp plugin +// (Netsnmp/User.xml), which holds the SNMPv3 users. +type NetsnmpUsers struct { + Version string `xml:"version,attr,omitempty" json:"version,omitempty" yaml:"version,omitempty"` + Users []NetsnmpUser `xml:"users>user" json:"users,omitempty" yaml:"users,omitempty"` +} + +// NetsnmpUser is one SNMPv3 user. The model also stores the user's +// authentication password and privacy key in cleartext; they are deliberately +// not bound, so nothing that reads this type can carry them into a report or +// an export. +type NetsnmpUser struct { + UUID string `xml:"uuid,attr,omitempty" json:"uuid,omitempty" yaml:"uuid,omitempty"` + Enabled string `xml:"enabled" json:"enabled" yaml:"enabled"` + Username string `xml:"username" json:"username" yaml:"username"` + ReadWrite string `xml:"readwrite" json:"readwrite" yaml:"readwrite"` +} diff --git a/pkg/schema/opnsense/netsnmp_test.go b/pkg/schema/opnsense/netsnmp_test.go new file mode 100644 index 000000000..b5fcbf18c --- /dev/null +++ b/pkg/schema/opnsense/netsnmp_test.go @@ -0,0 +1,135 @@ +package opnsense + +import ( + "encoding/json" + "encoding/xml" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" +) + +// TestNetsnmpGeneral_CommunityNotSerialized pins the standards rule that a +// credential in pkg/schema stays out of JSON and YAML: the community still +// round-trips through XML, but a stray marshal of the DTO cannot carry it. +func TestNetsnmpGeneral_CommunityNotSerialized(t *testing.T) { + t.Parallel() + + const community = "c0mmunity-not-for-export" + + general := NetsnmpGeneral{Enabled: "1", Community: community} + + jsonOut, err := json.Marshal(general) + require.NoError(t, err) + assert.NotContains(t, string(jsonOut), community) + + yamlOut, err := yaml.Marshal(general) + require.NoError(t, err) + assert.NotContains(t, string(yamlOut), community) + + xmlOut, err := xml.Marshal(general) + require.NoError(t, err) + assert.Contains(t, string(xmlOut), community) +} + +func TestNetsnmp_RoundTrip(t *testing.T) { + t.Parallel() + + const input = ` + + 1 + public + rack 4 + noc + 0 + 1 + 0 + 1 + 192.0.2.1,2001:db8::1 + + + + + 0 + retired + RetiredPass123 + RetiredKey12345 + 0 + + + 1 + monitor + MonitorPass123 + MonitorKey12345 + 1 + + + +` + + var first Netsnmp + require.NoError(t, xml.Unmarshal([]byte(input), &first)) + + want := Netsnmp{ + General: NetsnmpGeneral{ + Version: "1.0.7", Enabled: "1", Community: "public", SysLocation: "rack 4", SysContact: "noc", + L3Visibility: "0", VersionOID: "1", EnableAgentX: "0", EnableObservium: "1", + Listen: "192.0.2.1,2001:db8::1", + }, + User: NetsnmpUsers{ + Version: "1.0.1", + Users: []NetsnmpUser{ + {UUID: "6f1c2a52-6d0e-4b8e-9b51-0f3f4cdbb001", Enabled: "0", Username: "retired", ReadWrite: "0"}, + {UUID: "6f1c2a52-6d0e-4b8e-9b51-0f3f4cdbb002", Enabled: "1", Username: "monitor", ReadWrite: "1"}, + }, + }, + } + assert.Equal(t, want, first) + + out, err := xml.Marshal(struct { + Netsnmp + + XMLName xml.Name `xml:"netsnmp"` + }{Netsnmp: first}) + require.NoError(t, err) + assert.NotContains(t, string(out), "Pass123", "secrets are not bound, so they are not written back") + + var second Netsnmp + require.NoError(t, xml.Unmarshal(out, &second)) + assert.Equal(t, first, second) +} + +// TestSnmpd_EnableRoundTrip keeps an absent apart from an empty one, +// since an empty one starts the legacy agent. +func TestSnmpd_EnableRoundTrip(t *testing.T) { + t.Parallel() + + for _, input := range []string{ + `public`, + `public`, + `publicyes`, + } { + var first Snmpd + require.NoError(t, xml.Unmarshal([]byte(input), &first)) + + out, err := xml.Marshal(struct { + Snmpd + + XMLName xml.Name `xml:"snmpd"` + }{Snmpd: first}) + require.NoError(t, err) + + var second Snmpd + require.NoError(t, xml.Unmarshal(out, &second)) + assert.Equal(t, first, second, input) + assert.Equal(t, first.Enable == nil, second.Enable == nil, input) + } + + var absent, empty Snmpd + require.NoError(t, xml.Unmarshal([]byte(``), &absent)) + require.NoError(t, xml.Unmarshal([]byte(``), &empty)) + assert.Nil(t, absent.Enable) + require.NotNil(t, empty.Enable) + assert.Empty(t, *empty.Enable) +} diff --git a/pkg/schema/opnsense/opnsense.go b/pkg/schema/opnsense/opnsense.go index 3ab22432a..2ec799162 100644 --- a/pkg/schema/opnsense/opnsense.go +++ b/pkg/schema/opnsense/opnsense.go @@ -93,6 +93,9 @@ type OPNsense struct { // Monitoring components - now using references Monit *Monit `xml:"monit,omitempty" json:"monit,omitempty"` + // Netsnmp is nil when the os-net-snmp plugin never saved its settings. + Netsnmp *Netsnmp `xml:"netsnmp,omitempty" json:"netsnmp,omitempty"` + // Network components Interfaces struct { Text string `xml:",chardata" json:"text,omitempty"` diff --git a/pkg/schema/opnsense/services.go b/pkg/schema/opnsense/services.go index 6fe888420..a1603572e 100644 --- a/pkg/schema/opnsense/services.go +++ b/pkg/schema/opnsense/services.go @@ -26,6 +26,11 @@ type Snmpd struct { SysLocation string `xml:"syslocation"` SysContact string `xml:"syscontact"` ROCommunity string `xml:"rocommunity"` + + // Enable is nil when the element is absent. pfSense, and OPNsense up to + // 18.7, test it with isset(), so any element, empty or not, + // starts the agent (GOTCHAS 3.2). + Enable *string `xml:"enable,omitempty"` } // Rrd contains the RRDtool (Round-Robin Database) configuration for time-series data collection. diff --git a/pkg/schema/pfsense/README.md b/pkg/schema/pfsense/README.md index cf10f80f9..7adceb062 100644 --- a/pkg/schema/pfsense/README.md +++ b/pkg/schema/pfsense/README.md @@ -63,7 +63,7 @@ vlan, wolentry | `nat` (inbound + outbound) | `security.go` | Outbound reused | Inbound forked: the OPNsense rule has elements pfSense does not write | | `dhcpd` | `document.go` | Yes (full) | Identical map-based structure | | `dhcpdv6` | `network.go` | No (pfSense-specific) | Map-based with RAMode, RAPriority | -| `snmpd` | `document.go` | Yes (full) | Identical | +| `snmpd` | `document.go` | Yes (full) | Identical; `` (`*string`) gates the agent | | `openvpn` | `document.go` | Yes (full) | Client + server arrays | | `syslog` | `services.go` | No (pfSense-specific) | Currently minimal | | `unbound` | `services.go` | No (pfSense-specific) | Core fields |