blob: aa50888af735248632c670e924cb815c026d4470 [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
Tianyi Hu2e3ad2f2021-09-15 21:43:18 +080066import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS;
67
Brian Carlstrom65e649e2011-06-24 02:13:28 -070068public class KeyChainActivity extends Activity {
Fred Quintanafb2e18e2011-07-13 14:54:05 -070069 private static final String TAG = "KeyChain";
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070070
71 private static String KEY_STATE = "state";
72
73 private static final int REQUEST_UNLOCK = 1;
74
Fred Quintanafb2e18e2011-07-13 14:54:05 -070075 private int mSenderUid;
76
77 private PendingIntent mSender;
78
Kenny Root6ba32f22014-07-31 14:03:16 -070079 private static enum State { INITIAL, UNLOCK_REQUESTED, UNLOCK_CANCELED };
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070080
81 private State mState;
82
Brian Carlstrom65e649e2011-06-24 02:13:28 -070083 // beware that some of these KeyStore operations such as saw and
84 // get do file I/O in the remote keystore process and while they
85 // do not cause StrictMode violations, they logically should not
86 // be done on the UI thread.
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070087 private KeyStore mKeyStore = KeyStore.getInstance();
88
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070089 @Override public void onCreate(Bundle savedState) {
90 super.onCreate(savedState);
Tianyi Hu2e3ad2f2021-09-15 21:43:18 +080091 getWindow().addPrivateFlags(PRIVATE_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070092 if (savedState == null) {
93 mState = State.INITIAL;
94 } else {
95 mState = (State) savedState.getSerializable(KEY_STATE);
96 if (mState == null) {
97 mState = State.INITIAL;
98 }
99 }
100 }
101
102 @Override public void onResume() {
103 super.onResume();
104
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700105 mSender = getIntent().getParcelableExtra(KeyChain.EXTRA_SENDER);
106 if (mSender == null) {
107 // if no sender, bail, we need to identify the app to the user securely.
108 finish(null);
109 return;
110 }
111 try {
112 mSenderUid = getPackageManager().getPackageInfo(
113 mSender.getIntentSender().getTargetPackage(), 0).applicationInfo.uid;
114 } catch (PackageManager.NameNotFoundException e) {
115 // if unable to find the sender package info bail,
116 // we need to identify the app to the user securely.
117 finish(null);
118 return;
119 }
120
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700121 // see if KeyStore has been unlocked, if not start activity to do so
122 switch (mState) {
123 case INITIAL:
Kenny Root4ff22962013-02-14 10:17:06 -0800124 if (!mKeyStore.isUnlocked()) {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700125 mState = State.UNLOCK_REQUESTED;
126 this.startActivityForResult(new Intent(Credentials.UNLOCK_ACTION),
127 REQUEST_UNLOCK);
128 // Note that Credentials.unlock will start an
129 // Activity and we will be paused but then resumed
130 // when the unlock Activity completes and our
131 // onActivityResult is called with REQUEST_UNLOCK
132 return;
133 }
Robin Leeb46e4932015-02-03 18:17:39 +0000134 chooseCertificate();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700135 return;
136 case UNLOCK_REQUESTED:
137 // we've already asked, but have not heard back, probably just rotated.
138 // wait to hear back via onActivityResult
139 return;
Kenny Root6ba32f22014-07-31 14:03:16 -0700140 case UNLOCK_CANCELED:
141 // User wanted to cancel the request, so exit.
142 mState = State.INITIAL;
Kenny Root13e867c2014-11-14 08:34:57 -0800143 finish(null);
Kenny Root6ba32f22014-07-31 14:03:16 -0700144 return;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700145 default:
146 throw new AssertionError();
147 }
148 }
149
Robin Leeb46e4932015-02-03 18:17:39 +0000150 private void chooseCertificate() {
151 // Start loading the set of certs to choose from now- if device policy doesn't return an
152 // alias, having aliases loading already will save some time waiting for UI to start.
Eran Messeri1223b5f2017-11-08 18:47:40 +0000153 KeyInfoProvider keyInfoProvider = new KeyInfoProvider() {
154 public boolean isUserSelectable(String alias) {
155 try (KeyChain.KeyChainConnection connection =
156 KeyChain.bind(KeyChainActivity.this)) {
157 return connection.getService().isUserSelectable(alias);
158 }
159 catch (InterruptedException ignored) {
160 Log.e(TAG, "interrupted while checking if key is user-selectable", ignored);
161 Thread.currentThread().interrupt();
162 return false;
163 } catch (Exception ignored) {
164 Log.e(TAG, "error while checking if key is user-selectable", ignored);
165 return false;
166 }
167 }
168 };
169
170 final AliasLoader loader = new AliasLoader(mKeyStore, this, keyInfoProvider);
Robin Leeb46e4932015-02-03 18:17:39 +0000171 loader.execute();
172
173 final IKeyChainAliasCallback.Stub callback = new IKeyChainAliasCallback.Stub() {
174 @Override public void alias(String alias) {
175 // Use policy-suggested alias if provided
176 if (alias != null) {
Eran Messerid0bcac82017-11-20 11:55:31 +0000177 finishWithAliasFromPolicy(alias);
Robin Leeb46e4932015-02-03 18:17:39 +0000178 return;
179 }
180
181 // No suggested alias - instead finish loading and show UI to pick one
182 final CertificateAdapter certAdapter;
183 try {
184 certAdapter = loader.get();
185 } catch (InterruptedException | ExecutionException e) {
186 Log.e(TAG, "Loading certificate aliases interrupted", e);
187 finish(null);
188 return;
189 }
190 runOnUiThread(new Runnable() {
191 @Override public void run() {
192 displayCertChooserDialog(certAdapter);
193 }
194 });
195 }
196 };
197
198 // Give a profile or device owner the chance to intercept the request, if a private key
199 // access listener is registered with the DevicePolicyManagerService.
200 IDevicePolicyManager devicePolicyManager = IDevicePolicyManager.Stub.asInterface(
201 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
202
Robin Lee606d9d02015-05-05 15:57:13 +0100203 Uri uri = getIntent().getParcelableExtra(KeyChain.EXTRA_URI);
Robin Leeb46e4932015-02-03 18:17:39 +0000204 String alias = getIntent().getStringExtra(KeyChain.EXTRA_ALIAS);
Robin Leeb46e4932015-02-03 18:17:39 +0000205 try {
Robin Lee9bfaabb2015-07-31 14:52:54 +0100206 devicePolicyManager.choosePrivateKeyAlias(mSenderUid, uri, alias, callback);
Robin Leeb46e4932015-02-03 18:17:39 +0000207 } catch (RemoteException e) {
Robin Lee8eb453b2015-02-17 14:13:36 +0000208 Log.e(TAG, "Unable to request alias from DevicePolicyManager", e);
Robin Leeb46e4932015-02-03 18:17:39 +0000209 // Proceed without a suggested alias.
210 try {
211 callback.alias(null);
212 } catch (RemoteException shouldNeverHappen) {
213 finish(null);
214 }
215 }
Brian Carlstrom91940e72011-06-28 20:37:31 -0700216 }
217
Eran Messericdc828d2017-10-23 18:51:45 +0100218 @VisibleForTesting
219 static class AliasLoader extends AsyncTask<Void, Void, CertificateAdapter> {
Eran Messeri96235f62017-10-20 10:27:28 +0100220 private final KeyStore mKeyStore;
221 private final Context mContext;
Eran Messeri6cc717b2017-10-25 14:26:14 +0100222 private final KeyInfoProvider mInfoProvider;
223
224 public AliasLoader(KeyStore keyStore, Context context, KeyInfoProvider infoProvider) {
Eran Messeri96235f62017-10-20 10:27:28 +0100225 mKeyStore = keyStore;
226 mContext = context;
Eran Messeri6cc717b2017-10-25 14:26:14 +0100227 mInfoProvider = infoProvider;
Eran Messeri96235f62017-10-20 10:27:28 +0100228 }
229
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700230 @Override protected CertificateAdapter doInBackground(Void... params) {
Alex Klyubin44c777b2015-06-08 09:46:15 -0700231 String[] aliasArray = mKeyStore.list(Credentials.USER_PRIVATE_KEY);
Eran Messeri6cc717b2017-10-25 14:26:14 +0100232 List<String> rawAliasList = ((aliasArray == null)
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700233 ? Collections.<String>emptyList()
234 : Arrays.asList(aliasArray));
Eran Messeri6cc717b2017-10-25 14:26:14 +0100235 return new CertificateAdapter(mKeyStore, mContext,
236 rawAliasList.stream().filter(mInfoProvider::isUserSelectable).sorted()
237 .collect(Collectors.toList()));
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700238 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700239 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700240
Brian Carlstrom91940e72011-06-28 20:37:31 -0700241 private void displayCertChooserDialog(final CertificateAdapter adapter) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700242 AlertDialog.Builder builder = new AlertDialog.Builder(this);
Brian Carlstromdf172302011-06-26 17:13:54 -0700243
Brian Carlstrom91940e72011-06-28 20:37:31 -0700244 boolean empty = adapter.mAliases.isEmpty();
Brian Carlstromdf172302011-06-26 17:13:54 -0700245 int negativeLabel = empty ? android.R.string.cancel : R.string.deny_button;
Robin Lee128549b2016-07-11 19:34:59 +0100246 builder.setNegativeButton(negativeLabel, new DialogInterface.OnClickListener() {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700247 @Override public void onClick(DialogInterface dialog, int id) {
248 dialog.cancel(); // will cause OnDismissListener to be called
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700249 }
250 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700251
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700252 String title;
Robin Lee8c9d4332016-04-26 12:49:24 +0100253 int selectedItem = -1;
Brian Carlstromdf172302011-06-26 17:13:54 -0700254 Resources res = getResources();
255 if (empty) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700256 title = res.getString(R.string.title_no_certs);
257 } else {
258 title = res.getString(R.string.title_select_cert);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700259 String alias = getIntent().getStringExtra(KeyChain.EXTRA_ALIAS);
Robin Lee8c9d4332016-04-26 12:49:24 +0100260
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700261 if (alias != null) {
Brian Carlstrom62316552011-07-10 12:26:12 -0700262 // if alias was requested, set it if found
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700263 int adapterPosition = adapter.mAliases.indexOf(alias);
264 if (adapterPosition != -1) {
Robin Lee8c9d4332016-04-26 12:49:24 +0100265 // increase by 1 to account for item 0 being the header.
266 selectedItem = adapterPosition + 1;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700267 }
Brian Carlstrom62316552011-07-10 12:26:12 -0700268 } else if (adapter.mAliases.size() == 1) {
269 // if only one choice, preselect it
Robin Lee8c9d4332016-04-26 12:49:24 +0100270 selectedItem = 1;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700271 }
272
273 builder.setPositiveButton(R.string.allow_button, new DialogInterface.OnClickListener() {
274 @Override public void onClick(DialogInterface dialog, int id) {
Robin Lee8c9d4332016-04-26 12:49:24 +0100275 if (dialog instanceof AlertDialog) {
276 ListView lv = ((AlertDialog) dialog).getListView();
277 int listViewPosition = lv.getCheckedItemPosition();
278 int adapterPosition = listViewPosition-1;
279 String alias = ((adapterPosition >= 0)
280 ? adapter.getItem(adapterPosition)
281 : null);
282 finish(alias);
283 } else {
284 Log.wtf(TAG, "Expected AlertDialog, got " + dialog, new Exception());
285 finish(null);
286 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700287 }
288 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700289 }
290 builder.setTitle(title);
Robin Lee8c9d4332016-04-26 12:49:24 +0100291 builder.setSingleChoiceItems(adapter, selectedItem, null);
Robin Lee8c9d4332016-04-26 12:49:24 +0100292 final AlertDialog dialog = builder.create();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700293
Robin Lee128549b2016-07-11 19:34:59 +0100294 // Show text above and below the list to explain what the certificate will be used for,
295 // and how to install another one, respectively.
Robin Lee8c9d4332016-04-26 12:49:24 +0100296 TextView contextView = (TextView) View.inflate(this, R.layout.cert_chooser_header, null);
Robin Lee8c9d4332016-04-26 12:49:24 +0100297
298 final ListView lv = dialog.getListView();
299 lv.addHeaderView(contextView, null, false);
Robin Lee128549b2016-07-11 19:34:59 +0100300 lv.addFooterView(View.inflate(this, R.layout.cert_install, null));
Robin Lee8c9d4332016-04-26 12:49:24 +0100301 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
302 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Robin Lee128549b2016-07-11 19:34:59 +0100303 if (position == 0) {
304 // Header. Just text; ignore clicks.
305 return;
306 } else if (position == adapter.getCount() + 1) {
307 // Footer. Remove dialog so that we will recreate with possibly new content
308 // after install returns.
309 dialog.dismiss();
310 Credentials.getInstance().install(KeyChainActivity.this);
311 } else {
312 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
313 lv.setItemChecked(position, true);
314 adapter.notifyDataSetChanged();
315 }
Robin Lee8c9d4332016-04-26 12:49:24 +0100316 }
317 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700318
319 // getTargetPackage guarantees that the returned string is
320 // supplied by the system, so that an application can not
321 // spoof its package.
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700322 String pkg = mSender.getIntentSender().getTargetPackage();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700323 PackageManager pm = getPackageManager();
324 CharSequence applicationLabel;
325 try {
326 applicationLabel = pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString();
327 } catch (PackageManager.NameNotFoundException e) {
328 applicationLabel = pkg;
329 }
330 String appMessage = String.format(res.getString(R.string.requesting_application),
331 applicationLabel);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700332 String contextMessage = appMessage;
Robin Lee606d9d02015-05-05 15:57:13 +0100333 Uri uri = getIntent().getParcelableExtra(KeyChain.EXTRA_URI);
334 if (uri != null) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700335 String hostMessage = String.format(res.getString(R.string.requesting_server),
Robin Lee606d9d02015-05-05 15:57:13 +0100336 uri.getAuthority());
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700337 if (contextMessage == null) {
338 contextMessage = hostMessage;
339 } else {
340 contextMessage += " " + hostMessage;
341 }
342 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700343 contextView.setText(contextMessage);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700344
Robin Lee128549b2016-07-11 19:34:59 +0100345 if (selectedItem == -1) {
346 dialog.setOnShowListener(new DialogInterface.OnShowListener() {
347 @Override
348 public void onShow(DialogInterface dialogInterface) {
349 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
350 }
351 });
352 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700353 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
354 @Override public void onCancel(DialogInterface dialog) {
355 finish(null);
356 }
357 });
Rubin Xu754bb642021-09-15 21:43:18 +0800358 dialog.create();
359 // Prevents screen overlay attack.
360 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setFilterTouchesWhenObscured(true);
Brian Carlstrom91940e72011-06-28 20:37:31 -0700361 dialog.show();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700362 }
363
Eran Messericdc828d2017-10-23 18:51:45 +0100364 @VisibleForTesting
365 static class CertificateAdapter extends BaseAdapter {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700366 private final List<String> mAliases;
367 private final List<String> mSubjects = new ArrayList<String>();
Eran Messeri96235f62017-10-20 10:27:28 +0100368 private final KeyStore mKeyStore;
369 private final Context mContext;
370
371 private CertificateAdapter(KeyStore keyStore, Context context, List<String> aliases) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700372 mAliases = aliases;
373 mSubjects.addAll(Collections.nCopies(aliases.size(), (String) null));
Eran Messeri96235f62017-10-20 10:27:28 +0100374 mKeyStore = keyStore;
375 mContext = context;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700376 }
377 @Override public int getCount() {
378 return mAliases.size();
379 }
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700380 @Override public String getItem(int adapterPosition) {
381 return mAliases.get(adapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700382 }
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700383 @Override public long getItemId(int adapterPosition) {
384 return adapterPosition;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700385 }
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700386 @Override public View getView(final int adapterPosition, View view, ViewGroup parent) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700387 ViewHolder holder;
388 if (view == null) {
Eran Messeri96235f62017-10-20 10:27:28 +0100389 LayoutInflater inflater = LayoutInflater.from(mContext);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700390 view = inflater.inflate(R.layout.cert_item, parent, false);
391 holder = new ViewHolder();
392 holder.mAliasTextView = (TextView) view.findViewById(R.id.cert_item_alias);
393 holder.mSubjectTextView = (TextView) view.findViewById(R.id.cert_item_subject);
394 holder.mRadioButton = (RadioButton) view.findViewById(R.id.cert_item_selected);
395 view.setTag(holder);
396 } else {
397 holder = (ViewHolder) view.getTag();
398 }
399
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700400 String alias = mAliases.get(adapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700401
402 holder.mAliasTextView.setText(alias);
403
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700404 String subject = mSubjects.get(adapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700405 if (subject == null) {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700406 new CertLoader(adapterPosition, holder.mSubjectTextView).execute();
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700407 } else {
408 holder.mSubjectTextView.setText(subject);
409 }
410
411 ListView lv = (ListView)parent;
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700412 int listViewCheckedItemPosition = lv.getCheckedItemPosition();
413 int adapterCheckedItemPosition = listViewCheckedItemPosition-1;
414 holder.mRadioButton.setChecked(adapterPosition == adapterCheckedItemPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700415 return view;
416 }
417
418 private class CertLoader extends AsyncTask<Void, Void, String> {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700419 private final int mAdapterPosition;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700420 private final TextView mSubjectView;
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700421 private CertLoader(int adapterPosition, TextView subjectView) {
422 mAdapterPosition = adapterPosition;
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700423 mSubjectView = subjectView;
424 }
425 @Override protected String doInBackground(Void... params) {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700426 String alias = mAliases.get(mAdapterPosition);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700427 byte[] bytes = mKeyStore.get(Credentials.USER_CERTIFICATE + alias);
428 if (bytes == null) {
429 return null;
430 }
431 InputStream in = new ByteArrayInputStream(bytes);
432 X509Certificate cert;
433 try {
434 CertificateFactory cf = CertificateFactory.getInstance("X.509");
435 cert = (X509Certificate)cf.generateCertificate(in);
436 } catch (CertificateException ignored) {
437 return null;
438 }
439 // bouncycastle can handle the emailAddress OID of 1.2.840.113549.1.9.1
440 X500Principal subjectPrincipal = cert.getSubjectX500Principal();
441 X509Name subjectName = X509Name.getInstance(subjectPrincipal.getEncoded());
442 String subjectString = subjectName.toString(true, X509Name.DefaultSymbols);
443 return subjectString;
444 }
445 @Override protected void onPostExecute(String subjectString) {
Brian Carlstrom5dd41f62011-06-29 18:51:34 -0700446 mSubjects.set(mAdapterPosition, subjectString);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700447 mSubjectView.setText(subjectString);
448 }
449 }
450 }
451
452 private static class ViewHolder {
453 TextView mAliasTextView;
454 TextView mSubjectTextView;
455 RadioButton mRadioButton;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700456 }
457
458 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
459 switch (requestCode) {
460 case REQUEST_UNLOCK:
Kenny Root4ff22962013-02-14 10:17:06 -0800461 if (mKeyStore.isUnlocked()) {
Kenny Root6ba32f22014-07-31 14:03:16 -0700462 mState = State.INITIAL;
Robin Leeb46e4932015-02-03 18:17:39 +0000463 chooseCertificate();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700464 } else {
465 // user must have canceled unlock, give up
Kenny Root6ba32f22014-07-31 14:03:16 -0700466 mState = State.UNLOCK_CANCELED;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700467 }
468 return;
469 default:
470 throw new AssertionError();
471 }
472 }
473
Brian Carlstrombb04f702011-05-24 21:54:51 -0700474 private void finish(String alias) {
Eran Messerid0bcac82017-11-20 11:55:31 +0000475 finish(alias, false);
476 }
477
478 private void finishWithAliasFromPolicy(String alias) {
479 finish(alias, true);
480 }
481
482 private void finish(String alias, boolean isAliasFromPolicy) {
Brian Carlstrombb04f702011-05-24 21:54:51 -0700483 if (alias == null) {
484 setResult(RESULT_CANCELED);
485 } else {
486 Intent result = new Intent();
487 result.putExtra(Intent.EXTRA_TEXT, alias);
488 setResult(RESULT_OK, result);
489 }
Brian Carlstromf5b50a42011-06-09 16:05:09 -0700490 IKeyChainAliasCallback keyChainAliasResponse
491 = IKeyChainAliasCallback.Stub.asInterface(
Brian Carlstrombb04f702011-05-24 21:54:51 -0700492 getIntent().getIBinderExtra(KeyChain.EXTRA_RESPONSE));
493 if (keyChainAliasResponse != null) {
Eran Messerid0bcac82017-11-20 11:55:31 +0000494 new ResponseSender(keyChainAliasResponse, alias, isAliasFromPolicy).execute();
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700495 return;
496 }
497 finish();
498 }
499
500 private class ResponseSender extends AsyncTask<Void, Void, Void> {
501 private IKeyChainAliasCallback mKeyChainAliasResponse;
502 private String mAlias;
Eran Messerid0bcac82017-11-20 11:55:31 +0000503 private boolean mFromPolicy;
504
505 private ResponseSender(IKeyChainAliasCallback keyChainAliasResponse, String alias,
506 boolean isFromPolicy) {
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700507 mKeyChainAliasResponse = keyChainAliasResponse;
508 mAlias = alias;
Eran Messerid0bcac82017-11-20 11:55:31 +0000509 mFromPolicy = isFromPolicy;
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700510 }
511 @Override protected Void doInBackground(Void... unused) {
Brian Carlstrombb04f702011-05-24 21:54:51 -0700512 try {
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700513 if (mAlias != null) {
514 KeyChain.KeyChainConnection connection = KeyChain.bind(KeyChainActivity.this);
515 try {
Eran Messerid0bcac82017-11-20 11:55:31 +0000516 // This is a safety check to make sure an alias was not somehow chosen by
517 // the user but is not user-selectable.
518 // However, if the alias was selected by the Device Owner / Profile Owner
519 // (by implementing DeviceAdminReceiver), then there's no need to check
520 // this.
521 if (!mFromPolicy && (!connection.getService().isUserSelectable(mAlias))) {
Eran Messeri1223b5f2017-11-08 18:47:40 +0000522 Log.w(TAG, String.format("Alias %s not user-selectable.", mAlias));
523 //TODO: Should we invoke the callback with null here to indicate error?
524 return null;
525 }
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700526 connection.getService().setGrant(mSenderUid, mAlias, true);
527 } finally {
528 connection.close();
529 }
530 }
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700531 mKeyChainAliasResponse.alias(mAlias);
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700532 } catch (InterruptedException ignored) {
533 Thread.currentThread().interrupt();
534 Log.d(TAG, "interrupted while granting access", ignored);
Brian Carlstrom2a858832011-05-26 09:30:26 -0700535 } catch (Exception ignored) {
536 // don't just catch RemoteException, caller could
537 // throw back a RuntimeException across processes
538 // which we should protect against.
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700539 Log.e(TAG, "error while granting access", ignored);
Brian Carlstrombb04f702011-05-24 21:54:51 -0700540 }
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700541 return null;
Brian Carlstrombb04f702011-05-24 21:54:51 -0700542 }
Brian Carlstrom7d9aa752011-07-07 11:52:27 -0700543 @Override protected void onPostExecute(Void unused) {
544 finish();
545 }
Brian Carlstrombb04f702011-05-24 21:54:51 -0700546 }
547
Brian Carlstrom9e606df2011-06-07 12:03:08 -0700548 @Override public void onBackPressed() {
549 finish(null);
550 }
551
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700552 @Override protected void onSaveInstanceState(Bundle savedState) {
553 super.onSaveInstanceState(savedState);
554 if (mState != State.INITIAL) {
555 savedState.putSerializable(KEY_STATE, mState);
556 }
557 }
558}