scanner

package
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2025 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ASTFeatureExtractor

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

ASTFeatureExtractor extracts advanced features from AST analysis

func NewASTFeatureExtractor

func NewASTFeatureExtractor() *ASTFeatureExtractor

NewASTFeatureExtractor creates a new AST feature extractor

func (*ASTFeatureExtractor) ExtractASTFeatures

func (afe *ASTFeatureExtractor) ExtractASTFeatures(content []byte, filePath string, finding types.Finding) (*ASTFeatures, error)

ExtractASTFeatures extracts AST-based features from source code

type ASTFeatures

type ASTFeatures struct {
	// Structural features
	FunctionCallDepth    int `json:"function_call_depth"`
	NestedBlockDepth     int `json:"nested_block_depth"`
	VariableDeclarations int `json:"variable_declarations"`
	FunctionDefinitions  int `json:"function_definitions"`
	ClassDefinitions     int `json:"class_definitions"`
	ImportStatements     int `json:"import_statements"`

	// Crypto-specific AST features
	CryptoFunctionCalls int `json:"crypto_function_calls"`
	CryptoVariables     int `json:"crypto_variables"`
	CryptoConstants     int `json:"crypto_constants"`
	CryptoClassMethods  int `json:"crypto_class_methods"`

	// Code complexity
	CyclomaticComplexity int     `json:"cyclomatic_complexity"`
	HalsteadComplexity   float64 `json:"halstead_complexity"`
	LinesOfCode          int     `json:"lines_of_code"`

	// Pattern-specific features
	HasCryptoLoop        bool `json:"has_crypto_loop"`
	HasCryptoConditional bool `json:"has_crypto_conditional"`
	HasCryptoTryCatch    bool `json:"has_crypto_try_catch"`
	HasCryptoInterface   bool `json:"has_crypto_interface"`

	// Language-specific features
	Language    string `json:"language"`
	HasGenerics bool   `json:"has_generics"`
	HasPointers bool   `json:"has_pointers"`
	HasLambdas  bool   `json:"has_lambdas"`

	// Context features
	InCryptoNamespace bool `json:"in_crypto_namespace"`
	InSecurityContext bool `json:"in_security_context"`
	NearCryptoImports bool `json:"near_crypto_imports"`

	// Quality indicators
	HasDocumentation   bool `json:"has_documentation"`
	HasTypeAnnotations bool `json:"has_type_annotations"`
	HasErrorHandling   bool `json:"has_error_handling"`
}

ASTFeatures represents extracted AST-based features

type ASTMatch

type ASTMatch struct {
	Line    int
	Column  int
	Context string
}

ASTMatch represents a match from AST scanning

type ASTPattern

type ASTPattern struct {
	ID          string
	Language    string
	Query       string
	Category    string
	Severity    string
	Description string
	Intent      string   // What this pattern is trying to detect
	Variables   []string // Variables to track
}

ASTPattern represents a Tree-sitter pattern for L1 analysis

type ASTRule

type ASTRule struct {
	ID          string            `yaml:"id"`
	Name        string            `yaml:"name"`
	Description string            `yaml:"description"`
	Language    string            `yaml:"language"`
	Pattern     string            `yaml:"pattern"`
	Message     string            `yaml:"message"`
	Severity    string            `yaml:"severity"`
	CryptoType  string            `yaml:"crypto_type"`
	Algorithm   string            `yaml:"algorithm"`
	Suggestion  string            `yaml:"suggestion"`
	References  []string          `yaml:"references"`
	Metadata    map[string]string `yaml:"metadata"`
	Enabled     bool              `yaml:"enabled"`
}

ASTRule represents an AST-based detection rule

type AccuracyStats

type AccuracyStats struct {
	TruePositives  int64
	FalsePositives int64
	TrueNegatives  int64
	FalseNegatives int64
	Precision      float64
	Recall         float64
	F1Score        float64
	Confidence     float64
}

AccuracyStats tracks detection accuracy over time

type BenchmarkReport

type BenchmarkReport struct {
	OverallMetrics  *PerformanceMetric        `json:"overall_metrics"`
	StageBreakdown  map[string]*StageMetric   `json:"stage_breakdown"`
	AccuracyMetrics map[string]*AccuracyStats `json:"accuracy_metrics"`
	Recommendations []string                  `json:"recommendations"`
	GeneratedAt     time.Time                 `json:"generated_at"`
	DurationSeconds float64                   `json:"total_duration_seconds"`
}

BenchmarkReport provides comprehensive performance analysis

type CargoAuditScanner

type CargoAuditScanner struct{}

CargoAuditScanner scans Rust projects using cargo audit

func (*CargoAuditScanner) CanScan

func (s *CargoAuditScanner) CanScan(projectPath string) bool

func (*CargoAuditScanner) Name

func (s *CargoAuditScanner) Name() string

func (*CargoAuditScanner) RequiresExternal

func (s *CargoAuditScanner) RequiresExternal() bool

func (*CargoAuditScanner) Scan

func (s *CargoAuditScanner) Scan(ctx context.Context, projectPath string) (*DependencyScanResult, error)

type CodeEmbedder

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

CodeEmbedder creates vector embeddings from code patterns

func NewCodeEmbedder

func NewCodeEmbedder(embeddingSize int) *CodeEmbedder

NewCodeEmbedder creates a new code embedder

func (*CodeEmbedder) ComputeSimilarity

func (ce *CodeEmbedder) ComputeSimilarity(embedding1, embedding2 *CodeEmbedding) float64

ComputeSimilarity computes cosine similarity between two embeddings

func (*CodeEmbedder) CreateEmbedding

func (ce *CodeEmbedder) CreateEmbedding(finding types.Finding, astFeatures *ASTFeatures, fileContent []byte) (*CodeEmbedding, error)

CreateEmbedding creates a vector embedding from a code finding

func (*CodeEmbedder) DeserializeEmbedding

func (ce *CodeEmbedder) DeserializeEmbedding(data []byte) (*CodeEmbedding, error)

DeserializeEmbedding deserializes embedding from JSON

func (*CodeEmbedder) SerializeEmbedding

func (ce *CodeEmbedder) SerializeEmbedding(embedding *CodeEmbedding) ([]byte, error)

SerializeEmbedding serializes embedding to JSON

type CodeEmbedding

type CodeEmbedding struct {
	Vector           []float64              `json:"vector"`
	Tokens           []string               `json:"tokens"`
	CryptoScore      float64                `json:"crypto_score"`
	LanguageFeatures map[string]float64     `json:"language_features"`
	ContextFeatures  map[string]float64     `json:"context_features"`
	SemanticFeatures map[string]float64     `json:"semantic_features"`
	Metadata         map[string]interface{} `json:"metadata"`
}

CodeEmbedding represents a vector embedding of code

type Config

type Config struct {
	Path         string
	OutputFormat string
	OutputFile   string
	RulesPath    string
	Verbose      bool
}

Config holds scan configuration

type ContextFeature

type ContextFeature struct {
	Name        string
	Weight      float64
	Description string
	Extractor   func(string, *FileContext) float64
}

ContextFeature represents features used for ML confidence scoring

type CryptoHotspot

type CryptoHotspot struct {
	Location   types.Location
	Type       string // "key_generation", "signing", "encryption", etc.
	Confidence float64
	Variables  []Variable
	DataFlows  []DataFlow
}

CryptoHotspot represents a potential crypto usage area

type CryptoSinkInstance

type CryptoSinkInstance struct {
	Finding  types.Finding
	Location types.Location
	SinkType string
}

type DataFlow

type DataFlow struct {
	Source     types.Location
	Sink       types.Location
	TaintLevel string
	FlowType   string
	Confidence float64
}

DataFlow represents data flow between crypto operations

type DataFlowAnalyzer

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

DataFlowAnalyzer implements L2 stage - data flow and taint analysis

func NewDataFlowAnalyzer

func NewDataFlowAnalyzer(cfg *config.Config) *DataFlowAnalyzer

NewDataFlowAnalyzer creates a new L2 data flow analyzer

func (*DataFlowAnalyzer) AnalyzeFlows

func (da *DataFlowAnalyzer) AnalyzeFlows(dataFlows []DataFlow, fileCtx *FileContext) []types.Finding

AnalyzeFlows analyzes data flows for security violations

func (*DataFlowAnalyzer) TraceDataFlows

func (da *DataFlowAnalyzer) TraceDataFlows(fileCtx *FileContext, l1Findings []types.Finding) []DataFlow

TraceDataFlows traces data flows from L1 findings

type Dependency

type Dependency struct {
	Name    string
	Version string
	Type    string // "crypto", "utility", "framework"
}

Dependency represents project dependencies for context

type DependencyInfo

type DependencyInfo struct {
	Name            string          `json:"name"`
	Version         string          `json:"version"`
	License         string          `json:"license,omitempty"`
	Vulnerabilities []Vulnerability `json:"vulnerabilities,omitempty"`
	IsDevDependency bool            `json:"is_dev_dependency"`
}

DependencyInfo represents information about a dependency

type DependencyScanConfig

type DependencyScanConfig struct {
	UseExternalTools bool   `json:"use_external_tools"`
	SnykToken        string `json:"snyk_token,omitempty"`
	TimeoutMinutes   int    `json:"timeout_minutes"`
	ScanDevDeps      bool   `json:"scan_dev_deps"`
}

DependencyScanConfig configuration for dependency scanning

type DependencyScanResult

type DependencyScanResult struct {
	PackageManager      string           `json:"package_manager"`
	TotalDependencies   int              `json:"total_dependencies"`
	Dependencies        []DependencyInfo `json:"dependencies"`
	Vulnerabilities     []Vulnerability  `json:"vulnerabilities"`
	ScanTime            time.Time        `json:"scan_time"`
	ScanDurationSeconds float64          `json:"scan_duration_seconds"`
}

DependencyScanResult contains the results of dependency scanning

type DependencyScanner

type DependencyScanner interface {
	Name() string
	CanScan(projectPath string) bool
	Scan(ctx context.Context, projectPath string) (*DependencyScanResult, error)
	RequiresExternal() bool // Whether this scanner needs external tools
}

DependencyScanner interface for different package managers

type DependencyScannerManager

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

DependencyScannerManager manages multiple dependency scanners

func NewDependencyScannerManager

func NewDependencyScannerManager(config *DependencyScanConfig) *DependencyScannerManager

NewDependencyScannerManager creates a new dependency scanner manager

func (*DependencyScannerManager) ScanProject

func (dsm *DependencyScannerManager) ScanProject(ctx context.Context, projectPath string) ([]*DependencyScanResult, error)

ScanProject scans a project for dependency vulnerabilities

type DetectionBenchmark

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

DetectionBenchmark tracks performance and accuracy metrics

func NewDetectionBenchmark

func NewDetectionBenchmark() *DetectionBenchmark

NewDetectionBenchmark creates a new benchmarking system

func (*DetectionBenchmark) GenerateReport

func (db *DetectionBenchmark) GenerateReport() *BenchmarkReport

GenerateReport creates a comprehensive benchmark report

func (*DetectionBenchmark) GetBottlenecks

func (db *DetectionBenchmark) GetBottlenecks() map[string]string

GetBottlenecks identifies performance bottlenecks

func (*DetectionBenchmark) GetTopPerformers

func (db *DetectionBenchmark) GetTopPerformers(limit int) []string

GetTopPerformers returns files/categories with best performance

func (*DetectionBenchmark) RecordAnalysis

func (db *DetectionBenchmark) RecordAnalysis(filePath string, stageResults []LayeredResult, finalFindings []types.Finding)

RecordAnalysis records analysis performance and results

type DetectionStage

type DetectionStage int

DetectionStage represents the analysis pipeline stages

const (
	StageL0Regex    DetectionStage = iota // Fast regex pre-filter
	StageL1AST                            // Structured AST analysis
	StageL2DataFlow                       // Data flow & taint analysis
)

type Detector

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

Detector is the main scanning engine

func NewDetector

func NewDetector(cfg *config.Config) *Detector

NewDetector creates a new detector instance

func (*Detector) CollectFiles

func (d *Detector) CollectFiles(path string) ([]string, error)

CollectFiles recursively collects files to scan

func (*Detector) EnhancedScan

func (d *Detector) EnhancedScan(scanConfig *Config) (*EnhancedScanResult, error)

Enhanced scanning command that integrates both crypto and dependency scanning

func (*Detector) GenerateSummary

func (d *Detector) GenerateSummary(files []string, findings []types.Finding, duration time.Duration) types.ScanSummary

GenerateSummary generates a summary of the scan results

func (*Detector) GetEnhancedClassifier

func (d *Detector) GetEnhancedClassifier() *classifier.EnhancedClassifier

GetEnhancedClassifier returns the enhanced classifier instance

func (*Detector) GetRuleStatistics

func (d *Detector) GetRuleStatistics() map[string]interface{}

GetRuleStatistics returns rule statistics

func (*Detector) GetRulesCount

func (d *Detector) GetRulesCount() int

GetRulesCount returns the number of loaded rules

func (*Detector) LoadRules

func (d *Detector) LoadRules(rulesPath string) error

LoadRules loads rules from the specified path

func (*Detector) Scan

func (d *Detector) Scan(scanConfig *Config) error

Scan performs the main scanning operation

func (*Detector) ScanFiles

func (d *Detector) ScanFiles(files []string, verbose bool) ([]types.Finding, []string)

ScanFiles scans multiple files concurrently using a worker pool

type EnhancedFinding

type EnhancedFinding struct {
	types.Finding
	ASTFeatures   *ASTFeatures       `json:"ast_features,omitempty"`
	CodeEmbedding *CodeEmbedding     `json:"code_embedding,omitempty"`
	MLFeatures    map[string]float64 `json:"ml_features,omitempty"`
	EnhancedScore float64            `json:"enhanced_score"`
	FeatureVector []float64          `json:"feature_vector,omitempty"`
}

EnhancedFinding extends the basic finding with advanced ML features

type EnhancedMLDetector

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

EnhancedMLDetector combines AST analysis, code embeddings, and ML confidence scoring

func NewEnhancedMLDetector

func NewEnhancedMLDetector(cfg *config.Config) *EnhancedMLDetector

NewEnhancedMLDetector creates a new enhanced ML detector

func (*EnhancedMLDetector) ProcessFindings

func (emd *EnhancedMLDetector) ProcessFindings(findings []types.Finding, fileCtx *FileContext) ([]*EnhancedFinding, error)

ProcessFindings enhances findings with advanced ML features

func (*EnhancedMLDetector) SaveEnhancedFindings

func (emd *EnhancedMLDetector) SaveEnhancedFindings(findings []*EnhancedFinding, outputPath string) error

SaveEnhancedFindings saves enhanced findings to JSON

type EnhancedScanResult

type EnhancedScanResult struct {
	ProjectInfo       *ProjectInfo            `json:"project_info"`
	CryptoFindings    []types.Finding         `json:"crypto_findings"`
	CryptoErrors      []string                `json:"crypto_errors,omitempty"`
	DependencyResults []*DependencyScanResult `json:"dependency_results,omitempty"`
	ScanTime          time.Time               `json:"scan_time"`
	DurationSeconds   float64                 `json:"duration_seconds"`
}

EnhancedScanResult contains results from both crypto and dependency scanning

func (*EnhancedScanResult) GetVulnerabilitySummary

func (esr *EnhancedScanResult) GetVulnerabilitySummary() map[string]int

GetVulnerabilitySummary returns a summary of all vulnerabilities found

type ExclusionPattern

type ExclusionPattern struct {
	Pattern  string `json:"pattern"`
	Priority int    `json:"priority"`
	Reason   string `json:"reason"`
}

ExclusionPattern defines a pattern for excluding files from scanning

type FileContext

type FileContext struct {
	FilePath       string
	Content        []byte
	Language       string
	IsVendored     bool
	IsGenerated    bool
	IsTest         bool
	ProjectContext *ProjectContext
	Suppressions   []Suppression
	CryptoHotspots []CryptoHotspot
}

FileContext provides rich context for multi-stage analysis

type FlowRule

type FlowRule struct {
	ID          string
	SourceType  string
	SinkType    string
	Severity    string
	Message     string
	Description string
}

FlowRule defines data flow security rules

type GoVulnScanner

type GoVulnScanner struct{}

GoVulnScanner scans Go projects using govulncheck

func (*GoVulnScanner) CanScan

func (s *GoVulnScanner) CanScan(projectPath string) bool

func (*GoVulnScanner) Name

func (s *GoVulnScanner) Name() string

func (*GoVulnScanner) RequiresExternal

func (s *GoVulnScanner) RequiresExternal() bool

func (*GoVulnScanner) Scan

func (s *GoVulnScanner) Scan(ctx context.Context, projectPath string) (*DependencyScanResult, error)

type LanguageInfo

type LanguageInfo struct {
	Language    string   `json:"language"`
	Files       []string `json:"files"`
	Confidence  float64  `json:"confidence"`
	PackageFile string   `json:"package_file,omitempty"`
}

LanguageInfo represents detected programming language information

type LayeredDetector

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

LayeredDetector implements a multi-stage crypto detection pipeline

func NewLayeredDetector

func NewLayeredDetector(cfg *config.Config) *LayeredDetector

NewLayeredDetector creates a new layered detection system

func (*LayeredDetector) AnalyzeFile

func (ld *LayeredDetector) AnalyzeFile(ctx context.Context, fileCtx *FileContext) (*LayeredResult, error)

AnalyzeFile performs layered analysis on a single file

func (*LayeredDetector) LoadRules

func (ld *LayeredDetector) LoadRules(rulesPath string) error

LoadRules loads crypto detection rules into the layered detector

type LayeredResult

type LayeredResult struct {
	Stage                 DetectionStage  `json:"stage"`
	Findings              []types.Finding `json:"findings"`
	ConfidenceScore       float64         `json:"confidence_score"`
	ProcessingTimeSeconds float64         `json:"processing_time_seconds"`
	Metadata              map[string]any  `json:"metadata"`
	Suppressions          []string        `json:"suppressions,omitempty"`
}

LayeredResult contains results from all detection stages

type MLConfidenceScorer

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

MLConfidenceScorer implements ML-based confidence scoring and ranking

func NewMLConfidenceScorer

func NewMLConfidenceScorer(cfg *config.Config) *MLConfidenceScorer

NewMLConfidenceScorer creates a new ML confidence scorer

func (*MLConfidenceScorer) AutoDetectLibraryAnalysisMode

func (ml *MLConfidenceScorer) AutoDetectLibraryAnalysisMode(fileCtx *FileContext)

AutoDetectLibraryAnalysisMode automatically detects if we're analyzing a crypto library

func (*MLConfidenceScorer) GetConfidenceDistribution

func (ml *MLConfidenceScorer) GetConfidenceDistribution(findings []types.Finding) map[string]int

GetConfidenceDistribution returns distribution of confidence scores

func (*MLConfidenceScorer) GetTopFindings

func (ml *MLConfidenceScorer) GetTopFindings(findings []types.Finding, limit int) []types.Finding

GetTopFindings returns the highest confidence findings

func (*MLConfidenceScorer) ScoreFindings

func (ml *MLConfidenceScorer) ScoreFindings(findings []types.Finding, fileCtx *FileContext) []types.Finding

ScoreFindings applies ML-based confidence scoring to findings

func (*MLConfidenceScorer) SetLibraryAnalysisMode

func (ml *MLConfidenceScorer) SetLibraryAnalysisMode(enabled bool, libraryName string)

SetLibraryAnalysisMode configures the scorer for crypto library analysis

type MLEnhancedDetector

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

MLEnhancedDetector wraps a LayeredDetector with ML enhancements

func NewMLEnhancedDetector

func NewMLEnhancedDetector(baseDetector *LayeredDetector) *MLEnhancedDetector

NewMLEnhancedDetector creates a new ML-enhanced detector

func (*MLEnhancedDetector) AnalyzeFile

func (d *MLEnhancedDetector) AnalyzeFile(ctx context.Context, fileCtx *FileContext) (*LayeredResult, error)

AnalyzeFile analyzes a file and enhances findings with ML predictions

func (*MLEnhancedDetector) CollectFiles

func (d *MLEnhancedDetector) CollectFiles(scanPath string) ([]string, error)

CollectFiles collects files to scan (delegates to base detector)

func (*MLEnhancedDetector) EnableML

func (d *MLEnhancedDetector) EnableML(enabled bool)

EnableML enables or disables ML enhancements

func (*MLEnhancedDetector) LoadRules

func (d *MLEnhancedDetector) LoadRules(rulesPath string) error

LoadRules loads detection rules (delegates to base detector)

type MLEnhancedDetectorConfig

type MLEnhancedDetectorConfig struct {
	EnableML               bool    `yaml:"enable_ml"`
	FalsePositiveThreshold float64 `yaml:"false_positive_threshold"`
	ConfidenceBoostFactor  float64 `yaml:"confidence_boost_factor"`
	ConfidenceReduceFactor float64 `yaml:"confidence_reduce_factor"`
	AdjustSeverity         bool    `yaml:"adjust_severity"`
}

MLEnhancedDetectorConfig holds configuration for ML enhancements

func DefaultMLEnhancedDetectorConfig

func DefaultMLEnhancedDetectorConfig() MLEnhancedDetectorConfig

DefaultMLEnhancedDetectorConfig returns default configuration

type MLPrediction

type MLPrediction struct {
	Confidence   float64
	Features     map[string]float64
	Prediction   string
	ModelVersion string
	Timestamp    time.Time
}

MLPrediction represents a machine learning prediction

type NPMAuditScanner

type NPMAuditScanner struct{}

NPMAuditScanner scans Node.js projects using npm audit

func (*NPMAuditScanner) CanScan

func (s *NPMAuditScanner) CanScan(projectPath string) bool

func (*NPMAuditScanner) Name

func (s *NPMAuditScanner) Name() string

func (*NPMAuditScanner) RequiresExternal

func (s *NPMAuditScanner) RequiresExternal() bool

func (*NPMAuditScanner) Scan

func (s *NPMAuditScanner) Scan(ctx context.Context, projectPath string) (*DependencyScanResult, error)

type PatternMetadata

type PatternMetadata struct {
	RuleID      string
	Category    string
	Priority    int
	Languages   []string
	Description string
	FastPath    bool // Whether this pattern is optimized for speed
}

PatternMetadata contains metadata for L0 patterns

type PerformanceMetric

type PerformanceMetric struct {
	TotalCalls        int64
	TotalDurationSecs float64
	MinDurationSecs   float64
	MaxDurationSecs   float64
	AvgDurationSecs   float64
	FilesProcessed    int64
	BytesProcessed    int64
	ErrorCount        int64
	StageMetrics      map[DetectionStage]*StageMetric
}

PerformanceMetric tracks timing and resource usage

type PipSafetyScanner

type PipSafetyScanner struct{}

PipSafetyScanner scans Python projects using safety

func (*PipSafetyScanner) CanScan

func (s *PipSafetyScanner) CanScan(projectPath string) bool

func (*PipSafetyScanner) Name

func (s *PipSafetyScanner) Name() string

