Signal Sciences WAF in Java

1. Core IP Reputation Models

// IPReputation.java
package com.ipreputation.core;
import java.time.Instant;
import java.util.*;
public class IPReputation {
private final String ipAddress;
private final Instant timestamp;
private final ReputationScore overallScore;
private final Map<String, ThreatIntelligenceSource> sources;
private final List<ThreatCategory> threatCategories;
private final Map<String, Object> metadata;
private final boolean isMalicious;
private final int confidence;
public IPReputation(String ipAddress, ReputationScore overallScore,
Map<String, ThreatIntelligenceSource> sources,
List<ThreatCategory> threatCategories,
Map<String, Object> metadata) {
this.ipAddress = ipAddress;
this.timestamp = Instant.now();
this.overallScore = overallScore;
this.sources = sources != null ? new HashMap<>(sources) : new HashMap<>();
this.threatCategories = threatCategories != null ? new ArrayList<>(threatCategories) : new ArrayList<>();
this.metadata = metadata != null ? new HashMap<>(metadata) : new HashMap<>();
this.isMalicious = calculateMaliciousStatus();
this.confidence = calculateConfidence();
}
private boolean calculateMaliciousStatus() {
return overallScore.getScore() >= 70 || 
threatCategories.stream().anyMatch(ThreatCategory::isHighRisk);
}
private int calculateConfidence() {
int sourceCount = sources.size();
int highConfidenceSources = (int) sources.values().stream()
.filter(source -> source.getConfidence() >= 80)
.count();
if (sourceCount == 0) return 0;
return (highConfidenceSources * 100) / sourceCount;
}
// Getters
public String getIpAddress() { return ipAddress; }
public Instant getTimestamp() { return timestamp; }
public ReputationScore getOverallScore() { return overallScore; }
public Map<String, ThreatIntelligenceSource> getSources() { return Collections.unmodifiableMap(sources); }
public List<ThreatCategory> getThreatCategories() { return Collections.unmodifiableList(threatCategories); }
public Map<String, Object> getMetadata() { return Collections.unmodifiableMap(metadata); }
public boolean isMalicious() { return isMalicious; }
public int getConfidence() { return confidence; }
public ThreatLevel getThreatLevel() {
if (overallScore.getScore() >= 80) return ThreatLevel.CRITICAL;
if (overallScore.getScore() >= 60) return ThreatLevel.HIGH;
if (overallScore.getScore() >= 40) return ThreatLevel.MEDIUM;
if (overallScore.getScore() >= 20) return ThreatLevel.LOW;
return ThreatLevel.TRUSTED;
}
public boolean hasThreatCategory(ThreatType type) {
return threatCategories.stream()
.anyMatch(category -> category.getType() == type);
}
public Optional<ThreatIntelligenceSource> getSource(String sourceName) {
return Optional.ofNullable(sources.get(sourceName));
}
public static class Builder {
private String ipAddress;
private ReputationScore overallScore = new ReputationScore(0, "UNKNOWN");
private Map<String, ThreatIntelligenceSource> sources = new HashMap<>();
private List<ThreatCategory> threatCategories = new ArrayList<>();
private Map<String, Object> metadata = new HashMap<>();
public Builder(String ipAddress) {
this.ipAddress = ipAddress;
}
public Builder overallScore(ReputationScore score) {
this.overallScore = score;
return this;
}
public Builder source(ThreatIntelligenceSource source) {
this.sources.put(source.getName(), source);
return this;
}
public Builder threatCategory(ThreatCategory category) {
this.threatCategories.add(category);
return this;
}
public Builder metadata(String key, Object value) {
this.metadata.put(key, value);
return this;
}
public IPReputation build() {
return new IPReputation(ipAddress, overallScore, sources, threatCategories, metadata);
}
}
}
// ReputationScore.java
package com.ipreputation.core;
public class ReputationScore {
private final int score; // 0-100, higher = more malicious
private final String level;
public ReputationScore(int score, String level) {
this.score = Math.max(0, Math.min(100, score));
this.level = level;
}
public ReputationScore(int score) {
this(score, calculateLevel(score));
}
private static String calculateLevel(int score) {
if (score >= 80) return "CRITICAL";
if (score >= 60) return "HIGH";
if (score >= 40) return "MEDIUM";
if (score >= 20) return "LOW";
return "TRUSTED";
}
// Getters
public int getScore() { return score; }
public String getLevel() { return level; }
public boolean isMalicious() {
return score >= 60;
}
public boolean isSuspicious() {
return score >= 40;
}
@Override
public String toString() {
return String.format("%d (%s)", score, level);
}
}
// ThreatIntelligenceSource.java
package com.ipreputation.core;
import java.time.Instant;
import java.util.Map;
public class ThreatIntelligenceSource {
private final String name;
private final String description;
private final int confidence; // 0-100
private final Instant lastUpdated;
private final Map<String, Object> data;
public ThreatIntelligenceSource(String name, String description, int confidence,
Instant lastUpdated, Map<String, Object> data) {
this.name = name;
this.description = description;
this.confidence = Math.max(0, Math.min(100, confidence));
this.lastUpdated = lastUpdated;
this.data = data != null ? Map.copyOf(data) : Map.of();
}
// Getters
public String getName() { return name; }
public String getDescription() { return description; }
public int getConfidence() { return confidence; }
public Instant getLastUpdated() { return lastUpdated; }
public Map<String, Object> getData() { return data; }
public static class Builder {
private String name;
private String description;
private int confidence = 50;
private Instant lastUpdated = Instant.now();
private Map<String, Object> data = Map.of();
public Builder(String name) {
this.name = name;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder confidence(int confidence) {
this.confidence = confidence;
return this;
}
public Builder lastUpdated(Instant lastUpdated) {
this.lastUpdated = lastUpdated;
return this;
}
public Builder data(Map<String, Object> data) {
this.data = data;
return this;
}
public ThreatIntelligenceSource build() {
return new ThreatIntelligenceSource(name, description, confidence, lastUpdated, data);
}
}
}
// ThreatCategory.java
package com.ipreputation.core;
import java.util.List;
public class ThreatCategory {
private final ThreatType type;
private final String description;
private final int severity; // 0-100
private final List<String> evidence;
private final boolean active;
public ThreatCategory(ThreatType type, String description, int severity,
List<String> evidence, boolean active) {
this.type = type;
this.description = description;
this.severity = Math.max(0, Math.min(100, severity));
this.evidence = evidence != null ? List.copyOf(evidence) : List.of();
this.active = active;
}
// Getters
public ThreatType getType() { return type; }
public String getDescription() { return description; }
public int getSeverity() { return severity; }
public List<String> getEvidence() { return evidence; }
public boolean isActive() { return active; }
public boolean isHighRisk() {
return severity >= 70;
}
public static class Builder {
private ThreatType type;
private String description;
private int severity = 50;
private List<String> evidence = List.of();
private boolean active = true;
public Builder(ThreatType type) {
this.type = type;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder severity(int severity) {
this.severity = severity;
return this;
}
public Builder evidence(List<String> evidence) {
this.evidence = evidence;
return this;
}
public Builder active(boolean active) {
this.active = active;
return this;
}
public ThreatCategory build() {
return new ThreatCategory(type, description, severity, evidence, active);
}
}
}
// Enums
package com.ipreputation.core;
public enum ThreatType {
MALWARE_DISTRIBUTION,
BOTNET,
SPAM_SOURCE,
SCANNER,
DDoS_ATTACK,
BRUTE_FORCE,
WEB_ATTACK,
FRAUD,
PHISHING,
COMMAND_AND_CONTROL,
TOR_EXIT_NODE,
VPN,
PROXY,
SPOOFING,
EXPLOIT,
DATA_LEAK,
CRYPTO_MINING
}
public enum ThreatLevel {
TRUSTED(0, "TRUSTED"),
LOW(1, "LOW"),
MEDIUM(2, "MEDIUM"),
HIGH(3, "HIGH"),
CRITICAL(4, "CRITICAL");
private final int level;
private final String description;
ThreatLevel(int level, String description) {
this.level = level;
this.description = description;
}
public int getLevel() { return level; }
public String getDescription() { return description; }
}

2. Threat Intelligence Providers

// ThreatIntelligenceProvider.java
package com.ipreputation.providers;
import com.ipreputation.core.IPReputation;
import com.ipreputation.core.ThreatIntelligenceSource;
import java.util.concurrent.CompletableFuture;
public interface ThreatIntelligenceProvider {
String getName();
boolean isEnabled();
CompletableFuture<ThreatIntelligenceSource> checkIP(String ipAddress);
int getPriority();
long getTimeoutMs();
}
// AbuseIPDBProvider.java
package com.ipreputation.providers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ipreputation.core.ThreatIntelligenceSource;
import com.ipreputation.core.ThreatCategory;
import com.ipreputation.core.ThreatType;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.util.*;
public class AbuseIPDBProvider implements ThreatIntelligenceProvider {
private final String apiKey;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
private final String baseUrl = "https://api.abuseipdb.com/api/v2/check";
private boolean enabled = true;
public AbuseIPDBProvider(String apiKey) {
this.apiKey = apiKey;
this.httpClient = HttpClient.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(10))
.build();
this.objectMapper = new ObjectMapper();
}
@Override
public String getName() {
return "AbuseIPDB";
}
@Override
public boolean isEnabled() {
return enabled && apiKey != null && !apiKey.trim().isEmpty();
}
@Override
public CompletableFuture<ThreatIntelligenceSource> checkIP(String ipAddress) {
if (!isEnabled()) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.supplyAsync(() -> {
try {
String url = baseUrl + "?ipAddress=" + ipAddress + "&maxAgeInDays=90";
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create(url))
.header("Key", apiKey)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, 
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return parseResponse(ipAddress, response.body());
} else {
System.err.println("AbuseIPDB API error: " + response.statusCode() + " - " + response.body());
return createErrorSource(ipAddress, "HTTP " + response.statusCode());
}
} catch (Exception e) {
System.err.println("Error checking AbuseIPDB for IP " + ipAddress + ": " + e.getMessage());
return createErrorSource(ipAddress, e.getMessage());
}
});
}
private ThreatIntelligenceSource parseResponse(String ipAddress, String responseBody) throws Exception {
JsonNode root = objectMapper.readTree(responseBody);
JsonNode data = root.get("data");
int abuseConfidenceScore = data.get("abuseConfidenceScore").asInt();
int totalReports = data.get("totalReports").asInt();
String countryCode = data.get("countryCode").asText();
String isp = data.get("isp").asText();
String domain = data.get("domain").asText();
boolean isWhitelisted = data.get("isWhitelisted").asBoolean();
int numDistinctUsers = data.get("numDistinctUsers").asInt();
Map<String, Object> sourceData = new HashMap<>();
sourceData.put("totalReports", totalReports);
sourceData.put("countryCode", countryCode);
sourceData.put("isp", isp);
sourceData.put("domain", domain);
sourceData.put("isWhitelisted", isWhitelisted);
sourceData.put("numDistinctUsers", numDistinctUsers);
// Calculate confidence based on abuse score and report count
int confidence = calculateConfidence(abuseConfidenceScore, totalReports);
return new ThreatIntelligenceSource.Builder(getName())
.description("AbuseIPDB Threat Intelligence")
.confidence(confidence)
.lastUpdated(Instant.now())
.data(sourceData)
.build();
}
private int calculateConfidence(int abuseScore, int totalReports) {
// Weighted calculation considering both abuse score and report volume
double scoreWeight = abuseScore / 100.0;
double reportWeight = Math.min(totalReports / 50.0, 1.0); // Cap at 50 reports
return (int) ((scoreWeight * 0.7 + reportWeight * 0.3) * 100);
}
private ThreatIntelligenceSource createErrorSource(String ipAddress, String error) {
return new ThreatIntelligenceSource.Builder(getName())
.description("Error: " + error)
.confidence(0)
.lastUpdated(Instant.now())
.data(Map.of("error", error))
.build();
}
@Override
public int getPriority() {
return 10; // High priority source
}
@Override
public long getTimeoutMs() {
return 10000; // 10 seconds
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
// VirusTotalProvider.java
package com.ipreputation.providers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ipreputation.core.ThreatIntelligenceSource;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
public class VirusTotalProvider implements ThreatIntelligenceProvider {
private final String apiKey;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
private final String baseUrl = "https://www.virustotal.com/api/v3/ip_addresses";
private boolean enabled = true;
public VirusTotalProvider(String apiKey) {
this.apiKey = apiKey;
this.httpClient = HttpClient.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(15))
.build();
this.objectMapper = new ObjectMapper();
}
@Override
public String getName() {
return "VirusTotal";
}
@Override
public boolean isEnabled() {
return enabled && apiKey != null && !apiKey.trim().isEmpty();
}
@Override
public CompletableFuture<ThreatIntelligenceSource> checkIP(String ipAddress) {
if (!isEnabled()) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.supplyAsync(() -> {
try {
String url = baseUrl + "/" + ipAddress;
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create(url))
.header("x-apikey", apiKey)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, 
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return parseResponse(ipAddress, response.body());
} else {
System.err.println("VirusTotal API error: " + response.statusCode() + " - " + response.body());
return createErrorSource(ipAddress, "HTTP " + response.statusCode());
}
} catch (Exception e) {
System.err.println("Error checking VirusTotal for IP " + ipAddress + ": " + e.getMessage());
return createErrorSource(ipAddress, e.getMessage());
}
});
}
private ThreatIntelligenceSource parseResponse(String ipAddress, String responseBody) throws Exception {
JsonNode root = objectMapper.readTree(responseBody);
JsonNode data = root.get("data");
JsonNode attributes = data.get("attributes");
JsonNode lastAnalysisStats = attributes.get("last_analysis_stats");
int malicious = lastAnalysisStats.get("malicious").asInt();
int suspicious = lastAnalysisStats.get("suspicious").asInt();
int undetected = lastAnalysisStats.get("undetected").asInt();
int harmless = lastAnalysisStats.get("harmless").asInt();
int timeout = lastAnalysisStats.get("timeout").asInt();
int totalEngines = malicious + suspicious + undetected + harmless + timeout;
double threatRatio = totalEngines > 0 ? (double) (malicious + suspicious) / totalEngines : 0.0;
int confidence = (int) (threatRatio * 100);
Map<String, Object> sourceData = new HashMap<>();
sourceData.put("malicious", malicious);
sourceData.put("suspicious", suspicious);
sourceData.put("undetected", undetected);
sourceData.put("harmless", harmless);
sourceData.put("timeout", timeout);
sourceData.put("totalEngines", totalEngines);
sourceData.put("threatRatio", threatRatio);
// Add reputation if available
if (attributes.has("reputation")) {
sourceData.put("reputation", attributes.get("reputation").asInt());
}
return new ThreatIntelligenceSource.Builder(getName())
.description("VirusTotal IP Analysis")
.confidence(confidence)
.lastUpdated(Instant.now())
.data(sourceData)
.build();
}
private ThreatIntelligenceSource createErrorSource(String ipAddress, String error) {
return new ThreatIntelligenceSource.Builder(getName())
.description("Error: " + error)
.confidence(0)
.lastUpdated(Instant.now())
.data(Map.of("error", error))
.build();
}
@Override
public int getPriority() {
return 20; // Medium priority
}
@Override
public long getTimeoutMs() {
return 15000; // 15 seconds
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
// IPQualityScoreProvider.java
package com.ipreputation.providers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ipreputation.core.ThreatIntelligenceSource;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
public class IPQualityScoreProvider implements ThreatIntelligenceProvider {
private final String apiKey;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
private final String baseUrl = "https://ipqualityscore.com/api/json/ip";
private boolean enabled = true;
public IPQualityScoreProvider(String apiKey) {
this.apiKey = apiKey;
this.httpClient = HttpClient.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(10))
.build();
this.objectMapper = new ObjectMapper();
}
@Override
public String getName() {
return "IPQualityScore";
}
@Override
public boolean isEnabled() {
return enabled && apiKey != null && !apiKey.trim().isEmpty();
}
@Override
public CompletableFuture<ThreatIntelligenceSource> checkIP(String ipAddress) {
if (!isEnabled()) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.supplyAsync(() -> {
try {
String url = baseUrl + "/" + apiKey + "/" + ipAddress;
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create(url))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, 
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return parseResponse(ipAddress, response.body());
} else {
System.err.println("IPQualityScore API error: " + response.statusCode() + " - " + response.body());
return createErrorSource(ipAddress, "HTTP " + response.statusCode());
}
} catch (Exception e) {
System.err.println("Error checking IPQualityScore for IP " + ipAddress + ": " + e.getMessage());
return createErrorSource(ipAddress, e.getMessage());
}
});
}
private ThreatIntelligenceSource parseResponse(String ipAddress, String responseBody) throws Exception {
JsonNode root = objectMapper.readTree(responseBody);
boolean success = root.get("success").asBoolean();
if (!success) {
String message = root.get("message").asText();
return createErrorSource(ipAddress, message);
}
int fraudScore = root.get("fraud_score").asInt();
boolean proxy = root.get("proxy").asBoolean();
boolean vpn = root.get("vpn").asBoolean();
boolean tor = root.get("tor").asBoolean();
boolean active = root.get("active").asBoolean();
boolean bot = root.get("bot").asBoolean();
String country = root.get("country_code").asText();
String isp = root.get("ISP").asText();
String organization = root.get("organization").asText();
// Calculate confidence based on fraud score and threat indicators
int confidence = calculateConfidence(fraudScore, proxy, vpn, tor, bot);
Map<String, Object> sourceData = new HashMap<>();
sourceData.put("fraudScore", fraudScore);
sourceData.put("proxy", proxy);
sourceData.put("vpn", vpn);
sourceData.put("tor", tor);
sourceData.put("active", active);
sourceData.put("bot", bot);
sourceData.put("country", country);
sourceData.put("isp", isp);
sourceData.put("organization", organization);
return new ThreatIntelligenceSource.Builder(getName())
.description("IPQualityScore Fraud Detection")
.confidence(confidence)
.lastUpdated(Instant.now())
.data(sourceData)
.build();
}
private int calculateConfidence(int fraudScore, boolean proxy, boolean vpn, boolean tor, boolean bot) {
int baseConfidence = fraudScore;
// Boost confidence for specific threat indicators
if (proxy) baseConfidence = Math.max(baseConfidence, 70);
if (vpn) baseConfidence = Math.max(baseConfidence, 60);
if (tor) baseConfidence = Math.max(baseConfidence, 80);
if (bot) baseConfidence = Math.max(baseConfidence, 90);
return Math.min(baseConfidence, 100);
}
private ThreatIntelligenceSource createErrorSource(String ipAddress, String error) {
return new ThreatIntelligenceSource.Builder(getName())
.description("Error: " + error)
.confidence(0)
.lastUpdated(Instant.now())
.data(Map.of("error", error))
.build();
}
@Override
public int getPriority() {
return 30; // Lower priority
}
@Override
public long getTimeoutMs() {
return 10000; // 10 seconds
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
// Custom Threat Intelligence Provider
package com.ipreputation.providers;
import com.ipreputation.core.ThreatIntelligenceSource;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class CustomThreatIntelProvider implements ThreatIntelligenceProvider {
private final String name;
private final Map<String, Integer> maliciousIPs; // IP -> threat score
private boolean enabled = true;
public CustomThreatIntelProvider(String name, Map<String, Integer> maliciousIPs) {
this.name = name;
this.maliciousIPs = Map.copyOf(maliciousIPs);
}
@Override
public String getName() {
return name;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public CompletableFuture<ThreatIntelligenceSource> checkIP(String ipAddress) {
return CompletableFuture.supplyAsync(() -> {
Integer threatScore = maliciousIPs.get(ipAddress);
if (threatScore != null) {
return new ThreatIntelligenceSource.Builder(getName())
.description("Custom Threat Intelligence")
.confidence(threatScore)
.lastUpdated(Instant.now())
.data(Map.of("source", "custom", "threatScore", threatScore))
.build();
}
return null;
});
}
@Override
public int getPriority() {
return 5; // Highest priority for custom lists
}
@Override
public long getTimeoutMs() {
return 100; // Very fast for local lookups
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

3. IP Reputation Service

```java
// IPReputationService.java
package com.ipreputation.service;

import com.ipreputation.core.*;
import com.ipreputation.providers.ThreatIntelligenceProvider;

import java.util.; import java.util.concurrent.;
import java.util.stream.Collectors;

public class IPReputationService {
private final List providers;
private final IPReputationCache cache;
private final ExecutorService executorService;
private final ReputationCalculator reputationCalculator;

public IPReputationService() {
this.providers = new ArrayList<>();
this.cache = new IPReputationCache();
this.executorService = Executors.newFixedThreadPool(10);
this.reputationCalculator = new ReputationCalculator();
}
public void addProvider(ThreatIntelligenceProvider provider) {
providers.add(provider);
// Sort providers by priority (lower number = higher priority)
providers.sort(Comparator.comparingInt(ThreatIntelligenceProvider::getPriority));
}
public CompletableFuture<IPReputation> checkReputation(String ipAddress) {
// Validate IP address
if (!isValidIPAddress(ipAddress)) {
return CompletableFuture.completedFuture(createInvalidIPReputation(ipAddress));
}
// Check cache first
Optional<IPReputation> cached = cache.get(ipAddress);
if (cached.isPresent()) {
return CompletableFuture.completedFuture(cached.get());
}
// Check all providers in parallel
List<CompletableFuture<ThreatIntelligenceSource>> providerFutures = providers.stream()
.filter(ThreatIntelligenceProvider::isEnabled)
.map(provider -> checkProvider(provider, ipAddress))
.collect(Collectors.toList());
// Combine all results
return CompletableFuture.allOf(providerFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> {
Map<String, ThreatIntelligenceSource> sources = providerFutures.stream()
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
ThreatIntelligenceSource::getName,
source -> source,
(existing, replacement) -> existing.getConfidence() >= replacement.getConfidence() ? existing : replacement
));
// Calculate overall reputation
IPReputation reputation = reputationCalculator.calculateReputation(ipAddress, sources);
// Cache the result
cache.put(ipAddress, reputation);
return reputation;
})
.exceptionally(ex -> {
System.err.println("Error checking IP reputation for " + ipAddress + ": " + ex.getMessage());
return createErrorReputation(ipAddress, ex.getMessage());
});
}
public CompletableFuture<Map<String, IPReputation>> checkReputations(List<String> ipAddresses) {
List<CompletableFuture<IPReputation>> futures = ipAddresses.stream()
.map(this::checkReputation)
.collect(Collectors.toList());
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> {
Map<String, IPReputation> results = new HashMap<>();
for (int i = 0; i < ipAddresses.size(); i++) {
results.put(ipAddresses.get(i), futures.get(i).join());
}
return results;
});
}
public IPReputation checkReputationSync(String ipAddress) {
try {
return checkReputation(ipAddress).get(30, TimeUnit.SECONDS);
} catch (Exception e) {
System.err.println("Synchronous check failed for " + ipAddress + ": " + e.getMessage());
return createErrorReputation(ipAddress, e.getMessage());
}
}
private CompletableFuture<ThreatIntelligenceSource> checkProvider(
ThreatIntelligenceProvider provider, String ipAddress) {
return provider.checkIP(ipAddress)
.orTimeout(provider.getTimeoutMs(), TimeUnit.MILLISECONDS)
.exceptionally(ex -> {
System.err.println("Provider " + provider.getName() + " failed for " + ipAddress + ": " + ex.getMessage());
return null;
});
}
private boolean isValidIPAddress(String ipAddress) {
if (ipAddress == null || ipAddress.trim().isEmpty()) {
return false;
}
// Basic IP validation (IPv4 and IPv6)
String ipv4Pattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
String ipv6Pattern = "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$";
return ipAddress.matches(ipv4Pattern) || ipAddress.matches(ipv6Pattern);
}
private IPReputation createInvalidIPReputation(String ipAddress) {
return new IPReputation.Builder(ipAddress)
.overallScore(new ReputationScore(0, "INVALID"))
.metadata("error", "Invalid IP address")
.build();
}
private IPReputation createErrorReputation(String ipAddress, String error) {
return new IPReputation.Builder(ipAddress)
.overallScore(new ReputationScore(0, "ERROR"))
.metadata("error", error)
.build();
}
public void shutdown() {
executorService.shutdown();
try {
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
// Statistics and monitoring
public ServiceStatistics getStatistics() {
return new ServiceStatistics(
cache.getSize(),
cache.getHitRate(),
providers.size(),
providers.stream().filter(ThreatIntelligenceProvider::isEnabled).count()
);
}
public void clearCache() {
cache.clear();
}
public static class ServiceStatistics {
private final int cacheSize;
private final double cacheHitRate;
private final int totalProviders;
private final long enabledProviders;
public ServiceStatistics(int cacheSize, double cacheHitRate, int totalProviders, long enabledProviders) {
this.cacheSize = cacheSize;
this.cacheHitRate = cacheHitRate;
this.totalProviders = totalProviders;
this.enabledProviders = enabledProviders;
}
// Getters
public int getCacheSize() { return cacheSize; }
public double getCacheHitRate() { return cacheHitRate; }
public int getTotalProviders() { return totalProviders; }
public long getEnabledProviders() { return enabledProviders; }
}

}

// ReputationCalculator.java
package com.ipreputation.service;

import com.ipreputation.core.; import java.util.;

public class ReputationCalculator {

public IPReputation calculateReputation(String ipAddress, Map<String, ThreatIntelligenceSource> sources) {
if (sources.isEmpty()) {
return new IPReputation.Builder(ipAddress)
.overallScore(new ReputationScore(0, "UNKNOWN"))
.metadata("sources", "No data available")
.build();
}
// Calculate weighted average score
double weightedSum = 0;
double totalWeight = 0;
for (ThreatIntelligenceSource source : sources.values()) {
double weight = source.getConfidence() / 100.0;
double sourceScore = calculateSourceScore(source);
weightedSum += sourceScore * weight;
totalWeight += weight;
}
int overallScore = totalWeight > 0 ? (int) (weightedSum / totalWeight) : 0;
// Identify threat categories
List<ThreatCategory> threatCategories = identifyThreatCategories(sources);
// Build metadata
Map<String, Object> metadata = buildMetadata(sources);
return new IPReputation.Builder(ipAddress)
.overallScore(new ReputationScore(overallScore))
.sources(sources)
.threatCategories(threatCategories)
.metadata(metadata)
.build();
}
private double calculateSourceScore(ThreatIntelligenceSource source) {
Map<String, Object> data = source.getData();
// AbuseIPDB scoring
if (source.getName().equals("AbuseIPDB")) {
Integer abuseScore = (Integer) data.get("abuseConfidenceScore");
Integer totalReports = (Integer) data.get("totalReports");
if (abuseScore != null) {
// Boost score based on report volume
double reportBoost = Math.min(totalReports != null ? totalReports / 10.0 : 0, 20);
return Math.min(abuseScore + reportBoost, 100);
}
}
// VirusTotal scoring
else if (source.getName().equals("VirusTotal")) {
Integer malicious = (Integer) data.get("malicious");
Integer suspicious = (Integer) data.get("suspicious");
Integer totalEngines = (Integer) data.get("totalEngines");
if (totalEngines != null && totalEngines > 0) {
double threatRatio = (double) (malicious + suspicious) / totalEngines;
return threatRatio * 100;
}
}
// IPQualityScore scoring
else if (source.getName().equals("IPQualityScore")) {
Integer fraudScore = (Integer) data.get("fraudScore");
Boolean proxy = (Boolean) data.get("proxy");
Boolean vpn = (Boolean) data.get("vpn");
Boolean tor = (Boolean) data.get("tor");
Boolean bot = (Boolean) data.get("bot");
if (fraudScore != null) {
double baseScore = fraudScore;
// Apply multipliers for specific threats
if (Boolean.TRUE.equals(tor)) baseScore *= 1.3;

Leave a Reply

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


Macro Nepal Helper