Version: 1.1.0
Status: Enhanced with Real-World Threat Analysis
Target Platform: Windows 10/11 (x64), Linux (kernel 5.15+)
Last Updated: 2026-01-17
Variants is a next-generation endpoint security suite employing kernel-level debugging (DBG), Abstract Syntax Tree (AST) analysis, SAT constraint solving, and cloud-powered threat intelligence. The system provides superior threat prevention through:
| Component | Purpose | Platform |
|---|---|---|
| VariantsTerminalSec | Endpoint protection agent | Windows, Linux |
| VariantsThreatCloud | Cloud analysis & threat intelligence | Cloudflare Workers + DO PostgreSQL |
| VariantsRecoveryOS | Emergency recovery environment | Arch Linux (bootable) |
┌─────────────────────────────────────────────────────────────────┐
│ User Space │
├─────────────────────────────────────────────────────────────────┤
│ ┌──────────────────┐ ┌─────────────────────────────┐ │
│ │ Variants UI │◄────────┤ Protected Applications │ │
│ │ (Tauri + Vite) │ │ (Monitored via DBG) │ │
│ └────────┬─────────┘ └──────────────┬──────────────┘ │
│ │ │ │
│ │ IPC │ All I/O │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Variants Engine (User-mode Service) │ │
│ │ - AST Analysis Coordinator │ │
│ │ - Cloud Sync Manager │ │
│ │ - YARA Rule Engine │ │
│ │ - User Prompt Handler │ │
│ └────────┬──────────────────────────────────────────────┬──┘ │
│ │ │ │
└───────────┼───────────────────────────────────────────────┼──────┘
│ IOCTL │ HTTPS
┌───────────▼───────────────────────────────────────────────┼──────┐
│ Kernel Space │ │
├────────────────────────────────────────────────────────────┤ │
│ ┌───────────────────────────────────────────────────┐ │ │
│ │ Variants Kernel Driver (variants.sys) │ │ │
│ │ ┌─────────────────┐ ┌────────────────────────┐ │ │ │
│ │ │ DBG Session Mgr │ │ CoW File System Filter │ │ │ │
│ │ │ (Kernel Debug) │ │ (Minifilter FltMgr) │ │ │ │
│ │ └────────┬────────┘ └──────────┬─────────────┘ │ │ │
│ │ │ │ │ │ │
│ │ │ ┌─────────────────▼──────────────┐ │ │ │
│ │ │ │ MVCC Transaction Manager │ │ │ │
│ │ │ │ - Shadow Buffer Pool │ │ │ │
│ │ │ │ - Async Commit Queue │ │ │ │
│ │ │ └────────────────────────────────┘ │ │ │
│ │ │ │ │ │
│ │ ┌────────▼─────────────────────────────────────┐ │ │ │
│ │ │ Interrupt & Syscall Interceptor │ │ │ │
│ │ │ - INT 13h Hook (MBR/GPT Protection) │ │ │ │
│ │ │ - IRP_MJ_* Hooks (File/Registry/Network) │ │ │ │
│ │ │ - PsSetLoadImageNotifyRoutine (Driver Load) │ │ │ │
│ │ └────────────────────────────────────────────────┘ │ │ │
│ └───────────────────────────────────────────────────────┘ │ │
└────────────────────────────────────────────────────────────────┘ │
│
┌────────────────────────────────────────────────────────────┘
│
┌───────────▼──────────────────────────────────────────────────────┐
│ VariantsThreatCloud │
│ (Cloudflare Infrastructure) │
├───────────────────────────────────────────────────────────────────┤
│ ┌────────────────────┐ ┌──────────────────────────────┐ │
│ │ Workers (Hono.js) │◄──────┤ Durable Objects │ │
│ │ - File Upload API │ │ - Analysis Session Manager │ │
│ │ - Query Endpoint │ │ - Real-time Event Aggregator │ │
│ │ - Rule Sync API │ └──────────────┬───────────────┘ │
│ └─────────┬──────────┘ │ │
│ │ │ │
│ ▼ ▼ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ PostgreSQL (DigitalOcean Managed) │ │
│ │ - malware_signatures (LSH indexed) │ │
│ │ - clean_signatures │ │
│ │ - threat_events (time-series) │ │
│ │ - endpoint_registry │ │
│ └───────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────┘1. User double-clicks suspicious.exe
↓
2. Kernel intercepts CreateProcess → PsSetCreateProcessNotifyRoutineEx callback
↓
3. DBG Session Manager attaches kernel debug session to new process
↓
4. CoW Filter creates shadow buffer for process isolation
↓
5. Process executes, all I/O intercepted:
- File writes → Shadow buffer
- Registry sets → Shadow registry
- Network sends → Captured for analysis
↓
6. [PARALLEL] User-mode engine triggered:
- Extract executable to temp location
- LLVM lift binary to IR
- Run O3 optimization passes
- Triton symbolic execution on critical paths
- Generate 400-dim behavior vector
↓
7. [ASYNC] Cloud query:
- Upload behavior vector + AST hash
- PostgreSQL LSH similarity search
- YARA rule matching
- Return threat score (0.0-1.0)
↓
8. [DECISION POINT]
- Score < 0.3: Allow, commit shadow buffer on exit
- Score 0.3-0.7: Freeze process, prompt user (blue overlay + modal)
- Score > 0.7: Immediate freeze, full-screen Turnstile verification
↓
9. If malicious confirmed:
- Terminate process tree
- Discard shadow buffer (MVCC rollback)
- Upload full execution trace to ThreatCloud
↓
10. If benign:
- Commit shadow buffer to disk
- Upload clean signature to ThreatCloudBoot-time (ELAM):
1. UEFI Secure Boot → VariantsBootGuard.efi
↓
2. Enumerate all BOOT_START drivers queued for load
↓
3. For each driver:
- Verify signature (EV certificate)
- Check certificate revocation (OCSP - cached offline)
- Compute SHA256 hash
- Match against local whitelist
↓
4. Unknown driver found:
- Block load
- Log to recovery partition
- (Cannot upload - no network yet)
↓
5. If all drivers trusted → Boot continues
Runtime:
1. NtLoadDriver syscall intercepted
↓
2. DBG freezes caller process
↓
3. Extract driver binary
↓
4. [LOCAL] Static analysis:
- PE header validation
- Import table inspection (suspicious APIs?)
- Entropy calculation (packed?)
↓
5. [CLOUD] Upload driver hash + metadata
- Check ThreatCloud certificate database
- Query for known malicious drivers
↓
6. Decision:
- Trusted cert + clean hash → Allow
- Unknown → Prompt user with driver details
- Malicious → Block + alertProtocol: Fast IOCTL via shared memory ring buffer
// Shared memory layout
struct VariantsSharedMemory {
uint64_t magic; // 0x5641524941544E53 ("VARIANTS")
uint32_t kernel_write_index;
uint32_t user_read_index;
uint32_t user_write_index;
uint32_t kernel_read_index;
// Ring buffer for kernel → user events
struct Event k2u_buffer[4096];
// Ring buffer for user → kernel commands
struct Command u2k_buffer[1024];
};
// Event types (kernel → user)
enum EventType {
EVENT_PROCESS_START = 1,
EVENT_FILE_WRITE = 2,
EVENT_REGISTRY_SET = 3,
EVENT_NETWORK_CONNECT = 4,
EVENT_DRIVER_LOAD = 5,
EVENT_THREAT_DETECTED = 6,
};
// Command types (user → kernel)
enum CommandType {
CMD_ALLOW_PROCESS = 1,
CMD_DENY_PROCESS = 2,
CMD_FREEZE_PROCESS = 3,
CMD_COMMIT_SHADOW = 4,
CMD_ROLLBACK_SHADOW = 5,
};Protocol: HTTPS REST + WebSocket (for real-time updates)
Endpoints:
POST /v1/analyze/file - Upload file for analysisPOST /v1/analyze/behavior - Submit behavior vectorGET /v1/rules/hot - Fetch hot YARA rulesPOST /v1/report/clean - Report clean executionPOST /v1/report/threat - Report threat detectionWS /v1/stream - Real-time threat feedAuthentication: Ed25519 signature per request
Authorization: Variants-Sig v1,client=<client_id>,ts=<timestamp>,sig=<ed25519_sig>Language: Rust (windows-kernel-rs)
Target: Kernel-Mode Driver Framework (KMDF)
Load Type: BOOT_START (for ELAM)
Key Modules:
pub struct DbgSessionManager {
sessions: HashMap<ProcessId, KernelDebugSession>,
global_breakpoints: Vec<BreakpointDescriptor>,
}
pub struct KernelDebugSession {
pid: ProcessId,
debug_handle: HANDLE,
breakpoints: Vec<usize>, // Addresses
state: SessionState,
}
pub enum SessionState {
Active,
Frozen, // User decision pending
Terminated,
}
impl DbgSessionManager {
/// Attach kernel debug session on process creation
/// Called from PsSetCreateProcessNotifyRoutineEx callback
pub unsafe fn attach_on_create(&mut self, process: PEPROCESS) -> Result<()>;
/// Set breakpoint on critical syscalls (NtWriteFile, NtSetValueKey, etc.)
pub unsafe fn set_syscall_breakpoints(&mut self, pid: ProcessId) -> Result<()>;
/// Handle breakpoint hit (invoked by kernel debugger callback)
pub unsafe fn on_breakpoint(&mut self, context: &CONTEXT, pid: ProcessId) -> Action;
/// Freeze process (suspend all threads + remove from scheduler)
pub unsafe fn freeze_process_tree(&mut self, pid: ProcessId) -> Result<()>;
/// Force terminate process
pub unsafe fn terminate_process(&mut self, pid: ProcessId) -> Result<()>;
}pub struct CowFilter {
shadow_buffers: HashMap<ProcessId, ShadowBuffer>,
mvcc_manager: MvccTransactionManager,
}
pub struct ShadowBuffer {
pid: ProcessId,
file_shadows: HashMap<PathBuf, FileShadow>,
registry_shadows: HashMap<RegistryKey, RegistryValue>,
total_size_bytes: usize,
}
pub struct FileShadow {
original_path: PathBuf,
shadow_data: Vec<u8>, // In-memory for files < 10MB
shadow_file: Option<PathBuf>, // On-disk cache for large files
dirty_pages: BitVec, // Page-level COW tracking
}
impl CowFilter {
/// Minifilter pre-operation callback for IRP_MJ_CREATE
pub unsafe extern "C" fn pre_create(
data: PFLT_CALLBACK_DATA,
flt_objects: PCFLT_RELATED_OBJECTS,
completion_context: *mut PVOID,
) -> FLT_PREOP_CALLBACK_STATUS;
/// Intercept file write
pub unsafe extern "C" fn pre_write(
data: PFLT_CALLBACK_DATA,
flt_objects: PCFLT_RELATED_OBJECTS,
completion_context: *mut PVOID,
) -> FLT_PREOP_CALLBACK_STATUS;
/// Commit shadow buffer to disk (transaction commit)
pub unsafe fn commit_shadow(&mut self, pid: ProcessId) -> Result<()>;
/// Discard shadow buffer (transaction rollback)
pub unsafe fn rollback_shadow(&mut self, pid: ProcessId) -> Result<()>;
}pub struct PartitionTableProtector {
protected_sectors: Vec<SectorRange>,
original_int13_handler: Option<usize>,
}
impl PartitionTableProtector {
/// Hook INT 13h BIOS interrupt
pub unsafe fn hook_int13(&mut self) -> Result<()>;
/// Hook IRP_MJ_WRITE for disk devices
pub unsafe fn hook_disk_write(&mut self) -> Result<()>;
/// Check if sector is critical (MBR, GPT, backup GPT)
pub fn is_critical_sector(&self, sector: u64) -> bool;
/// Validate write request against trusted tool list
pub fn validate_partition_write(&self, caller_pid: ProcessId, sector: u64) -> Action;
}
pub enum Action {
Allow,
Deny,
PromptUser,
}Language: Rust
Architecture: Multi-threaded async service
Key Components:
pub struct AstAnalyzer {
llvm_context: LLVMContext,
triton_ctx: TritonContext,
sat_solver: satellite_kit::Solver,
}
impl AstAnalyzer {
/// Lift binary to LLVM IR
pub async fn lift_binary(&self, binary_path: &Path) -> Result<Module>;
/// Run O3 optimization passes
pub async fn optimize_ir(&self, module: &mut Module) -> Result<()>;
/// Symbolic execution on critical paths
pub async fn symbolic_execute(&self, module: &Module) -> Result<ExecutionPaths>;
/// Extract behavior vector (400 dimensions)
pub async fn extract_features(&self, paths: &ExecutionPaths) -> Result<BehaviorVector>;
/// SAT constraint solving for threat verification
/// Example: Can this program damage MBR?
pub async fn verify_threat_potential(&self, module: &Module) -> Result<ThreatScore>;
}
pub struct BehaviorVector {
api_calls: Vec<f32>, // 0-99: API call frequency
cfg_features: Vec<f32>, // 100-149: Control flow complexity
data_flow: Vec<f32>, // 150-199: Data flow patterns
runtime_behavior: Vec<f32>, // 200-299: Dynamic behavior
static_features: Vec<f32>, // 300-399: PE header, entropy, etc.
}pub struct CloudSyncManager {
client: reqwest::Client,
endpoint: Url,
client_id: Uuid,
ed25519_keypair: Ed25519KeyPair,
hot_rules: Arc<RwLock<Vec<YaraRule>>>,
}
impl CloudSyncManager {
/// Upload behavior vector for analysis
pub async fn analyze_behavior(&self, vector: &BehaviorVector) -> Result<ThreatScore>;
/// Report clean execution
pub async fn report_clean(&self, vector: &BehaviorVector, metadata: Metadata) -> Result<()>;
/// Report threat detection
pub async fn report_threat(&self,
vector: &BehaviorVector,
exec_trace: ExecutionTrace,
iocs: Vec<IoC>
) -> Result<()>;
/// Sync hot YARA rules (every 5 minutes)
pub async fn sync_hot_rules(&self) -> Result<()>;
/// Sign request with Ed25519
fn sign_request(&self, body: &[u8], timestamp: u64) -> Signature;
}pub enum PromptLevel {
Standard, // Blue overlay + modal
Critical, // Full-screen + Turnstile
Emergency, // System freeze + Turnstile
}
pub struct PromptHandler {
ui_channel: UnboundedSender<PromptRequest>,
}
pub struct PromptRequest {
level: PromptLevel,
process_info: ProcessInfo,
threat_details: ThreatDetails,
response_tx: oneshot::Sender<UserDecision>,
}
pub enum UserDecision {
Allow,
Deny,
Quarantine, // Freeze + upload for analysis
}
impl PromptHandler {
/// Standard prompt: Blue overlay on process window
pub async fn prompt_standard(&self, req: PromptRequest) -> Result<UserDecision>;
/// Critical prompt: Full-screen with Turnstile verification
pub async fn prompt_critical(&self, req: PromptRequest) -> Result<UserDecision>;
/// Emergency prompt: Freeze entire system
pub async fn prompt_emergency(&self, req: PromptRequest) -> Result<UserDecision>;
}Tech Stack: Tauri 2.0 + Vite + React + shadcn/ui
Features:
Language: Rust (rust-for-linux)
Target: Linux kernel 5.15+
Key Differences from Windows:
ptrace for process monitoring (no kernel-level DBG equivalent)kprobe/kretprobeModule Structure:
// variants-linux/src/lib.rs
#[no_mangle]
pub extern "C" fn init_module() -> i32 {
// Register kprobes for syscalls
register_kprobe("sys_execve", on_execve_enter);
register_kprobe("sys_write", on_write_enter);
register_kprobe("sys_open", on_open_enter);
// Initialize OverlayFS for CoW
init_overlay_manager();
0
}
fn on_execve_enter(regs: &pt_regs) -> i32 {
let filename = get_user_string(regs.rdi);
let pid = current_pid();
// Attach ptrace to new process
attach_monitor(pid);
// Create overlay mount for this process
create_process_overlay(pid);
0
}Similar to Windows, but with Linux-specific adjustments:
systemd service integrationTTY Prompt Example:
variants: Suspicious activity detected from ./malware.elf (PID 1234)
Threat Details:
- Attempted to write to /boot/grub/grub.cfg
- Opened raw disk device /dev/sda
- Network connection to known C2 server (45.67.89.10)
[Y]es (allow) / [N]o (block) / [A]nalysis (upload to cloud): _// workers/src/index.ts
import { Hono } from 'hono';
import { z } from 'zod';
const app = new Hono<{ Bindings: Env }>();
// Request schemas
const BehaviorVectorSchema = z.object({
vector: z.array(z.number()).length(400),
metadata: z.object({
sha256: z.string(),
pe_timestamp: z.number().optional(),
file_size: z.number(),
}),
});
app.post('/v1/analyze/behavior', async (c) => {
const body = await c.req.json();
const { vector, metadata } = BehaviorVectorSchema.parse(body);
// Verify signature
const sig = c.req.header('Authorization');
if (!verifyEd25519Signature(sig, body, c.env.TRUSTED_CLIENTS)) {
return c.json({ error: 'Invalid signature' }, 401);
}
// Query PostgreSQL with LSH
const db = c.env.DB;
const lshBuckets = computeLSH(vector);
const candidates = await db.prepare(`
SELECT signature_id, feature_vector, threat_family, severity
FROM malware_signatures
WHERE lsh_bucket IN (${lshBuckets.map(() => '?').join(',')})
LIMIT 100
`).bind(...lshBuckets).all();
// Compute exact similarities in-memory
const similarities = candidates.results.map(row => ({
id: row.signature_id,
similarity: cosineSimilarity(vector, row.feature_vector),
family: row.threat_family,
severity: row.severity,
})).filter(s => s.similarity > 0.85)
.sort((a, b) => b.similarity - a.similarity)
.slice(0, 10);
// Compute threat score
const threatScore = computeThreatScore(similarities);
return c.json({
threat_score: threatScore,
matches: similarities,
});
});
app.post('/v1/report/clean', async (c) => {
const { vector, metadata } = await c.req.json();
const featureHash = sha256(JSON.stringify(vector));
await c.env.DB.prepare(`
INSERT INTO clean_signatures (feature_hash, feature_vector, metadata, hit_count)
VALUES (?, ?, ?, 1)
ON CONFLICT (feature_hash)
DO UPDATE SET hit_count = hit_count + 1, last_seen = NOW()
`).bind(featureHash, JSON.stringify(vector), JSON.stringify(metadata)).run();
return c.json({ ok: true });
});
export default app;// workers/src/analysis-session.ts
export class AnalysisSession extends DurableObject {
async analyzeFile(fileData: ArrayBuffer, metadata: Metadata): Promise<AnalysisResult> {
// 1. YARA scanning
const yaraMatches = await this.yaraMatch(fileData);
// 2. Static analysis
const staticFeatures = extractStaticFeatures(fileData);
// 3. Query threat database
const dbMatches = await this.queryThreatDB(staticFeatures.hash);
// 4. If unknown, queue for deep analysis
if (dbMatches.length === 0 && staticFeatures.suspicious) {
await this.queueDeepAnalysis(fileData, metadata);
}
return {
threat_level: computeThreatLevel(yaraMatches, dbMatches, staticFeatures),
details: { yaraMatches, dbMatches, staticFeatures },
};
}
private async queueDeepAnalysis(fileData: ArrayBuffer, metadata: Metadata) {
// Store in R2 for batch processing
await this.env.R2_BUCKET.put(
`pending-analysis/${metadata.sha256}`,
fileData,
{ customMetadata: metadata }
);
}
}-- malware_signatures table
CREATE TABLE malware_signatures (
signature_id SERIAL PRIMARY KEY,
signature_hash TEXT UNIQUE NOT NULL,
feature_vector JSONB NOT NULL, -- 400-dim vector
lsh_bucket INTEGER[] NOT NULL, -- LSH hash buckets for fast filtering
threat_family TEXT,
severity INTEGER CHECK (severity BETWEEN 1 AND 10),
first_seen TIMESTAMP DEFAULT NOW(),
last_seen TIMESTAMP DEFAULT NOW(),
hit_count INTEGER DEFAULT 0,
false_positive_rate FLOAT DEFAULT 0.0,
-- Metadata
api_calls TEXT[],
iocs JSONB,
yara_rules TEXT[]
);
-- Indexes
CREATE INDEX idx_lsh_bucket ON malware_signatures USING GIN (lsh_bucket);
CREATE INDEX idx_threat_family ON malware_signatures (threat_family);
CREATE INDEX idx_severity ON malware_signatures (severity DESC);
-- clean_signatures table
CREATE TABLE clean_signatures (
id SERIAL PRIMARY KEY,
feature_hash TEXT UNIQUE NOT NULL,
feature_vector JSONB NOT NULL,
metadata JSONB,
hit_count INTEGER DEFAULT 0,
first_seen TIMESTAMP DEFAULT NOW(),
last_seen TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_clean_hash ON clean_signatures (feature_hash);
-- threat_events (time-series)
CREATE TABLE threat_events (
event_id BIGSERIAL PRIMARY KEY,
client_id UUID NOT NULL,
timestamp TIMESTAMP DEFAULT NOW(),
event_type TEXT NOT NULL,
threat_score FLOAT,
process_name TEXT,
process_pid INTEGER,
file_hash TEXT,
network_iocs JSONB,
execution_trace JSONB
);
CREATE INDEX idx_client_time ON threat_events (client_id, timestamp DESC);
CREATE INDEX idx_threat_score ON threat_events (threat_score DESC) WHERE threat_score > 0.7;
-- endpoint_registry
CREATE TABLE endpoint_registry (
client_id UUID PRIMARY KEY,
hostname TEXT,
os_version TEXT,
variants_version TEXT,
public_key_ed25519 TEXT NOT NULL,
first_seen TIMESTAMP DEFAULT NOW(),
last_heartbeat TIMESTAMP DEFAULT NOW(),
status TEXT DEFAULT 'active'
);
-- Scheduled cleanup job (every 24h)
CREATE OR REPLACE FUNCTION evict_bad_signatures() RETURNS void AS $$
BEGIN
-- Remove high false-positive rate signatures
DELETE FROM malware_signatures WHERE false_positive_rate > 0.3;
-- Remove signatures overlapping with clean signatures
DELETE FROM malware_signatures m
WHERE EXISTS (
SELECT 1 FROM clean_signatures c
WHERE (m.feature_vector::jsonb) = (c.feature_vector::jsonb)
);
-- Remove low-hit signatures older than 30 days
DELETE FROM malware_signatures
WHERE hit_count = 0 AND first_seen < NOW() - INTERVAL '30 days';
END;
$$ LANGUAGE plpgsql;Distribution: Arch Linux (minimal)
Size Target: < 200MB ISO
Bootloader: GRUB2 (signed with MOK via Shim)
Included Components:
// recovery-tools/src/sat_verifier.rs
use satellite_kit::Solver;
pub struct SystemIntegrityVerifier {
solver: Solver,
}
impl SystemIntegrityVerifier {
pub fn verify_mbr(&mut self, device: &Path) -> Result<bool> {
let mbr = std::fs::read(device)?[..512].to_vec();
// Encode MBR constraints as SAT problem
let sig_valid = self.solver.bool_var();
let part_valid = (0..4).map(|_| self.solver.bool_var()).collect::<Vec<_>>();
let code_valid = self.solver.bool_var();
// Constraint 1: Boot signature must be 0x55AA
if u16::from_le_bytes([mbr[510], mbr[511]]) == 0x55AA {
self.solver.add_clause(vec![sig_valid.positive_lit()]);
} else {
self.solver.add_clause(vec![sig_valid.negative_lit()]);
}
// Constraint 2: Partition table entries valid
for (i, var) in part_valid.iter().enumerate() {
let offset = 446 + i * 16;
let entry = &mbr[offset..offset + 16];
if self.is_valid_partition_entry(entry) {
self.solver.add_clause(vec![var.positive_lit()]);
} else {
self.solver.add_clause(vec![var.negative_lit()]);
}
}
// Constraint 3: Boot code reasonable (entropy check)
let boot_code = &mbr[0..446];
if self.is_reasonable_boot_code(boot_code) {
self.solver.add_clause(vec![code_valid.positive_lit()]);
} else {
self.solver.add_clause(vec![code_valid.negative_lit()]);
}
// All constraints must be satisfied
self.solver.add_clause(vec![sig_valid.positive_lit()]);
for var in &part_valid {
self.solver.add_clause(vec![var.positive_lit()]);
}
self.solver.add_clause(vec![code_valid.positive_lit()]);
// Solve
match self.solver.solve()? {
SatResult::Sat(_) => Ok(true),
SatResult::Unsat => Ok(false),
_ => Err(anyhow!("Cannot determine MBR validity")),
}
}
fn is_valid_partition_entry(&self, entry: &[u8]) -> bool {
// Check partition type, CHS/LBA values, etc.
let part_type = entry[4];
if part_type == 0 {
return true; // Empty entry is valid
}
let start_lba = u32::from_le_bytes(entry[8..12].try_into().unwrap());
let num_sectors = u32::from_le_bytes(entry[12..16].try_into().unwrap());
start_lba > 0 && num_sectors > 0
}
fn is_reasonable_boot_code(&self, code: &[u8]) -> bool {
let all_zeros = code.iter().all(|&b| b == 0);
let all_ff = code.iter().all(|&b| b == 0xFF);
if all_zeros || all_ff {
return false;
}
// Entropy check
let entropy = calculate_entropy(code);
entropy > 3.0 && entropy < 7.5
}
}Strategy: Mount infected system in chroot jail, scan with isolated tools
#!/bin/bash
# variants-recovery/linux-rootkit-deep-scan.sh
echo "=== Variants Linux Rootkit Scanner ==="
INFECTED_ROOT="/mnt/infected"
CLEAN_ROOT="/recovery/clean-debian"
# 1. Mount the infected system (read-only)
echo "[1] Mounting infected system..."
mount -o ro /dev/sda1 "$INFECTED_ROOT"
# 2. Setup chroot environment with clean tools
echo "[2] Setting up isolated scanning environment..."
mkdir -p "$INFECTED_ROOT/variants-scan"
mount --bind "$CLEAN_ROOT" "$INFECTED_ROOT/variants-scan/clean"
# 3. Run chrootkit from CLEAN environment
echo "[3] Running chrootkit scan..."
chroot "$INFECTED_ROOT/variants-scan/clean" /bin/bash -c "
chrootkit -r $INFECTED_ROOT > /tmp/chrootkit-report.txt
"
# 4. Additional checks with static binaries
echo "[4] Running additional checks..."
# Check for replaced system commands
CRITICAL_BINS=(
"/bin/ps"
"/bin/netstat"
"/usr/bin/ss"
"/bin/ls"
"/usr/bin/top"
"/usr/bin/lsof"
)
for bin in "${CRITICAL_BINS[@]}"; do
if [ -f "$INFECTED_ROOT$bin" ]; then
# Compare with known-good hash
ACTUAL_HASH=$(sha256sum "$INFECTED_ROOT$bin" | cut -d' ' -f1)
EXPECTED_HASH=$(grep "$(basename $bin)" /recovery/hashes/debian-11.txt | cut -d' ' -f1)
if [ "$ACTUAL_HASH" != "$EXPECTED_HASH" ]; then
echo " [!] TAMPERED: $bin"
echo " Expected: $EXPECTED_HASH"
echo " Actual: $ACTUAL_HASH"
# Upload to ThreatCloud
cp "$INFECTED_ROOT$bin" "/tmp/suspicious-$(basename $bin)"
./variants-cloud-upload "/tmp/suspicious-$(basename $bin)"
fi
fi
done
# 5. Check for hidden systemd services (like tmuxinfo10b4e87d)
echo "[5] Scanning systemd services..."
find "$INFECTED_ROOT/etc/systemd/system" -name "*.service" | while read svc; do
SERVICE_NAME=$(basename "$svc")
# Check if service name is random/suspicious
if [[ "$SERVICE_NAME" =~ ^[a-f0-9]{12,}\.service$ ]]; then
echo " [!] SUSPICIOUS SERVICE: $SERVICE_NAME"
cat "$svc"
# Extract ExecStart binary
EXEC=$(grep "ExecStart=" "$svc" | cut -d'=' -f2 | awk '{print $1}')
if [ -n "$EXEC" ]; then
echo " Analyzing binary: $EXEC"
# Upload for analysis
if [ -f "$INFECTED_ROOT$EXEC" ]; then
cp "$INFECTED_ROOT$EXEC" "/tmp/suspicious-service-$(basename $EXEC)"
./variants-cloud-upload "/tmp/suspicious-service-$(basename $EXEC)"
fi
fi
fi
done
# 6. Check for LD_PRELOAD hooks
echo "[6] Checking LD_PRELOAD..."
if [ -f "$INFECTED_ROOT/etc/ld.so.preload" ]; then
echo " [!] LD_PRELOAD FOUND (VERY SUSPICIOUS)"
cat "$INFECTED_ROOT/etc/ld.so.preload"
# Analyze preloaded libraries
while read lib; do
if [ -f "$INFECTED_ROOT$lib" ]; then
echo " Uploading: $lib"
cp "$INFECTED_ROOT$lib" "/tmp/ld-preload-$(basename $lib)"
./variants-cloud-upload "/tmp/ld-preload-$(basename $lib)"
fi
done < "$INFECTED_ROOT/etc/ld.so.preload"
fi
# 7. Kernel module check
echo "[7] Checking kernel modules..."
MODULES_DIR="$INFECTED_ROOT/lib/modules/$(uname -r)/kernel"
if [ -d "$MODULES_DIR" ]; then
find "$MODULES_DIR" -name "*.ko" | while read mod; do
# Check signature
if ! modinfo "$mod" | grep -q "sig_key.*Linux kernel"; then
echo " [!] UNSIGNED MODULE: $mod"
# Upload
cp "$mod" "/tmp/unsigned-$(basename $mod)"
./variants-cloud-upload "/tmp/unsigned-$(basename $mod)"
fi
done
fi
# 8. Check libc6 integrity (critical!)
echo "[8] Verifying libc6..."
LIBC_PATH=$(find "$INFECTED_ROOT/lib" -name "libc.so.6" | head -1)
if [ -n "$LIBC_PATH" ]; then
LIBC_HASH=$(sha256sum "$LIBC_PATH" | cut -d' ' -f1)
EXPECTED_LIBC=$(grep "libc.so.6" /recovery/hashes/debian-11.txt | cut -d' ' -f1)
if [ "$LIBC_HASH" != "$EXPECTED_LIBC" ]; then
echo " [!] CRITICAL: libc6 IS INFECTED!"
echo " This is a severe rootkit infection"
echo " Uploading for analysis..."
cp "$LIBC_PATH" "/tmp/infected-libc.so.6"
./variants-cloud-upload "/tmp/infected-libc.so.6"
fi
fi
# 9. Generate report
echo "[9] Generating final report..."
cat > /tmp/linux-rootkit-report.json <<EOF
{
"scan_date": "$(date -Iseconds)",
"infected_system": "$INFECTED_ROOT",
"chrootkit_findings": $(cat /tmp/chrootkit-report.txt | jq -Rs .),
"tampered_binaries": [
$(find /tmp/suspicious-* 2>/dev/null | jq -Rs 'split("\n") | map(select(length > 0))')
],
"suspicious_services": [
// ... parsed from systemd scan
],
"severity": "critical"
}
EOF
echo "[*] Scan complete. Report: /tmp/linux-rootkit-report.json"
echo ""
echo "Next steps:"
echo " 1. Review report"
echo " 2. Replace tampered binaries from clean backup"
echo " 3. Remove malicious systemd services"
echo " 4. Reinstall libc6 if infected"
echo " 5. Reboot and re-scan"Cloud Integration:
// variants-cloud-upload (static binary)
async fn upload_suspicious_file(path: &Path) -> Result<()> {
let file_data = std::fs::read(path)?;
let file_hash = sha256(&file_data);
// Upload to ThreatCloud
let client = reqwest::Client::new();
let response = client.post("https://threatcloud.variants.security/v1/analyze/linux-sample")
.header("Content-Type", "application/octet-stream")
.header("X-File-Hash", &file_hash)
.header("X-File-Name", path.file_name().unwrap().to_str().unwrap())
.body(file_data)
.send()
.await?;
let analysis: AnalysisResult = response.json().await?;
println!("Analysis result:");
println!(" Threat score: {}", analysis.threat_score);
println!(" Family: {:?}", analysis.threat_family);
Ok(())
}Adversary Capabilities:
Attack Vectors Defended:
┌─────────────────────────────────────────────┐
│ Untrusted Zone │
│ - All user applications │
│ - Unknown drivers (pre-validation) │
│ - Network input │
└──────────────┬──────────────────────────────┘
│
▼ DBG Monitoring + CoW Isolation
┌──────────────────────────────────────────────┐
│ Monitored Zone │
│ - Applications under DBG session │
│ - Shadow buffer environment │
└──────────────┬───────────────────────────────┘
│
▼ Signature Verification
┌──────────────────────────────────────────────┐
│ Trusted Zone │
│ - Microsoft-signed binaries │
│ - ThreatCloud whitelisted certificates │
│ - Variants components (self) │
└───────────────────────────────────────────────┘Rationale: PowerShell is signed by Microsoft. Even advanced malware like Silver Fox won't blacklist Microsoft certificates (would break the entire OS).
# variants-watchdog.ps1
# This script runs continuously to monitor and restore Variants
# Signed by Microsoft, immune to certificate blacklisting
$ErrorActionPreference = "Stop"
function Test-VariantsHealth {
# 1. Check if main service is running
$service = Get-Service -Name "VariantsEngine" -ErrorAction SilentlyContinue
if (-not $service -or $service.Status -ne "Running") {
Write-Warning "VariantsEngine service not running!"
return $false
}
# 2. Check if driver is loaded
$driver = Get-WmiObject Win32_SystemDriver | Where-Object { $_.Name -eq "Variants" }
if (-not $driver -or $driver.State -ne "Running") {
Write-Warning "Variants driver not loaded!"
return $false
}
# 3. Check communication channel
$testFile = "$env:TEMP\variants-health-check.tmp"
"test" | Out-File $testFile
try {
# Try to communicate with driver
$result = & "$env:ProgramFiles\Variants\VariantsCLI.exe" test-comm
if ($result -ne "OK") {
Write-Warning "Driver communication failed!"
return $false
}
} finally {
Remove-Item $testFile -ErrorAction SilentlyContinue
}
return $true
}
function Restore-CodeIntegrityPolicy {
# Check if certificate policies have been tampered
$cipPath = "$env:SystemRoot\System32\CodeIntegrity\Active\cip"
$backupPath = "$env:ProgramFiles\Variants\Backup\cip.backup"
if (Test-Path $cipPath) {
$currentHash = (Get-FileHash $cipPath -Algorithm SHA256).Hash
$expectedHash = (Get-Content "$env:ProgramFiles\Variants\Backup\cip.hash")
if ($currentHash -ne $expectedHash) {
Write-Warning "CodeIntegrity policy TAMPERED! Restoring..."
# Restore from backup
Copy-Item $backupPath $cipPath -Force
# Force policy reload
& bcdedit /set {current} testsigning off
& bcdedit /set {current} testsigning on
Write-Host "Policy restored. System needs reboot."
return $false
}
}
return $true
}
function Trigger-EmergencyRecovery {
param([string]$Reason)
Write-Warning "=== EMERGENCY: Triggering Recovery OS ==="
Write-Warning "Reason: $Reason"
# 1. Set next boot to Recovery OS
& bcdedit /set "{variants-recovery}" /d "Variants Recovery OS" /application bootsector
& bcdedit /bootsequence "{variants-recovery}"
# 2. Write emergency log
$logPath = "C:\Windows\Temp\variants-emergency.log"
@"
Timestamp: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Reason: $Reason
Watchdog PID: $PID
System Info: $(Get-WmiObject Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber)
"@ | Out-File $logPath -Encoding UTF8
# 3. Reboot immediately
Write-Warning "System will reboot in 10 seconds..."
Start-Sleep -Seconds 10
Restart-Computer -Force
}
# Main monitoring loop
Write-Host "Variants PowerShell Watchdog started (PID: $PID)"
Write-Host "Monitoring interval: 5 seconds"
while ($true) {
try {
# Health check
$healthy = Test-VariantsHealth
if (-not $healthy) {
Write-Warning "Health check FAILED!"
# Try to restart service
Write-Host "Attempting to restart VariantsEngine service..."
Restart-Service -Name "VariantsEngine" -ErrorAction Stop
Start-Sleep -Seconds 5
# Check again
if (-not (Test-VariantsHealth)) {
# Still failed - emergency recovery
Trigger-EmergencyRecovery "Service restart failed"
}
}
# Certificate policy check
$policyOK = Restore-CodeIntegrityPolicy
if (-not $policyOK) {
Trigger-EmergencyRecovery "Certificate policy tampered and restore requires reboot"
}
} catch {
Write-Error "Watchdog error: $_"
# Continue monitoring even if error occurs
}
Start-Sleep -Seconds 5
}Deployment:
Why kd > Driver: Kernel debugger has higher privilege than drivers, can intercept driver load before it happens.
// variants-kd-monitor/src/lib.rs
// Runs as kernel debugger extension
use windbg::*;
pub struct KdMonitor {
breakpoints: Vec<Breakpoint>,
protected_drivers: HashSet<String>,
}
impl KdMonitor {
pub unsafe fn initialize(&mut self) -> Result<()> {
// 1. Set breakpoint on nt!IopLoadDriver
self.set_breakpoint(
"nt!IopLoadDriver",
Self::on_driver_load_attempt
);
// 2. Set breakpoint on nt!NtTerminateProcess
self.set_breakpoint(
"nt!NtTerminateProcess",
Self::on_process_terminate_attempt
);
// 3. Set breakpoint on nt!ZwSetValueKey (registry protection)
self.set_breakpoint(
"nt!ZwSetValueKey",
Self::on_registry_write_attempt
);
// 4. Monitor SSDT modifications
self.monitor_ssdt_integrity();
Ok(())
}
unsafe fn on_driver_load_attempt(&mut self, regs: &Registers) -> DebugAction {
// RCX = PDRIVER_OBJECT (first argument)
let driver_object = regs.rcx as PDRIVER_OBJECT;
// Get driver path from RegistryPath
let registry_path = (*driver_object).DriverExtension.ServiceKeyName;
let driver_name = extract_driver_name(®istry_path);
log::info!("Driver load attempt: {}", driver_name);
// Check if this is a suspicious driver
if self.is_suspicious_driver(&driver_name) {
log::warn!("Blocking suspicious driver: {}", driver_name);
// Modify return value to STATUS_ACCESS_DENIED
regs.rax = STATUS_ACCESS_DENIED as u64;
// Skip the actual load
return DebugAction::Skip;
}
// Check if malware is trying to unload Variants driver
if driver_name.contains("Variants") {
log::critical!("Attempt to unload Variants driver detected!");
// Deny and trigger emergency
self.trigger_emergency_response();
return DebugAction::Skip;
}
DebugAction::Continue
}
unsafe fn on_process_terminate_attempt(&mut self, regs: &Registers) -> DebugAction {
// RCX = ProcessHandle
let process_handle = regs.rcx as HANDLE;
// Get process ID from handle
let pid = handle_to_pid(process_handle);
// Check if it's Variants process
if self.is_variants_process(pid) {
log::critical!("Malware attempting to terminate Variants! PID: {}", pid);
// Get caller process
let caller_pid = current_process_id();
log::critical!("Attacker PID: {}", caller_pid);
// Reverse attack: terminate the attacker
terminate_process(caller_pid);
// Deny the termination
regs.rax = STATUS_ACCESS_DENIED as u64;
return DebugAction::Skip;
}
DebugAction::Continue
}
unsafe fn on_registry_write_attempt(&mut self, regs: &Registers) -> DebugAction {
// Check if writing to CodeIntegrity policy
let key_handle = regs.rcx as HANDLE;
let key_path = handle_to_registry_path(key_handle);
if key_path.contains("CodeIntegrity") || key_path.contains("Policies") {
log::warn!("Registry write to security policy: {}", key_path);
// Allow only trusted processes (Microsoft signed)
let caller = current_process();
if !is_microsoft_signed(caller) {
log::critical!("Unsigned process attempting policy modification!");
regs.rax = STATUS_ACCESS_DENIED as u64;
return DebugAction::Skip;
}
}
DebugAction::Continue
}
fn monitor_ssdt_integrity(&mut self) {
// Get SSDT base address
let ssdt_base = find_ssdt_base();
// Hash the SSDT
let expected_hash = self.calculate_ssdt_hash(ssdt_base);
// Periodic check (every second)
std::thread::spawn(move || {
loop {
let current_hash = calculate_ssdt_hash(ssdt_base);
if current_hash != expected_hash {
log::critical!("SSDT HOOKED! Triggering emergency response!");
trigger_emergency_response();
}
std::thread::sleep(Duration::from_secs(1));
}
});
}
}Advantages over driver-only approach:
// Register process protection
unsafe {
ObRegisterCallbacks(
&callback_registration,
&mut registration_handle,
);
}
// Callback implementation
unsafe extern "C" fn pre_open_process(
registration_context: PVOID,
info: POB_PRE_OPERATION_INFORMATION,
) -> OB_PREOP_CALLBACK_STATUS {
let target_process = info.Object as PEPROCESS;
// Check if target is Variants process
if is_variants_process(target_process) {
// Strip dangerous access rights
if info.Parameters.CreateHandleInformation.DesiredAccess & PROCESS_TERMINATE != 0 {
info.Parameters.CreateHandleInformation.DesiredAccess &= !PROCESS_TERMINATE;
}
if info.Parameters.CreateHandleInformation.DesiredAccess & PROCESS_VM_WRITE != 0 {
info.Parameters.CreateHandleInformation.DesiredAccess &= !PROCESS_VM_WRITE;
}
}
OB_PREOP_SUCCESS
}// Periodic integrity check (every 60 seconds)
async fn integrity_check_loop() {
loop {
// 1. Verify driver code section
let driver_base = get_driver_base_address();
let code_section = read_code_section(driver_base);
let current_hash = sha256(&code_section);
if current_hash != EXPECTED_CODE_HASH {
log::critical!("Driver code section tampered!");
trigger_emergency_recovery();
}
// 2. Verify DBG session integrity
for (pid, session) in dbg_manager.sessions.iter() {
if !session.is_valid() {
log::critical!("DBG session {} compromised!", pid);
reattach_dbg_session(*pid);
}
}
tokio::time::sleep(Duration::from_secs(60)).await;
}
}Data Minimization:
User Control:
// variants-shared/include/ioctl.h
#define VARIANTS_DEVICE_NAME L"\\Device\\Variants"
#define VARIANTS_SYMLINK_NAME L"\\??\\Variants"
// IOCTL codes
#define IOCTL_VARIANTS_ATTACH_DBG CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_VARIANTS_DETACH_DBG CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_VARIANTS_FREEZE_PROCESS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x802, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_VARIANTS_COMMIT_SHADOW CTL_CODE(FILE_DEVICE_UNKNOWN, 0x803, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_VARIANTS_ROLLBACK_SHADOW CTL_CODE(FILE_DEVICE_UNKNOWN, 0x804, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_VARIANTS_GET_EVENT CTL_CODE(FILE_DEVICE_UNKNOWN, 0x805, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
// Structures
typedef struct _VARIANTS_ATTACH_DBG_REQUEST {
ULONG ProcessId;
BOOLEAN AttachAllThreads;
} VARIANTS_ATTACH_DBG_REQUEST, *PVARIANTS_ATTACH_DBG_REQUEST;
typedef struct _VARIANTS_EVENT {
ULONGLONG Timestamp;
ULONG EventType;
ULONG ProcessId;
ULONG ThreadId;
union {
struct {
WCHAR FilePath[260];
ULONGLONG Offset;
ULONG Length;
} FileWrite;
struct {
WCHAR KeyPath[260];
WCHAR ValueName[128];
} RegistrySet;
struct {
ULONG IpAddress;
USHORT Port;
} NetworkConnect;
} Data;
} VARIANTS_EVENT, *PVARIANTS_EVENT;Base URL: https://threatcloud.variants.security/v1
All requests must include Ed25519 signature:
Authorization: Variants-Sig v1,client=<uuid>,ts=<unix_timestamp>,sig=<hex_signature>Signature computed as:
sig = ed25519_sign(private_key, sha256(body + timestamp))POST /analyze/behavior
Request:
{
"vector": [0.12, 0.45, ...], // 400 floats
"metadata": {
"sha256": "abc123...",
"file_size": 1024000,
"pe_timestamp": 1705449600,
"client_version": "1.0.0"
}
}Response:
{
"threat_score": 0.85,
"matches": [
{
"signature_id": 12345,
"similarity": 0.92,
"threat_family": "Ransomware.WannaCry",
"severity": 9
}
],
"recommended_action": "block"
}POST /report/threat
Request:
{
"vector": [...],
"execution_trace": {
"syscalls": ["NtWriteFile", "NtSetValueKey", ...],
"network_iocs": ["45.67.89.10:8080"],
"file_operations": [
{"path": "C:\\Users\\<REDACTED>\\Documents\\file.txt", "op": "write"}
]
},
"detection_method": "ast_analysis",
"confidence": 0.95
}Response:
{
"threat_id": "THR-2026-01234",
"acknowledgement": "Threat recorded and signature extracted",
"signature_id": 67890
}GET /rules/hot
Query params:
client_version: Client version for compatibilitylast_update: Unix timestamp of last syncResponse:
{
"rules": [
{
"rule_id": "YR-2026-001",
"yara_rule": "rule SilverFox { strings: $a = { E8 ?? ?? ?? ?? 83 C4 04 } condition: $a }",
"priority": "critical",
"created_at": 1705449600
}
],
"next_update_in": 300
}| Operation | Target | Acceptable | Unacceptable |
|---|---|---|---|
| Process start overhead | < 50ms | < 100ms | > 200ms |
| File write (< 1MB) | < 10ms | < 20ms | > 50ms |
| Registry operation | < 5ms | < 10ms | > 20ms |
| Cloud query (behavior vector) | < 100ms | < 200ms | > 500ms |
| AST analysis (10MB binary) | < 10s | < 20s | > 60s |
| User prompt response time | < 2s | < 5s | > 10s |
Windows Driver:
User-mode Engine:
ThreatCloud:
Client-side:
Cloud-side:
1. User downloads VariantsSetup.exe (signed with EV certificate)
↓
2. Installer checks prerequisites:
- Windows 10 1809+ or Windows 11
- TPM 2.0 (optional but recommended)
- 8GB RAM, 10GB free disk
↓
3. Install driver:
- Copy variants.sys to %SystemRoot%\System32\drivers
- Register service (sc create Variants ...)
- Set BOOT_START for ELAM
↓
4. Install user-mode components:
- Engine service (VariantsEngine.exe)
- UI app (VariantsUI.exe)
- Recovery tools to hidden partition
↓
5. Enable kernel debug mode:
- bcdedit /debug on
- bcdedit /dbgsettings local
- Prompt user to reboot
↓
6. [After reboot] First-time setup:
- Generate Ed25519 keypair
- Register with ThreatCloud
- Download initial rule set
- Create recovery partition (if not exists)
↓
7. Installation completeGradual Rollout (prevent CrowdStrike-style incidents):
Phase 1: Canary (1% of users, internal testers)
- Duration: 48 hours
- Metrics: Crash rate, performance degradation
- Rollback trigger: Crash rate > 0.1%
Phase 2: Early Adopters (10%)
- Duration: 1 week
- Metrics: Detection accuracy, false positives
- Rollback trigger: False positive rate > 5%
Phase 3: Stable (50%)
- Duration: 1 week
- Metrics: Overall stability
Phase 4: General Availability (100%)
- Full rolloutUpdate Mechanism:
Emergency Rollback:
# Create hidden recovery partition (5GB)
diskpart <<EOF
select disk 0
create partition primary size=5120
assign letter=R
format fs=ntfs quick label="Variants Recovery"
set id=27 # Hidden partition type
EOF
# Install Recovery OS
cp VariantsRecoveryOS.iso /mnt/recovery/
grub-install --boot-directory=/mnt/recovery/boot /dev/sda
# Configure UEFI boot entry
bcdedit /create {variants-recovery} /d "Variants Recovery OS" /application bootsector
bcdedit /set {variants-recovery} device partition=R:
bcdedit /set {variants-recovery} path \boot\grub\x64efi.efi
bcdedit /displayorder {variants-recovery} /addlastCoverage Target: > 80% for Rust code
Critical Test Suites:
Example:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cow_write_commit() {
let mut filter = CowFilter::new();
let pid = 1234;
// Create shadow buffer
filter.create_shadow(pid);
// Simulate write
filter.write_to_shadow(pid, "test.txt", b"malicious data");
// Verify shadow contains data
let shadow_data = filter.read_shadow(pid, "test.txt").unwrap();
assert_eq!(shadow_data, b"malicious data");
// Commit
filter.commit_shadow(pid).unwrap();
// Verify real file now contains data
let real_data = std::fs::read("test.txt").unwrap();
assert_eq!(real_data, b"malicious data");
}
#[test]
fn test_cow_write_rollback() {
let mut filter = CowFilter::new();
let pid = 1234;
// Original file content
std::fs::write("test.txt", b"original").unwrap();
filter.create_shadow(pid);
filter.write_to_shadow(pid, "test.txt", b"malicious data");
// Rollback instead of commit
filter.rollback_shadow(pid).unwrap();
// Verify real file still has original content
let real_data = std::fs::read("test.txt").unwrap();
assert_eq!(real_data, b"original");
}
}Test Scenarios:
Load Generation:
Chaos Engineering:
Adversarial Evaluation:
Fuzzing:
Target Certifications:
| Feature | Variants | 360 | Kaspersky | Defender | CrowdStrike |
|---|---|---|---|---|---|
| Architecture | KD + CoW + AST | VT-x Hypervisor | Behavior Monitor | System Integrated | Cloud Sensor |
| Main Defense | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Detection Rate | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Performance | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Offline Capability | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ |
| Recovery | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
| Self-Protection | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| Anti-Rootkit | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Resource Usage | Heavy | Medium | Medium | Minimal | Minimal |
| Price | Free/Paid | Free | $40/yr | Free | $99/yr/endpoint |
Strengths:
Weaknesses:
Variants Advantage:
360 Advantage:
Strengths:
Weaknesses:
Variants Advantage:
Kaspersky Advantage:
Strengths:
Weaknesses:
Variants Advantage:
Defender Advantage:
Why Defender + Variants is the ultimate combo:
Defender: Handles known threats efficiently (low overhead)
Variants: Catches advanced threats Defender misses (kernel debugger)
Both: If one fails, the other has a chanceStrengths:
Weaknesses:
Variants Advantage:
CrowdStrike Advantage:
Target Audience Difference:
| Feature | Variants | ClamAV | Symantec EP | CrowdStrike (Linux) |
|---|---|---|---|---|
| Architecture | Kernel Module + ptrace | Signature Scanner | Agent + Kernel Module | Sensor (eBPF) |
| Rootkit Detection | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Performance | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Deep System Protection | ⭐⭐⭐⭐⭐ | ⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Offline Capability | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
| Recovery | ⭐⭐⭐⭐⭐ | ⭐ | ⭐⭐⭐ | ⭐⭐ |
| Price | Free/Paid | Free | $40+/endpoint/yr | $99+/endpoint/yr |
Strengths:
Weaknesses:
Variants Advantage:
ClamAV Advantage:
When to use ClamAV:
Strengths:
Weaknesses:
Variants Advantage:
SEP Advantage:
Strengths:
Weaknesses:
Variants Advantage:
Falcon Advantage:
Why malware often wins:
Defender's Dilemma:
┌─────────────────────────────────────────────────┐
│ Malware Developer │
│ - Only needs to find ONE bypass │
│ - Can test against all AVs before release │
│ - No compatibility concerns (can break systems) │
│ - No false positive concerns │
└─────────────────────────────────────────────────┘
VS
┌─────────────────────────────────────────────────┐
│ Antivirus Vendor │
│ - Must block ALL attack vectors │
│ - Can't test every malware (new ones daily) │
│ - Must maintain system stability │
│ - Must minimize false positives │
└─────────────────────────────────────────────────┘Examples:
Variants' Approach to Narrow the Gap:
Layer 1: Kernel Debugger (highest privilege)
Layer 2: Driver Protection (ELAM, signature validation)
Layer 3: CoW File System (transaction safety)
Layer 4: PowerShell Watchdog (self-healing)
Layer 5: Recovery OS (last resort)But Ultimately:
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Driver blue screen | Medium | Critical | Extensive testing, Rust safety, panic recovery |
| False positive epidemic | Medium | High | Gradual rollout, user feedback loop, ML retraining |
| Cloud outage | Low | Medium | Local-only fallback mode, cached rules |
| DBG performance impact | High | Medium | Selective monitoring, user-mode fallback |
| Rootkit bypass | Medium | High | Multi-layer defense, Recovery OS, continuous research |
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Cannot obtain WHQL | Medium | High | Launch in test-signing mode initially |
| Cloud costs exceed revenue | Medium | High | Tiered pricing, usage limits |
| Legal challenges (DMCA) | Low | Critical | Legal review, clear EULA |
| Competition from big players | High | Medium | Focus on niche (power users), open-source trust |
| Version | Date | Author | Changes |
|---|---|---|---|
| 1.0.0 | 2026-01-17 | Variants Team | Initial specification |
| 1.1.0 | 2026-01-17 | Variants Team | Added: PowerShell watchdog, kernel debugger mode, Linux rootkit detection, competitive analysis |
Document Status: Ready for Implementation
Next Review: 2026-02-17
Approval Required: Technical Lead, Security Architect