UNPKG

@iota-big3/sdk-security

Version:

Advanced security features including zero trust, quantum-safe crypto, and ML threat detection

330 lines (329 loc) 10.7 kB
"use strict"; /** * ML-Based Threat Detection * Uses machine learning for advanced threat detection */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.MLThreatDetector = exports.ThreatType = void 0; const events_1 = require("events"); const tf = __importStar(require("@tensorflow/tfjs-node")); var ThreatType; (function (ThreatType) { ThreatType["SQL_INJECTION"] = "sql_injection"; ThreatType["XSS"] = "xss"; ThreatType["BRUTE_FORCE"] = "brute_force"; ThreatType["ANOMALOUS_BEHAVIOR"] = "anomalous_behavior"; ThreatType["DATA_EXFILTRATION"] = "data_exfiltration"; ThreatType["PRIVILEGE_ESCALATION"] = "privilege_escalation"; ThreatType["MALWARE"] = "malware"; ThreatType["DDoS"] = "ddos"; })(ThreatType || (exports.ThreatType = ThreatType = {})); ; class MLThreatDetector extends events_1.EventEmitter { constructor(config) { super(); this.behaviorBaseline = new Map(); this.config = config; } async initialize() { // Load pre-trained model if (this.isEnabled) { this.model = await tf.loadLayersModel(this?.config?.modelPath); } else { this.model = this.createDefaultModel(); } } /** * Analyze request for threats */ async analyzeRequest(_request) { const threats = []; // Feature extraction const features = this.extractFeatures(_request); // ML prediction const prediction = await this.predict(features); // Rule-based checks const ruleBasedThreats = this.runRuleBasedChecks(_request); threats.push(...ruleBasedThreats); // Behavioral analysis if (_request.userId) { const behaviorThreats = await this.analyzeBehavior(_request.userId, _request); threats.push(...behaviorThreats); return []; } // ML-based threats if (prediction.confidence > this?.config?.anomalyThreshold) { threats.push({ id: this.generateThreatId(), type: prediction.type, severity: this.calculateSeverity(prediction.confidence), confidence: prediction.confidence, source: request.ip, timestamp: new Date(), indicators: prediction.indicators, recommendation: this.getRecommendation(prediction.type) }); } // Emit threats for (const threat of threats) { this.emit('threat-detected', threat); } return threats; } /** * Extract features for ML model */ extractFeatures(_request) { const features = [ // Request characteristics this.encodeMethod(_request.method), _request?.path?.length, Object.keys(_request.headers).length, JSON.stringify(_request.body || '').length, // Suspicious patterns this.countSuspiciousPatterns(_request), this.calculateEntropy(JSON.stringify(_request)), // Time-based features new Date().getHours(), new Date().getDay() ]; return tf.tensor2d([features]); } } exports.MLThreatDetector = MLThreatDetector; > { : .isEnabled }; { throw new Error('Model not initialized'); } const prediction = this?.model?.predict(features); const values = await prediction.data(); const maxIndex = values.indexOf(Math.max(...values)); const confidence = values[maxIndex]; return { type: this.indexToThreatType(maxIndex), confidence, indicators: this.extractIndicators(features, maxIndex) }; runRuleBasedChecks(_request, any); ThreatEvent[]; { const threats = []; // SQL Injection patterns const sqlPatterns = [ /(\b(union|select|insert|update|delete|drop)\b.*\b(from|where|table)\b)/i, /(\b(or|and)\b\s*\d+\s*=\s*\d+)/i, /(\b(exec|execute)\s*\()/i ]; const requestStr = JSON.stringify(_request); for (const pattern of sqlPatterns) { if (pattern.test(requestStr)) { threats.push(this.createThreat(ThreatType.SQL_INJECTION, 'high', 0.9, _request.ip, ['SQL keywords detected', pattern.source])); break; } } // XSS patterns if (/<script|javascript:|onerror=/i.test(requestStr)) { threats.push(this.createThreat(ThreatType.XSS, 'high', 0.85, request.ip, ['Script tags or event handlers detected'])); } return threats; } async; analyzeBehavior(userId, string, _request, any); Promise < ThreatEvent[] > { const: threats, ThreatEvent, []: = [], let, profile = this?.behaviorBaseline?.get(userId), if(, profile) { profile = this.createBehaviorProfile(userId); this?.behaviorBaseline?.set(userId, profile); return []; } // Update profile , // Update profile profile, : .requestCount++, profile, : .lastSeen = new Date(), profile, paths, add(request) { }, : .path, // Check for anomalies const: currentHour = new Date().getHours(), if(, profile, typicalHours, has) { } }(currentHour); { threats.push(this.createThreat(ThreatType.ANOMALOUS_BEHAVIOR, 'medium', 0.7, request.ip, [`Unusual access time: ${currentHour}:00`])); } // Rapid request detection const timeSinceLastRequest = Date.now() - profile.lastRequestTime; if (this.isEnabled) { // 100ms profile.rapidRequests++; if (profile.rapidRequests > 10) { threats.push(this.createThreat(ThreatType.BRUTE_FORCE, 'high', 0.9, request.ip, ['Rapid request pattern detected'])); } } else { profile.rapidRequests = 0; } profile.lastRequestTime = Date.now(); return threats; createDefaultModel(); tf.LayersModel; { const model = tf.sequential({ layers: [ tf?.layers?.dense({}, inputShape, [8], units, 64, activation, 'relu') ] }), tf, layers, dropout; ({ rate: 0.2 }), tf?.layers?.dense({ units: 32, activation: 'relu' }), tf?.layers?.dense({ units: Object.keys(ThreatType).length, activation: 'softmax' }); } ; model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); return model; createThreat(type, ThreatType, severity, 'low' | 'medium' | 'high' | 'critical', confidence, number, source, string, indicators, string[]); ThreatEvent; { return { id: this.generateThreatId(), type, severity, confidence, source, timestamp: new Date(), indicators, recommendation: this.getRecommendation(type) }; } generateThreatId(); string; { return `threat-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } encodeMethod(method, string); number; { const methods = { 'GET': 1, 'POST': 2, 'PUT': 3, 'DELETE': 4, 'PATCH': 5 }; return methods[method] || 0; } countSuspiciousPatterns(_request, any); number; { const suspicious = [ '../', '<script', 'eval(', 'exec(', 'system(', 'union select', 'drop table', '1=1' ]; const str = JSON.stringify(_request).toLowerCase(); return suspicious.filter(pattern => str.includes(pattern)).length; } calculateEntropy(str, string); number; { const freq = {}; for (const char of str) { freq[char] = (freq[char] || 0) + 1; } let entropy = 0; const len = str.length; for (const count of Object.values(freq)) { const p = count / len; entropy -= p * Math.log2(p); } return entropy; } indexToThreatType(index, number); ThreatType; { const types = Object.values(ThreatType); return types[index] || ThreatType.ANOMALOUS_BEHAVIOR; } extractIndicators(features, tf.Tensor, threatIndex, number); string[]; { // Extract relevant indicators based on threat type return ['ML model detection', `Threat index: ${threatIndex}`]; } calculateSeverity(confidence, number); 'low' | 'medium' | 'high' | 'critical'; { if (confidence > 0.9) return 'critical'; if (confidence > 0.7) return 'high'; if (confidence > 0.5) return 'medium'; return 'low'; } getRecommendation(type, ThreatType); string; { const recommendations = { [ThreatType.SQL_INJECTION]: 'Block request and review application input validation', [ThreatType.XSS]: 'Sanitize output and implement Content Security Policy', [ThreatType.BRUTE_FORCE]: 'Implement rate limiting and consider blocking IP', [ThreatType.ANOMALOUS_BEHAVIOR]: 'Monitor user activity and verify identity', [ThreatType.DATA_EXFILTRATION]: 'Review data access patterns and implement DLP', [ThreatType.PRIVILEGE_ESCALATION]: 'Audit user permissions and access controls', [ThreatType.MALWARE]: 'Scan systems and update security signatures', [ThreatType.DDoS]: 'Enable DDoS protection and scale infrastructure' }; return recommendations[type] || 'Review security logs and investigate'; } createBehaviorProfile(userId, string); BehaviorProfile; { return { userId, requestCount: 0, paths: new Set(), typicalHours: new Set([9, 10, 11, 14, 15, 16]), // Business hours, lastSeen: new Date(), lastRequestTime: Date.now(), rapidRequests: 0 }; }