KeyManagerImpl.java 8.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
Kenny Root's avatar
Kenny Root committed
17
package org.conscrypt;
18 19 20

import java.net.Socket;
import java.security.KeyStore;
Jesse Wilson's avatar
Jesse Wilson committed
21
import java.security.KeyStore.PrivateKeyEntry;
22 23 24 25 26 27 28
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
29
import java.util.ArrayList;
Brian Carlstrom's avatar
Brian Carlstrom committed
30
import java.util.Arrays;
31 32
import java.util.Enumeration;
import java.util.Hashtable;
Brian Carlstrom's avatar
Brian Carlstrom committed
33
import java.util.List;
34
import java.util.Locale;
35 36 37 38 39 40
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.security.auth.x500.X500Principal;

/**
 * KeyManager implementation.
41
 *
42 43 44 45
 * This implementation uses hashed key store information. It works faster than retrieving all of the
 * data from the key store. Any key store changes, that happen after key manager was created, have
 * no effect. The implementation does not use peer information (host, port) that may be obtained
 * from socket or engine.
46
 *
47
 * @see javax.net.ssl.KeyManager
48
 *
49 50 51 52
 */
public class KeyManagerImpl extends X509ExtendedKeyManager {

    // hashed key store information
53
    private final Hashtable<String, PrivateKeyEntry> hash;
54 55 56

    /**
     * Creates Key manager
57
     *
58 59 60 61
     * @param keyStore
     * @param pwd
     */
    public KeyManagerImpl(KeyStore keyStore, char[] pwd) {
62 63
        this.hash = new Hashtable<String, PrivateKeyEntry>();
        final Enumeration<String> aliases;
64 65 66 67 68 69
        try {
            aliases = keyStore.aliases();
        } catch (KeyStoreException e) {
            return;
        }
        for (; aliases.hasMoreElements();) {
70
            final String alias = aliases.nextElement();
71
            try {
72 73 74
                if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
                    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
                            .getEntry(alias, new KeyStore.PasswordProtection(pwd));
75 76 77 78 79 80 81 82 83 84 85 86
                    hash.put(alias, entry);
                }
            } catch (KeyStoreException e) {
                continue;
            } catch (UnrecoverableEntryException e) {
                continue;
            } catch (NoSuchAlgorithmException e) {
                continue;
            }
        }
    }

Kenny Root's avatar
Kenny Root committed
87
    @Override
88 89
    public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
        final String[] al = chooseAlias(keyTypes, issuers);
90
        return (al == null ? null : al[0]);
91 92
    }

Kenny Root's avatar
Kenny Root committed
93
    @Override
94 95 96
    public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
        final String[] al = chooseAlias(new String[] { keyType }, issuers);
        return (al == null ? null : al[0]);
97 98
    }

Kenny Root's avatar
Kenny Root committed
99
    @Override
100 101 102 103 104
    public X509Certificate[] getCertificateChain(String alias) {
        if (alias == null) {
            return null;
        }
        if (hash.containsKey(alias)) {
105
            Certificate[] certs = hash.get(alias).getCertificateChain();
106 107 108 109 110 111 112 113 114 115 116 117
            if (certs[0] instanceof X509Certificate) {
                X509Certificate[] xcerts = new X509Certificate[certs.length];
                for (int i = 0; i < certs.length; i++) {
                    xcerts[i] = (X509Certificate) certs[i];
                }
                return xcerts;
            }
        }
        return null;

    }

Kenny Root's avatar
Kenny Root committed
118
    @Override
119 120 121 122
    public String[] getClientAliases(String keyType, Principal[] issuers) {
        return chooseAlias(new String[] { keyType }, issuers);
    }

Kenny Root's avatar
Kenny Root committed
123
    @Override
124 125 126 127
    public String[] getServerAliases(String keyType, Principal[] issuers) {
        return chooseAlias(new String[] { keyType }, issuers);
    }

Kenny Root's avatar
Kenny Root committed
128
    @Override
129 130 131 132 133
    public PrivateKey getPrivateKey(String alias) {
        if (alias == null) {
            return null;
        }
        if (hash.containsKey(alias)) {
134
            return hash.get(alias).getPrivateKey();
135 136 137 138
        }
        return null;
    }

