collector

package
v0.16.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 88 Imported by: 0 modules, 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 collector provides a mechanism to collect network packets from a network interface on macOS, linux and windows

Index

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{
	Workers:             0,
	CaptureEvidence:     true,
	PacketBufferSize:    1000,
	WriteUnknownPackets: false,
	Promisc:             false,
	SnapLen:             defaults.SnapLen,
	DPI:                 false,
	BaseLayer:           utils.GetBaseLayer("ethernet"),
	DecodeOptions:       utils.GetDecodeOptions("default"),
	DecoderConfig:       config.DefaultConfig,
	ResolverConfig:      resolvers.DefaultConfig,
	Timeout:             pcap.BlockForever,
	LogErrors:           false,
}

DefaultConfig is a sane example configuration.

View Source
var DefaultConfigDPI = Config{
	Workers:             0,
	CaptureEvidence:     true,
	PacketBufferSize:    1000,
	WriteUnknownPackets: false,
	Promisc:             false,
	SnapLen:             defaults.SnapLen,
	DPI:                 true,
	BaseLayer:           utils.GetBaseLayer("ethernet"),
	DecodeOptions:       utils.GetDecodeOptions("default"),
	DecoderConfig:       config.DefaultConfig,
	ResolverConfig:      resolvers.DefaultConfig,
	LogErrors:           false,
}

DefaultConfigDPI is a sane example configuration for use with Deep Packet Inspection.

View Source
var ErrStopped = errors.New("collector stopped")

ErrStopped is returned when initialization or capture is attempted after Stop.

Functions

func ImportSensorOutput

func ImportSensorOutput(ctx context.Context, bundle, store string, scope SensorImportScope) (string, error)

ImportSensorOutput verifies scope, signature, expiry and every file before an atomic publication. Existing sensor/run identities are never overwritten.

func IsPcap

func IsPcap(file string) (bool, error)

IsPcap classifies classic PCAP by magic, including gzip streams. It does not validate headers: unsupported or damaged PCAP stays on the PCAP error path.

func NewCaptureReader added in v0.16.0

func NewCaptureReader(input io.Reader) (captureReader, error)

NewCaptureReader selects by magic, not parser success. A damaged classic PCAP must never be retried as PCAPNG. Mixed-link PCAPNG is rejected because callers use LinkType to compile one BPF program or write one PCAP header. Collection uses openCaptureInput instead, preserving per-interface metadata.

func NewPCAPReader added in v0.16.0

func NewPCAPReader(input io.Reader) (captureReader, error)

NewPCAPReader accepts classic PCAP 2.0–2.4, including gzip streams, while retaining the collector's allocation limits and malformed-record checks. The caller owns input and must close it when finished.

func OpenPCAP

func OpenPCAP(file string) (*pcapgo.Reader, *os.File, error)

OpenPCAP opens a Packet Capture file.

func PruneSensorImports

func PruneSensorImports(ctx context.Context, store string, scope SensorImportScope) ([]string, error)

PruneSensorImports removes only expired, signed runs belonging to the supplied scope. The service schedules this call; expiration alone does not delete bytes.

func ResetHeaderPrinted

func ResetHeaderPrinted()

ResetHeaderPrinted resets the flag that tracks whether the netcap header has been printed. This is useful when starting a new batch of processing or in testing scenarios.

func SealSensorOutput

func SealSensorOutput(ctx context.Context, output, store, sensorID string, now, expires time.Time, key []byte) (string, error)

SealSensorOutput snapshots a completed local collector output into a signed, private bundle. The transport to the receiving service is caller-owned.

Types

type BatchInfo

type BatchInfo struct {
	Type types.Type
	Chan <-chan []byte
}

BatchInfo contains information about a Batch source.

type CaptureInputError added in v0.16.0

type CaptureInputError struct{ Report CaptureInputReport }

func (*CaptureInputError) Error added in v0.16.0

func (e *CaptureInputError) Error() string

type CaptureInputIssue added in v0.16.0

type CaptureInputIssue struct {
	Offset      int64  `json:"offset"`
	Kind        string `json:"kind"`
	Reason      string `json:"reason"`
	Recoverable bool   `json:"recoverable"`
}

type CaptureInputReport added in v0.16.0

type CaptureInputReport struct {
	Format            string              `json:"format"`
	Status            string              `json:"status"`
	ReachedEOF        bool                `json:"reachedEOF"`
	CountedPackets    int64               `json:"countedPackets"`
	ProcessedPackets  int64               `json:"processedPackets"`
	SkippedRecords    int64               `json:"skippedRecords"`
	ReadErrors        int64               `json:"readErrors"`
	LinkErrors        int64               `json:"linkErrors"`
	DecodeErrors      int64               `json:"decodeErrors"`
	Unsupported       int64               `json:"unsupportedPackets"`
	SnaplenOverrides  int64               `json:"snaplenOverrides"`
	SnapshotTruncated int64               `json:"snapshotTruncatedPackets"`
	Issues            []CaptureInputIssue `json:"issues,omitempty"`
}

CaptureInputReport describes input coverage independently of audit counts. Issues is bounded; counters include every occurrence, even after it fills.

type Collector

type Collector struct {
	InputFile string
	PrintTime bool
	Bpf       string

	Epochs int
	// contains filtered or unexported fields
}

Collector provides an interface to collect data from PCAP or a network interface. this structure has an optimized field order to avoid excessive padding.

func New

func New(config Config) *Collector

New returns a new Collector instance.

func (*Collector) BehaviorForOutput

func (c *Collector) BehaviorForOutput(output string) *behavior.Engine

func (*Collector) CloseFileHandleOnShutdown

func (c *Collector) CloseFileHandleOnShutdown(f *os.File)

CloseFileHandleOnShutdown allows to register file handles for close on shutdown.

func (*Collector) CollectBPF

func (c *Collector) CollectBPF(path, bpf string) error

CollectBPF open the named PCAP file and sets the specified BPF filter.

func (*Collector) CollectLive

func (c *Collector) CollectLive(i string, bpf string, ctx context.Context) (resultErr error)

CollectLive starts collection of data from the given interface. optionally a BPF can be supplied. this is the linux version that uses the pure go version from pcapgo to fetch packets live.

func (*Collector) CollectPcap

func (c *Collector) CollectPcap(path string) (resultErr error)

CollectPcap implements parallel decoding of incoming packets.

func (*Collector) CollectPcapNG

func (c *Collector) CollectPcapNG(path string) error

CollectPcapNG shares the bounded count/process policy with CollectPcap.

func (*Collector) EvaluateRules

func (c *Collector) EvaluateRules(record types.AuditRecord)

EvaluateRules evaluates all rules against a record and generates alerts if matched.

func (*Collector) EvaluateRulesWithMetrics

func (c *Collector) EvaluateRulesWithMetrics(record types.AuditRecord) int

EvaluateRulesWithMetrics evaluates rules and returns the number of alerts generated. This is used by the FilteringWriter to track metrics.

func (*Collector) FlushAssemblers

func (c *Collector) FlushAssemblers()

FlushAssemblers synchronously flushes connections, retaining live assemblers. Page caches are reclaimed only when cleanup releases the stopped assemblers.

func (*Collector) GetAlertCount

func (c *Collector) GetAlertCount() int64

GetAlertCount returns the number of alerts generated.

func (*Collector) GetBehaviorEngine

func (c *Collector) GetBehaviorEngine() *behavior.Engine

func (*Collector) GetBehaviorError

func (c *Collector) GetBehaviorError() error

func (*Collector) GetBehaviorHealth

func (c *Collector) GetBehaviorHealth(output string) behavior.Health

func (*Collector) GetCurrentPacketCount

func (c *Collector) GetCurrentPacketCount() int64

GetCurrentPacketCount returns the current packet count (for live statistics)

func (*Collector) GetFilteredCount

func (c *Collector) GetFilteredCount() int64

GetFilteredCount returns the number of records filtered out.

func (*Collector) GetNetworkDetectionError

func (c *Collector) GetNetworkDetectionError() error

func (*Collector) GetNumPackets

func (c *Collector) GetNumPackets() int64

GetNumPackets returns the current number of processed packets.

func (*Collector) GetPacketsPerSecond

func (c *Collector) GetPacketsPerSecond() int64

GetPacketsPerSecond returns the current packets per second rate (for live statistics)

func (*Collector) GetProfilesCount

func (c *Collector) GetProfilesCount() int

GetProfilesCount returns the current number of device profiles (for live statistics)

func (*Collector) GetServicesCount

func (c *Collector) GetServicesCount() int

GetServicesCount returns the current number of services (for live statistics)

func (*Collector) GetTotalAuditRecords

func (c *Collector) GetTotalAuditRecords() int64

GetTotalAuditRecords returns the total number of audit records generated.

func (*Collector) GetTotalBytesWritten

func (c *Collector) GetTotalBytesWritten() int64

