PKIXValidator.java 15.8 KB
Newer Older
D
duke 已提交
1
/*
M
mbalao 已提交
2
 * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * 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.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33
 */

package sun.security.validator;

import java.util.*;

import java.security.*;
import java.security.cert.*;

import javax.security.auth.x500.X500Principal;
34 35
import sun.security.action.GetBooleanAction;
import sun.security.provider.certpath.AlgorithmChecker;
36
import sun.security.provider.certpath.PKIXExtendedParameters;
D
duke 已提交
37 38 39

/**
 * Validator implementation built on the PKIX CertPath API. This
40
 * implementation will be emphasized going forward.
41
 * <p>
D
duke 已提交
42 43 44 45
 * Note that the validate() implementation tries to use a PKIX validator
 * if that appears possible and a PKIX builder otherwise. This increases
 * performance and currently also leads to better exception messages
 * in case of failures.
46 47 48 49
 * <p>
 * {@code PKIXValidator} objects are immutable once they have been created.
 * Please DO NOT add methods that can change the state of an instance once
 * it has been created.
D
duke 已提交
50 51 52 53 54
 *
 * @author Andreas Sterbenz
 */
public final class PKIXValidator extends Validator {

55 56 57 58 59 60 61 62 63
    /**
     * Flag indicating whether to enable revocation check for the PKIX trust
     * manager. Typically, this will only work if the PKIX implementation
     * supports CRL distribution points as we do not manually setup CertStores.
     */
    private final static boolean checkTLSRevocation =
        AccessController.doPrivileged
            (new GetBooleanAction("com.sun.net.ssl.checkRevocation"));

D
duke 已提交
64 65 66 67 68 69 70 71
    // enable use of the validator if possible
    private final static boolean TRY_VALIDATOR = true;

    private final Set<X509Certificate> trustedCerts;
    private final PKIXBuilderParameters parameterTemplate;
    private int certPathLength = -1;

    // needed only for the validator
72 73
    private final Map<X500Principal, List<PublicKey>> trustedSubjects;
    private final CertificateFactory factory;
D
duke 已提交
74

75
    private final boolean plugin;
D
duke 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

    PKIXValidator(String variant, Collection<X509Certificate> trustedCerts) {
        super(TYPE_PKIX, variant);
        if (trustedCerts instanceof Set) {
            this.trustedCerts = (Set<X509Certificate>)trustedCerts;
        } else {
            this.trustedCerts = new HashSet<X509Certificate>(trustedCerts);
        }
        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
        for (X509Certificate cert : trustedCerts) {
            trustAnchors.add(new TrustAnchor(cert, null));
        }
        try {
            parameterTemplate = new PKIXBuilderParameters(trustAnchors, null);
        } catch (InvalidAlgorithmParameterException e) {
            throw new RuntimeException("Unexpected error: " + e.toString(), e);
        }
        setDefaultParameters(variant);
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

        // initCommon();
        if (TRY_VALIDATOR) {
            if (TRY_VALIDATOR == false) {
                return;
            }
            trustedSubjects = new HashMap<X500Principal, List<PublicKey>>();
            for (X509Certificate cert : trustedCerts) {
                X500Principal dn = cert.getSubjectX500Principal();
                List<PublicKey> keys;
                if (trustedSubjects.containsKey(dn)) {
                    keys = trustedSubjects.get(dn);
                } else {
                    keys = new ArrayList<PublicKey>();
                    trustedSubjects.put(dn, keys);
                }
                keys.add(cert.getPublicKey());
            }
            try {
                factory = CertificateFactory.getInstance("X.509");
            } catch (CertificateException e) {
                throw new RuntimeException("Internal error", e);
            }
            plugin = variant.equals(VAR_PLUGIN_CODE_SIGNING);
        } else {
            plugin = false;
        }
D
duke 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133
    }

    PKIXValidator(String variant, PKIXBuilderParameters params) {
        super(TYPE_PKIX, variant);
        trustedCerts = new HashSet<X509Certificate>();
        for (TrustAnchor anchor : params.getTrustAnchors()) {
            X509Certificate cert = anchor.getTrustedCert();
            if (cert != null) {
                trustedCerts.add(cert);
            }
        }
        parameterTemplate = params;

134 135 136 137
        // initCommon();
        if (TRY_VALIDATOR) {
            if (TRY_VALIDATOR == false) {
                return;
138
            }
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            trustedSubjects = new HashMap<X500Principal, List<PublicKey>>();
            for (X509Certificate cert : trustedCerts) {
                X500Principal dn = cert.getSubjectX500Principal();
                List<PublicKey> keys;
                if (trustedSubjects.containsKey(dn)) {
                    keys = trustedSubjects.get(dn);
                } else {
                    keys = new ArrayList<PublicKey>();
                    trustedSubjects.put(dn, keys);
                }
                keys.add(cert.getPublicKey());
            }
            try {
                factory = CertificateFactory.getInstance("X.509");
            } catch (CertificateException e) {
                throw new RuntimeException("Internal error", e);
            }
            plugin = variant.equals(VAR_PLUGIN_CODE_SIGNING);
        } else {
            plugin = false;
D
duke 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        }
    }

    public Collection<X509Certificate> getTrustedCertificates() {
        return trustedCerts;
    }

    /**
     * Returns the length of the last certification path that is validated by
     * CertPathValidator. This is intended primarily as a callback mechanism
     * for PKIXCertPathCheckers to determine the length of the certification
     * path that is being validated. It is necessary since engineValidate()
     * may modify the length of the path.
     *
     * @return the length of the last certification path passed to
     *   CertPathValidator.validate, or -1 if it has not been invoked yet
     */
176
    public int getCertPathLength() { // mutable, should be private
D
duke 已提交
177 178 179 180 181 182 183 184
        return certPathLength;
    }

    /**
     * Set J2SE global default PKIX parameters. Currently, hardcoded to disable
     * revocation checking. In the future, this should be configurable.
     */
    private void setDefaultParameters(String variant) {
185 186 187 188 189 190
        if ((variant == Validator.VAR_TLS_SERVER) ||
                (variant == Validator.VAR_TLS_CLIENT)) {
            parameterTemplate.setRevocationEnabled(checkTLSRevocation);
        } else {
            parameterTemplate.setRevocationEnabled(false);
        }
D
duke 已提交
191 192 193 194 195 196 197
    }

    /**
     * Return the PKIX parameters used by this instance. An application may
     * modify the parameters but must make sure not to perform any concurrent
     * validations.
     */
198
    public PKIXBuilderParameters getParameters() { // mutable, should be private
D
duke 已提交
199 200 201
        return parameterTemplate;
    }

202
    @Override
D
duke 已提交
203
    X509Certificate[] engineValidate(X509Certificate[] chain,
204 205 206
            Collection<X509Certificate> otherCerts,
            AlgorithmConstraints constraints,
            Object parameter) throws CertificateException {
D
duke 已提交
207 208 209 210
        if ((chain == null) || (chain.length == 0)) {
            throw new CertificateException
                ("null or zero-length certificate chain");
        }
211

M
mbalao 已提交
212

213 214 215 216 217 218 219 220 221 222 223 224 225
        // Use PKIXExtendedParameters for timestamp and variant additions
        PKIXBuilderParameters pkixParameters = null;
        try {
            pkixParameters = new PKIXExtendedParameters(
                    (PKIXBuilderParameters) parameterTemplate.clone(),
                    (parameter instanceof Timestamp) ?
                            (Timestamp) parameter : null,
                    variant);
        } catch (InvalidAlgorithmParameterException e) {
            // ignore exception
        }

        // add a new algorithm constraints checker
226
        if (constraints != null) {
227 228
            pkixParameters.addCertPathChecker(
                    new AlgorithmChecker(constraints, null, variant));
229 230
        }

D
duke 已提交
231
        if (TRY_VALIDATOR) {
232 233 234
            // check that chain is in correct order and check if chain contains
            // trust anchor
            X500Principal prevIssuer = null;
D
duke 已提交
235
            for (int i = 0; i < chain.length; i++) {
236
                X509Certificate cert = chain[i];
237
                X500Principal dn = cert.getSubjectX500Principal();
238

M
mbalao 已提交
239 240
                if (i == 0) {
                    if (trustedCerts.contains(cert)) {
D
duke 已提交
241 242
                        return new X509Certificate[] {chain[0]};
                    }
M
mbalao 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                } else {
                    if (!dn.equals(prevIssuer)) {
                        // chain is not ordered correctly, call builder instead
                        return doBuild(chain, otherCerts, pkixParameters);
                    }
                    // Check if chain[i] is already trusted. It may be inside
                    // trustedCerts, or has the same dn and public key as a cert
                    // inside trustedCerts. The latter happens when a CA has
                    // updated its cert with a stronger signature algorithm in JRE
                    // but the weak one is still in circulation.
                    if (trustedCerts.contains(cert) ||          // trusted cert
                            (trustedSubjects.containsKey(dn) && // replacing ...
                             trustedSubjects.get(dn).contains(  // ... weak cert
                                cert.getPublicKey()))) {
                        // Remove and call validator on partial chain [0 .. i-1]
                        X509Certificate[] newChain = new X509Certificate[i];
                        System.arraycopy(chain, 0, newChain, 0, i);
                        return doValidate(newChain, pkixParameters);
                    }
D
duke 已提交
262
                }
263
                prevIssuer = cert.getIssuerX500Principal();
D
duke 已提交
264 265
            }

266
            // apparently issued by trust anchor?
D
duke 已提交
267 268 269
            X509Certificate last = chain[chain.length - 1];
            X500Principal issuer = last.getIssuerX500Principal();
            X500Principal subject = last.getSubjectX500Principal();
270 271
            if (trustedSubjects.containsKey(issuer) &&
                    isSignatureValid(trustedSubjects.get(issuer), last)) {
272
                return doValidate(chain, pkixParameters);
D
duke 已提交
273 274 275 276 277 278 279 280 281 282 283
            }

            // don't fallback to builder if called from plugin/webstart
            if (plugin) {
                // Validate chain even if no trust anchor is found. This
                // allows plugin/webstart to make sure the chain is
                // otherwise valid
                if (chain.length > 1) {
                    X509Certificate[] newChain =
                        new X509Certificate[chain.length-1];
                    System.arraycopy(chain, 0, newChain, 0, newChain.length);
284

D
duke 已提交
285 286
                    // temporarily set last cert as sole trust anchor
                    try {
287
                        pkixParameters.setTrustAnchors
D
duke 已提交
288 289 290 291 292 293
                            (Collections.singleton(new TrustAnchor
                                (chain[chain.length-1], null)));
                    } catch (InvalidAlgorithmParameterException iape) {
                        // should never occur, but ...
                        throw new CertificateException(iape);
                    }
294
                    doValidate(newChain, pkixParameters);
D
duke 已提交
295 296 297 298 299 300 301 302 303
                }
                // if the rest of the chain is valid, throw exception
                // indicating no trust anchor was found
                throw new ValidatorException
                    (ValidatorException.T_NO_TRUST_ANCHOR);
            }
            // otherwise, fall back to builder
        }

304
        return doBuild(chain, otherCerts, pkixParameters);
D
duke 已提交
305 306
    }

307 308
    private boolean isSignatureValid(List<PublicKey> keys,
            X509Certificate sub) {
D
duke 已提交
309
        if (plugin) {
310 311 312 313 314 315 316
            for (PublicKey key: keys) {
                try {
                    sub.verify(key);
                    return true;
                } catch (Exception ex) {
                    continue;
                }
D
duke 已提交
317
            }
318
            return false;
D
duke 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        }
        return true; // only check if PLUGIN is set
    }

    private static X509Certificate[] toArray(CertPath path, TrustAnchor anchor)
            throws CertificateException {
        List<? extends java.security.cert.Certificate> list =
                                                path.getCertificates();
        X509Certificate[] chain = new X509Certificate[list.size() + 1];
        list.toArray(chain);
        X509Certificate trustedCert = anchor.getTrustedCert();
        if (trustedCert == null) {
            throw new ValidatorException
                ("TrustAnchor must be specified as certificate");
        }
        chain[chain.length - 1] = trustedCert;
        return chain;
    }

    /**
     * Set the check date (for debugging).
     */
    private void setDate(PKIXBuilderParameters params) {
342
        @SuppressWarnings("deprecation")
D
duke 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        Date date = validationDate;
        if (date != null) {
            params.setDate(date);
        }
    }

    private X509Certificate[] doValidate(X509Certificate[] chain,
            PKIXBuilderParameters params) throws CertificateException {
        try {
            setDate(params);

            // do the validation
            CertPathValidator validator = CertPathValidator.getInstance("PKIX");
            CertPath path = factory.generateCertPath(Arrays.asList(chain));
            certPathLength = chain.length;
            PKIXCertPathValidatorResult result =
                (PKIXCertPathValidatorResult)validator.validate(path, params);

            return toArray(path, result.getTrustAnchor());
        } catch (GeneralSecurityException e) {
            throw new ValidatorException
                ("PKIX path validation failed: " + e.toString(), e);
        }
    }

    private X509Certificate[] doBuild(X509Certificate[] chain,
369 370
        Collection<X509Certificate> otherCerts,
        PKIXBuilderParameters params) throws CertificateException {
D
duke 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

        try {
            setDate(params);

            // setup target constraints
            X509CertSelector selector = new X509CertSelector();
            selector.setCertificate(chain[0]);
            params.setTargetCertConstraints(selector);

            // setup CertStores
            Collection<X509Certificate> certs =
                                        new ArrayList<X509Certificate>();
            certs.addAll(Arrays.asList(chain));
            if (otherCerts != null) {
                certs.addAll(otherCerts);
            }
            CertStore store = CertStore.getInstance("Collection",
                                new CollectionCertStoreParameters(certs));
            params.addCertStore(store);

            // do the build
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
            PKIXCertPathBuilderResult result =
                (PKIXCertPathBuilderResult)builder.build(params);

            return toArray(result.getCertPath(), result.getTrustAnchor());
        } catch (GeneralSecurityException e) {
            throw new ValidatorException
                ("PKIX path building failed: " + e.toString(), e);
        }
    }
}