|
| 1 | +package com.wlanboy.javahttpclient.client; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | +import org.springframework.stereotype.Service; |
| 6 | + |
| 7 | +import javax.net.ssl.*; |
| 8 | +import java.net.URI; |
| 9 | +import java.security.SecureRandom; |
| 10 | +import java.security.cert.CertificateParsingException; |
| 11 | +import java.security.cert.X509Certificate; |
| 12 | +import java.time.Instant; |
| 13 | +import java.time.ZoneOffset; |
| 14 | +import java.time.format.DateTimeFormatter; |
| 15 | +import java.time.temporal.ChronoUnit; |
| 16 | +import java.util.*; |
| 17 | +import java.util.concurrent.atomic.AtomicReference; |
| 18 | + |
| 19 | +@Service |
| 20 | +public class TlsInspectorService { |
| 21 | + |
| 22 | + private static final Logger logger = LoggerFactory.getLogger(TlsInspectorService.class); |
| 23 | + private static final DateTimeFormatter ISO = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC); |
| 24 | + |
| 25 | + public Map<String, Object> inspect(String url) { |
| 26 | + Map<String, Object> result = new LinkedHashMap<>(); |
| 27 | + try { |
| 28 | + URI uri = URI.create(url); |
| 29 | + if (!"https".equalsIgnoreCase(uri.getScheme())) { |
| 30 | + result.put("error", "Kein HTTPS – TLS-Inspektion nicht möglich."); |
| 31 | + return result; |
| 32 | + } |
| 33 | + |
| 34 | + String host = uri.getHost(); |
| 35 | + int port = uri.getPort() != -1 ? uri.getPort() : 443; |
| 36 | + result.put("host", host); |
| 37 | + result.put("port", port); |
| 38 | + |
| 39 | + AtomicReference<X509Certificate[]> chainRef = new AtomicReference<>(); |
| 40 | + |
| 41 | + // TrustManager der alles akzeptiert, aber die Chain immer captured |
| 42 | + X509ExtendedTrustManager capturingTM = new X509ExtendedTrustManager() { |
| 43 | + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine e) { chainRef.set(chain); } |
| 44 | + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, java.net.Socket s) { chainRef.set(chain); } |
| 45 | + @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { chainRef.set(chain); } |
| 46 | + @Override public void checkClientTrusted(X509Certificate[] chain, String authType) {} |
| 47 | + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine e) {} |
| 48 | + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, java.net.Socket s) {} |
| 49 | + @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } |
| 50 | + }; |
| 51 | + |
| 52 | + SSLContext ctx = SSLContext.getInstance("TLS"); |
| 53 | + ctx.init(null, new TrustManager[]{capturingTM}, new SecureRandom()); |
| 54 | + SSLSocketFactory factory = ctx.getSocketFactory(); |
| 55 | + |
| 56 | + try (SSLSocket socket = (SSLSocket) factory.createSocket(host, port)) { |
| 57 | + socket.setSoTimeout(5000); |
| 58 | + |
| 59 | + // SNI setzen |
| 60 | + SSLParameters params = socket.getSSLParameters(); |
| 61 | + params.setServerNames(List.of(new SNIHostName(host))); |
| 62 | + socket.setSSLParameters(params); |
| 63 | + |
| 64 | + SSLSession session = socket.getSession(); // löst Handshake aus |
| 65 | + |
| 66 | + result.put("tlsVersion", session.getProtocol()); |
| 67 | + result.put("cipherSuite", session.getCipherSuite()); |
| 68 | + |
| 69 | + X509Certificate[] chain = chainRef.get(); |
| 70 | + if (chain != null && chain.length > 0) { |
| 71 | + String spiffe = extractSpiffe(chain[0]); |
| 72 | + result.put("isMtls", spiffe != null); |
| 73 | + if (spiffe != null) result.put("spiffeId", spiffe); |
| 74 | + result.put("chain", serializeChain(chain)); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + } catch (Exception e) { |
| 79 | + logger.warn("TLS-Inspektion fehlgeschlagen für {}: {}", url, e.getMessage()); |
| 80 | + result.put("error", e.getMessage()); |
| 81 | + } |
| 82 | + return result; |
| 83 | + } |
| 84 | + |
| 85 | + private List<Map<String, Object>> serializeChain(X509Certificate[] chain) { |
| 86 | + List<Map<String, Object>> list = new ArrayList<>(); |
| 87 | + for (int i = 0; i < chain.length; i++) { |
| 88 | + X509Certificate cert = chain[i]; |
| 89 | + Map<String, Object> entry = new LinkedHashMap<>(); |
| 90 | + entry.put("index", i); |
| 91 | + entry.put("type", i == 0 ? "leaf" : (i == chain.length - 1 ? "root" : "intermediate")); |
| 92 | + entry.put("subject", cert.getSubjectX500Principal().getName()); |
| 93 | + entry.put("issuer", cert.getIssuerX500Principal().getName()); |
| 94 | + entry.put("serial", cert.getSerialNumber().toString(16).toUpperCase()); |
| 95 | + entry.put("validFrom", ISO.format(cert.getNotBefore().toInstant())); |
| 96 | + entry.put("validTo", ISO.format(cert.getNotAfter().toInstant())); |
| 97 | + |
| 98 | + long daysLeft = ChronoUnit.DAYS.between(Instant.now(), cert.getNotAfter().toInstant()); |
| 99 | + entry.put("daysUntilExpiry", daysLeft); |
| 100 | + entry.put("expired", daysLeft < 0); |
| 101 | + |
| 102 | + List<String> sans = extractSans(cert); |
| 103 | + if (!sans.isEmpty()) entry.put("subjectAltNames", sans); |
| 104 | + |
| 105 | + list.add(entry); |
| 106 | + } |
| 107 | + return list; |
| 108 | + } |
| 109 | + |
| 110 | + private String extractSpiffe(X509Certificate cert) { |
| 111 | + List<String> sans = extractSans(cert); |
| 112 | + return sans.stream() |
| 113 | + .filter(s -> s.startsWith("URI:spiffe://")) |
| 114 | + .findFirst() |
| 115 | + .map(s -> s.substring(4)) // "URI:" prefix entfernen |
| 116 | + .orElse(null); |
| 117 | + } |
| 118 | + |
| 119 | + private List<String> extractSans(X509Certificate cert) { |
| 120 | + List<String> result = new ArrayList<>(); |
| 121 | + try { |
| 122 | + Collection<List<?>> sans = cert.getSubjectAlternativeNames(); |
| 123 | + if (sans == null) return result; |
| 124 | + for (List<?> san : sans) { |
| 125 | + int type = (Integer) san.get(0); |
| 126 | + String value = san.get(1).toString(); |
| 127 | + String prefix = switch (type) { |
| 128 | + case 0 -> "OtherName"; |
| 129 | + case 1 -> "Email"; |
| 130 | + case 2 -> "DNS"; |
| 131 | + case 4 -> "DirName"; |
| 132 | + case 6 -> "URI"; |
| 133 | + case 7 -> "IP"; |
| 134 | + default -> "Type" + type; |
| 135 | + }; |
| 136 | + result.add(prefix + ":" + value); |
| 137 | + } |
| 138 | + } catch (CertificateParsingException ignored) {} |
| 139 | + return result; |
| 140 | + } |
| 141 | +} |
0 commit comments