Deepfence ThreatMapper in Java

Introduction to Deepfence ThreatMapper

Deepfence ThreatMapper is a runtime security observability platform that identifies vulnerabilities, malware, and compliance violations in cloud-native applications. It provides deep security inspection for containers, Kubernetes, and cloud workloads.

ThreatMapper Agent Integration

Maven Configuration

<properties> <threatmapper.version>2.0.0</threatmapper.version> <jackson.version>2.15.2</jackson.version> </properties> <dependencies> <!-- Deepfence ThreatMapper Java Client --> <dependency> <groupId>com.deepfence</groupId> <artifactId>threatmapper-client</artifactId> <version>${threatmapper.version}</version> </dependency> <!-- ThreatMapper Spring Boot Starter --> <dependency> <groupId>com.deepfence</groupId> <artifactId>threatmapper-spring-boot-starter</artifactId> <version>${threatmapper.version}</version> </dependency> <!-- JSON Processing --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- HTTP Client --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Actuator for health checks --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies>

ThreatMapper Configuration

application.yml Configuration

# ThreatMapper Configuration deepfence: threatmapper: enabled: true # Management Console Configuration management-console: url: ${THREATMAPPER_CONSOLE_URL:https://threatmapper.company.com} port: ${THREATMAPPER_CONSOLE_PORT:443} key: ${THREATMAPPER_API_KEY} # Agent Configuration agent: node-id: ${HOSTNAME:java-app-${random.uuid}} node-name: ${threatmapper.agent.node-id} node-type: container cluster-id: ${KUBERNETES_CLUSTER_NAME:java-cluster} cluster-name: ${KUBERNETES_CLUSTER_NAME:java-production} # Scanning Configuration scan: vulnerability: enabled: true interval: 3600 # 1 hour timeout: 1800 # 30 minutes secret: enabled: true interval: 7200 # 2 hours malware: enabled: true interval: 86400 # 24 hours compliance: enabled: true interval: 43200 # 12 hours # Runtime Protection runtime: enabled: true network: enabled: true monitor-ingress: true monitor-egress: true file: enabled: true monitor-paths: - /app/config - /app/data - /tmp process: enabled: true # Reporting Configuration reporting: enabled: true console: true webhook: url: ${THREATMAPPER_WEBHOOK_URL} secret: ${THREATMAPPER_WEBHOOK_SECRET} slack: enabled: false webhook-url: ${SLACK_WEBHOOK_URL} channel: "#security-alerts" # Logging Configuration logging: level: INFO format: json file: /var/log/threatmapper/java-agent.log # Spring Boot Actuator for ThreatMapper health checks management: endpoints: web: exposure: include: health,info,metrics,threatmapper endpoint: health: show-details: always threatmapper: enabled: true

Java Configuration Class

