Skip to content
javahacks.dev
Security

Fix PKIX Path Building Failed in Java Without Disabling TLS

Fix the Java PKIX path building failed TLS error by finding the missing CA, importing it into a truststore and never disabling verification.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the OpenJDK, Spring Security, Docker, Apache Maven and Gradle logos.

A call to an HTTPS service fails in Java and works in a browser:

Text
javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Java validates a server certificate by building a chain from it up to a root certificate authority in its truststore (by default the cacerts file in the JDK). "PKIX" is the standard for that validation. The message means the chain could not be completed. The browser worked because it uses the operating system's trust store and fetches missing intermediates, and Java uses its own store. The general security habits are in Java security basics.

Step 1: see what the server sends

Shell
openssl s_client -connect api.example.test:443 -servername api.example.test -showcerts

Look at the Certificate chain section and the line Verify return code. Typical findings:

FindingMeaning
self-signed certificateThe server uses a certificate it signed itself
unable to get local issuer certificateThe chain is incomplete or the root is unknown to OpenSSL
Issuer is your company's nameA private CA, or a TLS-inspecting proxy
Only one certificate in the chainThe server omits its intermediate certificate

For Java's own view, run with -Djavax.net.debug=ssl:handshake and read which certificate failed validation.

Cause 1: a private or self-signed CA

Internal services often use a company CA. Java does not trust it unless you tell it. Get the CA certificate (not the server certificate) from your security team, as a PEM file, and import it into a truststore.

Cause 2: a corporate proxy re-signs traffic

A TLS-inspecting proxy terminates the connection and presents a certificate signed by the company's CA for every site. Your browser trusts it because IT installed the CA in the operating system. Java does not. The issuer in the chain shows the company's name for a public site such as github.com, which is the giveaway. The fix is the same: import the proxy's root CA.

Cause 3: the server omits the intermediate

A correct server sends its certificate and the intermediates. If it sends only its own, Java cannot build the path, while browsers that cache or fetch intermediates succeed. Fix the server to send the full chain; as a stopgap, import the intermediate on the client.

The fix: a truststore that includes the CA

Create an application-specific truststore, so you do not change the JDK:

Shell
keytool -importcert -alias corp-ca -file corp-ca.pem \
  -keystore app-truststore.p12 -storetype PKCS12 -storepass change-me -noprompt

Then point the JVM at it:

Shell
java -Djavax.net.ssl.trustStore=/etc/app/app-truststore.p12 \
     -Djavax.net.ssl.trustStorePassword=change-me -jar app.jar

This replaces the default truststore for the process, so the file must also contain public CAs your application needs. Copy the JDK's cacerts (default password changeit) and add to the copy. In Spring Boot 3.1 and later, an SSL bundle scopes the truststore to a client:

application.propertiesproperties
spring.ssl.bundle.jks.internal.truststore.location=file:/etc/app/app-truststore.p12
spring.ssl.bundle.jks.internal.truststore.password=${TRUSTSTORE_PASSWORD}
spring.ssl.bundle.jks.internal.truststore.type=PKCS12

and the RestClient or WebClient uses the bundle by name, without touching other connections. Import into the JDK's own cacerts only for a developer machine, and know that a JDK update replaces the file.

In containers, add the CA to the image at build time; do not rely on a manual step. The container side is in building a small Docker image for Java.

What not to do

java
// Do not do this
TrustManager[] trustAll = { new X509TrustManager() { /* accepts everything */ } };
HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);

Disabling verification makes the connection encrypted and unauthenticated, so anyone on the network path can impersonate the server. It tends to survive from a quick test into production. Search for it in code reviews.

Other messages in the same family

No subject alternative names matching IP address means the certificate does not cover the host name you used (connect with the name on the certificate). certificate_unknown from the other side means a client certificate problem in mutual TLS. SSLHandshakeException: Received fatal alert: protocol_version is a TLS version mismatch.

Inspect the chain from Java itself

openssl shows what a server sends, and what matters is what Java sees. This program connects, completes the handshake with a trust-everything manager only to read the chain, and prints each certificate. Use it for diagnosis only, and never copy the trust manager into an application:

java
import javax.net.ssl.*;
import java.security.cert.X509Certificate;

public class ChainDump {