139
    @Override
140 141
    public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, SSLEngine engine) {
        final String[] al = chooseAlias(keyTypes, issuers);
142
        return (al == null ? null : al[0]);
143 144
    }

145 146 147 148
    @Override
    public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
        final String[] al = chooseAlias(new String[] { keyType }, issuers);
        return (al == null ? null : al[0]);
149 150
    }

151 152
    private String[] chooseAlias(String[] keyTypes, Principal[] issuers) {
        if (keyTypes == null || keyTypes.length == 0) {
153 154
            return null;
        }
Brian Carlstrom's avatar
Brian Carlstrom committed
155
        List<Principal> issuersList = (issuers == null) ? null : Arrays.asList(issuers);
156
        ArrayList<String> found = new ArrayList<String>();
157 158 159
        for (Enumeration<String> aliases = hash.keys(); aliases.hasMoreElements();) {
            final String alias = aliases.nextElement();
            final KeyStore.PrivateKeyEntry entry = hash.get(alias);
Brian Carlstrom's avatar
Brian Carlstrom committed
160 161 162 163
            final Certificate[] chain = entry.getCertificateChain();
            final Certificate cert = chain[0];
            final String certKeyAlg = cert.getPublicKey().getAlgorithm();
            final String certSigAlg = (cert instanceof X509Certificate
164
                                       ? ((X509Certificate) cert).getSigAlgName().toUpperCase(Locale.US)
Brian Carlstrom's avatar
Brian Carlstrom committed
165
                                       : null);
166 167 168 169
            for (String keyAlgorithm : keyTypes) {
                if (keyAlgorithm == null) {
                    continue;
                }
170
                final String sigAlgorithm;
Brian Carlstrom's avatar
Brian Carlstrom committed
171 172 173
                // handle cases like EC_EC and EC_RSA
                int index = keyAlgorithm.indexOf('_');
                if (index == -1) {
174
                    sigAlgorithm = null;
Brian Carlstrom's avatar
Brian Carlstrom committed
175 176 177 178 179 180
                } else {
                    sigAlgorithm = keyAlgorithm.substring(index + 1);
                    keyAlgorithm = keyAlgorithm.substring(0, index);
                }
                // key algorithm does not match
                if (!certKeyAlg.equals(keyAlgorithm)) {
181
                    continue;
Brian Carlstrom's avatar
Brian Carlstrom committed
182 183 184 185 186 187 188 189
                }
                /*
                 * TODO find a more reliable test for signature
                 * algorithm. Unfortunately value varies with
                 * provider. For example for "EC" it could be
                 * "SHA1WithECDSA" or simply "ECDSA".
                 */
                // sig algorithm does not match
190 191
                if (sigAlgorithm != null && certSigAlg != null
                        && !certSigAlg.contains(sigAlgorithm)) {
Brian Carlstrom's avatar
Brian Carlstrom committed
192 193 194 195 196 197 198 199
                    continue;
                }
                // no issuers to match, just add to return list and continue
                if (issuers == null || issuers.length == 0) {
                    found.add(alias);
                    continue;
                }
                // check that a certificate in the chain was issued by one of the specified issuers
200
                for (Certificate certFromChain : chain) {
Brian Carlstrom's avatar
Brian Carlstrom committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
                    if (!(certFromChain instanceof X509Certificate)) {
                        // skip non-X509Certificates
                        continue;
                    }
                    X509Certificate xcertFromChain = (X509Certificate) certFromChain;
                    /*
                     * Note use of X500Principal from
                     * getIssuerX500Principal as opposed to Principal
                     * from getIssuerDN. Principal.equals test does
                     * not work in the case where
                     * xcertFromChain.getIssuerDN is a bouncycastle
                     * org.bouncycastle.jce.X509Principal.
                     */
                    X500Principal issuerFromChain = xcertFromChain.getIssuerX500Principal();
                    if (issuersList.contains(issuerFromChain)) {
216 217 218 219 220
                        found.add(alias);
                    }
                }
            }
        }
221 222
        if (!found.isEmpty()) {
            return found.toArray(new String[found.size()]);
223
        }
224
        return null;
225 226
    }
}