blob: 0702c3f719f5fe7d8c33fe2e837535dbfcbf35c6 [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;
20import android.app.AlertDialog;
21import android.app.Dialog;
22import android.app.PendingIntent;
23import android.content.DialogInterface;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070024import android.content.Intent;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070025import android.content.pm.PackageManager;
26import android.content.res.Resources;
27import android.os.AsyncTask;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070028import android.os.Bundle;
Brian Carlstrombb04f702011-05-24 21:54:51 -070029import android.os.RemoteException;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070030import android.security.Credentials;
Brian Carlstromf5b50a42011-06-09 16:05:09 -070031import android.security.IKeyChainAliasCallback;
Brian Carlstrombb04f702011-05-24 21:54:51 -070032import android.security.KeyChain;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070033import android.security.KeyStore;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070034import android.view.LayoutInflater;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070035import android.view.View;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070036import android.view.ViewGroup;
37import android.widget.BaseAdapter;
38import android.widget.Button;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070039import android.widget.ListView;
Brian Carlstrom65e649e2011-06-24 02:13:28 -070040import android.widget.RadioButton;
41import android.widget.TextView;
42import com.android.org.bouncycastle.asn1.x509.X509Name;
43import java.io.ByteArrayInputStream;
44import java.io.InputStream;
45import java.security.cert.CertificateException;
46import java.security.cert.CertificateFactory;
47import java.security.cert.X509Certificate;
48import java.util.ArrayList;
49import java.util.Arrays;
50import java.util.Collections;
51import java.util.List;
52import javax.security.auth.x500.X500Principal;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070053
Brian Carlstrom65e649e2011-06-24 02:13:28 -070054public class KeyChainActivity extends Activity {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070055
56 private static final String TAG = "KeyChainActivity";
57
58 private static String KEY_STATE = "state";
59
60 private static final int REQUEST_UNLOCK = 1;
61
Brian Carlstrom65e649e2011-06-24 02:13:28 -070062 private static final int DIALOG_CERT_CHOOSER = 0;
63
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070064 private static enum State { INITIAL, UNLOCK_REQUESTED };
65
66 private State mState;
67
Brian Carlstrom65e649e2011-06-24 02:13:28 -070068 // beware that some of these KeyStore operations such as saw and
69 // get do file I/O in the remote keystore process and while they
70 // do not cause StrictMode violations, they logically should not
71 // be done on the UI thread.
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070072 private KeyStore mKeyStore = KeyStore.getInstance();
73
Brian Carlstrom65e649e2011-06-24 02:13:28 -070074 private CertificateAdapter mCertificateAdapter;
75
76 // the KeyStore.state operation is safe to do on the UI thread, it
77 // does not do a file operation.
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070078 private boolean isKeyStoreUnlocked() {
Brian Carlstrome3b33902011-05-31 01:06:20 -070079 return mKeyStore.state() == KeyStore.State.UNLOCKED;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070080 }
81
82 @Override public void onCreate(Bundle savedState) {
83 super.onCreate(savedState);
84 if (savedState == null) {
85 mState = State.INITIAL;
86 } else {
87 mState = (State) savedState.getSerializable(KEY_STATE);
88 if (mState == null) {
89 mState = State.INITIAL;
90 }
91 }
92 }
93
94 @Override public void onResume() {
95 super.onResume();
96
97 // see if KeyStore has been unlocked, if not start activity to do so
98 switch (mState) {
99 case INITIAL:
100 if (!isKeyStoreUnlocked()) {
101 mState = State.UNLOCK_REQUESTED;
102 this.startActivityForResult(new Intent(Credentials.UNLOCK_ACTION),
103 REQUEST_UNLOCK);
104 // Note that Credentials.unlock will start an
105 // Activity and we will be paused but then resumed
106 // when the unlock Activity completes and our
107 // onActivityResult is called with REQUEST_UNLOCK
108 return;
109 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700110 new AliasLoader().execute();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700111 return;
112 case UNLOCK_REQUESTED:
113 // we've already asked, but have not heard back, probably just rotated.
114 // wait to hear back via onActivityResult
115 return;
116 default:
117 throw new AssertionError();
118 }
119 }
120
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700121 private class AliasLoader extends AsyncTask<Void, Void, CertificateAdapter> {
122 @Override protected CertificateAdapter doInBackground(Void... params) {
123 String[] aliasArray = mKeyStore.saw(Credentials.USER_PRIVATE_KEY);
124 List<String> aliasList = ((aliasArray == null)
125 ? Collections.<String>emptyList()
126 : Arrays.asList(aliasArray));
127 Collections.sort(aliasList);
128 return new CertificateAdapter(aliasList);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700129 }
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700130 @Override protected void onPostExecute(CertificateAdapter result) {
131 mCertificateAdapter = result;
132 showDialog(DIALOG_CERT_CHOOSER);
133 }
134 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700135
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700136 @Override protected Dialog onCreateDialog(int id, Bundle args) {
137 if (id == DIALOG_CERT_CHOOSER) {
138 return createCertChooserDialog();
139 }
140 throw new AssertionError();
141 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700142
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700143 private Dialog createCertChooserDialog() {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700144 AlertDialog.Builder builder = new AlertDialog.Builder(this);
Brian Carlstromdf172302011-06-26 17:13:54 -0700145
146 View view = View.inflate(this, R.layout.cert_chooser, null);
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700147 builder.setView(view);
Brian Carlstromdf172302011-06-26 17:13:54 -0700148
149 boolean empty = mCertificateAdapter.mAliases.isEmpty();
150 int negativeLabel = empty ? android.R.string.cancel : R.string.deny_button;
151 builder.setNegativeButton(negativeLabel, new DialogInterface.OnClickListener() {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700152 @Override public void onClick(DialogInterface dialog, int id) {
153 dialog.cancel(); // will cause OnDismissListener to be called
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700154 }
155 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700156
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700157 String title;
Brian Carlstromdf172302011-06-26 17:13:54 -0700158 Resources res = getResources();
159 if (empty) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700160 title = res.getString(R.string.title_no_certs);
161 } else {
162 title = res.getString(R.string.title_select_cert);
163 final ListView lv = (ListView) view.findViewById(R.id.cert_chooser_cert_list);
164 lv.setAdapter(mCertificateAdapter);
165 String alias = getIntent().getStringExtra(KeyChain.EXTRA_ALIAS);
166 if (alias != null) {
167 int position = mCertificateAdapter.mAliases.indexOf(alias);
168 if (position != -1) {
169 lv.setItemChecked(position, true);
170 }
171 }
172
173 builder.setPositiveButton(R.string.allow_button, new DialogInterface.OnClickListener() {
174 @Override public void onClick(DialogInterface dialog, int id) {
175 int pos = lv.getCheckedItemPosition();
176 String alias = ((pos != ListView.INVALID_POSITION)
177 ? mCertificateAdapter.getItem(pos)
178 : null);
179 finish(alias);
180 }
181 });
182
183 lv.setVisibility(View.VISIBLE);
184 }
185 builder.setTitle(title);
186
187 PendingIntent sender = getIntent().getParcelableExtra(KeyChain.EXTRA_SENDER);
188 if (sender == null) {
189 // if no sender, bail, we need to identify the app to the user securely.
190 finish(null);
191 }
192
193 // getTargetPackage guarantees that the returned string is
194 // supplied by the system, so that an application can not
195 // spoof its package.
196 String pkg = sender.getIntentSender().getTargetPackage();
197 PackageManager pm = getPackageManager();
198 CharSequence applicationLabel;
199 try {
200 applicationLabel = pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString();
201 } catch (PackageManager.NameNotFoundException e) {
202 applicationLabel = pkg;
203 }
204 String appMessage = String.format(res.getString(R.string.requesting_application),
205 applicationLabel);
206
207 String contextMessage = appMessage;
208 String host = getIntent().getStringExtra(KeyChain.EXTRA_HOST);
209 if (host != null) {
210 String hostString = host;
211 int port = getIntent().getIntExtra(KeyChain.EXTRA_PORT, -1);
212 if (port != -1) {
213 hostString += ":" + port;
214 }
215 String hostMessage = String.format(res.getString(R.string.requesting_server),
216 hostString);
217 if (contextMessage == null) {
218 contextMessage = hostMessage;
219 } else {
220 contextMessage += " " + hostMessage;
221 }
222 }
223 TextView contextView = (TextView) view.findViewById(R.id.cert_chooser_context_message);
224 contextView.setText(contextMessage);
225 contextView.setVisibility(View.VISIBLE);
226
227 String installMessage = String.format(res.getString(R.string.install_new_cert_message),
228 Credentials.EXTENSION_PFX, Credentials.EXTENSION_P12);
229 TextView installTextView = (TextView) view.findViewById(R.id.cert_chooser_install_message);
230 installTextView.setText(installMessage);
231
232 Button installButton = (Button) view.findViewById(R.id.cert_chooser_install_button);
233 installButton.setOnClickListener(new View.OnClickListener() {
234 @Override public void onClick(View v) {
235 // remove dialog so that we will recreate with
236 // possibly new content after install returns
237 removeDialog(DIALOG_CERT_CHOOSER);
238 Credentials.getInstance().install(KeyChainActivity.this);
239 }
240 });
241
242 Dialog dialog = builder.create();
243 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
244 @Override public void onCancel(DialogInterface dialog) {
245 finish(null);
246 }
247 });
248 return dialog;
249 }
250
251 private class CertificateAdapter extends BaseAdapter {
252 private final List<String> mAliases;
253 private final List<String> mSubjects = new ArrayList<String>();
254 private CertificateAdapter(List<String> aliases) {
255 mAliases = aliases;
256 mSubjects.addAll(Collections.nCopies(aliases.size(), (String) null));
257 }
258 @Override public int getCount() {
259 return mAliases.size();
260 }
261 @Override public String getItem(int position) {
262 return mAliases.get(position);
263 }
264 @Override public long getItemId(int position) {
265 return position;
266 }
267 @Override public View getView(final int position, View view, ViewGroup parent) {
268 ViewHolder holder;
269 if (view == null) {
270 LayoutInflater inflater = LayoutInflater.from(KeyChainActivity.this);
271 view = inflater.inflate(R.layout.cert_item, parent, false);
272 holder = new ViewHolder();
273 holder.mAliasTextView = (TextView) view.findViewById(R.id.cert_item_alias);
274 holder.mSubjectTextView = (TextView) view.findViewById(R.id.cert_item_subject);
275 holder.mRadioButton = (RadioButton) view.findViewById(R.id.cert_item_selected);
276 view.setTag(holder);
277 } else {
278 holder = (ViewHolder) view.getTag();
279 }
280
281 String alias = mAliases.get(position);
282
283 holder.mAliasTextView.setText(alias);
284
285 String subject = mSubjects.get(position);
286 if (subject == null) {
287 new CertLoader(position, holder.mSubjectTextView).execute();
288 } else {
289 holder.mSubjectTextView.setText(subject);
290 }
291
292 ListView lv = (ListView)parent;
293 holder.mRadioButton.setChecked(position == lv.getCheckedItemPosition());
294 return view;
295 }
296
297 private class CertLoader extends AsyncTask<Void, Void, String> {
298 private final int mPosition;
299 private final TextView mSubjectView;
300 private CertLoader(int position, TextView subjectView) {
301 mPosition = position;
302 mSubjectView = subjectView;
303 }
304 @Override protected String doInBackground(Void... params) {
305 String alias = mAliases.get(mPosition);
306 byte[] bytes = mKeyStore.get(Credentials.USER_CERTIFICATE + alias);
307 if (bytes == null) {
308 return null;
309 }
310 InputStream in = new ByteArrayInputStream(bytes);
311 X509Certificate cert;
312 try {
313 CertificateFactory cf = CertificateFactory.getInstance("X.509");
314 cert = (X509Certificate)cf.generateCertificate(in);
315 } catch (CertificateException ignored) {
316 return null;
317 }
318 // bouncycastle can handle the emailAddress OID of 1.2.840.113549.1.9.1
319 X500Principal subjectPrincipal = cert.getSubjectX500Principal();
320 X509Name subjectName = X509Name.getInstance(subjectPrincipal.getEncoded());
321 String subjectString = subjectName.toString(true, X509Name.DefaultSymbols);
322 return subjectString;
323 }
324 @Override protected void onPostExecute(String subjectString) {
325 mSubjects.set(mPosition, subjectString);
326 mSubjectView.setText(subjectString);
327 }
328 }
329 }
330
331 private static class ViewHolder {
332 TextView mAliasTextView;
333 TextView mSubjectTextView;
334 RadioButton mRadioButton;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700335 }
336
337 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
338 switch (requestCode) {
339 case REQUEST_UNLOCK:
340 if (isKeyStoreUnlocked()) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700341 showDialog(DIALOG_CERT_CHOOSER);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700342 } else {
343 // user must have canceled unlock, give up
Brian Carlstrombb04f702011-05-24 21:54:51 -0700344 finish(null);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700345 }
346 return;
347 default:
348 throw new AssertionError();
349 }
350 }
351
Brian Carlstrombb04f702011-05-24 21:54:51 -0700352 private void finish(String alias) {
353 if (alias == null) {
354 setResult(RESULT_CANCELED);
355 } else {
356 Intent result = new Intent();
357 result.putExtra(Intent.EXTRA_TEXT, alias);
358 setResult(RESULT_OK, result);
359 }
Brian Carlstromf5b50a42011-06-09 16:05:09 -0700360 IKeyChainAliasCallback keyChainAliasResponse
361 = IKeyChainAliasCallback.Stub.asInterface(
Brian Carlstrombb04f702011-05-24 21:54:51 -0700362 getIntent().getIBinderExtra(KeyChain.EXTRA_RESPONSE));
363 if (keyChainAliasResponse != null) {
364 try {
365 keyChainAliasResponse.alias(alias);
Brian Carlstrom2a858832011-05-26 09:30:26 -0700366 } catch (Exception ignored) {
367 // don't just catch RemoteException, caller could
368 // throw back a RuntimeException across processes
369 // which we should protect against.
Brian Carlstrombb04f702011-05-24 21:54:51 -0700370 }
371 }
372 finish();
373 }
374
Brian Carlstrom9e606df2011-06-07 12:03:08 -0700375 @Override public void onBackPressed() {
376 finish(null);
377 }
378
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700379 @Override protected void onSaveInstanceState(Bundle savedState) {
380 super.onSaveInstanceState(savedState);
381 if (mState != State.INITIAL) {
382 savedState.putSerializable(KEY_STATE, mState);
383 }
384 }
385}