Documentation
¶
Overview ¶
Package collector provides a mechanism to collect network packets from a network interface on macOS, linux and windows
Index ¶
- Variables
- func ImportSensorOutput(ctx context.Context, bundle, store string, scope SensorImportScope) (string, error)
- func IsPcap(file string) (bool, error)
- func NewCaptureReader(input io.Reader) (captureReader, error)
- func NewPCAPReader(input io.Reader) (captureReader, error)
- func OpenPCAP(file string) (*pcapgo.Reader, *os.File, error)
- func PruneSensorImports(ctx context.Context, store string, scope SensorImportScope) ([]string, error)
- func ResetHeaderPrinted()
- func SealSensorOutput(ctx context.Context, output, store, sensorID string, now, expires time.Time, ...) (string, error)
- type BatchInfo
- type CaptureInputError
- type CaptureInputIssue
- type CaptureInputReport
- type Collector
- func (c *Collector) BehaviorForOutput(output string) *behavior.Engine
- func (c *Collector) CloseFileHandleOnShutdown(f *os.File)
- func (c *Collector) CollectBPF(path, bpf string) error
- func (c *Collector) CollectLive(i string, bpf string, ctx context.Context) (resultErr error)
- func (c *Collector) CollectPcap(path string) (resultErr error)
- func (c *Collector) CollectPcapNG(path string) error
- func (c *Collector) EvaluateRules(record types.AuditRecord)
- func (c *Collector) EvaluateRulesWithMetrics(record types.AuditRecord) int
- func (c *Collector) FlushAssemblers()
- func (c *Collector) GetAlertCount() int64
- func (c *Collector) GetBehaviorEngine() *behavior.Engine
- func (c *Collector) GetBehaviorError() error
- func (c *Collector) GetBehaviorHealth(output string) behavior.Health
- func (c *Collector) GetCurrentPacketCount() int64
- func (c *Collector) GetFilteredCount() int64
- func (c *Collector) GetNetworkDetectionError() error
- func (c *Collector) GetNumPackets() int64
- func (c *Collector) GetPacketsPerSecond() int64
- func (c *Collector) GetProfilesCount() int
- func (c *Collector) GetServicesCount() int
- func (c *Collector) GetTotalAuditRecords() int64
- func (c *Collector) GetTotalBytesWritten() int64
- func (c *Collector) GetTotalPacketCount() int64
- func (c *Collector) Init() (err error)
- func (c *Collector) InitBatching(bpf string, in string) ([]BatchInfo, *pcap.Handle, error)
- func (c *Collector) NetworkDetectionForOutput(output string) (networkdetect.Stats, bool)
- func (c *Collector) PacketPipelineStats() packetview.Stats
- func (c *Collector) PrintConfiguration()
- func (c *Collector) ReloadRulesEngine() error
- func (c *Collector) RenderPacketsPerSecond(inputFile string, out string)
- func (c *Collector) SetBehaviorDeliveryHealth(read func() *behavior.DeliveryHealth)
- func (c *Collector) SetBehaviorEngine(engine *behavior.Engine, scope behavior.Scope)
- func (c *Collector) SetFilterExpression(expression string, recordType types.Type) error
- func (c *Collector) SetLogLevel(debug bool)
- func (c *Collector) SetRulesEngine(engine *rules.Engine)
- func (c *Collector) SetSignalExitHook(hook func() error)
- func (c *Collector) ShouldWriteRecord(record types.AuditRecord) bool
- func (c *Collector) Stop()
- func (c *Collector) WrapWritersWithFiltering()
- type Config
- type FilteringWriter
- func (fw *FilteringWriter) Close(numRecords int64) (name string, size int64)
- func (fw *FilteringWriter) Flush() error
- func (fw *FilteringWriter) Write(msg proto.Message) error
- func (fw *FilteringWriter) WriteHeader(t types.Type) error
- func (fw *FilteringWriter) WriteScoped(msg proto.Message, scope string) error
- type SensorFile
- type SensorImportScope
- type SensorManifest
Constants ¶
This section is empty.
Variables ¶
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.
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.
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 ¶
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
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
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 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.
Types ¶
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 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 (*Collector) BehaviorForOutput ¶
func (*Collector) CloseFileHandleOnShutdown ¶
CloseFileHandleOnShutdown allows to register file handles for close on shutdown.
func (*Collector) CollectBPF ¶
CollectBPF open the named PCAP file and sets the specified BPF filter.
func (*Collector) CollectLive ¶
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 ¶
CollectPcap implements parallel decoding of incoming packets.
func (*Collector) CollectPcapNG ¶
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 ¶
GetAlertCount returns the number of alerts generated.
func (*Collector) GetBehaviorEngine ¶
func (*Collector) GetBehaviorError ¶
func (*Collector) GetBehaviorHealth ¶
func (*Collector) GetCurrentPacketCount ¶
GetCurrentPacketCount returns the current packet count (for live statistics)
func (*Collector) GetFilteredCount ¶
GetFilteredCount returns the number of records filtered out.
func (*Collector) GetNetworkDetectionError ¶
func (*Collector) GetNumPackets ¶
GetNumPackets returns the current number of processed packets.
func (*Collector) GetPacketsPerSecond ¶
GetPacketsPerSecond returns the current packets per second rate (for live statistics)
func (*Collector) GetProfilesCount ¶
GetProfilesCount returns the current number of device profiles (for live statistics)
func (*Collector) GetServicesCount ¶
GetServicesCount returns the current number of services (for live statistics)
func (*Collector) GetTotalAuditRecords ¶
GetTotalAuditRecords returns the total number of audit records generated.
func (*Collector) GetTotalBytesWritten ¶
GetTotalBytesWritten returns the total bytes written to disk.
func (*Collector) GetTotalPacketCount ¶
GetTotalPacketCount returns the total packet count (for live statistics)
func (*Collector) Init ¶
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 ¶
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 ¶
ReloadRulesEngine reloads the rules engine configuration from disk. This is used when rules are updated via the webUI at runtime.
func (*Collector) RenderPacketsPerSecond ¶
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 ¶
SetBehaviorEngine installs the early observer before capture starts. The caller owns checkpointing and closing the engine and its alert sink.
func (*Collector) SetFilterExpression ¶
SetFilterExpression sets a filter expression for a specific record type.
func (*Collector) SetLogLevel ¶
SetLogLevel updates the log level for all zap loggers at runtime. This allows enabling/disabling debug logging without restarting.
func (*Collector) SetRulesEngine ¶
SetRulesEngine sets the rules engine for alert generation.
func (*Collector) SetSignalExitHook ¶
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 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"`
}
Source Files
¶
- atomic_pcap_go_writer.go
- batch.go
- behavior.go
- bpf.go
- capture_evidence.go
- capture_format.go
- capture_input.go
- capture_links.go
- capture_reader.go
- capture_reader_ng.go
- capture_time.go
- chart.go
- cleanup.go
- collector.go
- config.go
- dns_context.go
- errors.go
- filtering_writer.go
- flow_exports.go
- init.go
- lifecycle.go
- live_linux.go
- live_maintenance.go
- log.go
- memstats.go
- metrics.go
- network_detection.go
- pcap.go
- pcapNG.go
- pcap_file_exec.go
- pcap_utils.go
- periodic_flush.go
- record_analysis.go
- rules_scope.go
- sensor_import.go
- service_signatures.go
- utils.go
- worker.go