1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class HeaderAnomalyChecker {
  4. private static final Map<String, Integer> HARDCODED_LIMITS = new HashMap<>();
  5. static {
  6. // Define hardcoded limits for header values
  7. HARDCODED_LIMITS.put("User-Agent", 200); // Max length of User-Agent
  8. HARDCODED_LIMITS.put("Content-Length", 10000); //Max Content-Length
  9. HARDCODED_LIMITS.put("Referer", 255); //Max length of Referer
  10. HARDCODED_LIMITS.put("Cookie", 8000); //Max length of Cookie
  11. }
  12. public static boolean checkHeaderAnomalies(Map<String, String> headers) {
  13. boolean anomalyFound = false;
  14. if (headers == null) {
  15. return true; // Consider null headers as an anomaly
  16. }
  17. for (Map.Entry<String, String> entry : headers.entrySet()) {
  18. String headerName = entry.getKey();
  19. String headerValue = entry.getValue();
  20. if (headerValue != null) {
  21. if (headerName.equals("User-Agent") && headerValue.length() > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
  22. System.out.println("Anomaly: User-Agent length exceeds limit (" + headerValue.length() + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
  23. anomalyFound = true;
  24. } else if (headerName.equals("Content-Length") && Integer.parseInt(headerValue) > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
  25. System.out.println("Anomaly: Content-Length exceeds limit (" + Integer.parseInt(headerValue) + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
  26. anomalyFound = true;
  27. } else if (headerName.equals("Referer") && headerValue.length() > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
  28. System.out.println("Anomaly: Referer length exceeds limit (" + headerValue.length() + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
  29. anomalyFound = true;
  30. } else if (headerName.equals("Cookie") && headerValue.length() > HARDCODED_LIMITS.getOrDefault(headerName, 0)) {
  31. System.out.println("Anomaly: Cookie length exceeds limit (" + headerValue.length() + "> " + HARDCODED_LIMITS.getOrDefault(headerName, 0) + ")");
  32. anomalyFound = true;
  33. }
  34. }
  35. }
  36. return anomalyFound;
  37. }
  38. public static void main(String[] args) {
  39. // Example Usage
  40. Map<String, String> headers1 = new HashMap<>();
  41. 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");
  42. headers1.put("Content-Length", "5000");
  43. headers1.put("Referer", "https://example.com");
  44. Map<String, String> headers2 = new HashMap<>();
  45. headers2.put("User-Agent", "TooLongUserAgentStringThatExceedsTheLimit");
  46. headers2.put("Content-Length", "1000");
  47. System.out.println("Headers 1 Anomaly Check: " + checkHeaderAnomalies(headers1));
  48. System.out.println("Headers 2 Anomaly Check: " + checkHeaderAnomalies(headers2));
  49. }
  50. }

Add your comment