import java.util.HashMap;
import java.util.Map;
public class HeaderAnomalyChecker {
private static final Map<String, Integer> HARDCODED_LIMITS = new HashMap<>();
static {
// Define hardcoded limits for header values
HARDCODED_LIMITS.put("User-Agent", 200); // Max length of User-Agent
HARDCODED_LIMITS.put("Content-Length", 10000); //Max Content-Length
HARDCODED_LIMITS.put("Referer", 255); //Max length of Referer
HARDCODED_LIMITS.put("Cookie", 8000); //Max length of Cookie
}
public static boolean checkHeaderAnomalies(Map<String, String> headers) {
boolean anomalyFound = false;
if (headers == null) {
return true; // Consider null headers as an anomaly
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
String headerName = entry.getKey();
String headerValue = entry.getValue();
if (headerValue != null) {
if (headerName.equals("User-Agent") && headerValue.length() > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
System.out.println("Anomaly: User-Agent length exceeds limit (" + headerValue.length() + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
anomalyFound = true;
} else if (headerName.equals("Content-Length") && Integer.parseInt(headerValue) > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
System.out.println("Anomaly: Content-Length exceeds limit (" + Integer.parseInt(headerValue) + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
anomalyFound = true;
} else if (headerName.equals("Referer") && headerValue.length() > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
System.out.println("Anomaly: Referer length exceeds limit (" + headerValue.length() + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
anomalyFound = true;
} else if (headerName.equals("Cookie") && headerValue.length() > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
System.out.println("Anomaly: Cookie length exceeds limit (" + headerValue.length() + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
anomalyFound = true;
}
}
}
return anomalyFound;
}
public static void main(String[] args) {
// Example Usage
Map<String, String> headers1 = new HashMap<>();
headers1.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
headers1.put("Content-Length", "5000");
headers1.put("Referer", "https://example.com");
Map<String, String> headers2 = new HashMap<>();
headers2.put("User-Agent", "TooLongUserAgentStringThatExceedsTheLimit");
headers2.put("Content-Length", "1000");
System.out.println("Headers 1 Anomaly Check: " + checkHeaderAnomalies(headers1));
System.out.println("Headers 2 Anomaly Check: " + checkHeaderAnomalies(headers2));
}
}
Add your comment