export const meta = { name: 'endpoint-agent-security-audit', description: 'Security and performance audit of endpoint plugin, C# agent, and tray', phases: [ { title: 'Discovery', detail: 'Find code, binaries, and VM runtime state' }, { title: 'Code Security', detail: 'Multi-lens security review of source code', model: 'opus' }, { title: 'Runtime Security', detail: 'VM runtime analysis and threat surface', model: 'opus' }, { title: 'Performance', detail: 'Resource usage and optimization opportunities' }, { title: 'Verify', detail: 'Adversarially verify high-severity findings', model: 'opus' }, { title: 'Synthesize', detail: 'Security report and optimization plan', model: 'opus' } ] } const FINDINGS_SCHEMA = { type: 'object', properties: { findings: { type: 'array', items: { type: 'object', properties: { component: { type: 'string', enum: ['endpoint-plugin', 'csharp-agent', 'tray', 'vm-runtime'] }, severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] }, category: { type: 'string' }, title: { type: 'string' }, description: { type: 'string' }, exploitation: { type: 'string' }, recommendation: { type: 'string' } }, required: ['component', 'severity', 'category', 'title', 'description', 'recommendation'] } } }, required: ['findings'] } const VERDICT_SCHEMA = { type: 'object', properties: { confirmed: { type: 'boolean' }, severity_adjustment: { type: 'string' }, reasoning: { type: 'string' } }, required: ['confirmed', 'reasoning'] } // Phase 1: Discovery phase('Discovery') log('Discovering endpoint components and VM runtime state...') const discovery = await parallel([ () => agent(`Find all Python files in plugins/endpoints/ directory. List API routes, models, and key functionality.`, { label: 'Map endpoint plugin', phase: 'Discovery' }), () => agent(`Find the C# agent source code. Look for: agent/, Agent/, or .cs files related to endpoint collection. List key files and what they do.`, { label: 'Find C# agent code', phase: 'Discovery' }), () => agent(`Find the tray application source code. Look for tray-related .cs files. What does the tray do?`, { label: 'Find tray code', phase: 'Discovery' }), () => agent(`Check if there are compiled executables in publish/ or deploy/ directories. What .exe files exist for deployment?`, { label: 'Find binaries', phase: 'Discovery' }), () => agent(`Use VM MCP to check what processes are running on SFTest related to ShopDB. Run: Get-Process | Where-Object {$_.ProcessName -like '*shopdb*' -or $_.ProcessName -like '*agent*' -or $_.ProcessName -like '*tray*'} | Select-Object Name,Id,CPU,WorkingSet,Path`, { label: 'Check VM processes', phase: 'Discovery' }) ]) const [endpointPlugin, agentCode, trayCode, binaries, vmProcesses] = discovery log('Discovery complete') // Phase 2: Code Security Review phase('Code Security') log('Performing multi-lens code security review...') const CODE_SECURITY_DIMENSIONS = [ { key: 'endpoint-injection', prompt: `Review plugins/endpoints/api/routes.py for injection vulnerabilities. Look for: - SQL injection in raw queries or unsafe ORM usage - Command injection in subprocess/exec calls - Path traversal in file operations - LDAP injection in directory queries - Expression injection in eval/exec Context: This is the backend that receives data from agents on shop floor PCs. Return ONLY exploitable vulnerabilities with proof of concept.`, component: 'endpoint-plugin' }, { key: 'endpoint-auth', prompt: `Review authentication and authorization in plugins/endpoints/. Look for: - Weak token generation or validation - Missing authentication on sensitive endpoints - Authorization bypass opportunities - Session fixation or hijacking - Credential exposure in logs or errors Context: Agents use service tokens (ADR-016), users use JWT. Return findings with exploitation scenarios.`, component: 'endpoint-plugin' }, { key: 'endpoint-data-validation', prompt: `Review data validation in endpoint plugin collector payload handling. Look for: - Missing input validation on agent payloads - Type confusion attacks - Buffer overflow potential - Integer overflow in size calculations - Unsafe deserialization Context: Agents POST JSON payloads to /api/collector/endpoints. Return exploitable issues.`, component: 'endpoint-plugin' }, { key: 'csharp-security', prompt: `Review C# agent code for security vulnerabilities. C# Agent Code: ${agentCode} Look for: - Unsafe P/Invoke or interop - Insecure file operations or temp file usage - Process injection vulnerabilities - Privilege escalation paths - Hardcoded credentials or keys - Unsafe XML/JSON parsing - Registry manipulation without validation Context: Runs as Windows service with SYSTEM privileges. Return critical/high findings only.`, component: 'csharp-agent' }, { key: 'tray-security', prompt: `Review tray application for security issues. Tray Code: ${trayCode} Look for: - Inter-process communication vulnerabilities - Named pipe security - Local privilege escalation - DLL hijacking opportunities - Insecure update mechanism - User data exposure Context: Runs in user session, communicates with SYSTEM service. Return exploitable vulnerabilities.`, component: 'tray' }, { key: 'secrets-exposure', prompt: `Search ALL endpoint-related code for exposed secrets or credentials. Files to check: - plugins/endpoints/ - C# agent: ${agentCode} - Tray: ${trayCode} - Config files Look for: - Hardcoded passwords, tokens, keys - Connection strings with credentials - API keys in code - Cryptographic keys in source - Comments containing credentials Return ALL findings regardless of severity.`, component: 'endpoint-plugin' } ] const codeSecurityFindings = await parallel( CODE_SECURITY_DIMENSIONS.map(dim => () => agent(dim.prompt, { label: `Security: ${dim.key}`, phase: 'Code Security', schema: FINDINGS_SCHEMA, model: 'opus', effort: 'high' }).then(result => result ? result.findings.map(f => ({...f, component: dim.component})) : []) ) ) const allCodeFindings = codeSecurityFindings.filter(Boolean).flat() log(`Found ${allCodeFindings.length} code security findings`) // Phase 3: Runtime Security on VM phase('Runtime Security') log('Analyzing runtime security on SFTest VM...') const RUNTIME_DIMENSIONS = [ { key: 'vm-attack-surface', prompt: `Analyze the attack surface of components running on SFTest VM. Running processes: ${vmProcesses} Binaries: ${binaries} Look for: - Network ports/services exposed - IPC mechanisms (named pipes, shared memory) - File system access patterns - Registry keys accessed - Privilege levels and escalation paths What can an attacker compromise from: 1. Another process on same machine 2. Network access 3. Unprivileged user account Return threat model and attack vectors.` }, { key: 'vm-persistence', prompt: `Review persistence mechanisms of agent and tray on SFTest. Running processes: ${vmProcesses} Check: - Windows services configuration - Startup entries (registry, startup folder) - Scheduled tasks - Can malware hijack these mechanisms? - Are there weak permissions allowing replacement? Return security risks in persistence layer.` }, { key: 'vm-communication', prompt: `Analyze communication security between tray, agent, and server. Context: - Agent is Windows service (SYSTEM) - Tray runs in user session - Both communicate with Flask backend Check: - How do tray and service communicate? - Is IPC authenticated/encrypted? - Can user tamper with service via tray? - Are network communications encrypted? - Certificate validation? Return exploitable communication vulnerabilities.` } ] const runtimeFindings = await parallel( RUNTIME_DIMENSIONS.map(dim => () => agent(dim.prompt, { label: `Runtime: ${dim.key}`, phase: 'Runtime Security', schema: FINDINGS_SCHEMA, model: 'opus', effort: 'high' }).then(result => result ? result.findings.map(f => ({...f, component: 'vm-runtime'})) : []) ) ) const allRuntimeFindings = runtimeFindings.filter(Boolean).flat() log(`Found ${allRuntimeFindings.length} runtime security findings`) // Phase 4: Performance Analysis phase('Performance') log('Analyzing performance and resource usage...') const PERFORMANCE_DIMENSIONS = [ { key: 'resource-usage', prompt: `Analyze resource usage of agent and tray on VM. VM Processes: ${vmProcesses} Assess: - CPU usage (acceptable for background service?) - Memory footprint (is this lean or bloated?) - Disk I/O patterns - Network bandwidth usage - Battery impact on laptops Return performance issues and optimization opportunities.` }, { key: 'collection-efficiency', prompt: `Review collection efficiency in endpoint plugin. Plugin code: ${endpointPlugin} Look for: - Redundant data collection - Inefficient queries - Unnecessary polling - Can collection frequency be reduced? - Are we collecting data we don't use? Return optimization recommendations with impact estimate.` }, { key: 'agent-optimization', prompt: `Find optimization opportunities in C# agent. Agent code: ${agentCode} Look for: - Polling intervals (can we increase them?) - Unnecessary WMI queries - Redundant process enumeration - Memory leaks or inefficient allocations - Can we batch operations? - Threading inefficiencies Return concrete optimizations with expected savings.` }, { key: 'tray-optimization', prompt: `Find ways to reduce tray application footprint. Tray code: ${trayCode} Look for: - UI refresh frequency - Background work frequency - Can it be more event-driven vs polling? - Memory usage optimization - Startup time reduction Return optimizations prioritized by user impact.` } ] const performanceFindings = await parallel( PERFORMANCE_DIMENSIONS.map(dim => () => agent(dim.prompt, { label: `Perf: ${dim.key}`, phase: 'Performance', schema: FINDINGS_SCHEMA }) ) ) const allPerfFindings = performanceFindings.filter(Boolean).flatMap(r => r.findings) log(`Found ${allPerfFindings.length} performance opportunities`) // Phase 5: Adversarial Verification phase('Verify') const allFindings = [...allCodeFindings, ...allRuntimeFindings, ...allPerfFindings] const criticalFindings = allFindings.filter(f => f.severity === 'critical' || f.severity === 'high') log(`Adversarially verifying ${criticalFindings.length} critical/high findings...`) const verified = await pipeline( criticalFindings, async (finding) => { const votes = await parallel([ () => agent(`Try to REFUTE this security finding. Be skeptical. Finding: ${finding.title} Component: ${finding.component} Category: ${finding.category} Description: ${finding.description} Is this actually exploitable? Can it be reached? Is the impact real? Default to confirmed=false if uncertain.`, { phase: 'Verify', schema: VERDICT_SCHEMA, model: 'opus', effort: 'high' }), () => agent(`ADVERSARIALLY verify this finding from a different angle. Finding: ${finding.title} Description: ${finding.description} Consider: Is there a mitigating control we missed? Is the exploitation scenario realistic? Be harsh in assessment.`, { phase: 'Verify', schema: VERDICT_SCHEMA, model: 'opus', effort: 'high' }) ]) const confirmedVotes = votes.filter(Boolean).filter(v => v.confirmed).length const survives = confirmedVotes >= 1 return survives ? { ...finding, verified: true, verificationReasoning: votes.filter(Boolean).map(v => v.reasoning).join(' | ') } : null } ) const confirmedFindings = verified.filter(Boolean) log(`${confirmedFindings.length} findings confirmed after adversarial verification`) // Phase 6: Synthesize Report phase('Synthesize') log('Generating comprehensive security and optimization report...') const report = await agent(`Create a comprehensive security and optimization report. VERIFIED CRITICAL/HIGH FINDINGS: ${JSON.stringify(confirmedFindings, null, 2)} ALL FINDINGS SUMMARY: - Code security: ${allCodeFindings.length} - Runtime security: ${allRuntimeFindings.length} - Performance: ${allPerfFindings.length} Create report with: # Executive Summary - Overall security posture - Most critical risks (top 3) - Quick wins for security - Performance optimization summary # Security Findings ## Critical Issues (fix immediately) ## High Priority Issues ## Medium/Low Issues # Runtime Environment Analysis - Attack surface assessment - VM security posture - Inter-process communication risks # Performance Optimization Plan ## Quick Wins (easy, high impact) ## Medium Effort Optimizations ## Long-term Improvements - Estimated resource savings for each # Recommendations 1. Immediate actions (this week) 2. Short-term (this sprint) 3. Long-term improvements # Deployment Safety - Are the agents safe to deploy as-is? - What must be fixed before wider rollout? Format as actionable guidance with specific file paths and line numbers where available.`, { phase: 'Synthesize', model: 'opus', effort: 'high' }) return { report, stats: { codeSecurityFindings: allCodeFindings.length, runtimeSecurityFindings: allRuntimeFindings.length, performanceOpportunities: allPerfFindings.length, criticalVerified: confirmedFindings.length }, confirmedCritical: confirmedFindings, allFindings: allFindings }