Deepfence ThreatMapper is a powerful runtime security observability platform that scans running containers, VMs, and serverless workloads for vulnerabilities and identifies attack paths.
Setup and Dependencies
1. Maven Dependencies
<!-- pom.xml -->
<properties>
<deepfence.version>2.0.0</deepfence.version>
<spring-boot.version>3.1.0</spring-boot.version>
<okhttp.version>4.11.0</okhttp.version>
</properties>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- Deepfence Java Client -->
<dependency>
<groupId>com.deepfence</groupId>
<artifactId>threatmapper-client</artifactId>
<version>${deepfence.version}</version>
</dependency>
<!-- HTTP Client -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<!-- JSON Processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
</dependencies>
2. Dockerfile with Security Configuration
# Multi-stage build for security
FROM eclipse-temurin:17-jdk as builder
# Install Deepfence agent
RUN curl -s https://packages.deepfence.io/deepfence-agent/install.sh | bash
WORKDIR /app
COPY . .
RUN ./mvnw clean package -DskipTests
FROM eclipse-temurin:17-jre
# Install Deepfence agent in runtime
RUN curl -s https://packages.deepfence.io/deepfence-agent/install.sh | bash
# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
# Security hardening
RUN chown -R appuser:appuser /app && \
chmod -R 750 /app && \
chmod -R 400 /app/app.jar
USER appuser
# Deepfence environment variables
ENV DEEPFENCE_KEY=${DEEPFENCE_KEY}
ENV DEEPFENCE_MGMT_CONSOLE_URL=https://deepfence.example.com
ENV DEEPFENCE_MGMT_CONSOLE_PORT=443
# Health check including security status
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD curl -f http://localhost:8080/actuator/health || exit 1
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
3. Environment Setup Script
#!/bin/bash # setup-deepfence.sh export DEEPFENCE_MGMT_CONSOLE_URL=https://deepfence.example.com export DEEPFENCE_MGMT_CONSOLE_PORT=443 export DEEPFENCE_KEY=your-deepfence-api-key export DEEPFENCE_AGENT_VERSION=2.0.0 # Install Deepfence Agent curl -s https://packages.deepfence.io/deepfence-agent/install.sh | sudo bash # Configure agent sudo deepfence_agent config set management_console_url $DEEPFENCE_MGMT_CONSOLE_URL sudo deepfence_agent config set management_console_port $DEEPFENCE_MGMT_CONSOLE_PORT sudo deepfence_agent config set deepfence_key $DEEPFENCE_KEY # Start agent sudo systemctl enable deepfence-agent sudo systemctl start deepfence-agent echo "Deepfence ThreatMapper configured and started"
Deepfence API Integration
1. Deepfence Client Service
package com.example.security.deepfence;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Service
public class DeepfenceClientService {
private static final Logger logger = LoggerFactory.getLogger(DeepfenceClientService.class);
private final String DEEPFENCE_BASE_URL;
private final String DEEPFENCE_API_KEY;
private final OkHttpClient httpClient;
private final ObjectMapper objectMapper;
public DeepfenceClientService(
@Value("${deepfence.url}") String deepfenceUrl,
@Value("${deepfence.api-key}") String apiKey) {
this.DEEPFENCE_BASE_URL = deepfenceUrl;
this.DEEPFENCE_API_KEY = apiKey;
this.objectMapper = new ObjectMapper();
this.httpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
}
public List<CloudNode> getCloudNodes() throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/cloud-nodes";
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
CloudNodeResponse nodeResponse = objectMapper.readValue(responseBody, CloudNodeResponse.class);
return nodeResponse.getData().getCloudNodes();
}
}
public List<ContainerImage> getContainerImages() throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/images";
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
ContainerImageResponse imageResponse = objectMapper.readValue(responseBody, ContainerImageResponse.class);
return imageResponse.getData().getImages();
}
}
public VulnerabilityScanReport scanImage(String imageName, String tag) throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/scan/image";
Map<String, String> scanRequest = Map.of(
"image_name", imageName,
"tag", tag
);
RequestBody body = RequestBody.create(
objectMapper.writeValueAsString(scanRequest),
MediaType.parse("application/json")
);
Request request = createRequest(url)
.post(body)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Scan request failed: " + response);
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, VulnerabilityScanReport.class);
}
}
public List<Vulnerability> getVulnerabilities(String scanId) throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/vulnerabilities?scan_id=" + scanId;
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
VulnerabilityResponse vulnResponse = objectMapper.readValue(responseBody, VulnerabilityResponse.class);
return vulnResponse.getData().getVulnerabilities();
}
}
public List<Compliance> getComplianceResults(String nodeId) throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/compliance?node_id=" + nodeId;
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
ComplianceResponse complianceResponse = objectMapper.readValue(responseBody, ComplianceResponse.class);
return complianceResponse.getData().getCompliances();
}
}
public List<Threat> getThreatIntelligence() throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/threat-intel";
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
ThreatIntelligenceResponse threatResponse = objectMapper.readValue(responseBody, ThreatIntelligenceResponse.class);
return threatResponse.getData().getThreats();
}
}
public TopologyData getTopology() throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/topology";
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, TopologyData.class);
}
}
public AttackPathAnalysis analyzeAttackPaths(String nodeId) throws IOException {
String url = DEEPFENCE_BASE_URL + "/deepfence/attack-paths?node_id=" + nodeId;
Request request = createRequest(url);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, AttackPathAnalysis.class);
}
}
private Request.Builder createRequest(String url) {
return new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + DEEPFENCE_API_KEY)
.addHeader("Content-Type", "application/json");
}
// DTO classes for Deepfence API
public static class CloudNodeResponse {
private ResponseData data;
public ResponseData getData() { return data; }
public void setData(ResponseData data) { this.data = data; }
}
public static class ContainerImageResponse {
private ImageResponseData data;
public ImageResponseData getData() { return data; }
public void setData(ImageResponseData data) { this.data = data; }
}
public static class VulnerabilityResponse {
private VulnerabilityResponseData data;
public VulnerabilityResponseData getData() { return data; }
public void setData(VulnerabilityResponseData data) { this.data = data; }
}
public static class ComplianceResponse {
private ComplianceResponseData data;
public ComplianceResponseData getData() { return data; }
public void setData(ComplianceResponseData data) { this.data = data; }
}
public static class ThreatIntelligenceResponse {
private ThreatResponseData data;
public ThreatResponseData getData() { return data; }
public void setData(ThreatResponseData data) { this.data = data; }
}
public static class ResponseData {
private List<CloudNode> cloud_nodes;
public List<CloudNode> getCloudNodes() { return cloud_nodes; }
public void setCloudNodes(List<CloudNode> cloud_nodes) { this.cloud_nodes = cloud_nodes; }
}
public static class ImageResponseData {
private List<ContainerImage> images;
public List<ContainerImage> getImages() { return images; }
public void setImages(List<ContainerImage> images) { this.images = images; }
}
public static class VulnerabilityResponseData {
private List<Vulnerability> vulnerabilities;
public List<Vulnerability> getVulnerabilities() { return vulnerabilities; }
public void setVulnerabilities(List<Vulnerability> vulnerabilities) { this.vulnerabilities = vulnerabilities; }
}
public static class ComplianceResponseData {
private List<Compliance> compliances;
public List<Compliance> getCompliances() { return compliances; }
public void setCompliances(List<Compliance> compliances) { this.compliances = compliances; }
}
public static class ThreatResponseData {
private List<Threat> threats;
public List<Threat> getThreats() { return threats; }
public void setThreats(List<Threat> threats) { this.threats = threats; }
}
public static class CloudNode {
private String node_id;
private String node_name;
private String node_type;
private String cloud_provider;
private String region;
private String status;
private int vulnerability_count;
private int compliance_violation_count;
// Getters and setters
public String getNode_id() { return node_id; }
public void setNode_id(String node_id) { this.node_id = node_id; }
public String getNode_name() { return node_name; }
public void setNode_name(String node_name) { this.node_name = node_name; }
public String getNode_type() { return node_type; }
public void setNode_type(String node_type) { this.node_type = node_type; }
public String getCloud_provider() { return cloud_provider; }
public void setCloud_provider(String cloud_provider) { this.cloud_provider = cloud_provider; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public int getVulnerability_count() { return vulnerability_count; }
public void setVulnerability_count(int vulnerability_count) { this.vulnerability_count = vulnerability_count; }
public int getCompliance_violation_count() { return compliance_violation_count; }
public void setCompliance_violation_count(int compliance_violation_count) { this.compliance_violation_count = compliance_violation_count; }
}
public static class ContainerImage {
private String image_id;
private String image_name;
private String tag;
private String registry;
private Date created_at;
private long size;
private int vulnerability_count;
private String scan_status;
// Getters and setters
public String getImage_id() { return image_id; }
public void setImage_id(String image_id) { this.image_id = image_id; }
public String getImage_name() { return image_name; }
public void setImage_name(String image_name) { this.image_name = image_name; }
public String getTag() { return tag; }
public void setTag(String tag) { this.tag = tag; }
public String getRegistry() { return registry; }
public void setRegistry(String registry) { this.registry = registry; }
public Date getCreated_at() { return created_at; }
public void setCreated_at(Date created_at) { this.created_at = created_at; }
public long getSize() { return size; }
public void setSize(long size) { this.size = size; }
public int getVulnerability_count() { return vulnerability_count; }
public void setVulnerability_count(int vulnerability_count) { this.vulnerability_count = vulnerability_count; }
public String getScan_status() { return scan_status; }
public void setScan_status(String scan_status) { this.scan_status = scan_status; }
}
public static class VulnerabilityScanReport {
private String scan_id;
private String status;
private Date started_at;
private Date completed_at;
private int total_vulnerabilities;
private int critical_count;
private int high_count;
private int medium_count;
private int low_count;
// Getters and setters
public String getScan_id() { return scan_id; }
public void setScan_id(String scan_id) { this.scan_id = scan_id; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Date getStarted_at() { return started_at; }
public void setStarted_at(Date started_at) { this.started_at = started_at; }
public Date getCompleted_at() { return completed_at; }
public void setCompleted_at(Date completed_at) { this.completed_at = completed_at; }
public int getTotal_vulnerabilities() { return total_vulnerabilities; }
public void setTotal_vulnerabilities(int total_vulnerabilities) { this.total_vulnerabilities = total_vulnerabilities; }
public int getCritical_count() { return critical_count; }
public void setCritical_count(int critical_count) { this.critical_count = critical_count; }
public int getHigh_count() { return high_count; }
public void setHigh_count(int high_count) { this.high_count = high_count; }
public int getMedium_count() { return medium_count; }
public void setMedium_count(int medium_count) { this.medium_count = medium_count; }
public int getLow_count() { return low_count; }
public void setLow_count(int low_count) { this.low_count = low_count; }
}
public static class Vulnerability {
private String cve_id;
private String severity;
private String package_name;
private String package_version;
private String fixed_version;
private String description;
private List<String> references;
private Date published_date;
private double cvss_score;
private String attack_vector;
// Getters and setters
public String getCve_id() { return cve_id; }
public void setCve_id(String cve_id) { this.cve_id = cve_id; }
public String getSeverity() { return severity; }
public void setSeverity(String severity) { this.severity = severity; }
public String getPackage_name() { return package_name; }
public void setPackage_name(String package_name) { this.package_name = package_name; }
public String getPackage_version() { return package_version; }
public void setPackage_version(String package_version) { this.package_version = package_version; }
public String getFixed_version() { return fixed_version; }
public void setFixed_version(String fixed_version) { this.fixed_version = fixed_version; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public List<String> getReferences() { return references; }
public void setReferences(List<String> references) { this.references = references; }
public Date getPublished_date() { return published_date; }
public void setPublished_date(Date published_date) { this.published_date = published_date; }
public double getCvss_score() { return cvss_score; }
public void setCvss_score(double cvss_score) { this.cvss_score = cvss_score; }
public String getAttack_vector() { return attack_vector; }
public void setAttack_vector(String attack_vector) { this.attack_vector = attack_vector; }
}
public static class Compliance {
private String compliance_id;
private String node_id;
private String compliance_type;
private String test_number;
private String description;
private String status;
private String severity;
private String remediation;
// Getters and setters
public String getCompliance_id() { return compliance_id; }
public void setCompliance_id(String compliance_id) { this.compliance_id = compliance_id; }
public String getNode_id() { return node_id; }
public void setNode_id(String node_id) { this.node_id = node_id; }
public String getCompliance_type() { return compliance_type; }
public void setCompliance_type(String compliance_type) { this.compliance_type = compliance_type; }
public String getTest_number() { return test_number; }
public void setTest_number(String test_number) { this.test_number = test_number; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getSeverity() { return severity; }
public void setSeverity(String severity) { this.severity = severity; }
public String getRemediation() { return remediation; }
public void setRemediation(String remediation) { this.remediation = remediation; }
}
public static class Threat {
private String threat_id;
private String title;
private String description;
private String severity;
private List<String> affected_platforms;
private Date published_date;
private List<String> mitigation;
// Getters and setters
public String getThreat_id() { return threat_id; }
public void setThreat_id(String threat_id) { this.threat_id = threat_id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getSeverity() { return severity; }
public void setSeverity(String severity) { this.severity = severity; }
public List<String> getAffected_platforms() { return affected_platforms; }
public void setAffected_platforms(List<String> affected_platforms) { this.affected_platforms = affected_platforms; }
public Date getPublished_date() { return published_date; }
public void setPublished_date(Date published_date) { this.published_date = published_date; }
public List<String> getMitigation() { return mitigation; }
public void setMitigation(List<String> mitigation) { this.mitigation = mitigation; }
}
public static class TopologyData {
private List<TopologyNode> nodes;
private List<TopologyEdge> edges;
// Getters and setters
public List<TopologyNode> getNodes() { return nodes; }
public void setNodes(List<TopologyNode> nodes) { this.nodes = nodes; }
public List<TopologyEdge> getEdges() { return edges; }
public void setEdges(List<TopologyEdge> edges) { this.edges = edges; }
}
public static class TopologyNode {
private String id;
private String type;
private String name;
private Map<String, Object> properties;
// Getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Map<String, Object> getProperties() { return properties; }
public void setProperties(Map<String, Object> properties) { this.properties = properties; }
}
public static class TopologyEdge {
private String source;
private String target;
private String type;
// Getters and setters
public String getSource() { return source; }
public void setSource(String source) { this.source = source; }
public String getTarget() { return target; }
public void setTarget(String target) { this.target = target; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
}
public static class AttackPathAnalysis {
private String node_id;
private List<AttackPath> attack_paths;
private int risk_score;
private String risk_level;
// Getters and setters
public String getNode_id() { return node_id; }
public void setNode_id(String node_id) { this.node_id = node_id; }
public List<AttackPath> getAttack_paths() { return attack_paths; }
public void setAttack_paths(List<AttackPath> attack_paths) { this.attack_paths = attack_paths; }
public int getRisk_score() { return risk_score; }
public void setRisk_score(int risk_score) { this.risk_score = risk_score; }
public String getRisk_level() { return risk_level; }
public void setRisk_level(String risk_level) { this.risk_level = risk_level; }
}
public static class AttackPath {
private String path_id;
private List<String> steps;
private String severity;
private String description;
private List<String> mitigation_steps;
// Getters and setters
public String getPath_id() { return path_id; }
public void setPath_id(String path_id) { this.path_id = path_id; }
public List<String> getSteps() { return steps; }
public void setSteps(List<String> steps) { this.steps = steps; }
public String getSeverity() { return severity; }
public void setSeverity(String severity) { this.severity = severity; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public List<String> getMitigation_steps() { return mitigation_steps; }
public void setMitigation_steps(List<String> mitigation_steps) { this.mitigation_steps = mitigation_steps; }
}
}
2. Threat Monitoring Service
package com.example.security.deepfence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
@Service
public class ThreatMonitoringService {
private static final Logger logger = LoggerFactory.getLogger(ThreatMonitoringService.class);
private final DeepfenceClientService deepfenceClient;
private final SecurityAlertService alertService;
public ThreatMonitoringService(DeepfenceClientService deepfenceClient,
SecurityAlertService alertService) {
this.deepfenceClient = deepfenceClient;
this.alertService = alertService;
}
@Scheduled(cron = "0 */5 * * * ?") // Every 5 minutes
public void monitorRuntimeThreats() {
logger.info("Starting runtime threat monitoring");
try {
// Get cloud nodes and check for threats
List<DeepfenceClientService.CloudNode> nodes = deepfenceClient.getCloudNodes();
for (DeepfenceClientService.CloudNode node : nodes) {
monitorNodeThreats(node);
}
// Monitor container images
monitorContainerImages();
// Check threat intelligence
monitorThreatIntelligence();
} catch (Exception e) {
logger.error("Runtime threat monitoring failed", e);
alertService.sendAlert("Threat monitoring failure", e.getMessage());
}
}
@Scheduled(cron = "0 0 2 * * ?") // Daily at 2 AM
public void performDeepSecurityScan() {
logger.info("Starting deep security scan");
try {
// Scan all container images
List<DeepfenceClientService.ContainerImage> images = deepfenceClient.getContainerImages();
for (DeepfenceClientService.ContainerImage image : images) {
if ("ready".equals(image.getScan_status())) {
performImageSecurityScan(image);
}
}
// Perform compliance checks
performComplianceChecks();
// Analyze attack paths
analyzeAttackPaths();
} catch (Exception e) {
logger.error("Deep security scan failed", e);
alertService.sendAlert("Deep security scan failure", e.getMessage());
}
}
public SecurityAssessment assessApplicationSecurity() {
SecurityAssessment assessment = new SecurityAssessment();
assessment.setAssessmentTime(new Date());
try {
// Get topology data
DeepfenceClientService.TopologyData topology = deepfenceClient.getTopology();
assessment.setTopologyData(topology);
// Analyze vulnerabilities
List<DeepfenceClientService.ContainerImage> images = deepfenceClient.getContainerImages();
int totalVulnerabilities = images.stream()
.mapToInt(DeepfenceClientService.ContainerImage::getVulnerability_count)
.sum();
assessment.setTotalVulnerabilities(totalVulnerabilities);
// Analyze compliance
List<DeepfenceClientService.CloudNode> nodes = deepfenceClient.getCloudNodes();
int totalComplianceViolations = nodes.stream()
.mapToInt(DeepfenceClientService.CloudNode::getCompliance_violation_count)
.sum();
assessment.setTotalComplianceViolations(totalComplianceViolations);
// Calculate risk score
int riskScore = calculateRiskScore(totalVulnerabilities, totalComplianceViolations);
assessment.setRiskScore(riskScore);
assessment.setRiskLevel(determineRiskLevel(riskScore));
assessment.setSuccessful(true);
} catch (Exception e) {
logger.error("Security assessment failed", e);
assessment.setSuccessful(false);
assessment.setErrorMessage(e.getMessage());
}
return assessment;
}
public List<VulnerabilityAlert> getCriticalVulnerabilities() throws IOException {
List<VulnerabilityAlert> criticalAlerts = new ArrayList<>();
List<DeepfenceClientService.ContainerImage> images = deepfenceClient.getContainerImages();
for (DeepfenceClientService.ContainerImage image : images) {
if (image.getVulnerability_count() > 0) {
// Get detailed vulnerabilities for critical/high severity
// This would require additional API calls to get specific vulnerabilities
if (image.getVulnerability_count() > 10) { // Threshold
VulnerabilityAlert alert = new VulnerabilityAlert();
alert.setImageName(image.getImage_name());
alert.setTag(image.getTag());
alert.setVulnerabilityCount(image.getVulnerability_count());
alert.setAlertLevel("HIGH");
criticalAlerts.add(alert);
}
}
}
return criticalAlerts;
}
private void monitorNodeThreats(DeepfenceClientService.CloudNode node) throws IOException {
if (node.getVulnerability_count() > 20) {
alertService.sendAlert(
"High vulnerability count in node: " + node.getNode_name(),
String.format("Node %s has %d vulnerabilities", node.getNode_name(), node.getVulnerability_count())
);
}
if (node.getCompliance_violation_count() > 10) {
alertService.sendAlert(
"High compliance violations in node: " + node.getNode_name(),
String.format("Node %s has %d compliance violations", node.getNode_name(), node.getCompliance_violation_count())
);
}
// Analyze attack paths for high-risk nodes
if (node.getVulnerability_count() > 50 || node.getCompliance_violation_count() > 20) {
DeepfenceClientService.AttackPathAnalysis attackPaths =
deepfenceClient.analyzeAttackPaths(node.getNode_id());
if (attackPaths.getRisk_level().equals("HIGH") || attackPaths.getRisk_level().equals("CRITICAL")) {
alertService.sendCriticalAlert(
"Critical attack path detected for node: " + node.getNode_name(),
"Risk score: " + attackPaths.getRisk_score() + ", Risk level: " + attackPaths.getRisk_level()
);
}
}
}
private void monitorContainerImages() throws IOException {
List<DeepfenceClientService.ContainerImage> images = deepfenceClient.getContainerImages();
for (DeepfenceClientService.ContainerImage image : images) {
if ("scan_failed".equals(image.getScan_status())) {
alertService.sendAlert(
"Image scan failed: " + image.getImage_name(),
"Image " + image.getImage_name() + ":" + image.getTag() + " scan failed"
);
}
if (image.getVulnerability_count() > 50) {
alertService.sendAlert(
"High vulnerability image: " + image.getImage_name(),
String.format("Image %s:%s has %d vulnerabilities",
image.getImage_name(), image.getTag(), image.getVulnerability_count())
);
}
}
}
private void monitorThreatIntelligence() throws IOException {
List<DeepfenceClientService.Threat> threats = deepfenceClient.getThreatIntelligence();
for (DeepfenceClientService.Threat threat : threats) {
if ("CRITICAL".equals(threat.getSeverity()) || "HIGH".equals(threat.getSeverity())) {
alertService.sendAlert(
"New threat intelligence: " + threat.getTitle(),
"Severity: " + threat.getSeverity() + " - " + threat.getDescription()
);
}
}
}
private void performImageSecurityScan(DeepfenceClientService.ContainerImage image) throws IOException {
logger.info("Scanning image: {}:{}", image.getImage_name(), image.getTag());
DeepfenceClientService.VulnerabilityScanReport scanReport =
deepfenceClient.scanImage(image.getImage_name(), image.getTag());
if ("completed".equals(scanReport.getStatus())) {
if (scanReport.getCritical_count() > 0) {
alertService.sendCriticalAlert(
"Critical vulnerabilities found in image: " + image.getImage_name(),
String.format("Critical: %d, High: %d, Total: %d",
scanReport.getCritical_count(),
scanReport.getHigh_count(),
scanReport.getTotal_vulnerabilities())
);
}
}
}
private void performComplianceChecks() throws IOException {
List<DeepfenceClientService.CloudNode> nodes = deepfenceClient.getCloudNodes();
for (DeepfenceClientService.CloudNode node : nodes) {
List<DeepfenceClientService.Compliance> compliances =
deepfenceClient.getComplianceResults(node.getNode_id());
long criticalViolations = compliances.stream()
.filter(c -> "CRITICAL".equals(c.getSeverity()) && "FAIL".equals(c.getStatus()))
.count();
if (criticalViolations > 0) {
alertService.sendCriticalAlert(
"Critical compliance violations in node: " + node.getNode_name(),
"Found " + criticalViolations + " critical compliance violations"
);
}
}
}
private void analyzeAttackPaths() throws IOException {
List<DeepfenceClientService.CloudNode> nodes = deepfenceClient.getCloudNodes();
for (DeepfenceClientService.CloudNode node : nodes) {
if (node.getVulnerability_count() > 10) {
DeepfenceClientService.AttackPathAnalysis attackPaths =
deepfenceClient.analyzeAttackPaths(node.getNode_id());
if ("CRITICAL".equals(attackPaths.getRisk_level())) {
logger.warn("Critical attack paths found for node {}: {}",
node.getNode_name(), attackPaths.getAttack_paths().size());
}
}
}
}
private int calculateRiskScore(int vulnerabilities, int complianceViolations) {
// Simple risk calculation - in practice, this would be more sophisticated
return vulnerabilities + (complianceViolations * 2);
}
private String determineRiskLevel(int riskScore) {
if (riskScore >= 100) return "CRITICAL";
if (riskScore >= 50) return "HIGH";
if (riskScore >= 20) return "MEDIUM";
if (riskScore >= 10) return "LOW";
return "MINIMAL";
}
// DTO classes
public static class SecurityAssessment {
private Date assessmentTime;
private boolean successful;
private String errorMessage;
private int totalVulnerabilities;
private int totalComplianceViolations;
private int riskScore;
private String riskLevel;
private DeepfenceClientService.TopologyData topologyData;
// Getters and setters
public Date getAssessmentTime() { return assessmentTime; }
public void setAssessmentTime(Date assessmentTime) { this.assessmentTime = assessmentTime; }
public boolean isSuccessful() { return successful; }
public void setSuccessful(boolean successful) { this.successful = successful; }
public String getErrorMessage() { return errorMessage; }
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
public int getTotalVulnerabilities() { return totalVulnerabilities; }
public void setTotalVulnerabilities(int totalVulnerabilities) { this.totalVulnerabilities = totalVulnerabilities; }
public int getTotalComplianceViolations() { return totalComplianceViolations; }
public void setTotalComplianceViolations(int totalComplianceViolations) { this.totalComplianceViolations = totalComplianceViolations; }
public int getRiskScore() { return riskScore; }
public void setRiskScore(int riskScore) { this.riskScore = riskScore; }
public String getRiskLevel() { return riskLevel; }
public void setRiskLevel(String riskLevel) { this.riskLevel = riskLevel; }
public DeepfenceClientService.TopologyData getTopologyData() { return topologyData; }
public void setTopologyData(DeepfenceClientService.TopologyData topologyData) { this.topologyData = topologyData; }
}
public static class VulnerabilityAlert {
private String imageName;
private String tag;
private int vulnerabilityCount;
private String alertLevel;
private Date detectedAt;
// Getters and setters
public String getImageName() { return imageName; }
public void setImageName(String imageName) { this.imageName = imageName; }
public String getTag() { return tag; }
public void setTag(String tag) { this.tag = tag; }
public int getVulnerabilityCount() { return vulnerabilityCount; }
public void setVulnerabilityCount(int vulnerabilityCount) { this.vulnerabilityCount = vulnerabilityCount; }
public String getAlertLevel() { return alertLevel; }
public void setAlertLevel(String alertLevel) { this.alertLevel = alertLevel; }
public Date getDetectedAt() { return detectedAt; }
public void setDetectedAt(Date detectedAt) { this.detectedAt = detectedAt; }
}
}
3. Security Dashboard Controller
package com.example.security.deepfence;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/api/security/deepfence")
@PreAuthorize("hasRole('SECURITY_TEAM')")
public class DeepfenceSecurityController {
private final DeepfenceClientService deepfenceClient;
private final ThreatMonitoringService threatMonitoringService;
public DeepfenceSecurityController(DeepfenceClientService deepfenceClient,
ThreatMonitoringService threatMonitoringService) {
this.deepfenceClient = deepfenceClient;
this.threatMonitoringService = threatMonitoringService;
}
@GetMapping("/assessment")
public ThreatMonitoringService.SecurityAssessment getSecurityAssessment() {
return threatMonitoringService.assessApplicationSecurity();
}
@GetMapping("/nodes")
public List<DeepfenceClientService.CloudNode> getCloudNodes() throws IOException {
return deepfenceClient.getCloudNodes();
}
@GetMapping("/images")
public List<DeepfenceClientService.ContainerImage> getContainerImages() throws IOException {
return deepfenceClient.getContainerImages();
}
@GetMapping("/vulnerabilities/critical")
public List<ThreatMonitoringService.VulnerabilityAlert> getCriticalVulnerabilities() throws IOException {
return threatMonitoringService.getCriticalVulnerabilities();
}
@PostMapping("/scan/image")
public DeepfenceClientService.VulnerabilityScanReport scanImage(
@RequestParam String imageName,
@RequestParam String tag) throws IOException {
return deepfenceClient.scanImage(imageName, tag);
}
@GetMapping("/vulnerabilities/{scanId}")
public List<DeepfenceClientService.Vulnerability> getVulnerabilities(
@PathVariable String scanId) throws IOException {
return deepfenceClient.getVulnerabilities(scanId);
}
@GetMapping("/compliance/{nodeId}")
public List<DeepfenceClientService.Compliance> getComplianceResults(
@PathVariable String nodeId) throws IOException {
return deepfenceClient.getComplianceResults(nodeId);
}
@GetMapping("/threat-intel")
public List<DeepfenceClientService.Threat> getThreatIntelligence() throws IOException {
return deepfenceClient.getThreatIntelligence();
}
@GetMapping("/topology")
public DeepfenceClientService.TopologyData getTopology() throws IOException {
return deepfenceClient.getTopology();
}
@GetMapping("/attack-paths/{nodeId}")
public DeepfenceClientService.AttackPathAnalysis analyzeAttackPaths(
@PathVariable String nodeId) throws IOException {
return deepfenceClient.analyzeAttackPaths(nodeId);
}
@PostMapping("/scan/trigger-full")
public String triggerFullSecurityScan() {
threatMonitoringService.performDeepSecurityScan();
return "Full security scan triggered";
}
}
CI/CD Integration
1. GitHub Actions Workflow
# .github/workflows/deepfence-scan.yml
name: Deepfence Security Scan
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
schedule:
- cron: '0 6 * * 1' # Weekly Monday at 6 AM
jobs:
security-scan:
name: Deepfence Runtime Security Scan
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Build with Maven
run: mvn clean package -DskipTests
- name: Build Docker image
run: |
docker build -t my-app:${{ github.sha }} .
docker tag my-app:${{ github.sha }} my-app:latest
- name: Install Deepfence Agent
run: |
curl -s https://packages.deepfence.io/deepfence-agent/install.sh | sudo bash
sudo deepfence_agent config set management_console_url ${{ secrets.DEEPFENCE_URL }}
sudo deepfence_agent config set deepfence_key ${{ secrets.DEEPFENCE_API_KEY }}
sudo systemctl start deepfence-agent
- name: Run Deepfence Scan
run: |
# Trigger vulnerability scan
curl -X POST \
-H "Authorization: Bearer ${{ secrets.DEEPFENCE_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{"image_name": "my-app", "tag": "${{ github.sha }}"}' \
"${{ secrets.DEEPFENCE_URL }}/deepfence/scan/image"
- name: Check Scan Results
run: |
sleep 60 # Wait for scan completion
curl -X GET \
-H "Authorization: Bearer ${{ secrets.DEEPFENCE_API_KEY }}" \
"${{ secrets.DEEPFENCE_URL }}/deepfence/images" > scan-results.json
# Check for critical vulnerabilities
CRITICAL_COUNT=$(jq '.data.images[] | select(.image_name == "my-app") | .vulnerability_count' scan-results.json)
if [ "$CRITICAL_COUNT" -gt "0" ]; then
echo "❌ Critical vulnerabilities detected: $CRITICAL_COUNT"
exit 1
else
echo "✅ No critical vulnerabilities detected"
fi
- name: Upload Security Report
uses: actions/upload-artifact@v3
with:
name: deepfence-security-report
path: scan-results.json
2. Docker Compose with Deepfence
# docker-compose.yml
version: '3.8'
services:
app:
build: .
image: my-app:latest
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
- DEEPFENCE_KEY=${DEEPFENCE_KEY}
labels:
- "deepfence.role=application"
- "deepfence.environment=production"
deepfence-agent:
image: deepfenceio/deepfence_agent_ce:latest
container_name: deepfence-agent
restart: unless-stopped
environment:
- DEEPFENCE_KEY=${DEEPFENCE_KEY}
- DEEPFENCE_MGMT_CONSOLE_URL=${DEEPFENCE_URL}
- DEEPFENCE_MGMT_CONSOLE_PORT=443
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /:/fenced/mnt/host/:ro
pid: host
privileged: true
cap_add:
- ALL
network_mode: host
deepfence-console:
image: deepfenceio/deepfence_console_ce:latest
container_name: deepfence-console
restart: unless-stopped
ports:
- "8081:8081"
environment:
- DEEPFENCE_KEY=${DEEPFENCE_KEY}
depends_on:
- deepfence-agent
Best Practices
- Runtime Security:
- Continuous monitoring of running containers
- Real-time threat detection
- Network topology analysis
- Compliance monitoring
- Vulnerability Management:
- Regular image scanning
- Attack path analysis
- Risk scoring and prioritization
- Automated remediation suggestions
- Integration Strategy:
- CI/CD pipeline integration
- Real-time alerting
- Centralized dashboard
- API-driven automation
- Compliance:
- CIS benchmark compliance
- Regulatory compliance monitoring
- Custom compliance checks
- Audit reporting
# Deepfence CLI commands deepfence scan image my-app:latest deepfence list vulnerabilities deepfence topology view deepfence compliance check
Conclusion
Deepfence ThreatMapper for Java provides:
- Runtime security monitoring for containers and cloud workloads
- Vulnerability scanning and attack path analysis
- Compliance monitoring with CIS benchmarks
- Threat intelligence integration
- Real-time alerting and dashboard
By implementing the patterns and configurations shown above, you can establish comprehensive runtime security monitoring, identify vulnerabilities and attack paths in real-time, ensure compliance with security standards, and maintain a robust security posture for your Java applications in production environments.