Documentation
¶
Index ¶
- Constants
- Variables
- func BindAnalysisRunID(runID string)
- func CancelAnalysis()
- func DetectContentType(data []byte) (string, bool)
- func ExtensionForContentType(typ string) string
- func FinishAnalysis() (analysisErr, persistenceErr error)
- func GetDedupCache() *fileDeduplicationCache
- func GetDedupStats() dedupStats
- func GetMaxFileSize() int64
- func IsProtocolEnabled(protocol string) bool
- func IsReassemblyEnabled() bool
- func ListExtractors() []string
- func LogDedupStats(logger *zap.Logger)
- func PrepareSourceEvidence(conv *core.ConversationInfo) error
- func ReadBody(r io.Reader) ([]byte, func(), error)
- func ReadBodyLimit(r io.Reader, limit int64) (body []byte, release func(), err error)
- func RecordArtifactWriteError(err error)
- func RecordExtractionIssue(err error)
- func RegisterExtractor(extractor FileExtractor)
- func ResetDedupCache()
- func ResetGlobalYaraScanner()
- func SaveFileEnhanced(conv *core.ConversationInfo, source, name string, err error, body []byte, ...) error
- func SaveSpoolEnhanced(conv *core.ConversationInfo, source, name string, bodyErr error, ...) error
- func SetGlobalConfig(cfg *Config)
- func SetSaveFileLogger(logger *zap.Logger)
- func ShouldComputeHash(algorithm string) bool
- func ShouldExtractMimeType(mimeType string) bool
- func ShouldUseMagicDetection() bool
- func StartAnalysis(directory, runID string) error
- func ValidateConfig(cfg *Config) error
- func ValidateYaraSource(source string) error
- func WriteFile(f *types.File)
- func WriteFileEnhanced(f *types.File)
- func YaraAvailable() bool
- type AdvancedConfig
- type AnalysisReport
- type AnalyzerResult
- type ArtifactAnalysis
- type BodySpool
- type Config
- type ContentInfo
- type FileAnalysis
- type FileExtractionConfig
- type FileExtractor
- type FileHandle
- type FileHashes
- type FileMetadata
- type FileReassembler
- type HashAlgorithmsConfig
- type IncompleteFilesConfig
- type MIMESignature
- type MimeTypesConfig
- type ProtocolsConfig
- type ReassemblyConfig
- type SizeLimitsConfig
- type StorageConfig
- type StreamingHashWriter
- type YaraScanner
- func (ys *YaraScanner) Digest() string
- func (ys *YaraScanner) LastLoad() time.Time
- func (ys *YaraScanner) Reload() error
- func (ys *YaraScanner) RuleCount() int
- func (ys *YaraScanner) RulesDir() string
- func (ys *YaraScanner) ScanBytes(data []byte) ([]string, error)
- func (ys *YaraScanner) ScanBytesContext(ctx context.Context, data []byte) ([]string, error)
- func (ys *YaraScanner) ScanFile(path string) ([]string, error)
Constants ¶
const AnalysisReportFile = "artifact-analysis.json"
Variables ¶
var Decoder = &decoder.AbstractDecoder{ Type: types.Type_NC_File, Name: "File", Description: "A file that was transferred over the network", }
Decoder for protocol analysis and writing audit records to disk.
var ErrArtifactLimit = errors.New("artifact byte budget exceeded")
var ErrContentDecodeDisabled = errors.New("content decoding disabled by extraction policy")
Functions ¶
func BindAnalysisRunID ¶ added in v0.16.0
func BindAnalysisRunID(runID string)
func CancelAnalysis ¶ added in v0.16.0
func CancelAnalysis()
func DetectContentType ¶
DetectContentType performs enhanced MIME type detection using magic numbers Returns the MIME type and a boolean indicating if detection was accurate
func ExtensionForContentType ¶
ExtensionForContentType returns the file extension for the given MIME type.
func FinishAnalysis ¶ added in v0.16.0
func FinishAnalysis() (analysisErr, persistenceErr error)
FinishAnalysis drains accepted jobs and durably reports incomplete coverage.
func GetDedupCache ¶
func GetDedupCache() *fileDeduplicationCache
GetDedupCache returns the global deduplication cache
func GetDedupStats ¶
func GetDedupStats() dedupStats
GetDedupStats returns the current deduplication statistics
func GetMaxFileSize ¶
func GetMaxFileSize() int64
GetMaxFileSize returns the configured maximum file size
func IsProtocolEnabled ¶
IsProtocolEnabled checks if file extraction is enabled for a protocol
func IsReassemblyEnabled ¶
func IsReassemblyEnabled() bool
IsReassemblyEnabled checks if file reassembly is enabled
func ListExtractors ¶
func ListExtractors() []string
ListExtractors returns a list of all registered protocol extractors
func LogDedupStats ¶
LogDedupStats logs the current deduplication statistics
func PrepareSourceEvidence ¶ added in v0.16.11
func PrepareSourceEvidence(conv *core.ConversationInfo) error
PrepareSourceEvidence snapshots immutable transport-run qualifications once.
func ReadBody ¶ added in v0.16.0
ReadBody retains its allocation reservation until release, including partial reads.
func ReadBodyLimit ¶ added in v0.16.0
func RecordArtifactWriteError ¶ added in v0.16.0
func RecordArtifactWriteError(err error)
func RecordExtractionIssue ¶ added in v0.16.0
func RecordExtractionIssue(err error)
func RegisterExtractor ¶
func RegisterExtractor(extractor FileExtractor)
RegisterExtractor registers a file extractor for a specific protocol
func ResetDedupCache ¶
func ResetDedupCache()
ResetDedupCache resets the deduplication cache (useful for testing or new capture sessions)
func ResetGlobalYaraScanner ¶
func ResetGlobalYaraScanner()
ResetGlobalYaraScanner resets the singleton so it can be re-initialized (for testing or reconfiguration).
func SaveFileEnhanced ¶
func SaveFileEnhanced( conv *core.ConversationInfo, source, name string, err error, body []byte, encoding []string, host string, contentType string, depth int, parentFileID string, flowDirection string, protocol string, ) error
SaveFileEnhanced is an enhanced version of SaveFile with support for: - Multiple hash algorithms (MD5, SHA1, SHA256) - Better content type detection - Depth tracking for nested files - Parent file tracking - Flow direction tracking - Protocol tracking (HTTP, FTP, SMB, SMTP, IRC, etc.) - Configuration-based filtering and settings
func SaveSpoolEnhanced ¶ added in v0.16.11
func SetGlobalConfig ¶
func SetGlobalConfig(cfg *Config)
SetGlobalConfig sets the global configuration
func SetSaveFileLogger ¶
SetSaveFileLogger sets the logger for file saving operations
func ShouldComputeHash ¶
ShouldComputeHash checks if a specific hash algorithm should be computed
func ShouldExtractMimeType ¶
ShouldExtractMimeType checks if a MIME type should be extracted based on whitelist/blacklist
func ShouldUseMagicDetection ¶
func ShouldUseMagicDetection() bool
ShouldUseMagicDetection checks if magic number detection should be used
func StartAnalysis ¶ added in v0.16.0
StartAnalysis freezes extraction policy and private analyzer snapshots for one capture.
func ValidateConfig ¶ added in v0.16.0
func ValidateYaraSource ¶
ValidateYaraSource compiles YARA source to check for errors. Returns nil if valid, or the compilation error.
func WriteFileEnhanced ¶
WriteFileEnhanced writes an enhanced file record with additional fields This is an alias to WriteFile for consistency
func YaraAvailable ¶
func YaraAvailable() bool
YaraAvailable returns true when yara-x support is compiled in.
Types ¶
type AdvancedConfig ¶
type AdvancedConfig struct {
UseMagicDetection bool `yaml:"use_magic_detection"`
DecodeCompressed bool `yaml:"decode_compressed"`
DecodeBase64 bool `yaml:"decode_base64"`
MaxFilenameLength int `yaml:"max_filename_length"`
DeduplicateFiles bool `yaml:"deduplicate_files"` // Only save each unique file once based on content hash
// Security analysis options
ComputeEntropy bool `yaml:"compute_entropy"` // Calculate Shannon entropy
DetectExecutables bool `yaml:"detect_executables"` // Detect PE/ELF/Mach-O executables
DetectEmbeddedScripts bool `yaml:"detect_embedded_scripts"` // Detect embedded VBA/JS/PowerShell
EnableYaraScanning bool `yaml:"enable_yara_scanning"` // Enable YARA rule matching (requires yara rules path)
YaraRulesPath string `yaml:"yara_rules_path"` // Path to YARA rules directory
EnableMagika bool `yaml:"enable_magika"` // Enable AI-based file type classification (requires magika CLI in PATH)
MagikaAssetsDir string `yaml:"magika_assets_dir"` // Unused (Rust CLI embeds model), kept for config compatibility
MagikaModelName string `yaml:"magika_model_name"` // Unused (Rust CLI embeds model), kept for config compatibility
}
AdvancedConfig defines advanced file extraction options
type AnalysisReport ¶ added in v0.16.0
type AnalysisReport struct {
ExecutedJobs uint64 `json:"executedJobs"`
CacheHits uint64 `json:"cacheHits"`
Analyzers []AnalyzerResult `json:"analyzers"`
Version int `json:"version"`
RunID string `json:"runId"`
State string `json:"state"`
Error string `json:"error,omitempty"`
ConfigDigest string `json:"configDigest"`
Results map[string]*ArtifactAnalysis `json:"results"`
Rejected uint64 `json:"rejected"`
ExtractionIssues []string `json:"extractionIssues,omitempty"`
PersistenceFailures uint64 `json:"persistenceFailures,omitempty"`
}
type AnalyzerResult ¶ added in v0.16.0
type AnalyzerResult struct {
Version string `json:"version,omitempty"`
Engine string `json:"engine"`
State string `json:"state"`
Outcome string `json:"outcome,omitempty"`
Error string `json:"error,omitempty"`
Digest string `json:"digest"`
Matches []string `json:"matches,omitempty"`
Classification *magika.Result `json:"classification,omitempty"`
}
type ArtifactAnalysis ¶ added in v0.16.0
type ArtifactAnalysis struct {
SHA256 string `json:"sha256"`
ConfigDigest string `json:"configDigest"`
Analyzers []AnalyzerResult `json:"analyzers"`
}
type BodySpool ¶ added in v0.16.11
type BodySpool struct {
// contains filtered or unexported fields
}
type Config ¶
type Config struct {
FileExtraction FileExtractionConfig `yaml:"file_extraction"`
}
Config represents the file extraction configuration
func GetDefaultConfig ¶
func GetDefaultConfig() *Config
GetDefaultConfig returns the default configuration
func GetGlobalConfig ¶
func GetGlobalConfig() *Config
GetGlobalConfig returns the global configuration
func LoadConfig ¶
LoadConfig loads file extraction configuration from a YAML file
type ContentInfo ¶
type ContentInfo struct {
Hash string // SHA256 hash of the decoded content
DecodedContent []byte // Decompressed content
WasCompressed bool // Whether the content was compressed
CompressionType string // Compression algorithm (gzip, deflate, or empty)
CompressedSize int64 // Original compressed size
// contains filtered or unexported fields
}
ContentInfo contains information about decoded content
func ComputeContentHash ¶
func ComputeContentHash(body []byte, encoding []string) (*ContentInfo, error)
ComputeContentHash computes SHA256 hash of the content, handling all encoding types. This function decodes gzip/deflate/base64 content before hashing to ensure we hash the actual content. It also returns compression information for audit records.
func ComputeContentHashWithLimit ¶
func ComputeContentHashWithLimit(body []byte, encoding []string, limit int64) (*ContentInfo, error)
type FileAnalysis ¶
type FileAnalysis struct {
Entropy float64
MagicBytes []byte
TrueFileType string
TypeMismatch bool
IsPEExecutable bool
IsELFExecutable bool
IsMachO bool
HasEmbeddedScript bool
IsPasswordProtected bool
YaraMatches []string
IsKnownMalware bool
ThreatName string
}
FileAnalysis contains security analysis results for a file
func AnalyzeFile ¶
func AnalyzeFile(content []byte, filename string) *FileAnalysis
AnalyzeFile performs security analysis on file content Respects configuration settings for which analyses to perform
type FileExtractionConfig ¶
type FileExtractionConfig struct {
Enabled bool `yaml:"enabled"`
Protocols ProtocolsConfig `yaml:"protocols"`
SizeLimits SizeLimitsConfig `yaml:"size_limits"`
HashAlgorithms HashAlgorithmsConfig `yaml:"hash_algorithms"`
MimeTypes MimeTypesConfig `yaml:"mime_types"`
Storage StorageConfig `yaml:"storage"`
IncompleteFiles IncompleteFilesConfig `yaml:"incomplete_files"`
Reassembly ReassemblyConfig `yaml:"reassembly"`
Advanced AdvancedConfig `yaml:"advanced"`
}
FileExtractionConfig contains all settings for file extraction
type FileExtractor ¶
type FileExtractor interface {
// GetFileHandle generates a unique identifier for a file in the conversation
GetFileHandle(conv *core.ConversationInfo, isOrigin bool, depth int) string
// DescribeFile returns a human-readable description of the file
DescribeFile(handle *FileHandle) string
// ExtractFile performs the actual file extraction
ExtractFile(conv *core.ConversationInfo, data []byte, metadata FileMetadata) error
// ProtocolName returns the name of the protocol this extractor handles
ProtocolName() string
}
FileExtractor is the interface that protocol-specific extractors must implement
func GetExtractor ¶
func GetExtractor(protocol string) (FileExtractor, bool)
GetExtractor retrieves a file extractor for the given protocol
type FileHandle ¶
type FileHandle struct {
ID string
ConversationID string
Protocol string
Timestamp int64
Depth int
IsComplete bool
TotalBytes int64
SeenBytes int64
MissingBytes int64
ParentFileID string
}
FileHandle represents a unique file being extracted from network traffic
type FileHashes ¶
FileHashes contains multiple hash values for a file
func ComputeFileHashes ¶
func ComputeFileHashes(filepath string) (FileHashes, error)
ComputeFileHashes computes hashes for an existing file on disk
func ComputeHashes ¶
func ComputeHashes(data []byte) FileHashes
ComputeHashes calculates MD5, SHA1, and SHA256 hashes for the given data
type FileMetadata ¶
type FileMetadata struct {
Protocol string
ParentFileID string
Depth int
ExtractionError error
Timestamp int64
// Network context
ConnectionUID string
FlowDirection string // "client_to_server" or "server_to_client"
// Protocol-specific context
HTTPMethod string // For HTTP files
HTTPStatusCode int
HTTPURL string
FTPCommand string // RETR/STOR
SMBPath string
// Content information
Filename string
ContentType string
Host string
Encoding []string
}
FileMetadata contains contextual information about an extracted file
type FileReassembler ¶
type FileReassembler struct {
// contains filtered or unexported fields
}
FileReassembler handles reassembly of files that may arrive out-of-order or with missing chunks (e.g., due to packet loss)
func NewFileReassembler ¶
func NewFileReassembler(totalSize int64) *FileReassembler
NewFileReassembler creates a new file reassembler
func (*FileReassembler) AddChunk ¶
func (fr *FileReassembler) AddChunk(offset int64, data []byte)
AddChunk adds a chunk of data at the specified offset
func (*FileReassembler) GetMissingBytes ¶
func (fr *FileReassembler) GetMissingBytes() int64
GetMissingBytes returns the number of missing bytes
func (*FileReassembler) GetSeenBytes ¶
func (fr *FileReassembler) GetSeenBytes() int64
GetSeenBytes returns the number of bytes received
func (*FileReassembler) IsComplete ¶
func (fr *FileReassembler) IsComplete() bool
IsComplete checks if all bytes have been received and are contiguous
func (*FileReassembler) Reassemble ¶
func (fr *FileReassembler) Reassemble(includeMissing bool) ([]byte, error)
Reassemble reconstructs the file from chunks If includeMissing is false, the function returns an error if data is missing If includeMissing is true, gaps will be filled with zeros (sparse file)
type HashAlgorithmsConfig ¶
type HashAlgorithmsConfig struct {
MD5 bool `yaml:"md5"`
SHA1 bool `yaml:"sha1"`
SHA256 bool `yaml:"sha256"`
}
HashAlgorithmsConfig defines which hash algorithms to compute
type IncompleteFilesConfig ¶
type IncompleteFilesConfig struct {
WriteIncomplete bool `yaml:"write_incomplete"`
IncompletePrefix string `yaml:"incomplete_prefix"`
}
IncompleteFilesConfig defines handling of incomplete files
type MIMESignature ¶
MIMESignature represents a file signature for magic number detection
type MimeTypesConfig ¶
type MimeTypesConfig struct {
Whitelist []string `yaml:"whitelist"`
Blacklist []string `yaml:"blacklist"`
}
MimeTypesConfig defines MIME type filtering
type ProtocolsConfig ¶
type ProtocolsConfig struct {
HTTP bool `yaml:"http"`
FTP bool `yaml:"ftp"`
SMTP bool `yaml:"smtp"`
POP3 bool `yaml:"pop3"`
IMAP bool `yaml:"imap"`
SMB bool `yaml:"smb"`
IRC bool `yaml:"irc"`
}
ProtocolsConfig defines which protocols have file extraction enabled
type ReassemblyConfig ¶
type ReassemblyConfig struct {
Enabled bool `yaml:"enabled"`
AllowSparseFiles bool `yaml:"allow_sparse_files"`
MaxBufferSize int64 `yaml:"max_buffer_size"`
}
ReassemblyConfig defines file reassembly settings
type SizeLimitsConfig ¶
type SizeLimitsConfig struct {
MaxFileSize int64 `yaml:"max_file_size"`
IncludeMissingBytes bool `yaml:"include_missing_bytes"`
MaxFilesPerSession int `yaml:"max_files_per_session"`
MaxInflightBytes int64 `yaml:"max_inflight_bytes"`
MaxScratchBytes int64 `yaml:"max_scratch_bytes"`
}
SizeLimitsConfig defines size limits for file extraction
type StorageConfig ¶
type StorageConfig struct {
OrganizeByMime bool `yaml:"organize_by_mime"`
OrganizeByProtocol bool `yaml:"organize_by_protocol"`
OrganizeByDate bool `yaml:"organize_by_date"`
CompressStoredFiles bool `yaml:"compress_stored_files"`
IncludeConnectionID bool `yaml:"include_connection_id"`
}
StorageConfig defines how extracted files are organized
type StreamingHashWriter ¶
type StreamingHashWriter struct {
// contains filtered or unexported fields
}
StreamingHashWriter computes multiple hashes while writing to a file This avoids having to re-read the file contents after writing
func NewStreamingHashWriter ¶
func NewStreamingHashWriter(file *os.File) *StreamingHashWriter
NewStreamingHashWriter creates a new streaming hash writer
func (*StreamingHashWriter) Close ¶
func (w *StreamingHashWriter) Close() error
Close closes the underlying file
func (*StreamingHashWriter) GetHashes ¶
func (w *StreamingHashWriter) GetHashes() FileHashes
GetHashes returns the computed hashes
type YaraScanner ¶
type YaraScanner struct {
// contains filtered or unexported fields
}
YaraScanner provides thread-safe YARA rule scanning using yara-x.
func GetGlobalYaraScanner ¶
func GetGlobalYaraScanner() *YaraScanner
GetGlobalYaraScanner returns the global YARA scanner, or nil if not initialized.
func InitGlobalYaraScanner ¶
func InitGlobalYaraScanner(rulesDir string) (*YaraScanner, error)
InitGlobalYaraScanner initializes the global YARA scanner with the given rules directory. Safe to call multiple times; only the first call takes effect.
func NewYaraScanner ¶
func NewYaraScanner(rulesDir string) (*YaraScanner, error)
NewYaraScanner creates a scanner by compiling all .yar/.yara files from rulesDir.
func (*YaraScanner) Digest ¶ added in v0.16.0
func (ys *YaraScanner) Digest() string
func (*YaraScanner) LastLoad ¶
func (ys *YaraScanner) LastLoad() time.Time
LastLoad returns the time the rules were last compiled.
func (*YaraScanner) Reload ¶
func (ys *YaraScanner) Reload() error
Reload recompiles all enabled YARA rules from the rules directory.
func (*YaraScanner) RuleCount ¶
func (ys *YaraScanner) RuleCount() int
RuleCount returns the number of compiled rules, or 0 if none loaded.
func (*YaraScanner) RulesDir ¶
func (ys *YaraScanner) RulesDir() string
RulesDir returns the configured rules directory.
func (*YaraScanner) ScanBytes ¶
func (ys *YaraScanner) ScanBytes(data []byte) ([]string, error)
ScanBytes scans byte content against loaded YARA rules and returns matched rule identifiers.