• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.security;
17 
18 import android.app.Activity;
19 import android.app.PendingIntent;
20 import android.content.ComponentName;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.ServiceConnection;
24 import android.os.IBinder;
25 import android.os.Looper;
26 import android.os.RemoteException;
27 import java.io.ByteArrayInputStream;
28 import java.io.Closeable;
29 import java.io.IOException;
30 import java.security.KeyPair;
31 import java.security.Principal;
32 import java.security.PrivateKey;
33 import java.security.cert.Certificate;
34 import java.security.cert.CertificateException;
35 import java.security.cert.CertificateFactory;
36 import java.security.cert.X509Certificate;
37 import java.util.ArrayList;
38 import java.util.List;
39 import java.util.concurrent.BlockingQueue;
40 import java.util.concurrent.LinkedBlockingQueue;
41 import libcore.util.Objects;
42 import org.apache.harmony.xnet.provider.jsse.TrustedCertificateStore;
43 
44 /**
45  * The {@code KeyChain} class provides access to private keys and
46  * their corresponding certificate chains in credential storage.
47  *
48  * <p>Applications accessing the {@code KeyChain} normally go through
49  * these steps:
50  *
51  * <ol>
52  *
53  * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
54  * X509KeyManager} that a private key is requested.
55  *
56  * <li>Call {@link #choosePrivateKeyAlias
57  * choosePrivateKeyAlias} to allow the user to select from a
58  * list of currently available private keys and corresponding
59  * certificate chains. The chosen alias will be returned by the
60  * callback {@link KeyChainAliasCallback#alias}, or null if no private
61  * key is available or the user cancels the request.
62  *
63  * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
64  * retrieve the credentials to return to the corresponding {@link
65  * javax.net.ssl.X509KeyManager} callbacks.
66  *
67  * </ol>
68  *
69  * <p>An application may remember the value of a selected alias to
70  * avoid prompting the user with {@link #choosePrivateKeyAlias
71  * choosePrivateKeyAlias} on subsequent connections. If the alias is
72  * no longer valid, null will be returned on lookups using that value
73  *
74  * <p>An application can request the installation of private keys and
75  * certificates via the {@code Intent} provided by {@link
76  * #createInstallIntent}. Private keys installed via this {@code
77  * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
78  * Certificate Authority (CA) certificates will be trusted by all
79  * applications through the default {@code X509TrustManager}.
80  */
81 // TODO reference intent for credential installation when public
82 public final class KeyChain {
83 
84     private static final String TAG = "KeyChain";
85 
86     /**
87      * @hide Also used by KeyChainService implementation
88      */
89     public static final String ACCOUNT_TYPE = "com.android.keychain";
90 
91     /**
92      * Action to bring up the KeyChainActivity
93      */
94     private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
95 
96     /**
97      * Extra for use with {@link #ACTION_CHOOSER}
98      * @hide Also used by KeyChainActivity implementation
99      */
100     public static final String EXTRA_RESPONSE = "response";
101 
102     /**
103      * Extra for use with {@link #ACTION_CHOOSER}
104      * @hide Also used by KeyChainActivity implementation
105      */
106     public static final String EXTRA_HOST = "host";
107 
108     /**
109      * Extra for use with {@link #ACTION_CHOOSER}
110      * @hide Also used by KeyChainActivity implementation
111      */
112     public static final String EXTRA_PORT = "port";
113 
114     /**
115      * Extra for use with {@link #ACTION_CHOOSER}
116      * @hide Also used by KeyChainActivity implementation
117      */
118     public static final String EXTRA_ALIAS = "alias";
119 
120     /**
121      * Extra for use with {@link #ACTION_CHOOSER}
122      * @hide Also used by KeyChainActivity implementation
123      */
124     public static final String EXTRA_SENDER = "sender";
125 
126     /**
127      * Action to bring up the CertInstaller
128      */
129     private static final String ACTION_INSTALL = "android.credentials.INSTALL";
130 
131     /**
132      * Optional extra to specify a {@code String} credential name on
133      * the {@code Intent} returned by {@link #createInstallIntent}.
134      */
135     // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
136     public static final String EXTRA_NAME = "name";
137 
138     /**
139      * Optional extra to specify an X.509 certificate to install on
140      * the {@code Intent} returned by {@link #createInstallIntent}.
141      * The extra value should be a PEM or ASN.1 DER encoded {@code
142      * byte[]}. An {@link X509Certificate} can be converted to DER
143      * encoded bytes with {@link X509Certificate#getEncoded}.
144      *
145      * <p>{@link #EXTRA_NAME} may be used to provide a default alias
146      * name for the installed certificate.
147      */
148     // Compatible with old android.security.Credentials.CERTIFICATE
149     public static final String EXTRA_CERTIFICATE = "CERT";
150 
151     /**
152      * Optional extra for use with the {@code Intent} returned by
153      * {@link #createInstallIntent} to specify a PKCS#12 key store to
154      * install. The extra value should be a {@code byte[]}. The bytes
155      * may come from an external source or be generated with {@link
156      * java.security.KeyStore#store} on a "PKCS12" instance.
157      *
158      * <p>The user will be prompted for the password to load the key store.
159      *
160      * <p>The key store will be scanned for {@link
161      * java.security.KeyStore.PrivateKeyEntry} entries and both the
162      * private key and associated certificate chain will be installed.
163      *
164      * <p>{@link #EXTRA_NAME} may be used to provide a default alias
165      * name for the installed credentials.
166      */
167     // Compatible with old android.security.Credentials.PKCS12
168     public static final String EXTRA_PKCS12 = "PKCS12";
169 
170     /**
171      * Returns an {@code Intent} that can be used for credential
172      * installation. The intent may be used without any extras, in
173      * which case the user will be able to install credentials from
174      * their own source.
175      *
176      * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
177      * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
178      * certificate or a PKCS#12 key store for installation. These
179      * extras may be combined with {@link #EXTRA_NAME} to provide a
180      * default alias name for credentials being installed.
181      *
182      * <p>When used with {@link Activity#startActivityForResult},
183      * {@link Activity#RESULT_OK} will be returned if a credential was
184      * successfully installed, otherwise {@link
185      * Activity#RESULT_CANCELED} will be returned.
186      */
createInstallIntent()187     public static Intent createInstallIntent() {
188         Intent intent = new Intent(ACTION_INSTALL);
189         intent.setClassName("com.android.certinstaller",
190                             "com.android.certinstaller.CertInstallerMain");
191         return intent;
192     }
193 
194     /**
195      * Launches an {@code Activity} for the user to select the alias
196      * for a private key and certificate pair for authentication. The
197      * selected alias or null will be returned via the
198      * KeyChainAliasCallback callback.
199      *
200      * <p>{@code keyTypes} and {@code issuers} may be used to
201      * highlight suggested choices to the user, although to cope with
202      * sometimes erroneous values provided by servers, the user may be
203      * able to override these suggestions.
204      *
205      * <p>{@code host} and {@code port} may be used to give the user
206      * more context about the server requesting the credentials.
207      *
208      * <p>{@code alias} allows the chooser to preselect an existing
209      * alias which will still be subject to user confirmation.
210      *
211      * <p>This method requires the caller to hold the permission
212      * {@link android.Manifest.permission#USE_CREDENTIALS}.
213      *
214      * @param activity The {@link Activity} context to use for
215      *     launching the new sub-Activity to prompt the user to select
216      *     a private key; used only to call startActivity(); must not
217      *     be null.
218      * @param response Callback to invoke when the request completes;
219      *     must not be null
220      * @param keyTypes The acceptable types of asymmetric keys such as
221      *     "RSA" or "DSA", or a null array.
222      * @param issuers The acceptable certificate issuers for the
223      *     certificate matching the private key, or null.
224      * @param host The host name of the server requesting the
225      *     certificate, or null if unavailable.
226      * @param port The port number of the server requesting the
227      *     certificate, or -1 if unavailable.
228      * @param alias The alias to preselect if available, or null if
229      *     unavailable.
230      */
choosePrivateKeyAlias(Activity activity, KeyChainAliasCallback response, String[] keyTypes, Principal[] issuers, String host, int port, String alias)231     public static void choosePrivateKeyAlias(Activity activity, KeyChainAliasCallback response,
232                                              String[] keyTypes, Principal[] issuers,
233                                              String host, int port,
234                                              String alias) {
235         /*
236          * TODO currently keyTypes, issuers are unused. They are meant
237          * to follow the semantics and purpose of X509KeyManager
238          * method arguments.
239          *
240          * keyTypes would allow the list to be filtered and typically
241          * will be set correctly by the server. In practice today,
242          * most all users will want only RSA, rarely DSA, and usually
243          * only a small number of certs will be available.
244          *
245          * issuers is typically not useful. Some servers historically
246          * will send the entire list of public CAs known to the
247          * server. Others will send none. If this is used, if there
248          * are no matches after applying the constraint, it should be
249          * ignored.
250          */
251         if (activity == null) {
252             throw new NullPointerException("activity == null");
253         }
254         if (response == null) {
255             throw new NullPointerException("response == null");
256         }
257         Intent intent = new Intent(ACTION_CHOOSER);
258         intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
259         intent.putExtra(EXTRA_HOST, host);
260         intent.putExtra(EXTRA_PORT, port);
261         intent.putExtra(EXTRA_ALIAS, alias);
262         // the PendingIntent is used to get calling package name
263         intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
264         activity.startActivity(intent);
265     }
266 
267     private static class AliasResponse extends IKeyChainAliasCallback.Stub {
268         private final KeyChainAliasCallback keyChainAliasResponse;
AliasResponse(KeyChainAliasCallback keyChainAliasResponse)269         private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
270             this.keyChainAliasResponse = keyChainAliasResponse;
271         }
alias(String alias)272         @Override public void alias(String alias) {
273             keyChainAliasResponse.alias(alias);
274         }
275     }
276 
277     /**
278      * Returns the {@code PrivateKey} for the requested alias, or null
279      * if no there is no result.
280      *
281      * <p>This method requires the caller to hold the permission
282      * {@link android.Manifest.permission#USE_CREDENTIALS}.
283      *
284      * @param alias The alias of the desired private key, typically
285      * returned via {@link KeyChainAliasCallback#alias}.
286      * @throws KeyChainException if the alias was valid but there was some problem accessing it.
287      */
getPrivateKey(Context context, String alias)288     public static PrivateKey getPrivateKey(Context context, String alias)
289             throws KeyChainException, InterruptedException {
290         if (alias == null) {
291             throw new NullPointerException("alias == null");
292         }
293         KeyChainConnection keyChainConnection = bind(context);
294         try {
295             IKeyChainService keyChainService = keyChainConnection.getService();
296             byte[] privateKeyBytes = keyChainService.getPrivateKey(alias);
297             return toPrivateKey(privateKeyBytes);
298         } catch (RemoteException e) {
299             throw new KeyChainException(e);
300         } catch (RuntimeException e) {
301             // only certain RuntimeExceptions can be propagated across the IKeyChainService call
302             throw new KeyChainException(e);
303         } finally {
304             keyChainConnection.close();
305         }
306     }
307 
308     /**
309      * Returns the {@code X509Certificate} chain for the requested
310      * alias, or null if no there is no result.
311      *
312      * <p>This method requires the caller to hold the permission
313      * {@link android.Manifest.permission#USE_CREDENTIALS}.
314      *
315      * @param alias The alias of the desired certificate chain, typically
316      * returned via {@link KeyChainAliasCallback#alias}.
317      * @throws KeyChainException if the alias was valid but there was some problem accessing it.
318      */
getCertificateChain(Context context, String alias)319     public static X509Certificate[] getCertificateChain(Context context, String alias)
320             throws KeyChainException, InterruptedException {
321         if (alias == null) {
322             throw new NullPointerException("alias == null");
323         }
324         KeyChainConnection keyChainConnection = bind(context);
325         try {
326             IKeyChainService keyChainService = keyChainConnection.getService();
327             byte[] certificateBytes = keyChainService.getCertificate(alias);
328             List<X509Certificate> chain = new ArrayList<X509Certificate>();
329             chain.add(toCertificate(certificateBytes));
330             TrustedCertificateStore store = new TrustedCertificateStore();
331             for (int i = 0; true; i++) {
332                 X509Certificate cert = chain.get(i);
333                 if (Objects.equal(cert.getSubjectX500Principal(), cert.getIssuerX500Principal())) {
334                     break;
335                 }
336                 X509Certificate issuer = store.findIssuer(cert);
337                 if (issuer == null) {
338                     break;
339                 }
340                 chain.add(issuer);
341             }
342             return chain.toArray(new X509Certificate[chain.size()]);
343         } catch (RemoteException e) {
344             throw new KeyChainException(e);
345         } catch (RuntimeException e) {
346             // only certain RuntimeExceptions can be propagated across the IKeyChainService call
347             throw new KeyChainException(e);
348         } finally {
349             keyChainConnection.close();
350         }
351     }
352 
toPrivateKey(byte[] bytes)353     private static PrivateKey toPrivateKey(byte[] bytes) {
354         if (bytes == null) {
355             throw new IllegalArgumentException("bytes == null");
356         }
357         try {
358             KeyPair keyPair = (KeyPair) Credentials.convertFromPem(bytes).get(0);
359             return keyPair.getPrivate();
360         } catch (IOException e) {
361             throw new AssertionError(e);
362         }
363     }
364 
toCertificate(byte[] bytes)365     private static X509Certificate toCertificate(byte[] bytes) {
366         if (bytes == null) {
367             throw new IllegalArgumentException("bytes == null");
368         }
369         try {
370             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
371             Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
372             return (X509Certificate) cert;
373         } catch (CertificateException e) {
374             throw new AssertionError(e);
375         }
376     }
377 
378     /**
379      * @hide for reuse by CertInstaller and Settings.
380      * @see KeyChain#bind
381      */
382     public final static class KeyChainConnection implements Closeable {
383         private final Context context;
384         private final ServiceConnection serviceConnection;
385         private final IKeyChainService service;
KeyChainConnection(Context context, ServiceConnection serviceConnection, IKeyChainService service)386         private KeyChainConnection(Context context,
387                                    ServiceConnection serviceConnection,
388                                    IKeyChainService service) {
389             this.context = context;
390             this.serviceConnection = serviceConnection;
391             this.service = service;
392         }
close()393         @Override public void close() {
394             context.unbindService(serviceConnection);
395         }
getService()396         public IKeyChainService getService() {
397             return service;
398         }
399     }
400 
401     /**
402      * @hide for reuse by CertInstaller and Settings.
403      *
404      * Caller should call unbindService on the result when finished.
405      */
bind(Context context)406     public static KeyChainConnection bind(Context context) throws InterruptedException {
407         if (context == null) {
408             throw new NullPointerException("context == null");
409         }
410         ensureNotOnMainThread(context);
411         final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
412         ServiceConnection keyChainServiceConnection = new ServiceConnection() {
413             volatile boolean mConnectedAtLeastOnce = false;
414             @Override public void onServiceConnected(ComponentName name, IBinder service) {
415                 if (!mConnectedAtLeastOnce) {
416                     mConnectedAtLeastOnce = true;
417                     try {
418                         q.put(IKeyChainService.Stub.asInterface(service));
419                     } catch (InterruptedException e) {
420                         // will never happen, since the queue starts with one available slot
421                     }
422                 }
423             }
424             @Override public void onServiceDisconnected(ComponentName name) {}
425         };
426         boolean isBound = context.bindService(new Intent(IKeyChainService.class.getName()),
427                                               keyChainServiceConnection,
428                                               Context.BIND_AUTO_CREATE);
429         if (!isBound) {
430             throw new AssertionError("could not bind to KeyChainService");
431         }
432         return new KeyChainConnection(context, keyChainServiceConnection, q.take());
433     }
434 
ensureNotOnMainThread(Context context)435     private static void ensureNotOnMainThread(Context context) {
436         Looper looper = Looper.myLooper();
437         if (looper != null && looper == context.getMainLooper()) {
438             throw new IllegalStateException(
439                     "calling this from your main thread can lead to deadlock");
440         }
441     }
442 }
443