1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.ssl;
  27 
  28 import java.net.Socket;
  29 import java.security.Key;
  30 import java.security.KeyStore;
  31 import java.security.KeyStoreException;
  32 import java.security.NoSuchAlgorithmException;
  33 import java.security.Principal;
  34 import java.security.PrivateKey;
  35 import java.security.UnrecoverableKeyException;
  36 import java.security.cert.Certificate;
  37 import java.security.cert.X509Certificate;
  38 import java.util.ArrayList;
  39 import java.util.Collections;
  40 import java.util.Enumeration;
  41 import java.util.HashMap;
  42 import java.util.HashSet;
  43 import java.util.List;
  44 import java.util.Locale;
  45 import java.util.Map;
  46 import java.util.Set;
  47 import javax.net.ssl.SSLEngine;
  48 import javax.net.ssl.X509ExtendedKeyManager;
  49 import javax.security.auth.x500.X500Principal;
  50 
  51 
  52 /**
  53  * An implementation of X509KeyManager backed by a KeyStore.
  54  *
  55  * The backing KeyStore is inspected when this object is constructed.
  56  * All key entries containing a PrivateKey and a non-empty chain of
  57  * X509Certificate are then copied into an internal store. This means
  58  * that subsequent modifications of the KeyStore have no effect on the
  59  * X509KeyManagerImpl object.
  60  *
  61  * Note that this class assumes that all keys are protected by the same
  62  * password.
  63  *
  64  * The JSSE handshake code currently calls into this class via
  65  * chooseClientAlias() and chooseServerAlias() to find the certificates to
  66  * use. As implemented here, both always return the first alias returned by
  67  * getClientAliases() and getServerAliases(). In turn, these methods are
  68  * implemented by calling getAliases(), which performs the actual lookup.
  69  *
  70  * Note that this class currently implements no checking of the local
  71  * certificates. In particular, it is *not* guaranteed that:
  72  *  . the certificates are within their validity period and not revoked
  73  *  . the signatures verify
  74  *  . they form a PKIX compliant chain.
  75  *  . the certificate extensions allow the certificate to be used for
  76  *    the desired purpose.
  77  *
  78  * Chains that fail any of these criteria will probably be rejected by
  79  * the remote peer.
  80  *
  81  */
  82 final class SunX509KeyManagerImpl extends X509ExtendedKeyManager {
  83 
  84     private static final String[] STRING0 = new String[0];
  85 
  86     /*
  87      * The credentials from the KeyStore as
  88      * Map: String(alias) -> X509Credentials(credentials)
  89      */
  90     private Map<String,X509Credentials> credentialsMap;
  91 
  92     /*
  93      * Cached server aliases for the case issuers == null.
  94      * (in the current JSSE implementation, issuers are always null for
  95      * server certs). See chooseServerAlias() for details.
  96      *
  97      * Map: String(keyType) -> String[](alias)
  98      */
  99     private final Map<String,String[]> serverAliasCache;
 100 
 101     /*
 102      * Basic container for credentials implemented as an inner class.
 103      */
 104     private static class X509Credentials {
 105         final PrivateKey privateKey;
 106         final X509Certificate[] certificates;
 107         private final Set<X500Principal> issuerX500Principals;
 108 
 109         X509Credentials(PrivateKey privateKey, X509Certificate[] certificates) {
 110             // assert privateKey and certificates != null
 111             this.privateKey = privateKey;
 112             this.certificates = certificates;
 113             this.issuerX500Principals = new HashSet<>(certificates.length);
 114             for (X509Certificate certificate : certificates) {
 115                 issuerX500Principals.add(certificate.getIssuerX500Principal());
 116             }
 117         }
 118 
 119         Set<X500Principal> getIssuerX500Principals() {
 120             return issuerX500Principals;
 121         }
 122     }
 123 
 124     SunX509KeyManagerImpl(KeyStore ks, char[] password)
 125             throws KeyStoreException,
 126             NoSuchAlgorithmException, UnrecoverableKeyException {
 127 
 128         credentialsMap = new HashMap<String,X509Credentials>();
 129         serverAliasCache = Collections.synchronizedMap(
 130                             new HashMap<String,String[]>());
 131         if (ks == null) {
 132             return;
 133         }
 134 
 135         for (Enumeration<String> aliases = ks.aliases();
 136                                         aliases.hasMoreElements(); ) {
 137             String alias = aliases.nextElement();
 138             if (!ks.isKeyEntry(alias)) {
 139                 continue;
 140             }
 141             Key key = ks.getKey(alias, password);
 142             if (key instanceof PrivateKey == false) {
 143                 continue;
 144             }
 145             Certificate[] certs = ks.getCertificateChain(alias);
 146             if ((certs == null) || (certs.length == 0) ||
 147                     !(certs[0] instanceof X509Certificate)) {
 148                 continue;
 149             }
 150             if (!(certs instanceof X509Certificate[])) {
 151                 Certificate[] tmp = new X509Certificate[certs.length];
 152                 System.arraycopy(certs, 0, tmp, 0, certs.length);
 153                 certs = tmp;
 154             }
 155 
 156             X509Credentials cred = new X509Credentials((PrivateKey)key,
 157                 (X509Certificate[])certs);
 158             credentialsMap.put(alias, cred);
 159             if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
 160                 SSLLogger.fine("found key for : " + alias, (Object[])certs);
 161             }
 162         }
 163     }
 164 
 165     /*
 166      * Returns the certificate chain associated with the given alias.
 167      *
 168      * @return the certificate chain (ordered with the user's certificate first
 169      * and the root certificate authority last)
 170      */
 171     @Override
 172     public X509Certificate[] getCertificateChain(String alias) {
 173         if (alias == null) {
 174             return null;
 175         }
 176         X509Credentials cred = credentialsMap.get(alias);
 177         if (cred == null) {
 178             return null;
 179         } else {
 180             return cred.certificates.clone();
 181         }
 182     }
 183 
 184     /*
 185      * Returns the key associated with the given alias
 186      */
 187     @Override
 188     public PrivateKey getPrivateKey(String alias) {
 189         if (alias == null) {
 190             return null;
 191         }
 192         X509Credentials cred = credentialsMap.get(alias);
 193         if (cred == null) {
 194             return null;
 195         } else {
 196             return cred.privateKey;
 197         }
 198     }
 199 
 200     /*
 201      * Choose an alias to authenticate the client side of a secure
 202      * socket given the public key type and the list of
 203      * certificate issuer authorities recognized by the peer (if any).
 204      */
 205     @Override
 206     public String chooseClientAlias(String[] keyTypes, Principal[] issuers,
 207             Socket socket) {
 208         /*
 209          * We currently don't do anything with socket, but
 210          * someday we might.  It might be a useful hint for
 211          * selecting one of the aliases we get back from
 212          * getClientAliases().
 213          */
 214 
 215         if (keyTypes == null) {
 216             return null;
 217         }
 218 
 219         for (int i = 0; i < keyTypes.length; i++) {
 220             String[] aliases = getClientAliases(keyTypes[i], issuers);
 221             if ((aliases != null) && (aliases.length > 0)) {
 222                 return aliases[0];
 223             }
 224         }
 225         return null;
 226     }
 227 
 228     /*
 229      * Choose an alias to authenticate the client side of an
 230      * <code>SSLEngine</code> connection given the public key type
 231      * and the list of certificate issuer authorities recognized by
 232      * the peer (if any).
 233      *
 234      * @since 1.5
 235      */
 236     @Override
 237     public String chooseEngineClientAlias(String[] keyType,
 238             Principal[] issuers, SSLEngine engine) {
 239         /*
 240          * If we ever start using socket as a selection criteria,
 241          * we'll need to adjust this.
 242          */
 243         return chooseClientAlias(keyType, issuers, null);
 244     }
 245 
 246     /*
 247      * Choose an alias to authenticate the server side of a secure
 248      * socket given the public key type and the list of
 249      * certificate issuer authorities recognized by the peer (if any).
 250      */
 251     @Override
 252     public String chooseServerAlias(String keyType,
 253             Principal[] issuers, Socket socket) {
 254         /*
 255          * We currently don't do anything with socket, but
 256          * someday we might.  It might be a useful hint for
 257          * selecting one of the aliases we get back from
 258          * getServerAliases().
 259          */
 260         if (keyType == null) {
 261             return null;
 262         }
 263 
 264         String[] aliases;
 265 
 266         if (issuers == null || issuers.length == 0) {
 267             aliases = serverAliasCache.get(keyType);
 268             if (aliases == null) {
 269                 aliases = getServerAliases(keyType, issuers);
 270                 // Cache the result (positive and negative lookups)
 271                 if (aliases == null) {
 272                     aliases = STRING0;
 273                 }
 274                 serverAliasCache.put(keyType, aliases);
 275             }
 276         } else {
 277             aliases = getServerAliases(keyType, issuers);
 278         }
 279         if ((aliases != null) && (aliases.length > 0)) {
 280             return aliases[0];
 281         }
 282         return null;
 283     }
 284 
 285     /*
 286      * Choose an alias to authenticate the server side of an
 287      * <code>SSLEngine</code> connection given the public key type
 288      * and the list of certificate issuer authorities recognized by
 289      * the peer (if any).
 290      *
 291      * @since 1.5
 292      */
 293     @Override
 294     public String chooseEngineServerAlias(String keyType,
 295             Principal[] issuers, SSLEngine engine) {
 296         /*
 297          * If we ever start using socket as a selection criteria,
 298          * we'll need to adjust this.
 299          */
 300         return chooseServerAlias(keyType, issuers, null);
 301     }
 302 
 303     /*
 304      * Get the matching aliases for authenticating the client side of a secure
 305      * socket given the public key type and the list of
 306      * certificate issuer authorities recognized by the peer (if any).
 307      */
 308     @Override
 309     public String[] getClientAliases(String keyType, Principal[] issuers) {
 310         return getAliases(keyType, issuers);
 311     }
 312 
 313     /*
 314      * Get the matching aliases for authenticating the server side of a secure
 315      * socket given the public key type and the list of
 316      * certificate issuer authorities recognized by the peer (if any).
 317      */
 318     @Override
 319     public String[] getServerAliases(String keyType, Principal[] issuers) {
 320         return getAliases(keyType, issuers);
 321     }
 322 
 323     /*
 324      * Get the matching aliases for authenticating the either side of a secure
 325      * socket given the public key type and the list of
 326      * certificate issuer authorities recognized by the peer (if any).
 327      *
 328      * Issuers comes to us in the form of X500Principal[].
 329      */
 330     private String[] getAliases(String keyType, Principal[] issuers) {
 331         if (keyType == null) {
 332             return null;
 333         }
 334         if (issuers == null) {
 335             issuers = new X500Principal[0];
 336         }
 337         if (issuers instanceof X500Principal[] == false) {
 338             // normally, this will never happen but try to recover if it does
 339             issuers = convertPrincipals(issuers);
 340         }
 341         String sigType;
 342         if (keyType.contains("_")) {
 343             int k = keyType.indexOf('_');
 344             sigType = keyType.substring(k + 1);
 345             keyType = keyType.substring(0, k);
 346         } else {
 347             sigType = null;
 348         }
 349 
 350         X500Principal[] x500Issuers = (X500Principal[])issuers;
 351         // the algorithm below does not produce duplicates, so avoid Set
 352         List<String> aliases = new ArrayList<>();
 353 
 354         for (Map.Entry<String,X509Credentials> entry :
 355                                                 credentialsMap.entrySet()) {
 356 
 357             String alias = entry.getKey();
 358             X509Credentials credentials = entry.getValue();
 359             X509Certificate[] certs = credentials.certificates;
 360 
 361             if (!keyType.equals(certs[0].getPublicKey().getAlgorithm())) {
 362                 continue;
 363             }
 364             if (sigType != null) {
 365                 if (certs.length > 1) {
 366                     // if possible, check the public key in the issuer cert
 367                     if (!sigType.equals(
 368                             certs[1].getPublicKey().getAlgorithm())) {
 369                         continue;
 370                     }
 371                 } else {
 372                     // Check the signature algorithm of the certificate itself.
 373                     // Look for the "withRSA" in "SHA1withRSA", etc.
 374                     String sigAlgName =
 375                         certs[0].getSigAlgName().toUpperCase(Locale.ENGLISH);
 376                     String pattern = "WITH" +
 377                         sigType.toUpperCase(Locale.ENGLISH);
 378                     if (sigAlgName.contains(pattern) == false) {
 379                         continue;
 380                     }
 381                 }
 382             }
 383 
 384             if (issuers.length == 0) {
 385                 // no issuer specified, match all
 386                 aliases.add(alias);
 387                 if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
 388                     SSLLogger.fine("matching alias: " + alias);
 389                 }
 390             } else {
 391                 Set<X500Principal> certIssuers =
 392                                         credentials.getIssuerX500Principals();
 393                 for (int i = 0; i < x500Issuers.length; i++) {
 394                     if (certIssuers.contains(issuers[i])) {
 395                         aliases.add(alias);
 396                         if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
 397                             SSLLogger.fine("matching alias: " + alias);
 398                         }
 399                         break;
 400                     }
 401                 }
 402             }
 403         }
 404 
 405         String[] aliasStrings = aliases.toArray(STRING0);
 406         return ((aliasStrings.length == 0) ? null : aliasStrings);
 407     }
 408 
 409     /*
 410      * Convert an array of Principals to an array of X500Principals, if
 411      * possible. Principals that cannot be converted are ignored.
 412      */
 413     private static X500Principal[] convertPrincipals(Principal[] principals) {
 414         List<X500Principal> list = new ArrayList<>(principals.length);
 415         for (int i = 0; i < principals.length; i++) {
 416             Principal p = principals[i];
 417             if (p instanceof X500Principal) {
 418                 list.add((X500Principal)p);
 419             } else {
 420                 try {
 421                     list.add(new X500Principal(p.getName()));
 422                 } catch (IllegalArgumentException e) {
 423                     // ignore
 424                 }
 425             }
 426         }
 427         return list.toArray(new X500Principal[list.size()]);
 428     }
 429 }