malware

package
v1.3.7 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdjustSeverity added in v0.9.95

func AdjustSeverity(finding *Finding, webRoot WebRoot)

AdjustSeverity modifies finding severity based on file location context.

func InstallYara added in v0.9.100

func InstallYara() error

InstallYara attempts to install the yara package on the system. Detects the package manager (apt, yum, dnf, apk) and installs yara. Returns nil on success, error on failure.

func QuarantineFile added in v0.9.100

func QuarantineFile(filePath string) (string, error)

QuarantineFile moves a malicious file to a quarantine directory. The file is renamed with metadata to allow restoration. Returns the quarantine path or error.

func RestoreFile added in v0.9.100

func RestoreFile(quarantinePath string) (string, error)

RestoreFile moves a quarantined file back to its original location.

Types

type AllowList added in v0.9.95

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

AllowList manages false positive prevention: 1. Framework core checksums (WordPress, etc.) 2. User-ignored findings (synced from dashboard)

func NewAllowList added in v0.9.95

func NewAllowList() *AllowList

NewAllowList creates an empty allow list.

func (*AllowList) FindModifiedCoreFiles added in v0.9.95

func (a *AllowList) FindModifiedCoreFiles(webRoot WebRoot) []Finding

FindModifiedCoreFiles checks all core files and returns ones that have been modified. If too many files are modified (>20), it's likely a version mismatch or manual update, not a targeted injection — so we skip reporting to avoid mass false positives.

func (*AllowList) IsCoreFile added in v0.9.95

func (a *AllowList) IsCoreFile(filePath string) (isCore bool, isModified bool)

IsCoreFile checks if a file is a known framework core file with matching checksum. Returns: (isCore bool, isModified bool)

  • isCore=true, isModified=false → skip scanning (legitimate core file)
  • isCore=true, isModified=true → ALERT (core file was tampered with)
  • isCore=false → scan normally

func (*AllowList) IsUserIgnored added in v0.9.95

func (a *AllowList) IsUserIgnored(filePath, signatureID string) bool

IsUserIgnored returns true if the user has marked this finding as false positive.

func (*AllowList) LoadWordPressChecksums added in v0.9.95

func (a *AllowList) LoadWordPressChecksums(wpRoot, version string) error

LoadWordPressChecksums fetches official checksums from WordPress.org API.

func (*AllowList) SetUserIgnored added in v0.9.95

func (a *AllowList) SetUserIgnored(entries []IgnoreEntry)

SetUserIgnored replaces the user ignore list (synced from backend).

type Finding

type Finding struct {
	FilePath    string `json:"file_path"`
	SignatureID string `json:"signature_id"`
	Name        string `json:"name"`
	Severity    string `json:"severity"`
	Type        string `json:"type"`
	MatchLine   int    `json:"match_line"`
	MatchText   string `json:"match_text"` // truncated snippet
	Domain      string `json:"domain,omitempty"`
	Framework   string `json:"framework,omitempty"`
}

Finding represents a single malware detection result.

func CheckCredentials added in v0.9.100

func CheckCredentials(webRoots []WebRoot) []Finding

CheckCredentials scans for exposed credentials and secrets on the server. Checks: .env files, SSH keys, git credentials, cloud provider keys.

func CheckMaliciousProcesses added in v0.9.100

func CheckMaliciousProcesses() []Finding

CheckMaliciousProcesses scans running processes for known malware indicators: crypto miners, reverse shells, suspicious network connections.

func CheckWordPressDatabase added in v0.9.100

func CheckWordPressDatabase(root WebRoot) []Finding

CheckWordPressDatabase connects to the WordPress database and scans for injected malicious content in posts and options tables. Reads credentials from wp-config.php, uses mysql CLI.

type Framework

type Framework struct {
	Name    string `json:"name"`    // "wordpress", "laravel", "django", "express", "rails", "joomla", "drupal"
	Version string `json:"version"` // detected version if possible
}

Framework represents a detected web application framework.

type FrameworkFinding

type FrameworkFinding struct {
	CheckID     string `json:"check_id"`
	Title       string `json:"title"`
	Severity    string `json:"severity"` // "critical", "high", "medium", "low"
	Description string `json:"description"`
	FilePath    string `json:"file_path"`
	Domain      string `json:"domain,omitempty"`
	Framework   string `json:"framework"`
}

FrameworkFinding represents a security issue specific to a framework.

func CheckFramework

func CheckFramework(root WebRoot) []FrameworkFinding

CheckFramework runs security checks specific to the detected framework.

type HashLookupFunc added in v0.9.100

type HashLookupFunc func(hashes []string) map[string]string

HashLookupFunc is called by the scanner to check file hashes against a remote malware DB. Receives a batch of sha256 hashes, returns a map of matches: sha256 → malware name.

type HeuristicConfig added in v0.9.100

type HeuristicConfig struct {
	// Entropy threshold for flagging PHP files (0-8 scale, 8 = random)
	// Normal PHP: 4.0-5.5. Obfuscated: 5.8-6.5. Encrypted/packed: 6.5+
	EntropyThreshold float64

	// Flag PHP files created in the last N hours in upload directories
	RecentFileHours int
}

HeuristicConfig controls heuristic scanning behavior.

func DefaultHeuristicConfig added in v0.9.100

func DefaultHeuristicConfig() HeuristicConfig

DefaultHeuristicConfig returns sensible defaults.

type HeuristicFinding added in v0.9.100

type HeuristicFinding struct {
	FilePath string
	CheckID  string
	Name     string
	Severity string
	Detail   string
}

HeuristicFinding represents a suspicious file detected by heuristic analysis.

func CheckFileEntropy added in v0.9.100

func CheckFileEntropy(path string, threshold float64) *HeuristicFinding

CheckFileEntropy analyzes if a PHP file has suspiciously high entropy (indicating heavy obfuscation or encoding, common in malware).

Shannon entropy scale for PHP:

  • 3.5-4.5: Simple PHP (mostly whitespace, HTML)
  • 4.5-5.5: Normal PHP code
  • 5.5-6.0: Minified or moderately complex PHP
  • 6.0-6.5: Heavily obfuscated (eval+base64 chains, ionCube loaders)
  • 6.5-7.5: Packed/encrypted payloads (almost certainly malware)
  • 7.5-8.0: Random/encrypted data

func CheckRecentPHP added in v0.9.100

func CheckRecentPHP(path string, maxAgeHours int) *HeuristicFinding

CheckRecentPHP flags PHP files created recently in upload/temp directories. Useful for detecting freshly uploaded webshells.

type IgnoreEntry added in v0.9.95

type IgnoreEntry struct {
	FilePath    string `json:"file_path"`
	SignatureID string `json:"signature_id"`
}

IgnoreEntry represents a user-ignored finding from the dashboard.

type Intensity

type Intensity int

Intensity controls scan speed vs resource usage.

const (
	IntensityLow    Intensity = iota // 50 files/sec
	IntensityMedium                  // 200 files/sec
	IntensityHigh                    // 1000 files/sec
)

func (Intensity) FilesPerSecond

func (i Intensity) FilesPerSecond() int

type QuarantinedFile added in v0.9.100

type QuarantinedFile struct {
	QuarantinePath string `json:"quarantine_path"`
	OriginalPath   string `json:"original_path"`
	Name           string `json:"name"`
	Size           int64  `json:"size"`
	QuarantinedAt  string `json:"quarantined_at"`
}

QuarantinedFile represents a file in quarantine.

func ListQuarantined added in v0.9.100

func ListQuarantined() []QuarantinedFile

ListQuarantined returns all files currently in quarantine.

type RealtimeWatcher added in v0.9.100

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

RealtimeWatcher monitors web directories for new/modified PHP files and triggers immediate scanning when changes are detected. Uses polling instead of inotify to avoid external dependencies and kernel watch limits on servers with many domains.

func NewRealtimeWatcher added in v0.9.100

func NewRealtimeWatcher(onNewFile func(path, domain string)) *RealtimeWatcher

NewRealtimeWatcher creates a watcher that polls directories for changes.

func (*RealtimeWatcher) SetDirectories added in v0.9.100

func (w *RealtimeWatcher) SetDirectories(webRoots []WebRoot)

SetDirectories configures which directories to watch. Typically: uploads/, tmp/, and web root directories.

func (*RealtimeWatcher) Start added in v0.9.100

func (w *RealtimeWatcher) Start()

Start begins polling. Call Stop() to stop.

func (*RealtimeWatcher) Stop added in v0.9.100

func (w *RealtimeWatcher) Stop()

Stop stops the polling loop.

type ScanResult

type ScanResult struct {
	Findings     []Finding     `json:"findings"`
	FilesScanned int64         `json:"files_scanned"`
	FilesSkipped int64         `json:"files_skipped"`
	Duration     time.Duration `json:"duration"`
	StartedAt    time.Time     `json:"started_at"`
}

ScanResult holds the outcome of a malware scan.

type Scanner

type Scanner struct {

	// Scan configuration
	ExcludeDirs []string       // directories to skip (e.g., node_modules, vendor)
	MaxFileSize int64          // skip files larger than this (bytes)
	AllowList   *AllowList     // false positive prevention (checksums + user ignores)
	HashLookup  HashLookupFunc // remote hash lookup (set by main.go)
	// contains filtered or unexported fields
}

Scanner performs malware scanning on web directories.

func New

func New() *Scanner

New creates a scanner with default configuration.

func (*Scanner) IsRunning

func (s *Scanner) IsRunning() bool

IsRunning returns true if a scan is in progress.

func (*Scanner) LoadDynamicSignatures added in v0.9.100

func (s *Scanner) LoadDynamicSignatures(sigs []Signature)

LoadDynamicSignatures adds signatures synced from the backend. Called during sync to merge dynamic signatures with built-in ones. Caps at 200 to protect scan performance on large directories. Skips recompilation if signatures haven't changed since last sync.

func (*Scanner) ScanSingleFile added in v0.9.100

func (s *Scanner) ScanSingleFile(path, domain string) []Finding

ScanSingleFile scans a single file against all signatures + heuristics. Used by the realtime watcher for immediate detection.

func (*Scanner) ScanWebRoots added in v0.9.95

func (s *Scanner) ScanWebRoots(webRoots []WebRoot, intensity Intensity) (*ScanResult, error)

ScanWebRoots scans web roots for malware with full FP prevention. It loads framework checksums, applies context severity, and respects user allow-list.

func (*Scanner) Stop

func (s *Scanner) Stop()

Stop cancels a running scan.

type ScheduleConfig added in v0.9.100

type ScheduleConfig struct {
	Enabled   bool
	Frequency string // "daily", "weekly"
	Time      string // "03:00" (HH:MM)
	Intensity Intensity
}

ScheduleConfig controls when automatic scans run.

type Scheduler added in v0.9.100

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

Scheduler manages automatic malware scan scheduling.

func NewScheduler added in v0.9.100

func NewScheduler(onScan func(intensity string)) *Scheduler

NewScheduler creates a scheduler that calls onScan when it's time to scan.

func (*Scheduler) UpdateConfig added in v0.9.100

func (s *Scheduler) UpdateConfig(enabled bool, frequency, timeStr, intensity string)

UpdateConfig applies new schedule configuration. Restarts the scheduler goroutine if config changed.

type SecurityScore added in v0.9.100

type SecurityScore struct {
	Score                int    `json:"score"` // 0-100
	Grade                string `json:"grade"` // A, B, C, D, F
	MalwareDeductions    int    `json:"malware_deductions"`
	FrameworkDeductions  int    `json:"framework_deductions"`
	CredentialDeductions int    `json:"credential_deductions"`
	IntegrityDeductions  int    `json:"integrity_deductions"`
}

SecurityScore calculates an overall security posture score (0-100) based on scan findings, framework issues, and system checks.

func CalculateScore added in v0.9.100

func CalculateScore(findings []Finding, frameworkIssues []FrameworkFinding) SecurityScore

CalculateScore computes the security score based on scan results.

type Signature

type Signature struct {
	ID       string // Unique identifier (e.g., "WEBSHELL_C99")
	Name     string // Human-readable name
	Pattern  string // Regex or literal string to match
	Severity string // "critical", "high", "medium", "low"
	Type     string // "webshell", "backdoor", "injected_code", "crypto_miner", "phishing"
	IsRegex  bool   // If true, Pattern is a regex; otherwise literal substring
	PHPOnly  bool   // If true, only scan .php/.phtml files (skip .js, .html, etc.)
}

Signature represents a known malware pattern.

func DefaultSignatures

func DefaultSignatures() []Signature

DefaultSignatures returns the built-in malware signature database.

IMPORTANT: Every signature here MUST be tested against common frameworks (WordPress core, Laravel, CodeIgniter, jQuery, TinyMCE) to avoid false positives. When in doubt, make the pattern more specific rather than broad.

type SystemIntegrityResult added in v0.9.100

type SystemIntegrityResult struct {
	ModifiedBinaries  []Finding
	RootkitIndicators []Finding
}

SystemIntegrityResult holds all system-level security findings.

func CheckSystemIntegrity added in v0.9.100

func CheckSystemIntegrity() *SystemIntegrityResult

CheckSystemIntegrity runs system-level checks: modified binaries and rootkit indicators.

type WebRoot

type WebRoot struct {
	Path      string    `json:"path"`
	Domain    string    `json:"domain,omitempty"`
	Framework Framework `json:"framework"`
}

WebRoot represents a discovered web application directory.

func DetectWebRoots

func DetectWebRoots() []WebRoot

DetectWebRoots discovers web application directories on the server. It checks common hosting paths and returns roots with their frameworks.

type YaraRulesSync added in v0.9.100

type YaraRulesSync struct {
	Rules   string `json:"rules"`   // raw YARA rules content
	Version string `json:"version"` // rules version for cache
}

YaraRulesFromSync is the format received from backend.

type YaraScanner added in v0.9.100

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

YaraScanner wraps the yara CLI for rule-based malware scanning. Falls back gracefully if yara is not installed.

func NewYaraScanner added in v0.9.100

func NewYaraScanner() *YaraScanner

NewYaraScanner checks if yara CLI is available and sets up rules directory.

func (*YaraScanner) IsAvailable added in v0.9.100

func (ys *YaraScanner) IsAvailable() bool

IsAvailable returns true if yara CLI is installed.

func (*YaraScanner) LoadRulesCache added in v0.9.100

func (ys *YaraScanner) LoadRulesCache() *YaraRulesSync

LoadRulesCache loads rules from disk cache.

func (*YaraScanner) SaveRulesCache added in v0.9.100

func (ys *YaraScanner) SaveRulesCache(rules YaraRulesSync)

SaveRulesCache saves rules to disk for offline use.

func (*YaraScanner) ScanDirectory added in v0.9.100

func (ys *YaraScanner) ScanDirectory(dir, domain string) []Finding

ScanDirectory runs yara against a directory and returns findings.

func (*YaraScanner) UpdateRules added in v0.9.100

func (ys *YaraScanner) UpdateRules(rulesContent string) error

UpdateRules writes YARA rules to disk for scanning. Rules are received from the backend via sync.

Jump to

Keyboard shortcuts

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