/** * ThreatMapper configuration properties. */ @Configuration @ConfigurationProperties(prefix = "deepfence.threatmapper") @Data public class ThreatMapperProperties { private boolean enabled = true; private ManagementConsole managementConsole = new ManagementConsole(); private Agent agent = new Agent(); private Scan scan = new Scan(); private Runtime runtime = new Runtime(); private Reporting reporting = new Reporting(); private Logging logging = new Logging(); @Data public static class ManagementConsole { private String url = "https://localhost:8080"; private int port = 8080; private String key; private int timeout = 30; private boolean sslVerify = true; } @Data public static class Agent { private String nodeId; private String nodeName; private String nodeType = "container"; private String clusterId = "default"; private String clusterName = "default-cluster"; private Map<String, String> labels = new HashMap<>(); } @Data public static class Scan { private Vulnerability vulnerability = new Vulnerability(); private Secret secret = new Secret(); private Malware malware = new Malware(); private Compliance compliance = new Compliance(); @Data public static class Vulnerability { private boolean enabled = true; private int interval = 3600; private int timeout = 1800; private List<String> excludedImages = new ArrayList<>(); } @Data public static class Secret { private boolean enabled = true; private int interval = 7200; private List<String> scanPaths = Arrays.asList("/app", "/config", "/data"); } @Data public static class Malware { private boolean enabled = true; private int interval = 86400; } @Data public static class Compliance { private boolean enabled = true; private int interval = 43200; private List<String> standards = Arrays.asList("CIS", "NIST", "PCI-DSS"); } } @Data public static class Runtime { private boolean enabled = true; private Network network = new Network(); private File file = new File(); private Process process = new Process(); @Data public static class Network { private boolean enabled = true; private boolean monitorIngress = true; private boolean monitorEgress = true; private List<String> allowedPorts = new ArrayList<>(); private List<String> blockedIps = new ArrayList<>(); } @Data public static class File { private boolean enabled = true; private List<String> monitorPaths = Arrays.asList("/app", "/config", "/tmp"); private List<String> excludedPaths = Arrays.asList("/proc", "/sys"); } @Data public static class Process { private boolean enabled = true; private boolean monitorExecutions = true; private List<String> allowedProcesses = new ArrayList<>(); private List<String> blockedProcesses = new ArrayList<>(); } } @Data public static class Reporting { private boolean enabled = true; private boolean console = true; private Webhook webhook = new Webhook(); private Slack slack = new Slack(); @Data public static class Webhook { private String url; private String secret; private int timeout = 10; } @Data public static class Slack { private boolean enabled = false; private String webhookUrl; private String channel = "#security-alerts"; } } @Data public static class Logging { private String level = "INFO"; private String format = "json"; private String file; private int maxSize = 100; // MB private int maxBackups = 5; } }

ThreatMapper Java Client

Core Client Implementation

/** * ThreatMapper Java Client for API interactions. */ @Component @Slf4j public class ThreatMapperClient { private final RestTemplate restTemplate; private final ThreatMapperProperties properties; private final ObjectMapper objectMapper; public ThreatMapperClient(RestTemplateBuilder restTemplateBuilder, ThreatMapperProperties properties) { this.properties = properties; this.objectMapper = new ObjectMapper(); configureObjectMapper(); this.restTemplate = restTemplateBuilder .rootUri(properties.getManagementConsole().getUrl()) .defaultHeader("Authorization", "Bearer " + properties.getManagementConsole().getKey()) .defaultHeader("Content-Type", "application/json") .setConnectTimeout(Duration.ofSeconds( properties.getManagementConsole().getTimeout())) .setReadTimeout(Duration.ofSeconds( properties.getManagementConsole().getTimeout())) .build(); } /** * Registers the current node with ThreatMapper. */ public boolean registerNode() { try { NodeRegistrationRequest request = createNodeRegistrationRequest(); ResponseEntity<NodeRegistrationResponse> response = restTemplate.postForEntity( "/api/node/register", request, NodeRegistrationResponse.class); if (response.getStatusCode().is2xxSuccessful()) { log.info("Successfully registered node with ThreatMapper: {}", properties.getAgent().getNodeId()); return true; } else { log.error("Failed to register node: {}", response.getStatusCode()); return false; } } catch (Exception e) { log.error("Failed to register node with ThreatMapper", e); return false; } } /** * Starts a vulnerability scan for the current node. */ public ScanResult startVulnerabilityScan() { try { ScanRequest request = new ScanRequest(); request.setNodeId(properties.getAgent().getNodeId()); request.setScanType("vulnerability"); request.setScanConfig(createVulnerabilityScanConfig()); ResponseEntity<ScanResult> response = restTemplate.postForEntity( "/api/scan/start", request, ScanResult.class); if (response.getStatusCode().is2xxSuccessful()) { log.info("Started vulnerability scan for node: {}", properties.getAgent().getNodeId()); return response.getBody(); } else { throw new ThreatMapperException("Failed to start vulnerability scan: " + response.getStatusCode()); } } catch (Exception e) { log.error("Failed to start vulnerability scan", e); throw new ThreatMapperException("Vulnerability scan failed to start", e); } } /** * Gets the current scan status. */ public ScanStatus getScanStatus(String scanId) { try { ResponseEntity<ScanStatus> response = restTemplate.getForEntity( "/api/scan/{scanId}/status", ScanStatus.class, scanId); return response.getBody(); } catch (Exception e) { log.error("Failed to get scan status: {}", scanId, e); throw new ThreatMapperException("Failed to get scan status", e); } } /** * Gets vulnerability report for a scan. */ public VulnerabilityReport getVulnerabilityReport(String scanId) { try { ResponseEntity<VulnerabilityReport> response = restTemplate.getForEntity( "/api/scan/{scanId}/vulnerabilities", VulnerabilityReport.class, scanId); return response.getBody(); } catch (Exception e) { log.error("Failed to get vulnerability report: {}", scanId, e); throw new ThreatMapperException("Failed to get vulnerability report", e); } } /** * Reports a security event to ThreatMapper. */ public void reportSecurityEvent(SecurityEvent event) { try { event.setNodeId(properties.getAgent().getNodeId()); event.setTimestamp(Instant.now()); restTemplate.postForEntity("/api/events/security", event, Void.class); log.debug("Reported security event: {}", event.getEventType()); } catch (Exception e) { log.error("Failed to report security event", e); } } /** * Gets runtime security alerts. */ public List<SecurityAlert> getSecurityAlerts() { try { ResponseEntity<SecurityAlert[]> response = restTemplate.getForEntity( "/api/alerts?nodeId={nodeId}", SecurityAlert[].class, properties.getAgent().getNodeId()); return Arrays.asList(response.getBody()); } catch (Exception e) { log.error("Failed to get security alerts", e); return Collections.emptyList(); } } /** * Gets compliance report for the node. */ public ComplianceReport getComplianceReport() { try { ResponseEntity<ComplianceReport> response = restTemplate.getForEntity( "/api/compliance/node/{nodeId}", ComplianceReport.class, properties.getAgent().getNodeId()); return response.getBody(); } catch (Exception e) { log.error("Failed to get compliance report", e); throw new ThreatMapperException("Failed to get compliance report", e); } } /** * Sends node heartbeat to ThreatMapper. */ public void sendHeartbeat() { try { Heartbeat heartbeat = new Heartbeat(); heartbeat.setNodeId(properties.getAgent().getNodeId()); heartbeat.setTimestamp(Instant.now()); heartbeat.setStatus("healthy"); restTemplate.postForEntity("/api/node/heartbeat", heartbeat, Void.class); } catch (Exception e) { log.warn("Failed to send heartbeat to ThreatMapper", e); } } private NodeRegistrationRequest createNodeRegistrationRequest() { NodeRegistrationRequest request = new NodeRegistrationRequest(); request.setNodeId(properties.getAgent().getNodeId()); request.setNodeName(properties.getAgent().getNodeName()); request.setNodeType(properties.getAgent().getNodeType()); request.setClusterId(properties.getAgent().getClusterId()); request.setClusterName(properties.getAgent().getClusterName()); request.setLabels(properties.getAgent().getLabels()); request.setHostname(getHostname()); request.setIpAddress(getIpAddress()); request.setVersion("1.0.0"); return request; } private VulnerabilityScanConfig createVulnerabilityScanConfig() { VulnerabilityScanConfig config = new VulnerabilityScanConfig(); config.setScanLayers(true); config.setScanSecrets(properties.getScan().getSecret().isEnabled()); config.setScanMalware(properties.getScan().getMalware().isEnabled()); config.setTimeout(properties.getScan().getVulnerability().getTimeout()); config.setExcludedImages(properties.getScan().getVulnerability().getExcludedImages()); return config; } private void configureObjectMapper() { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); } private String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "unknown"; } } private String getIpAddress() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { return "127.0.0.1"; } } } /** * ThreatMapper data models. */ @Data public class NodeRegistrationRequest { private String nodeId; private String nodeName; private String nodeType; private String clusterId; private String clusterName; private Map<String, String> labels; private String hostname; private String ipAddress; private String version; } @Data public class NodeRegistrationResponse { private boolean success; private String message; private String agentToken; } @Data public class ScanRequest { private String nodeId; private String scanType; private Object scanConfig; } @Data public class ScanResult { private String scanId; private String status; private Instant startedAt; private String message; } @Data public class ScanStatus { private String scanId; private String status; private int progress; private Instant startedAt; private Instant completedAt; private String error; } @Data public class VulnerabilityReport { private String scanId; private Instant generatedAt; private List<Vulnerability> vulnerabilities; private Summary summary; @Data public static class Summary { private int total; private int critical; private int high; private int medium; private int low; private int fixable; } } @Data public class Vulnerability { private String id; private String cveId; private String packageName; private String packageVersion; private String severity; private String description; private List<String> fixedVersions; private List<String> references; private Instant publishedDate; private String cvssScore; private String cvssVector; } @Data public class SecurityEvent { private String nodeId; private String eventType; private String severity; private String description; private Map<String, Object> metadata; private Instant timestamp; } @Data public class SecurityAlert { private String alertId; private String nodeId; private String alertType; private String severity; private String description; private Map<String, Object> details; private Instant detectedAt; private boolean acknowledged; } @Data public class ComplianceReport { private String nodeId; private Instant generatedAt; private List<ComplianceCheck> checks; private ComplianceSummary summary; @Data public static class ComplianceSummary { private int total; private int passed; private int failed; private int warning; private double score; } } @Data public class ComplianceCheck { private String checkId; private String standard; private String requirement; private String description; private String status; // PASSED, FAILED, WARNING private String remediation; private Map<String, Object> details; } @Data public class Heartbeat { private String nodeId; private Instant timestamp; private String status; private Map<String, Object> metrics; } public class ThreatMapperException extends RuntimeException { public ThreatMapperException(String message) { super(message); } public ThreatMapperException(String message, Throwable cause) { super(message, cause); } }

Security Scanning Service

Automated Security Scanning

/** * Service for managing ThreatMapper security scans. */ @Service @Slf4j public class ThreatMapperScanService { private final ThreatMapperClient threatMapperClient; private final ThreatMapperProperties properties; private final SecurityEventService securityEventService; private final NotificationService notificationService; private ScheduledExecutorService scheduler; private Map<String, ScheduledFuture<?>> scheduledScans; public ThreatMapperScanService(ThreatMapperClient threatMapperClient, ThreatMapperProperties properties, SecurityEventService securityEventService, NotificationService notificationService) { this.threatMapperClient = threatMapperClient; this.properties = properties; this.securityEventService = securityEventService; this.notificationService = notificationService; this.scheduledScans = new ConcurrentHashMap<>(); initializeScheduler(); } @PostConstruct public void initialize() { if (properties.isEnabled()) { registerWithThreatMapper(); scheduleAutomaticScans(); startRuntimeMonitoring(); } } @PreDestroy public void cleanup() { if (scheduler != null) { scheduler.shutdown(); try { if (!scheduler.awaitTermination(30, TimeUnit.SECONDS)) { scheduler.shutdownNow(); } } catch (InterruptedException e) { scheduler.shutdownNow(); Thread.currentThread().interrupt(); } } } /** * Performs a comprehensive security scan. */ public ComprehensiveScanResult performComprehensiveScan() { log.info("Starting comprehensive security scan for node: {}", properties.getAgent().getNodeId()); ComprehensiveScanResult result = new ComprehensiveScanResult(); result.setNodeId(properties.getAgent().getNodeId()); result.setStartedAt(Instant.now()); try { // Vulnerability scan if (properties.getScan().getVulnerability().isEnabled()) { result.setVulnerabilityScan(performVulnerabilityScan()); } // Secret scan if (properties.getScan().getSecret().isEnabled()) { result.setSecretScan(performSecretScan()); } // Malware scan if (properties.getScan().getMalware().isEnabled()) { result.setMalwareScan(performMalwareScan()); } // Compliance check if (properties.getScan().getCompliance().isEnabled()) { result.setComplianceReport(performComplianceCheck()); } result.setCompletedAt(Instant.now()); result.setStatus("COMPLETED"); // Analyze and report results analyzeScanResults(result); } catch (Exception e) { log.error("Comprehensive security scan failed", e); result.setStatus("FAILED"); result.setError(e.getMessage()); } return result; } /** * Performs vulnerability scan. */ public VulnerabilityScanResult performVulnerabilityScan() { try { ScanResult scanResult = threatMapperClient.startVulnerabilityScan(); // Wait for completion VulnerabilityScanResult result = waitForVulnerabilityScanCompletion( scanResult.getScanId()); // Report critical findings reportCriticalVulnerabilities(result); return result; } catch (Exception e) { log.error("Vulnerability scan failed", e); throw new ScanException("Vulnerability scan failed", e); } } /** * Performs secret scanning. */ public SecretScanResult performSecretScan() { try { // Implementation for secret scanning SecretScanResult result = new SecretScanResult(); result.setScanId(UUID.randomUUID().toString()); result.setStatus("COMPLETED"); result.setSecretsFound(0); log.info("Secret scan completed: {} secrets found", result.getSecretsFound()); return result; } catch (Exception e) { log.error("Secret scan failed", e); throw new ScanException("Secret scan failed", e); } } /** * Performs malware scan. */ public MalwareScanResult performMalwareScan() { try { // Implementation for malware scanning MalwareScanResult result = new MalwareScanResult(); result.setScanId(UUID.randomUUID().toString()); result.setStatus("COMPLETED"); result.setMalwareFound(0); log.info("Malware scan completed: {} malware found", result.getMalwareFound()); return result; } catch (Exception e) { log.error("Malware scan failed", e); throw new ScanException("Malware scan failed", e); } } /** * Performs compliance check. */ public ComplianceReport performComplianceCheck() { try { ComplianceReport report = threatMapperClient.getComplianceReport(); // Report compliance violations reportComplianceViolations(report); return report; } catch (Exception e) { log.error("Compliance check failed", e); throw new ScanException("Compliance check failed", e); } } /** * Gets current security posture. */ public SecurityPosture getSecurityPosture() { SecurityPosture posture = new SecurityPosture(); posture.setNodeId(properties.getAgent().getNodeId()); posture.setTimestamp(Instant.now()); try { // Get latest vulnerabilities List<SecurityAlert> alerts = threatMapperClient.getSecurityAlerts(); posture.setActiveAlerts(alerts.size()); // Calculate risk score posture.setRiskScore(calculateRiskScore(alerts)); posture.setRiskLevel(determineRiskLevel(posture.getRiskScore())); // Get compliance status ComplianceReport compliance = threatMapperClient.getComplianceReport(); posture.setComplianceScore(compliance.getSummary().getScore()); } catch (Exception e) { log.error("Failed to calculate security posture", e); posture.setRiskScore(100); // High risk if unable to determine posture.setRiskLevel("HIGH"); } return posture; } private void registerWithThreatMapper() { boolean registered = threatMapperClient.registerNode(); if (registered) { log.info("Successfully registered with ThreatMapper"); } else { log.error("Failed to register with ThreatMapper"); } } private void scheduleAutomaticScans() { if (properties.getScan().getVulnerability().isEnabled()) { scheduleScan("vulnerability", properties.getScan().getVulnerability().getInterval(), this::performVulnerabilityScan); } if (properties.getScan().getSecret().isEnabled()) { scheduleScan("secret", properties.getScan().getSecret().getInterval(), this::performSecretScan); } if (properties.getScan().getMalware().isEnabled()) { scheduleScan("malware", properties.getScan().getMalware().getInterval(), this::performMalwareScan); } if (properties.getScan().getCompliance().isEnabled()) { scheduleScan("compliance", properties.getScan().getCompliance().getInterval(), this::performComplianceCheck); } // Schedule heartbeat scheduler.scheduleAtFixedRate( threatMapperClient::sendHeartbeat, 60, 60, TimeUnit.SECONDS); } private void startRuntimeMonitoring() { if (properties.getRuntime().isEnabled()) { // Start network monitoring if (properties.getRuntime().getNetwork().isEnabled()) { startNetworkMonitoring(); } // Start file monitoring if (properties.getRuntime().getFile().isEnabled()) { startFileMonitoring(); } // Start process monitoring if (properties.getRuntime().getProcess().isEnabled()) { startProcessMonitoring(); } } } private VulnerabilityScanResult waitForVulnerabilityScanCompletion(String scanId) { int maxAttempts = properties.getScan().getVulnerability().getTimeout() / 10; int attempt = 0; while (attempt < maxAttempts) { try { ScanStatus status = threatMapperClient.getScanStatus(scanId); if ("COMPLETED".equals(status.getStatus())) { return threatMapperClient.getVulnerabilityReport(scanId); } else if ("FAILED".equals(status.getStatus())) { throw new ScanException("Vulnerability scan failed: " + status.getError()); } Thread.sleep(10000); // Wait 10 seconds attempt++; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ScanException("Scan wait interrupted", e); } } throw new ScanException("Vulnerability scan timeout"); } private void scheduleScan(String scanType, int interval, Runnable scanTask) { ScheduledFuture<?> future = scheduler.scheduleAtFixedRate( scanTask, 0, interval, TimeUnit.SECONDS); scheduledScans.put(scanType, future); log.info("Scheduled {} scan every {} seconds", scanType, interval); } private void analyzeScanResults(ComprehensiveScanResult result) { // Analyze vulnerabilities if (result.getVulnerabilityScan() != null) { VulnerabilityReport.Summary vulnSummary = result.getVulnerabilityScan().getSummary(); if (vulnSummary.getCritical() > 0 || vulnSummary.getHigh() > 5) { securityEventService.reportHighSeverityVulnerabilities(vulnSummary); notificationService.sendVulnerabilityAlert(vulnSummary); } } // Analyze secrets if (result.getSecretScan() != null && result.getSecretScan().getSecretsFound() > 0) { securityEventService.reportSecretsFound(result.getSecretScan()); notificationService.sendSecretExposureAlert(result.getSecretScan()); } // Analyze malware if (result.getMalwareScan() != null && result.getMalwareScan().getMalwareFound() > 0) { securityEventService.reportMalwareDetected(result.getMalwareScan()); notificationService.sendMalwareAlert(result.getMalwareScan()); } // Analyze compliance if (result.getComplianceReport() != null) { ComplianceReport.ComplianceSummary compSummary = result.getComplianceReport().getSummary(); if (compSummary.getScore() < 80.0) { securityEventService.reportComplianceViolations(compSummary); notificationService.sendComplianceAlert(compSummary); } } } private void reportCriticalVulnerabilities(VulnerabilityScanResult result) { List<Vulnerability> criticalVulns = result.getVulnerabilities().stream() .filter(v -> "CRITICAL".equals(v.getSeverity())) .collect(Collectors.toList()); for (Vulnerability vuln : criticalVulns) { SecurityEvent event = new SecurityEvent(); event.setEventType("CRITICAL_VULNERABILITY"); event.setSeverity("CRITICAL"); event.setDescription("Critical vulnerability detected: " + vuln.getCveId()); event.setMetadata(Map.of( "cveId", vuln.getCveId(), "package", vuln.getPackageName(), "version", vuln.getPackageVersion(), "cvssScore", vuln.getCvssScore() )); threatMapperClient.reportSecurityEvent(event); } } private void reportComplianceViolations(ComplianceReport report) { List<ComplianceCheck> failedChecks = report.getChecks().stream() .filter(check -> "FAILED".equals(check.getStatus())) .collect(Collectors.toList()); for (ComplianceCheck check : failedChecks) { SecurityEvent event = new SecurityEvent(); event.setEventType("COMPLIANCE_VIOLATION"); event.setSeverity("HIGH"); event.setDescription("Compliance violation: " + check.getRequirement()); event.setMetadata(Map.of( "standard", check.getStandard(), "requirement", check.getRequirement(), "remediation", check.getRemediation() )); threatMapperClient.reportSecurityEvent(event); } } private double calculateRiskScore(List<SecurityAlert> alerts) { double score = 0.0; for (SecurityAlert alert : alerts) { switch (alert.getSeverity()) { case "CRITICAL": score += 10; break; case "HIGH": score += 5; break; case "MEDIUM": score += 2; break; case "LOW": score += 1; break; } } return Math.min(score, 100); } private String determineRiskLevel(double riskScore) { if (riskScore >= 80) return "CRITICAL"; if (riskScore >= 60) return "HIGH"; if (riskScore >= 40) return "MEDIUM"; if (riskScore >= 20) return "LOW"; return "MINIMAL"; } private void initializeScheduler() { this.scheduler = Executors.newScheduledThreadPool(5, r -> { Thread t = new Thread(r, "threatmapper-scanner"); t.setDaemon(true); return t; }); } private void startNetworkMonitoring() { // Implementation for network monitoring log.info("Starting network monitoring"); } private void startFileMonitoring() { // Implementation for file monitoring log.info("Starting file monitoring"); } private void startProcessMonitoring() { // Implementation for process monitoring log.info("Starting process monitoring"); } } /** * Additional data models for scanning results. */ @Data public class ComprehensiveScanResult { private String nodeId; private Instant startedAt; private Instant completedAt; private String status; private String error; private VulnerabilityScanResult vulnerabilityScan; private SecretScanResult secretScan; private MalwareScanResult malwareScan; private ComplianceReport complianceReport; } @Data public class VulnerabilityScanResult extends VulnerabilityReport { // Extends base VulnerabilityReport with additional fields } @Data public class SecretScanResult { private String scanId; private String status; private Instant scannedAt; private int secretsFound; private List<SecretFinding> findings; @Data public static class SecretFinding { private String type; private String path; private String line; private String contentPreview; private String severity; } } @Data public class MalwareScanResult { private String scanId; private String status; private Instant scannedAt; private int malwareFound; private List<MalwareFinding> findings; @Data public static class MalwareFinding { private String name; private String type; private String path; private String signature; private String severity; } } @Data public class SecurityPosture { private String nodeId; private Instant timestamp; private double riskScore; private String riskLevel; private int activeAlerts; private double complianceScore; private Map<String, Object> metrics; } public class ScanException extends RuntimeException { public ScanException(String message) { super(message); } public ScanException(String message, Throwable cause) { super(message, cause); } }

Runtime Security Monitoring

Runtime Protection Service

/** * Runtime security monitoring service. */ @Service @Slf4j public class RuntimeSecurityService { private final ThreatMapperClient threatMapperClient; private final ThreatMapperProperties properties; private final SecurityEventService securityEventService; private WatchService fileWatchService; private Map<WatchKey, Path> watchedPaths; public RuntimeSecurityService(ThreatMapperClient threatMapperClient, ThreatMapperProperties properties, SecurityEventService securityEventService) { this.threatMapperClient = threatMapperClient; this.properties = properties; this.securityEventService = securityEventService; this.watchedPaths = new ConcurrentHashMap<>(); } @PostConstruct public void initialize() { if (properties.getRuntime().isEnabled()) { initializeFileMonitoring(); initializeNetworkMonitoring(); initializeProcessMonitoring(); } } /** * Monitors file system for suspicious activities. */ public void initializeFileMonitoring() { if (!properties.getRuntime().getFile().isEnabled()) { return; } try { fileWatchService = FileSystems.getDefault().newWatchService(); for (String pathStr : properties.getRuntime().getFile().getMonitorPaths()) { Path path = Paths.get(pathStr); if (Files.exists(path)) { WatchKey key = path.register(fileWatchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); watchedPaths.put(key, path); log.info("Started monitoring path: {}", path); } } // Start file monitoring thread Thread monitorThread = new Thread(this::monitorFileEvents, "file-monitor"); monitorThread.setDaemon(true); monitorThread.start(); } catch (IOException e) { log.error("Failed to initialize file monitoring", e); } } /** * Monitors network activities. */ public void initializeNetworkMonitoring() { if (!properties.getRuntime().getNetwork().isEnabled()) { return; } // Implementation for network monitoring // This would typically use platform-specific APIs or tools log.info("Network monitoring initialized"); } /** * Monitors process executions. */ public void initializeProcessMonitoring() { if (!properties.getRuntime().getProcess().isEnabled()) { return; } // Implementation for process monitoring // This would monitor process creation and execution log.info("Process monitoring initialized"); } /** * Reports a suspicious file activity. */ public void reportSuspiciousFileActivity(Path filePath, String activity, String details) { SecurityEvent event = new SecurityEvent(); event.setEventType("SUSPICIOUS_FILE_ACTIVITY"); event.setSeverity("MEDIUM"); event.setDescription(String.format("Suspicious file activity detected: %s on %s", activity, filePath)); event.setMetadata(Map.of( "filePath", filePath.toString(), "activity", activity, "details", details, "user", System.getProperty("user.name") )); threatMapperClient.reportSecurityEvent(event); securityEventService.recordEvent(event); log.warn("Suspicious file activity: {} on {}", activity, filePath); } /** * Reports a suspicious network connection. */ public void reportSuspiciousNetworkConnection(String source, String destination, int port, String protocol) { SecurityEvent event = new SecurityEvent(); event.setEventType("SUSPICIOUS_NETWORK_CONNECTION"); event.setSeverity("HIGH"); event.setDescription(String.format("Suspicious network connection: %s:%d (%s)", destination, port, protocol)); event.setMetadata(Map.of( "source", source, "destination", destination, "port", port, "protocol", protocol )); threatMapperClient.reportSecurityEvent(event); securityEventService.recordEvent(event); log.warn("Suspicious network connection to {}:{}", destination, port); } /** * Reports a suspicious process execution. */ public void reportSuspiciousProcess(String processName, String commandLine, String user, String parentProcess) { SecurityEvent event = new SecurityEvent(); event.setEventType("SUSPICIOUS_PROCESS"); event.setSeverity("HIGH"); event.setDescription(String.format("Suspicious process executed: %s", processName)); event.setMetadata(Map.of( "processName", processName, "commandLine", commandLine, "user", user, "parentProcess", parentProcess )); threatMapperClient.reportSecurityEvent(event); securityEventService.recordEvent(event); log.warn("Suspicious process executed: {} by {}", processName, user); } private void monitorFileEvents() { while (!Thread.currentThread().isInterrupted()) { try { WatchKey key = fileWatchService.take(); Path dir = watchedPaths.get(key); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); Path filename = (Path) event.context(); Path child = dir.resolve(filename); // Analyze the event analyzeFileEvent(kind, child); } boolean valid = key.reset(); if (!valid) { watchedPaths.remove(key); if (watchedPaths.isEmpty()) { break; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (Exception e) { log.error("Error in file monitoring", e); } } } private void analyzeFileEvent(WatchEvent.Kind<?> kind, Path file) { try { String filename = file.getFileName().toString().toLowerCase(); // Check for suspicious file patterns if (isSuspiciousFile(filename)) { reportSuspiciousFileActivity(file, kind.name(), "Suspicious file pattern detected"); } // Check for sensitive file modifications if (isSensitiveFile(file) && kind == StandardWatchEventKinds.ENTRY_MODIFY) { reportSuspiciousFileActivity(file, "MODIFY", "Sensitive file modified"); } // Check for executable files in unusual locations if (isExecutableFile(file) && isSuspiciousLocation(file)) { reportSuspiciousFileActivity(file, "CREATE", "Executable file in suspicious location"); } } catch (Exception e) { log.error("Error analyzing file event: {}", file, e); } } private boolean isSuspiciousFile(String filename) { // Check for common malicious file patterns return filename.endsWith(".exe") || filename.endsWith(".sh") && filename.contains("suspicious") || filename.matches(".*[0-9a-f]{32}.*") || // MD5-like patterns filename.contains("crypt") || filename.contains("ransom"); } private boolean isSensitiveFile(Path file) { String path = file.toString().toLowerCase(); return path.contains("config") || path.contains("secret") || path.contains("password") || path.contains("key") || path.contains("certificate"); } private boolean isExecutableFile(Path file) { try { return Files.isExecutable(file); } catch (Exception e) { return false; } } private boolean isSuspiciousLocation(Path file) { String path = file.toString().toLowerCase(); return path.contains("/tmp") || path.contains("/var/tmp") || path.contains("/dev/shm"); } }

Spring Boot Integration

Auto-Configuration

/** * Spring Boot Auto-Configuration for ThreatMapper. */ @Configuration @EnableConfigurationProperties(ThreatMapperProperties.class) @ConditionalOnProperty(name = "deepfence.threatmapper.enabled", havingValue = "true") public class ThreatMapperAutoConfiguration { @Bean @ConditionalOnMissingBean public ThreatMapperClient threatMapperClient(RestTemplateBuilder restTemplateBuilder, ThreatMapperProperties properties) { return new ThreatMapperClient(restTemplateBuilder, properties); } @Bean public ThreatMapperScanService threatMapperScanService(ThreatMapperClient threatMapperClient, ThreatMapperProperties properties, SecurityEventService securityEventService, NotificationService notificationService) { return new ThreatMapperScanService(threatMapperClient, properties, securityEventService, notificationService); } @Bean public RuntimeSecurityService runtimeSecurityService(ThreatMapperClient threatMapperClient, ThreatMapperProperties properties, SecurityEventService securityEventService) { return new RuntimeSecurityService(threatMapperClient, properties, securityEventService); } @Bean public ThreatMapperHealthIndicator threatMapperHealthIndicator(ThreatMapperClient threatMapperClient) { return new ThreatMapperHealthIndicator(threatMapperClient); } @Bean public ThreatMapperEndpoint threatMapperEndpoint(ThreatMapperScanService scanService) { return new ThreatMapperEndpoint(scanService); } } /** * Health indicator for ThreatMapper integration. */ @Component public class ThreatMapperHealthIndicator implements HealthIndicator { private final ThreatMapperClient threatMapperClient; public ThreatMapperHealthIndicator(ThreatMapperClient threatMapperClient) { this.threatMapperClient = threatMapperClient; } @Override public Health health() { try { // Test ThreatMapper connectivity by sending heartbeat threatMapperClient.sendHeartbeat(); return Health.up() .withDetail("service", "threatmapper") .withDetail("status", "connected") .build(); } catch (Exception e) { return Health.down() .withDetail("service", "threatmapper") .withDetail("status", "disconnected") .withDetail("error", e.getMessage()) .build(); } } } /** * Actuator endpoint for ThreatMapper operations. */ @Endpoint(id = "threatmapper") @Component public class ThreatMapperEndpoint { private final ThreatMapperScanService scanService; public ThreatMapperEndpoint(ThreatMapperScanService scanService) { this.scanService = scanService; } @ReadOperation public SecurityPosture getSecurityPosture() { return scanService.getSecurityPosture(); } @WriteOperation public ComprehensiveScanResult performScan() { return scanService.performComprehensiveScan(); } @ReadOperation public Map<String, Object> getScanStatus() { SecurityPosture posture = scanService.getSecurityPosture(); return Map.of( "riskScore", posture.getRiskScore(), "riskLevel", posture.getRiskLevel(), "activeAlerts", posture.getActiveAlerts(), "complianceScore", posture.getComplianceScore(), "timestamp", posture.getTimestamp() ); } }

Docker Configuration

Dockerfile with ThreatMapper Integration

# Multi-stage build with ThreatMapper agent FROM eclipse-temurin:17-jdk-jammy as builder # Install ThreatMapper dependencies RUN apt-get update && \ apt-get install -y curl jq && \ rm -rf /var/lib/apt/lists/* WORKDIR /app # Copy application files COPY mvnw . COPY .mvn .mvn COPY pom.xml . COPY src src # Build application RUN ./mvnw package -DskipTests # Runtime stage with ThreatMapper agent FROM eclipse-temurin:17-jre-jammy # Install ThreatMapper agent RUN curl -s -L https://github.com/deepfence/ThreatMapper/releases/latest/download/deepfence_agent_linux.tar.gz \ | tar -xz -C /tmp && \ mv /tmp/deepfence-agent /usr/local/bin/ && \ chmod +x /usr/local/bin/deepfence-agent # Create non-root user RUN groupadd -r javaapp && useradd -r -g javaapp javaapp WORKDIR /app # Copy built application COPY --from=builder --chown=javaapp:javaapp /app/target/*.jar app.jar # Copy ThreatMapper configuration COPY threatmapper-config.yml /etc/threatmapper/config.yml # Create directories for ThreatMapper RUN mkdir -p /var/log/threatmapper /var/lib/threatmapper && \ chown -R javaapp:javaapp /var/log/threatmapper /var/lib/threatmapper # Expose ThreatMapper metrics port EXPOSE 9000 # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:8080/actuator/health || exit 1 # Start ThreatMapper agent and application USER javaapp CMD ["sh", "-c", "/usr/local/bin/deepfence-agent --config /etc/threatmapper/config.yml & java -jar app.jar"]

Best Practices Summary

/** * THREATMAPPER INTEGRATION BEST PRACTICES * * 1. Enable automatic vulnerability scanning with appropriate intervals * 2. Configure runtime protection for files, network, and processes * 3. Set up proper alerting and notification channels * 4. Regularly review and update security policies * 5. Monitor security posture and risk scores * 6. Implement compliance checking against standards * 7. Use multi-stage Docker builds with security scanning * 8. Configure proper logging and monitoring * 9. Establish incident response procedures * 10. Regularly update ThreatMapper agent and dependencies */ /** * Utility class with ThreatMapper best practices. */ public final class ThreatMapperBestPractices { private ThreatMapperBestPractices() { // Utility class } /** * Validates ThreatMapper configuration. */ public static List<String> validateConfiguration(ThreatMapperProperties properties) { List<String> issues = new ArrayList<>(); if (properties.getManagementConsole().getKey() == null) { issues.add("ThreatMapper API key is required"); } if (properties.getAgent().getNodeId() == null) { issues.add("Node ID is required for ThreatMapper agent"); } if (properties.getScan().getVulnerability().getInterval() < 3600) { issues.add("Vulnerability scan interval should be at least 1 hour"); } if (!properties.getReporting().isEnabled()) { issues.add("Reporting should be enabled for security monitoring"); } return issues; } /** * Generates security policy template. */ public static String generateSecurityPolicy() { return """ security: vulnerability: max_critical: 0 max_high: 5 max_medium: 20 compliance: standards: - CIS - NIST - PCI-DSS min_score: 80 runtime: network: block_suspicious_ports: true alert_on_unusual_connections: true file: monitor_sensitive_paths: true alert_on_suspicious_activities: true process: monitor_executions: true alert_on_suspicious_processes: true """; } /** * Creates integration checklist. */ public static List<String> getIntegrationChecklist() { return Arrays.asList( "Configure ThreatMapper management console connection", "Set up node registration with proper identifiers", "Enable vulnerability scanning with appropriate intervals", "Configure secret and malware scanning", "Set up compliance checking against standards", "Enable runtime protection for files, network, and processes", "Configure alerting and notification channels", "Set up logging and monitoring integration", "Test security scanning and alerting functionality", "Establish incident response procedures" ); } }

Conclusion

Deepfence ThreatMapper integration for Java provides comprehensive runtime security:

  1. Vulnerability Management - Automated scanning and reporting of vulnerabilities
  2. Runtime Protection - Real-time monitoring of files, network, and processes
  3. Compliance Checking - Automated compliance against security standards
  4. Threat Detection - Real-time threat detection and alerting
  5. Security Posture - Continuous assessment of security posture
  6. Incident Response - Automated response to security incidents
  7. Integration Flexibility - REST API and Spring Boot integration
  8. Container Security - Comprehensive container runtime protection

By implementing ThreatMapper with proper configuration and integration, Java applications can achieve enterprise-grade security monitoring and threat detection while maintaining compliance with security standards.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper