blob: d7119fff170faf8bb4c22262d7a1637e38268731 [file] [log] [blame]
Brian Carlstromb9a07c12011-04-11 09:03:51 -07001/*
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 */
16package android.security;
17
Brian Carlstromba1a6672011-05-24 21:54:37 -070018import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070019import android.app.PendingIntent;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070020import android.content.ComponentName;
21import android.content.Context;
22import android.content.Intent;
23import android.content.ServiceConnection;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070024import android.os.IBinder;
25import android.os.Looper;
26import android.os.RemoteException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070027import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070028import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080029import java.security.InvalidKeyException;
Brian Carlstrom93201f52011-06-09 15:05:35 -070030import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070031import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070032import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import java.security.cert.CertificateException;
34import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070035import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070036import java.util.List;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070037import java.util.concurrent.BlockingQueue;
38import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080039
40import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine;
Brian Carlstromdb93b782011-07-01 00:12:17 -070041import org.apache.harmony.xnet.provider.jsse.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042
43/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070044 * The {@code KeyChain} class provides access to private keys and
45 * their corresponding certificate chains in credential storage.
46 *
47 * <p>Applications accessing the {@code KeyChain} normally go through
48 * these steps:
49 *
50 * <ol>
51 *
52 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
53 * X509KeyManager} that a private key is requested.
54 *
55 * <li>Call {@link #choosePrivateKeyAlias
56 * choosePrivateKeyAlias} to allow the user to select from a
57 * list of currently available private keys and corresponding
58 * certificate chains. The chosen alias will be returned by the
59 * callback {@link KeyChainAliasCallback#alias}, or null if no private
60 * key is available or the user cancels the request.
61 *
62 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
63 * retrieve the credentials to return to the corresponding {@link
64 * javax.net.ssl.X509KeyManager} callbacks.
65 *
66 * </ol>
67 *
68 * <p>An application may remember the value of a selected alias to
69 * avoid prompting the user with {@link #choosePrivateKeyAlias
70 * choosePrivateKeyAlias} on subsequent connections. If the alias is
71 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070072 *
73 * <p>An application can request the installation of private keys and
74 * certificates via the {@code Intent} provided by {@link
75 * #createInstallIntent}. Private keys installed via this {@code
76 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
77 * Certificate Authority (CA) certificates will be trusted by all
78 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070079 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070080// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070081public final class KeyChain {
82
83 private static final String TAG = "KeyChain";
84
85 /**
86 * @hide Also used by KeyChainService implementation
87 */
88 public static final String ACCOUNT_TYPE = "com.android.keychain";
89
90 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -070091 * Action to bring up the KeyChainActivity
92 */
93 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
94
95 /**
96 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -070097 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -070098 */
Brian Carlstromba1a6672011-05-24 21:54:37 -070099 public static final String EXTRA_RESPONSE = "response";
100
101 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700102 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700103 * @hide Also used by KeyChainActivity implementation
104 */
105 public static final String EXTRA_HOST = "host";
106
107 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700108 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700109 * @hide Also used by KeyChainActivity implementation
110 */
111 public static final String EXTRA_PORT = "port";
112
113 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700114 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700115 * @hide Also used by KeyChainActivity implementation
116 */
117 public static final String EXTRA_ALIAS = "alias";
118
119 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700120 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700121 * @hide Also used by KeyChainActivity implementation
122 */
123 public static final String EXTRA_SENDER = "sender";
124
125 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800126 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700127 */
128 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
129
130 /**
131 * Optional extra to specify a {@code String} credential name on
132 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700133 */
134 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
135 public static final String EXTRA_NAME = "name";
136
137 /**
138 * Optional extra to specify an X.509 certificate to install on
139 * the {@code Intent} returned by {@link #createInstallIntent}.
140 * The extra value should be a PEM or ASN.1 DER encoded {@code
141 * byte[]}. An {@link X509Certificate} can be converted to DER
142 * encoded bytes with {@link X509Certificate#getEncoded}.
143 *
144 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
145 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700146 */
147 // Compatible with old android.security.Credentials.CERTIFICATE
148 public static final String EXTRA_CERTIFICATE = "CERT";
149
150 /**
151 * Optional extra for use with the {@code Intent} returned by
152 * {@link #createInstallIntent} to specify a PKCS#12 key store to
153 * install. The extra value should be a {@code byte[]}. The bytes
154 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700155 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700156 *
157 * <p>The user will be prompted for the password to load the key store.
158 *
159 * <p>The key store will be scanned for {@link
160 * java.security.KeyStore.PrivateKeyEntry} entries and both the
161 * private key and associated certificate chain will be installed.
162 *
163 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
164 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700165 */
166 // Compatible with old android.security.Credentials.PKCS12
167 public static final String EXTRA_PKCS12 = "PKCS12";
168
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800169
170 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800171 * Broadcast Action: Indicates the trusted storage has changed. Sent when
172 * one of this happens:
173 *
174 * <ul>
175 * <li>a new CA is added,
176 * <li>an existing CA is removed or disabled,
177 * <li>a disabled CA is enabled,
178 * <li>trusted storage is reset (all user certs are cleared),
179 * <li>when permission to access a private key is changed.
180 * </ul>
181 */
182 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
183
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700184 /**
185 * Returns an {@code Intent} that can be used for credential
186 * installation. The intent may be used without any extras, in
187 * which case the user will be able to install credentials from
188 * their own source.
189 *
190 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
191 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
192 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700193 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700194 * default alias name for credentials being installed.
195 *
196 * <p>When used with {@link Activity#startActivityForResult},
197 * {@link Activity#RESULT_OK} will be returned if a credential was
198 * successfully installed, otherwise {@link
199 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700200 */
201 public static Intent createInstallIntent() {
202 Intent intent = new Intent(ACTION_INSTALL);
203 intent.setClassName("com.android.certinstaller",
204 "com.android.certinstaller.CertInstallerMain");
205 return intent;
206 }
207
208 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700209 * Launches an {@code Activity} for the user to select the alias
210 * for a private key and certificate pair for authentication. The
211 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700212 * KeyChainAliasCallback callback.
213 *
214 * <p>{@code keyTypes} and {@code issuers} may be used to
215 * highlight suggested choices to the user, although to cope with
216 * sometimes erroneous values provided by servers, the user may be
217 * able to override these suggestions.
218 *
219 * <p>{@code host} and {@code port} may be used to give the user
220 * more context about the server requesting the credentials.
221 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700222 * <p>{@code alias} allows the chooser to preselect an existing
223 * alias which will still be subject to user confirmation.
224 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700225 * @param activity The {@link Activity} context to use for
226 * launching the new sub-Activity to prompt the user to select
227 * a private key; used only to call startActivity(); must not
228 * be null.
229 * @param response Callback to invoke when the request completes;
230 * must not be null
231 * @param keyTypes The acceptable types of asymmetric keys such as
232 * "RSA" or "DSA", or a null array.
233 * @param issuers The acceptable certificate issuers for the
234 * certificate matching the private key, or null.
235 * @param host The host name of the server requesting the
236 * certificate, or null if unavailable.
237 * @param port The port number of the server requesting the
238 * certificate, or -1 if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700239 * @param alias The alias to preselect if available, or null if
240 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700241 */
Brian Carlstrom93201f52011-06-09 15:05:35 -0700242 public static void choosePrivateKeyAlias(Activity activity, KeyChainAliasCallback response,
243 String[] keyTypes, Principal[] issuers,
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700244 String host, int port,
245 String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700246 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700247 * TODO currently keyTypes, issuers are unused. They are meant
248 * to follow the semantics and purpose of X509KeyManager
249 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700250 *
251 * keyTypes would allow the list to be filtered and typically
252 * will be set correctly by the server. In practice today,
253 * most all users will want only RSA, rarely DSA, and usually
254 * only a small number of certs will be available.
255 *
256 * issuers is typically not useful. Some servers historically
257 * will send the entire list of public CAs known to the
258 * server. Others will send none. If this is used, if there
259 * are no matches after applying the constraint, it should be
260 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700261 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700262 if (activity == null) {
263 throw new NullPointerException("activity == null");
264 }
265 if (response == null) {
266 throw new NullPointerException("response == null");
267 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700268 Intent intent = new Intent(ACTION_CHOOSER);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700269 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700270 intent.putExtra(EXTRA_HOST, host);
271 intent.putExtra(EXTRA_PORT, port);
272 intent.putExtra(EXTRA_ALIAS, alias);
273 // the PendingIntent is used to get calling package name
274 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700275 activity.startActivity(intent);
276 }
277
Brian Carlstrom93201f52011-06-09 15:05:35 -0700278 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700279 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700280 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700281 this.keyChainAliasResponse = keyChainAliasResponse;
282 }
283 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700284 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700285 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700286 }
287
288 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700289 * Returns the {@code PrivateKey} for the requested alias, or null
290 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700291 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700292 * @param alias The alias of the desired private key, typically
293 * returned via {@link KeyChainAliasCallback#alias}.
294 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700295 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700296 public static PrivateKey getPrivateKey(Context context, String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700297 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700298 if (alias == null) {
299 throw new NullPointerException("alias == null");
300 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700301 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700302 try {
Kenny Root5423e682011-11-14 08:43:13 -0800303 final IKeyChainService keyChainService = keyChainConnection.getService();
304 final String keyId = keyChainService.requestPrivateKey(alias);
305 if (keyId == null) {
306 throw new KeyChainException("keystore had a problem");
307 }
308
309 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
310 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700311 } catch (RemoteException e) {
312 throw new KeyChainException(e);
313 } catch (RuntimeException e) {
314 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
315 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800316 } catch (InvalidKeyException e) {
317 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700318 } finally {
319 keyChainConnection.close();
320 }
321 }
322
323 /**
324 * Returns the {@code X509Certificate} chain for the requested
325 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700326 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700327 * @param alias The alias of the desired certificate chain, typically
328 * returned via {@link KeyChainAliasCallback#alias}.
329 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700330 */
331 public static X509Certificate[] getCertificateChain(Context context, String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700332 throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700333 if (alias == null) {
334 throw new NullPointerException("alias == null");
335 }
336 KeyChainConnection keyChainConnection = bind(context);
337 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700338 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800339
340 final byte[] certificateBytes = keyChainService.getCertificate(alias);
341 if (certificateBytes == null) {
342 return null;
343 }
344
Brian Carlstromdb93b782011-07-01 00:12:17 -0700345 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700346 List<X509Certificate> chain = store
347 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700348 return chain.toArray(new X509Certificate[chain.size()]);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700349 } catch (RemoteException e) {
350 throw new KeyChainException(e);
351 } catch (RuntimeException e) {
352 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
353 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700354 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700355 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700356 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700357 }
358
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700359 private static X509Certificate toCertificate(byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700360 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700361 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700362 }
363 try {
364 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
365 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
366 return (X509Certificate) cert;
367 } catch (CertificateException e) {
368 throw new AssertionError(e);
369 }
370 }
371
Brian Carlstromd7524722011-05-17 16:20:36 -0700372 /**
373 * @hide for reuse by CertInstaller and Settings.
374 * @see KeyChain#bind
375 */
376 public final static class KeyChainConnection implements Closeable {
377 private final Context context;
378 private final ServiceConnection serviceConnection;
379 private final IKeyChainService service;
380 private KeyChainConnection(Context context,
381 ServiceConnection serviceConnection,
382 IKeyChainService service) {
383 this.context = context;
384 this.serviceConnection = serviceConnection;
385 this.service = service;
386 }
387 @Override public void close() {
388 context.unbindService(serviceConnection);
389 }
390 public IKeyChainService getService() {
391 return service;
392 }
393 }
394
395 /**
396 * @hide for reuse by CertInstaller and Settings.
397 *
398 * Caller should call unbindService on the result when finished.
399 */
400 public static KeyChainConnection bind(Context context) throws InterruptedException {
401 if (context == null) {
402 throw new NullPointerException("context == null");
403 }
404 ensureNotOnMainThread(context);
405 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
406 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700407 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700408 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700409 if (!mConnectedAtLeastOnce) {
410 mConnectedAtLeastOnce = true;
411 try {
412 q.put(IKeyChainService.Stub.asInterface(service));
413 } catch (InterruptedException e) {
414 // will never happen, since the queue starts with one available slot
415 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700416 }
417 }
418 @Override public void onServiceDisconnected(ComponentName name) {}
419 };
420 boolean isBound = context.bindService(new Intent(IKeyChainService.class.getName()),
421 keyChainServiceConnection,
422 Context.BIND_AUTO_CREATE);
423 if (!isBound) {
424 throw new AssertionError("could not bind to KeyChainService");
425 }
426 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
427 }
428
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700429 private static void ensureNotOnMainThread(Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700430 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700431 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700432 throw new IllegalStateException(
433 "calling this from your main thread can lead to deadlock");
434 }
435 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700436}