sanitizer

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package sanitizer provides functionality to redact sensitive information from OPNsense configuration files.

Package sanitizer provides functionality to redact sensitive information from OPNsense configuration files.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractEmails

func ExtractEmails(s string) []string

ExtractEmails extracts all substrings that match email addresses in s, in the order they appear. It preserves duplicates and returns an empty slice if none are found.

func ExtractIPv4Addresses

func ExtractIPv4Addresses(s string) []string

ExtractIPv4Addresses extracts all IPv4 addresses from s. It returns a slice of IPv4 address strings in dotted-decimal form, in the order they appear; duplicates are preserved and an empty slice is returned if none are found.

func IsBase64

func IsBase64(s string) bool

IsBase64 reports whether s appears to be base64-encoded data. It trims surrounding whitespace, requires s to be at least the package's minimum base64 length, and then checks against the compiled base64 pattern. Returns true if s matches those criteria, false otherwise.

func IsCertificate

func IsCertificate(s string) bool

IsCertificate reports whether s appears to contain an X.509 certificate.

If s is PEM-formatted, it must include the literal "CERTIFICATE" in the PEM markers to be considered a certificate. Otherwise the function treats s as base64 and returns true if it matches base64 characteristics.

Returns `true` if s appears to be a certificate in PEM or base64 form, `false` otherwise.

func IsDomain

func IsDomain(s string) bool

IsDomain reports whether s is a domain name suitable as a hostname. It requires at least one dot, must not be an IP address, and must match the package's hostname pattern.

func IsEmail

func IsEmail(s string) bool

IsEmail reports whether s is a syntactically valid email address according to the package's email pattern. It checks only the string format and does not verify DNS records, domain ownership, or mailbox deliverability.

func IsHostname

func IsHostname(s string) bool

IsHostname reports whether s looks like a hostname or fully-qualified domain name. It requires at least one dot, rejects plain IP addresses, and validates the string against the package hostname pattern.

func IsIP

func IsIP(s string) bool

IsIP reports whether s is a valid IPv4 or IPv6 address. It returns true if s can be parsed as an IP address, false otherwise.

func IsIPv4

func IsIPv4(s string) bool

IsIPv4 checks if the string is a valid IPv4 address.

func IsIPv6

func IsIPv6(s string) bool

IsIPv6 reports whether s is a textual IPv6 address in common formats.

The check accepts typical IPv6 representations such as full and compressed forms and mixed IPv4/IPv6 notations; it does not attempt network-level reachability checks. Returns true if s matches an IPv6 textual form, false otherwise.

func IsMAC

func IsMAC(s string) bool

IsMAC reports whether s is a MAC address in common colon- or hyphen-separated notation. It matches six groups of two hexadecimal digits separated by `:` or `-` (for example "01:23:45:67:89:ab" or "01-23-45-67-89-ab").

func IsPEM

func IsPEM(s string) bool

IsPEM reports whether s contains one or more PEM-formatted blocks delimited by "-----BEGIN ...-----" and "-----END ...-----" markers with content between them. It only detects the PEM markers and enclosed data and does not validate the decoded contents.

func IsPrivateIP

func IsPrivateIP(s string) bool

IsPrivateIP reports whether the provided string is an IPv4 or IPv6 private address. It returns `true` if the string parses as an IPv4 address within RFC1918 ranges or as an IPv6 unique local address (fc00::/7), and `false` otherwise.

func IsPrivateKey

func IsPrivateKey(s string) bool

IsPrivateKey reports whether s appears to be a private key in PEM format. It returns true when s matches PEM structure and contains the "PRIVATE KEY" label, and false otherwise.

func IsPublicIP

func IsPublicIP(s string) bool

IsPublicIP reports whether s is a publicly routable IP address.

For unparsable input it returns false. For IPv4 addresses it returns false for RFC1918 private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), for loopback (127.0.0.0/8) and for link-local (169.254.0.0/16). For IPv6 it returns false for link-local addresses, for unique local addresses (fc00::/7) and for loopback.

func IsValidMode

func IsValidMode(mode string) bool

IsValidMode checks if the provided mode string is one of the valid sanitization modes (aggressive, moderate, minimal).

func LooksLikeAPIKey

func LooksLikeAPIKey(fieldName string) bool

LooksLikeAPIKey reports whether fieldName likely refers to an API key. It performs a case-insensitive substring check and returns true if fieldName contains any of the common API key indicators such as "apikey", "api_key", "api-key", "accesskey", or "secretkey".

func LooksLikePSK

func LooksLikePSK(fieldName string) bool

LooksLikePSK reports whether a field name suggests it contains a pre-shared key. It performs a case-insensitive substring check for common PSK-related tokens: "psk", "preshared", "pre-shared", and "ipsecpsk".

func LooksLikePassword

func LooksLikePassword(fieldName string) bool

LooksLikePassword reports whether fieldName likely contains a password or secret. It performs a case-insensitive substring check for common password/key-related keywords such as "password", "passwd", "pass", "secret", "key", "token", "credential", "auth", "prv", and "private". It returns true if any keyword is present in fieldName, false otherwise.

func LooksLikeSNMPCommunity

func LooksLikeSNMPCommunity(fieldName string) bool

LooksLikeSNMPCommunity reports whether fieldName likely refers to an SNMP community string. It returns true if the lower-cased field name contains "community" or "rocommunity".

Types

type Mapper

type Mapper struct {
	// contains filtered or unexported fields
}

Mapper maintains consistent mappings between original and redacted values. This ensures the same original value always maps to the same redacted value throughout the entire document for referential integrity.

func NewMapper

func NewMapper() *Mapper

NewMapper creates and returns a ready-to-use Mapper with all mapping tables initialized. The returned Mapper is safe for concurrent use via its internal mutex.

func (*Mapper) GenerateReport

func (m *Mapper) GenerateReport(mode string) *MappingReport

GenerateReport creates a mapping report for the given mode.

func (*Mapper) MapDomain

func (m *Mapper) MapDomain(original string) string

MapDomain returns a consistent replacement for a domain name.

func (*Mapper) MapEmail

func (m *Mapper) MapEmail(original string) string

MapEmail returns a consistent replacement for an email address.

func (*Mapper) MapGeneric

func (m *Mapper) MapGeneric(original, category string) string

MapGeneric returns a consistent replacement for a generic value.

func (*Mapper) MapHostname

func (m *Mapper) MapHostname(original string) string

MapHostname returns a consistent replacement for a hostname.

func (*Mapper) MapMAC

func (m *Mapper) MapMAC(original string) string

MapMAC returns a consistent replacement for a MAC address.

func (*Mapper) MapPrivateIP

func (m *Mapper) MapPrivateIP(original string, preserveStructure bool) string

MapPrivateIP returns a consistent replacement for a private IP address. If preserveStructure is true, it preserves the network class structure.

func (*Mapper) MapPublicIP

func (m *Mapper) MapPublicIP(original string) string

MapPublicIP returns a consistent replacement for a public IP address.

func (*Mapper) MapUsername

func (m *Mapper) MapUsername(original string) string

MapUsername returns a consistent replacement for a username.

func (*Mapper) Reset

func (m *Mapper) Reset()

Reset clears all mappings and counters.

func (*Mapper) ToJSON

func (m *Mapper) ToJSON(mode string) ([]byte, error)

ToJSON returns the mapping report as JSON bytes.

type MappingCategories

type MappingCategories struct {
	IPAddresses  map[string]string `json:"ip_addresses,omitempty"`
	Hostnames    map[string]string `json:"hostnames,omitempty"`
	Usernames    map[string]string `json:"usernames,omitempty"`
	Domains      map[string]string `json:"domains,omitempty"`
	MACAddresses map[string]string `json:"mac_addresses,omitempty"`
	Emails       map[string]string `json:"emails,omitempty"`
	Other        map[string]string `json:"other,omitempty"`
}

MappingCategories groups mappings by category.

type MappingReport

type MappingReport struct {
	Version   string            `json:"version"`
	Timestamp string            `json:"timestamp"`
	Mode      string            `json:"mode"`
	Mappings  MappingCategories `json:"mappings"`
}

MappingReport represents the JSON output for the mapping file.

type Mode

type Mode string

Mode represents the sanitization aggressiveness level.

const (
	// ModeAggressive redacts all sensitive data for public sharing.
	ModeAggressive Mode = "aggressive"
	// ModeModerate redacts most sensitive data but preserves some network structure.
	ModeModerate Mode = "moderate"
	// ModeMinimal redacts only the most sensitive data (passwords, keys).
	ModeMinimal Mode = "minimal"
)

func ValidModes

func ValidModes() []Mode

ValidModes returns the supported sanitization modes (aggressive, moderate, minimal) in order from most to least aggressive.

type Rule

type Rule struct {
	// Name is the rule identifier.
	Name string
	// Description explains what this rule redacts.
	Description string
	// Category groups related rules together.
	Category RuleCategory
	// Modes specifies which sanitization modes activate this rule.
	Modes []Mode
	// FieldPatterns are field name patterns that trigger redaction.
	FieldPatterns []string
	// ValueDetector is an optional function to detect sensitive values.
	ValueDetector func(value string) bool
	// Redactor performs the actual redaction using the mapper.
	Redactor func(mapper *Mapper, fieldName, value string) string
}

Rule defines a redaction rule for a specific type of sensitive data.

type RuleCategory

type RuleCategory string

RuleCategory groups related redaction rules.

const (
	// CategoryCredentials groups rules that redact passwords, keys, and tokens.
	CategoryCredentials RuleCategory = "credentials"
	// CategoryNetwork groups rules that redact IP addresses and network configurations.
	CategoryNetwork RuleCategory = "network"
	// CategoryIdentity groups rules that redact usernames, hostnames, and domain names.
	CategoryIdentity RuleCategory = "identity"
	// CategoryCrypto groups rules that redact certificates and cryptographic material.
	CategoryCrypto RuleCategory = "crypto"
	// CategorySystem groups rules that redact system-level configuration details.
	CategorySystem RuleCategory = "system"
)

Rule category constants.

type RuleEngine

type RuleEngine struct {
	// contains filtered or unexported fields
}

RuleEngine manages and applies redaction rules.

func NewRuleEngine

func NewRuleEngine(mode Mode) *RuleEngine

NewRuleEngine creates a RuleEngine configured for the given Mode. The engine is populated with the package's builtin rules and a default Mapper.

func (*RuleEngine) GetActiveRules

func (e *RuleEngine) GetActiveRules() []Rule

GetActiveRules returns rules that are active for the current mode.

func (*RuleEngine) GetMapper

func (e *RuleEngine) GetMapper() *Mapper

GetMapper returns the current mapper for generating reports.

func (*RuleEngine) GetRulesByCategory

func (e *RuleEngine) GetRulesByCategory(category RuleCategory) []Rule

GetRulesByCategory returns all rules in a specific category.

func (*RuleEngine) Redact

func (e *RuleEngine) Redact(fieldName, value string) string

Redact applies the appropriate redaction for a field/value pair.

func (*RuleEngine) SetMapper

func (e *RuleEngine) SetMapper(m *Mapper)

SetMapper allows setting a custom mapper (useful for testing or chaining).

func (*RuleEngine) ShouldRedactField

func (e *RuleEngine) ShouldRedactField(fieldName string) (bool, *Rule)

ShouldRedactField determines if a field should be redacted based on its name.

func (*RuleEngine) ShouldRedactValue

func (e *RuleEngine) ShouldRedactValue(fieldName, value string) (bool, *Rule)

ShouldRedactValue determines if a value should be redacted based on its content.

type Sanitizer

type Sanitizer struct {
	// contains filtered or unexported fields
}

Sanitizer orchestrates the redaction of sensitive data from OPNsense configuration.

func NewSanitizer

func NewSanitizer(mode Mode) *Sanitizer

NewSanitizer creates a Sanitizer configured for the given Mode, initializing its rule engine and an empty statistics map for tracking redactions. The returned *Sanitizer is ready to perform XML and struct sanitization and to collect sanitization metrics.

func (*Sanitizer) GetMapper

func (s *Sanitizer) GetMapper() *Mapper

GetMapper returns the mapper for generating mapping reports.

func (*Sanitizer) GetStats

func (s *Sanitizer) GetStats() Stats

GetStats returns a copy of the current sanitization statistics. The copy ensures callers cannot observe or mutate internal state.

func (*Sanitizer) SanitizeStruct

func (s *Sanitizer) SanitizeStruct(v any) error

SanitizeStruct uses reflection to sanitize a struct in place. This is useful for sanitizing parsed model structs before re-encoding.

func (*Sanitizer) SanitizeXML

func (s *Sanitizer) SanitizeXML(r io.Reader, w io.Writer) error

SanitizeXML reads XML from the reader, sanitizes it, and writes to the writer. This processes the XML as a stream, maintaining the original structure.

type Stats

type Stats struct {
	TotalFields      int
	RedactedFields   int
	SkippedFields    int
	RedactionsByType map[string]int
}

Stats tracks sanitization statistics.

Jump to

Keyboard shortcuts

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