A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.
Java application-securityappsecbug-bountyburp-alternativeburp-suitedasthttp-proxyinfosecintercepting-proxyjavaowaspowasp-zappenetration-testingpentestingsecuritysecurity-toolsvulnerability-scannerweb-application-securityweb-security
package opensuite.core;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Settings > Network, as the HTTP client applies it: name resolution, the
* SOCKS proxy, and how TLS is negotiated and trusted. Every connection the
* suite opens asks here, so a change takes effect on the next connection.
* Unbound (as in most tests), everything is at its default.
*/
public final class NetworkConfig {
public static final String DNS_MODE = "dns.mode", DNS_OVERRIDES = "dns.overrides", DNS_TIMEOUT = "timeout.dns",
DNS_FAILED = "timeout.dnsFailed";
public static final String SOCKS_ON = "socks.enabled", SOCKS_HOST = "socks.host", SOCKS_PORT = "socks.port",
SOCKS_USER = "socks.user", SOCKS_PASSWORD = "socks.password", SOCKS_DNS = "socks.dns", SOCKS_BYPASS = "socks.bypass";
public static final String TLS_VERIFY = "tls.verifyUpstream", TLS_PROTOCOLS = "tls.protocols",
TLS_CUSTOM_PROTOCOLS = "tls.custom.protocols", TLS_CUSTOM_CIPHERS = "tls.custom.ciphers",
TLS_NO_RESUME = "tls.noSessionResume", TLS_RENEGOTIATION = "tls.unsafeRenegotiation",
TLS_CLIENT = "tls.client.rows", TLS_SERVER = "tls.server.rows", TLS_CA = "tls.ca.rows",
TLS_UNBLOCK = "tls.java.unblockAlgorithms", TLS_NO_SNI = "tls.java.disableSni";
private static volatile Settings settings;
private NetworkConfig() { }
/** The settings the suite runs on; from here on connections follow them. */
public static void bind(Settings s) {
settings = s;
CONTEXTS.clear();
applyRuntime(s);
HttpClient.defaultKeepAlive = s != null && s.getBool("http.keepAlive", false);
if (s != null) s.addListener(key -> {
if (key == null || key.equals("http.keepAlive")) HttpClient.defaultKeepAlive = s.getBool("http.keepAlive", false);
if (key == null || key.startsWith("tls.")) CONTEXTS.clear();
if (key == null || key.equals(DNS_FAILED)) applyRuntime(s);
});
}
/**
* The Java TLS settings, which the runtime reads once: call before the
* first TLS connection of the process. They are the ones marked "requires restart".
*/
public static void applyStartup(Settings s) {
if (s.getBool(TLS_UNBLOCK, true)) {
// Old servers are exactly what gets tested; the suite must still be able to talk to them.
java.security.Security.setProperty("jdk.tls.disabledAlgorithms", "");
}
if (s.getBool(TLS_NO_SNI, false)) System.setProperty("jsse.enableSNIExtension", "false");
if (s.getBool(TLS_RENEGOTIATION, false)) {
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");
}
applyRuntime(s);
}
private static void applyRuntime(Settings s) {
if (s == null) return;
// How long a failed lookup is remembered, in seconds; 0 asks again every time.
int failed = Math.max(0, s.getInt(DNS_FAILED, 60));
try { java.security.Security.setProperty("networkaddress.cache.negative.ttl", String.valueOf(failed)); } catch (RuntimeException ignored) { }
}
// ---- names ----
/** The address a hostname is connected at: an override if there is one, else DNS with the preferred family first. */
public static InetAddress resolve(String host) throws UnknownHostException {
Settings s = settings;
if (s == null || host == null) return InetAddress.getByName(host);
String fixed = override(s.get(DNS_OVERRIDES, ""), host);
if (fixed != null) {
// The name is kept with the address, so TLS still names the host asked for.
return InetAddress.getByAddress(host, InetAddress.getByName(fixed).getAddress());
}
return prefer(lookup(host, s.getInt(DNS_TIMEOUT, 300)), s.get(DNS_MODE, "system"));
}
/** The IP an override row gives a hostname, or null. Rows are: enabled, hostname, IP address. */
static String override(String rows, String host) {
for (String line : rows.split("\n")) {
String[] c = line.split("\t", -1);
if (c.length < 3 || "false".equals(c[0]) || c[2].isBlank()) continue;
if (c[1].trim().equalsIgnoreCase(host)) {
// Only a literal address is accepted, so an override never causes a lookup of its own.
String ip = c[2].trim();
if (ip.matches("[0-9.]+") || (ip.contains(":") && ip.matches("[0-9a-fA-F:.%\\[\\]]+"))) return ip;
}
}
return null;
}
/** The first address of the preferred family, or the first of all when there is none of it. */
static InetAddress prefer(InetAddress[] all, String mode) {
if (all == null || all.length == 0) return null;
for (InetAddress a : all) {
if ("ipv4".equals(mode) && a instanceof Inet4Address) return a;
if ("ipv6".equals(mode) && a instanceof Inet6Address) return a;
}
return all[0];
}
private static InetAddress[] lookup(String host, int timeoutSeconds) throws UnknownHostException {
if (timeoutSeconds <= 0) return InetAddress.getAllByName(host);
java.util.concurrent.CompletableFuture<InetAddress[]> f = new java.util.concurrent.CompletableFuture<>();
Thread t = new Thread(() -> {
try { f.complete(InetAddress.getAllByName(host)); } catch (Throwable e) { f.completeExceptionally(e); }
}, "dns-lookup");
t.setDaemon(true);
t.start();
try {
return f.get(timeoutSeconds, java.util.concurrent.TimeUnit.SECONDS);
} catch (java.util.concurrent.ExecutionException e) {
if (e.getCause() instanceof UnknownHostException u) throw u;
throw new UnknownHostException(host + ": " + e.getCause());
} catch (java.util.concurrent.TimeoutException e) {
throw new UnknownHostException(host + ": name resolution timed out after " + timeoutSeconds + " s");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UnknownHostException(host + ": interrupted");
}
}
// ---- SOCKS ----
/** The SOCKS proxy a connection to this host goes through, or null. */
public static UpstreamProxy socksFor(String host) {
Settings s = settings;
if (s == null || !s.getBool(SOCKS_ON, false)) return null;
String proxyHost = s.get(SOCKS_HOST, "").trim();
if (proxyHost.isEmpty()) return null;
for (String line : s.get(SOCKS_BYPASS, "").split("\n")) {
String pattern = line.split("\t", -1)[0].trim();
if (!pattern.isEmpty() && hostMatches(pattern, host)) return null;
}
UpstreamProxy p = new UpstreamProxy();
p.type = UpstreamProxy.Type.SOCKS;
p.host = proxyHost;
p.port = s.getInt(SOCKS_PORT, 1080);
p.user = s.get(SOCKS_USER, "");
p.pass = s.get(SOCKS_PASSWORD, "");
return p;
}
/** Whether names are left to the SOCKS proxy to resolve. */
public static boolean socksResolves() {
Settings s = settings;
return s == null || s.getBool(SOCKS_DNS, true);
}
/** The name and password the SOCKS proxy at this address is given, or null. */
public static java.net.PasswordAuthentication socksLogin(String proxyHost) {
Settings s = settings;
if (s == null || !s.getBool(SOCKS_ON, false) || s.get(SOCKS_USER, "").isEmpty()) return null;
if (proxyHost != null && !proxyHost.equalsIgnoreCase(s.get(SOCKS_HOST, "").trim())) return null;
return new java.net.PasswordAuthentication(s.get(SOCKS_USER, ""), s.get(SOCKS_PASSWORD, "").toCharArray());
}
/** A host against a pattern: the name itself, or with * for any run of characters. */
public static boolean hostMatches(String pattern, String host) {
if (pattern == null || host == null) return false;
String p = pattern.trim().toLowerCase(Locale.ROOT), h = host.toLowerCase(Locale.ROOT);
if (p.isEmpty() || p.equals("*")) return true;
if (!p.contains("*")) return p.equals(h);
StringBuilder rx = new StringBuilder();
for (String piece : p.split("\\*", -1)) {
if (rx.length() > 0) rx.append(".*");
rx.append(java.util.regex.Pattern.quote(piece));
}
return h.matches(rx.toString());
}
// ---- HTTP ----
private static volatile java.util.function.BiPredicate<HttpService, String> streamTest;
/** How the suite tells that a URL is listed under Streaming responses. */
/** Settings > Network > HTTP > HTTP/2: "Default to HTTP/2 if the server supports it". */
public static final String HTTP2_DEFAULT = "http.http2";
/** The protocol a tool starts a new request on: HTTP/2 only when the setting is on, the target is HTTPS and it offers HTTP/2. */
public static HttpMode defaultMode(boolean setting, boolean secure, boolean serverSpeaksHttp2) {
return setting && secure && serverSpeaksHttp2 ? HttpMode.HTTP_2 : HttpMode.HTTP_1;
}
/** The same for a target, asking the server once (the answer is kept for the session). */
public static HttpMode defaultMode(HttpService svc) {
Settings s = settings;
boolean on = s == null || s.getBool(HTTP2_DEFAULT, true);
if (!on || svc == null || !svc.secure()) return HttpMode.HTTP_1;
return defaultMode(true, true, speaksHttp2(svc));
}
private static final java.util.Map<String, Boolean> HTTP2_KNOWN = new java.util.concurrent.ConcurrentHashMap<>();
private static volatile java.util.function.Predicate<HttpService> http2Probe = NetworkConfig::probeHttp2;
/** For tests: stand in for the handshake that asks a server whether it speaks HTTP/2. */
public static void setHttp2Probe(java.util.function.Predicate<HttpService> probe) {
http2Probe = probe == null ? NetworkConfig::probeHttp2 : probe;
HTTP2_KNOWN.clear();
}
/** Whether the server at that address chooses HTTP/2 when offered it. */
public static boolean speaksHttp2(HttpService svc) {
if (svc == null || !svc.secure()) return false;
return HTTP2_KNOWN.computeIfAbsent(svc.host().toLowerCase(java.util.Locale.ROOT) + ":" + svc.port(), k -> {
try { return http2Probe.test(svc); } catch (RuntimeException e) { return false; }
});
}
/** One TLS handshake offering h2 and http/1.1. A server that cannot be reached this way counts as HTTP/1. */
private static boolean probeHttp2(HttpService svc) {
try (javax.net.ssl.SSLSocket socket = (javax.net.ssl.SSLSocket) context(svc.host()).getSocketFactory().createSocket()) {
socket.connect(new java.net.InetSocketAddress(resolve(svc.host()), svc.port()), 5000);
socket.setSoTimeout(5000);
javax.net.ssl.SSLParameters p = socket.getSSLParameters();
p.setApplicationProtocols(new String[]{ "h2", "http/1.1" });
p.setServerNames(java.util.List.of(new javax.net.ssl.SNIHostName(svc.host())));
socket.setSSLParameters(p);
socket.startHandshake();
return "h2".equals(socket.getApplicationProtocol());
} catch (Exception e) {
return false;
}
}
public static void setStreamTest(java.util.function.BiPredicate<HttpService, String> test) { streamTest = test; }
/** Whether the URL is one of those listed as returning a response that does not end. */
public static boolean streams(HttpService svc, String path) {
java.util.function.BiPredicate<HttpService, String> t = streamTest;
try { return t != null && settings != null && t.test(svc, path); } catch (RuntimeException e) { return false; }
}
public static boolean eventStreamsStream() { Settings s = settings; return s == null || s.getBool("http.streaming.eventStream", true); }
/** "Strip chunked encoding metadata in streaming responses": off keeps a stream's chunk sizes as the server sent them. */
public static boolean stripsChunked() { Settings s = settings; return s == null || s.getBool("http.streaming.stripChunked", true); }
public static boolean storesStreams() { Settings s = settings; return s == null || s.getBool("http.streaming.store", true); }
public static boolean understands100() { Settings s = settings; return s == null || s.getBool("http.100.understand", true); }
public static boolean removes100() { Settings s = settings; return s != null && s.getBool("http.100.remove", false); }
/** How long an open-ended response may go quiet before it is taken as finished, in milliseconds; 0 for the socket's own timeout. */
public static int openEndedMs() {
Settings s = settings;
if (s == null) return 0;
long seconds = s.getInt("timeout.openEnded", 10);
return seconds <= 0 ? 0 : (int) Math.min(Integer.MAX_VALUE, seconds * 1000L);
}
private static final java.util.regex.Pattern REFRESH = java.util.regex.Pattern.compile("^\\s*\\d+\\s*[;,]\\s*(?:url\\s*=\\s*)?[\"']?([^\"'>\\s][^\"'>]*)", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final String QUOTED = "(?:\"([^\"]+)\"|'([^']+)')";
private static final java.util.regex.Pattern META = java.util.regex.Pattern.compile(
"<meta[^>]+http-equiv\\s*=\\s*[\"']?refresh[\"']?[^>]*content\\s*=\\s*" + QUOTED, java.util.regex.Pattern.CASE_INSENSITIVE);
private static final java.util.regex.Pattern META_REVERSED = java.util.regex.Pattern.compile(
"<meta[^>]+content\\s*=\\s*" + QUOTED + "[^>]*http-equiv\\s*=\\s*[\"']?refresh", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final java.util.regex.Pattern SCRIPT = java.util.regex.Pattern.compile(
"(?:window\\.|document\\.|top\\.|self\\.)?location(?:\\.href)?\\s*=\\s*[\"']([^\"']+)[\"']"
+ "|location\\.(?:replace|assign)\\(\\s*[\"']([^\"']+)[\"']\\s*\\)");
/**
* Where a response redirects to, by the kinds of redirection allowed
* (Settings > Network > HTTP > Allowed redirect types), or null.
*/
public static String redirectTarget(HttpMessage response) {
Settings s = settings;
boolean status = s == null || s.getBool("http.redirect.3xx", true);
boolean any = s != null && s.getBool("http.redirect.anyLocation", false);
boolean refresh = s != null && s.getBool("http.redirect.refreshHeader", true);
boolean meta = s != null && s.getBool("http.redirect.metaRefresh", true);
boolean script = s != null && s.getBool("http.redirect.javascript", false);
if (response == null) return null;
int sc = response.statusCode();
String location = response.header("Location");
if (location != null && !location.isBlank() && (any || (status && sc >= 300 && sc <= 399))) return location.trim();
if (refresh) {
String h = response.header("Refresh");
if (h != null) {
java.util.regex.Matcher m = REFRESH.matcher(h);
if (m.find()) return m.group(1).trim();
}
}
if (!meta && !script) return null;
String type = response.header("Content-Type");
if (type != null && !type.toLowerCase(Locale.ROOT).contains("html")) return null;
byte[] body = response.body();
if (body == null || body.length == 0) return null;
// Only the start of the page is searched: a redirecting page says so at once.
String text = new String(body, 0, Math.min(body.length, 64 * 1024), java.nio.charset.StandardCharsets.ISO_8859_1);
if (meta) {
for (java.util.regex.Pattern p : new java.util.regex.Pattern[]{ META, META_REVERSED }) {
java.util.regex.Matcher m = p.matcher(text);
if (m.find()) {
String content = m.group(1) != null ? m.group(1) : m.group(2);
java.util.regex.Matcher r = REFRESH.matcher(content.replace("&", "&"));
if (r.find()) return r.group(1).trim();
}
}
}
if (script) {
java.util.regex.Matcher m = SCRIPT.matcher(text);
if (m.find()) return (m.group(1) != null ? m.group(1) : m.group(2)).trim();
}
return null;
}
// ---- TLS ----
private static final Map<String, SSLContext> CONTEXTS = new ConcurrentHashMap<>();
private static final TrustManager TRUST_ALL = new X509ExtendedTrustManager() {
public void checkClientTrusted(X509Certificate[] c, String a) {}
public void checkServerTrusted(X509Certificate[] c, String a) {}
public void checkClientTrusted(X509Certificate[] c, String a, Socket s) {}
public void checkServerTrusted(X509Certificate[] c, String a, Socket s) {}
public void checkClientTrusted(X509Certificate[] c, String a, SSLEngine e) {}
public void checkServerTrusted(X509Certificate[] c, String a, SSLEngine e) {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
};
/** Whether server certificates are checked (Verify upstream TLS). */
public static boolean verifies() {
Settings s = settings;
return s != null && s.getBool(TLS_VERIFY, false);
}
/** Whether connections to this host need a TLS context of their own: verified, or with a client certificate. */
public static boolean special(String host) {
Settings s = settings;
return s != null && (verifies() || clientRow(s.get(TLS_CLIENT, ""), host) != null);
}
/**
* The TLS context for connections to a host: trusting every certificate
* unless verification is on, and offering the client certificate set for
* the host, if any.
*/
public static SSLContext context(String host) throws Exception {
Settings s = settings;
String[] client = s == null ? null : clientRow(s.get(TLS_CLIENT, ""), host);
String key = (verifies() ? "v" : "t") + "|" + (client == null ? "" : String.join("\t", client));
SSLContext cached = CONTEXTS.get(key);
if (cached != null) return cached;
KeyManager[] keys = null;
if (client != null) {
try {
keys = keyManagers(client[8], client[9]);
} catch (Exception e) {
// A certificate that cannot be read must not stop the connection being tried without it.
Debug.error("client TLS certificate for " + host + " could not be loaded from " + client[8], e);
}
}
TrustManager[] trust = verifies() ? trustManagers(s.get(TLS_CA, "")) : new TrustManager[]{ TRUST_ALL };
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keys, trust, new java.security.SecureRandom());
CONTEXTS.put(key, ctx);
return ctx;
}
/**
* The first enabled client certificate row whose host matches, or null. Rows
* are: enabled, host, type, alias, subject, issuer, intermediate CA, key,
* then the file and its password.
*/
static String[] clientRow(String rows, String host) {
for (String line : rows.split("\n")) {
String[] c = line.split("\t", -1);
if (c.length < 10 || "false".equals(c[0]) || c[8].isBlank()) continue;
if (hostMatches(c[1], host)) return c;
}
return null;
}
private static KeyManager[] keyManagers(String file, String password) throws Exception {
KeyStore ks = KeyStore.getInstance("PKCS12");
char[] pw = password == null ? new char[0] : password.toCharArray();
try (InputStream in = new FileInputStream(file)) { ks.load(in, pw); }
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, pw);
return kmf.getKeyManagers();
}
/** The runtime's own authorities and the custom ones. Rows are: name, then the certificate file. */
private static TrustManager[] trustManagers(String caRows) throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
TrustManagerFactory system = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
system.init((KeyStore) null);
int n = 0;
for (TrustManager tm : system.getTrustManagers()) {
if (tm instanceof javax.net.ssl.X509TrustManager x) {
for (X509Certificate c : x.getAcceptedIssuers()) ks.setCertificateEntry("system-" + n++, c);
}
}
for (String line : caRows.split("\n")) {
String[] c = line.split("\t", -1);
if (c.length < 2 || c[1].isBlank()) continue;
try (InputStream in = new FileInputStream(c[1])) {
for (Certificate cert : CertificateFactory.getInstance("X.509").generateCertificates(in)) ks.setCertificateEntry("custom-" + n++, cert);
} catch (Exception e) {
Debug.error("custom CA certificate could not be read from " + c[1], e);
}
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
return tmf.getTrustManagers();
}
/** Set a socket up before its handshake: the protocols and ciphers chosen, and the name check when verifying. */
public static void prepare(SSLSocket socket) {
Settings s = settings;
if (s == null) return;
try {
String mode = s.get(TLS_PROTOCOLS, "all");
if ("all".equals(mode)) {
socket.setEnabledProtocols(usable(socket.getSupportedProtocols(), null));
socket.setEnabledCipherSuites(usable(socket.getSupportedCipherSuites(), null));
} else if ("custom".equals(mode)) {
String[] p = usable(socket.getSupportedProtocols(), s.get(TLS_CUSTOM_PROTOCOLS, ""));
String[] c = usable(socket.getSupportedCipherSuites(), s.get(TLS_CUSTOM_CIPHERS, ""));
if (p.length > 0) socket.setEnabledProtocols(p);
if (c.length > 0) socket.setEnabledCipherSuites(c);
}
if (verifies()) {
SSLParameters p = socket.getSSLParameters();
p.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(p);
}
} catch (RuntimeException e) {
Debug.error("TLS negotiation settings could not be applied", e);
}
}
/** Those of the supported names that were chosen (all of them when nothing is said), never the SSLv2 hello or signalling suites. */
static String[] usable(String[] supported, String chosen) {
Set<String> want = null;
if (chosen != null && !chosen.isBlank()) {
want = new LinkedHashSet<>();
for (String c : chosen.split(",")) if (!c.isBlank()) want.add(c.trim());
}
List<String> out = new ArrayList<>();
for (String name : supported) {
if (name.equals("SSLv2Hello") || name.contains("_SCSV")) continue;
if (chosen != null && (want == null || !want.contains(name))) continue;
out.add(name);
}
return out.toArray(new String[0]);
}
/** After the handshake: note the certificate the server showed, and drop the session if it is not to be resumed. */
public static void handshaken(SSLSocket socket, String host) {
Settings s = settings;
if (s == null) return;
try {
Certificate[] chain = socket.getSession().getPeerCertificates();
if (chain.length > 0 && chain[0] instanceof X509Certificate x) remember(s, host, x);
} catch (Exception ignored) { }
if (s.getBool(TLS_NO_RESUME, false)) {
try { socket.getSession().invalidate(); } catch (RuntimeException ignored) { }
}
}
private static final Set<String> SEEN = ConcurrentHashMap.newKeySet();
/** Add a server certificate to the list of those seen, once. Rows are: host, name, issuer, then the certificate itself. */
static void remember(Settings s, String host, X509Certificate cert) throws Exception {
String der = java.util.Base64.getEncoder().encodeToString(cert.getEncoded());
if (!SEEN.add(host + "|" + der.hashCode())) return;
synchronized (SEEN) {
String rows = s.get(TLS_SERVER, "");
if (rows.contains("\t" + der)) return;
// Kept to a size that stays quick to store: the newest 500.
String[] lines = rows.isEmpty() ? new String[0] : rows.split("\n");
StringBuilder sb = new StringBuilder();
for (int i = Math.max(0, lines.length - 499); i < lines.length; i++) sb.append(lines[i]).append('\n');
sb.append(clean(host)).append('\t').append(clean(commonName(cert.getSubjectX500Principal().getName())))
.append('\t').append(clean(commonName(cert.getIssuerX500Principal().getName()))).append('\t').append(der).append('\n');
s.set(TLS_SERVER, sb.toString());
}
}
private static String clean(String s) { return s == null ? "" : s.replace('\t', ' ').replace('\n', ' '); }
/** The CN of a distinguished name, or the whole name when it has none. */
public static String commonName(String dn) {
if (dn == null) return "";
try {
for (javax.naming.ldap.Rdn r : new javax.naming.ldap.LdapName(dn).getRdns()) {
if ("CN".equalsIgnoreCase(r.getType())) return String.valueOf(r.getValue());
}
} catch (Exception ignored) { }
return dn;
}
/** The protocols and cipher suites this runtime can speak, for the custom lists. */
public static String[][] supported() {
try {
SSLParameters p = SSLContext.getDefault().getSupportedSSLParameters();
return new String[][] { usable(p.getProtocols(), null), usable(p.getCipherSuites(), null) };
} catch (Exception e) {
return new String[][] { new String[0], new String[0] };
}
}
/** Read a PKCS#12 file: its first key entry's alias, subject, issuer and whether a chain came with it. */
public static String[] describeClientCertificate(String file, String password) throws Exception {
KeyStore ks = KeyStore.getInstance("PKCS12");
try (InputStream in = new FileInputStream(file)) { ks.load(in, password == null ? new char[0] : password.toCharArray()); }
for (String alias : java.util.Collections.list(ks.aliases())) {
if (!ks.isKeyEntry(alias)) continue;
Certificate[] chain = ks.getCertificateChain(alias);
if (chain == null || chain.length == 0 || !(chain[0] instanceof X509Certificate x)) continue;
String intermediate = chain.length > 1 && chain[1] instanceof X509Certificate i ? commonName(i.getSubjectX500Principal().getName()) : "";
return new String[] { alias, commonName(x.getSubjectX500Principal().getName()), commonName(x.getIssuerX500Principal().getName()),
intermediate, x.getPublicKey().getAlgorithm() };
}
throw new java.security.KeyStoreException("The file contains no private key with a certificate.");
}
/** Whether the array holds the name; for the tests. */
static boolean has(String[] names, String name) { return Arrays.asList(names).contains(name); }
}