Documentation
¶
Index ¶
- Constants
- Variables
- func EnsureOpen(statePath string) error
- func ParseTimeKeyPrefix(date string) string
- func SetGlobal(db *DB)
- func TimeKey(t time.Time, counter int) string
- type AttackEvent
- type AuditReport
- type AuditResult
- type DB
- func (db *DB) AbuseQueryCount(utcDate string) int
- func (db *DB) AbuseQuotaExhaustedUntil() time.Time
- func (db *DB) AddModSecNoEscalateRule(ruleID int) error
- func (db *DB) AddPermanentBlock(ip, reason string) error
- func (db *DB) AddPortAllow(ip string, port int, proto, reason string) error
- func (db *DB) AddSubnet(cidr, reason string) error
- func (db *DB) AddWhitelistEntry(ip string, expiresAt time.Time, permanent bool) error
- func (db *DB) AggregateByDay() []DayBucket
- func (db *DB) AggregateByDayN(days int) []DayBucket
- func (db *DB) AggregateByHour() []HourBucket
- func (db *DB) AllPermanentBlocks() []PermanentBlockEntry
- func (db *DB) AllReputation() map[string]ReputationEntry
- func (db *DB) AllSitePlugins() map[string]SitePlugins
- func (db *DB) AllowIP(ip, reason string, expiresAt time.Time) error
- func (db *DB) AppendHistory(findings []alert.Finding) error
- func (db *DB) BackfillStatsDaily() error
- func (db *DB) BlockIP(ip, reason string, expiresAt time.Time) error
- func (db *DB) CleanExpiredReputation(maxAge time.Duration) int
- func (db *DB) ClearFirewallRollback() error
- func (db *DB) Close() error
- func (db *DB) CompactIncidents(now time.Time, retention time.Duration) (int, error)
- func (db *DB) CompactInto(dstPath string, txMaxSize int64) (srcSize, dstSize int64, err error)
- func (db *DB) DeleteIPRecord(ip string) error
- func (db *DB) DeleteSitePlugins(wpPath string) error
- func (db *DB) DryRunBlocksCount() int
- func (db *DB) EnforceReputationCap(max int) int
- func (db *DB) Export(opts ExportOptions) (*ExportResult, error)
- func (db *DB) GetBlockedIP(ip string) (FWBlockedEntry, bool)
- func (db *DB) GetDBObjectBackupByKey(key string) (DBObjectBackup, bool, error)
- func (db *DB) GetEmailPWLastRefresh() time.Time
- func (db *DB) GetFirewallRollback() (FirewallRollback, bool)
- func (db *DB) GetForwarderHash(key string) (string, bool)
- func (db *DB) GetGeoHistory(mailbox string) (GeoHistory, bool)
- func (db *DB) GetIncident(id string) (incident.Incident, bool, error)
- func (db *DB) GetMetaString(key string) string
- func (db *DB) GetModSecNoEscalateRules() map[int]bool
- func (db *DB) GetModSecRuleHits() map[int]RuleHitStats
- func (db *DB) GetPermanentBlock(ip string) (PermanentBlockEntry, bool)
- func (db *DB) GetPluginInfo(slug string) (PluginInfo, bool)
- func (db *DB) GetPluginRefreshTime() time.Time
- func (db *DB) GetReputation(ip string) (ReputationEntry, bool)
- func (db *DB) GetSignatureMtimes() (map[string]time.Time, error)
- func (db *DB) GetSitePlugins(wpPath string) (SitePlugins, bool)
- func (db *DB) HasBucket(name string) bool
- func (db *DB) HistoryCount() int
- func (db *DB) IncrModSecRuleHit(ruleID int, timestamp time.Time)
- func (db *DB) IncrementAbuseQueryCount(utcDate string) int
- func (db *DB) IsHealthy() bool
- func (db *DB) IsWhitelisted(ip string) bool
- func (db *DB) ListDBObjectBackups(account string) ([]DBObjectBackup, error)
- func (db *DB) ListDBObjectBackupsAll() ([]DBObjectBackup, []string, error)
- func (db *DB) ListIncidents() ([]incident.Incident, error)
- func (db *DB) ListIncidentsByStatus(status incident.Status) ([]incident.Incident, error)
- func (db *DB) ListPortAllows() []FWPortAllowEntry
- func (db *DB) ListWhitelist() []WhitelistEntry
- func (db *DB) LoadAllIPRecords() map[string]*IPRecord
- func (db *DB) LoadFirewallState() FirewallState
- func (db *DB) LoadHardeningReport() (*AuditReport, error)
- func (db *DB) LoadIPRecord(ip string) (IPRecord, bool)
- func (db *DB) MarkDBObjectBackupRestored(key string, restoredAt time.Time) error
- func (db *DB) PHPRelayDelete(bucket, key string) error
- func (db *DB) PHPRelayGet(bucket, key string) ([]byte, bool, error)
- func (db *DB) PHPRelayList(bucket string) (map[string][]byte, error)
- func (db *DB) PHPRelayPut(bucket, key string, value []byte) error
- func (db *DB) PHPRelayPutBatch(bucket string, ops []PHPRelayKV) error
- func (db *DB) PHPRelaySweep(bucket string, shouldDelete func(key, value []byte) bool) (int, error)
- func (db *DB) Path() string
- func (db *DB) PruneExpiredWhitelist() int
- func (db *DB) PutDBObjectBackup(b DBObjectBackup) error
- func (db *DB) PutSignatureMtimes(m map[string]time.Time) error
- func (db *DB) QueryAttackEvents(ip string, limit int) []AttackEvent
- func (db *DB) ReadAllAttackEvents() []AttackEvent
- func (db *DB) ReadHistory(limit, offset int) ([]alert.Finding, int)
- func (db *DB) ReadHistoryFiltered(limit, offset int, from, to string, severity int, search string) ([]alert.Finding, int)
- func (db *DB) ReadHistorySince(since time.Time) []alert.Finding
- func (db *DB) RecordAttackEvent(event AttackEvent, counter int) error
- func (db *DB) RecordDryRunBlock(ip, reason string, timeout time.Duration)
- func (db *DB) RemoveAllow(ip string) error
- func (db *DB) RemoveModSecNoEscalateRule(ruleID int) error
- func (db *DB) RemovePermanentBlock(ip string) error
- func (db *DB) RemovePortAllow(ip string, port int, proto string) error
- func (db *DB) RemoveSubnet(cidr string) error
- func (db *DB) RemoveWhitelistEntry(ip string) error
- func (db *DB) SaveFirewallRollback(rb FirewallRollback) error
- func (db *DB) SaveHardeningReport(report *AuditReport) error
- func (db *DB) SaveIPRecord(record IPRecord) error
- func (db *DB) SaveIncident(inc incident.Incident) error
- func (db *DB) SetAbuseQuotaExhaustedUntil(t time.Time) error
- func (db *DB) SetEmailPWLastRefresh(t time.Time) error
- func (db *DB) SetForwarderHash(key, hash string) error
- func (db *DB) SetGeoHistory(mailbox string, h GeoHistory) error
- func (db *DB) SetMetaString(key, val string) error
- func (db *DB) SetModSecNoEscalateRules(rules map[int]bool) error
- func (db *DB) SetPluginInfo(slug string, info PluginInfo) error
- func (db *DB) SetPluginRefreshTime(t time.Time) error
- func (db *DB) SetReputation(ip string, entry ReputationEntry) error
- func (db *DB) SetSitePlugins(wpPath string, site SitePlugins) error
- func (db *DB) Size() (int64, error)
- func (db *DB) SizeBytes() int64
- func (db *DB) SweepAttackEventsOlderThan(cutoff time.Time) (int, error)
- func (db *DB) SweepHistoryOlderThan(cutoff time.Time) (int, error)
- func (db *DB) SweepReputationOlderThan(cutoff time.Time) (int, error)
- func (db *DB) UnblockIP(ip string) error
- type DBObjectBackup
- type DayBucket
- type ExportOptions
- type ExportResult
- type FWAllowedEntry
- type FWBlockedEntry
- type FWPortAllowEntry
- type FWSubnetEntry
- type FirewallRollback
- type FirewallState
- type GeoHistory
- type HourBucket
- type IPRecord
- type ImportOptions
- type ImportResult
- type Manifest
- type PHPRelayKV
- type PermanentBlockEntry
- type PluginInfo
- type ReputationEntry
- type RuleHitStats
- type SeverityBucket
- type SitePluginEntry
- type SitePlugins
- type WhitelistEntry
Constants ¶
const ArchiveSchemaVersion = 1
ArchiveSchemaVersion is the on-wire schema for backup archives. Bump when the manifest layout or contents shape changes incompatibly. Old CSM binaries refuse archives newer than the version they understand.
Variables ¶
var ( ErrSchemaVersionTooNew = errors.New("archive schema version is newer than this binary supports") ErrPlatformMismatch = errors.New("archive source platform does not match current host") ErrManifestMissing = errors.New("archive does not contain manifest.json") ErrCorruptArchive = errors.New("archive is corrupt or not a CSM backup") )
Sentinel errors so callers can branch on the failure mode instead of matching strings.
Functions ¶
func EnsureOpen ¶
EnsureOpen opens the store if not already open. Safe to call from any CLI path. First call opens the DB; subsequent calls return immediately.
func ParseTimeKeyPrefix ¶
ParseTimeKeyPrefix converts a date string "YYYY-MM-DD" to a seek prefix "YYYYMMDD".
Types ¶
type AttackEvent ¶
type AttackEvent struct {
Timestamp time.Time `json:"timestamp"`
IP string `json:"ip"`
AttackType string `json:"attack_type"`
CheckName string `json:"check_name"`
Severity int `json:"severity"`
Account string `json:"account,omitempty"`
Message string `json:"message,omitempty"`
}
AttackEvent is the store-layer representation of an attack event.
type AuditReport ¶
type AuditReport struct {
Timestamp time.Time `json:"timestamp"`
ServerType string `json:"server_type"`
Results []AuditResult `json:"results"`
Score int `json:"score"`
Total int `json:"total"`
}
AuditReport is the full result of a hardening audit run.
type AuditResult ¶
type AuditResult struct {
Category string `json:"category"`
Name string `json:"name"`
Title string `json:"title"`
Status string `json:"status"`
Message string `json:"message"`
Fix string `json:"fix,omitempty"`
}
AuditResult represents a single hardening check result.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB wraps a bbolt database.
func Open ¶
Open opens or creates the bbolt database at {statePath}/csm.db. Creates all buckets if they don't exist. Runs migration if needed.
func (*DB) AbuseQueryCount ¶
AbuseQueryCount returns the AbuseIPDB query count for the given UTC date.
func (*DB) AbuseQuotaExhaustedUntil ¶
AbuseQuotaExhaustedUntil returns the persisted quota-reset timestamp, or zero time if none is recorded (or the stored value is unparseable).
func (*DB) AddModSecNoEscalateRule ¶
AddModSecNoEscalateRule atomically adds a single rule ID to the no-escalate set. Read-modify-write happens in a single bbolt Update transaction to prevent races.
func (*DB) AddPermanentBlock ¶
AddPermanentBlock adds an IP to the permanent block list. Only increments threats:count if the key is new.
func (*DB) AddPortAllow ¶
AddPortAllow adds a per-IP port allow rule to the fw:port_allowed bucket.
func (*DB) AddWhitelistEntry ¶
AddWhitelistEntry adds an IP to the whitelist.
func (*DB) AggregateByDay ¶
AggregateByDay returns 30 daily buckets (oldest first) for the last 30 days. Reads from the pre-aggregated stats:daily bucket so the trend chart is not affected by history pruning.
func (*DB) AggregateByDayN ¶
AggregateByDayN returns `days` daily buckets (oldest first) ending today. Days outside [1, dailyRetentionDays] are clamped to that range. Days with no recorded findings are returned as zero-value buckets.
func (*DB) AggregateByHour ¶
func (db *DB) AggregateByHour() []HourBucket
AggregateByHour returns 24 hourly buckets (oldest first) for the last 24 hours. It seeks directly to the start key in bbolt, scanning only the relevant range.
func (*DB) AllPermanentBlocks ¶
func (db *DB) AllPermanentBlocks() []PermanentBlockEntry
AllPermanentBlocks returns all entries in the permanent block list.
func (*DB) AllReputation ¶
func (db *DB) AllReputation() map[string]ReputationEntry
AllReputation returns all reputation entries keyed by IP.
func (*DB) AllSitePlugins ¶
func (db *DB) AllSitePlugins() map[string]SitePlugins
AllSitePlugins returns all site plugin inventories keyed by WordPress path.
func (*DB) AppendHistory ¶
AppendHistory inserts findings into the history bucket with TimeKey keys. It increments the history:count counter and prunes oldest entries if the count exceeds maxHistoryEntries.
func (*DB) BackfillStatsDaily ¶
BackfillStatsDaily seeds stats:daily from the history bucket on first run after upgrade. Idempotent: a meta sentinel ensures it only runs once. Safe on hosts where the meta:migrated sentinel was set before stats:daily existed.
func (*DB) CleanExpiredReputation ¶
CleanExpiredReputation deletes entries older than maxAge. Uses a collect-then-delete pattern because bbolt does not allow mutation during ForEach iteration. Returns the count of entries removed.
func (*DB) ClearFirewallRollback ¶
ClearFirewallRollback drops the pending rollback. Idempotent: deleting a non-existent key is not an error in bbolt.
func (*DB) CompactIncidents ¶
CompactIncidents removes resolved/dismissed incidents whose UpdatedAt is older than now-retention. Open and Contained incidents are never pruned regardless of age. Returns the number of records removed.
func (*DB) CompactInto ¶
CompactInto snapshots the live DB into a fresh bbolt file at dstPath using bolt.Compact. Returns the source size and the compacted size (both in bytes).
Correctness: bolt.Compact runs a View transaction on src for the duration of the walk, so concurrent Update calls on src will either land before the walk begins (captured in the snapshot) or after it completes (not in the snapshot). It is the caller's job to quiesce writers between the CompactInto call and the file rename+reopen that promotes the new file; otherwise post-snapshot writes are silently dropped during the swap.
txMaxSize caps per-transaction bytes written to the destination (see bolt.Compact docs). Zero means "one transaction for the whole copy", which is the fastest path for DBs that comfortably fit in memory.
func (*DB) DeleteIPRecord ¶
DeleteIPRecord removes an IP record from the attacks:records bucket.
func (*DB) DeleteSitePlugins ¶
DeleteSitePlugins removes the plugin inventory for a WordPress installation.
func (*DB) DryRunBlocksCount ¶
DryRunBlocksCount returns the number of recorded dry-run block entries.
func (*DB) EnforceReputationCap ¶
EnforceReputationCap ensures the reputation bucket has at most max entries. If the count exceeds max, the oldest entries (by CheckedAt) are deleted. Returns the count of entries removed.
func (*DB) Export ¶
func (db *DB) Export(opts ExportOptions) (*ExportResult, error)
Export writes a tar+zstd archive containing a bbolt snapshot, the state directory, and (optionally) the signature-rules directory. The daemon is the single source of truth for paths; the caller fills the manifest with hostname/version/platform.
func (*DB) GetBlockedIP ¶
func (db *DB) GetBlockedIP(ip string) (FWBlockedEntry, bool)
GetBlockedIP looks up a blocked IP. Returns false if not found or expired.
func (*DB) GetDBObjectBackupByKey ¶
func (db *DB) GetDBObjectBackupByKey(key string) (DBObjectBackup, bool, error)
GetDBObjectBackupByKey fetches a single record by its exact bbolt key. Returns ok=false (not an error) when the key is missing, matching the lookup-then-act flow callers use.
func (*DB) GetEmailPWLastRefresh ¶
GetEmailPWLastRefresh reads the last email password-check refresh timestamp from the meta bucket. Returns the zero time if not set.
func (*DB) GetFirewallRollback ¶
func (db *DB) GetFirewallRollback() (FirewallRollback, bool)
GetFirewallRollback returns the pending rollback or (zero, false) if none. The bool distinguishes "no record" from a zero-valued record. A bbolt unmarshal failure is treated as "no usable record" so the daemon can skip a corrupt entry instead of refusing to start.
func (*DB) GetForwarderHash ¶
GetForwarderHash retrieves a forwarder config hash. Returns the hash and true if found, or an empty string and false if not.
func (*DB) GetGeoHistory ¶
func (db *DB) GetGeoHistory(mailbox string) (GeoHistory, bool)
GetGeoHistory retrieves geo login history for a mailbox. Returns the entry and true if found, or a zero value and false if not.
func (*DB) GetIncident ¶
GetIncident returns (incident, true, nil) if found, (zero, false, nil) if not, (zero, false, err) on store error.
func (*DB) GetMetaString ¶
GetMetaString reads a string value from the meta bucket. Returns an empty string if the key is not found.
func (*DB) GetModSecNoEscalateRules ¶
GetModSecNoEscalateRules returns the set of ModSecurity rule IDs that should NOT escalate to nftables firewall blocks. Stored in the meta bucket.
func (*DB) GetModSecRuleHits ¶
func (db *DB) GetModSecRuleHits() map[int]RuleHitStats
GetModSecRuleHits returns hit counts and last-hit timestamps for all rules within the last 24 hours. Prunes buckets older than 24h. Note: hourly bucket granularity means the window is 24h +/- 1h at boundaries.
func (*DB) GetPermanentBlock ¶
func (db *DB) GetPermanentBlock(ip string) (PermanentBlockEntry, bool)
GetPermanentBlock looks up a permanent block entry by IP. Returns the entry and true if found, or a zero value and false if not.
func (*DB) GetPluginInfo ¶
func (db *DB) GetPluginInfo(slug string) (PluginInfo, bool)
GetPluginInfo retrieves plugin metadata for the given slug. Returns the entry and true if found, or a zero value and false if not.
func (*DB) GetPluginRefreshTime ¶
GetPluginRefreshTime reads the last plugin refresh timestamp from the meta bucket. Returns the zero time if not set.
func (*DB) GetReputation ¶
func (db *DB) GetReputation(ip string) (ReputationEntry, bool)
GetReputation retrieves a reputation entry for the given IP. Returns the entry and true if found, or a zero value and false if not.
func (*DB) GetSignatureMtimes ¶
GetSignatureMtimes returns the persisted mtime map. Empty (not nil) when the bucket has no value yet -- callers can range over the result without a nil check.
func (*DB) GetSitePlugins ¶
func (db *DB) GetSitePlugins(wpPath string) (SitePlugins, bool)
GetSitePlugins retrieves the plugin inventory for a WordPress installation. Returns the entry and true if found, or a zero value and false if not.
func (*DB) HistoryCount ¶
getCounter reads a counter from the meta bucket. Returns 0 if not found. HistoryCount returns the number of findings in the history bucket.
func (*DB) IncrModSecRuleHit ¶
IncrModSecRuleHit increments the hit counter for a rule ID in the current hour bucket.
func (*DB) IncrementAbuseQueryCount ¶
IncrementAbuseQueryCount bumps and returns the AbuseIPDB query counter for the given UTC date (YYYY-MM-DD). Used as a daily circuit breaker.
func (*DB) IsHealthy ¶
IsHealthy returns true if the bbolt file is open and all required buckets exist.
func (*DB) IsWhitelisted ¶
IsWhitelisted checks if an IP is whitelisted and not expired.
func (*DB) ListDBObjectBackups ¶
func (db *DB) ListDBObjectBackups(account string) ([]DBObjectBackup, error)
ListDBObjectBackups returns every record for the given account, in insertion order. Used by the CLI's listing path and cleanup-history UI.
func (*DB) ListDBObjectBackupsAll ¶
func (db *DB) ListDBObjectBackupsAll() ([]DBObjectBackup, []string, error)
ListDBObjectBackupsAll returns every record in the bucket, regardless of account, in insertion order. Used by the webui cleanup-history listing where the operator browses across all accounts at once.
func (*DB) ListIncidents ¶
ListIncidents returns every stored incident, newest UpdatedAt first.
func (*DB) ListIncidentsByStatus ¶
ListIncidentsByStatus returns incidents matching the requested status, newest UpdatedAt first.
func (*DB) ListPortAllows ¶
func (db *DB) ListPortAllows() []FWPortAllowEntry
ListPortAllows returns all entries in the fw:port_allowed bucket.
func (*DB) ListWhitelist ¶
func (db *DB) ListWhitelist() []WhitelistEntry
ListWhitelist returns all whitelist entries (including expired - caller filters).
func (*DB) LoadAllIPRecords ¶
LoadAllIPRecords returns all IP records from the attacks:records bucket.
func (*DB) LoadFirewallState ¶
func (db *DB) LoadFirewallState() FirewallState
LoadFirewallState reads all 4 firewall buckets and assembles a FirewallState. Expired blocked entries are filtered out.
func (*DB) LoadHardeningReport ¶
func (db *DB) LoadHardeningReport() (*AuditReport, error)
LoadHardeningReport retrieves the latest audit report from the meta bucket. Returns a zero-value report (nil Results) if no report has been saved yet.
func (*DB) LoadIPRecord ¶
LoadIPRecord retrieves an IP record from the attacks:records bucket. Returns the record and true if found, or a zero value and false if not.
func (*DB) MarkDBObjectBackupRestored ¶
MarkDBObjectBackupRestored records that a backup has been replayed. The backup row stays in place for audit and future manual inspection, but the WebUI can stop offering repeat restore actions for that exact archive.
func (*DB) PHPRelayDelete ¶
PHPRelayDelete removes a key. Missing keys are not an error.
func (*DB) PHPRelayGet ¶
PHPRelayGet reads a single value. ok=false when the key is absent.
func (*DB) PHPRelayList ¶
PHPRelayList returns a copy of every key/value in the bucket. Used at daemon start to restore the in-memory ignoreList.
func (*DB) PHPRelayPut ¶
PHPRelayPut writes a single key/value into the named php_relay bucket.
func (*DB) PHPRelayPutBatch ¶
func (db *DB) PHPRelayPutBatch(bucket string, ops []PHPRelayKV) error
PHPRelayPutBatch writes many key/value pairs in a single bbolt transaction. Used by the msgIndexPersister to keep IOPS bounded. Returns on the first encode/put error; partial commits are visible only at transaction boundary.
func (*DB) PHPRelaySweep ¶
PHPRelaySweep iterates the bucket and deletes every key for which shouldDelete returns true. Decoding is the caller's responsibility. Returns the number of deletions.
func (*DB) PruneExpiredWhitelist ¶
PruneExpiredWhitelist deletes expired non-permanent whitelist entries. Returns the count of entries removed. Uses a collect-then-delete pattern because bbolt does not allow mutation during ForEach iteration.
func (*DB) PutDBObjectBackup ¶
func (db *DB) PutDBObjectBackup(b DBObjectBackup) error
PutDBObjectBackup writes one backup record. Key shape: `<account>:<schema>:<kind>:<name>:<unix_nanos>` so multiple drops of the same object name (e.g., re-creates by an attacker) each get their own record.
func (*DB) PutSignatureMtimes ¶
PutSignatureMtimes overwrites the persisted mtime map. Called from the watcher's tick after every walk, regardless of whether any file changed -- removed files need to disappear from the store, not stick around forever.
func (*DB) QueryAttackEvents ¶
func (db *DB) QueryAttackEvents(ip string, limit int) []AttackEvent
QueryAttackEvents returns up to limit attack events for the given IP, newest-first. It uses the secondary index bucket for efficient prefix-based iteration.
func (*DB) ReadAllAttackEvents ¶
func (db *DB) ReadAllAttackEvents() []AttackEvent
ReadAllAttackEvents returns all attack events from the primary bucket. Used for stats computation (hourly/daily bucketing).
func (*DB) ReadHistory ¶
ReadHistory reads findings from the history bucket, newest-first. It returns up to limit findings starting at offset, plus the total count.
func (*DB) ReadHistoryFiltered ¶
func (db *DB) ReadHistoryFiltered(limit, offset int, from, to string, severity int, search string) ([]alert.Finding, int)
ReadHistoryFiltered reads findings with optional filtering. Parameters:
- from, to: date strings "YYYY-MM-DD" for time-range filtering (empty to skip)
- severity: filter by severity level (-1 for no filter)
- search: case-insensitive substring match on check/message/details (empty to skip)
func (*DB) ReadHistorySince ¶
ReadHistorySince returns all findings since the given time, using bbolt cursor seeking for efficiency. Results are newest-first.
func (*DB) RecordAttackEvent ¶
func (db *DB) RecordAttackEvent(event AttackEvent, counter int) error
RecordAttackEvent inserts an attack event into both the primary bucket (attacks:events, keyed by TimeKey) and the secondary index bucket (attacks:events:ip, keyed by IP/TimeKey). It increments the event counter and prunes oldest entries if the count exceeds maxAttackEvents.
func (*DB) RecordDryRunBlock ¶
RecordDryRunBlock appends a dry-run-block record to the "dry_run_blocks" bucket. Called by the firewall engine when auto_response.dry_run is active so operators can review "what would have been blocked" before going live.
func (*DB) RemoveAllow ¶
RemoveAllow removes an IP from the fw:allowed bucket.
func (*DB) RemoveModSecNoEscalateRule ¶
RemoveModSecNoEscalateRule atomically removes a single rule ID from the no-escalate set.
func (*DB) RemovePermanentBlock ¶
RemovePermanentBlock removes an IP from the permanent block list and decrements the count.
func (*DB) RemovePortAllow ¶
RemovePortAllow removes a per-IP port allow rule from the fw:port_allowed bucket.
func (*DB) RemoveSubnet ¶
RemoveSubnet removes a CIDR from the fw:subnets bucket.
func (*DB) RemoveWhitelistEntry ¶
RemoveWhitelistEntry removes an IP from the whitelist.
func (*DB) SaveFirewallRollback ¶
func (db *DB) SaveFirewallRollback(rb FirewallRollback) error
SaveFirewallRollback writes a pending rollback record. Overwrites any existing pending entry; callers must clear or revert the previous one first if that matters for their flow.
func (*DB) SaveHardeningReport ¶
func (db *DB) SaveHardeningReport(report *AuditReport) error
SaveHardeningReport persists the latest audit report in the meta bucket.
func (*DB) SaveIPRecord ¶
SaveIPRecord stores an IP record in the attacks:records bucket, keyed by IP.
func (*DB) SaveIncident ¶
SaveIncident persists an incident, overwriting any prior record with the same ID. Caller is responsible for setting UpdatedAt before invoking; this method just writes.
func (*DB) SetAbuseQuotaExhaustedUntil ¶
SetAbuseQuotaExhaustedUntil records the time at which the AbuseIPDB quota is expected to reset. While now < t, callers should skip API queries. The daemon re-reads this on every cycle so the flag survives restarts and multi-hour backoffs.
func (*DB) SetEmailPWLastRefresh ¶
SetEmailPWLastRefresh writes the email password-check refresh timestamp to the meta bucket.
func (*DB) SetForwarderHash ¶
SetForwarderHash stores a forwarder config hash in the email:fwd bucket.
func (*DB) SetGeoHistory ¶
func (db *DB) SetGeoHistory(mailbox string, h GeoHistory) error
SetGeoHistory stores geo login history for a mailbox in the email:geo bucket.
func (*DB) SetMetaString ¶
SetMetaString writes a string value to the meta bucket.
func (*DB) SetModSecNoEscalateRules ¶
SetModSecNoEscalateRules stores the set of rule IDs that should not escalate.
func (*DB) SetPluginInfo ¶
func (db *DB) SetPluginInfo(slug string, info PluginInfo) error
SetPluginInfo stores plugin metadata keyed by slug in the plugins bucket.
func (*DB) SetPluginRefreshTime ¶
SetPluginRefreshTime writes the plugin refresh timestamp to the meta bucket.
func (*DB) SetReputation ¶
func (db *DB) SetReputation(ip string, entry ReputationEntry) error
SetReputation stores a reputation entry for the given IP.
func (*DB) SetSitePlugins ¶
func (db *DB) SetSitePlugins(wpPath string, site SitePlugins) error
SetSitePlugins stores the plugin inventory for a WordPress installation keyed by its filesystem path in the plugins:sites bucket.
func (*DB) Size ¶
Size returns the on-disk size of the bbolt file in bytes. bbolt does not shrink the file on delete; compare Size() before and after a CompactInto call to see how much space would be reclaimed.
func (*DB) SizeBytes ¶
SizeBytes returns the on-disk size of the bbolt database file. Returns 0 if unavailable.
func (*DB) SweepAttackEventsOlderThan ¶
SweepAttackEventsOlderThan deletes attacks:events entries older than cutoff and the matching entries from the attacks:events:ip secondary index. Returns the number of primary-bucket entries deleted.
func (*DB) SweepHistoryOlderThan ¶
SweepHistoryOlderThan deletes history entries whose TimeKey is strictly older than cutoff. Returns the number of entries deleted. All work runs in a single bbolt transaction so the UI never sees a half-swept state; callers pick cutoffs that keep the batch bounded.
func (*DB) SweepReputationOlderThan ¶
SweepReputationOlderThan deletes reputation entries whose CheckedAt is strictly older than cutoff. The bucket is keyed by IP and not by time, so the sweep inspects each value; malformed rows are skipped rather than aborting the sweep.
type DBObjectBackup ¶
type DBObjectBackup struct {
Account string `json:"account"`
Schema string `json:"schema"`
Kind string `json:"kind"` // trigger | event | procedure | function
Name string `json:"name"`
CreateSQL string `json:"create_sql"`
DroppedAt time.Time `json:"dropped_at"`
DroppedBy string `json:"dropped_by"` // operator login or "csm" for daemon-driven
FindingID string `json:"finding_id,omitempty"`
RestoredAt time.Time `json:"restored_at,omitempty"`
}
DBObjectBackup is the persisted record of a SHOW CREATE captured before a manual `csm db-clean drop-object`. The CREATE SQL is the backup -- replaying it restores the object verbatim. Fields are public so the cleanup-history UI can render them without a separate API.
type DayBucket ¶
type DayBucket struct {
Date string `json:"date"`
SeverityBucket
}
DayBucket is a SeverityBucket keyed by date.
type ExportOptions ¶
type ExportOptions struct {
StatePath string // /var/lib/csm/state, source for state JSON files
RulesPath string // /opt/csm/rules, source for signature cache (empty -> skip)
DstPath string // .csmbak file to create
Manifest Manifest // caller fills CSMVersion/SourceHostname/SourcePlatform; rest filled here
}
ExportOptions configures Export.
type ExportResult ¶
ExportResult summarises a successful export.
type FWAllowedEntry ¶
type FWAllowedEntry struct {
IP string `json:"ip"`
Reason string `json:"reason"`
Source string `json:"source,omitempty"`
Port int `json:"port"` // 0 = all ports
ExpiresAt time.Time `json:"expires_at"` // zero = permanent
}
FWAllowedEntry represents an IP explicitly allowed through the firewall.
type FWBlockedEntry ¶
type FWBlockedEntry struct {
IP string `json:"ip"`
Reason string `json:"reason"`
Source string `json:"source,omitempty"`
BlockedAt time.Time `json:"blocked_at"`
ExpiresAt time.Time `json:"expires_at"` // zero = permanent
}
FWBlockedEntry represents an IP blocked by the firewall.
type FWPortAllowEntry ¶
type FWPortAllowEntry struct {
Key string `json:"key"` // IP:port/proto
IP string `json:"ip"`
Port int `json:"port"`
Proto string `json:"proto"`
Reason string `json:"reason"`
Source string `json:"source,omitempty"`
}
FWPortAllowEntry represents a per-IP port allow rule.
type FWSubnetEntry ¶
type FWSubnetEntry struct {
CIDR string `json:"cidr"`
Reason string `json:"reason"`
Source string `json:"source,omitempty"`
AddedAt time.Time `json:"added_at"`
}
FWSubnetEntry represents a subnet added to the firewall.
type FirewallRollback ¶
type FirewallRollback struct {
PrevYAML []byte `json:"prev_yaml"`
PrevHash string `json:"prev_hash"`
NewHash string `json:"new_hash"`
AppliedAt time.Time `json:"applied_at"`
ExpiresAt time.Time `json:"expires_at"`
AppliedBy string `json:"applied_by"`
}
FirewallRollback is a pending tentative-apply record. The previous csm.yaml bytes are stashed verbatim so a recovery path can restore the file byte-for-byte without re-rendering through any encoder. Hashes are recorded so the daemon can sanity-check the on-disk file matches what was applied before deciding to revert.
type FirewallState ¶
type FirewallState struct {
Blocked []FWBlockedEntry
Allowed []FWAllowedEntry
Subnets []FWSubnetEntry
PortAllowed []FWPortAllowEntry
}
FirewallState holds the full state across all 4 firewall buckets.
type GeoHistory ¶
type GeoHistory struct {
Countries map[string]int64 `json:"countries"`
LoginCount int `json:"login_count"`
}
GeoHistory tracks the countries from which a mailbox has logged in.
type HourBucket ¶
type HourBucket struct {
Hour string `json:"hour"`
SeverityBucket
}
HourBucket is a SeverityBucket keyed by hour label.
type IPRecord ¶
type IPRecord struct {
IP string `json:"ip"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
EventCount int `json:"event_count"`
AttackCounts map[string]int `json:"attack_counts,omitempty"`
Accounts map[string]int `json:"accounts,omitempty"`
ThreatScore int `json:"threat_score"`
AutoBlocked bool `json:"auto_blocked,omitempty"`
}
IPRecord is the store-layer representation of an IP attack record.
type ImportOptions ¶
type ImportOptions struct {
SrcPath string
StatePath string
RulesPath string
Only string // "all" | "baseline" | "firewall"
ForcePlatformMismatch bool
CurrentPlatform map[string]string // for the mismatch check
}
ImportOptions configures Import.
type ImportResult ¶
type ImportResult struct {
Manifest Manifest
BucketsRestored []string
StateFiles int
RulesFiles int
}
ImportResult summarises a successful import.
func Import ¶
func Import(opts ImportOptions) (*ImportResult, error)
Import unpacks an archive into the target state and rules paths. Live daemons must be stopped first; callers enforce that before invoking.
type Manifest ¶
type Manifest struct {
SchemaVersion int `json:"schema_version"`
CSMVersion string `json:"csm_version"`
SourceHostname string `json:"source_hostname"`
SourcePlatform map[string]string `json:"source_platform"`
ExportTS time.Time `json:"export_ts"`
Contents []string `json:"contents"`
BboltBuckets []string `json:"bbolt_buckets,omitempty"`
BboltSHA256 string `json:"bbolt_sha256,omitempty"`
}
Manifest is the JSON header at the top of every archive.
type PHPRelayKV ¶
PHPRelayKV is a single key/value pair for batched writes.
type PermanentBlockEntry ¶
type PermanentBlockEntry struct {
IP string `json:"ip"`
Reason string `json:"reason"`
BlockedAt time.Time `json:"blocked_at"`
}
PermanentBlockEntry represents an IP permanently blocked by the threat system.
type PluginInfo ¶
type PluginInfo struct {
LatestVersion string `json:"latest_version"`
TestedUpTo string `json:"tested_up_to"`
LastChecked int64 `json:"last_checked_unix"`
}
PluginInfo holds cached metadata for a WordPress plugin from the API.
type ReputationEntry ¶
type ReputationEntry struct {
Score int `json:"score"`
Category string `json:"category"`
CheckedAt time.Time `json:"checked_at"`
}
ReputationEntry holds the cached reputation data for an IP address.
type RuleHitStats ¶
RuleHitStats holds hit count and last-hit time for a ModSecurity rule.
type SeverityBucket ¶
type SeverityBucket struct {
Critical int `json:"critical"`
High int `json:"high"`
Warning int `json:"warning"`
Total int `json:"total"`
}
SeverityBucket holds aggregated counts by severity.
type SitePluginEntry ¶
type SitePluginEntry struct {
Slug string `json:"slug"`
Name string `json:"name"`
Status string `json:"status"`
InstalledVersion string `json:"installed_version"`
UpdateVersion string `json:"update_version"`
}
SitePluginEntry describes a single plugin installed on a WordPress site.
type SitePlugins ¶
type SitePlugins struct {
Account string `json:"account"`
Domain string `json:"domain"`
Plugins []SitePluginEntry `json:"plugins"`
}
SitePlugins holds the full plugin inventory for a WordPress installation.