analysis

package
v1.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 22, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package analysis provides canonical types for security analysis findings and shared analysis functions (detection, statistics, rule comparison) used across the audit, compliance, converter, and processor packages.

Index

Constants

View Source
const ServiceNameSNMP = "SNMP Daemon"

ServiceNameSNMP is the display name for the SNMP service in statistics.

Variables

This section is empty.

Functions

func ComputeAnalysis

func ComputeAnalysis(cfg *common.CommonDevice) *common.Analysis

ComputeAnalysis performs lightweight analysis of the device configuration and returns an Analysis suitable for serialization in JSON/YAML exports. The returned Analysis is derived purely from cfg with no side effects. A nil cfg returns an empty Analysis.

func ComputeConfigComplexity

func ComputeConfigComplexity(stats *common.Statistics) int

ComputeConfigComplexity returns a normalized complexity score for the configuration based on weighted counts of various configuration elements. Returns 0 when stats is nil.

func ComputeSecurityScore

func ComputeSecurityScore(cfg *common.CommonDevice, stats *common.Statistics) int

ComputeSecurityScore returns a security score based on detected security features, firewall rules, HTTPS Web GUI usage, SSH group configuration, and IDS/IPS enablement. The score is capped at MaxSecurityScore. Returns 0 when cfg or stats is nil.

func ComputeStatistics

func ComputeStatistics(cfg *common.CommonDevice) *common.Statistics

ComputeStatistics analyzes a device configuration and returns aggregated statistics using the common.Statistics type suitable for serialization in JSON/YAML exports. A nil cfg returns an initialized but empty Statistics.

func ComputeTotalConfigItems

func ComputeTotalConfigItems(stats *common.Statistics) int

ComputeTotalConfigItems calculates the total number of configuration items by summing interfaces, rules, users, groups, services, gateways, sysctl, DHCP, load balancer, VLANs, bridges, certificates, and CAs.

func DetectConsistency

func DetectConsistency(cfg *common.CommonDevice) []common.ConsistencyFinding

DetectConsistency detects configuration consistency issues. Returns nil when no consistency issues are found.

func DetectDeadRules

func DetectDeadRules(cfg *common.CommonDevice) []common.DeadRuleFinding

DetectDeadRules detects unreachable and duplicate firewall rules. It is a compatibility view *derived* from the shared shadow-detection core (ADR-0004, R16): the unreachable-plus-duplicate subset of DetectShadowedRules, re-projected into the legacy DeadRuleFinding shape and legacy per-interface, raw-list-position ordering. Each finding carries a Kind field ("unreachable" or "duplicate") for structured classification. Returns nil when no dead rules are found.

The shadow core groups rules by (interface, direction) with floating-first reordering (internal/analysis/precedence.go), but the pre-existing DetectDeadRules output — pinned byte-for-byte by this file's test suite — buckets by interface name only and orders by raw per-interface list position, with no notion of direction, quick, or floating rules. normalizeForDeadRuleView collapses the shadow core's grouping back down to that legacy shape before calling DetectShadowedRules; the flatten loop below then re-projects the filtered result using the *original* rules' interface bindings and positions so output ordering is unchanged.

func DetectPerformanceIssues

func DetectPerformanceIssues(cfg *common.CommonDevice) []common.PerformanceFinding

DetectPerformanceIssues detects performance configuration issues. Returns nil when no performance issues are found.

func DetectSecurityIssues

func DetectSecurityIssues(cfg *common.CommonDevice) []common.SecurityFinding

DetectSecurityIssues detects security configuration issues. Returns nil when no security issues are found.

func DetectShadowedRules added in v1.7.0

func DetectShadowedRules(cfg *common.CommonDevice) []common.ShadowedRuleFinding

DetectShadowedRules reports firewall rules — or subsets of their traffic — that never take effect because a higher-precedence rule under pf evaluation semantics (quick first-match, non-quick last-match, floating device-wide) already covers them (R5-R7, R9, R12-R15).

DetectShadowedRules is a pure function of cfg: no shared state, mirroring every other Detect* in this package. Returns nil for a nil cfg or fewer than two firewall rules.

func DetectUnusedInterfaces

func DetectUnusedInterfaces(cfg *common.CommonDevice) []common.UnusedInterfaceFinding

DetectUnusedInterfaces detects enabled interfaces not referenced by firewall rules, DHCP scopes, DNS resolvers (Unbound/DNSMasq), OpenVPN instances, WireGuard, or the load balancer. DNS, WireGuard, and load balancer currently assume "lan" binding when enabled — this is a known limitation when these services are bound to non-LAN interfaces. Returns nil when no unused interfaces are found.

func DetectUnusedObjects added in v1.7.0

func DetectUnusedObjects(cfg *common.CommonDevice) []common.UnusedObjectFinding

DetectUnusedObjects reports named objects (aliases) that are defined in cfg but not referenced by any policy (issue #203). It is framed as graph reachability from policy roots: nodes are cfg.NamedObjects entries, an edge runs from an object to each member that names another object, and roots are every live ObjectRef on a Tracked policy surface (the Surface Audit / KTD-3 root sites). Any object not reachable from a root is unused.

DetectUnusedObjects is a pure function of cfg: no shared state, mirroring every other Detect* in this package. Returns nil for a nil cfg or an empty NamedObjects registry. Output is sorted by object name for deterministic rendering (GOTCHAS §3.1).

func FindDHCPScope

func FindDHCPScope(scopes []common.DHCPScope, ifaceName string) *common.DHCPScope

FindDHCPScope returns the DHCP scope for the given interface, or nil if not found.

func FindInterface

func FindInterface(interfaces []common.Interface, name string) *common.Interface

FindInterface returns the interface with the given name, or nil if not found.

func IsValidConfidence added in v1.7.0

func IsValidConfidence(c Confidence) bool

IsValidConfidence checks whether the given confidence is a recognized value.

func IsValidSeverity

func IsValidSeverity(s Severity) bool

IsValidSeverity checks whether the given severity is a recognized value.

func IsWANInterfaceName added in v1.7.0

func IsWANInterfaceName(name string) bool

IsWANInterfaceName reports whether name is a WAN-style interface name, using case-insensitive "wan" prefix matching (e.g. "wan", "WAN", "wan2").

This is the single canonical WAN-interface-name predicate in the codebase. internal/plugins/sans, internal/plugins/firewall, and the rest of internal/analysis all route through this function instead of reimplementing the check — see GOTCHAS.md and the reachability consolidation history for why the two previously-divergent exact-match sites in this package were bugs, not just duplication.

Known limitation: detection is name-prefix-only. A secondary internet uplink left with its default logical name (e.g. "opt1") rather than renamed to a "wan"-prefixed name is classified LAN-only, so a service exposed on it can be under-reported. Closing this requires consulting gateway/default-route signals (common.Gateway.Interface) and is tracked as follow-up work, not addressed by this consolidation.

func RedactServiceDetails added in v1.6.0

func RedactServiceDetails(details []common.ServiceStatistics) ([]common.ServiceStatistics, bool)

RedactServiceDetails returns a copy of details whose sensitive SNMP detail values are replaced with the redaction marker, plus a flag indicating whether any redaction was applied.

The input is never mutated. When at least one SNMP entry carries a non-empty sensitive key the slice is cloned and only the affected per-element Details maps are cloned (clone-on-write); the second return is true. When nothing matches, the input slice is returned unchanged and the second return is false, letting non-mutating callers (e.g. the converter's memoized Statistics) skip allocating a new container.

Every matching SNMP entry is redacted — not just the first — and every key in snmpSensitiveDetailKeys is redacted on each match. analysis.ComputeStatistics emits a single SNMP entry with a single sensitive key today, but a future schema change could surface multiple; leaving any in cleartext would be a security regression.

func RulesEquivalent

func RulesEquivalent(a, b common.FirewallRule) bool

RulesEquivalent checks if two firewall rules are functionally equivalent. Interface order is normalized before comparison so that ["wan","lan"] and ["lan","wan"] are treated as equivalent. Metadata fields (Description, etc.) are intentionally excluded from comparison. A disabled rule is not equivalent to an enabled rule.

Types

type Confidence added in v1.7.0

type Confidence string

Confidence represents how confident the shared detection engine is that an Observation reflects a real, actionable condition. Confidence never gates whether an observation is surfaced — every match is reported regardless of its confidence label; confidence is presentation metadata only.

const (
	// ConfidenceHigh indicates a deterministic, low-false-positive detection.
	ConfidenceHigh Confidence = "high"
	// ConfidenceMedium indicates a detection with plausible false positives.
	ConfidenceMedium Confidence = "medium"
	// ConfidenceLow indicates a heuristic detection with a higher false-positive rate.
	ConfidenceLow Confidence = "low"
)

Confidence level constants define the three-level confidence scale shared by observations, blue hygiene findings, and red findings.

func ValidConfidences added in v1.7.0

func ValidConfidences() []Confidence

ValidConfidences returns a fresh copy of all valid confidence values. Returns a new slice each call to prevent callers from mutating shared state.

func (Confidence) String added in v1.7.0

func (c Confidence) String() string

String returns the string representation of the confidence level.

type Coverage added in v1.7.0

type Coverage int

Coverage classifies how completely an earlier firewall rule's match set covers a later rule's match set, on a single dimension or for a whole rule pair. See coverage for the combining rules across dimensions.

const (
	// CoverNone indicates the earlier rule does not overlap the later rule
	// at all on this dimension (or, once combined, on the whole rule).
	CoverNone Coverage = iota
	// CoverPartial indicates the earlier rule overlaps some, but not all,
	// of the later rule's match set.
	CoverPartial
	// CoverFull indicates the earlier rule's match set fully contains the
	// later rule's match set.
	CoverFull
	// CoverIndeterminate indicates negation makes the overlap relationship
	// impossible to determine with confidence; callers must not report a
	// finding for this result (R10).
	CoverIndeterminate
)

Recognized Coverage values.

func (Coverage) String added in v1.7.0

func (c Coverage) String() string

String returns a human-readable name for c, used in test failure output and any future debug logging.

type Finding

type Finding struct {
	// Type categorizes the finding (e.g., "security", "performance", "compliance").
	Type string `json:"type"`
	// Severity indicates the severity level of the finding.
	Severity string `json:"severity,omitempty"`
	// Title is a brief description of the finding.
	Title string `json:"title"`
	// Description provides detailed information about the finding.
	Description string `json:"description"`
	// Recommendation suggests how to address the finding.
	Recommendation string `json:"recommendation"`
	// Component identifies the configuration component involved.
	Component string `json:"component"`
	// Reference provides additional information or documentation links.
	Reference string `json:"reference"`

	// Generic references and metadata
	// References contains related standard or control identifiers.
	References []string `json:"references,omitempty"`
	// Tags contains classification labels for the finding.
	Tags []string `json:"tags,omitempty"`
	// Metadata contains arbitrary key-value pairs for additional context.
	Metadata map[string]string `json:"metadata,omitempty"`
}

Finding represents a canonical analysis finding that unifies the common fields across audit, compliance, and processor findings.

JSON tag note: Recommendation, Component, and Reference intentionally lack omitempty to match compliance.Finding conventions. The subsequent migration phase that replaces processor.Finding with analysis.Finding should verify that downstream JSON consumers can handle the presence of empty-string fields for these three keys, since processor.Finding currently uses omitempty on them.

type IndexedRule

type IndexedRule struct {
	// Index is the position of the rule in the original flat rule list.
	Index int
	// Rule is the firewall rule at this position.
	Rule common.FirewallRule
}

IndexedRule pairs a firewall rule with its original index in the flat rule list.

type Observation added in v1.7.0

type Observation struct {
	// Severity is the shared severity scale value (critical..info), aligned
	// with the compliance-plugin severity vocabulary.
	Severity Severity `json:"severity"`
	// Confidence labels how certain the detection is; never used to drop an
	// observation.
	Confidence Confidence `json:"confidence"`
	// Reachability tags where this observation is reachable from: WAN, LAN,
	// or local only.
	Reachability Reachability `json:"reachability"`
	// Component identifies the originating configuration element (e.g.
	// "filter.rule[3]", "system.webgui.protocol").
	Component string `json:"component"`
	// Evidence carries a human-readable pointer to the specific config value
	// that triggered the observation.
	Evidence string `json:"evidence,omitempty"`
	// Title is a brief description of the observation.
	Title string `json:"title"`
	// Description provides detailed information about the observation.
	Description string `json:"description"`
	// Recommendation suggests how to address the observation.
	Recommendation string `json:"recommendation"`
}

Observation is a neutral, mode-agnostic detection produced by the shared detection engine (ScanObservations). Blue and red audit modes are presentation lenses over the same observations, so detection logic lives here exactly once and the two modes cannot disagree about the underlying facts. See docs/plans/2026-07-17-001-feat-audit-blue-red-analysis-plan.md.

func ScanObservations added in v1.7.0

func ScanObservations(cfg *common.CommonDevice) []Observation

ScanObservations runs the shared detection engine over cfg and returns a flat, neutral list of Observations: the existing DetectSecurityIssues detections wrapped with reachability and confidence, plus additive framework-free hygiene detectors for categories no compliance plugin owns at per-instance granularity (insecure management protocols, weak crypto defaults, any-to-any rules, disabled logging).

ScanObservations does not modify DetectSecurityIssues or ComputeAnalysis; both remain unchanged for their existing callers in internal/converter and internal/processor (KTD3, R4). Returns nil for a nil cfg.

func (Observation) ToFinding added in v1.7.0

func (o Observation) ToFinding() Finding

ToFinding maps the observation into the canonical analysis.Finding shape consumed by blue-mode hygiene rendering. analysis.Finding has no dedicated confidence/reachability/evidence fields, so those three axes are carried in Metadata rather than dropped.

type PrecedencePair added in v1.7.0

type PrecedencePair struct {
	// Interface is the interface name the evaluation group was built for.
	Interface string
	// Direction is the direction bucket the group was evaluated under
	// (DirectionIn or DirectionOut; a DirectionAny rule joins both buckets
	// and so may appear in a PrecedencePair under either value).
	Direction common.FirewallDirection
	// Winner is the rule that wins the shared traffic under pf evaluation
	// semantics.
	Winner IndexedRule
	// Loser is the rule that is shadowed on the overlap — the rule a shadow
	// finding should be reported against.
	Loser IndexedRule
	// Extent is how much of Loser's match set Winner covers: CoverFull when
	// Loser is shadowed in its entirety, CoverPartial when only the
	// overlapping subset is shadowed. Never CoverNone or CoverIndeterminate;
	// pairs with those coverage results produce no PrecedencePair.
	Extent Coverage
	// AliasBlocked mirrors the coverage() aliasBlocked signal computed for
	// this pair, so consumers needing the R8 advisory path do not have to
	// re-run coverage() themselves.
	AliasBlocked bool
}

PrecedencePair describes one resolved overlapping pair of firewall rules within a single (interface, direction) pf evaluation group: which rule wins the shared traffic, which rule is shadowed on it, and how much of the loser's match set the winner covers.

Quick and non-quick are mirror images (ADR-0005, KTD-5). Under quick (first-match) semantics the earlier-positioned rule in the group wins outright when it covers the later rule, so the later rule is the loser. Under non-quick (last-match) semantics the later-positioned rule wins the overlap, so the earlier rule is the loser. Winner and Loser therefore do not correlate with rule-list position in a fixed direction — callers must not assume Loser.Index is greater than Winner.Index.

func ResolvePrecedence added in v1.7.0

func ResolvePrecedence(cfg *common.CommonDevice) []PrecedencePair

ResolvePrecedence groups cfg's firewall rules into pf evaluation-order groups — by (interface, direction), with unscoped floating rules (Floating && len(Interfaces)==0) joining every interface group ahead of interface-bound rules — and resolves every overlapping pair within each group into its effective PrecedencePair per pf quick (first-match) / non-quick (last-match) semantics (ADR-0005, KTD-5). Overlap candidacy is decided by the U4 coverage predicate; pairs whose coverage is CoverNone or CoverIndeterminate produce no result.

ResolvePrecedence is a pure function of cfg: no shared state, and deterministic output order (sorted interface name, then direction bucket, then group position). Returns nil for a nil cfg or fewer than two firewall rules.

type Reachability added in v1.7.0

type Reachability string

Reachability describes where a firewall rule, interface, or NAT rule can be reached from: the public internet (WAN), only from local/internal networks (LAN), or nowhere on any network (Local — e.g. a disabled interface, or a NAT rule with no matching enabled pass rule).

const (
	// WANReachable indicates the element is reachable from the WAN (internet).
	WANReachable Reachability = "wan"
	// LANOnly indicates the element is reachable only from LAN/internal networks.
	LANOnly Reachability = "lan"
	// Local indicates the element is not reachable from any network — for
	// example a disabled interface, or a NAT rule with no matching enabled
	// pass rule.
	Local Reachability = "local"
)

func InboundNATRuleReachability added in v1.7.0

func InboundNATRuleReachability(
	nat common.InboundNATRule,
	ifaces []common.Interface,
	passRules []common.FirewallRule,
) Reachability

InboundNATRuleReachability reports whether an inbound (port-forward) NAT rule is WAN-reachable.

A NAT rule is WAN-reachable only when it is enabled, applies to a WAN interface, AND at least one enabled pass rule also applies to a WAN interface. NAT presence alone — with no matching enabled pass rule — is never WAN-reachable: OPNsense and pfSense both require an explicit pass rule (or an auto-added "filter rule association") to actually allow the forwarded traffic through the firewall; a port-forward with no corresponding pass rule is inert.

func InterfaceReachability added in v1.7.0

func InterfaceReachability(iface common.Interface) Reachability

InterfaceReachability classifies a single interface as WAN-reachable, LAN-only, or local, based on its administrative state and name.

func RuleReachability added in v1.7.0

func RuleReachability(rule common.FirewallRule, ifaces []common.Interface) Reachability

RuleReachability classifies a firewall rule's reachability using its bound interfaces and IP protocol.

A rule counts as WAN-reachable when it applies to any WAN interface. This includes:

  • Interface-scoped floating rules, which — like ordinary rules — are scoped to exactly the interfaces in rule.Interfaces; the Floating flag does not by itself widen a rule's reach beyond its interface list.
  • Unscoped floating rules (Floating == true with an empty rule.Interfaces), which apply to every interface and are therefore WAN-reachable whenever any live WAN interface exists on the device.
  • IPv6-only WAN interfaces, matched the same way as any other WAN interface: the classification below is purely name-prefix based via IsWANInterfaceName and does not branch on rule.IPProtocol or inspect the interface's IPv6Address, so a wan-prefixed interface serving only IPv6 is matched by its name alone — a misconfigured/unassigned address must not mask a real exposure.

Enabled-state handling is deliberately asymmetric between the two binding styles. The unscoped-floating path resolves against the actual interface list via InterfaceReachability, which treats a disabled interface as Local — a device-wide rule cannot reach a WAN that is administratively down, and nothing in rule.Interfaces tells us which interfaces exist. The interface-scoped path, by contrast, trusts the operator's explicit binding: a rule bound by name to "wan" is classified as governing WAN traffic by intent, independent of the interface's current admin state (a disabled interface merely makes the rule inert, which is a separate concern from where the rule is scoped). It also keeps classification working for rules that reference an interface name not present in the passed-in ifaces slice.

func (Reachability) String added in v1.7.0

func (r Reachability) String() string

String returns the string representation of the reachability tag.

type Severity

type Severity string

Severity represents the severity levels for findings.

const (
	// SeverityCritical indicates a critical severity finding.
	SeverityCritical Severity = "critical"
	// SeverityHigh indicates a high severity finding.
	SeverityHigh Severity = "high"
	// SeverityMedium indicates a medium severity finding.
	SeverityMedium Severity = "medium"
	// SeverityLow indicates a low severity finding.
	SeverityLow Severity = "low"
	// SeverityInfo indicates an informational finding.
	SeverityInfo Severity = "info"
)

Severity level constants define the standard severity tiers for security findings.

func ValidSeverities

func ValidSeverities() []Severity

ValidSeverities returns a fresh copy of all valid severity values. Returns a new slice each call to prevent callers from mutating shared state.

func (Severity) String

func (s Severity) String() string

String returns the string representation of the severity.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL