@iota-big3/sdk-security
Version:
Advanced security features including zero trust, quantum-safe crypto, and ML threat detection
924 lines • 37.4 kB
JavaScript
"use strict";
/**
* @iota-big3/sdk-security - Clean Security Manager
* Main security management system
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecurityManager = void 0;
const events_1 = require("events");
const adapters_1 = require("./adapters");
const enhanced_security_scanner_1 = require("./enhanced-security-scanner");
const forensics_manager_1 = require("./forensics/forensics-manager");
const types_1 = require("./forensics/types");
const automated_detector_1 = require("./incident-response/automated-detector");
const incident_response_manager_1 = require("./incident-response/incident-response-manager");
const types_2 = require("./incident-response/types");
const secrets_manager_1 = require("./secrets/secrets-manager");
class SecurityManager extends events_1.EventEmitter {
constructor(options) {
super();
this.isEnabled = true;
this.events = [];
this.scanResults = [];
this.isInitialized = false;
// Handle both old style (just config) and new style (with integrations)
if ('config' in options) {
this.integrations = options;
this.config = this.mergeWithCoreConfig(options.config);
}
else {
this.config = this.mergeWithCoreConfig(options);
this.integrations = { config: this.config };
}
// Create adapters for integrations
if (this.integrations.database) {
this.database = (0, adapters_1.createDatabaseAdapter)(this.integrations.database);
}
if (this.integrations.eventBus) {
this.eventBus = (0, adapters_1.createEventsAdapter)(this.integrations.eventBus);
}
this.metrics = {
threatsDetected: 0,
threatsBlocked: 0,
vulnerabilities: 0,
complianceScore: 100,
lastScanTime: 0,
uptime: Date.now()
};
// Setup event listeners if eventBus available
if (this.eventBus) {
this.setupEventListeners();
}
}
mergeWithCoreConfig(config) {
// Get config from core SDK if available
let coreConfig = {};
if (this.integrations?.core?.config) {
coreConfig = this.integrations.core.config.get('security') || {};
}
return {
zeroTrust: { enabled: false, ...config.zeroTrust },
quantumSafe: { enabled: false, algorithm: 'KYBER', keySize: 1024, ...config.quantumSafe },
threatDetection: { enabled: false, mlEnabled: false, realTimeScanning: false, anomalyDetection: false, ...config.threatDetection },
compliance: { enabled: false, standards: [], auditEnabled: false, ...config.compliance },
audit: { enabled: false, logLevel: 'INFO', retention: 30, encryption: true, ...config.audit },
iam: {
enabled: false,
rbacEnabled: false,
sessionTimeout: coreConfig.sessionTimeout || 30,
passwordPolicy: {
minLength: coreConfig.passwordMinLength || 8,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSpecialChars: false,
maxAge: 90,
...config.iam?.passwordPolicy
},
...config.iam,
mfaRequired: coreConfig.mfaRequired ?? config.iam?.mfaRequired
},
forensics: {
enabled: false,
evidenceStorage: {
path: './forensics/evidence',
encrypted: true
},
incidentResponseIntegration: true,
siemIntegration: this.config.siem
}
};
}
setupEventListeners() {
if (!this.eventBus)
return;
// Listen for user creation events
this.eventBus.on('auth:user.created', async (event) => {
if (this.integrations.logger) {
this.integrations.logger.info('Creating default security settings for new user', { userId: event.userId });
}
// Create default security settings for new user
await this.createUserSecurityDefaults(event.userId);
});
// Listen for configuration changes
if (this.integrations.core?.config) {
this.integrations.core.config.on?.('config:changed', async (event) => {
if (event.key.startsWith('security.')) {
if (this.integrations.logger) {
this.integrations.logger.info('Security configuration updated', event);
}
// Reload configuration
this.config = this.mergeWithCoreConfig(this.config);
this.emit('security:config.updated', event);
}
});
}
}
async initialize() {
if (this.isInitialized)
return;
try {
// Initialize database adapter
if (this.database) {
await this.database.connect();
}
// Initialize event bus adapter
if (this.eventBus) {
await this.eventBus.connect();
}
// Initialize enhanced scanner if SIEM/vulnerability scanning is configured
if (this.config.siem || this.config.vulnerabilityScanning) {
const enhancedConfig = {
siemConfigs: this.config.siem?.map(siemConfig => ({
platform: siemConfig.platform,
enabled: true,
endpoint: siemConfig.endpoint,
authentication: {
type: siemConfig.authType || 'API_KEY',
credentials: siemConfig.credentials
},
batchSize: 100,
flushInterval: 5000
})),
vulnerabilityScanners: this.config.vulnerabilityScanning?.scanners,
orchestration: this.config.securityOrchestration,
waf: this.config.waf,
ddosProtection: this.config.ddosProtection
};
this.enhancedScanner = new enhanced_security_scanner_1.EnhancedSecurityScanner(enhancedConfig);
// Forward enhanced scanner events
this.enhancedScanner.on('error', (error) => {
this.emit('security:error', error);
});
this.enhancedScanner.on('siem:error', (error) => {
this.emit('siem:error', error);
});
this.enhancedScanner.on('scan:completed', (scan) => {
this.emit('scan:completed', scan);
});
}
// Initialize secrets management if configured
if (this.config.secretsManagement?.enabled) {
const secretsConfig = {
primary: this.config.secretsManagement.primary,
providers: this.config.secretsManagement.providers.map(p => ({
provider: p.type,
endpoint: p.endpoint,
region: p.region,
namespace: p.namespace,
authentication: p.authentication,
caching: this.config.secretsManagement?.caching
})),
syncEnabled: this.config.secretsManagement.syncEnabled || false,
conflictResolution: 'PRIMARY'
};
this.secretsManager = new secrets_manager_1.MultiProviderSecretsManager(secretsConfig);
await this.secretsManager.initialize();
// Forward secrets manager events
this.secretsManager.on('error', (error) => {
this.emit('secrets:error', error);
});
this.secretsManager.on('audit', (event) => {
this.emit('secrets:audit', event);
});
}
// Initialize incident response if configured
if (this.config.incidentResponse?.enabled) {
this.incidentManager = new incident_response_manager_1.IncidentResponseManager({
autoEscalation: this.config.incidentResponse.autoEscalation,
retentionDays: this.config.incidentResponse.retentionDays,
notificationConfig: this.config.incidentResponse.notifications,
integrations: {
siem: this.config.incidentResponse.siemIntegration,
ticketing: this.config.incidentResponse.ticketing
}
});
await this.incidentManager.initialize();
// Initialize automated detection
this.incidentDetector = new automated_detector_1.AutomatedIncidentDetector(this.incidentManager);
this.incidentDetector.start();
// Forward incident events
this.incidentManager.on('incident:created', (incident) => {
this.emit('incident:created', incident);
this.recordSecurityEvent({
id: crypto.randomUUID(),
timestamp: new Date(),
type: 'INCIDENT_CREATED',
severity: incident.severity,
description: `Incident created: ${incident.title}`,
source: 'incident-response',
metadata: { incidentId: incident.id }
});
});
this.incidentDetector.on('incident:auto-created', (data) => {
this.emit('incident:auto-detected', data);
});
// Connect to security scanner
if (this.enhancedScanner) {
this.enhancedScanner.on('vulnerability:critical', async (vuln) => {
await this.createSecurityIncident({
title: `Critical Vulnerability: ${vuln.title}`,
description: vuln.description,
type: types_2.IncidentType.MISCONFIGURATION,
severity: types_2.IncidentSeverity.CRITICAL,
affectedSystems: [vuln.system || 'unknown']
});
});
}
}
// Initialize forensics if configured
if (this.config.forensics?.enabled) {
this.forensicsManager = new forensics_manager_1.ForensicsManager({
evidenceStorage: this.config.forensics.evidenceStorage || {
path: './forensics/evidence',
encrypted: true
},
incidentResponseIntegration: true,
siemIntegration: this.config.siem
});
await this.forensicsManager.initialize();
// Connect forensics to incident response
if (this.incidentManager) {
this.forensicsManager.on('forensics:findings', async (data) => {
// Create incident from forensic findings
const incident = await this.incidentManager.createIncident({
title: `Forensic Evidence: ${data.findings[0]?.title || 'Multiple Findings'}`,
description: `Forensic analysis revealed ${data.findings.length} findings`,
type: this.mapForensicFindingToIncidentType(data.findings[0]?.type),
severity: this.mapForensicSeverityToIncidentSeverity(data.findings[0]?.severity),
source: types_2.IncidentSource.INTERNAL_DETECTION,
evidence: data.findings.map(f => ({
id: f.id,
type: types_2.EvidenceType.FORENSIC,
collectedAt: new Date(),
collectedBy: 'ForensicsManager',
description: f.description,
hash: crypto.randomUUID(),
size: 0,
metadata: {
caseId: data.caseId,
evidenceId: data.evidenceId,
finding: f
}
}))
});
this.emit('forensics:incident-created', { incident, caseId: data.caseId });
});
}
}
this.initializeMetrics();
this.setupEventHandlers();
this.isInitialized = true;
this.emit('security:initialized', {
timestamp: new Date(),
config: this.sanitizeConfig(this.config)
});
}
catch (error) {
this.emit('security:error', error);
throw error;
}
}
async createDatabaseTables() {
if (!this.database)
return;
// In a real implementation, this would create tables
// For now, we'll just log
if (this.integrations.logger) {
this.integrations.logger.debug('Creating security database tables');
}
}
async registerGatewayRoutes() {
if (!this.integrations.gateway)
return;
// Register health endpoint
this.integrations.gateway.registerRoute?.({
path: '/security/health',
method: 'GET',
handler: async () => this.getHealth(),
middleware: []
});
// Register audit query endpoint
this.integrations.gateway.registerRoute?.({
path: '/security/audit/query',
method: 'POST',
handler: async (req) => this.queryAuditLogs(req.body),
middleware: ['authenticate', 'authorize']
});
}
async registerGatewayMiddleware() {
if (!this.integrations.gateway)
return;
this.integrations.gateway.registerMiddleware?.({
name: 'security',
middleware: async (req, res, next) => {
// Security middleware logic
const token = req.headers.authorization?.replace('Bearer ', '');
if (token) {
const session = await this.validateSession(token);
if (session) {
req.user = session.user;
}
}
next();
},
priority: 100
});
}
async authenticate(credentials) {
const startTime = Date.now();
if (this.integrations.logger) {
this.integrations.logger.info('Authentication attempt', { username: credentials.username });
}
try {
// Check user in database
if (this.database) {
const result = await this.database.query('SELECT * FROM users WHERE username = ?', [credentials.username]);
if (result.rows && result.rows.length > 0) {
const user = result.rows[0];
// In real implementation, verify password hash
if (user.passwordHash) {
const sessionId = this.generateSessionId();
// Cache session
if (this.integrations.cache) {
await this.integrations.cache.set(`session:${sessionId}`, {
userId: user.id,
username: user.username,
createdAt: Date.now()
}, this.config.iam?.sessionTimeout || 3600);
}
// Emit success event
if (this.eventBus) {
this.eventBus.emit('security:auth.success', {
userId: user.id,
username: user.username,
timestamp: Date.now(),
sessionId
});
}
// Log audit event
if (this.database) {
await this.database.insert('audit_events', {
id: this.generateId(),
event_type: 'authentication',
actor: JSON.stringify({ type: 'user', id: user.id, name: user.username }),
resource: JSON.stringify({ type: 'system', id: 'auth', name: 'Authentication' }),
action: 'login',
outcome: 'success',
timestamp: new Date()
});
}
return { success: true, userId: user.id, sessionId };
}
}
}
// Authentication failed
if (this.eventBus) {
this.eventBus.emit('security:auth.failed', {
username: credentials.username,
reason: 'Invalid credentials',
timestamp: Date.now()
});
}
return { success: false, reason: 'Invalid credentials' };
}
catch (error) {
if (this.integrations.logger) {
this.integrations.logger.error('Authentication error', { error, username: credentials.username });
}
return { success: false, reason: 'Authentication error' };
}
}
async validateSession(token) {
if (!this.integrations.cache)
return null;
const session = await this.integrations.cache.get(`session:${token}`);
return session;
}
async checkRateLimit(userId, resource) {
if (!this.integrations.gateway) {
return { allowed: true, remaining: 999 };
}
const rateLimiter = this.integrations.gateway.getRateLimiter?.();
if (rateLimiter) {
return await rateLimiter.checkLimit(userId, resource);
}
return { allowed: true, remaining: 999 };
}
async createUserSecurityDefaults(userId) {
// Create default security settings for new user
if (this.database) {
// Add default role
await this.database.insert('security_user_roles', {
user_id: userId,
role_id: 'user', // default user role
assigned_at: new Date()
});
}
}
async queryAuditLogs(query) {
if (!this.database)
return [];
const result = await this.database.query('SELECT * FROM audit_events WHERE timestamp > ? LIMIT ?', [query.startDate || new Date(Date.now() - 86400000), query.limit || 100]);
return result.rows || [];
}
getConfig() {
return { ...this.config };
}
async shutdown() {
this.isInitialized = false;
if (this.integrations.logger) {
this.integrations.logger.info('SecurityManager shutting down');
}
// Cleanup resources
if (this.eventBus) {
this.eventBus.removeAllListeners();
}
this.emit('security:shutdown');
}
isReady() {
return this.isInitialized;
}
async checkAccess(params) {
const startTime = Date.now();
if (this.integrations.logger) {
this.integrations.logger.debug('Checking access', params);
}
// Basic access check - in real implementation would use AccessControl
const allowed = true; // Mock for now
const event = {
id: this.generateId(),
type: allowed ? 'AUTHORIZATION_FAILURE' : 'AUTHORIZATION_FAILURE',
severity: allowed ? 'LOW' : 'MEDIUM',
timestamp: Date.now(),
source: 'access-control',
target: params.resource,
details: {
subject: params.subject,
action: params.action,
duration: Date.now() - startTime
},
resolved: true
};
this.recordEvent(event);
return { allowed, reason: allowed ? 'Access granted' : 'Access denied' };
}
async recordEvent(event) {
this.events.push(event);
// Persist to database
if (this.database) {
await this.database.insert('security_events', {
...event,
details: JSON.stringify(event.details)
});
}
// Emit event
this.emit('security:event', event);
}
async runScan(scanType, target) {
const scan = {
id: this.generateId(),
timestamp: Date.now(),
target,
scanType,
status: 'RUNNING',
findings: [],
score: 100
};
this.scanResults.push(scan);
// Simulate scan completion
setTimeout(() => {
scan.status = 'COMPLETED';
scan.score = 85;
this.metrics.lastScanTime = Date.now();
this.emit('scan:completed', scan);
}, 2000);
return scan;
}
getMetrics() {
return { ...this.metrics };
}
async getHealth() {
const checks = {
zeroTrust: this.config.zeroTrust?.enabled || false,
quantumSafe: this.config.quantumSafe?.enabled || false,
threatDetection: this.config.threatDetection?.enabled || false,
compliance: this.config.compliance?.enabled || false,
audit: this.config.audit?.enabled || false,
iam: this.config.iam?.enabled || false
};
const allEnabled = Object.values(checks).every(v => v);
const someEnabled = Object.values(checks).some(v => v);
return {
status: allEnabled ? 'healthy' : someEnabled ? 'degraded' : 'unhealthy',
message: allEnabled ? 'All security features enabled' : 'Some security features disabled',
checks,
lastUpdated: Date.now()
};
}
async healthCheck() {
return this.getHealth();
}
generateId() {
return `sec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
generateSessionId() {
return `sess_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Perform enhanced security scan with SIEM integration
*/
async performEnhancedScan(target, scanType) {
if (!this.enhancedScanner) {
throw new Error('Enhanced scanner not initialized. Configure SIEM or vulnerability scanning.');
}
const result = await this.enhancedScanner.scan(scanType || 'DAST', target);
// Store result
this.scanResults.push(result);
// Emit event
this.emit('scan:enhanced:completed', result);
return result;
}
/**
* Get current security posture from enhanced scanner
*/
async getSecurityPosture() {
if (!this.enhancedScanner) {
return {
enhanced: false,
message: 'Enhanced scanner not configured'
};
}
return await this.enhancedScanner.getSecurityPosture();
}
/**
* Filter request through WAF
*/
async filterRequest(request) {
if (!this.enhancedScanner) {
return { allowed: true };
}
return await this.enhancedScanner.filterRequest(request);
}
/**
* Update DDoS metrics
*/
updateDDoSMetrics(metrics) {
if (this.enhancedScanner) {
this.enhancedScanner.updateDDoSMetrics(metrics);
}
}
/**
* Get secret value
*/
async getSecret(name) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
const secret = await this.secretsManager.getSecret(name);
return secret.value;
}
/**
* Set secret value
*/
async setSecret(name, value, options) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
await this.secretsManager.setSecret(name, value, options);
}
/**
* Rotate secret
*/
async rotateSecret(name) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
await this.secretsManager.rotateSecret(name);
}
/**
* Create dynamic database credentials
*/
async createDynamicDatabaseCredentials(database, role) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
const lease = await this.secretsManager.createDynamicSecret({
type: 'DATABASE',
backend: database,
role: role || 'readonly',
ttl: 3600, // 1 hour
renewable: true
});
return lease.credentials;
}
/**
* Generate certificate
*/
async generateCertificate(commonName, options) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
return await this.secretsManager.generateCertificate({
commonName,
...options
});
}
/**
* Encrypt data using transit encryption
*/
async encryptData(plaintext) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
return await this.secretsManager.encrypt(plaintext);
}
/**
* Decrypt data
*/
async decryptData(ciphertext) {
if (!this.secretsManager) {
throw new Error('Secrets management not configured');
}
return await this.secretsManager.decrypt(ciphertext);
}
/**
* Create security incident
*/
async createSecurityIncident(incidentData) {
if (!this.incidentManager) {
throw new Error('Incident response not configured');
}
return await this.incidentManager.createIncident(incidentData);
}
/**
* Get incident by ID
*/
async getIncident(id) {
if (!this.incidentManager) {
throw new Error('Incident response not configured');
}
return await this.incidentManager.getIncident(id);
}
/**
* List active incidents
*/
async listActiveIncidents() {
if (!this.incidentManager) {
throw new Error('Incident response not configured');
}
return await this.incidentManager.listIncidents({
status: ['DETECTED', 'TRIAGED', 'INVESTIGATING', 'CONTAINED', 'ERADICATING', 'RECOVERING']
});
}
/**
* Execute incident response playbook
*/
async executePlaybook(incidentId, playbookId) {
if (!this.incidentManager) {
throw new Error('Incident response not configured');
}
await this.incidentManager.executePlaybook(incidentId, playbookId);
}
/**
* Add evidence to incident
*/
async addIncidentEvidence(incidentId, evidence) {
if (!this.incidentManager) {
throw new Error('Incident response not configured');
}
await this.incidentManager.addEvidence(incidentId, evidence);
}
/**
* Generate incident report
*/
async generateIncidentReport(incidentId, type = types_2.ReportType.FULL_REPORT) {
if (!this.incidentManager) {
throw new Error('Incident response not configured');
}
return await this.incidentManager.generateReport(incidentId, type);
}
/**
* Integrate security event processing with incident detection
*/
async processSecurityEventForIncidents(event) {
if (!this.incidentDetector)
return;
// Send to automated detector
await this.incidentDetector.processSecurityEvent(event);
// Check for specific high-risk events
if (event.severity === 'CRITICAL') {
// Auto-create incident for critical events
await this.createSecurityIncident({
title: `Critical Security Event: ${event.type}`,
description: event.description,
type: this.mapEventTypeToIncidentType(event.type),
severity: types_2.IncidentSeverity.HIGH,
source: 'AUTOMATED_DETECTION',
affectedSystems: event.metadata?.systems || [],
customFields: { securityEvent: event }
});
}
}
/**
* Map security event type to incident type
*/
mapEventTypeToIncidentType(eventType) {
const typeMap = {
'INTRUSION_DETECTED': types_2.IncidentType.UNAUTHORIZED_ACCESS,
'MALWARE_DETECTED': types_2.IncidentType.MALWARE,
'DATA_LEAK_DETECTED': types_2.IncidentType.DATA_BREACH,
'DDOS_DETECTED': types_2.IncidentType.DENIAL_OF_SERVICE,
'PHISHING_DETECTED': types_2.IncidentType.PHISHING,
'RANSOMWARE_DETECTED': types_2.IncidentType.RANSOMWARE,
'COMPLIANCE_VIOLATION': types_2.IncidentType.COMPLIANCE_VIOLATION
};
return typeMap[eventType] || types_2.IncidentType.OTHER;
}
/**
* Create forensic case
*/
async createForensicCase(caseData) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
return this.forensicsManager.createCase(caseData);
}
/**
* Add forensic evidence
*/
async addForensicEvidence(caseId, evidenceData) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
return this.forensicsManager.addEvidence(caseId, evidenceData);
}
/**
* Analyze forensic evidence
*/
async analyzeForensicEvidence(evidenceId) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
const result = await this.forensicsManager.analyzeEvidence(evidenceId);
// Send findings to threat detection
if (result.iocs && result.iocs.length > 0) {
for (const ioc of result.iocs) {
await this.checkThreatIndicator({
type: ioc.type,
value: ioc.value,
source: 'Forensics',
confidence: ioc.confidence || 80,
metadata: { evidenceId }
});
}
}
return result;
}
/**
* Generate forensic report
*/
async generateForensicReport(caseId, type = types_1.ReportType.FINAL) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
return this.forensicsManager.generateReport(caseId, type);
}
/**
* Capture memory dump for forensics
*/
async captureMemoryDump(targetSystem) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
// Create a case if needed
const forensicCase = await this.forensicsManager.createCase({
title: `Memory Dump - ${targetSystem || 'Local System'}`,
description: 'Automated memory capture for forensic analysis',
priority: types_1.CasePriority.HIGH
});
// Add memory evidence
const evidence = await this.forensicsManager.addEvidence(forensicCase.id, {
type: types_1.ForensicAnalysisType.MEMORY,
acquisitionMethod: types_1.AcquisitionMethod.LIVE_MEMORY,
sourceName: targetSystem || 'localhost',
sourceType: 'System Memory',
size: 8 * 1024 * 1024 * 1024, // Mock 8GB
acquisitionTool: 'IOTA Memory Capture'
});
this.emit('forensics:memory-captured', { caseId: forensicCase.id, evidenceId: evidence.id });
return evidence;
}
/**
* Capture network traffic for forensics
*/
async captureNetworkTraffic(duration = 300, filter) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
// Create a case
const forensicCase = await this.forensicsManager.createCase({
title: `Network Capture - ${new Date().toISOString()}`,
description: `Network traffic capture for ${duration} seconds`,
priority: types_1.CasePriority.MEDIUM
});
// Start capture (mock)
this.emit('forensics:capture-started', { type: 'network', duration });
// Add network evidence after duration
setTimeout(async () => {
const evidence = await this.forensicsManager.addEvidence(forensicCase.id, {
type: types_1.ForensicAnalysisType.NETWORK,
acquisitionMethod: types_1.AcquisitionMethod.NETWORK_CAPTURE,
sourceName: 'eth0',
sourceType: 'Network Interface',
size: 250 * 1024 * 1024, // Mock 250MB
acquisitionTool: 'IOTA Packet Capture',
acquisitionNotes: filter ? `Filter: ${filter}` : undefined
});
this.emit('forensics:network-captured', {
caseId: forensicCase.id,
evidenceId: evidence.id,
duration,
filter
});
}, duration * 1000);
return {}; // Return placeholder
}
/**
* Quick forensic triage
*/
async performForensicTriage(targetPath) {
if (!this.forensicsManager) {
throw new Error('Forensics not enabled');
}
// Create triage case
const forensicCase = await this.forensicsManager.createCase({
title: `Triage - ${targetPath}`,
description: 'Quick forensic triage for incident response',
priority: types_1.CasePriority.CRITICAL
});
// Collect multiple evidence types
const evidencePromises = [];
// Disk evidence
evidencePromises.push(this.forensicsManager.addEvidence(forensicCase.id, {
type: types_1.ForensicAnalysisType.DISK,
acquisitionMethod: types_1.AcquisitionMethod.LOGICAL_COPY,
sourceName: targetPath,
sourceType: 'File System',
size: 500 * 1024 * 1024 * 1024 // Mock 500GB
}));
// Log evidence
evidencePromises.push(this.forensicsManager.addEvidence(forensicCase.id, {
type: types_1.ForensicAnalysisType.LOG,
acquisitionMethod: types_1.AcquisitionMethod.LOG_COLLECTION,
sourceName: '/var/log',
sourceType: 'System Logs',
size: 1024 * 1024 * 1024 // Mock 1GB
}));
const evidence = await Promise.all(evidencePromises);
// Analyze all evidence
const analysisPromises = evidence.map(e => this.forensicsManager.analyzeEvidence(e.id));
const results = await Promise.all(analysisPromises);
// Generate quick report
const report = await this.forensicsManager.generateReport(forensicCase.id, types_1.ReportType.INITIAL);
return {
caseId: forensicCase.id,
evidence,
results,
report
};
}
/**
* Map forensic finding type to incident type
*/
mapForensicFindingToIncidentType(findingType) {
const mapping = {
'MALWARE': types_2.IncidentType.MALWARE,
'SUSPICIOUS_PROCESS': types_2.IncidentType.UNAUTHORIZED_ACCESS,
'NETWORK_CONNECTION': types_2.IncidentType.SUSPICIOUS_NETWORK,
'DATA_EXFILTRATION': types_2.IncidentType.DATA_BREACH,
'PERSISTENCE': types_2.IncidentType.MALWARE,
'PRIVILEGE_ESCALATION': types_2.IncidentType.UNAUTHORIZED_ACCESS,
'LATERAL_MOVEMENT': types_2.IncidentType.INSIDER_THREAT,
'DELETED_FILE': types_2.IncidentType.OTHER,
'REGISTRY_MODIFICATION': types_2.IncidentType.MISCONFIGURATION,
'LOG_TAMPERING': types_2.IncidentType.OTHER
};
return mapping[findingType || ''] || types_2.IncidentType.OTHER;
}
/**
* Map forensic severity to incident severity
*/
mapForensicSeverityToIncidentSeverity(severity) {
const mapping = {
'CRITICAL': types_2.IncidentSeverity.CRITICAL,
'HIGH': types_2.IncidentSeverity.HIGH,
'MEDIUM': types_2.IncidentSeverity.MEDIUM,
'LOW': types_2.IncidentSeverity.LOW,
'INFO': types_2.IncidentSeverity.INFO
};
return mapping[severity || ''] || types_2.IncidentSeverity.MEDIUM;
}
}
exports.SecurityManager = SecurityManager;
//# sourceMappingURL=security-manager.js.map