store

package
v0.0.0-...-8b48234 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
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

func EnsureOpen(statePath string) error

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

func ParseTimeKeyPrefix(date string) string

ParseTimeKeyPrefix converts a date string "YYYY-MM-DD" to a seek prefix "YYYYMMDD".

func SetGlobal

func SetGlobal(db *DB)

SetGlobal sets the singleton DB instance.

func TimeKey

func TimeKey(t time.Time, counter int) string

TimeKey produces a fixed-width 28-byte key for chronological ordering. Format: YYYYMMDDHHmmssNNNNNNNNN-CCCC Lexicographic order equals chronological order.

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 Global

func Global() *DB

Global returns the singleton DB instance.

func Open

func Open(statePath string) (*DB, error)

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

func (db *DB) AbuseQueryCount(utcDate string) int

AbuseQueryCount returns the AbuseIPDB query count for the given UTC date.

func (*DB) AbuseQuotaExhaustedUntil

func (db *DB) AbuseQuotaExhaustedUntil() time.Time

AbuseQuotaExhaustedUntil returns the persisted quota-reset timestamp, or zero time if none is recorded (or the stored value is unparseable).

func (*DB) AddModSecNoEscalateRule

func (db *DB) AddModSecNoEscalateRule(ruleID int) error

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

func (db *DB) AddPermanentBlock(ip, reason string) error

AddPermanentBlock adds an IP to the permanent block list. Only increments threats:count if the key is new.

func (*DB) AddPortAllow

func (db *DB) AddPortAllow(ip string, port int, proto, reason string) error

AddPortAllow adds a per-IP port allow rule to the fw:port_allowed bucket.

func (*DB) AddSubnet

func (db *DB) AddSubnet(cidr, reason string) error

AddSubnet adds a CIDR to the fw:subnets bucket.

func (*DB) AddWhitelistEntry

func (db *DB) AddWhitelistEntry(ip string, expiresAt time.Time, permanent bool) error

AddWhitelistEntry adds an IP to the whitelist.

func (*DB) AggregateByDay

func (db *DB) AggregateByDay() []DayBucket

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

func (db *DB) AggregateByDayN(days int) []DayBucket

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) AllowIP

func (db *DB) AllowIP(ip, reason string, expiresAt time.Time) error

AllowIP adds an IP to the fw:allowed bucket.

func (*DB) AppendHistory

func (db *DB) AppendHistory(findings []alert.Finding) error

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

func (db *DB) BackfillStatsDaily() error

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) BlockIP

func (db *DB) BlockIP(ip, reason string, expiresAt time.Time) error

BlockIP adds an IP to the fw:blocked bucket.

func (*DB) CleanExpiredReputation

func (db *DB) CleanExpiredReputation(maxAge time.Duration) int

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

func (db *DB) ClearFirewallRollback() error

ClearFirewallRollback drops the pending rollback. Idempotent: deleting a non-existent key is not an error in bbolt.

func (*DB) Close

func (db *DB) Close() error

Close closes the bbolt database.

func (*DB) CompactIncidents

func (db *DB) CompactIncidents(now time.Time, retention time.Duration) (int, error)

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

func (db *DB) CompactInto(dstPath string, txMaxSize int64) (srcSize, dstSize int64, err error)

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

func (db *DB) DeleteIPRecord(ip string) error

DeleteIPRecord removes an IP record from the attacks:records bucket.

func (*DB) DeleteSitePlugins

func (db *DB) DeleteSitePlugins(wpPath string) error

DeleteSitePlugins removes the plugin inventory for a WordPress installation.

func (*DB) DryRunBlocksCount

func (db *DB) DryRunBlocksCount() int

DryRunBlocksCount returns the number of recorded dry-run block entries.

func (*DB) EnforceReputationCap

func (db *DB) EnforceReputationCap(max int) int

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

func (db *DB) GetEmailPWLastRefresh() time.Time

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

func (db *DB) GetForwarderHash(key string) (string, bool)

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

func (db *DB) GetIncident(id string) (incident.Incident, bool, error)

GetIncident returns (incident, true, nil) if found, (zero, false, nil) if not, (zero, false, err) on store error.

func (*DB) GetMetaString

func (db *DB) GetMetaString(key string) string

GetMetaString reads a string value from the meta bucket. Returns an empty string if the key is not found.

func (*DB) GetModSecNoEscalateRules

func (db *DB) GetModSecNoEscalateRules() map[int]bool

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

func (db *DB) GetPluginRefreshTime() time.Time

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

func (db *DB) GetSignatureMtimes() (map[string]time.Time, error)

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) HasBucket

func (db *DB) HasBucket(name string) bool

HasBucket reports whether a top-level bucket named name exists in db.

func (*DB) HistoryCount

func (db *DB) HistoryCount() int

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

func (db *DB) IncrModSecRuleHit(ruleID int, timestamp time.Time)

IncrModSecRuleHit increments the hit counter for a rule ID in the current hour bucket.

func (*DB) IncrementAbuseQueryCount

func (db *DB) IncrementAbuseQueryCount(utcDate string) int

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

func (db *DB) IsHealthy() bool

IsHealthy returns true if the bbolt file is open and all required buckets exist.

func (*DB) IsWhitelisted

func (db *DB) IsWhitelisted(ip string) bool

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

func (db *DB) ListIncidents() ([]incident.Incident, error)

ListIncidents returns every stored incident, newest UpdatedAt first.

func (*DB) ListIncidentsByStatus

func (db *DB) ListIncidentsByStatus(status incident.Status) ([]incident.Incident, error)

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

func (db *DB) LoadAllIPRecords() map[string]*IPRecord

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

func (db *DB) LoadIPRecord(ip string) (IPRecord, bool)

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

func (db *DB) MarkDBObjectBackupRestored(key string, restoredAt time.Time) error

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

func (db *DB) PHPRelayDelete(bucket, key string) error

PHPRelayDelete removes a key. Missing keys are not an error.

func (*DB) PHPRelayGet

func (db *DB) PHPRelayGet(bucket, key string) ([]byte, bool, error)

PHPRelayGet reads a single value. ok=false when the key is absent.

func (*DB) PHPRelayList

func (db *DB) PHPRelayList(bucket string) (map[string][]byte, error)

PHPRelayList returns a copy of every key/value in the bucket. Used at daemon start to restore the in-memory ignoreList.

func (*DB) PHPRelayPut

func (db *DB) PHPRelayPut(bucket, key string, value []byte) error

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

func (db *DB) PHPRelaySweep(bucket string, shouldDelete func(key, value []byte) bool) (int, error)

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) Path

func (db *DB) Path() string

Path returns the on-disk path of the bbolt database file.

func (*DB) PruneExpiredWhitelist

func (db *DB) PruneExpiredWhitelist() int

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

func (db *DB) PutSignatureMtimes(m map[string]time.Time) error

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

func (db *DB) ReadHistory(limit, offset int) ([]alert.Finding, int)

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

func (db *DB) ReadHistorySince(since time.Time) []alert.Finding

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

func (db *DB) RecordDryRunBlock(ip, reason string, timeout time.Duration)

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

func (db *DB) RemoveAllow(ip string) error

RemoveAllow removes an IP from the fw:allowed bucket.

func (*DB) RemoveModSecNoEscalateRule

func (db *DB) RemoveModSecNoEscalateRule(ruleID int) error

RemoveModSecNoEscalateRule atomically removes a single rule ID from the no-escalate set.

func (*DB) RemovePermanentBlock

func (db *DB) RemovePermanentBlock(ip string) error

RemovePermanentBlock removes an IP from the permanent block list and decrements the count.

func (*DB) RemovePortAllow

func (db *DB) RemovePortAllow(ip string, port int, proto string) error

RemovePortAllow removes a per-IP port allow rule from the fw:port_allowed bucket.

func (*DB) RemoveSubnet

func (db *DB) RemoveSubnet(cidr string) error

RemoveSubnet removes a CIDR from the fw:subnets bucket.

func (*DB) RemoveWhitelistEntry

func (db *DB) RemoveWhitelistEntry(ip string) error

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

func (db *DB) SaveIPRecord(record IPRecord) error

SaveIPRecord stores an IP record in the attacks:records bucket, keyed by IP.

func (*DB) SaveIncident

func (db *DB) SaveIncident(inc incident.Incident) error

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

func (db *DB) SetAbuseQuotaExhaustedUntil(t time.Time) error

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

func (db *DB) SetEmailPWLastRefresh(t time.Time) error

SetEmailPWLastRefresh writes the email password-check refresh timestamp to the meta bucket.

func (*DB) SetForwarderHash

func (db *DB) SetForwarderHash(key, hash string) error

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

func (db *DB) SetMetaString(key, val string) error

SetMetaString writes a string value to the meta bucket.

func (*DB) SetModSecNoEscalateRules

func (db *DB) SetModSecNoEscalateRules(rules map[int]bool) error

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

func (db *DB) SetPluginRefreshTime(t time.Time) error

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

func (db *DB) Size() (int64, error)

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

func (db *DB) SizeBytes() int64

SizeBytes returns the on-disk size of the bbolt database file. Returns 0 if unavailable.

func (*DB) SweepAttackEventsOlderThan

func (db *DB) SweepAttackEventsOlderThan(cutoff time.Time) (int, error)

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

func (db *DB) SweepHistoryOlderThan(cutoff time.Time) (int, error)

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

func (db *DB) SweepReputationOlderThan(cutoff time.Time) (int, error)

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.

func (*DB) UnblockIP

func (db *DB) UnblockIP(ip string) error

UnblockIP removes an IP from the fw:blocked bucket.

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

type ExportResult struct {
	Path          string
	Bytes         int64
	ArchiveSHA256 string
	BboltSHA256   string
}

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

type PHPRelayKV struct {
	Key   []byte
	Value []byte
}

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

type RuleHitStats struct {
	Hits    int       `json:"hits"`
	LastHit time.Time `json:"last_hit"`
}

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.

type WhitelistEntry

type WhitelistEntry struct {
	IP        string    `json:"ip"`
	ExpiresAt time.Time `json:"expires_at"`
	Permanent bool      `json:"permanent"`
}

WhitelistEntry represents an IP that should bypass threat checks.

Jump to

Keyboard shortcuts

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