1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17package org.conscrypt;
18
19import java.net.Socket;
20import java.security.KeyStore;
21import java.security.KeyStore.PrivateKeyEntry;
22import java.security.KeyStoreException;
23import java.security.NoSuchAlgorithmException;
24import java.security.Principal;
25import java.security.PrivateKey;
26import java.security.UnrecoverableEntryException;
27import java.security.cert.Certificate;
28import java.security.cert.X509Certificate;
29import java.util.ArrayList;
30import java.util.Arrays;
31import java.util.Enumeration;
32import java.util.Hashtable;
33import java.util.List;
34import java.util.Locale;
35import javax.net.ssl.SSLEngine;
36import javax.net.ssl.X509ExtendedKeyManager;
37import javax.security.auth.x500.X500Principal;
38
39/**
40 * KeyManager implementation.
41 *
42 * This implementation uses hashed key store information. It works faster than retrieving all of the
43 * data from the key store. Any key store changes, that happen after key manager was created, have
44 * no effect. The implementation does not use peer information (host, port) that may be obtained
45 * from socket or engine.
46 *
47 * @see javax.net.ssl.KeyManager
48 */
49class KeyManagerImpl extends X509ExtendedKeyManager {
50
51    // hashed key store information
52    private final Hashtable<String, PrivateKeyEntry> hash;
53
54    /**
55     * Creates Key manager
56     *
57     * @param keyStore
58     * @param pwd
59     */
60    KeyManagerImpl(KeyStore keyStore, char[] pwd) {
61        this.hash = new Hashtable<String, PrivateKeyEntry>();
62        final Enumeration<String> aliases;
63        try {
64            aliases = keyStore.aliases();
65        } catch (KeyStoreException e) {
66            return;
67        }
68        for (; aliases.hasMoreElements();) {
69            final String alias = aliases.nextElement();
70            try {
71                if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
72                    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
73                            .getEntry(alias, new KeyStore.PasswordProtection(pwd));
74                    hash.put(alias, entry);
75                }
76            } catch (KeyStoreException e) {
77                continue;
78            } catch (UnrecoverableEntryException e) {
79                continue;
80            } catch (NoSuchAlgorithmException e) {
81                continue;
82            }
83        }
84    }
85
86    @Override
87    public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
88        final String[] al = chooseAlias(keyTypes, issuers);
89        return (al == null ? null : al[0]);
90    }
91
92    @Override
93    public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
94        final String[] al = chooseAlias(new String[] { keyType }, issuers);
95        return (al == null ? null : al[0]);
96    }
97
98    @Override
99    public X509Certificate[] getCertificateChain(String alias) {
100        if (alias == null) {
101            return null;
102        }
103        if (hash.containsKey(alias)) {
104            Certificate[] certs = hash.get(alias).getCertificateChain();
105            if (certs[0] instanceof X509Certificate) {
106                X509Certificate[] xcerts = new X509Certificate[certs.length];
107                for (int i = 0; i < certs.length; i++) {
108                    xcerts[i] = (X509Certificate) certs[i];
109                }
110                return xcerts;
111            }
112        }
113        return null;
114
115    }
116
117    @Override
118    public String[] getClientAliases(String keyType, Principal[] issuers) {
119        return chooseAlias(new String[] { keyType }, issuers);
120    }
121
122    @Override
123    public String[] getServerAliases(String keyType, Principal[] issuers) {
124        return chooseAlias(new String[] { keyType }, issuers);
125    }
126
127    @Override
128    public PrivateKey getPrivateKey(String alias) {
129        if (alias == null) {
130            return null;
131        }
132        if (hash.containsKey(alias)) {
133            return hash.get(alias).getPrivateKey();
134        }
135        return null;
136    }
137
138    @Override
139    public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, SSLEngine engine) {
140        final String[] al = chooseAlias(keyTypes, issuers);
141        return (al == null ? null : al[0]);
142    }
143
144    @Override
145    public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
146        final String[] al = chooseAlias(new String[] { keyType }, issuers);
147        return (al == null ? null : al[0]);
148    }
149
150    private String[] chooseAlias(String[] keyTypes, Principal[] issuers) {
151        if (keyTypes == null || keyTypes.length == 0) {
152            return null;
153        }
154        List<Principal> issuersList = (issuers == null) ? null : Arrays.asList(issuers);
155        ArrayList<String> found = new ArrayList<String>();
156        for (Enumeration<String> aliases = hash.keys(); aliases.hasMoreElements();) {
157            final String alias = aliases.nextElement();
158            final KeyStore.PrivateKeyEntry entry = hash.get(alias);
159            final Certificate[] chain = entry.getCertificateChain();
160            final Certificate cert = chain[0];
161            final String certKeyAlg = cert.getPublicKey().getAlgorithm();
162            final String certSigAlg = (cert instanceof X509Certificate
163                                       ? ((X509Certificate) cert).getSigAlgName().toUpperCase(Locale.US)
164                                       : null);
165            for (String keyAlgorithm : keyTypes) {
166                if (keyAlgorithm == null) {
167                    continue;
168                }
169                final String sigAlgorithm;
170                // handle cases like EC_EC and EC_RSA
171                int index = keyAlgorithm.indexOf('_');
172                if (index == -1) {
173                    sigAlgorithm = null;
174                } else {
175                    sigAlgorithm = keyAlgorithm.substring(index + 1);
176                    keyAlgorithm = keyAlgorithm.substring(0, index);
177                }
178                // key algorithm does not match
179                if (!certKeyAlg.equals(keyAlgorithm)) {
180                    continue;
181                }
182                /*
183                 * TODO find a more reliable test for signature
184                 * algorithm. Unfortunately value varies with
185                 * provider. For example for "EC" it could be
186                 * "SHA1WithECDSA" or simply "ECDSA".
187                 */
188                // sig algorithm does not match
189                if (sigAlgorithm != null && certSigAlg != null
190                        && !certSigAlg.contains(sigAlgorithm)) {
191                    continue;
192                }
193                // no issuers to match, just add to return list and continue
194                if (issuers == null || issuers.length == 0) {
195                    found.add(alias);
196                    continue;
197                }
198                // check that a certificate in the chain was issued by one of the specified issuers
199                for (Certificate certFromChain : chain) {
200                    if (!(certFromChain instanceof X509Certificate)) {
201                        // skip non-X509Certificates
202                        continue;
203                    }
204                    X509Certificate xcertFromChain = (X509Certificate) certFromChain;
205                    /*
206                     * Note use of X500Principal from
207                     * getIssuerX500Principal as opposed to Principal
208                     * from getIssuerDN. Principal.equals test does
209                     * not work in the case where
210                     * xcertFromChain.getIssuerDN is a bouncycastle
211                     * org.bouncycastle.jce.X509Principal.
212                     */
213                    X500Principal issuerFromChain = xcertFromChain.getIssuerX500Principal();
214                    if (issuersList.contains(issuerFromChain)) {
215                        found.add(alias);
216                    }
217                }
218            }
219        }
220        if (!found.isEmpty()) {
221            return found.toArray(new String[found.size()]);
222        }
223        return null;
224    }
225}
226