From 9228c1fbe87d899d793e77d201f8a27154618eb8 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:04:51 -0700 Subject: [PATCH 01/46] fix(parser): read the os-net-snmp agent on OPNsense From 19.1 the only SNMP agent OPNsense ships is the os-net-snmp plugin, which stores its settings under . The converter read only the legacy top-level , so a net-snmp agent answering "public" behind a WAN pass rule for UDP 161 passed FIREWALL-045, FIREWALL-046 and STIG V-206690, and red mode reported no SNMP exposure. Bind the plugin's general and user models and map an enabled agent (1, compared raw as the plugin's templates do) into SNMPConfig: community, location, contact, listen addresses and the enabled SNMPv3 users with their read-write flag. The users' passwords and privacy keys are not bound in the schema, so nothing downstream can carry them. Both model versions are pinned: general 1.0.0 to 1.0.7 and user 1.0.0 to 1.0.1, with a warning on any other. An SNMPv3-only agent has no community, so SNMPConfig gains Enabled and IsEnabled(), and FIREWALL-045, STIG V-206690, the enabled-services statistic and red-mode exposure ask IsEnabled() instead of testing the community. A community alone still counts, so the pfSense converter and hand-built devices behave as before. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/compliance-standards.md | 2 +- docs/data-model/model-reference.md | 18 ++ internal/analysis/statistics.go | 2 +- internal/audit/red_analysis.go | 8 +- internal/audit/snmp_agent_test.go | 148 ++++++++++++++ .../converter/builder/builder_services.go | 1 + internal/converter/builder/builder_snmp.go | 40 ++++ .../converter/builder/builder_snmp_test.go | 44 ++++ internal/plugins/firewall/checks_dispatch.go | 4 +- .../plugins/firewall/checks_encryption.go | 7 +- internal/plugins/firewall/controls.go | 2 +- internal/plugins/stig/stig.go | 5 +- pkg/model/services.go | 29 +++ pkg/parser/opnsense/converter_services.go | 9 - pkg/parser/opnsense/converter_snmp.go | 101 ++++++++++ pkg/parser/opnsense/converter_snmp_test.go | 190 ++++++++++++++++++ .../testdata/api-snapshots/pkg-model.golden | 27 +++ .../api-snapshots/pkg-schema-opnsense.golden | 54 +++++ pkg/schema/opnsense/netsnmp.go | 52 +++++ pkg/schema/opnsense/netsnmp_test.go | 76 +++++++ pkg/schema/opnsense/opnsense.go | 3 + 21 files changed, 797 insertions(+), 25 deletions(-) create mode 100644 internal/audit/snmp_agent_test.go create mode 100644 internal/converter/builder/builder_snmp.go create mode 100644 internal/converter/builder/builder_snmp_test.go create mode 100644 pkg/parser/opnsense/converter_snmp.go create mode 100644 pkg/parser/opnsense/converter_snmp_test.go create mode 100644 pkg/schema/opnsense/netsnmp.go create mode 100644 pkg/schema/opnsense/netsnmp_test.go diff --git a/docs/compliance-standards.md b/docs/compliance-standards.md index cb85d0d2e..9b0db6d47 100644 --- a/docs/compliance-standards.md +++ b/docs/compliance-standards.md @@ -223,7 +223,7 @@ The following controls are organized by security domain and represent the full p | 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-045 | SNMP Disabled if Unused | Medium | Full | No SNMP agent is enabled when there is no operational need | | FIREWALL-046 | No Default Community Strings | High | Full | SNMP community strings changed from well-known defaults ("public", "private") | ##### VPN Configuration diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 76e6b7f74..92d22cba1 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -336,6 +336,24 @@ 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 + +The OPNsense converter reads the os-net-snmp plugin when `` is `1`, and otherwise the legacy `` block. The pfSense converter reports its `` block through the first three fields and leaves `Enabled` false. `SNMPConfig.IsEnabled()` reports a running agent for either. + +| Field | Type | JSON Key | Description | +| ----------------- | ------------ | ---------------------- | ---------------------------------------------------------------- | +| `ROCommunity` | `string` | `snmp.roCommunity` | Read-only community (v1/v2c); redacted on export | +| `SysLocation` | `string` | `snmp.sysLocation` | System location | +| `SysContact` | `string` | `snmp.sysContact` | System contact | +| `Enabled` | `bool` | `snmp.enabled` | An SNMP agent runs (OPNsense) | +| `ListenAddresses` | `[]string` | `snmp.listenAddresses` | Bound addresses; empty means the agent default (all IPv4) | +| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | + +| 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/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/audit/red_analysis.go b/internal/audit/red_analysis.go index 84e473b1f..893656be8 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -73,9 +73,9 @@ 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. Local-only services are not // possible here — a configured management service is at least LAN-reachable. func serviceExposures(device *common.CommonDevice) []exposedService { if device == nil { @@ -122,7 +122,7 @@ func serviceExposures(device *common.CommonDevice) []exposedService { }) } - if device.SNMP.ROCommunity != "" { + if device.SNMP.IsEnabled() { services = append(services, exposedService{ kind: exploitKindSNMP, name: "snmp", diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go new file mode 100644 index 000000000..64d8b54e4 --- /dev/null +++ b/internal/audit/snmp_agent_test.go @@ -0,0 +1,148 @@ +package audit + +import ( + "slices" + "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 ( + 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 os-net-snmp agent, including one that answers only +// SNMPv3 users and so has no community. +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: "net-snmp disabled", 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}, + } + + 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") + }) + } +} 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..121a5d3f3 100644 --- a/internal/plugins/stig/stig.go +++ b/internal/plugins/stig/stig.go @@ -443,9 +443,8 @@ func (sp *Plugin) hasOverlyPermissiveRules(device *common.CommonDevice) bool { 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..25af7f0bd 100644 --- a/pkg/model/services.go +++ b/pkg/model/services.go @@ -397,6 +397,35 @@ 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. The OPNsense + // converter sets it for an enabled os-net-snmp agent. The pfSense + // converter leaves it false and reports the agent through 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; empty means the + // agent's default, which includes every IPv4 address. + 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 the pfSense converter and a +// hand-built device 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..2602ac3d7 --- /dev/null +++ b/pkg/parser/opnsense/converter_snmp.go @@ -0,0 +1,101 @@ +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, 1.0.0 (2018) to 1.0.7 (26.7); 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") + +// netsnmpOn is the value the plugin's templates and netsnmp_enabled() compare +// and with. They read the raw config, so an absent +// element is off, and so is an empty one. +const netsnmpOn = "1" + +const snmpNetsnmpPath = "SNMP.Netsnmp" + +// convertSNMP reports the SNMP agent the config starts. From 19.1 the only +// agent OPNsense ships is the os-net-snmp plugin, which reads +// and starts only when is 1. Without +// one, the legacy top-level is mapped as before. +func (c *converter) convertSNMP(doc *schema.OpnSenseDocument) common.SNMPConfig { + netsnmp := doc.OPNsense.Netsnmp + if netsnmp != nil { + c.checkNetsnmpVersions(netsnmp) + + if netsnmp.General.Enabled == netsnmpOn { + return netsnmpConfig(netsnmp) + } + } + + return common.SNMPConfig{ + ROCommunity: doc.Snmpd.ROCommunity, + SysLocation: doc.Snmpd.SysLocation, + SysContact: doc.Snmpd.SysContact, + } +} + +// 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..ff1397981 --- /dev/null +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -0,0 +1,190 @@ +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" +) + +// 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", + body: 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 enabled element empty", + body: netsnmpBlock("1.0.7", "", "public", "", ""), + want: common.SNMPConfig{}, + }, + { + 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_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"`) +} diff --git a/pkg/parser/testdata/api-snapshots/pkg-model.golden b/pkg/parser/testdata/api-snapshots/pkg-model.golden index ec6519140..0a434e3e1 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-model.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-model.golden @@ -2413,9 +2413,36 @@ 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. The OPNsense + // converter sets it for an enabled os-net-snmp agent. The pfSense + // converter leaves it false and reports the agent through 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; empty means the + // agent's default, which includes every IPv4 address. + 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 the pfSense converter and a hand-built device + 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..afeb79614 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -1564,6 +1564,57 @@ 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"` + User NetsnmpUsers `xml:"user" json:"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"` + Enabled string `xml:"enabled" json:"enabled"` + Community string `xml:"community" json:"community"` + SysLocation string `xml:"syslocation" json:"syslocation"` + SysContact string `xml:"syscontact" json:"syscontact"` + L3Visibility string `xml:"l3visibility" json:"l3visibility"` + VersionOID string `xml:"versionoid" json:"versionoid"` + EnableAgentX string `xml:"enableagentx" json:"enableagentx"` + EnableObservium string `xml:"enableobservium" json:"enableobservium"` + // Listen is a comma-separated list of addresses; empty means every IPv4 + // address and IPv6 loopback. + Listen string `xml:"listen" json:"listen"` +} + NetsnmpGeneral is the general model of the os-net-snmp plugin + (Netsnmp/General.xml). Its element names are unchanged from model version + 1.0.0 to 1.0.7; the converter warns on a version it has not been checked + against. + +type NetsnmpUser struct { + UUID string `xml:"uuid,attr,omitempty" json:"uuid,omitempty"` + Enabled string `xml:"enabled" json:"enabled"` + Username string `xml:"username" json:"username"` + ReadWrite string `xml:"readwrite" json:"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"` + Users []NetsnmpUser `xml:"users>user" json:"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 +1667,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/netsnmp.go b/pkg/schema/opnsense/netsnmp.go new file mode 100644 index 000000000..6c6cdd4ba --- /dev/null +++ b/pkg/schema/opnsense/netsnmp.go @@ -0,0 +1,52 @@ +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"` + User NetsnmpUsers `xml:"user" json:"user"` +} + +// NetsnmpGeneral is the general model of the os-net-snmp plugin +// (Netsnmp/General.xml). Its element names are unchanged from model version +// 1.0.0 to 1.0.7; the converter warns on a version it has not been checked +// against. +type NetsnmpGeneral struct { + Version string `xml:"version,attr,omitempty" json:"version,omitempty"` + Enabled string `xml:"enabled" json:"enabled"` + Community string `xml:"community" json:"community"` + SysLocation string `xml:"syslocation" json:"syslocation"` + SysContact string `xml:"syscontact" json:"syscontact"` + L3Visibility string `xml:"l3visibility" json:"l3visibility"` + VersionOID string `xml:"versionoid" json:"versionoid"` + EnableAgentX string `xml:"enableagentx" json:"enableagentx"` + EnableObservium string `xml:"enableobservium" json:"enableobservium"` + // Listen is a comma-separated list of addresses; empty means every IPv4 + // address and IPv6 loopback. + Listen string `xml:"listen" json:"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"` + Users []NetsnmpUser `xml:"users>user" json:"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"` + Enabled string `xml:"enabled" json:"enabled"` + Username string `xml:"username" json:"username"` + ReadWrite string `xml:"readwrite" json:"readwrite"` +} diff --git a/pkg/schema/opnsense/netsnmp_test.go b/pkg/schema/opnsense/netsnmp_test.go new file mode 100644 index 000000000..1d3c2b00b --- /dev/null +++ b/pkg/schema/opnsense/netsnmp_test.go @@ -0,0 +1,76 @@ +package opnsense + +import ( + "encoding/xml" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +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) +} 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"` From 790fdc5e750868f3e742391e553194e3814ed9d8 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:11:57 -0700 Subject: [PATCH 02/46] fix(parser): stop reading a stale legacy as a running agent OPNsense core stopped running an SNMP agent at 17.1, and the os-snmp plugin that went on reading the legacy top-level was removed in 19.1. Both started bsnmpd only when was set (isset()). Factory defaults kept writing public without up to 25.7, and nothing removes it, so most upgraded configs carry a block that starts no agent. The converter copied it unconditionally, and every consumer read the community as a running agent: FIREWALL-045, FIREWALL-046 and STIG V-206690 failed, the high "Default SNMP Community String" issue and the v1/v2c observation fired, and red mode could report WAN-exposed SNMP on a firewall with none. Bind as a presence field and report a legacy block only when it carries one and net-snmp is not enabled, with a Low warning, since the config does not record whether the release still runs that agent. A block without starts nothing on any release and is left out without a warning. pfSense shares the schema type but its converter is unchanged. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 1 + ...sense-pfsense-snmp-config-storage-model.md | 7 ++ docs/data-model/model-reference.md | 2 +- internal/audit/snmp_agent_test.go | 17 ++++- pkg/model/services.go | 3 +- pkg/parser/opnsense/converter_snmp.go | 66 ++++++++++++++----- pkg/parser/opnsense/converter_snmp_test.go | 50 +++++++++++++- pkg/parser/opnsense/converter_test.go | 6 +- .../testdata/api-snapshots/pkg-model.golden | 3 +- .../api-snapshots/pkg-schema-opnsense.golden | 6 ++ pkg/schema/opnsense/netsnmp_test.go | 34 ++++++++++ pkg/schema/opnsense/services.go | 6 ++ 12 files changed, 176 insertions(+), 25 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index 2c351167c..5d68ec8e2 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 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. - **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. 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..8116c73b5 100644 --- a/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md +++ b/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md @@ -56,6 +56,13 @@ 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 to 1.0.7 (the plugin never used 1.0.2) 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. The `password` and `enckey` elements are not bound in the schema, so model-based features never see them. + ## 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/data-model/model-reference.md b/docs/data-model/model-reference.md index 92d22cba1..4fd77111d 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -338,7 +338,7 @@ DHCP scopes are a flat array with one entry per interface. ### SNMP -The OPNsense converter reads the os-net-snmp plugin when `` is `1`, and otherwise the legacy `` block. The pfSense converter reports its `` block through the first three fields and leaves `Enabled` false. `SNMPConfig.IsEnabled()` reports a running agent for either. +The OPNsense converter fills these fields only for an agent the config starts: the os-net-snmp plugin when `` is `1`, otherwise a legacy `` block that carries ``. A legacy block without ``, which factory defaults wrote up to 25.7, starts no agent and leaves the struct empty. The pfSense converter reports its `` block through the first three fields and leaves `Enabled` false. `SNMPConfig.IsEnabled()` reports a running agent for either. | Field | Type | JSON Key | Description | | ----------------- | ------------ | ---------------------- | ---------------------------------------------------------------- | diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index 64d8b54e4..a9ac7f286 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -54,6 +54,15 @@ func snmpAgentConfig(topLevel, model string) string { } const ( + // snmpStaleLegacy is the factory default's legacy block, which starts no + // agent on any release. + snmpStaleLegacy = ` + + + + public + ` + snmpNetsnmpDisabled = ` @@ -99,8 +108,9 @@ const ( // TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts drives OPNsense configs // through parse, convert, the FIREWALL and STIG plugins and red mode. The -// verdicts follow the os-net-snmp agent, including one that answers only -// SNMPv3 users and so has no community. +// verdicts follow the agent the config starts: the os-net-snmp model when it +// is enabled, and never the legacy block the factory default left +// behind without . func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { t.Parallel() @@ -113,7 +123,8 @@ func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { running bool defaultCommunity bool }{ - {name: "net-snmp disabled", model: snmpNetsnmpDisabled}, + {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}, } diff --git a/pkg/model/services.go b/pkg/model/services.go index 25af7f0bd..f3c6bf44f 100644 --- a/pkg/model/services.go +++ b/pkg/model/services.go @@ -399,7 +399,8 @@ type SNMPConfig struct { SysContact string `json:"sysContact,omitempty" yaml:"sysContact,omitempty"` // Enabled reports that the config starts an SNMP agent. The OPNsense - // converter sets it for an enabled os-net-snmp agent. The pfSense + // converter sets it, and fills the other fields only when it does, so a + // settings block no agent reads leaves the whole struct empty. The pfSense // converter leaves it false and reports the agent through ROCommunity; // use IsEnabled rather than this field to ask whether an agent runs. Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` diff --git a/pkg/parser/opnsense/converter_snmp.go b/pkg/parser/opnsense/converter_snmp.go index 2602ac3d7..c1f6f90b3 100644 --- a/pkg/parser/opnsense/converter_snmp.go +++ b/pkg/parser/opnsense/converter_snmp.go @@ -17,32 +17,66 @@ var netsnmpGeneralVersions = strings.Fields("1.0.0 1.0.1 1.0.3 1.0.4 1.0.5 1.0.6 // added . var netsnmpUserVersions = strings.Fields("1.0.0 1.0.1") -// netsnmpOn is the value the plugin's templates and netsnmp_enabled() compare -// and with. They read the raw config, so an absent -// element is off, and so is an empty one. -const netsnmpOn = "1" - -const snmpNetsnmpPath = "SNMP.Netsnmp" +const ( + // netsnmpOn is the value the plugin's templates and netsnmp_enabled() + // compare and with. They read the raw config, so an + // absent element is off, and so is an empty one. + netsnmpOn = "1" + + snmpLegacyPath = "SNMP.Snmpd" + snmpNetsnmpPath = "SNMP.Netsnmp" +) -// convertSNMP reports the SNMP agent the config starts. From 19.1 the only -// agent OPNsense ships is the os-net-snmp plugin, which reads -// and starts only when is 1. Without -// one, the legacy top-level is mapped as before. +// 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.General.Enabled == netsnmpOn { - return netsnmpConfig(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) } - return common.SNMPConfig{ - ROCommunity: doc.Snmpd.ROCommunity, - SysLocation: doc.Snmpd.SysLocation, - SysContact: doc.Snmpd.SysContact, + 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 diff --git a/pkg/parser/opnsense/converter_snmp_test.go b/pkg/parser/opnsense/converter_snmp_test.go index ff1397981..6a1768abe 100644 --- a/pkg/parser/opnsense/converter_snmp_test.go +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -13,6 +13,15 @@ import ( "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. @@ -102,8 +111,8 @@ func TestConverter_SNMP_AgentTheConfigStarts(t *testing.T) { wantWarnings []string }{ { - name: "net-snmp enabled", - body: netsnmpBlock("1.0.7", "1", "public", "192.0.2.1, 2001:db8::1", snmpUsers), + 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, }, { @@ -116,11 +125,48 @@ func TestConverter_SNMP_AgentTheConfigStarts(t *testing.T) { 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), 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/testdata/api-snapshots/pkg-model.golden b/pkg/parser/testdata/api-snapshots/pkg-model.golden index 0a434e3e1..cfa55e98d 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-model.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-model.golden @@ -2415,7 +2415,8 @@ type SNMPConfig struct { SysContact string `json:"sysContact,omitempty" yaml:"sysContact,omitempty"` // Enabled reports that the config starts an SNMP agent. The OPNsense - // converter sets it for an enabled os-net-snmp agent. The pfSense + // converter sets it, and fills the other fields only when it does, so a + // settings block no agent reads leaves the whole struct empty. The pfSense // converter leaves it false and reports the agent through ROCommunity; // use IsEnabled rather than this field to ask whether an agent runs. 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 afeb79614..f194486f7 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -2259,6 +2259,12 @@ type Snmpd struct { SysLocation string `xml:"syslocation"` SysContact string `xml:"syscontact"` ROCommunity string `xml:"rocommunity"` + + // Enable is nil when the element is absent. OPNsense up to 18.7 tests it + // with isset(), so any element, empty or not, starts the agent + // (GOTCHAS 3.2). pfSense also gates its agent on this element; the pfSense + // converter does not read it. + 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_test.go b/pkg/schema/opnsense/netsnmp_test.go index 1d3c2b00b..e43d3f304 100644 --- a/pkg/schema/opnsense/netsnmp_test.go +++ b/pkg/schema/opnsense/netsnmp_test.go @@ -74,3 +74,37 @@ func TestNetsnmp_RoundTrip(t *testing.T) { 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/services.go b/pkg/schema/opnsense/services.go index 6fe888420..ae177f85c 100644 --- a/pkg/schema/opnsense/services.go +++ b/pkg/schema/opnsense/services.go @@ -26,6 +26,12 @@ type Snmpd struct { SysLocation string `xml:"syslocation"` SysContact string `xml:"syscontact"` ROCommunity string `xml:"rocommunity"` + + // Enable is nil when the element is absent. OPNsense up to 18.7 tests it + // with isset(), so any element, empty or not, starts the agent + // (GOTCHAS 3.2). pfSense also gates its agent on this element; the pfSense + // converter does not read it. + Enable *string `xml:"enable,omitempty"` } // Rrd contains the RRDtool (Round-Robin Database) configuration for time-series data collection. From ea1ccad618d19abe4b5bf04ee8706074778416ce Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:41:28 -0700 Subject: [PATCH 03/46] fix(parser): report a pfSense SNMP agent only when snmpd/enable is set pfSense starts bsnmpd only when config_path_enabled('snmpd') holds, which is isset() on , and its GUI writes that element when the service is ticked. The pfSense converter copied the community whatever held, so a config with a community and the agent off, such as both pfSense fixtures, failed FIREWALL-045, FIREWALL-046 and STIG V-206690 and could be reported as WAN-exposed SNMP. Report the block only when is present, and set Enabled as the OPNsense converter does, so both vendors fill SNMPConfig only for an agent the config starts. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/data-model/model-reference.md | 8 ++- pkg/model/services.go | 13 ++-- pkg/parser/pfsense/converter_services.go | 11 +++- pkg/parser/pfsense/converter_snmp_test.go | 61 +++++++++++++++++++ pkg/parser/pfsense/parser_test.go | 10 ++- .../testdata/api-snapshots/pkg-model.golden | 13 ++-- .../api-snapshots/pkg-schema-opnsense.golden | 7 +-- pkg/schema/opnsense/services.go | 7 +-- 8 files changed, 101 insertions(+), 29 deletions(-) create mode 100644 pkg/parser/pfsense/converter_snmp_test.go diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 4fd77111d..89d1eee16 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -338,17 +338,19 @@ DHCP scopes are a flat array with one entry per interface. ### SNMP -The OPNsense converter fills these fields only for an agent the config starts: the os-net-snmp plugin when `` is `1`, otherwise a legacy `` block that carries ``. A legacy block without ``, which factory defaults wrote up to 25.7, starts no agent and leaves the struct empty. The pfSense converter reports its `` block through the first three fields and leaves `Enabled` false. `SNMPConfig.IsEnabled()` reports a running agent for either. +Both converters fill these fields only for an agent the config starts, 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 ``; 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 on export | +| `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 (OPNsense) | +| `Enabled` | `bool` | `snmp.enabled` | An SNMP agent runs | | `ListenAddresses` | `[]string` | `snmp.listenAddresses` | Bound addresses; empty means the agent default (all IPv4) | | `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 | diff --git a/pkg/model/services.go b/pkg/model/services.go index f3c6bf44f..b20a03d95 100644 --- a/pkg/model/services.go +++ b/pkg/model/services.go @@ -398,11 +398,11 @@ type SNMPConfig struct { // SysContact is the SNMP system contact. SysContact string `json:"sysContact,omitempty" yaml:"sysContact,omitempty"` - // Enabled reports that the config starts an SNMP agent. The OPNsense - // converter sets it, and fills the other fields only when it does, so a - // settings block no agent reads leaves the whole struct empty. The pfSense - // converter leaves it false and reports the agent through ROCommunity; - // use IsEnabled rather than this field to ask whether an agent runs. + // 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; empty means the @@ -415,8 +415,7 @@ type SNMPConfig struct { } // IsEnabled reports whether an SNMP agent runs: Enabled is set, or a -// community is configured, which is how the pfSense converter and a -// hand-built device report one. +// community is configured, which is how a hand-built device may report one. func (c SNMPConfig) IsEnabled() bool { return c.Enabled || c.ROCommunity != "" } 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 cfa55e98d..89d5c5cac 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-model.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-model.golden @@ -2414,11 +2414,11 @@ type SNMPConfig struct { // SysContact is the SNMP system contact. SysContact string `json:"sysContact,omitempty" yaml:"sysContact,omitempty"` - // Enabled reports that the config starts an SNMP agent. The OPNsense - // converter sets it, and fills the other fields only when it does, so a - // settings block no agent reads leaves the whole struct empty. The pfSense - // converter leaves it false and reports the agent through ROCommunity; - // use IsEnabled rather than this field to ask whether an agent runs. + // 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; empty means the @@ -2433,8 +2433,7 @@ type SNMPConfig struct { func (c SNMPConfig) IsEnabled() bool IsEnabled reports whether an SNMP agent runs: Enabled is set, or a community - is configured, which is how the pfSense converter and a hand-built device - report one. + is configured, which is how a hand-built device may report one. type SNMPUser struct { // Username is the SNMPv3 security name. diff --git a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden index f194486f7..2b2fc2129 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -2260,10 +2260,9 @@ type Snmpd struct { SysContact string `xml:"syscontact"` ROCommunity string `xml:"rocommunity"` - // Enable is nil when the element is absent. OPNsense up to 18.7 tests it - // with isset(), so any element, empty or not, starts the agent - // (GOTCHAS 3.2). pfSense also gates its agent on this element; the pfSense - // converter does not read it. + // 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, diff --git a/pkg/schema/opnsense/services.go b/pkg/schema/opnsense/services.go index ae177f85c..a1603572e 100644 --- a/pkg/schema/opnsense/services.go +++ b/pkg/schema/opnsense/services.go @@ -27,10 +27,9 @@ type Snmpd struct { SysContact string `xml:"syscontact"` ROCommunity string `xml:"rocommunity"` - // Enable is nil when the element is absent. OPNsense up to 18.7 tests it - // with isset(), so any element, empty or not, starts the agent - // (GOTCHAS 3.2). pfSense also gates its agent on this element; the pfSense - // converter does not read it. + // 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"` } From f0c4f2d549c641e44505ea31b619951605d9462c Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:44:18 -0700 Subject: [PATCH 04/46] test(parser): pin each os-net-snmp model version and its warnings Every version the general and user models have carried must convert without a warning, and an unknown version of either must warn even when the agent is off, since a renamed would read as off. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- pkg/parser/opnsense/converter_snmp_test.go | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/pkg/parser/opnsense/converter_snmp_test.go b/pkg/parser/opnsense/converter_snmp_test.go index 6a1768abe..b7ebe0388 100644 --- a/pkg/parser/opnsense/converter_snmp_test.go +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -234,3 +234,52 @@ func TestConverter_SNMP_SecretsNeverExported(t *testing.T) { } 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 +// 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.Fields("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", + }, + { + 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) + }) + } +} From 447f69d95629f3493869913d96e8efae85233f9f Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:50:26 -0700 Subject: [PATCH 05/46] docs: correct SNMP wording after the agent gating Describe STIG V-206690 by the enabled-agent check, date the net-snmp general model pin to 26.7.9, qualify the GOTCHAS example to configs without the legacy block, and drop the redaction comment's claim that SNMPv3 secrets will be parsed: they are deliberately never parsed. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- docs/compliance-standards.md | 2 +- internal/analysis/statistics_redact.go | 6 +++--- pkg/parser/opnsense/converter_snmp.go | 5 +++-- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index 5d68ec8e2..6f05eba93 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -203,7 +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 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. +- **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. - **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. diff --git a/docs/compliance-standards.md b/docs/compliance-standards.md index 9b0db6d47..572ad4437 100644 --- a/docs/compliance-standards.md +++ b/docs/compliance-standards.md @@ -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, Unbound DNS with DNSSEC stripping, 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/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/pkg/parser/opnsense/converter_snmp.go b/pkg/parser/opnsense/converter_snmp.go index c1f6f90b3..79656d421 100644 --- a/pkg/parser/opnsense/converter_snmp.go +++ b/pkg/parser/opnsense/converter_snmp.go @@ -9,8 +9,9 @@ import ( ) // netsnmpGeneralVersions lists every version Netsnmp/General.xml has carried -// in the os-net-snmp plugin, 1.0.0 (2018) to 1.0.7 (26.7); the plugin's -// history skips 1.0.2. The elements convertSNMP reads kept their names in each. +// 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 From 222cc1f4b1ad40e447ab590867f50297c91d6267 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:00:07 -0700 Subject: [PATCH 06/46] docs: describe the SNMP agent reading in every affected reference The control reference, XML field references, pfSense schema notes and device support matrix still described SNMP as configured whenever a community was present. Describe the agent each vendor starts, the net-snmp elements and versions read, and the presence test, and mark ADR-0001 as updated, including the pfSense gating. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- ...sense-pfsense-snmp-config-storage-model.md | 4 ++ docs/compliance-standards.md | 8 ++-- docs/development/xml-structure-research.md | 3 ++ docs/firewall-security-controls-reference.md | 10 +++-- docs/user-guide/device-support-matrix.md | 2 + docs/xml-field-reference.md | 40 +++++++++++++++++++ pkg/schema/pfsense/README.md | 2 +- 7 files changed, 60 insertions(+), 9 deletions(-) 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 8116c73b5..4a34d5f58 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. @@ -62,6 +64,8 @@ Two findings above were incomplete, and the parser now reads the plugin namespac - 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 to 1.0.7 (the plugin never used 1.0.2) 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. 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 diff --git a/docs/compliance-standards.md b/docs/compliance-standards.md index 572ad4437..a766a01ad 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 | No SNMP agent is enabled when there is 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 | No SNMP agent is enabled when there is no operational need | +| FIREWALL-046 | No Default Community Strings | High | Full | The running agent's community is not a well-known default ("public", "private") | ##### VPN Configuration 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..6b457c5c2 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 | No SNMP agent enabled (`SNMP.IsEnabled()`) when there is no operational need | +| FIREWALL-046 | No Default Community Strings | High | The running agent's community is not "public"/"private" | + +Both controls read the agent the config starts. On OPNsense that is the os-net-snmp plugin (`1`), or a legacy `` block only when it carries ``; 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 and passes both. An agent with SNMPv3 users and no community fails FIREWALL-045 and passes FIREWALL-046. ### VPN Configuration 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..d1aba609e 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 general model versions 1.0.0 to 1.0.7 and 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/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 | From cb41de518394fe40e9c943045fd7e4e283aa4263 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:18:05 -0700 Subject: [PATCH 07/46] docs: align the V-206690 description with the Unbound fix The Unbound branch drops DNSSEC stripping from this control, since harden-dnssec-stripped is the secure setting. Both branches now carry the same line, so the two merge cleanly in either order. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/compliance-standards.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/compliance-standards.md b/docs/compliance-standards.md index a766a01ad..5e0fd4dca 100644 --- a/docs/compliance-standards.md +++ b/docs/compliance-standards.md @@ -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 an enabled SNMP agent, 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). From 92598f5e3f140c864d6217735017806066eb693b Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:40:23 -0700 Subject: [PATCH 08/46] docs(stig): describe hasUnnecessaryServices by the enabled SNMP agent The comment still named SNMP community strings. Use the wording the Unbound branch carries for the same lines, so the two merge cleanly. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/plugins/stig/stig.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/plugins/stig/stig.go b/internal/plugins/stig/stig.go index 121a5d3f3..b5e4f19ba 100644 --- a/internal/plugins/stig/stig.go +++ b/internal/plugins/stig/stig.go @@ -438,8 +438,8 @@ 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 From af2a2781cbe400d91200b09b40f8f775c4f9d032 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:24:59 -0700 Subject: [PATCH 09/46] test(parser): range over strings.FieldsSeq in the version-pin test modernize-check flags ranging over strings.Fields when the slice is not kept. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- pkg/parser/opnsense/converter_snmp_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/parser/opnsense/converter_snmp_test.go b/pkg/parser/opnsense/converter_snmp_test.go index b7ebe0388..a4fdd6327 100644 --- a/pkg/parser/opnsense/converter_snmp_test.go +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -242,7 +242,7 @@ func TestConverter_SNMP_SecretsNeverExported(t *testing.T) { func TestConverter_SNMP_ModelVersionPins(t *testing.T) { t.Parallel() - for _, version := range strings.Fields("1.0.0 1.0.1 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7") { + 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) } From 6f4841ca033484af82847e723b13f725ac368333 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:23:29 -0700 Subject: [PATCH 10/46] fix(audit): do not report a loopback-only SNMP agent as WAN-exposed The os-net-snmp plugin binds the agent to the addresses in its listen list. An agent bound only to loopback answers no other host, yet red mode reported it as a WAN-exposed SNMP service whenever a WAN pass rule admitted UDP 161 to the firewall. Such an agent is now Local. Any other address, one that does not parse, or an empty list, which binds every IPv4 address, is still judged by the firewall rules. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_analysis.go | 2 +- internal/audit/red_snmp_listen.go | 56 +++++++++++++++++++++++++++++++ internal/audit/snmp_agent_test.go | 43 ++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 internal/audit/red_snmp_listen.go diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index 893656be8..2c65e288b 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -130,7 +130,7 @@ func serviceExposures(device *common.CommonDevice) []exposedService { severity: analysis.SeverityHigh, component: "snmpd", port: portSNMP, - reachability: serviceReachability(device, portSNMP), + reachability: snmpReachability(device), 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.", 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..837ca4d0a --- /dev/null +++ b/internal/audit/red_snmp_listen.go @@ -0,0 +1,56 @@ +package audit + +import ( + "net/netip" + + "github.com/EvilBit-Labs/opnDossier/internal/analysis" + common "github.com/EvilBit-Labs/opnDossier/pkg/model" +) + +// snmpReachability is serviceReachability for the SNMP agent, which the +// os-net-snmp plugin can bind to chosen addresses. An agent whose every listen +// address is a loopback address answers no other host, so it is Local whatever +// the firewall rules pass. Any other listen address, and an empty list, which +// binds every IPv4 address, is judged by the rules as the other services are. +func snmpReachability(device *common.CommonDevice) analysis.Reachability { + if listensOnLoopbackOnly(device.SNMP.ListenAddresses) { + return analysis.Local + } + + return serviceReachability(device, portSNMP) +} + +// 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/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index a9ac7f286..72c66b313 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -2,6 +2,7 @@ package audit import ( "slices" + "strings" "testing" "github.com/EvilBit-Labs/opnDossier/internal/analysis" @@ -157,3 +158,45 @@ func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { }) } } + +// TestSNMPAgent_ListenAddressesDecideWANExposure keeps the WAN rule passing +// UDP 161 and varies the agent's listen list. 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) 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: "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") + }) + } +} From fa792e7de0eee4f4949e40e9ef265972ce9d3ba0 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:24:12 -0700 Subject: [PATCH 11/46] fix(schema): keep the net-snmp community out of JSON and YAML docs/development/standards.md requires a credential in pkg/schema to carry json:"-" and yaml:"-" so a stray marshal of the DTO cannot carry it. NetsnmpGeneral.Community now does, and the net-snmp types carry yaml tags that match their json tags. The community still round-trips through XML. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- .../api-snapshots/pkg-schema-opnsense.golden | 38 ++++++++++--------- pkg/schema/opnsense/netsnmp.go | 38 ++++++++++--------- pkg/schema/opnsense/netsnmp_test.go | 25 ++++++++++++ 3 files changed, 65 insertions(+), 36 deletions(-) diff --git a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden index 2b2fc2129..000aa4296 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -1565,8 +1565,8 @@ type Nat struct { same path, so no release nests them in a container. type Netsnmp struct { - General NetsnmpGeneral `xml:"general" json:"general"` - User NetsnmpUsers `xml:"user" json:"user"` + 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 @@ -1579,18 +1579,20 @@ type Netsnmp struct { "1", and the converter does the same. type NetsnmpGeneral struct { - Version string `xml:"version,attr,omitempty" json:"version,omitempty"` - Enabled string `xml:"enabled" json:"enabled"` - Community string `xml:"community" json:"community"` - SysLocation string `xml:"syslocation" json:"syslocation"` - SysContact string `xml:"syscontact" json:"syscontact"` - L3Visibility string `xml:"l3visibility" json:"l3visibility"` - VersionOID string `xml:"versionoid" json:"versionoid"` - EnableAgentX string `xml:"enableagentx" json:"enableagentx"` - EnableObservium string `xml:"enableobservium" json:"enableobservium"` + 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"` + Listen string `xml:"listen" json:"listen" yaml:"listen"` } NetsnmpGeneral is the general model of the os-net-snmp plugin (Netsnmp/General.xml). Its element names are unchanged from model version @@ -1598,10 +1600,10 @@ type NetsnmpGeneral struct { against. type NetsnmpUser struct { - UUID string `xml:"uuid,attr,omitempty" json:"uuid,omitempty"` - Enabled string `xml:"enabled" json:"enabled"` - Username string `xml:"username" json:"username"` - ReadWrite string `xml:"readwrite" json:"readwrite"` + 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 @@ -1609,8 +1611,8 @@ type NetsnmpUser struct { an export. type NetsnmpUsers struct { - Version string `xml:"version,attr,omitempty" json:"version,omitempty"` - Users []NetsnmpUser `xml:"users>user" json:"users,omitempty"` + 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. diff --git a/pkg/schema/opnsense/netsnmp.go b/pkg/schema/opnsense/netsnmp.go index 6c6cdd4ba..4d704a8c6 100644 --- a/pkg/schema/opnsense/netsnmp.go +++ b/pkg/schema/opnsense/netsnmp.go @@ -10,8 +10,8 @@ package opnsense // 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"` - User NetsnmpUsers `xml:"user" json:"user"` + 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 @@ -19,25 +19,27 @@ type Netsnmp struct { // 1.0.0 to 1.0.7; the converter warns on a version it has not been checked // against. type NetsnmpGeneral struct { - Version string `xml:"version,attr,omitempty" json:"version,omitempty"` - Enabled string `xml:"enabled" json:"enabled"` - Community string `xml:"community" json:"community"` - SysLocation string `xml:"syslocation" json:"syslocation"` - SysContact string `xml:"syscontact" json:"syscontact"` - L3Visibility string `xml:"l3visibility" json:"l3visibility"` - VersionOID string `xml:"versionoid" json:"versionoid"` - EnableAgentX string `xml:"enableagentx" json:"enableagentx"` - EnableObservium string `xml:"enableobservium" json:"enableobservium"` + 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"` + 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"` - Users []NetsnmpUser `xml:"users>user" json:"users,omitempty"` + 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 @@ -45,8 +47,8 @@ type NetsnmpUsers struct { // 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"` - Enabled string `xml:"enabled" json:"enabled"` - Username string `xml:"username" json:"username"` - ReadWrite string `xml:"readwrite" json:"readwrite"` + 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 index e43d3f304..b5fcbf18c 100644 --- a/pkg/schema/opnsense/netsnmp_test.go +++ b/pkg/schema/opnsense/netsnmp_test.go @@ -1,13 +1,38 @@ 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() From fde38408e6e59feeff00689e5f96e999329ef54f Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:24:48 -0700 Subject: [PATCH 12/46] docs: describe FIREWALL-045 and the reported SNMP agent precisely FIREWALL-045 fails for any enabled agent; it does not judge operational need. A legacy snmpd block with enable is reported as a running agent because the config does not record the release, though only OPNsense up to 18.7 starts one. A block without enable passes both controls only when no other agent is enabled. The model reference also notes that red mode never reports a loopback-only agent as WAN-exposed. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/compliance-standards.md | 2 +- docs/data-model/model-reference.md | 20 ++++++++++---------- docs/firewall-security-controls-reference.md | 10 +++++----- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/compliance-standards.md b/docs/compliance-standards.md index 5e0fd4dca..f20ae15f0 100644 --- a/docs/compliance-standards.md +++ b/docs/compliance-standards.md @@ -223,7 +223,7 @@ The following controls are organized by security domain and represent the full p | Control ID | Title | Severity | Implementability | Description | | ------------ | ---------------------------- | -------- | ---------------- | ------------------------------------------------------------------------------- | -| FIREWALL-045 | SNMP Disabled if Unused | Medium | Full | No SNMP agent is enabled when there is no operational need | +| 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 diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 89d1eee16..f44ea3140 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -338,16 +338,16 @@ DHCP scopes are a flat array with one entry per interface. ### SNMP -Both converters fill these fields only for an agent the config starts, 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 ``; 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; empty means the agent default (all IPv4) | -| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | +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; empty means the agent default (all IPv4). Red mode never reports an agent bound only to loopback as WAN-exposed | +| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | #### SNMPUser diff --git a/docs/firewall-security-controls-reference.md b/docs/firewall-security-controls-reference.md index 6b457c5c2..a69f2dad5 100644 --- a/docs/firewall-security-controls-reference.md +++ b/docs/firewall-security-controls-reference.md @@ -407,12 +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 | No SNMP agent enabled (`SNMP.IsEnabled()`) when there is no operational need | -| FIREWALL-046 | No Default Community Strings | High | The running agent's community is not "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 config starts. On OPNsense that is the os-net-snmp plugin (`1`), or a legacy `` block only when it carries ``; 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 and passes both. An agent with SNMPv3 users and no community fails FIREWALL-045 and passes FIREWALL-046. +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 From 441d4ef3fd62b1aeb8b353ff20dd1a8cc3717750 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:16:07 -0700 Subject: [PATCH 13/46] test(audit): pin an IPv6 loopback prefix in the SNMP listen list An agent listening on ::1/128 answers no other host and is local; ::1/127 also holds the unspecified address and is still judged by the WAN rule. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/snmp_agent_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index 72c66b313..f04bf61ab 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -175,6 +175,9 @@ func TestSNMPAgent_ListenAddressesDecideWANExposure(t *testing.T) { {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}, From 8480e51e3ae1bb526a31cba1d8353dc2e291751d Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:46:22 -0700 Subject: [PATCH 14/46] fix(audit): stop telling an SNMP agent with no community to use SNMPv3 Red mode reports an SNMP agent as WAN-exposed whenever IsEnabled() holds, which now includes an os-net-snmp agent with SNMPv3 users and no community. Its finding still recommended migrating to SNMPv3 with authPriv, and the --audit-blackhat note said community-based authentication provides little resistance. The plugin's snmpd.conf template writes rocommunity only for a non-empty community, so such an agent answers no community at all. An agent with no community now gets its own exploit note kind, whose text in both tones does not name community authentication, and a recommendation that does not mention SNMPv3. An agent with a community keeps the previous text. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/exploit_notes.go | 11 +++- internal/audit/red_analysis.go | 14 ++++- internal/audit/snmp_exposure_text_test.go | 60 +++++++++++++++++++ .../testdata/golden/exploit_notes.golden | 6 ++ 5 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 internal/audit/snmp_exposure_text_test.go diff --git a/GOTCHAS.md b/GOTCHAS.md index 6f05eba93..2dce3ff25 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -203,7 +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. +- **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. 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 2c65e288b..9039074cb 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -123,8 +123,18 @@ func serviceExposures(device *common.CommonDevice) []exposedService { } 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, + kind: kind, name: "snmp", displayName: "SNMP Management Service", severity: analysis.SeverityHigh, @@ -132,7 +142,7 @@ func serviceExposures(device *common.CommonDevice) []exposedService { port: portSNMP, reachability: snmpReachability(device), 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/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/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. From 0f87ddce576134131f27d63297a68625ebc7172b Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:49:32 -0700 Subject: [PATCH 15/46] test(parser): pin a legacy enable beside net-snmp that is off convertSNMP reports a legacy block with , with a Low warning, when the os-net-snmp agent is not enabled. Every existing case with that legacy element had either no block or an enabled one, so restricting the fallback to configs without a block passed every test, while it stopped reporting the configured agent and passed FIREWALL-045. TestConverter_SNMP_LegacyEnableBesideNetsnmpOff covers a net-snmp block whose is 0, empty or absent, and an empty , each expecting the legacy agent's own values and the Low warning, plus an unknown general model version, which adds its Medium warning. The audit test gains the same input with net-snmp disabled, pinning FIREWALL-045, FIREWALL-046, STIG V-206690, the enabled-services statistic and the red-mode exposure for it. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/snmp_agent_test.go | 14 +++- pkg/parser/opnsense/converter_snmp_test.go | 81 ++++++++++++++++++++++ 2 files changed, 93 insertions(+), 2 deletions(-) diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index f04bf61ab..7f2bea8b2 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -110,8 +110,8 @@ const ( // 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, and never the legacy block the factory default left -// behind without . +// 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() @@ -128,6 +128,16 @@ func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { {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) diff --git a/pkg/parser/opnsense/converter_snmp_test.go b/pkg/parser/opnsense/converter_snmp_test.go index a4fdd6327..262adb364 100644 --- a/pkg/parser/opnsense/converter_snmp_test.go +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -197,6 +197,87 @@ func TestConverter_SNMP_AgentTheConfigStarts(t *testing.T) { } } +// 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 From b0b4e57af38f8dfc4d76d1857521d469d91c8fa5 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:53:04 -0700 Subject: [PATCH 16/46] docs: correct the net-snmp reading, version and listen descriptions The netsnmpOn comment said netsnmp_enabled() compares and on the raw config. It builds the General model, compares only the general , and decides no more than whether the GUI lists the service. The plugin's templates are what read the raw config: snmpd.conf compares the general , each user's and with "1", and the rc.conf.d template sets snmpd_enable only when the general is "1". The comment now names the templates and notes that User.xml defaults a user's to 1, which the templates do not apply. docs/xml-field-reference.md and the NetsnmpGeneral comment said the general model is pinned, or unchanged, from 1.0.0 to 1.0.7. The plugin shipped 1.0.0, 1.0.1 and 1.0.3 to 1.0.7, never 1.0.2, which still draws the version warning, and later versions only added elements. Both now say so. The empty ListenAddresses was described as every IPv4 address in the model comment, the model reference and the red-mode comment. The plugin's template binds every IPv4 address and the IPv6 loopback when is empty, and the list is filled only for the os-net-snmp agent: neither converter reads a bind address for an agent. Each description now says so. No behavior changes; the API snapshots are regenerated for the comment text. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/data-model/model-reference.md | 16 ++++++++-------- docs/xml-field-reference.md | 2 +- internal/audit/red_snmp_listen.go | 6 ++++-- internal/audit/snmp_agent_test.go | 3 ++- pkg/model/services.go | 6 ++++-- pkg/parser/opnsense/converter_snmp.go | 8 +++++--- .../testdata/api-snapshots/pkg-model.golden | 6 ++++-- .../api-snapshots/pkg-schema-opnsense.golden | 7 ++++--- pkg/schema/opnsense/netsnmp.go | 7 ++++--- 9 files changed, 36 insertions(+), 25 deletions(-) diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index f44ea3140..210f7820a 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -340,14 +340,14 @@ DHCP scopes are a flat array with one entry per interface. 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; empty means the agent default (all IPv4). Red mode never reports an agent bound only to loopback as WAN-exposed | -| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | +| 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 never reports an agent bound only to loopback as WAN-exposed | +| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | #### SNMPUser diff --git a/docs/xml-field-reference.md b/docs/xml-field-reference.md index d1aba609e..05f2ffb40 100644 --- a/docs/xml-field-reference.md +++ b/docs/xml-field-reference.md @@ -172,7 +172,7 @@ 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 general model versions 1.0.0 to 1.0.7 and 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. +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 diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 837ca4d0a..ced73f2ca 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -10,8 +10,10 @@ import ( // snmpReachability is serviceReachability for the SNMP agent, which the // os-net-snmp plugin can bind to chosen addresses. An agent whose every listen // address is a loopback address answers no other host, so it is Local whatever -// the firewall rules pass. Any other listen address, and an empty list, which -// binds every IPv4 address, is judged by the rules as the other services are. +// the firewall rules pass. Any other listen address, and an empty list, is +// judged by the rules 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 snmpReachability(device *common.CommonDevice) analysis.Reachability { if listensOnLoopbackOnly(device.SNMP.ListenAddresses) { return analysis.Local diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index 7f2bea8b2..04c85ad96 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -173,7 +173,8 @@ func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { // UDP 161 and varies the agent's listen list. 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) is still judged by the rule. +// an empty list (every IPv4 address and the IPv6 loopback) is still judged by +// the rule. func TestSNMPAgent_ListenAddressesDecideWANExposure(t *testing.T) { t.Parallel() diff --git a/pkg/model/services.go b/pkg/model/services.go index b20a03d95..ecc25d28b 100644 --- a/pkg/model/services.go +++ b/pkg/model/services.go @@ -405,8 +405,10 @@ type SNMPConfig struct { // whether an agent runs. Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` - // ListenAddresses lists the addresses the agent binds; empty means the - // agent's default, which includes every IPv4 address. + // 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 diff --git a/pkg/parser/opnsense/converter_snmp.go b/pkg/parser/opnsense/converter_snmp.go index 79656d421..75c2727ae 100644 --- a/pkg/parser/opnsense/converter_snmp.go +++ b/pkg/parser/opnsense/converter_snmp.go @@ -19,9 +19,11 @@ var netsnmpGeneralVersions = strings.Fields("1.0.0 1.0.1 1.0.3 1.0.4 1.0.5 1.0.6 var netsnmpUserVersions = strings.Fields("1.0.0 1.0.1") const ( - // netsnmpOn is the value the plugin's templates and netsnmp_enabled() - // compare and with. They read the raw config, so an - // absent element is off, and so is an empty one. + // 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" diff --git a/pkg/parser/testdata/api-snapshots/pkg-model.golden b/pkg/parser/testdata/api-snapshots/pkg-model.golden index 89d5c5cac..2996fbfa4 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-model.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-model.golden @@ -2421,8 +2421,10 @@ type SNMPConfig struct { // whether an agent runs. Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` - // ListenAddresses lists the addresses the agent binds; empty means the - // agent's default, which includes every IPv4 address. + // 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 diff --git a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden index 000aa4296..4b585bf2a 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -1595,9 +1595,10 @@ type NetsnmpGeneral struct { Listen string `xml:"listen" json:"listen" yaml:"listen"` } NetsnmpGeneral is the general model of the os-net-snmp plugin - (Netsnmp/General.xml). Its element names are unchanged from model version - 1.0.0 to 1.0.7; the converter warns on a version it has not been checked - against. + (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; + later versions only added elements. 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"` diff --git a/pkg/schema/opnsense/netsnmp.go b/pkg/schema/opnsense/netsnmp.go index 4d704a8c6..35570a04f 100644 --- a/pkg/schema/opnsense/netsnmp.go +++ b/pkg/schema/opnsense/netsnmp.go @@ -15,9 +15,10 @@ type Netsnmp struct { } // NetsnmpGeneral is the general model of the os-net-snmp plugin -// (Netsnmp/General.xml). Its element names are unchanged from model version -// 1.0.0 to 1.0.7; the converter warns on a version it has not been checked -// against. +// (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; later +// versions only added elements. 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"` From 6c0109560df836bc306f02419b34ec957f5a66a5 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:16:44 -0700 Subject: [PATCH 17/46] docs: limit the loopback claim to the os-net-snmp agent The ListenAddresses row said red mode never reports an agent bound only to loopback as WAN-exposed. No bind address is read for an agent, so one that pfSense binds to 127.0.0.1 or lo0 through is judged by the firewall rules alone and is reported when a WAN rule passes UDP 161. The row now says so, and TestSNMPAgent_SnmpdBindAddressIsNotRead pins that reading. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/data-model/model-reference.md | 16 ++++---- internal/audit/snmp_agent_test.go | 61 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 8 deletions(-) diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 210f7820a..a389186bb 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -340,14 +340,14 @@ DHCP scopes are a flat array with one entry per interface. 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 never reports an agent bound only to loopback as WAN-exposed | -| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | +| 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 never reports an os-net-snmp agent bound only to loopback as WAN-exposed; 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 diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index 04c85ad96..81a69b743 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -214,3 +214,64 @@ func TestSNMPAgent_ListenAddressesDecideWANExposure(t *testing.T) { }) } } + +// 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") + }) + } +} From eb2df79a07144747acfb3b15c27cafc1ea2b80a6 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:39:08 -0700 Subject: [PATCH 18/46] test(audit): pin a loopback-only SNMP agent as local with pf disabled An os-net-snmp agent bound only to loopback answers no other host, whether or not pf filters. Setting , which turns pf off, must not make red mode report it as WAN-exposed. The new cases set that element, with and without a WAN rule passing UDP 161, and require the agent to stay local and draw no exposure. A listen list holding any other address keeps the WAN rule and is still reported. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/snmp_agent_test.go | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index 81a69b743..0f9c46934 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -215,6 +215,59 @@ func TestSNMPAgent_ListenAddressesDecideWANExposure(t *testing.T) { } } +// TestSNMPAgent_LoopbackOnlyAgentStaysLocalWithPacketFilteringDisabled sets +// , which turns pf off, and varies the agent's listen +// list. 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 From 64f8a27bfb0912c9644e7005f43c2d6283169104 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:40:05 -0700 Subject: [PATCH 19/46] docs(audit): name the loopback SNMP agent in the serviceExposures comment The comment said no service in the list can be Local. Since snmpReachability, an os-net-snmp agent bound only to loopback is. Name it as the one exception. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_analysis.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index 9039074cb..b5a9909eb 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -75,7 +75,8 @@ type exposedService struct { // serviceExposures enumerates the in-scope management services present on the // 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. Local-only services are not +// WAN-reachable rules. An SNMP agent bound only to loopback is the one +// exception: it is Local (snmpReachability). 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 { From 824b848018587e23c2e77b345fac533459707b95 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:41:10 -0700 Subject: [PATCH 20/46] docs(audit): limit the serviceExposures exception to os-net-snmp Only the os-net-snmp agent has a listen list. An agent bound to loopback through is still judged by the firewall rules, so the exception names the agent it covers. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_analysis.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index b5a9909eb..4b1a206a3 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -75,7 +75,7 @@ type exposedService struct { // serviceExposures enumerates the in-scope management services present on the // 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 SNMP agent bound only to loopback is the one +// WAN-reachable rules. An os-net-snmp agent bound only to loopback is the one // exception: it is Local (snmpReachability). For any other service Local is not // possible here — a configured management service is at least LAN-reachable. func serviceExposures(device *common.CommonDevice) []exposedService { From 9cf3f01e6bb249be8ef5661f28f0dba2e3082698 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:16:28 -0700 Subject: [PATCH 21/46] fix(audit): apply the SNMP listen list after every other reachability step serviceExposures computed a loopback-only os-net-snmp agent as Local inside the SNMP entry, so any step that later set the list's reachability, such as one marking services WAN-reachable for a reason other than a rule, could report that agent as exposed although no other host can reach it. The list is now built by managementServices, and serviceExposures applies the agent's listen addresses to it last (applySNMPListen). The SNMP entry is classified by the rules like the other services, and an agent bound only to loopback is then set to Local whatever the list says. Red-mode output is unchanged on every testdata fixture and on the synthetic SNMP configs, in both tones. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_analysis.go | 19 +++++- internal/audit/red_snmp_listen.go | 29 +++++---- internal/audit/red_snmp_listen_test.go | 84 ++++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 14 deletions(-) create mode 100644 internal/audit/red_snmp_listen_test.go diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index 4b1a206a3..b8bbd7f51 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -76,13 +76,26 @@ type exposedService struct { // 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 is the one -// exception: it is Local (snmpReachability). For any other service Local is not +// 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. + 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 @@ -136,12 +149,12 @@ func serviceExposures(device *common.CommonDevice) []exposedService { services = append(services, exposedService{ kind: kind, - name: "snmp", + name: serviceNameSNMP, displayName: "SNMP Management Service", severity: analysis.SeverityHigh, component: "snmpd", port: portSNMP, - reachability: snmpReachability(device), + reachability: serviceReachability(device, portSNMP), description: "The SNMP management service is reachable from a WAN interface, exposing device and topology information to untrusted networks.", recommendation: recommendation, vulnerabilities: []string{"exposed-snmp"}, diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index ced73f2ca..6ec460843 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -7,19 +7,26 @@ import ( common "github.com/EvilBit-Labs/opnDossier/pkg/model" ) -// snmpReachability is serviceReachability for the SNMP agent, which the -// os-net-snmp plugin can bind to chosen addresses. An agent whose every listen -// address is a loopback address answers no other host, so it is Local whatever -// the firewall rules pass. Any other listen address, and an empty list, is -// judged by the rules 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 snmpReachability(device *common.CommonDevice) analysis.Reachability { - if listensOnLoopbackOnly(device.SNMP.ListenAddresses) { - return analysis.Local +// serviceNameSNMP is the exposedService name of the SNMP agent. +const serviceNameSNMP = "snmp" + +// applySNMPListen marks the SNMP agent in services as Local when the +// os-net-snmp plugin binds it only to loopback. Such an agent answers no other +// host, so it is Local whatever reachability services already gives it, and +// serviceExposures calls this last. A list holding any other address, or an +// empty list, leaves the agent as it is, 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) { + return } - return serviceReachability(device, portSNMP) + for i := range services { + if services[i].name == serviceNameSNMP { + services[i].reachability = analysis.Local + } + } } // listensOnLoopbackOnly reports whether addresses is non-empty and every entry diff --git a/internal/audit/red_snmp_listen_test.go b/internal/audit/red_snmp_listen_test.go new file mode 100644 index 000000000..c45ec2687 --- /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 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") +} From cc84320b11e35afa31de655224290679da635ab2 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:47:37 -0700 Subject: [PATCH 22/46] docs(schema): say what each net-snmp general model version changed The NetsnmpGeneral comment said the versions after 1.0.0 only added elements. 1.0.1 and 1.0.3 to 1.0.5 each added one; 1.0.6 changed community, syslocation and syscontact to StrictTextField, and 1.0.7 set AllowSpaces on syslocation and syscontact, so neither added an element. No element the type binds was renamed or removed in any of them. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- .../testdata/api-snapshots/pkg-schema-opnsense.golden | 9 +++++---- pkg/schema/opnsense/netsnmp.go | 7 ++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden index 4b585bf2a..82774addd 100644 --- a/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden +++ b/pkg/parser/testdata/api-snapshots/pkg-schema-opnsense.golden @@ -1595,10 +1595,11 @@ type NetsnmpGeneral struct { 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; - later versions only added elements. The converter warns on a version it has - not been checked against. + (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"` diff --git a/pkg/schema/opnsense/netsnmp.go b/pkg/schema/opnsense/netsnmp.go index 35570a04f..9fa6d7b82 100644 --- a/pkg/schema/opnsense/netsnmp.go +++ b/pkg/schema/opnsense/netsnmp.go @@ -16,9 +16,10 @@ type Netsnmp struct { // 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; later -// versions only added elements. The converter warns on a version it has not -// been checked against. +// 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"` From e2873a0cab74927e467307e308ff3515018f93a9 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:03:56 -0700 Subject: [PATCH 23/46] fix(audit): keep a loopback SNMP agent exposed when a forward targets loopback applySNMPListen marked an os-net-snmp agent bound only to loopback as Local whatever reachability the firewall rules gave it. pf rewrites a port forward's destination before delivery, so a WAN forward of UDP 161 to 127.0.0.1 reaches such an agent, and the filter rule passing the forward is evidence of exposure; red mode reported only the port forward and no SNMP exposure. The agent is now left as the rules judge it whenever an enabled forward that redirects traffic targets a loopback address, or an alias whose members hold one, or a name no alias defines that has the shape of an alias name. The forward's interface, protocol and ports are not read, and neither is whether pf runs, so a forward to loopback for another service, or one that never runs with packet filtering disabled, can over-report. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/data-model/model-reference.md | 16 +- internal/audit/red_analysis.go | 6 +- internal/audit/red_snmp_listen.go | 52 ++- internal/audit/red_snmp_listen_test.go | 10 +- internal/audit/snmp_agent_test.go | 18 +- internal/audit/snmp_loopback_forward_test.go | 408 +++++++++++++++++++ 6 files changed, 479 insertions(+), 31 deletions(-) create mode 100644 internal/audit/snmp_loopback_forward_test.go diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index a389186bb..1ca16b7b5 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -340,14 +340,14 @@ DHCP scopes are a flat array with one entry per interface. 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 never reports an os-net-snmp agent bound only to loopback as WAN-exposed; an `` agent is judged by the firewall rules alone | -| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | +| 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 redirects traffic to a loopback address, which pf delivers to such an agent; 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 diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index b8bbd7f51..b0bf4c448 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -75,7 +75,8 @@ type exposedService struct { // serviceExposures enumerates the in-scope management services present on the // 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 is the one +// WAN-reachable rules. An os-net-snmp agent bound only to loopback, when no +// port forward redirects traffic 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 { @@ -87,7 +88,8 @@ func serviceExposures(device *common.CommonDevice) []exposedService { // 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. + // host, whatever the firewall passes, unless a port forward redirects + // traffic to loopback. applySNMPListen(device, services) return services diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 6ec460843..344b97bf0 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -2,6 +2,7 @@ package audit import ( "net/netip" + "slices" "github.com/EvilBit-Labs/opnDossier/internal/analysis" common "github.com/EvilBit-Labs/opnDossier/pkg/model" @@ -10,15 +11,23 @@ import ( // 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()} + // applySNMPListen marks the SNMP agent in services as Local when the -// os-net-snmp plugin binds it only to loopback. Such an agent answers no other -// host, so it is Local whatever reachability services already gives it, and -// serviceExposures calls this last. A list holding any other address, or an -// empty list, leaves the agent as it is, 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. +// os-net-snmp plugin binds it only to loopback and no port forward redirects +// 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 to loopback reaches 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) { + if !listensOnLoopbackOnly(device.SNMP.ListenAddresses) || forwardsToLoopback(device) { return } @@ -29,6 +38,35 @@ func applySNMPListen(device *common.CommonDevice, services []exposedService) { } } +// forwardsToLoopback reports whether an enabled port forward that redirects +// traffic has a target holding a loopback address (targetHoldsLoopback). The +// forward's interface, protocol and ports are not read, so a forward to +// loopback for another service, such as a transparent proxy, also leaves the +// SNMP agent as applySNMPListen found it. Nor is it read whether pf runs: with +// set, pf is off and no forward redirects anything. +// Both 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 && targetHoldsLoopback(nat.InternalIP, device.NamedObjects) + }) +} + +// targetHoldsLoopback reports whether a port forward's target is, or spans, a +// loopback address. OPNsense accepts an alias as the target, and pf then +// redirects to the addresses it holds, so a target 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). A name no alias defines counts too when it has the +// shape of an alias name, since it can name such a table itself. A hostname +// with a domain tells nothing and does not count. +func targetHoldsLoopback(target string, objects common.NamedObjects) bool { + if _, defined := objects[target]; defined { + return aliasHoldsFirewallAddress(objects, target, loopbackAddresses) + } + + return holdsFirewallAddress(target, loopbackAddresses) || aliasNamePattern.MatchString(target) +} + // 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. diff --git a/internal/audit/red_snmp_listen_test.go b/internal/audit/red_snmp_listen_test.go index c45ec2687..f8447aa9b 100644 --- a/internal/audit/red_snmp_listen_test.go +++ b/internal/audit/red_snmp_listen_test.go @@ -9,11 +9,11 @@ import ( ) // TestApplySNMPListen_OverridesEarlierReachability checks that an agent bound -// only to loopback 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. +// 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() diff --git a/internal/audit/snmp_agent_test.go b/internal/audit/snmp_agent_test.go index 0f9c46934..fa08443b3 100644 --- a/internal/audit/snmp_agent_test.go +++ b/internal/audit/snmp_agent_test.go @@ -170,11 +170,11 @@ func TestSNMPAgent_ControlsFollowTheAgentTheConfigStarts(t *testing.T) { } // TestSNMPAgent_ListenAddressesDecideWANExposure keeps the WAN rule passing -// UDP 161 and varies the agent's listen list. 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. +// 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() @@ -217,10 +217,10 @@ func TestSNMPAgent_ListenAddressesDecideWANExposure(t *testing.T) { // TestSNMPAgent_LoopbackOnlyAgentStaysLocalWithPacketFilteringDisabled sets // , which turns pf off, and varies the agent's listen -// list. 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. +// 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() diff --git a/internal/audit/snmp_loopback_forward_test.go b/internal/audit/snmp_loopback_forward_test.go new file mode 100644 index 000000000..df994d3cd --- /dev/null +++ b/internal/audit/snmp_loopback_forward_test.go @@ -0,0 +1,408 @@ +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. 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, + }, + { + // The forward's interface, protocol and ports are not read, so a + // transparent proxy's forward to loopback keeps the agent exposed + // by the rule. That over-reports. + 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), + exposed: true, + }, + { + 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") + } + + want := analysis.Local + if tc.exposed { + want = analysis.WANReachable + } + + 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) + + _, exposed := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") + assert.Equal(t, tc.exposed, exposed, "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 an alias, or +// names one, that holds one; 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: "urltable", Members: []string{"https://example.com/list.txt"}}, + "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: "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")}}, + { + 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) + }) + } +} From 0a87891cff4ca41770443c472e986f1a7c1ab474 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:56:14 -0700 Subject: [PATCH 24/46] fix(audit): count only a forward that can reach UDP 161 for a loopback SNMP agent The previous commit left an os-net-snmp agent bound only to loopback to the firewall rules whenever any enabled port forward targeted loopback, whatever its protocol and ports. The plugin's snmpd.conf template binds every agent address on UDP 161, so a forward to another port cannot reach the agent. A LAN redirect of TCP/UDP 53 to 127.0.0.1:53, which sends DNS queries to the local resolver, kept such an agent exposed, and with a WAN rule for UDP 161 red mode reported "WAN-Exposed Service: SNMP Management Service" for an agent only 127.0.0.1 can reach. The pushed branch reported no SNMP exposure for that config. A forward now counts only when it can redirect UDP to port 161 as OPNsense generates it (ForwardRule.php, Rule.php): a forward with no protocol or any matches every protocol and keeps every port, since OPNsense reads ports only for tcp, udp and tcp/udp; another named protocol, tcp among them, redirects no UDP. For udp and tcp/udp, the destination port must permit 161 when there is no local port. With a local port, pf rewrites the matched port to it when the destination port is a single number or any port, so the local port decides; a range, an alias or a service name is still read as reaching the agent. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/data-model/model-reference.md | 16 +- internal/audit/red_snmp_listen.go | 69 ++++-- internal/audit/snmp_forward_port_test.go | 232 +++++++++++++++++++ internal/audit/snmp_loopback_forward_test.go | 48 ++-- 4 files changed, 320 insertions(+), 45 deletions(-) create mode 100644 internal/audit/snmp_forward_port_test.go diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 1ca16b7b5..93c3a3b34 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -340,14 +340,14 @@ DHCP scopes are a flat array with one entry per interface. 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 redirects traffic to a loopback address, which pf delivers to such an agent; an `` agent is judged by the firewall rules alone | -| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | +| 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 to a loopback address can redirect UDP port 161, where that agent answers SNMP; 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 diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 344b97bf0..eebf01a70 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -3,6 +3,8 @@ package audit import ( "net/netip" "slices" + "strconv" + "strings" "github.com/EvilBit-Labs/opnDossier/internal/analysis" common "github.com/EvilBit-Labs/opnDossier/pkg/model" @@ -16,16 +18,16 @@ const serviceNameSNMP = "snmp" var loopbackAddresses = []netip.Addr{netip.MustParseAddr("127.0.0.1"), netip.IPv6Loopback()} // applySNMPListen marks the SNMP agent in services as Local when the -// os-net-snmp plugin binds it only to loopback and no port forward redirects -// 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 to loopback reaches 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. +// 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 reaches 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 @@ -39,18 +41,51 @@ func applySNMPListen(device *common.CommonDevice, services []exposedService) { } // forwardsToLoopback reports whether an enabled port forward that redirects -// traffic has a target holding a loopback address (targetHoldsLoopback). The -// forward's interface, protocol and ports are not read, so a forward to -// loopback for another service, such as a transparent proxy, also leaves the -// SNMP agent as applySNMPListen found it. Nor is it read whether pf runs: with -// set, pf is off and no forward redirects anything. -// Both can over-report, the safe direction. +// traffic can redirect UDP to port 161 (forwardCanReachSNMPPort) and has a +// target holding a loopback address (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. Both 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 && targetHoldsLoopback(nat.InternalIP, device.NamedObjects) + return !nat.Disabled && !nat.NoRDR && forwardCanReachSNMPPort(nat) && + targetHoldsLoopback(nat.InternalIP, device.NamedObjects) }) } +// 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 service name is read as permitting 161 +// (analysis.RulePortPermits). +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, or spans, a // loopback address. OPNsense accepts an alias as the target, and pf then // redirects to the addresses it holds, so a target an alias defines counts when diff --git a/internal/audit/snmp_forward_port_test.go b/internal/audit/snmp_forward_port_test.go new file mode 100644 index 000000000..1a0d78083 --- /dev/null +++ b/internal/audit/snmp_forward_port_test.go @@ -0,0 +1,232 @@ +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 range, alias or service name is read as reaching the agent. +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 a service name", protocol: "udp", dstPort: "domain", 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_loopback_forward_test.go b/internal/audit/snmp_loopback_forward_test.go index df994d3cd..f1cf7b664 100644 --- a/internal/audit/snmp_loopback_forward_test.go +++ b/internal/audit/snmp_loopback_forward_test.go @@ -163,8 +163,9 @@ func snmpForwardAlias(uuid, name, aliasType, members string) string { // 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. The cases vary what the forward targets, its flags in both -// stored shapes, its place in the list, and the service it forwards. +// 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() @@ -217,13 +218,11 @@ func TestSNMPAgent_PortForwardToLoopbackKeepsWANExposure(t *testing.T) { exposed: true, }, { - // The forward's interface, protocol and ports are not read, so a - // transparent proxy's forward to loopback keeps the agent exposed - // by the rule. That over-reports. + // 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), - exposed: true, }, { name: "rule to 127.0.0.1 of its own, no forward", @@ -272,23 +271,32 @@ func TestSNMPAgent_PortForwardToLoopbackKeepsWANExposure(t *testing.T) { require.Equal(t, tc.noRDR, last.NoRDR, "no-RDR") } - want := analysis.Local - if tc.exposed { - want = analysis.WANReachable - } - - 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) + assertSNMPForwardExposure(t, device, tc.exposed) + }) + } +} - report := newRedReport(device) - runRedAnalysis(report) +// 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() - _, exposed := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") - assert.Equal(t, tc.exposed, exposed, "red-mode SNMP exposure") - }) + want := analysis.Local + if exposed { + want = analysis.WANReachable } + + 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, exposed, reported, "red-mode SNMP exposure") } // TestForwardsToLoopback_TargetsAndFlags checks which port forwards count as From 867db623b11fae1656288b355ce807af83e55ba4 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:32:13 -0700 Subject: [PATCH 25/46] test(audit): pin the snmp service name in the forward port test TestForwardCanReachSNMPPort expected a forward to the service name "domain" to reach UDP 161, because analysis.RulePortPermits cannot read a service name and reads it as permitting. The port alias PR (#1016) teaches RulePortPermits the service names OPNsense's PortField accepts, where "domain" is 53, so on the merge of the two branches the case fails. The case now uses "snmp", which reaches 161 whether or not service names resolve. The forwardCanReachSNMPPort comment and the test comment no longer say a service name is read as permitting 161: a port alias, or another port RulePortPermits cannot read, is. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_snmp_listen.go | 4 ++-- internal/audit/snmp_forward_port_test.go | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index eebf01a70..ddc32e18c 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -63,8 +63,8 @@ func forwardsToLoopback(device *common.CommonDevice) bool { // 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 service name is read as permitting 161 -// (analysis.RulePortPermits). +// 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 diff --git a/internal/audit/snmp_forward_port_test.go b/internal/audit/snmp_forward_port_test.go index 1a0d78083..a0083ac08 100644 --- a/internal/audit/snmp_forward_port_test.go +++ b/internal/audit/snmp_forward_port_test.go @@ -112,7 +112,8 @@ func TestSNMPAgent_ForwardProtocolAndPortsDecideExposure(t *testing.T) { // 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 range, alias or service name is read as reaching the agent. +// 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() @@ -139,7 +140,7 @@ func TestForwardCanReachSNMPPort(t *testing.T) { {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 a service name", protocol: "udp", dstPort: "domain", 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"}, From 78ebd58fc0ec72daaf485ee2cbdf5193cf3c81cf Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:34:11 -0700 Subject: [PATCH 26/46] docs(audit): name the forward that keeps a loopback SNMP agent exposed The serviceExposures comments still said a loopback-only os-net-snmp agent is Local only when no port forward redirects traffic to loopback. Since the previous commit, a forward to loopback that cannot reach UDP 161, such as a LAN DNS redirect to 127.0.0.1:53, leaves the agent Local, so both comments now name a forward that can redirect UDP port 161 to loopback, as applySNMPListen and the model reference do. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_analysis.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/audit/red_analysis.go b/internal/audit/red_analysis.go index b0bf4c448..1143b8427 100644 --- a/internal/audit/red_analysis.go +++ b/internal/audit/red_analysis.go @@ -76,7 +76,7 @@ type exposedService struct { // 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 redirects traffic to loopback, is the one +// 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 { @@ -88,8 +88,8 @@ func serviceExposures(device *common.CommonDevice) []exposedService { // 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 redirects - // traffic to loopback. + // host, whatever the firewall passes, unless a port forward can redirect + // UDP port 161 to loopback (forwardsToLoopback). applySNMPListen(device, services) return services From 654c6c635ce3c91b969776f522691b25e204ac8a Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:39:26 -0700 Subject: [PATCH 27/46] test(parser): pin os-net-snmp general model 1.0.2 as unrecognized The plugin's General.xml history skips version 1.0.2, so the converter pins 1.0.0, 1.0.1 and 1.0.3 to 1.0.7 and a config at 1.0.2 draws the Medium version warning. The test only checked an unknown version past the newest, so adding 1.0.2 to the pin list to make it contiguous passed every test. A case for general 1.0.2 now expects the warning. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- pkg/parser/opnsense/converter_snmp_test.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pkg/parser/opnsense/converter_snmp_test.go b/pkg/parser/opnsense/converter_snmp_test.go index 262adb364..4307b8b1d 100644 --- a/pkg/parser/opnsense/converter_snmp_test.go +++ b/pkg/parser/opnsense/converter_snmp_test.go @@ -317,9 +317,10 @@ func TestConverter_SNMP_SecretsNeverExported(t *testing.T) { } // TestConverter_SNMP_ModelVersionPins checks every version each os-net-snmp -// model has carried converts without a warning, and that an unknown version -// 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. +// 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() @@ -345,6 +346,12 @@ func TestConverter_SNMP_ModelVersionPins(t *testing.T) { 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", "", ""), From 8110165bfd23503c80b0690010a117a00e82cad8 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:18:31 -0700 Subject: [PATCH 28/46] docs: record the forward read that keeps a loopback SNMP agent exposed GOTCHAS 8.4 says NAT rules never correlate against firewall-local services, which holds for wanRulePermitsPort. applySNMPListen reads the port forwards too: forwardsToLoopback keeps an os-net-snmp agent bound only to loopback from being set Local when an enabled forward that can redirect UDP 161 targets loopback. Nothing recorded that, so the rule read as a reason to remove it, which would bring back a missed WAN exposure. Add a bullet after the rule that names the read, says the forward never makes the agent reachable by itself, and says that neither the forward's interface nor packet filtering being off is read, which over-reports. The solution page for the original bug gets the same note beside its note on forwardsToAnotherHost. TestSNMPAgent_ForwardInterfaceIsNotRead pins the interface claim with a LAN forward of UDP 161 to 127.0.0.1: requiring the forward to be on wan fails both of its cases. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 1 + ...rongly-correlated-with-firewall-service.md | 2 + internal/audit/snmp_forward_interface_test.go | 47 +++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 internal/audit/snmp_forward_interface_test.go diff --git a/GOTCHAS.md b/GOTCHAS.md index 2dce3ff25..b29d4ad0b 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,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, an alias that may hold one, or a name no alias 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 reaches an agent bound to loopback. 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 `` is read there, so a LAN forward (`TestSNMPAgent_ForwardInterfaceIsNotRead`), or a forward on a firewall with packet filtering off, keeps the verdict too, which 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/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..40aca3c7f 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:** `applySNMPListen` reads `device.NAT.InboundRules` too, through `forwardsToLoopback`. An enabled forward that can redirect UDP port 161 to loopback 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, so a NAT rule is still never evidence of exposure. 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/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) + }) + } +} From d75270e98fc133c8e18a0209a516066485ad8a25 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:01:28 -0700 Subject: [PATCH 29/46] fix(audit): leave a loopback SNMP agent local on a forward to an interface OPNsense accepts an interface as a port forward's target: its key for the interface's network, and for wan, lan and optN the key and "ip" for its address (Rule.php loadAliasMap maps them to (if:network) and (if), and ForwardRule.php parseRdrRules redirects to any name in that map). targetHoldsLoopback read lanip, wanip and lan as names no alias defines with the shape of an alias name, which may hold loopback, so an os-net-snmp agent bound only to 127.0.0.1 with a WAN forward of UDP 161 to lanip was reported as a WAN-exposed SNMP service. pf delivers that traffic to the LAN address, where the agent does not listen. A target that is an interface's key, or its key and "ip", now counts only when that interface's own IPv4 or IPv6 address is a loopback address, as on lo0. An alias of the same name is still read first, as the alias map lets an alias replace an interface entry. A name that matches no interface, lo0 on a config without the lo0 interface among them, is read as before. The comment and GOTCHAS 8.4 name the interface case, and both now say that the target's address family is not matched against the listen list, which over-reports. Tests drive configs through parse, convert and red mode: forwards to lanip, wanip and the lan net leave the agent Local; forwards to the lo0 net with and without the lo0 interface, to 127.0.0.1, to an alias holding it, and to an undefined name keep it exposed. A unit table covers DHCP and IPv6-only interfaces, an IPv6-only lo0, an assigned loopback device, interface order, and a name in another case. Removing the interface check fails ten cases. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 31 +++- .../snmp_forward_interface_target_test.go | 172 ++++++++++++++++++ 3 files changed, 195 insertions(+), 10 deletions(-) create mode 100644 internal/audit/snmp_forward_interface_target_test.go diff --git a/GOTCHAS.md b/GOTCHAS.md index b29d4ad0b..50be44b9c 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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, an alias that may hold one, or a name no alias 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 reaches an agent bound to loopback. 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 `` is read there, so a LAN forward (`TestSNMPAgent_ForwardInterfaceIsNotRead`), or a forward on a firewall with packet filtering off, keeps the verdict too, which 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. +- **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, 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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward reaches an agent bound to loopback. 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. 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index ddc32e18c..5d3042f2b 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -45,12 +45,14 @@ func applySNMPListen(device *common.CommonDevice, services []exposedService) { // target holding a loopback address (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. Both can over-report, the safe direction. +// 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.NamedObjects) + targetHoldsLoopback(nat.InternalIP, device) }) } @@ -91,12 +93,23 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // redirects to the addresses it holds, so a target 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). A name no alias defines counts too when it has the -// shape of an alias name, since it can name such a table itself. A hostname -// with a domain tells nothing and does not count. -func targetHoldsLoopback(target string, objects common.NamedObjects) bool { - if _, defined := objects[target]; defined { - return aliasHoldsFirewallAddress(objects, target, loopbackAddresses) +// config does not store). 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. 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 hostname with a domain tells +// nothing and does not count. +func targetHoldsLoopback(target string, device *common.CommonDevice) bool { + if _, defined := device.NamedObjects[target]; defined { + return aliasHoldsFirewallAddress(device.NamedObjects, target, loopbackAddresses) + } + + for _, iface := range device.Interfaces { + if target == iface.Name || target == iface.Name+"ip" { + return isLoopbackEntry(iface.IPAddress) || isLoopbackEntry(iface.IPv6Address) + } } return holdsFirewallAddress(target, loopbackAddresses) || aliasNamePattern.MatchString(target) 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..4e81e882d --- /dev/null +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -0,0 +1,172 @@ +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. OPNsense +// accepts 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. +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 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. 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. +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"}}, + } + + tests := []struct { + name string + target string + interfaces []common.Interface + 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: "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}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + device := &common.CommonDevice{Interfaces: tc.interfaces, NamedObjects: objects} + assert.Equal(t, tc.want, targetHoldsLoopback(tc.target, device)) + }) + } +} From 6594d2430f401f1ded5704aaf985c10bd21b40a3 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:04:51 -0700 Subject: [PATCH 30/46] docs: name every forward target that keeps a loopback SNMP agent exposed The ListenAddresses row in the model reference said red mode reports a loopback-only os-net-snmp agent as WAN-exposed only when an enabled forward to a loopback address can redirect UDP port 161. forwardsToLoopback also counts a network spanning loopback, an alias that may hold it, such as one naming a table the config does not store, the net or address of an interface whose own address is loopback, such as lo0, and a name no alias or interface defines that has the shape of an alias name, as GOTCHAS 8.4 lists. The row now names a loopback address, a network spanning one, or a name that may hold one, and points to that section for the list. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/data-model/model-reference.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/data-model/model-reference.md b/docs/data-model/model-reference.md index 93c3a3b34..568711dfb 100644 --- a/docs/data-model/model-reference.md +++ b/docs/data-model/model-reference.md @@ -340,14 +340,14 @@ DHCP scopes are a flat array with one entry per interface. 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 to a loopback address can redirect UDP port 161, where that agent answers SNMP; an `` agent is judged by the firewall rules alone | -| `Users` | `[]SNMPUser` | `snmp.users` | SNMPv3 users the agent loads; passwords and keys are not carried | +| 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 From 2a88121c5b83e0335dfc72f555ee9d87c079a518 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:05:11 -0700 Subject: [PATCH 31/46] docs: say what the loopback SNMP forward read does bear on The solution page for the NAT correlation bug said the forward never makes a loopback SNMP agent reachable by itself, "so a NAT rule is still never evidence of exposure". For an os-net-snmp agent bound only to loopback, the forward is what lets a WAN pass rule count: without it the agent is set Local whatever the rules say. The note keeps the accurate half, says the forward lets that rule count, and names the forward the read counts as one that can redirect UDP port 161 and may target loopback, pointing to GOTCHAS 8.4 for the targets. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- ...at-inbound-rules-wrongly-correlated-with-firewall-service.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 40aca3c7f..bff9c8359 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,7 +41,7 @@ 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:** `applySNMPListen` reads `device.NAT.InboundRules` too, through `forwardsToLoopback`. An enabled forward that can redirect UDP port 161 to loopback 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, so a NAT rule is still never evidence of exposure. Do not remove that read as a regression of this bug either. +> **Another read:** `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`: From 9b0db9d686ded8d118771abb9ea8a440b3c86fe7 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:56:43 -0700 Subject: [PATCH 32/46] fix(audit): keep a loopback SNMP agent exposed on a forward to (self) OPNsense offers (self), This Firewall, as a port forward's target (NetworkAliasField), Rule.php loadAliasMap maps it to (self), and ForwardRule.php parseRdrRules redirects to any name in that map. pf reads (self) as every address of every interface, as the "self" dynamic address attaches to the group of all interfaces (pf_if.c), so the addresses of lo0 are among them. targetHoldsLoopback did not count it: it is no alias or interface, and the parentheses fail both the address read and the alias-name shape. An os-net-snmp agent bound only to 127.0.0.1, with a WAN forward of UDP 161 to (self) and the rule that passes it, was set Local and its WAN exposure went unreported, while the same forward to 0.0.0.0/0, which spans loopback the same way, kept it. The target (self) now counts, before the alias lookup. The match is exact, as the alias map's is: OPNsense disables a forward to (SELF) as an invalid target. The comment and GOTCHAS 8.4 name the target. Tests drive a forward to (self) in both stored shapes through parse, convert and red mode, one with the agent bound to ::1, and a unit case pins (self) counting and (SELF) not. Removing the check fails four cases; matching without case fails the (SELF) case. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 8 +++++++- .../snmp_forward_interface_target_test.go | 8 +++++++- internal/audit/snmp_loopback_forward_test.go | 20 ++++++++++++++++++- 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index 50be44b9c..a89b82ec9 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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, 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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward reaches an agent bound to loopback. 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. 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. +- **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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward reaches an agent bound to loopback. 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. 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 5d3042f2b..c3768e04e 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -89,7 +89,9 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { } // targetHoldsLoopback reports whether a port forward's target is, or spans, a -// loopback address. OPNsense accepts an alias as the target, and pf then +// loopback address. 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 as the target, and pf then // redirects to the addresses it holds, so a target 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 @@ -102,6 +104,10 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // can name a table the config does not store. A hostname with a domain tells // nothing and does not count. func targetHoldsLoopback(target string, device *common.CommonDevice) bool { + if target == "(self)" { + return true + } + if _, defined := device.NamedObjects[target]; defined { return aliasHoldsFirewallAddress(device.NamedObjects, target, loopbackAddresses) } diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go index 4e81e882d..619b815a5 100644 --- a/internal/audit/snmp_forward_interface_target_test.go +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -42,7 +42,9 @@ func snmpForwardNetworkRule(network string) string { // 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. +// 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. func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { t.Parallel() @@ -77,6 +79,10 @@ func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { 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}, diff --git a/internal/audit/snmp_loopback_forward_test.go b/internal/audit/snmp_loopback_forward_test.go index f1cf7b664..657b12d7d 100644 --- a/internal/audit/snmp_loopback_forward_test.go +++ b/internal/audit/snmp_loopback_forward_test.go @@ -217,6 +217,20 @@ func TestSNMPAgent_PortForwardToLoopbackKeepsWANExposure(t *testing.T) { 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. @@ -301,7 +315,9 @@ func assertSNMPForwardExposure(t *testing.T, device *common.CommonDevice, expose // 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 an alias, or +// 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; 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. @@ -337,6 +353,8 @@ func TestForwardsToLoopback_TargetsAndFlags(t *testing.T) { {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("")}}, From 8c1453195d0ac6179485685888ed27984e92c22b Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:30:08 -0700 Subject: [PATCH 33/46] test(audit): pin that an alias is read before an interface of its name targetHoldsLoopback reads an alias named like a port forward's target before it matches the target against the interfaces, as OPNsense does: Rule.php loadAliasMap adds every alias but a port alias after the interface entries, so an alias of the same name replaces the interface's net or address, and ForwardRule.php parseRdrRules redirects to what that map holds. Swapping the two lookups passed every test in internal/audit. TestTargetHoldsLoopback_InterfaceTargets gains three cases: an alias named lo0 that holds no loopback, beside the lo0 interface, does not count, and aliases named lan and lanip that hold 127.0.0.1, beside a lan interface with a LAN address, do. Swapping the lookups fails all three. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- .../snmp_forward_interface_target_test.go | 41 ++++++++++++++++++- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go index 619b815a5..6550b54c6 100644 --- a/internal/audit/snmp_forward_interface_target_test.go +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -126,7 +126,9 @@ func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { // the list. An interface with a dynamic address, or none, holds no loopback. 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. +// the lo0 interface. An alias named like an interface is read in place of the +// interface, as OPNsense's alias map adds aliases after interfaces, so it +// counts only when its members hold loopback, whatever the interface holds. func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { t.Parallel() @@ -141,11 +143,22 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { "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"}}, + } + tests := []struct { name string target string interfaces []common.Interface - want bool + // 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}}, @@ -165,6 +178,26 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { {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, + }, } for _, tc := range tests { @@ -172,6 +205,10 @@ func TestTargetHoldsLoopback_InterfaceTargets(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)) }) } From 0d779c389de54211d3318902e0ab46eecf87f374 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:31:28 -0700 Subject: [PATCH 34/46] docs: scope the forwardsToAnotherHost note to that read The first note under Solution on the page for the NAT correlation bug said that, since forwardsToAnotherHost can only take a pass rule out of the count, a NAT rule is still never evidence of exposure and the invariant on the page holds. The note below it says that for an os-net-snmp agent bound only to loopback, a forward that may target loopback does bear on whether the agent is reported as exposed, so the two contradicted each other. The first note now says that its read never makes a NAT rule evidence of exposure. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- ...at-inbound-rules-wrongly-correlated-with-firewall-service.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 bff9c8359..09576d57e 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 @@ -39,7 +39,7 @@ Caught by CodeRabbit on PR #695. ## Solution -> **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. +> **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 that read never makes a NAT rule evidence of exposure. 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:** `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. From 133694d82eaf16907eea6ca97fdf61366e4a17aa Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:32:35 -0700 Subject: [PATCH 35/46] docs: say a forward to loopback can reach a loopback SNMP agent GOTCHAS section 8.4 said that pf rewrites a forward's destination before delivery, so a forward to one of the targets it lists reaches an os-net-snmp agent bound to loopback. That claims too much: the list holds targets that only may hold loopback, pf maps a forward to the lo0 net onto an address inside 127.0.0.0/8 that need not be the one the agent binds, and a forward to 127.0.0.2 does not reach an agent bound to 127.0.0.1. The section now says such a forward can reach the agent, and the applySNMPListen comment, which said the same of a forward to loopback, does too. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index a89b82ec9..e2a6d83e5 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward reaches an agent bound to loopback. 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. 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. +- **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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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. 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index c3768e04e..e71e5da47 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -22,9 +22,9 @@ var loopbackAddresses = []netip.Addr{netip.MustParseAddr("127.0.0.1"), netip.IPv // 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 reaches 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, +// 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. From 15331c52069a265cda7a8ae4530d8c1df2364b1c Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:34:01 -0700 Subject: [PATCH 36/46] docs(adr): list the net-snmp general model versions that are pinned The 2026-11-13 update to ADR 0001 said general model versions 1.0.0 to 1.0.7 are pinned, with a note that the plugin never used 1.0.2. checkNetsnmpVersions pins 1.0.0, 1.0.1 and 1.0.3 to 1.0.7, and a model carrying any other version, 1.0.2 included, is still read and draws a Medium conversion warning, as TestConverter_SNMP_ModelVersionPins checks. The ADR now lists the pinned versions and says what any other version does, as docs/xml-field-reference.md already lists them. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4a34d5f58..4874b2875 100644 --- a/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md +++ b/docs/adr/0001-opnsense-pfsense-snmp-config-storage-model.md @@ -63,7 +63,7 @@ Scope opnDossier's SNMP credential handling to what the vendor source actually p 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 to 1.0.7 (the plugin never used 1.0.2) 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. The `password` and `enckey` elements are not bound in the schema, so model-based features never see them. +- 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. From b94c70656c7f762613f9bf2712663e8785f0f8e0 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:36:25 -0700 Subject: [PATCH 37/46] docs(audit): describe the loopback forward target reading as coded The forwardsToLoopback comment said a forward counts when its target holds a loopback address. targetHoldsLoopback also counts a network spanning one and a name that may hold one, such as (self), an alias naming a table the config does not store, or a name no alias defines, so the comment now says a target that is, spans or may hold one. The targetHoldsLoopback comment named wan, lan and optN for the key and "ip" form of an interface target, but the code matches that form for every interface, so lo0ip counts beside a lo0 that holds loopback. OPNsense maps the form only for wan, lan and optN (Rule.php loadAliasMap) and disables a forward to any other name it does not map as an invalid target (ForwardRule.php parseRdrRules), so the wider match can only over-report. The comment and GOTCHAS section 8.4 now say so, and TestTargetHoldsLoopback_InterfaceTargets pins that a forward to lo0ip counts. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 25 +++++++++++-------- .../snmp_forward_interface_target_test.go | 16 +++++++++--- 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index e2a6d83e5..dcb076b5b 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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. 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. +- **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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index e71e5da47..ed0e8391e 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -42,13 +42,13 @@ func applySNMPListen(device *common.CommonDevice, services []exposedService) { // forwardsToLoopback reports whether an enabled port forward that redirects // traffic can redirect UDP to port 161 (forwardCanReachSNMPPort) and has a -// target holding a loopback address (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. +// target that is, spans or may hold a loopback address (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) && @@ -99,10 +99,13 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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. 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 hostname with a domain tells -// nothing and does not count. +// a forward to lanip or to the lan net leaves the agent Local. 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 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 hostname with a domain tells nothing and does not count. func targetHoldsLoopback(target string, device *common.CommonDevice) bool { if target == "(self)" { return true diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go index 6550b54c6..25dd537e9 100644 --- a/internal/audit/snmp_forward_interface_target_test.go +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -123,10 +123,12 @@ func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { // 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. 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 +// 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 adds aliases after interfaces, so it // counts only when its members hold loopback, whatever the interface holds. func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { @@ -174,6 +176,12 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { 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}, From 2694943f7fd5c3e7ac5a372bf9b9828092f99afb Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:38:18 -0700 Subject: [PATCH 38/46] docs: scope the forwardsToAnotherHost note from the note below it The previous change to the page for the NAT correlation bug rewrote the first note under Solution, which the interface group PR (#1001) also rewrites, so the two branches no longer merged without a conflict. That note is restored as it stands on main, and the note this branch adds below it now opens by saying that what the first note concludes, that a NAT rule is never evidence of exposure, holds for the read through forwardsToAnotherHost only. The two notes agree again, and the page merges cleanly with #1001. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- ...-inbound-rules-wrongly-correlated-with-firewall-service.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 09576d57e..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 @@ -39,9 +39,9 @@ Caught by CodeRabbit on PR #695. ## Solution -> **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 that read never makes a NAT rule evidence of exposure. 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. +> **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:** `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. +> **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`: From bc218b7dcc495cba0194058ed23403570d57a163 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:09:56 -0700 Subject: [PATCH 39/46] fix(audit): leave port aliases out of the loopback forward target lookup targetHoldsLoopback read an alias named like a port forward's target before it matched the target against the interfaces, and that included port aliases. OPNsense maps the interfaces first and then every alias but a port alias (Rule.php loadAliasMap), and ForwardRule.php parseRdrRules redirects to what that map holds, so a port alias named like an interface does not replace it. With a port alias named lo0 beside the lo0 interface, an os-net-snmp agent bound only to 127.0.0.1, with a WAN forward of UDP 161 to the lo0 net and the rule that passes it, was set Local and reported no SNMP exposure. A port alias is now left out of the alias lookup, so the interface of its name decides. A port alias named like no interface does not count: parseRdrRules disables a forward to a name the map does not hold unless it is an address or a subnet, and an alias name can be neither, since it holds only letters, digits and underscores. TestTargetHoldsLoopback_InterfaceTargets gains three cases: a port alias named lo0 beside the lo0 interface counts, and a port alias named lanip beside a lan interface, or named like no interface, does not. TestSNMPAgent_ForwardToPortAliasName drives the first and the last through parse, convert and red mode. Reading a port alias as any other alias fails the lo0 case of both tests, and dropping the check that a port alias named like no interface does not count fails the other case of both. Red and blue JSON on every testdata fixture match the previous commit. Commit 8c145319 said the alias lookup comes first as OPNsense does; that held for every alias but a port alias. The test comment it added now says so. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_snmp_listen.go | 29 ++++--- .../snmp_forward_interface_target_test.go | 75 ++++++++++++++++++- 2 files changed, 93 insertions(+), 11 deletions(-) diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index ed0e8391e..5d5e9cabc 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -91,18 +91,24 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // targetHoldsLoopback reports whether a port forward's target is, or spans, a // loopback address. 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 as the target, and pf then -// redirects to the addresses it holds, so a target an alias defines counts when -// a member of the alias, or of an alias it names, holds one +// 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). 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. 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 as an invalid target: the wider +// 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 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 hostname with a domain tells nothing and does not count. @@ -111,7 +117,8 @@ func targetHoldsLoopback(target string, device *common.CommonDevice) bool { return true } - if _, defined := device.NamedObjects[target]; defined { + object, defined := device.NamedObjects[target] + if defined && object.Type != common.NamedObjectTypePort { return aliasHoldsFirewallAddress(device.NamedObjects, target, loopbackAddresses) } @@ -121,6 +128,10 @@ func targetHoldsLoopback(target string, device *common.CommonDevice) bool { } } + if defined { + return false + } + return holdsFirewallAddress(target, loopbackAddresses) || aliasNamePattern.MatchString(target) } diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go index 25dd537e9..ecd9c2fff 100644 --- a/internal/audit/snmp_forward_interface_target_test.go +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -129,8 +129,12 @@ func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { // 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 adds aliases after interfaces, so it -// counts only when its members hold loopback, whatever the interface holds. +// interface, as OPNsense's alias map 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 OPNsense disables a forward to it as an +// invalid target. func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { t.Parallel() @@ -154,6 +158,14 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { "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 @@ -206,6 +218,25 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { 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 { @@ -221,3 +252,43 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { }) } } + +// 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. 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. +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) + }) + } +} From 1b5f23f85cfed75b1c1226a242df74e2626fbce8 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:17:10 -0700 Subject: [PATCH 40/46] docs(audit): say a loopback forward target may hold loopback The targetHoldsLoopback summary said a target counts when it is, or spans, a loopback address. It also counts names that may hold one: (self), an alias whose members name a table the config does not store, and an undefined name with the shape of an alias name. The summary now says is, spans or may hold, as the forwardsToLoopback comment does. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- internal/audit/red_snmp_listen.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 5d5e9cabc..a3ff53a15 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -88,8 +88,8 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { return analysis.RulePortPermits(nat.LocalPort, portSNMP) } -// targetHoldsLoopback reports whether a port forward's target is, or spans, a -// loopback address. The target (self), This Firewall on the forward page, +// targetHoldsLoopback reports whether a port forward's target is, spans or may +// hold a loopback address. 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 From 76d3109e180d1b11cbccdb93c7de0b88f82168b0 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:18:48 -0700 Subject: [PATCH 41/46] docs(audit): limit the invalid key and ip target to names no alias defines The targetHoldsLoopback comment and GOTCHAS.md section 8.4 said OPNsense disables a forward to any key and "ip" name outside wan, lan and optN as an invalid target. loadAliasMap in Rule.php adds every alias but a port alias after the interfaces, so such a name that an alias defines maps to the alias and the forward runs; targetHoldsLoopback reads that alias first. Both now say any other such name no alias defines. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index dcb076b5b..86d9b11be 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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 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. +- **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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index a3ff53a15..0689ae641 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -108,8 +108,8 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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 as an invalid target: the wider -// match can only over-report. A name no alias or interface defines counts when +// 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 hostname with a domain tells nothing and does not count. func targetHoldsLoopback(target string, device *common.CommonDevice) bool { From b4d2cab748fa11cb1c61fb643a2cf38e82d63e3e Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:21:51 -0700 Subject: [PATCH 42/46] docs(audit): scope the forward target reading to OPNsense 26.7 The targetHoldsLoopback comment, GOTCHAS.md section 8.4 and three test comments described how OPNsense resolves a port forward's target without naming a release. That is ForwardRule.php from 26.7, which resolves the target through loadAliasMap: (self), interface names and every alias but a port alias. Through 26.1 ForwardRule.php maps a target only through Util::isAlias, which any alias passes, port aliases included, and disables any other name that is no address or network as an invalid target, (self) and interface names among them. Each now says the reading is 26.7's, and that on earlier releases the readings of (self) and of an interface can only over-report. The targetHoldsLoopback comment is reflowed where the previous commit left a long line. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 18 +++++--- .../snmp_forward_interface_target_test.go | 43 +++++++++++-------- 3 files changed, 37 insertions(+), 26 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index 86d9b11be..55f273930 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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`). 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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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. +- **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`). 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.7. Through 26.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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 0689ae641..d4da5a2be 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -89,9 +89,10 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { } // targetHoldsLoopback reports whether a port forward's target is, spans or may -// hold a loopback address. 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 +// hold a loopback address. It reads the target as ForwardRule.php does from +// OPNsense 26.7. 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 @@ -109,9 +110,14 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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 hostname with a domain tells nothing and does not count. +// 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 hostname with a domain tells nothing and +// does not count. Through 26.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 diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go index ecd9c2fff..423603190 100644 --- a/internal/audit/snmp_forward_interface_target_test.go +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -37,14 +37,16 @@ func snmpForwardNetworkRule(network string) string { // 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. OPNsense -// accepts 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. +// each with a WAN forward of UDP 161 and the rule that passes it. From 26.7 +// OPNsense accepts 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 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() @@ -129,12 +131,12 @@ func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { // 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 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 OPNsense disables a forward to it as an -// invalid target. +// interface, as OPNsense's alias map from 26.7 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 OPNsense 26.7 disables a +// forward to it as an invalid target. func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { t.Parallel() @@ -256,11 +258,14 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { // 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. 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. +// defines and a WAN rule passing UDP 161 to any destination. From 26.7 +// 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 +// 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() From 3ada16c4ad97299806acceee1555b024f1bd1fe6 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:29:47 -0700 Subject: [PATCH 43/46] fix(audit): count a URL table forward target as possibly holding loopback targetHoldsLoopback sent a defined alias that is not a port alias to aliasHoldsFirewallAddress, which reads only the members the config holds. A URL table's members are URLs, so it read as holding no address, and an os-net-snmp agent bound only to 127.0.0.1, with a WAN rule passing UDP 161 to any destination beside a WAN forward of UDP 161 to a URL table, or to a network group naming one, was set local and reported no SNMP exposure. OPNsense 26.7 accepts any alias but a port alias as a forward's target (NetworkAliasField, loadAliasMap in Rule.php), a host, network or network group alias can name an alias of any type (AliasContentField), and the alias loader keeps every address a fetched list holds, loopback included (iter_addresses in the alias library), so such a table may hold the agent's address. targetHoldsLoopback now also counts an alias that is, or names at any depth, a URL alias, a URL table, a URL table in JSON format or an external alias, whose addresses OPNsense gets at runtime (aliasNamesRuntimeTable). aliasHoldsFirewallAddress is unchanged, since forwardsToAlias relies on its reading such an alias as holding no address. A GeoIP alias still does not count. A rule to the table itself is still skipped as the forward's own (forwardsToAnotherHost), so with only that rule the agent is not reported; it now keeps the LAN reachability it has without a WAN rule rather than being set local. The targetHoldsLoopback and forwardsToLoopback comments and GOTCHAS.md section 8.4 name the runtime alias types. TestForwardsToLoopback_ TargetsAndFlags expected a URL table to count as holding no loopback; it now expects it to count, as does a network group naming one. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 78 ++++-- .../audit/snmp_forward_runtime_alias_test.go | 223 ++++++++++++++++++ internal/audit/snmp_loopback_forward_test.go | 40 +++- 4 files changed, 318 insertions(+), 25 deletions(-) create mode 100644 internal/audit/snmp_forward_runtime_alias_test.go diff --git a/GOTCHAS.md b/GOTCHAS.md index 55f273930..b49be480c 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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`). 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.7. Through 26.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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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. +- **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`). 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, 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.7. Through 26.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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index d4da5a2be..83359b56f 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -17,6 +17,20 @@ const serviceNameSNMP = "snmp" // 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 @@ -42,13 +56,14 @@ func applySNMPListen(device *common.CommonDevice, services []exposedService) { // 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 (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. +// 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) && @@ -92,13 +107,16 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // hold a loopback address. It reads the target as ForwardRule.php does from // OPNsense 26.7. 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 +// 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). 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 +// config does not store), or when the alias, or an alias it names, gets its +// addresses at runtime, as a URL table does (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 @@ -125,7 +143,8 @@ func targetHoldsLoopback(target string, device *common.CommonDevice) bool { object, defined := device.NamedObjects[target] if defined && object.Type != common.NamedObjectTypePort { - return aliasHoldsFirewallAddress(device.NamedObjects, target, loopbackAddresses) + return aliasHoldsFirewallAddress(device.NamedObjects, target, loopbackAddresses) || + aliasNamesRuntimeTable(device.NamedObjects, target) } for _, iface := range device.Interfaces { @@ -141,6 +160,37 @@ func targetHoldsLoopback(target string, device *common.CommonDevice) bool { return holdsFirewallAddress(target, loopbackAddresses) || aliasNamePattern.MatchString(target) } +// aliasNamesRuntimeTable reports whether the alias name, or an alias it names +// at any depth, is of a type in runtimeAliasTypes. What such an alias holds +// arrives at runtime, and OPNsense loads every address a fetched list holds, +// loopback addresses included, so it 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 { + if _, defined := objects[member]; defined && !seen[member] { + seen[member] = true + pending = append(pending, member) + } + } + } + + return false +} + // 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. 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 index 657b12d7d..5141e5179 100644 --- a/internal/audit/snmp_loopback_forward_test.go +++ b/internal/audit/snmp_loopback_forward_test.go @@ -301,6 +301,15 @@ func assertSNMPForwardExposure(t *testing.T, device *common.CommonDevice, expose 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) @@ -310,17 +319,18 @@ func assertSNMPForwardExposure(t *testing.T, device *common.CommonDevice, expose runRedAnalysis(report) _, reported := findingByTitlePrefix(report.Findings, "WAN-Exposed Service: SNMP") - assert.Equal(t, exposed, reported, "red-mode SNMP exposure") + 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; 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. +// 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() @@ -332,10 +342,15 @@ func TestForwardsToLoopback_TargetsAndFlags(t *testing.T) { 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: "urltable", Members: []string{"https://example.com/list.txt"}}, - "SNMP_GROUP": {Name: "SNMP_GROUP", Type: aliasTypeNetworkGroup, Members: []string{"LAN_HOST", "LOOP_HOST"}}, - "LAN_GROUP": {Name: "LAN_GROUP", Type: aliasTypeNetworkGroup, Members: []string{"LAN_HOST"}}, + "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 { @@ -372,7 +387,12 @@ func TestForwardsToLoopback_TargetsAndFlags(t *testing.T) { forwards: []common.InboundNATRule{forward("UNSTORED")}, want: true, }, - {name: "URL table alias", forwards: []common.InboundNATRule{forward("URL_TABLE")}}, + {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")}, From c303b32b1ed8b01f77bbdc8d968e85a956f7d07a Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:31:01 -0700 Subject: [PATCH 44/46] docs: keep the pf rewrite sentence beside the forward targets it covers The release scope added to GOTCHAS.md section 8.4 went between the list of forward targets and the sentence saying pf rewrites a forward's destination, so "such a forward" in that sentence read as the forward releases up to 26.1 disable. The sentence now follows the list again. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index b49be480c..2801e8f21 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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`). 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, 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.7. Through 26.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. pf rewrites a forward's destination before the packet is delivered, so such a forward can reach an agent bound to loopback. 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. +- **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, 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.7. Through 26.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. From daa8b0a094b2fcf86bcbfe9a2091bcd9810a8657 Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:57:26 -0700 Subject: [PATCH 45/46] docs(audit): start the forward target reading at OPNsense 26.1.2 The targetHoldsLoopback comment, GOTCHAS.md section 8.4 and three test comments said ForwardRule.php resolves a port forward's target through the alias map Rule.php loadAliasMap builds from 26.7, and only through Util::isAlias up to 26.1. The alias map lookup arrived in 26.1.2. 26.1 and 26.1.1 still use Util::isAlias and disable any other name that is no address or network as an invalid target, (self) and interface names among them. From 26.1.2, the later 26.1 releases included, a forward to (self), lo0 or lanip is resolved, so the over-report the comments described for 26.1 does not occur there. Each now starts the reading at 26.1.2 and ends the earlier one at 26.1.1. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 20 +++++++++---------- .../snmp_forward_interface_target_test.go | 16 +++++++-------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/GOTCHAS.md b/GOTCHAS.md index 2801e8f21..d25dfd974 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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, 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.7. Through 26.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. +- **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, 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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 83359b56f..5b049d910 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -105,11 +105,11 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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.7. 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 +// 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 (aliasNamesRuntimeTable). @@ -131,11 +131,11 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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 hostname with a domain tells nothing and -// does not count. Through 26.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. +// does not count. 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 diff --git a/internal/audit/snmp_forward_interface_target_test.go b/internal/audit/snmp_forward_interface_target_test.go index 423603190..10a23c7fc 100644 --- a/internal/audit/snmp_forward_interface_target_test.go +++ b/internal/audit/snmp_forward_interface_target_test.go @@ -37,14 +37,14 @@ func snmpForwardNetworkRule(network string) string { // 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.7 -// OPNsense accepts an interface's net (lan) or address (lanip) as a forward's +// 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 OPNsense +// 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) { @@ -131,12 +131,12 @@ func TestSNMPAgent_ForwardToInterfaceTarget(t *testing.T) { // 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.7 adds every alias but a port +// 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 OPNsense 26.7 disables a -// forward to it as an invalid target. +// 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() @@ -258,11 +258,11 @@ func TestTargetHoldsLoopback_InterfaceTargets(t *testing.T) { // 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.7 +// 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 +// 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. From be115a60511087165614d466cd4f71d7769fd0df Mon Sep 17 00:00:00 2001 From: intigenesis <313311150+intigenesis@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:05:12 -0700 Subject: [PATCH 46/46] fix(audit): count a host alias holding a hostname as possibly holding loopback targetHoldsLoopback read a host alias whose member is a hostname as holding no address, since the member names no alias and is no address, so an os-net-snmp agent bound only to 127.0.0.1, with a WAN rule passing UDP 161 to any destination beside a WAN forward of UDP 161 to such an alias, or to a network group naming one, was set Local and reported no SNMP exposure. OPNsense accepts a hostname in a host alias (AliasContentField validateHost), and its alias loader queues every entry that is no address, network or range for DNS (iter_addresses in scripts/filter/lib/alias/base.py) and keeps every A and AAAA answer, loopback included. That is the reading the URL table fix adopted for an alias whose addresses OPNsense gets at runtime. aliasNamesRuntimeTable now also returns true when the alias, or an alias it names, is a host alias holding a member that names no alias and that the loader resolves through DNS (resolvedThroughDNS): no address, no first-last range, no "/" and no "!". aliasHoldsFirewallAddress is unchanged, since forwardsToAlias relies on its reading such an alias as holding no address. A target that is itself a hostname still does not count, since OPNsense disables such a forward as an invalid target. Signed-off-by: intigenesis <313311150+intigenesis@users.noreply.github.com> --- GOTCHAS.md | 2 +- internal/audit/red_snmp_listen.go | 47 ++++- .../audit/snmp_forward_hostname_alias_test.go | 192 ++++++++++++++++++ 3 files changed, 230 insertions(+), 11 deletions(-) create mode 100644 internal/audit/snmp_forward_hostname_alias_test.go diff --git a/GOTCHAS.md b/GOTCHAS.md index d25dfd974..6103a5b4d 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -371,7 +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, 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. +- **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/internal/audit/red_snmp_listen.go b/internal/audit/red_snmp_listen.go index 5b049d910..1fcff9053 100644 --- a/internal/audit/red_snmp_listen.go +++ b/internal/audit/red_snmp_listen.go @@ -112,7 +112,8 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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 (aliasNamesRuntimeTable). +// 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 @@ -130,8 +131,9 @@ func forwardCanReachSNMPPort(nat common.InboundNATRule) bool { // 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 hostname with a domain tells nothing and -// does not count. Through 26.1.1 ForwardRule.php maps a target only when an +// 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 @@ -161,12 +163,14 @@ func targetHoldsLoopback(target string, device *common.CommonDevice) bool { } // aliasNamesRuntimeTable reports whether the alias name, or an alias it names -// at any depth, is of a type in runtimeAliasTypes. What such an alias holds -// arrives at runtime, and OPNsense loads every address a fetched list holds, -// loopback addresses included, so it 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. +// 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} @@ -181,7 +185,12 @@ func aliasNamesRuntimeTable(objects common.NamedObjects, name string) bool { } for _, member := range object.Members { - if _, defined := objects[member]; defined && !seen[member] { + _, 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) } @@ -191,6 +200,24 @@ func aliasNamesRuntimeTable(objects common.NamedObjects, name string) bool { 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. 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) + }) + } +}