1 /*
   2  * Copyright (c) 1999, 2018, 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         PrivateKey privateKey;
 106         X509Certificate[] certificates;
 107         private 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         }
 114 
 115         synchronized Set<X500Principal> getIssuerX500Principals() {
 116             // lazy initialization
 117             if (issuerX500Principals == null) {
 118                 issuerX500Principals = new HashSet<X500Principal>();
 119                 for (int i = 0; i < certificates.length; i++) {
 120                     issuerX500Principals.add(
 121                                 certificates[i].getIssuerX500Principal());
 122                 }
 123             }
 124             return issuerX500Principals;
 125         }
 126     }
 127 
 128     SunX509KeyManagerImpl(KeyStore ks, char[] password)
 129             throws KeyStoreException,
 130             NoSuchAlgorithmException, UnrecoverableKeyException {
 131 
 132         credentialsMap = new HashMap<String,X509Credentials>();
 133         serverAliasCache = Collections.synchronizedMap(
 134                             new HashMap<String,String[]>());
 135         if (ks == null) {
 136             return;
 137         }
 138 
 139         for (Enumeration<String> aliases = ks.aliases();
 140                                         aliases.hasMoreElements(); ) {
 141             String alias = aliases.nextElement();
 142             if (!ks.isKeyEntry(alias)) {
 143                 continue;
 144             }
 145             Key key = ks.getKey(alias, password);
 146             if (key instanceof PrivateKey == false) {
 147                 continue;
 148             }
 149             Certificate[] certs = ks.getCertificateChain(alias);
 150             if ((certs == null) || (certs.length == 0) ||
 151                     !(certs[0] instanceof X509Certificate)) {
 152                 continue;
 153             }
 154             if (!(certs instanceof X509Certificate[])) {
 155                 Certificate[] tmp = new X509Certificate[certs.length];
 156                 System.arraycopy(certs, 0, tmp, 0, certs.length);
 157                 certs = tmp;
 158             }
 159 
 160             X509Credentials cred = new X509Credentials((PrivateKey)key,
 161                 (X509Certificate[])certs);
 162             credentialsMap.put(alias, cred);
 163             if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
 164                 SSLLogger.fine("found key for : " + alias, (Object[])certs);
 165             }
 166         }
 167     }
 168 
 169     /*
 170      * Returns the certificate chain associated with the given alias.
 171      *
 172      * @return the certificate chain (ordered with the user's certificate first
 173      * and the root certificate authority last)
 174      */
 175     @Override
 176     public X509Certificate[] getCertificateChain(String alias) {
 177         if (alias == null) {
 178             return null;
 179         }
 180         X509Credentials cred = credentialsMap.get(alias);
 181         if (cred == null) {
 182             return null;
 183         } else {
 184             return cred.certificates.clone();
 185         }
 186     }
 187 
 188     /*
 189      * Returns the key associated with the given alias
 190      */
 191     @Override
 192     public PrivateKey getPrivateKey(String alias) {
 193         if (alias == null) {
 194             return null;
 195         }
 196         X509Credentials cred = credentialsMap.get(alias);
 197         if (cred == null) {
 198             return null;
 199         } else {
 200             return cred.privateKey;
 201         }
 202     }
 203 
 204     /*
 205      * Choose an alias to authenticate the client side of a secure
 206      * socket given the public key type and the list of
 207      * certificate issuer authorities recognized by the peer (if any).
 208      */
 209     @Override
 210     public String chooseClientAlias(String[] keyTypes, Principal[] issuers,
 211             Socket socket) {
 212         /*
 213          * We currently don't do anything with socket, but
 214          * someday we might.  It might be a useful hint for
 215          * selecting one of the aliases we get back from
 216          * getClientAliases().
 217          */
 218 
 219         if (keyTypes == null) {
 220             return null;
 221         }
 222 
 223         for (int i = 0; i < keyTypes.length; i++) {
 224             String[] aliases = getClientAliases(keyTypes[i], issuers);
 225             if ((aliases != null) && (aliases.length > 0)) {
 226                 return aliases[0];
 227             }
 228         }
 229         return null;
 230     }
 231 
 232     /*
 233      * Choose an alias to authenticate the client side of an
 234      * <code>SSLEngine</code> connection given the public key type
 235      * and the list of certificate issuer authorities recognized by
 236      * the peer (if any).
 237      *
 238      * @since 1.5
 239      */
 240     @Override
 241     public String chooseEngineClientAlias(String[] keyType,
 242             Principal[] issuers, SSLEngine engine) {
 243         /*
 244          * If we ever start using socket as a selection criteria,
 245          * we'll need to adjust this.
 246          */
 247         return chooseClientAlias(keyType, issuers, null);
 248     }
 249 
 250     /*
 251      * Choose an alias to authenticate the server side of a secure
 252      * socket given the public key type and the list of
 253      * certificate issuer authorities recognized by the peer (if any).
 254      */
 255     @Override
 256     public String chooseServerAlias(String keyType,
 257             Principal[] issuers, Socket socket) {
 258         /*
 259          * We currently don't do anything with socket, but
 260          * someday we might.  It might be a useful hint for
 261          * selecting one of the aliases we get back from
 262          * getServerAliases().
 263          */
 264         if (keyType == null) {
 265             return null;
 266         }
 267 
 268         String[] aliases;
 269 
 270         if (issuers == null || issuers.length == 0) {
 271             aliases = serverAliasCache.get(keyType);
 272             if (aliases == null) {
 273                 aliases = getServerAliases(keyType, issuers);
 274                 // Cache the result (positive and negative lookups)
 275                 if (aliases == null) {
 276                     aliases = STRING0;
 277                 }
 278                 serverAliasCache.put(keyType, aliases);
 279             }
 280         } else {
 281             aliases = getServerAliases(keyType, issuers);
 282         }
 283         if ((aliases != null) && (aliases.length > 0)) {
 284             return aliases[0];
 285         }
 286         return null;
 287     }
 288 
 289     /*
 290      * Choose an alias to authenticate the server side of an
 291      * <code>SSLEngine</code> connection given the public key type
 292      * and the list of certificate issuer authorities recognized by
 293      * the peer (if any).
 294      *
 295      * @since 1.5
 296      */
 297     @Override
 298     public String chooseEngineServerAlias(String keyType,
 299             Principal[] issuers, SSLEngine engine) {
 300         /*
 301          * If we ever start using socket as a selection criteria,
 302          * we'll need to adjust this.
 303          */
 304         return chooseServerAlias(keyType, issuers, null);
 305     }
 306 
 307     /*
 308      * Get the matching aliases for authenticating the client side of a secure
 309      * socket given the public key type and the list of
 310      * certificate issuer authorities recognized by the peer (if any).
 311      */
 312     @Override
 313     public String[] getClientAliases(String keyType, Principal[] issuers) {
 314         return getAliases(keyType, issuers);
 315     }
 316 
 317     /*
 318      * Get the matching aliases for authenticating the server side of a secure
 319      * socket given the public key type and the list of
 320      * certificate issuer authorities recognized by the peer (if any).
 321      */
 322     @Override
 323     public String[] getServerAliases(String keyType, Principal[] issuers) {
 324         return getAliases(keyType, issuers);
 325     }
 326 
 327     /*
 328      * Get the matching aliases for authenticating the either side of a secure
 329      * socket given the public key type and the list of
 330      * certificate issuer authorities recognized by the peer (if any).
 331      *
 332      * Issuers comes to us in the form of X500Principal[].
 333      */
 334     private String[] getAliases(String keyType, Principal[] issuers) {
 335         if (keyType == null) {
 336             return null;
 337         }
 338         if (issuers == null) {
 339             issuers = new X500Principal[0];
 340         }
 341         if (issuers instanceof X500Principal[] == false) {
 342             // normally, this will never happen but try to recover if it does
 343             issuers = convertPrincipals(issuers);
 344         }
 345         String sigType;
 346         if (keyType.contains("_")) {
 347             int k = keyType.indexOf('_');
 348             sigType = keyType.substring(k + 1);
 349             keyType = keyType.substring(0, k);
 350         } else {
 351             sigType = null;
 352         }
 353 
 354         X500Principal[] x500Issuers = (X500Principal[])issuers;
 355         // the algorithm below does not produce duplicates, so avoid Set
 356         List<String> aliases = new ArrayList<>();
 357 
 358         for (Map.Entry<String,X509Credentials> entry :
 359                                                 credentialsMap.entrySet()) {
 360 
 361             String alias = entry.getKey();
 362             X509Credentials credentials = entry.getValue();
 363             X509Certificate[] certs = credentials.certificates;
 364 
 365             if (!keyType.equals(certs[0].getPublicKey().getAlgorithm())) {
 366                 continue;
 367             }
 368             if (sigType != null) {
 369                 if (certs.length > 1) {
 370                     // if possible, check the public key in the issuer cert
 371                     if (!sigType.equals(
 372                             certs[1].getPublicKey().getAlgorithm())) {
 373                         continue;
 374                     }
 375                 } else {
 376                     // Check the signature algorithm of the certificate itself.
 377                     // Look for the "withRSA" in "SHA1withRSA", etc.
 378                     String sigAlgName =
 379                         certs[0].getSigAlgName().toUpperCase(Locale.ENGLISH);
 380                     String pattern = "WITH" +
 381                         sigType.toUpperCase(Locale.ENGLISH);
 382                     if (sigAlgName.contains(pattern) == false) {
 383                         continue;
 384                     }
 385                 }
 386             }
 387 
 388             if (issuers.length == 0) {
 389                 // no issuer specified, match all
 390                 aliases.add(alias);
 391                 if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
 392                     SSLLogger.fine("matching alias: " + alias);
 393                 }
 394             } else {
 395                 Set<X500Principal> certIssuers =
 396                                         credentials.getIssuerX500Principals();
 397                 for (int i = 0; i < x500Issuers.length; i++) {
 398                     if (certIssuers.contains(issuers[i])) {
 399                         aliases.add(alias);
 400                         if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
 401                             SSLLogger.fine("matching alias: " + alias);
 402                         }
 403                         break;
 404                     }
 405                 }
 406             }
 407         }
 408 
 409         String[] aliasStrings = aliases.toArray(STRING0);
 410         return ((aliasStrings.length == 0) ? null : aliasStrings);
 411     }
 412 
 413     /*
 414      * Convert an array of Principals to an array of X500Principals, if
 415      * possible. Principals that cannot be converted are ignored.
 416      */
 417     private static X500Principal[] convertPrincipals(Principal[] principals) {
 418         List<X500Principal> list = new ArrayList<>(principals.length);
 419         for (int i = 0; i < principals.length; i++) {
 420             Principal p = principals[i];
 421             if (p instanceof X500Principal) {
 422                 list.add((X500Principal)p);
 423             } else {
 424                 try {
 425                     list.add(new X500Principal(p.getName()));
 426                 } catch (IllegalArgumentException e) {
 427                     // ignore
 428                 }
 429             }
 430         }
 431         return list.toArray(new X500Principal[list.size()]);
 432     }
 433 }