func (*PipSafetyScanner) RequiresExternal

func (s *PipSafetyScanner) RequiresExternal() bool

func (*PipSafetyScanner) Scan

func (s *PipSafetyScanner) Scan(ctx context.Context, projectPath string) (*DependencyScanResult, error)

type ProjectContext

type ProjectContext struct {
	RootPath        string
	Language        string
	Dependencies    []Dependency
	CryptoLibraries []string
	SecurityLevel   string
}

ProjectContext provides project-wide analysis context

type ProjectInfo

type ProjectInfo struct {
	Languages         []LanguageInfo `json:"languages"`
	PackageManagers   []string       `json:"package_managers"`
	SourceDirectories []string       `json:"source_directories"`
	ExcludedPaths     []string       `json:"excluded_paths"`
}

ProjectInfo contains detected project structure information

type RegexPreFilter

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

RegexPreFilter implements L0 stage - blazing fast regex pre-filtering

func NewRegexPreFilter

func NewRegexPreFilter(cfg *config.Config) *RegexPreFilter

NewRegexPreFilter creates a new L0 regex pre-filter

func (*RegexPreFilter) LoadRules

func (rf *RegexPreFilter) LoadRules(rulesPath string) error

LoadRules loads regex rules from the RuleEngine

func (*RegexPreFilter) ScanContent

func (rf *RegexPreFilter) ScanContent(content []byte, filePath, language string) []types.Finding

ScanContent performs L0 regex scanning on file content

type RegexRule

type RegexRule struct {
	ID          string            `yaml:"id"`
	Name        string            `yaml:"name"`
	Description string            `yaml:"description"`
	Pattern     string            `yaml:"pattern"`
	Regex       *regexp.Regexp    `yaml:"-"`
	Message     string            `yaml:"message"`
	Severity    string            `yaml:"severity"`
	CryptoType  string            `yaml:"crypto_type"`
	Algorithm   string            `yaml:"algorithm"`
	Suggestion  string            `yaml:"suggestion"`
	References  []string          `yaml:"references"`
	Metadata    map[string]string `yaml:"metadata"`
	Enabled     bool              `yaml:"enabled"`
	Languages   []string          `yaml:"languages"`
}

RegexRule represents a regex-based detection rule

type RuleEngine

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

RuleEngine manages detection rules

func NewRuleEngine

func NewRuleEngine(cfg *config.Config) *RuleEngine

NewRuleEngine creates a new rule engine

func (*RuleEngine) Count

func (re *RuleEngine) Count() int

Count returns the total number of loaded rules

func (*RuleEngine) GetASTRules

func (re *RuleEngine) GetASTRules(language string) []ASTRule

GetASTRules returns AST rules for a specific language

func (*RuleEngine) GetRegexRules

func (re *RuleEngine) GetRegexRules() []RegexRule

GetRegexRules returns all regex rules

func (*RuleEngine) GetRuleByID

func (re *RuleEngine) GetRuleByID(ruleID string) (interface{}, bool)

GetRuleByID returns a rule by its ID

func (*RuleEngine) GetRuleStatistics

func (re *RuleEngine) GetRuleStatistics() map[string]interface{}

GetRuleStatistics returns statistics about loaded rules

func (*RuleEngine) LoadRules

func (re *RuleEngine) LoadRules(rulesPath string) error

LoadRules loads rules from the specified path

func (*RuleEngine) ValidateRules

func (re *RuleEngine) ValidateRules() []error

ValidateRules validates all loaded rules

type RuleSet

type RuleSet struct {
	Version    string      `yaml:"version"`
	Name       string      `yaml:"name"`
	Author     string      `yaml:"author"`
	ASTRules   []ASTRule   `yaml:"ast_rules"`
	RegexRules []RegexRule `yaml:"regex_rules"`
}

RuleSet represents a collection of rules

type Sanitizer

type Sanitizer struct {
	ID            string
	Pattern       string
	Effectiveness float64 // 0.0 to 1.0
	Description   string
}

Sanitizer represents data sanitization operations

type SnykScanner

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

SnykScanner scans using Snyk API (external tool)

func (*SnykScanner) CanScan

func (s *SnykScanner) CanScan(projectPath string) bool

func (*SnykScanner) Name

func (s *SnykScanner) Name() string

func (*SnykScanner) RequiresExternal

func (s *SnykScanner) RequiresExternal() bool

func (*SnykScanner) Scan

func (s *SnykScanner) Scan(ctx context.Context, projectPath string) (*DependencyScanResult, error)

type SourceDetector

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

SourceDetector intelligently detects source code vs. build artifacts

func NewSourceDetector

func NewSourceDetector(rootPath string) *SourceDetector

NewSourceDetector creates a new source detector

func (*SourceDetector) DetectProject

func (sd *SourceDetector) DetectProject() (*ProjectInfo, error)

DetectProject analyzes the project structure and programming languages

func (*SourceDetector) GetEnhancedIgnorePatterns

func (sd *SourceDetector) GetEnhancedIgnorePatterns() []string

GetEnhancedIgnorePatterns returns ignore patterns based on detected project structure

func (*SourceDetector) GetSourceCodePaths

func (sd *SourceDetector) GetSourceCodePaths() []string

GetSourceCodePaths returns paths that likely contain source code

type StageMetric

type StageMetric struct {
	CallCount       int64
	DurationSeconds float64
	FindingsCount   int64
	SuccessRate     float64
}

StageMetric tracks metrics for each detection stage

type StructuredAnalyzer

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

StructuredAnalyzer implements L1 stage - AST-based structured analysis

func NewStructuredAnalyzer

func NewStructuredAnalyzer(cfg *config.Config) *StructuredAnalyzer

NewStructuredAnalyzer creates a new L1 structured analyzer

func (*StructuredAnalyzer) AnalyzeHotspots

func (sa *StructuredAnalyzer) AnalyzeHotspots(fileCtx *FileContext, hotspots []CryptoHotspot) []types.Finding

AnalyzeHotspots performs detailed AST analysis on identified hotspots

func (*StructuredAnalyzer) IdentifyHotspots

func (sa *StructuredAnalyzer) IdentifyHotspots(fileCtx *FileContext, l0Findings []types.Finding) []CryptoHotspot

IdentifyHotspots analyzes L0 findings to identify crypto hotspots

type Suppression

type Suppression struct {
	RuleID   string
	Location types.Location
	Reason   string
	Scope    string // "line", "block", "file"
}

Suppression represents inline code suppressions

type TaintSink

type TaintSink struct {
	ID          string
	Pattern     string
	Severity    string
	Description string
	Languages   []string
}

TaintSink represents a sensitive operation that should not receive tainted data

type TaintSource

type TaintSource struct {
	ID          string
	Pattern     string
	TaintLevel  string // "high", "medium", "low"
	Description string
	Languages   []string
}

TaintSource represents a source of potentially unsafe data

type TaintSourceInstance

type TaintSourceInstance struct {
	Source     TaintSource
	Location   types.Location
	TaintLevel string
}

type Variable

type Variable struct {
	Name          string
	Type          string
	Scope         string
	Location      types.Location
	CryptoContext map[string]any
}

Variable tracks crypto-relevant variables through analysis

type Vulnerability

type Vulnerability struct {
	ID          string   `json:"id"`
	Title       string   `json:"title"`
	Description string   `json:"description"`
	Severity    string   `json:"severity"`
	CVSS        float64  `json:"cvss,omitempty"`
	CVE         []string `json:"cve,omitempty"`
	CWE         []string `json:"cwe,omitempty"`
	References  []string `json:"references,omitempty"`
	Package     string   `json:"package"`
	Version     string   `json:"version"`
	FixedIn     string   `json:"fixed_in,omitempty"`
}

Vulnerability represents a security vulnerability in a dependency

Jump to

Keyboard shortcuts

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