// Package stig provides a compliance plugin for STIG security controls. package stig import ( "slices" "github.com/EvilBit-Labs/opnDossier/internal/analysis" "github.com/EvilBit-Labs/opnDossier/internal/compliance" "github.com/EvilBit-Labs/opnDossier/internal/constants" common "github.com/EvilBit-Labs/opnDossier/pkg/model" ) // STIG compliance thresholds used to evaluate service hardening controls. const ( // MaxDHCPInterfaces represents the maximum number of DHCP interfaces before flagging as unnecessary. MaxDHCPInterfaces = 2 ) // Plugin implements the compliance.Plugin interface for STIG plugin. type Plugin struct { controls []compliance.Control // severityByID maps control ID -> severity for O(1) lookups during finding // construction (previously O(n) linear scan over controls). severityByID map[string]string } // NewPlugin creates a new STIG compliance plugin. func NewPlugin() *Plugin { p := &Plugin{ controls: []compliance.Control{ { ID: "V-206694", Title: "Firewall must deny network communications traffic by default", Description: "Firewall must implement a default deny policy for all traffic", Category: "Default Deny Policy", Severity: "high", Rationale: "A default deny policy ensures that only explicitly allowed traffic is permitted", Remediation: "Configure firewall to deny all traffic by default and only allow necessary traffic through explicit rules", Tags: []string{"default-deny", "firewall-rules", "security-posture"}, }, { ID: "V-206674", Title: "Firewall must use packet headers and attributes for filtering", Description: "Firewall must use specific packet headers and attributes for filtering", Category: "Packet Filtering", Severity: "high", Rationale: "Specific packet filtering ensures precise control over network traffic", Remediation: "Review and tighten firewall rules to use specific source/destination addresses and ports", Tags: []string{"packet-filtering", "access-control", "network-segmentation"}, }, { ID: "V-206690", Title: "Firewall must disable unnecessary network services", Description: "Firewall must have unnecessary network services disabled", Category: "Service Hardening", Severity: "medium", Rationale: "Disabling unnecessary services reduces attack surface", Remediation: "Disable or remove unnecessary network services and functions", Tags: []string{"service-hardening", "unnecessary-services", "security-hardening"}, }, { ID: "V-206682", Title: "Firewall must generate comprehensive traffic logs", Description: "Firewall must generate comprehensive logs for all traffic", Category: "Logging", Severity: "medium", Rationale: "Comprehensive logging enables security analysis and incident response", Remediation: "Enable comprehensive logging for all firewall rules and ensure logs capture success/failure outcomes", Tags: []string{"logging", "audit-trail", "security-monitoring"}, }, { ID: "V-206701", Title: "Firewall must employ DoS attack prevention filters", Description: "Firewall must implement rate limiting or connection throttling to mitigate denial-of-service attacks", Category: "DoS Prevention", Severity: "high", Rationale: "DoS prevention filters reduce the impact of volumetric attacks on protected services", Remediation: "Configure connection rate limiting (MaxSrcConnRate) and maximum connection limits (MaxSrcConn) on pass rules", Tags: []string{"dos-prevention", "rate-limiting", "availability"}, }, { ID: "V-206680", Title: "Firewall must log network location information", Description: "Firewall must capture source and destination interface information in log entries", Category: "Logging", Severity: "medium", Rationale: "Network location data in logs enables accurate incident response and traffic attribution", Remediation: "Configure syslog to include interface and zone information in firewall log entries", Tags: []string{"logging", "network-location", "audit-trail"}, }, { ID: "V-206679", Title: "Firewall must log event timestamps", Description: "Firewall must include accurate timestamps in all log entries for forensic timeline reconstruction", Category: "Logging", Severity: "medium", Rationale: "Accurate timestamps are essential for correlating events across multiple systems during incident investigation", Remediation: "Enable NTP synchronization and ensure syslog includes timestamps in all forwarded messages", Tags: []string{"logging", "timestamps", "ntp", "forensics"}, }, { ID: "V-206678", Title: "Firewall must log event type information", Description: "Firewall must categorize log entries by event type for efficient filtering and analysis", Category: "Logging", Severity: "medium", Rationale: "Event type classification enables automated log analysis and priority-based alerting", Remediation: "Configure syslog to include facility and severity information in all forwarded log messages", Tags: []string{"logging", "event-type", "categorization"}, }, { ID: "V-206681", Title: "Firewall must log source information for events", Description: "Firewall must capture source IP addresses and identifiers in all security-relevant log entries", Category: "Logging", Severity: "medium", Rationale: "Source attribution in logs is critical for identifying threat actors and compromised systems", Remediation: "Enable filter logging with source/destination information in syslog configuration", Tags: []string{"logging", "source-tracking", "attribution"}, }, { ID: "V-206711", Title: "Firewall must alert on DoS incidents", Description: "Firewall must generate alerts when denial-of-service conditions are detected", Category: "DoS Prevention", Severity: "medium", Rationale: "Timely DoS alerting enables rapid response to mitigate service disruption", Remediation: "Configure IDS/IPS alerting for DoS patterns and integrate with SIEM for automated notification", Tags: []string{"dos-prevention", "alerting", "incident-response"}, }, }, } p.severityByID = make(map[string]string, len(p.controls)) for _, c := range p.controls { p.severityByID[c.ID] = c.Severity } return p } // Name returns the plugin name. func (sp *Plugin) Name() string { return "stig" } // Version returns the plugin version. func (sp *Plugin) Version() string { return "1.0.0" } // Description returns the plugin description. func (sp *Plugin) Description() string { return "STIG (Security Technical Implementation Guide) compliance checks for firewall security" } // RunChecks performs STIG compliance checks in a single traversal. Returns // (findings, evaluated, err). All 10 STIG controls can be evaluated from // config.xml data, so every control ID is appended to evaluated regardless of // pass/fail — this matches the semantics of the previous EvaluatedControlIDs // implementation that unconditionally returned all IDs. // // err is currently always nil; reserved for future unrecoverable conditions. // //nolint:gocritic // nonamedreturns enforced project-wide; docstring clarifies return shape. func (sp *Plugin) RunChecks( device *common.CommonDevice, ) ([]compliance.Finding, []string, error) { findings := make([]compliance.Finding, 0, len(sp.controls)) // Pre-build evaluated with every control ID — STIG evaluates them all. evaluated := make([]string, 0, len(sp.controls)) for _, c := range sp.controls { evaluated = append(evaluated, c.ID) } // V-206694: Default deny policy if !sp.hasDefaultDenyPolicy(device) { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity("V-206694"), Title: "Missing Default Deny Policy", Description: "Firewall does not implement a default deny policy for all traffic", Recommendation: "Configure firewall to deny all traffic by default and only allow necessary traffic through explicit rules", Component: "firewall-rules", Reference: "STIG V-206694", References: []string{"V-206694"}, Tags: []string{"default-deny", "firewall-rules", "security-posture", "stig"}, }) } // V-206674: Specific packet filtering if sp.hasOverlyPermissiveRules(device) { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity("V-206674"), Title: "Overly Permissive Firewall Rules", Description: "Firewall contains rules that are too broad or permissive", Recommendation: "Review and tighten firewall rules to use specific source/destination addresses and ports", Component: "firewall-rules", Reference: "STIG V-206674", References: []string{"V-206674"}, Tags: []string{"packet-filtering", "access-control", "network-segmentation", "stig"}, }) } // V-206690: Unnecessary services if sp.hasUnnecessaryServices(device) { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity("V-206690"), Title: "Unnecessary Network Services Enabled", Description: "Firewall has unnecessary network services enabled", Recommendation: "Disable or remove unnecessary network services and functions", Component: "service-config", Reference: "STIG V-206690", References: []string{"V-206690"}, Tags: []string{"service-hardening", "unnecessary-services", "security-hardening", "stig"}, }) } // V-206682: Comprehensive logging if !sp.hasComprehensiveLogging(device) { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity("V-206682"), Title: "Insufficient Firewall Logging", Description: "Firewall does not generate comprehensive logs for all traffic", Recommendation: "Enable comprehensive logging for all firewall rules and ensure logs capture success/failure outcomes", Component: "logging-config", Reference: "STIG V-206682", References: []string{"V-206682"}, Tags: []string{"logging", "audit-trail", "security-monitoring", "stig"}, }) } // V-206701: DoS prevention filters (rate limiting on rules) if !sp.hasDoSPreventionFilters(device) { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity("V-206701"), Title: "Missing DoS Prevention Filters", Description: "Firewall does not implement rate limiting or connection throttling on pass rules", Recommendation: "Configure MaxSrcConnRate and MaxSrcConn on critical pass rules to mitigate DoS attacks", Component: "firewall-rules", Reference: "STIG V-206701", References: []string{"V-206701"}, Tags: []string{"dos-prevention", "rate-limiting", "availability", "stig"}, }) } // V-206680 through V-206681 and V-206678/V-206679: Logging detail controls // These require syslog to be properly configured — checked via syslog enablement if !sp.hasSyslogEnabled(device) { for _, ctrl := range []struct { id string title string desc string }{ {"V-206680", "Network Location Logging Not Configured", "Firewall does not log network location (interface/zone) information"}, {"V-206679", "Event Timestamp Logging Not Configured", "Firewall does not log event timestamps via NTP-synchronized syslog"}, {"V-206678", "Event Type Logging Not Configured", "Firewall does not log event type (facility/severity) information"}, {"V-206681", "Source Information Logging Not Configured", "Firewall does not log source IP/identifier information"}, } { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity(ctrl.id), Title: ctrl.title, Description: ctrl.desc, Recommendation: "Enable syslog with system, auth, and filter logging to capture comprehensive event data", Component: "logging-config", Reference: "STIG " + ctrl.id, References: []string{ctrl.id}, Tags: []string{"logging", "syslog", "audit-trail", "stig"}, }) } } // V-206711: DoS incident alerting — requires IDS/IPS with alerting, advisory // We can partially check: is IDS enabled? if !sp.hasDoSAlerting(device) { findings = append(findings, compliance.Finding{ Type: constants.FindingTypeCompliance, Severity: sp.controlSeverity("V-206711"), Title: "DoS Incident Alerting Not Configured", Description: "Firewall does not have IDS/IPS-based DoS alerting configured", Recommendation: "Enable Suricata IDS/IPS with DoS detection rules and integrate with SIEM for alerting", Component: "ids-config", Reference: "STIG V-206711", References: []string{"V-206711"}, Tags: []string{"dos-prevention", "alerting", "ids", "stig"}, }) } return findings, evaluated, nil } // GetControls returns all STIG controls. The returned slice is a deep copy to // prevent callers from mutating the plugin's internal state, including nested // reference types (References, Tags, Metadata). func (sp *Plugin) GetControls() []compliance.Control { return compliance.CloneControls(sp.controls) } // GetControlByID returns a specific control by ID. func (sp *Plugin) GetControlByID(id string) (*compliance.Control, error) { for _, control := range sp.controls { if control.ID == id { return &control, nil } } return nil, compliance.ErrControlNotFound } // ValidateConfiguration validates the plugin configuration. func (sp *Plugin) ValidateConfiguration() error { if len(sp.controls) == 0 { return compliance.ErrNoControlsDefined } return nil } // controlSeverity returns the severity for a control ID from the pre-built // severityByID map populated in NewPlugin. Returns "" when the ID is unknown. // O(1) — replaces the historical O(n) linear scan over sp.controls. func (sp *Plugin) controlSeverity(id string) string { return sp.severityByID[id] } // hasDefaultDenyPolicy checks whether the device's firewall implements a default deny // posture by verifying explicit block or reject rules exist and that no overly broad // any-to-any allow rules override the deny policy. func (sp *Plugin) hasDefaultDenyPolicy(device *common.CommonDevice) bool { // Check for default deny policy configuration rules := device.FirewallRules // If no rules exist, assume default deny (conservative approach) if len(rules) == 0 { return true } // Look for explicit deny rules at the end of rule sets hasExplicitDeny := false for _, rule := range rules { // Look for rules that explicitly deny traffic if rule.Type == common.RuleTypeBlock || rule.Type == common.RuleTypeReject { hasExplicitDeny = true break } } // Check if there are any "any/any" allow rules that would override default deny hasAnyAnyAllow := false for _, rule := range rules { // A disabled rule overrides nothing, so it cannot defeat a default-deny // policy. Now that an omitted address counts as a wildcard, skipping // them keeps a disabled rule with no endpoints set from reading as // any/any. if !rule.Disabled && rule.Type == common.RuleTypePass { if analysis.IsAnyEndpoint(rule.Source) && analysis.IsAnyEndpoint(rule.Destination) { hasAnyAnyAllow = true break } } } // Conservative approach: if there are explicit deny rules and no overly broad allow rules, // consider it as having a default deny policy return hasExplicitDeny && !hasAnyAnyAllow } // isBroadEndpoint reports whether an endpoint still matches a broad swathe of // hosts once its inverted-match flag is taken into account. // // broadNetworks holds the wildcards themselves ("any", 0.0.0.0/0, ::/0) // alongside genuinely large but bounded ranges. Those two halves invert // differently: a negated 0.0.0.0/0 or ::/0 matches nothing and is not broad, // while a negated bounded range is everything outside it and stays broad. A // negated any still matches every host, and the caller has already counted it // through analysis.IsAnyEndpoint. Testing membership on the raw address alone // would keep reporting a rule that matches no traffic as overly permissive. func isBroadEndpoint(ep common.RuleEndpoint, addr string) bool { if ep.Negated && analysis.IsAnyAddress(addr) { return false } return slices.Contains(broadNetworks, addr) } // hasOverlyPermissiveRules checks whether the device contains firewall pass rules with // overly broad source or destination addresses, wide network ranges, or missing port // restrictions that violate STIG packet-filtering requirements. // // Disabled rules are skipped: they forward nothing, so they cannot be overly // permissive. That matters now an omitted address counts as a wildcard, which // makes a disabled rule with no endpoints set look maximally broad. func (sp *Plugin) hasOverlyPermissiveRules(device *common.CommonDevice) bool { // Check for overly permissive firewall rules rules := device.FirewallRules for _, rule := range rules { if rule.Disabled || rule.Type != common.RuleTypePass { continue } srcTarget := rule.Source.Address dstTarget := rule.Destination.Address srcAny := analysis.IsAnyEndpoint(rule.Source) dstAny := analysis.IsAnyEndpoint(rule.Destination) srcBroad := srcAny || isBroadEndpoint(rule.Source, srcTarget) dstBroad := dstAny || isBroadEndpoint(rule.Destination, dstTarget) // Check for "any/any" rules (most permissive) if srcAny && dstAny { return true } // Check for broad network ranges (e.g., entire subnets without specific restrictions) if srcBroad && dstBroad { return true } // Check for broad rules without specific port restrictions (TCP/UDP or unspecified protocol) if srcBroad && dstBroad && (rule.Protocol == "" || rule.Protocol == "tcp" || rule.Protocol == "udp" || rule.Protocol == "tcp/udp") && analysis.IsAnyPort(rule.Destination.Port) { return true } } return false } // hasUnnecessaryServices checks whether the device has network services enabled that // increase the attack surface: an enabled SNMP agent, more than two DHCP scopes, or // load balancer configurations. func (sp *Plugin) hasUnnecessaryServices(device *common.CommonDevice) bool { // Check for unnecessary network services // Check SNMP configuration - SNMP with community strings can be a security risk if device.SNMP.ROCommunity != "" { // SNMP is enabled with community string - could be unnecessary return true } // Check for DHCP server on interfaces that might not need it dhcpCount := len(device.DHCP) if dhcpCount > 0 { // Multiple DHCP interfaces might indicate unnecessary services if dhcpCount > MaxDHCPInterfaces { return true } } // Check for load balancer services if len(device.LoadBalancer.MonitorTypes) > 0 { // Load balancer is configured - check if it's necessary // This is a conservative check - load balancers can be necessary // but also represent additional attack surface return true } // Check for RRD (Round Robin Database) - usually necessary for monitoring // but could be disabled in high-security environments // RRD is generally necessary for monitoring, so we won't flag it as unnecessary return false } // LoggingStatus represents the result of logging configuration analysis. type LoggingStatus int // LoggingStatus values classify the device's logging posture for STIG compliance evaluation. const ( // LoggingStatusNotConfigured indicates no logging configuration is detected. LoggingStatusNotConfigured LoggingStatus = iota // LoggingStatusComprehensive indicates comprehensive logging is properly configured. LoggingStatusComprehensive // LoggingStatusPartial indicates logging is partially configured but missing critical components. LoggingStatusPartial // LoggingStatusUnableToDetermine indicates logging status cannot be determined due to model limitations. LoggingStatusUnableToDetermine ) // hasComprehensiveLogging checks whether the device is configured with comprehensive // logging by delegating to analyzeLoggingConfiguration and requiring full coverage. func (sp *Plugin) hasComprehensiveLogging(device *common.CommonDevice) bool { status := sp.analyzeLoggingConfiguration(device) return status == LoggingStatusComprehensive } // analyzeLoggingConfiguration provides detailed analysis of logging configuration // and returns a LoggingStatus indicating the level of logging coverage. func (sp *Plugin) analyzeLoggingConfiguration(device *common.CommonDevice) LoggingStatus { // Check syslog configuration if device.Syslog.Enabled { // Syslog is enabled - good // Check if it's configured to log important events if device.Syslog.SystemLogging && device.Syslog.AuthLogging { // System and auth logging are enabled return LoggingStatusComprehensive } // Syslog enabled but missing critical logging categories return LoggingStatusPartial } // Check for firewall rule logging rules := device.FirewallRules if len(rules) > 0 { // CRITICAL ASSUMPTION: When firewall rules exist and syslog is not explicitly // configured, we cannot definitively determine if logging is enabled. // The current model doesn't expose individual rule logging settings, // so we must return "unable to determine" rather than making assumptions // about logging being enabled or disabled. // // This assumption affects compliance assessment accuracy and should be // addressed by enhancing the model to expose rule-level logging configuration. return LoggingStatusUnableToDetermine } // Check for IDS/IPS logging if available if device.IDS != nil { // IDS is configured - this provides additional logging capabilities // but without syslog, we cannot determine if logging is actually enabled return LoggingStatusUnableToDetermine } // No logging configuration detected return LoggingStatusNotConfigured } // hasDoSPreventionFilters checks whether any pass rules have rate-limiting or // connection-throttling parameters configured (MaxSrcConn, MaxSrcConnRate, MaxSrcNodes). func (sp *Plugin) hasDoSPreventionFilters(device *common.CommonDevice) bool { for _, rule := range device.FirewallRules { if rule.Type != common.RuleTypePass || rule.Disabled { continue } if rule.MaxSrcConn != "" || rule.MaxSrcConnRate != "" || rule.MaxSrcNodes != "" { return true } } return false } // hasSyslogEnabled checks whether syslog is enabled with remote forwarding configured. func (sp *Plugin) hasSyslogEnabled(device *common.CommonDevice) bool { return device.Syslog.Enabled && device.Syslog.RemoteServer != "" } // hasDoSAlerting checks whether IDS/IPS is enabled, which provides DoS detection capability. // Full alerting configuration (SIEM integration, notification rules) cannot be verified from // config.xml alone, but IDS/IPS enablement is the prerequisite. func (sp *Plugin) hasDoSAlerting(device *common.CommonDevice) bool { return device.IDS != nil && device.IDS.Enabled } // broadNetworks contains common broad network ranges used to detect overly // permissive firewall rules. Declared at package level to avoid allocation // on every call within the rule-checking loop. var broadNetworks = []string{ "0.0.0.0/0", // All IPv4 "::/0", // All IPv6 "10.0.0.0/8", // Large private network "172.16.0.0/12", // Large private network "192.168.0.0/16", // Large private network constants.NetworkAny, // Any network }