blob: 7360531245b03b3871f31fbdabeaeeac05da8999 [file] [log] [blame]
Brian Carlstrom3e6251d2011-04-11 09:05:06 -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 */
16
17package com.android.keychain;
18
Brian Carlstrom65e649e2011-06-24 02:13:28 -070019import android.app.Activity;
Robin Leeb46e4932015-02-03 18:17:39 +000020import android.app.admin.IDevicePolicyManager;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070021import android.app.AlertDialog;
22import android.app.Dialog;
23import android.app.PendingIntent;
Robin Leeb46e4932015-02-03 18:17:39 +000024import android.content.Context;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070025import android.content.DialogInterface;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070026import android.content.Intent;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070027import android.content.pm.PackageManager;
28import android.content.res.Resources;
Robin Lee606d9d02015-05-05 15:57:13 +010029import android.net.Uri;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070030import android.os.AsyncTask;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070031import android.os.Bundle;
Robin Leeb46e4932015-02-03 18:17:39 +000032import android.os.IBinder;
33import android.os.RemoteException;
34import android.os.ServiceManager;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070035import android.security.Credentials;
Brian Carlstromf5b50a42011-06-09 16:05:09 -070036import android.security.IKeyChainAliasCallback;
Brian Carlstrombb04f702011-05-24 21:54:51 -070037import android.security.KeyChain;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070038import android.security.KeyStore;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070039import android.util.Log;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070040import android.view.LayoutInflater;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070041import android.view.View;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070042import android.view.ViewGroup;
Selim Gurun9c2b71c2012-03-22 15:51:14 -070043import android.widget.AdapterView;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070044import android.widget.BaseAdapter;
45import android.widget.Button;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070046import android.widget.ListView;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070047import android.widget.RadioButton;
48import android.widget.TextView;
Eran Messericdc828d2017-10-23 18:51:45 +010049import com.android.internal.annotations.VisibleForTesting;
Eran Messeri6cc717b2017-10-25 14:26:14 +010050import com.android.keychain.internal.KeyInfoProvider;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070051import com.android.org.bouncycastle.asn1.x509.X509Name;
52import java.io.ByteArrayInputStream;
53import java.io.InputStream;
54import java.security.cert.CertificateException;
55import java.security.cert.CertificateFactory;
56import java.security.cert.X509Certificate;
57import java.util.ArrayList;
58import java.util.Arrays;
59import java.util.Collections;
Robin Leeb46e4932015-02-03 18:17:39 +000060import java.util.concurrent.ExecutionException;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070061import java.util.List;
Eran Messeri6cc717b2017-10-25 14:26:14 +010062import java.util.stream.Collectors;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070063
Brian Carlstrom65e649e2011-06-24 02:13:28 -070064import javax.security.auth.x500.X500Principal;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070065
Brian Carlstrom65e649e2011-06-24 02:13:28 -070066public class KeyChainActivity extends Activity {
Fred Quintanafb2e18e2011-07-13 14:54:05 -070067 private static final String TAG = "KeyChain";
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070068
69 private static String KEY_STATE = "state";
70
71 private static final int REQUEST_UNLOCK = 1;
72
Fred Quintanafb2e18e2011-07-13 14:54:05 -070073 private int mSenderUid;
74
75 private PendingIntent mSender;
76
Kenny Root6ba32f22014-07-31 14:03:16 -070077 private static enum State { INITIAL, UNLOCK_REQUESTED, UNLOCK_CANCELED };
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070078
79 private State mState;
80
Brian Carlstrom65e649e2011-06-24 02:13:28 -070081 // beware that some of these KeyStore operations such as saw and
82 // get do file I/O in the remote keystore process and while they
83 // do not cause StrictMode violations, they logically should not
84 // be done on the UI thread.
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070085 private KeyStore mKeyStore = KeyStore.getInstance();
86
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070087 @Override public void onCreate(Bundle savedState) {
88 super.onCreate(savedState);
89 if (savedState == null) {
90 mState = State.INITIAL;
91 } else {
92 mState = (State) savedState.getSerializable(KEY_STATE);
93 if (mState == null) {
94 mState = State.INITIAL;
95 }
96 }
97 }
98
99 @Override public void onResume() {
100 super.onResume();
101
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700102 mSender = getIntent().getParcelableExtra(KeyChain.EXTRA_SENDER);
103 if (mSender == null) {
104 // if no sender, bail, we need to identify the app to the user securely.
105 finish(null);
106 return;
107 }
108 try {
109 mSenderUid = getPackageManager().getPackageInfo(
110 mSender.getIntentSender().getTargetPackage(), 0).applicationInfo.uid;
111 } catch (PackageManager.NameNotFoundException e) {
112 // if unable to find the sender package info bail,
113 // we need to identify the app to the user securely.
114 finish(null);
115 return;
116 }
117
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700118 // see if KeyStore has been unlocked, if not start activity to do so
119 switch (mState) {
120 case INITIAL:
Kenny Root4ff22962013-02-14 10:17:06 -0800121 if (!mKeyStore.isUnlocked()) {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700122 mState = State.UNLOCK_REQUESTED;
123 this.startActivityForResult(new Intent(Credentials.UNLOCK_ACTION),
124 REQUEST_UNLOCK);
125 // Note that Credentials.unlock will start an
126 // Activity and we will be paused but then resumed
127 // when the unlock Activity completes and our
128 // onActivityResult is called with REQUEST_UNLOCK
129 return;
130 }
Robin Leeb46e4932015-02-03 18:17:39 +0000131 chooseCertificate();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700132 return;
133 case UNLOCK_REQUESTED:
134 // we've already asked, but have not heard back, probably just rotated.
135 // wait to hear back via onActivityResult
136 return;
Kenny Root6ba32f22014-07-31 14:03:16 -0700137 case UNLOCK_CANCELED:
138 // User wanted to cancel the request, so exit.
139 mState = State.INITIAL;
Kenny Root13e867c2014-11-14 08:34:57 -0800140 finish(null);
Kenny Root6ba32f22014-07-31 14:03:16 -0700141 return;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700142 default:
143 throw new AssertionError();
144 }
145 }
146
Robin Leeb46e4932015-02-03 18:17:39 +0000147 private void chooseCertificate() {
148 // Start loading the set of certs to choose from now- if device policy doesn't return an
149 // alias, having aliases loading already will save some time waiting for UI to start.
Eran Messeri1223b5f2017-11-08 18:47:40 +0000150 KeyInfoProvider keyInfoProvider = new KeyInfoProvider() {
151 public boolean isUserSelectable(String alias) {
152 try (KeyChain.KeyChainConnection connection =
153 KeyChain.bind(KeyChainActivity.this)) {
154 return connection.getService().isUserSelectable(alias);
155 }
156 catch (InterruptedException ignored) {
157 Log.e(TAG, "interrupted while checking if key is user-selectable", ignored);
158 Thread.currentThread().interrupt();
159 return false;
160 } catch (Exception ignored) {
161 Log.e(TAG, "error while checking if key is user-selectable", ignored);
162 return false;
163 }
164 }
165 };
166
167 final AliasLoader loader = new AliasLoader(mKeyStore, this, keyInfoProvider);
Robin Leeb46e4932015-02-03 18:17:39 +0000168 loader.execute();
169
170 final IKeyChainAliasCallback.Stub callback = new IKeyChainAliasCallback.Stub() {
171 @Override public void alias(String alias) {
172 // Use policy-suggested alias if provided
173 if (alias != null) {
Eran Messerid0bcac82017-11-20 11:55:31 +0000174 finishWithAliasFromPolicy(alias);
Robin Leeb46e4932015-02-03 18:17:39 +0000175 return;
176 }
177
178 // No suggested alias - instead finish loading and show UI to pick one
179 final CertificateAdapter certAdapter;
180 try {
181 certAdapter = loader.get();
182 } catch (InterruptedException | ExecutionException e) {
183 Log.e(TAG, "Loading certificate aliases interrupted", e);
184 finish(null);
185 return;
186 }
187 runOnUiThread(new Runnable() {
188 @Override public void run() {
189 displayCertChooserDialog(certAdapter);
190 }
191 });
192 }
193 };
194
195 // Give a profile or device owner the chance to intercept the request, if a private key
196 // access listener is registered with the DevicePolicyManagerService.
197 IDevicePolicyManager devicePolicyManager = IDevicePolicyManager.Stub.asInterface(
198 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
199
Robin Lee606d9d02015-05-05 15:57:13 +0100200 Uri uri = getIntent().getParcelableExtra(KeyChain.EXTRA_URI);
Robin Leeb46e4932015-02-03 18:17:39 +0000201 String alias = getIntent().getStringExtra(KeyChain.EXTRA_ALIAS);
Robin Leeb46e4932015-02-03 18:17:39 +0000202 try {
Robin Lee9bfaabb2015-07-31 14:52:54 +0100203 devicePolicyManager.choosePrivateKeyAlias(mSenderUid, uri, alias, callback);
Robin Leeb46e4932015-02-03 18:17:39 +0000204 } catch (RemoteException e) {
Robin Lee8eb453b2015-02-17 14:13:36 +0000205 Log.e(TAG, "Unable to request alias from DevicePolicyManager", e);
Robin Leeb46e4932015-02-03 18:17:39 +0000206 // Proceed without a suggested alias.
207 try {
208 callback.alias(null);
209 } catch (RemoteException shouldNeverHappen) {
210 finish(null);
211 }
212 }
Brian Carlstrom91940e72011-06-28 20:37:31 -0700213 }
214
Eran Messericdc828d2017-10-23 18:51:45 +0100215 @VisibleForTesting
216 static class AliasLoader extends AsyncTask<Void, Void, CertificateAdapter> {
Eran Messeri96235f62017-10-20 10:27:28 +0100217 private final KeyStore mKeyStore;
218 private final Context mContext;
Eran Messeri6cc717b2017-10-25 14:26:14 +0100219 private final KeyInfoProvider mInfoProvider;
220
221 public AliasLoader(KeyStore keyStore, Context context, KeyInfoProvider infoProvider) {
Eran Messeri96235f62017-10-20 10:27:28 +0100222 mKeyStore = keyStore;
223 mContext = context;
Eran Messeri6cc717b2017-10-25 14:26:14 +0100224 mInfoProvider = infoProvider;
Eran Messeri96235f62017-10-20 10:27:28 +0100225 }
226
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700227 @Override protected CertificateAdapter doInBackground(Void... params) {
Alex Klyubin44c777b2015-06-08 09:46:15 -0700228 String[] aliasArray = mKeyStore.list(Credentials.USER_PRIVATE_KEY);
Eran Messeri6cc717b2017-10-25 14:26:14 +0100229 List<String> rawAliasList = ((aliasArray == null)
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700230 ? Collections.<String>emptyList()
231 : Arrays.asList(aliasArray));
Eran Messeri6cc717b2017-10-25 14:26:14 +0100232 return new CertificateAdapter(mKeyStore, mContext,
233 rawAliasList.stream().filter(mInfoProvider::isUserSelectable).sorted()
234 .collect(Collectors.toList()));
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700235 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700236 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700237
Brian Carlstrom91940e72011-06-28 20:37:31 -0700238 private void displayCertChooserDialog(final CertificateAdapter adapter) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700239 AlertDialog.Builder builder = new AlertDialog.Builder(this);
Brian Carlstromdf172302011-06-26 17:13:54 -0700240
Brian Carlstrom91940e72011-06-28 20:37:31 -0700241 boolean empty = adapter.mAliases.isEmpty();
Brian Carlstromdf172302011-06-26 17:13:54 -0700242 int negativeLabel = empty ? android.R.string.cancel : R.string.deny_button;
Robin Lee128549b2016-07-11 19:34:59 +0100243 builder.setNegativeButton(negativeLabel, new DialogInterface.OnClickListener() {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700244 @Override public void onClick(DialogInterface dialog, int id) {
245 dialog.cancel(); // will cause OnDismissListener to be called
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700246 }
247 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700248
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700249 String title;
Robin Lee8c9d4332016-04-26 12:49:24 +0100250 int selectedItem = -1;
Brian Carlstromdf172302011-06-26 17:13:54 -0700251 Resources res = getResources();
252 if (empty) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700253 title = res.getString(R.string.title_no_certs);
254 } else {
255 title = res.getString(R.string.title_select_cert);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700256 String alias = getIntent().getStringExtra(KeyChain.EXTRA_ALIAS);
Robin Lee8c9d4332016-04-26 12:49:24 +0100257
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700258 if (alias != null) {
Brian Carlstrom62316552011-07-10 12:26:12 -0700259 // if alias was requested, set it if found
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700260 int adapterPosition = adapter.mAliases.indexOf(alias);
261 if (adapterPosition != -1) {
Robin Lee8c9d4332016-04-26 12:49:24 +0100262 // increase by 1 to account for item 0 being the header.
263 selectedItem = adapterPosition + 1;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700264 }
Brian Carlstrom62316552011-07-10 12:26:12 -0700265 } else if (adapter.mAliases.size() == 1) {
266 // if only one choice, preselect it
Robin Lee8c9d4332016-04-26 12:49:24 +0100267 selectedItem = 1;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700268 }
269
270 builder.setPositiveButton(R.string.allow_button, new DialogInterface.OnClickListener() {
271 @Override public void onClick(DialogInterface dialog, int id) {
Robin Lee8c9d4332016-04-26 12:49:24 +0100272 if (dialog instanceof AlertDialog) {
273 ListView lv = ((AlertDialog) dialog).getListView();
274 int listViewPosition = lv.getCheckedItemPosition();
275 int adapterPosition = listViewPosition-1;
276 String alias = ((adapterPosition >= 0)
277 ? adapter.getItem(adapterPosition)
278 : null);
279 finish(alias);
280 } else {
281 Log.wtf(TAG, "Expected AlertDialog, got " + dialog, new Exception());
282 finish(null);
283 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700284 }
285 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700286 }
287 builder.setTitle(title);
Robin Lee8c9d4332016-04-26 12:49:24 +0100288 builder.setSingleChoiceItems(adapter, selectedItem, null);
Robin Lee8c9d4332016-04-26 12:49:24 +0100289 final AlertDialog dialog = builder.create();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700290
Robin Lee128549b2016-07-11 19:34:59 +0100291 // Show text above and below the list to explain what the certificate will be used for,
292 // and how to install another one, respectively.
Robin Lee8c9d4332016-04-26 12:49:24 +0100293 TextView contextView = (TextView) View.inflate(this, R.layout.cert_chooser_header, null);
Robin Lee8c9d4332016-04-26 12:49:24 +0100294
295 final ListView lv = dialog.getListView();
296 lv.addHeaderView(contextView, null, false);
Robin Lee128549b2016-07-11 19:34:59 +0100297 lv.addFooterView(View.inflate(this, R.layout.cert_install, null));
Robin Lee8c9d4332016-04-26 12:49:24 +0100298 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
299 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Robin Lee128549b2016-07-11 19:34:59 +0100300 if (position == 0) {
301 // Header. Just text; ignore clicks.
302 return;
303 } else if (position == adapter.getCount() + 1) {
304 // Footer. Remove dialog so that we will recreate with possibly new content
305 // after install returns.
306 dialog.dismiss();
307 Credentials.getInstance().install(KeyChainActivity.this);
308 } else {
309 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
310 lv.setItemChecked(position, true);
311 adapter.notifyDataSetChanged();
312 }
Robin Lee8c9d4332016-04-26 12:49:24 +0100313 }
314 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700315
316 // getTargetPackage guarantees that the returned string is
317 // supplied by the system, so that an application can not
318 // spoof its package.
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700319 String pkg = mSender.getIntentSender().getTargetPackage();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700320 PackageManager pm = getPackageManager();
321 CharSequence applicationLabel;
322 try {
323 applicationLabel = pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString();
324 } catch (PackageManager.NameNotFoundException e) {
325 applicationLabel = pkg;
326 }
327 String appMessage = String.format(res.getString(R.string.requesting_application),
328 applicationLabel);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700329 String contextMessage = appMessage;
Robin Lee606d9d02015-05-05 15:57:13 +0100330 Uri uri = getIntent().getParcelableExtra(KeyChain.EXTRA_URI);
331 if (uri != null) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700332 String hostMessage = String.format(res.getString(R.string.requesting_server),
Robin Lee606d9d02015-05-05 15:57:13 +0100333 uri.getAuthority());
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700334 if (contextMessage == null) {
335 contextMessage = hostMessage;
336 } else {
337 contextMessage += " " + hostMessage;
338 }
339 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700340 contextView.setText(contextMessage);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700341
Robin Lee128549b2016-07-11 19:34:59 +0100342 if (selectedItem == -1) {
343 dialog.setOnShowListener(new DialogInterface.OnShowListener() {
344 @Override
345 public void onShow(DialogInterface dialogInterface) {
346 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
347 }
348 });
349 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700350 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
351 @Override public void onCancel(DialogInterface dialog) {
352 finish(null);
353 }
354 });
Brian Carlstrom91940e72011-06-28 20:37:31 -0700355 dialog.show();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700356 }
357
Eran Messericdc828d2017-10-23 18:51:45 +0100358 @VisibleForTesting
359 static class CertificateAdapter extends BaseAdapter {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700360 private final List<String> mAliases;
361 private final List<String> mSubjects = new ArrayList<String>();
Eran Messeri96235f62017-10-20 10:27:28 +0100362 private final KeyStore mKeyStore;
363 private final Context mContext;
364
365 private CertificateAdapter(KeyStore keyStore, Context context, List<String> aliases) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700366 mAliases = aliases;
367 mSubjects.addAll(Collections.nCopies(aliases.size(), (String) null));
Eran Messeri96235f62017-10-20 10:27:28 +0100368 mKeyStore = keyStore;
369 mContext = context;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700370 }
371 @Override public int getCount() {
372 return mAliases.size();
373 }
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700374 @Override public String getItem(int adapterPosition) {
375 return mAliases.get(adapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700376 }
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700377 @Override public long getItemId(int adapterPosition) {
378 return adapterPosition;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700379 }
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700380 @Override public View getView(final int adapterPosition, View view, ViewGroup parent) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700381 ViewHolder holder;
382 if (view == null) {
Eran Messeri96235f62017-10-20 10:27:28 +0100383 LayoutInflater inflater = LayoutInflater.from(mContext);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700384 view = inflater.inflate(R.layout.cert_item, parent, false);
385 holder = new ViewHolder();
386 holder.mAliasTextView = (TextView) view.findViewById(R.id.cert_item_alias);
387 holder.mSubjectTextView = (TextView) view.findViewById(R.id.cert_item_subject);
388 holder.mRadioButton = (RadioButton) view.findViewById(R.id.cert_item_selected);
389 view.setTag(holder);
390 } else {
391 holder = (ViewHolder) view.getTag();
392 }
393
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700394 String alias = mAliases.get(adapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700395
396 holder.mAliasTextView.setText(alias);
397
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700398 String subject = mSubjects.get(adapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700399 if (subject == null) {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700400 new CertLoader(adapterPosition, holder.mSubjectTextView).execute();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700401 } else {
402 holder.mSubjectTextView.setText(subject);
403 }
404
405 ListView lv = (ListView)parent;
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700406 int listViewCheckedItemPosition = lv.getCheckedItemPosition();
407 int adapterCheckedItemPosition = listViewCheckedItemPosition-1;
408 holder.mRadioButton.setChecked(adapterPosition == adapterCheckedItemPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700409 return view;
410 }
411
412 private class CertLoader extends AsyncTask<Void, Void, String> {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700413 private final int mAdapterPosition;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700414 private final TextView mSubjectView;
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700415 private CertLoader(int adapterPosition, TextView subjectView) {
416 mAdapterPosition = adapterPosition;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700417 mSubjectView = subjectView;
418 }
419 @Override protected String doInBackground(Void... params) {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700420 String alias = mAliases.get(mAdapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700421 byte[] bytes = mKeyStore.get(Credentials.USER_CERTIFICATE + alias);
422 if (bytes == null) {
423 return null;
424 }
425 InputStream in = new ByteArrayInputStream(bytes);
426 X509Certificate cert;
427 try {
428 CertificateFactory cf = CertificateFactory.getInstance("X.509");
429 cert = (X509Certificate)cf.generateCertificate(in);
430 } catch (CertificateException ignored) {
431 return null;
432 }
433 // bouncycastle can handle the emailAddress OID of 1.2.840.113549.1.9.1
434 X500Principal subjectPrincipal = cert.getSubjectX500Principal();
435 X509Name subjectName = X509Name.getInstance(subjectPrincipal.getEncoded());
436 String subjectString = subjectName.toString(true, X509Name.DefaultSymbols);
437 return subjectString;
438 }
439 @Override protected void onPostExecute(String subjectString) {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700440 mSubjects.set(mAdapterPosition, subjectString);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700441 mSubjectView.setText(subjectString);
442 }
443 }
444 }
445
446 private static class ViewHolder {
447 TextView mAliasTextView;
448 TextView mSubjectTextView;
449 RadioButton mRadioButton;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700450 }
451
452 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
453 switch (requestCode) {
454 case REQUEST_UNLOCK:
Kenny Root4ff22962013-02-14 10:17:06 -0800455 if (mKeyStore.isUnlocked()) {
Kenny Root6ba32f22014-07-31 14:03:16 -0700456 mState = State.INITIAL;
Robin Leeb46e4932015-02-03 18:17:39 +0000457 chooseCertificate();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700458 } else {
459 // user must have canceled unlock, give up
Kenny Root6ba32f22014-07-31 14:03:16 -0700460 mState = State.UNLOCK_CANCELED;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700461 }
462 return;
463 default:
464 throw new AssertionError();
465 }
466 }
467
Brian Carlstrombb04f702011-05-24 21:54:51 -0700468 private void finish(String alias) {
Eran Messerid0bcac82017-11-20 11:55:31 +0000469 finish(alias, false);
470 }
471
472 private void finishWithAliasFromPolicy(String alias) {
473 finish(alias, true);
474 }
475
476 private void finish(String alias, boolean isAliasFromPolicy) {
Brian Carlstrombb04f702011-05-24 21:54:51 -0700477 if (alias == null) {
478 setResult(RESULT_CANCELED);
479 } else {
480 Intent result = new Intent();
481 result.putExtra(Intent.EXTRA_TEXT, alias);
482 setResult(RESULT_OK, result);
483 }
Brian Carlstromf5b50a42011-06-09 16:05:09 -0700484 IKeyChainAliasCallback keyChainAliasResponse
485 = IKeyChainAliasCallback.Stub.asInterface(
Brian Carlstrombb04f702011-05-24 21:54:51 -0700486 getIntent().getIBinderExtra(KeyChain.EXTRA_RESPONSE));
487 if (keyChainAliasResponse != null) {
Eran Messerid0bcac82017-11-20 11:55:31 +0000488 new ResponseSender(keyChainAliasResponse, alias, isAliasFromPolicy).execute();
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700489 return;
490 }
491 finish();
492 }
493
494 private class ResponseSender extends AsyncTask<Void, Void, Void> {
495 private IKeyChainAliasCallback mKeyChainAliasResponse;
496 private String mAlias;
Eran Messerid0bcac82017-11-20 11:55:31 +0000497 private boolean mFromPolicy;
498
499 private ResponseSender(IKeyChainAliasCallback keyChainAliasResponse, String alias,
500 boolean isFromPolicy) {
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700501 mKeyChainAliasResponse = keyChainAliasResponse;
502 mAlias = alias;
Eran Messerid0bcac82017-11-20 11:55:31 +0000503 mFromPolicy = isFromPolicy;
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700504 }
505 @Override protected Void doInBackground(Void... unused) {
Brian Carlstrombb04f702011-05-24 21:54:51 -0700506 try {
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700507 if (mAlias != null) {
508 KeyChain.KeyChainConnection connection = KeyChain.bind(KeyChainActivity.this);
509 try {
Eran Messerid0bcac82017-11-20 11:55:31 +0000510 // This is a safety check to make sure an alias was not somehow chosen by
511 // the user but is not user-selectable.
512 // However, if the alias was selected by the Device Owner / Profile Owner
513 // (by implementing DeviceAdminReceiver), then there's no need to check
514 // this.
515 if (!mFromPolicy && (!connection.getService().isUserSelectable(mAlias))) {
Eran Messeri1223b5f2017-11-08 18:47:40 +0000516 Log.w(TAG, String.format("Alias %s not user-selectable.", mAlias));
517 //TODO: Should we invoke the callback with null here to indicate error?
518 return null;
519 }
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700520 connection.getService().setGrant(mSenderUid, mAlias, true);
521 } finally {
522 connection.close();
523 }
524 }
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700525 mKeyChainAliasResponse.alias(mAlias);
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700526 } catch (InterruptedException ignored) {
527 Thread.currentThread().interrupt();
528 Log.d(TAG, "interrupted while granting access", ignored);
Brian Carlstrom2a858832011-05-26 09:30:26 -0700529 } catch (Exception ignored) {
530 // don't just catch RemoteException, caller could
531 // throw back a RuntimeException across processes
532 // which we should protect against.
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700533 Log.e(TAG, "error while granting access", ignored);
Brian Carlstrombb04f702011-05-24 21:54:51 -0700534 }
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700535 return null;
Brian Carlstrombb04f702011-05-24 21:54:51 -0700536 }
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700537 @Override protected void onPostExecute(Void unused) {
538 finish();
539 }
Brian Carlstrombb04f702011-05-24 21:54:51 -0700540 }
541
Brian Carlstrom9e606df2011-06-07 12:03:08 -0700542 @Override public void onBackPressed() {
543 finish(null);
544 }
545
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700546 @Override protected void onSaveInstanceState(Bundle savedState) {
547 super.onSaveInstanceState(savedState);
548 if (mState != State.INITIAL) {
549 savedState.putSerializable(KEY_STATE, mState);
550 }
551 }
552}