changeset 12728:25e1b15a5e71

8134708: Certpath validation fails to load certs and CRLs if AIA and CRLDP extensions point to LDAP resources Reviewed-by: mullan, coffeys
author asmotrak
date Wed, 09 Sep 2015 12:39:45 +0300
parents b8ceaba10dfe
children 3884ca98c792
files src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java test/sun/security/x509/URICertStore/ExtensionsWithLDAP.java test/sun/security/x509/URICertStore/META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor
diffstat 5 files changed, 270 insertions(+), 60 deletions(-) [+]
line wrap: on
line diff
--- a/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java	Wed Sep 09 04:02:59 2015 -0400
+++ b/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java	Wed Sep 09 12:39:45 2015 +0300
@@ -233,8 +233,7 @@
         }
         CertStore ucs = null;
         try {
-            ucs = URICertStore.getInstance
-                (new URICertStore.URICertStoreParameters(uri));
+            ucs = URICertStore.getInstance(new URICertStoreParameters(uri));
         } catch (InvalidAlgorithmParameterException |
                  NoSuchAlgorithmException e) {
             if (debug != null) {
--- a/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java	Wed Sep 09 04:02:59 2015 -0400
+++ b/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java	Wed Sep 09 12:39:45 2015 +0300
@@ -44,9 +44,7 @@
 import java.security.cert.CRLSelector;
 import java.security.cert.URICertStoreParameters;
 import java.security.cert.X509Certificate;
-import java.security.cert.X509CertSelector;
 import java.security.cert.X509CRL;
-import java.security.cert.X509CRLSelector;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -160,12 +158,11 @@
             throw new InvalidAlgorithmParameterException
                 ("params must be instanceof URICertStoreParameters");
         }
-        this.uri = ((URICertStoreParameters) params).uri;
+        this.uri = ((URICertStoreParameters) params).getURI();
         // if ldap URI, use an LDAPCertStore to fetch certs and CRLs
         if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
             ldap = true;
-            URICertStoreParameters lparams = new URICertStoreParameters(uri);
-            ldapCertStore = CertStore.getInstance("LDAP", lparams);
+            ldapCertStore = CertStore.getInstance("LDAP", params);
         }
         try {
             factory = CertificateFactory.getInstance("X.509");
@@ -183,7 +180,7 @@
     static synchronized CertStore getInstance(URICertStoreParameters params)
         throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
         if (debug != null) {
-            debug.println("CertStore URI:" + params.uri);
+            debug.println("CertStore URI:" + params.getURI());
         }
         CertStore ucs = certStoreCache.get(params);
         if (ucs == null) {
@@ -212,8 +209,7 @@
         }
         URI uri = ((URIName) gn).getURI();
         try {
-            return URICertStore.getInstance
-                (new URICertStore.URICertStoreParameters(uri));
+            return URICertStore.getInstance(new URICertStoreParameters(uri));
         } catch (Exception ex) {
             if (debug != null) {
                 debug.println("exception creating CertStore: " + ex);
@@ -421,40 +417,6 @@
     }
 
     /**
-     * CertStoreParameters for the URICertStore.
-     */
-    static class URICertStoreParameters implements CertStoreParameters {
-        private final URI uri;
-        private volatile int hashCode = 0;
-        URICertStoreParameters(URI uri) {
-            this.uri = uri;
-        }
-        @Override public boolean equals(Object obj) {
-            if (!(obj instanceof URICertStoreParameters)) {
-                return false;
-            }
-            URICertStoreParameters params = (URICertStoreParameters) obj;
-            return uri.equals(params.uri);
-        }
-        @Override public int hashCode() {
-            if (hashCode == 0) {
-                int result = 17;
-                result = 37*result + uri.hashCode();
-                hashCode = result;
-            }
-            return hashCode;
-        }
-        @Override public Object clone() {
-            try {
-                return super.clone();
-            } catch (CloneNotSupportedException e) {
-                /* Cannot happen */
-                throw new InternalError(e.toString(), e);
-            }
-        }
-    }
-
-    /**
      * This class allows the URICertStore to be accessed as a CertStore.
      */
     private static class UCS extends CertStore {
--- a/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Wed Sep 09 04:02:59 2015 -0400
+++ b/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Wed Sep 09 12:39:45 2015 +0300
@@ -25,18 +25,12 @@
 
 package sun.security.provider.certpath.ldap;
 
-import java.math.BigInteger;
 import java.net.URI;
+import java.security.*;
+import java.security.cert.*;
 import java.util.*;
-
-import java.security.*;
-import java.security.cert.Certificate;
-import java.security.cert.*;
-import javax.security.auth.x500.X500Principal;
-
 import sun.security.util.Cache;
 import sun.security.util.Debug;
-import sun.security.x509.X500Name;
 
 /**
  * A <code>CertStore</code> that retrieves <code>Certificates</code> and
@@ -93,8 +87,6 @@
 
     private static final Debug debug = Debug.getInstance("certpath");
 
-    private final static boolean DEBUG = false;
-
     private String ldapDN;
 
     private LDAPCertStoreImpl impl;
@@ -108,7 +100,7 @@
         String dn = null;
         if (params == null) {
             throw new InvalidAlgorithmParameterException(
-                "parameters required for LDAP Certore");
+                    "Parameters required for LDAP certstore");
         }
         if (params instanceof LDAPCertStoreParameters) {
             LDAPCertStoreParameters p = (LDAPCertStoreParameters) params;
@@ -119,7 +111,9 @@
             URI u = p.getURI();
             if (!u.getScheme().equalsIgnoreCase("ldap")) {
                 throw new InvalidAlgorithmParameterException(
-                "Only LDAP URIs are supported for LDAP Certore");
+                        "Unsupported scheme '" + u.getScheme()
+                                + "', only LDAP URIs are supported "
+                                + "for LDAP certstore");
             }
             // Use the same default values as in LDAPCertStoreParameters
             // if unspecified in URI
@@ -137,8 +131,9 @@
             }
         } else {
             throw new InvalidAlgorithmParameterException(
-                "parameters must be either LDAPCertStoreParameters or " +
-                "URICertStoreParameters");
+                "Parameters must be either LDAPCertStoreParameters or "
+                        + "URICertStoreParameters, but instance of "
+                        + params.getClass().getName() + " passed");
         }
 
         Key k = new Key(serverName, port);
@@ -236,6 +231,7 @@
      *         match the specified selector
      * @throws CertStoreException if an exception occurs
      */
+    @Override
     public synchronized Collection<X509Certificate> engineGetCertificates
             (CertSelector selector) throws CertStoreException {
         if (debug != null) {
@@ -245,7 +241,9 @@
         if (selector == null) {
             selector = new X509CertSelector();
         } else if (!(selector instanceof X509CertSelector)) {
-            throw new CertStoreException("need X509CertSelector to find certs");
+            throw new CertStoreException("Need X509CertSelector to find certs, "
+                    + "but instance of " + selector.getClass().getName()
+                    + " passed");
         }
         return impl.getCertificates((X509CertSelector) selector, ldapDN);
     }
@@ -271,6 +269,7 @@
      *         match the specified selector
      * @throws CertStoreException if an exception occurs
      */
+    @Override
     public synchronized Collection<X509CRL> engineGetCRLs(CRLSelector selector)
             throws CertStoreException {
         if (debug != null) {
@@ -281,7 +280,9 @@
         if (selector == null) {
             selector = new X509CRLSelector();
         } else if (!(selector instanceof X509CRLSelector)) {
-            throw new CertStoreException("need X509CRLSelector to find CRLs");
+            throw new CertStoreException("Need X509CRLSelector to find CRLs, "
+                    + "but instance of " + selector.getClass().getName()
+                    + " passed");
         }
         return impl.getCRLs((X509CRLSelector) selector, ldapDN);
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/x509/URICertStore/ExtensionsWithLDAP.java	Wed Sep 09 12:39:45 2015 +0300
@@ -0,0 +1,247 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.IOException;
+import java.io.StringBufferInputStream;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.CertPath;
+import java.security.cert.CertPathValidator;
+import java.security.cert.CertPathValidatorException;
+import java.security.cert.PKIXParameters;
+import java.security.cert.TrustAnchor;
+import java.security.cert.X509Certificate;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import sun.net.spi.nameservice.NameService;
+import sun.net.spi.nameservice.NameServiceDescriptor;
+
+/*
+ * @test
+ * @bug 8134708
+ * @summary Check if LDAP resources from CRLDP and AIA extensions can be loaded
+ * @run main/othervm ExtensionsWithLDAP
+ */
+public class ExtensionsWithLDAP {
+
+    /*
+     *  Certificate:
+     *  Data:
+     *    Version: 3 (0x2)
+     *    Serial Number: 11174053930990688938 (0x9b1236d8f9c1daaa)
+     *  Signature Algorithm: sha512WithRSAEncryption
+     *    Issuer: CN=Root
+     *    Validity
+     *        Not Before: Sep  1 18:03:59 2015 GMT
+     *        Not After : Jan 17 18:03:59 2043 GMT
+     *    Subject: CN=Root
+     */
+    private static final String CA_CERT = ""
+        + "-----BEGIN CERTIFICATE-----\n"
+        + "MIIC8TCCAdmgAwIBAgIJAJsSNtj5wdqqMA0GCSqGSIb3DQEBDQUAMA8xDTALBgNV\n"
+        + "BAMMBFJvb3QwHhcNMTUwOTAxMTgwMzU5WhcNNDMwMTE3MTgwMzU5WjAPMQ0wCwYD\n"
+        + "VQQDDARSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvj892vPm\n"
+        + "bB++x9QqqyBveP+ZqQ2B1stV7vh5JmDnOTevkZUOcemp3SXu/esNLSbpL+fARYXH\n"
+        + "V5ubnrfip6RbvcxPfVIIDJrRTLIIsU6W7M6/LJLbLkEVGy4ZV4IHkOw9W2O92rcv\n"
+        + "BkoqhzZnOTGR6uT3rRcKx4RevEKBKhZO+OPPf//lnckOybmYL7t7yQrajzHro76b\n"
+        + "QTXYjAUq/DKhglXfC7vF/JzlAvG2IunGmIfjGcnuDo/9X3Bxef/q5TxCS35fvb7t\n"
+        + "svC+g2QhTcBkQh4uNW2jSjlTIVp1uErCfP5aCjLaez5mqmb1hxPIlcvsNR23HwU6\n"
+        + "bQO7z7NBo9Do6QIDAQABo1AwTjAdBgNVHQ4EFgQUmLZNOBBkqdYoElyxklPYHmAb\n"
+        + "QXIwHwYDVR0jBBgwFoAUmLZNOBBkqdYoElyxklPYHmAbQXIwDAYDVR0TBAUwAwEB\n"
+        + "/zANBgkqhkiG9w0BAQ0FAAOCAQEAYV4fOhDi5q7+XNXCxO8Eil2frR9jqdP4LaQp\n"
+        + "3L0evW0gvPX68s2WmkPWzIu4TJcpdGFQqxyQFSXuKBXjthyiln77QItGTHWeafES\n"
+        + "q5ESrKdSaJZq1bTIrrReCIP74f+fY/F4Tnb3dCqzaljXfzpdbeRsIW6gF71xcOUQ\n"
+        + "nnPEjGVPLUegN+Wn/jQpeLxxIB7FmNXncdRUfMfZ43xVSKuMCy1UUYqJqTa/pXZj\n"
+        + "jCMeRPThRjRqHlJ69jStfWUQATbLyj9KN09rUaJxzmUSt61UqJi7sjcGySaCjAJc\n"
+        + "IcCdVmX/DmRLsdv8W36O3MgrvpT1zR3kaAlv2d8HppnBqcL3xg==\n"
+        + "-----END CERTIFICATE-----";
+
+    /*
+     *  Certificate:
+     *  Data:
+     *    Version: 3 (0x2)
+     *    Serial Number: 7 (0x7)
+     *  Signature Algorithm: sha512WithRSAEncryption
+     *    Issuer: CN=Root
+     *    Validity
+     *       Not Before: Sep  1 18:03:59 2015 GMT
+     *       Not After : Jan 17 18:03:59 2043 GMT
+     *    Subject: CN=EE
+     *    ...
+     *  X509v3 extensions:
+     *       X509v3 CRL Distribution Points:
+     *           Full Name:
+     *             URI:ldap://ldap.host.for.crldp/main.crl
+     *       Authority Information Access:
+     *           CA Issuers - URI:ldap://ldap.host.for.aia/dc=Root?cACertificate
+     */
+    private static final String EE_CERT = ""
+        + "-----BEGIN CERTIFICATE-----\n"
+        + "MIIDHTCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQ0FADAPMQ0wCwYDVQQDDARSb290\n"
+        + "MB4XDTE1MDkwMTE4MDM1OVoXDTQzMDExNzE4MDM1OVowDTELMAkGA1UEAwwCRUUw\n"
+        + "ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpyz97liuWPDYcLH9TX8Bi\n"
+        + "T78olCmAfmevvch6ncXUVuCzbdaKuKXwn4EVbDszsVJLoK5zdtP+X3iDhutj+IgK\n"
+        + "mLhuczF3M9VIcWr+JJUyTH4+3h/RT8cjCDZOmk9iXkb5ifruVsLqzb9g+Vp140Oz\n"
+        + "7leikne7KmclHvTfvFd0WDI7Gb9vo4f5rT717BXJ/n+M6pNk8DLpLiEu6eziYvXR\n"
+        + "v5x+t5Go3x0eCXdaxEQUf2j876Wfr2qHRJK7lDfFe1DDsMg/KpKGiILYZ+g2qtVM\n"
+        + "ZSxtp5BZEtfB5qV/IE5kWO+mCIAGpXSZIdbERR6pZUq8GLEe1T9e+sO6H24w2F19\n"
+        + "AgMBAAGjgYUwgYIwNAYDVR0fBC0wKzApoCegJYYjbGRhcDovL2xkYXAuaG9zdC5m\n"
+        + "b3IuY3JsZHAvbWFpbi5jcmwwSgYIKwYBBQUHAQEEPjA8MDoGCCsGAQUFBzAChi5s\n"
+        + "ZGFwOi8vbGRhcC5ob3N0LmZvci5haWEvZGM9Um9vdD9jQUNlcnRpZmljYXRlMA0G\n"
+        + "CSqGSIb3DQEBDQUAA4IBAQBWDfZHpuUx0yn5d3+BuztFqoks1MkGdk+USlH0TB1/\n"
+        + "gWWBd+4S4PCKlpSur0gj2rMW4fP5HQfNlHci8JV8/bG4KuKRAXW56dg1818Hl3pc\n"
+        + "iIrUSRn8uUjH3p9qb+Rb/u3mmVQRyJjN2t/zceNsO8/+Dd808OB9aEwGs8lMT0nn\n"
+        + "ZYaaAqYz1GIY/Ecyx1vfEZEQ1ljo6i/r70C3igbypBUShxSiGsleiVTLOGNA+MN1\n"
+        + "/a/Qh0bkaQyTGqK3bwvzzMeQVqWu2EWTBD/PmND5ExkpRICdv8LBVXfLnpoBr4lL\n"
+        + "hnxn9+e0Ah+t8dS5EKfn44w5bI5PCu2bqxs6RCTxNjcY\n"
+        + "-----END CERTIFICATE-----";
+
+
+    private static final String LDAP_HOST_CRLDP = "ldap.host.for.crldp";
+    private static final String LDAP_HOST_AIA = "ldap.host.for.aia";
+
+    // a date within the certificates validity period
+    static final Date validationDate;
+    static {
+        try {
+            validationDate = DateFormat.getDateInstance(
+                    DateFormat.MEDIUM, Locale.US).parse("Sep 02, 2015");
+        } catch (ParseException e) {
+            throw new RuntimeException("Couldn't parse date", e);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        // enable CRLDP and AIA extensions
+        System.setProperty("com.sun.security.enableCRLDP", "true");
+        System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
+
+        // register a local name service
+        System.setProperty("sun.net.spi.nameservice.provider.1", "ns,localdns");
+
+        X509Certificate trustedCert = loadCertificate(CA_CERT);
+        X509Certificate eeCert = loadCertificate(EE_CERT);
+
+        Set<TrustAnchor> trustedCertsSet = new HashSet<>();
+        trustedCertsSet.add(new TrustAnchor(trustedCert, null));
+
+        CertPath cp = (CertPath) CertificateFactory.getInstance("X509")
+                .generateCertPath(Arrays.asList(eeCert));
+
+        PKIXParameters params = new PKIXParameters(trustedCertsSet);
+        params.setDate(validationDate);
+
+        // certpath validator should try to parse CRLDP and AIA extensions,
+        // and load CRLs/certs which they point to
+        // if a local name service catched requests for resolving host names
+        // which extensions contain, then it means that certpath validator
+        // tried to load CRLs/certs which they point to
+        try {
+            CertPathValidator.getInstance("PKIX").validate(cp, params);
+            throw new RuntimeException("CertPathValidatorException not thrown");
+        } catch (CertPathValidatorException cpve) {
+            System.out.println("Expected exception: " + cpve);
+        }
+
+        // check if it tried to resolve a host name from CRLDP extension
+        if (!LocalNameService.requestedHosts.contains(LDAP_HOST_CRLDP)) {
+            throw new RuntimeException(
+                    "A hostname from CRLDP extension not requested");
+        }
+
+        // check if it tried to resolve a host name from AIA extension
+        if (!LocalNameService.requestedHosts.contains(LDAP_HOST_AIA)) {
+            throw new RuntimeException(
+                    "A hostname from AIA extension not requested");
+        }
+
+        System.out.println("Test passed");
+    }
+
+    // load a X509 certificate
+    public static X509Certificate loadCertificate(String s)
+            throws IOException, CertificateException {
+
+        try (StringBufferInputStream is = new StringBufferInputStream(s)) {
+            return (X509Certificate) CertificateFactory.getInstance("X509")
+                    .generateCertificate(is);
+        }
+    }
+
+    // a local name service which log requested host names
+    public static class LocalNameService implements NameServiceDescriptor {
+
+        static final List<String> requestedHosts = new ArrayList<>();
+
+        @Override
+        public NameService createNameService() throws Exception {
+            System.out.println("LocalNameService: createNameService() called");
+            NameService ns = new NameService() {
+
+                @Override
+                public InetAddress[] lookupAllHostAddr(String host)
+                        throws UnknownHostException {
+
+                    System.out.println("LocalNameService: "
+                            + "NameService.lookupAllHostAddr(): " + host);
+
+                    requestedHosts.add(host);
+
+                    throw new UnknownHostException();
+                }
+
+                @Override
+                public String getHostByAddr(byte[] addr)
+                        throws UnknownHostException {
+                    System.out.println("LocalNameService: "
+                            + "NameService.getHostByAddr(): "
+                            + Arrays.toString(addr));
+                    throw new UnknownHostException("No reverse lookup");
+                }
+            };
+            return ns;
+        }
+
+        @Override
+        public String getProviderName() {
+            return "localdns";
+        }
+
+        @Override
+        public String getType() {
+            return "ns";
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/x509/URICertStore/META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor	Wed Sep 09 12:39:45 2015 +0300
@@ -0,0 +1,1 @@
+ExtensionsWithLDAP$LocalNameService