GetTotalBytesWritten returns the total bytes written to disk.

func (*Collector) GetTotalPacketCount

func (c *Collector) GetTotalPacketCount() int64

GetTotalPacketCount returns the total packet count (for live statistics)

func (*Collector) Init

func (c *Collector) Init() (err error)

Init sets up the collector and starts the configured number of workers must be called prior to usage of the collector instance.

func (*Collector) InitBatching

func (c *Collector) InitBatching(bpf string, in string) ([]BatchInfo, *pcap.Handle, error)

InitBatching initializes batching mode and returns decoder channels and the pcap handle. Closing the handle stops capture early; lifecycle cleanup also closes it when capture ends.

func (*Collector) NetworkDetectionForOutput

func (c *Collector) NetworkDetectionForOutput(output string) (networkdetect.Stats, bool)

func (*Collector) PacketPipelineStats added in v0.16.0

func (c *Collector) PacketPipelineStats() packetview.Stats

PacketPipelineStats reports bounded normalization/defragmentation outcomes.

func (*Collector) PrintConfiguration

func (c *Collector) PrintConfiguration()

PrintConfiguration dumps the current collector config to stdout.

func (*Collector) ReloadRulesEngine

func (c *Collector) ReloadRulesEngine() error

ReloadRulesEngine reloads the rules engine configuration from disk. This is used when rules are updated via the webUI at runtime.

func (*Collector) RenderPacketsPerSecond

func (c *Collector) RenderPacketsPerSecond(inputFile string, out string)

RenderPacketsPerSecond will render a html chart for the packet ingestion rate of the collector over time. Do not call while the collector is running, the access to the pps map is not synchronized. If you need runtime metrics, use prometheus.

func (*Collector) SetBehaviorDeliveryHealth

func (c *Collector) SetBehaviorDeliveryHealth(read func() *behavior.DeliveryHealth)

func (*Collector) SetBehaviorEngine

func (c *Collector) SetBehaviorEngine(engine *behavior.Engine, scope behavior.Scope)

SetBehaviorEngine installs the early observer before capture starts. The caller owns checkpointing and closing the engine and its alert sink.

func (*Collector) SetFilterExpression

func (c *Collector) SetFilterExpression(expression string, recordType types.Type) error

SetFilterExpression sets a filter expression for a specific record type.

func (*Collector) SetLogLevel

func (c *Collector) SetLogLevel(debug bool)

SetLogLevel updates the log level for all zap loggers at runtime. This allows enabling/disabling debug logging without restarting.

func (*Collector) SetRulesEngine

func (c *Collector) SetRulesEngine(engine *rules.Engine)

SetRulesEngine sets the rules engine for alert generation.

func (*Collector) SetSignalExitHook

func (c *Collector) SetSignalExitHook(hook func() error)

SetSignalExitHook installs command finalization before a handled signal exits. Set it before starting capture. Normal cleanup does not call it (multi-input commands).

func (*Collector) ShouldWriteRecord

func (c *Collector) ShouldWriteRecord(record types.AuditRecord) bool

ShouldWriteRecord checks if a record should be written based on the filter. Returns true if the record passes the filter (or no filter is set).

func (*Collector) Stop

func (c *Collector) Stop()

Stop will halt packet collection and wait for all processing to finish.

func (*Collector) WrapWritersWithFiltering

func (c *Collector) WrapWritersWithFiltering()

WrapWritersWithFiltering wraps all decoder writers with FilteringWriters. This should be called after decoders are initialized and before processing starts.

type Config

type Config struct {
	NetworkDetection       bool
	DNSResolutionContext   bool
	NetworkDetectionConfig string

	// Decoder configuration
	DecoderConfig *config.Config

	// Baselayer to start decoding from
	BaseLayer gopacket.LayerType

	// Number of workers to use
	Workers int

	// Size of the input buffer channels for the workers
	PacketBufferSize int

	// Ethernet frame snaplength for live capture
	SnapLen int

	// Can be used to periodically free OS memory
	FreeOSMem int

	// Permissions for output directory
	OutDirPermission os.FileMode

	// Attach in promiscuous mode for live capture
	Promisc bool

	// Controls whether packets that had an unknown layer will get written into a separate file
	WriteUnknownPackets bool

	// Resolver configuration
	ResolverConfig resolvers.Config

	// Decoding options for gopacket
	DecodeOptions gopacket.DecodeOptions

	// Enable deep packet inspection
	DPI bool

	// DPI modules to use (comma-separated: lpi, ndpi, go)
	// If empty and DPI is enabled, all modules will be used
	DPIModules string

	// Independent DPI contexts; 0 selects automatically, 1 minimizes native context memory.
	DPIWorkers int

	// Use TCP reassembly
	ReassembleConnections bool

	// LogErrors will log verbose packet decoding errors into the errors.log file
	LogErrors bool

	// NoPrompt will disable all human interaction prompts
	NoPrompt bool

	// HTTPShutdownEndpoint will run a HTTP service on localhost:60589
	// sending a GET request there can be used to trigger teardown and audit record flushing
	// which can be used as alternative to using OS signals
	HTTPShutdownEndpoint bool

	// NoSignalHandling disables signal handling in the collector
	// This is useful when running in service mode where the parent process handles signals
	NoSignalHandling bool

	// Timeout controls libpcap batching for live and batch capture. Positive
	// values are honored exactly. Zero and negative values use a 100ms polling
	// interval so cancellation can interrupt an idle read.
	// From the macOS docs on libpcap:
	//   The read timeout is used to arrange that the read not necessarily return
	//   immediately when a packet is seen, but that it wait for some amount of time
	//   to allow more packets to arrive and to read multiple packets from the OS
	//   kernel in one operation.
	Timeout time.Duration

	// Labels is a filesystem path to the labels file on disk
	// that contains the attack mappings
	Labels string

	// Generate scatter chart for the applied labels during labeling.
	Scatter bool

	// ScatterDuration is the interval for data used in the scatter plot.
	ScatterDuration time.Duration

	// LiveFlushInterval is the interval at which audit records are flushed during live capture.
	// This makes data visible while capture is ongoing.
	// If zero, no periodic flushing is performed (records only flushed on shutdown).
	// Recommended: 30s to 60s for most use cases.
	LiveFlushInterval time.Duration
	// LiveMaintenanceInterval schedules ordered stream expiry independently of output snapshots.
	// Zero selects one second; negative disables it. Offline replay never uses wall-clock maintenance.
	LiveMaintenanceInterval time.Duration
	FlowExports             bool
	FlowExportPorts         string
	CaptureEvidence         bool
	RetainPackets           bool
	PacketSegmentBytes      int64
	PacketRetentionBytes    int64
}

Config contains configuration parameters for the Collector instance. this structure has an optimized field order to avoid excessive padding.

type FilteringWriter

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

FilteringWriter wraps an AuditRecordWriter and applies filtering and rules before writing.

func NewFilteringWriter

func NewFilteringWriter(underlying netio.AuditRecordWriter, collector *Collector) *FilteringWriter

NewFilteringWriter creates a new filtering writer that wraps an underlying writer.

func (*FilteringWriter) Close

func (fw *FilteringWriter) Close(numRecords int64) (name string, size int64)

Close closes the underlying writer.

func (*FilteringWriter) Flush

func (fw *FilteringWriter) Flush() error

Flush flushes the underlying writer's buffer.

func (*FilteringWriter) Write

func (fw *FilteringWriter) Write(msg proto.Message) error

Write applies filtering and rules evaluation before writing the record.

func (*FilteringWriter) WriteHeader

func (fw *FilteringWriter) WriteHeader(t types.Type) error

WriteHeader writes the header to the underlying writer.

func (*FilteringWriter) WriteScoped added in v0.16.0

func (fw *FilteringWriter) WriteScoped(msg proto.Message, scope string) error

WriteScoped carries packet provenance without adding transient wire fields.

type SensorFile

type SensorFile struct {
	Path   string `json:"path"`
	Bytes  int64  `json:"bytes,string"`
	SHA256 string `json:"sha256"`
}

type SensorImportScope

type SensorImportScope struct {
	SensorKeys   map[string][]byte
	Now          time.Time
	MaxBytes     int64
	MaxRetention time.Duration
}

Scope is supplied by the receiving service, never decoded from an upload. SensorKeys proves shared-key possession, not endpoint or user authentication.

type SensorManifest

type SensorManifest struct {
	Version     int          `json:"version"`
	SensorID    string       `json:"sensorId"`
	RunID       string       `json:"runId"`
	InputSHA256 string       `json:"inputSHA256"`
	CreatedNs   int64        `json:"createdNs,string"`
	ExpiresNs   int64        `json:"expiresNs,string"`
	Files       []SensorFile `json:"files"`
	Signature   string       `json:"hmacSHA256"`
}

Jump to

Keyboard shortcuts

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