    public static void main(String[] args) throws Exception {
        String host = args[0];
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] c, String a) {}
            public void checkServerTrusted(X509Certificate[] c, String a) {}
            public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
        } }, null);

        try (SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket(host, 443)) {
            socket.startHandshake();
            var chain = socket.getSession().getPeerCertificates();
            for (int i = 0; i < chain.length; i++) {
                X509Certificate cert = (X509Certificate) chain[i];
                System.out.printf("[%d] subject=%s%n    issuer=%s%n    expires=%s%n",
                    i, cert.getSubjectX500Principal(), cert.getIssuerX500Principal(), cert.getNotAfter());
            }
        }
    }
}
Shell
java ChainDump.java api.example.test

Read the output from the top. Certificate 0 is the server's. If there is only one entry, the server omitted its intermediate. If the last issuer is not a root your truststore holds, that is the missing link. If the issuer of certificate 0 carries your company's name for a public site, a proxy is re-signing traffic, which changes the fix from "fix the server" to "trust the corporate CA".

Build a client that trusts one extra CA

For a single client that must talk to an internal service, load the CA into a dedicated SSLContext. Everything else in the process keeps the default trust:

java
static SSLContext contextTrusting(Path caPemFile) throws Exception {
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate ca;
    try (InputStream in = Files.newInputStream(caPemFile)) {
        ca = (X509Certificate) factory.generateCertificate(in);
    }

    KeyStore defaults = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream in = Files.newInputStream(Path.of(System.getProperty("java.home"), "lib", "security", "cacerts"))) {
        defaults.load(in, "changeit".toCharArray());
    }
    defaults.setCertificateEntry("corp-ca", ca);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(defaults);

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
}

HttpClient client = HttpClient.newBuilder()
    .sslContext(contextTrusting(Path.of("/etc/app/corp-ca.pem")))
    .build();

The store starts from the JDK defaults and adds one certificate, so public sites still validate. That is the difference between this and -Djavax.net.ssl.trustStore, which replaces the default and breaks every public call unless the file contains the public roots as well.

The Spring Boot way, scoped to one client

With an SSL bundle, the same intent is configuration, and the HTTP client picks the bundle by name:

YAML
spring:
  ssl:
    bundle:
      pem:
        internal:
          truststore:
            certificate: "file:/etc/app/corp-ca.pem"
java
@Bean
RestClient internalApi(RestClient.Builder builder, SslBundles bundles) {
    return builder
        .baseUrl("https://billing.internal")
        .apply(ssl -> ssl.sslBundle(bundles.getBundle("internal")))
        .build();
}

Check the Spring Boot reference for the exact builder method on your version, since the way a bundle is attached to a client differs between RestClient, WebClient and the Apache and Jetty request factories. The configuration side is stable: a named bundle with a PEM truststore, no password and no JKS file to maintain.

In the image, not by hand

Importing a CA into the JDK's store by hand on a running container is a fix that disappears with the next pod. Do it in the Dockerfile, where it is reviewed and repeated:

Dockerfile
FROM eclipse-temurin:25-jre
COPY corp-ca.pem /tmp/corp-ca.pem
RUN keytool -importcert -cacerts -storepass changeit -noprompt \
        -alias corp-ca -file /tmp/corp-ca.pem \
 && rm /tmp/corp-ca.pem

The -cacerts option points keytool at the running JDK's default store without needing its path. A new base image rebuild reapplies the step, so a JDK update does not drop your CA. Keep the PEM file in the repository only if it is a public CA certificate, which carries no secret, and fetch it from your internal artifact store otherwise.

Expiry and rotation

The quiet version of this error arrives on a certain date when a certificate expires. Print the expiry of what you trust and of what you call, and put both dates in monitoring:

Shell
keytool -list -v -cacerts -storepass changeit -alias corp-ca | grep -E "Valid from|Until"
echo | openssl s_client -connect billing.internal:443 -servername billing.internal 2>/dev/null \
  | openssl x509 -noout -enddate

A CA certificate often lasts for years, so nobody remembers it, and the day it expires every service that trusts it fails together. Add a check that alerts at 60 and 30 days, and keep the rotation procedure next to it: add the new CA alongside the old one, roll the services, and remove the old one only after the last server presents a chain that uses the new one.

Where this does not apply

For certificates that expired, the message is NotAfter in the debug output; renew the certificate, not the truststore. The Java PKI programmer's guide and the [keytool reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/keytool.html) are the primary sources, and Spring Boot's SSL bundle documentation covers the Spring side. For the next step in a TLS problem that is not about trust, see HikariCP and connection failures, and for the Docker side of installing a CA, writing a Dockerfile for Java.

Also inDevOps
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.