Security & Detection
DefenSys uses multiple detection layers and automated response capabilities to identify and mitigate network threats.
Overview
Security is built from rule-based detection, ML anomaly detection, network baseline learning, and firewall integration. Each layer is documented in detail:
- Detection Layers – Rule-based and ML detection
- Firewall – Auto-block and manual IP blocking
- Network Baseline – Behavioral learning and deviation detection
Detection Layers (Summary)
1. Multi-Layer Threat Detection
- Critical Port Access Detection
- Port Scanning Detection
- Brute Force Detection
- Data Exfiltration Detection
- Connection Flood Detection
- Protocol Anomaly Detection
- Malicious Pattern Detection
Threat scoring (0–200+) and behavioral analysis distinguish internal vs. external traffic.
2. ML-Powered Anomaly Detection
- Isolation Forest model (Python subprocess or mock)
- 20+ feature extraction (packet size, flow duration, ports, protocols)
- Real-time inference (<50ms latency)
- Configurable thresholds
3. Signature-Based Detection
- Suricata rules integration
- Custom rule support
4. Network Baseline Learning
- 7-day learning period
- Learns normal patterns (protocols, ports, IP behavior)
- Deviation detection for new IPs, unusual ports, volume anomalies
- Adaptive thresholds
Automated Response
Firewall Manager
- Windows Firewall / Linux iptables integration
- Auto-block after configurable alert threshold
- Manual block/unblock
- Blocklist management and export
Historical Analysis
- Threat database (up to 100,000 records)
- IP reputation tracking and risk scores
- Attack pattern recognition
- Threat search and timeline
- PDF report generation
Notifications
- Email alerts (SMTP)
- Webhooks (Slack, Discord, Teams)
- Desktop notifications
- Push notifications (mobile app)
Data Storage
DefenSys uses SQLite for alerts, traffic logs, historical threats, IP reputation, and attack patterns. Data retention and backup are configurable in Settings.
Detection Layers
DefenSys uses multiple detection layers that work together. Rule-based detection catches known patterns; ML catches behavioral anomalies; the combined engine merges results.
Rule-Based Detection
The combined detection engine runs several rule checks on each packet:
Port Scanning
Detects when a source IP probes multiple destination ports in a short time. Indicates reconnaissance.
// backend/services/combinedDetectionEngine.js - detectPortScanning()
const tracker = this.portScanTracker[srcKey];
tracker.ports.add(packet.dstPort);
tracker.lastSeen = now;
const timeWindow = now - tracker.firstSeen;
// Reset if older than 1 minute
if (timeWindow > 60000) { delete this.portScanTracker[srcKey]; return false; }
// Alert: 4+ different ports in 30 seconds
return tracker.ports.size >= 4 && timeWindow < 30000;SYN Flood
Tracks SYN packets from the same source. Abnormal rate suggests a SYN flood DoS attack.
// backend/services/combinedDetectionEngine.js - detectSYNFlood()
// Only TCP SYN without ACK (initial handshake)
if (packet.protocol !== "TCP" || !packet.flags?.includes("SYN") || packet.flags?.includes("ACK"))
return false;
const windowMs = 10000; // 10 seconds
const threshold = 30; // 30+ SYN packets from same source
// Reset if window expired
if (now - tracker.firstSeen > windowMs) {
tracker.count = 0;
tracker.firstSeen = now;
}
tracker.count++;
return tracker.count >= threshold;Suspicious Ports
Flags access to high-risk ports (135, 139, 1433, 5900) when the source is external (not local network).
// backend/services/combinedDetectionEngine.js - detectSuspiciousPorts()
const highRiskPorts = [135, 139, 1433, 5900];
const isLocal = srcIP.startsWith("10.") || srcIP.startsWith("192.168.") || ...;
return highRiskPorts.includes(packet.dstPort) &&
packet.protocol === "TCP" &&
packet.srcPort > 1024 &&
!isLocal;SQL Injection & XSS
Scans packet payload for known attack patterns (regex).
// SQL patterns: union select, drop table, or '1'='1', etc. const sqlPatterns = [/union.*select/i, /drop\s+table/i, /insert\s+into/i, ...]; return sqlPatterns.some((pattern) => pattern.test(payload)); // XSS patterns: <script, javascript:, onerror=, <iframe, etc. const xssPatterns = [/<script/i, /javascript:/i, /on\w+\s*=/i, ...];
Brute Force
Tracks rapid connections from same IP to same dst IP:port. Many attempts in a short window indicates brute force.
Data Exfiltration
Unusually large outbound flows or specific port patterns associated with data theft.
Connection Flood
Too many new connections from a single source in a short window.
Protocol Anomaly
Unexpected protocol usage, malformed packets, or protocol misuse.
Malicious Pattern
Signatures or patterns associated with known attacks.
ML Detection
See Machine Learning for how anomaly detection works. ML runs in parallel with rule-based detection.
Combined Result
The engine merges rule and ML results. An alert is raised if either triggers with sufficient severity/confidence, or if both agree (higher confidence). Thresholds are tuned to reduce false positives.
// backend/services/combinedDetectionEngine.js - combineResults()
// Rule-based contribution (weighted by severity)
if (ruleResult.alert) {
combinedScore += getSeverityWeight(ruleResult.severity) * ruleResult.confidence;
alertMethods.push("rule_based");
}
// ML contribution (weight 0.8)
if (mlResult.alert) {
combinedScore += 0.8 * mlResult.confidence;
alertMethods.push("ml");
}
// Final alert: high combined score OR critical rule OR high-confidence ML
const isAlert =
combinedScore > this.thresholds.combinedScore || // e.g. 0.95
(ruleResult.alert && ruleResult.severity === "critical") ||
(mlResult.alert && mlResult.confidence > 0.9);7-Layer Enhanced Detection
The broader system includes additional layers such as critical port access, threat intelligence, and behavioral baseline deviation. These feed into the overall threat score (0–200+).
Firewall Integration
DefenSys can block malicious IPs via the system firewall. Blocking is automatic (after a threshold) or manual.
Platform Support
- Windows – Windows Firewall (netsh advfirewall)
- Linux – iptables
Block Implementation (Code)
// backend/services/firewallManager.js - blockIP()
if (this.isWindows) {
const ruleName = `DefenSys_Block_${ip.replace(/\./g, "_")}`;
const command = `netsh advfirewall firewall add rule name="${ruleName}" dir=in action=block remoteip=${ip}`;
await execAsync(command);
} else {
// Linux iptables
const command = `sudo iptables -I INPUT -s ${ip} -j DROP`;
await execAsync(command);
}
this.blockedIPs.set(ip, { reason, timestamp, ruleId });
this.emit("ipBlocked", { ip, reason, timestamp });Auto-Block
When enabled, an IP is blocked after it generates a configurable number of critical alerts (e.g. 3). This helps stop repeat attackers automatically.
// backend/services/firewallManager.js this.autoBlockEnabled = false; // Toggle in Settings this.autoBlockThreshold = 3; // Block after 3 critical alerts this.ipAlertCounts = new Map(); // Track alerts per IP // When alert is raised: increment ipAlertCounts[srcIP] // If count >= threshold and autoBlockEnabled: call blockIP(ip, reason)
Manual Block/Unblock
You can block or unblock IPs from the Alerts feed, the blocked IP list, or via the API. Each block includes an optional reason for auditing.
Blocked IP List
View all blocked IPs, with timestamps and reasons. Unblock with one click. Lists can be exported or imported for sharing across deployments.
API
POST /api/firewall/block– Body: ip, reasonPOST /api/firewall/unblock– Body: ipGET /api/firewall/blocked– List blocked IPs
IPC
blockIP(ip, reason)unblockIP(ip)getBlockedIPs()setAutoBlock(enabled, threshold)
Network Baseline Learning
The network baseline learns "normal" traffic patterns over a learning period (e.g. 7 days). Deviations from the baseline can trigger alerts.
What It Learns
- Protocol distribution – Typical mix of TCP, UDP, ICMP, etc.
- Port usage – Common source and destination ports
- IP behavior – Which IPs communicate with which
- Hourly patterns – Traffic by time of day
- Port pairs – Typical src/dst port combinations
Deviation Detection
After the learning period, the baseline compares new traffic to the learned profile. Deviations include:
- New or unknown IPs
- Unusual ports
- Unusual protocols
- Traffic volume anomalies
Adaptive Thresholds
Statistical methods (e.g. standard deviation) define how much deviation is acceptable. Thresholds can be tuned to balance sensitivity and false positives.
Persistence
The baseline can be saved and loaded so learning does not need to restart after app restarts. Reset the baseline to relearn when the network changes significantly.
IPC Methods (for devs)
// Frontend/API can call: getBaselineSummary() // Returns learned profile summary resetBaseline() // Clears learned data, starts fresh