ids

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 27 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package ids is the intrusion detection module: alerts of IPS and IDS events and their link to the vulnerabilities of the attacked device (S-IDS-1). In this release its source is the IPS and IDS events customers' firewalls write in the logs they send to the box (FortiGate IPS, Suricata and Snort on pfSense, OPNsense and other gateways, Sophos, SonicWall, Palo Alto, Meraki): the logs module hands each stored line over, this package reads the ones that are IPS events (every byte is untrusted, SYS-6), and keeps one alert per signature, source, destination and hour with the CVE ids the event names. Detection never blocks traffic; the module never opens a port, never runs a process and never calls out. Other sources (an engine on the box) add values to ids_alert.source.

Index

Constants

View Source
const (
	// MaxLineBytes is the longest line read; the logs module stores at most 2,048 bytes of a line, so this is only a guard.
	MaxLineBytes = 4096
	// MaxSignatureLen and MaxCategoryLen are the longest signature and category kept, in characters (the API's limits).
	MaxSignatureLen = 300
	MaxCategoryLen  = 120
	// MaxCVEs is how many CVE ids one event keeps (the lowest ones, sorted).
	MaxCVEs = 8
)

Limits of what one IPS event can put in a row. A log line is untrusted input (SYS-6): every value is cut to these bounds and a line that does not have the shape of its vendor's IPS event gives no event at all (fail closed).

View Source
const (
	// MaxPending is how many distinct alerts (signature, source, destination, hour) wait in memory for the next flush; the events of
	// more are dropped and counted.
	MaxPending = 2000
	// MaxAlerts is how many alert rows are kept; the oldest go first.
	MaxAlerts = 50000
	// RetentionDays is how long an alert is kept after its last event.
	RetentionDays = 90
	// AlertEventsPerHour is how many announcements of alerts notify gets in a clock hour (like the logs module's IocEventsPerHour): a
	// flood of distinct sources (UDP syslog can be forged on the LAN) cannot make thousands of incidents. Past it, the alerts are stored
	// and shown, and one summary incident a clock hour says that more came. The most severe alerts are announced first.
	AlertEventsPerHour = 100
	// FlushEvery is the pause between two flushes of the events received.
	FlushEvery = 5 * time.Second
)

Bounds of what a flood of events can make the module hold or write (SYS-6).

View Source
const AttackWindow = 14 * 24 * time.Hour

AttackWindow is how recent an alert must be for its CVE to count as attacked here (layer 1 of a finding's urgency).

View Source
const EventAlertDetected = "ids.alert.detected"

EventAlertDetected is published after an alert's events are stored (new, or more of them): notify opens or counts the incident of kind intrusion from it.

View Source
const ModuleID = "ids"

ModuleID is the id of the module in its MANIFEST.

View Source
const PageMax = 200

PageMax is the largest page of the alert list.

View Source
const SourceLog = "log"

SourceLog is the source of an alert read from an IPS or IDS event in a log line a device sent to the box.

Variables

View Source
var Migrations = mustSub(migrationFiles, "migrations/sqlite")

Migrations holds the SQLite migrations of the module.

Functions

func IncidentKey

func IncidentKey(srcIP string, cves []string, sid int64, signature string) (source, target string)

IncidentKey is the source and target of the intrusion incident an alert counts on: one incident per (CVE ids or rule, source address) while it repeats.

func NativeIPS

func NativeIPS(kind string) bool

NativeIPS reports whether a log source of this kind is a device that writes IPS events.

func Reads

func Reads(kind string) bool

Reads reports whether lines of a source of this kind can carry IPS events.

Types

type Alert

type Alert struct {
	ID        string          `json:"id"`
	Source    string          `json:"source"`
	SID       *int64          `json:"sid"`
	Signature string          `json:"signature"`
	Category  string          `json:"category"`
	Priority  int             `json:"priority"`
	Severity  string          `json:"severity"`
	SrcIP     string          `json:"src_ip"`
	SrcDevice *DeviceRef      `json:"src_device"`
	DstIP     string          `json:"dst_ip"`
	DstPort   *int            `json:"dst_port"`
	Proto     string          `json:"proto"`
	DstDevice *DeviceRef      `json:"dst_device"`
	CVEs      []string        `json:"cves"`
	Findings  []FindingLink   `json:"findings"`
	FirstSeen string          `json:"first_seen"`
	LastSeen  string          `json:"last_seen"`
	Count     int             `json:"count"`
	Incident  *IncidentRefAPI `json:"incident"`
	// contains filtered or unexported fields
}

Alert is one intrusion alert as the API shows it (contract Alert).

type AlertEvent

type AlertEvent struct {
	AlertID  string      `json:"alert_id"`
	Source   string      `json:"source"`
	Target   string      `json:"target"`
	Title    string      `json:"title"`
	What     string      `json:"what"`
	Action   string      `json:"action"`
	Severity string      `json:"severity"`
	Link     string      `json:"link"`
	At       time.Time   `json:"at"`
	Devices  []DeviceRef `json:"devices"`
}

AlertEvent is the data of ids.alert.detected: notify opens or counts the incident of kind intrusion from it (source and target are its key). Every string is derived from an untrusted log line; notify shows it as plain text.

type AlertsView

type AlertsView struct {
	Items []Alert `json:"items"`
	Total int     `json:"total"`
}

AlertsView is the answer of GET /detection/alerts.

type Attack

type Attack struct {
	CVE         string
	DstIP       string
	DstAssetID  string
	FirstSeen   time.Time
	LastSeen    time.Time
	Events      int
	LastAlertID string
}

Attack is one CVE fired at one address, as the alerts since a time saw it: the input of layer 1 of a finding's urgency ("under attack here"). DstAssetID is the device that had the address when the events arrived ("" when none did).

func ReadAttacked

func ReadAttacked(ctx context.Context, q *sql.DB, since time.Time) ([]Attack, error)

ReadAttacked is Attacked through q, the service's reader or a read-only handle on the same file (the selfcheck recomputes stored urgencies with it).

type Config

type Config struct {
	DB        *store.DB
	Inventory Inventory
	Findings  Findings
	Incidents Incidents
	Events    Publisher
	Modules   Modules // nil: the module counts as on
	Log       *slog.Logger
	Clock     func() time.Time
}

Config is what the service needs. DB is required; every port may be nil (no names, no linked findings, no incidents, no events).

type DeviceRef

type DeviceRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

DeviceRef is a device as an event or the API names it.

type Event

type Event struct {
	Profile   string // the device profile that read it: fortigate, suricata, snort, suricata_eve, sophos, sonicwall, paloalto, meraki
	SID       int64  // the rule or signature number; -1 when the event gives none
	Signature string // the rule name as the event wrote it, never empty
	Category  string // the rule's class as the event wrote it; "" when it gives none
	Priority  int    // 1 (most urgent) .. 4
	Src, Dst  netip.Addr
	DstPort   int    // -1 when the event gives no port (ICMP)
	Proto     string // tcp, udp, icmp... lower case; "" when the event gives none
	CVEs      []string
}

Event is one IPS or IDS event read from a log line: what fired, from where, at what.

func Parse

func Parse(kind, line string) (Event, bool)

Parse reads one stored log line of a source of the given kind. ok is false for every line that is not an IPS event of a format the kind can send, and for one that is but is malformed: a missing or doubled field, an address that is not an address, a cut line. Parse is total and bounded: no input makes it panic, allocate more than a few times the line, or run in more than linear time (Go's regexp is linear).

type FindingLink struct {
	ID     string    `json:"id"`
	CVE    string    `json:"cve"`
	Device DeviceRef `json:"device"`
	Status string    `json:"status"`
}

FindingLink is a linked finding as the API shows it.

type Findings

type Findings interface {
	Linked(ctx context.Context, cvesByDevice map[string][]string) (map[string][]LinkedFinding, error)
}

Findings is what the module needs of the findings module: the findings of some devices for some CVEs, read once for all of them (device id -> the CVEs an alert at it names; the answer is keyed by device id).

type IDSHandlers

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

IDSHandlers implements the alert operations of intrusion detection (GET /detection/alerts, /detection/alerts/{id}). The overview (GET /detection/overview) is core's: it answers while this module is off. Embed it in the composite handler.

func NewIDSHandlers

func NewIDSHandlers(svc *Service) *IDSHandlers

NewIDSHandlers returns the handlers of svc.

func (*IDSHandlers) DetectionGetDetectionAlerts

DetectionGetDetectionAlerts implements detection_get_detection_alerts (viewer).

func (*IDSHandlers) DetectionGetDetectionAlertsID

DetectionGetDetectionAlertsID implements detection_get_detection_alerts_id (viewer).

type IncidentRef

type IncidentRef struct{ ID, Status string }

IncidentRef is the incident of kind intrusion that groups an alert.

type IncidentRefAPI

type IncidentRefAPI struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

IncidentRefAPI is the incident of an alert as the API shows it.

type Incidents

type Incidents interface {
	Intrusion(ctx context.Context, source, target string, at time.Time) (IncidentRef, bool, error)
	ResolvedSince(ctx context.Context, ev AlertEvent, since time.Time) (bool, error)
}

Incidents reads notify's intrusion incidents. Intrusion finds the incident opened for an incident key (source and target, as the event gave them) that existed at a time. ResolvedSince says whether the incident an announcement of ev would count on was resolved at or after since and none of its key is open: a repeat announced at since and held back since then must be announced again, as a new incident (notify ResolvedSince).

type Inventory

type Inventory interface {
	// DevicesAt maps each address to the one device that has it; an address no device or more than one device has is left out.
	DevicesAt(ctx context.Context, ips []string) (map[string]string, error)
	// Names gives the display name of each device id; a device that is gone is left out.
	Names(ctx context.Context, ids []string) (map[string]string, error)
}

Inventory is what the module needs of the inventory: the device that has an address, and device names.

type Line

type Line struct {
	SourceID, SourceName, Kind string
	At                         time.Time
	Text                       string
}

Line is a log line the logs module stored, with the kind of the source that sent it.

type LinkedFinding

type LinkedFinding struct {
	ID, CVE, Status string
	// Affected: the finding is open, so the device is affected by the CVE (not patched, mitigated, accepted or dismissed), and the flaw
	// can be exploited over the network: an alert naming a flaw that needs local or physical access is not an attack on it.
	Affected bool
}

LinkedFinding is a finding of the attacked device for a CVE an alert names, with the findings module's one status.

type Modules

type Modules interface{ Enabled(id string) bool }

Modules says whether a module is on.

type Publisher

type Publisher interface {
	Publish(ctx context.Context, e events.Event) error
}

Publisher publishes events after a commit.

type Query

type Query struct {
	Window, Q, Device, CVE, Sort string
	Offset, Limit                int
}

Query is the filter of the alert list.

type Service

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

Service owns ids_alert and ids_alert_cve.

func NewService

func NewService(cfg Config) (*Service, error)

NewService checks the config and returns the service.

func (*Service) Attacked

func (s *Service) Attacked(ctx context.Context, since time.Time) ([]Attack, error)

Attacked is the port findings reads: which CVEs were attacked here, against which address and device, and when, for the alerts with an event at or after since (one row per CVE and destination address, newest first). Findings decides what that means for a finding (layer 1: an attack in the last AttackWindow aimed at the device, or at any address while the device is affected).

func (*Service) DeviceMerged

func (s *Service) DeviceMerged(ctx context.Context, tx *sql.Tx, m lifecycle.Merge) error

DeviceMerged moves the alerts of the merged device to the device it joined, in the inventory's transaction. (A deleted device needs nothing: the foreign keys set its alerts' device to NULL.)

func (*Service) Flush

func (s *Service) Flush(ctx context.Context) error

Flush stores the alerts Offer kept, in one transaction, and then announces them. Dropped events are logged once per flush.

func (*Service) Get

func (s *Service) Get(ctx context.Context, id string) (Alert, error)

Get answers GET /detection/alerts/{id}: the alert as the list shows it, every hour of it folded into one (fold), whichever of its hours the id names.

func (*Service) Jobs

func (s *Service) Jobs() []jobs.Job

Jobs are the module's jobs: flush (stores what Offer kept, while the module is on) and purge (Housekeeping: deletes the alerts past RetentionDays and over MaxAlerts, also while the module is off).

func (*Service) List

func (s *Service) List(ctx context.Context, q Query) (AlertsView, error)

List answers GET /detection/alerts: the alerts with activity in the window, filtered by a device (source or destination), a CVE and a search over the signature, category, addresses, device names and CVE ids; sorted by the newest last event or the most events, ties by id; paged.

func (*Service) Offer

func (s *Service) Offer(_ context.Context, lines []Line)

Offer reads stored log lines for IPS events and keeps them for the next flush. It never blocks on the database (the logs module calls it after a batch is stored, and a syslog flood must not wait for the main database's writer): it only parses and counts in memory, bounded by MaxPending alerts. While the module is off it does nothing.

func (*Service) Purge

func (s *Service) Purge(ctx context.Context) error

Purge deletes the alerts past RetentionDays and over MaxAlerts (the Housekeeping job).

func (*Service) Summarize

func (s *Service) Summarize(ctx context.Context, since time.Time) (Summary, error)

Summarize counts the alerts with activity since a time.

type Summary

type Summary struct {
	Alerts, Affected int       // alerts with activity in the window, and those whose attacked device is affected by a CVE they name
	LastEvent        time.Time // the newest event of any alert (zero when none)
}

Summary is what the Intrusion detection overview shows of the module.

Jump to

Keyboard shortcuts

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