blob: 10735567aec3930a386eaf2ea4a7744e88c28e37 [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() {
144 View view = View.inflate(this, R.layout.cert_chooser, null);
145
146 AlertDialog.Builder builder = new AlertDialog.Builder(this);
147 builder.setView(view);
148 builder.setNegativeButton(R.string.deny_button, new DialogInterface.OnClickListener() {
149 @Override public void onClick(DialogInterface dialog, int id) {
150 dialog.cancel(); // will cause OnDismissListener to be called
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700151 }
152 });
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700153
154 Resources res = getResources();
155
156 String title;
157 if (mCertificateAdapter.mAliases.isEmpty()) {
158 title = res.getString(R.string.title_no_certs);
159 } else {
160 title = res.getString(R.string.title_select_cert);
161 final ListView lv = (ListView) view.findViewById(R.id.cert_chooser_cert_list);
162 lv.setAdapter(mCertificateAdapter);
163 String alias = getIntent().getStringExtra(KeyChain.EXTRA_ALIAS);
164 if (alias != null) {
165 int position = mCertificateAdapter.mAliases.indexOf(alias);
166 if (position != -1) {
167 lv.setItemChecked(position, true);
168 }
169 }
170
171 builder.setPositiveButton(R.string.allow_button, new DialogInterface.OnClickListener() {
172 @Override public void onClick(DialogInterface dialog, int id) {
173 int pos = lv.getCheckedItemPosition();
174 String alias = ((pos != ListView.INVALID_POSITION)
175 ? mCertificateAdapter.getItem(pos)
176 : null);
177 finish(alias);
178 }
179 });
180
181 lv.setVisibility(View.VISIBLE);
182 }
183 builder.setTitle(title);
184
185 PendingIntent sender = getIntent().getParcelableExtra(KeyChain.EXTRA_SENDER);
186 if (sender == null) {
187 // if no sender, bail, we need to identify the app to the user securely.
188 finish(null);
189 }
190
191 // getTargetPackage guarantees that the returned string is
192 // supplied by the system, so that an application can not
193 // spoof its package.
194 String pkg = sender.getIntentSender().getTargetPackage();
195 PackageManager pm = getPackageManager();
196 CharSequence applicationLabel;
197 try {
198 applicationLabel = pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString();
199 } catch (PackageManager.NameNotFoundException e) {
200 applicationLabel = pkg;
201 }
202 String appMessage = String.format(res.getString(R.string.requesting_application),
203 applicationLabel);
204
205 String contextMessage = appMessage;
206 String host = getIntent().getStringExtra(KeyChain.EXTRA_HOST);
207 if (host != null) {
208 String hostString = host;
209 int port = getIntent().getIntExtra(KeyChain.EXTRA_PORT, -1);
210 if (port != -1) {
211 hostString += ":" + port;
212 }
213 String hostMessage = String.format(res.getString(R.string.requesting_server),
214 hostString);
215 if (contextMessage == null) {
216 contextMessage = hostMessage;
217 } else {
218 contextMessage += " " + hostMessage;
219 }
220 }
221 TextView contextView = (TextView) view.findViewById(R.id.cert_chooser_context_message);
222 contextView.setText(contextMessage);
223 contextView.setVisibility(View.VISIBLE);
224
225 String installMessage = String.format(res.getString(R.string.install_new_cert_message),
226 Credentials.EXTENSION_PFX, Credentials.EXTENSION_P12);
227 TextView installTextView = (TextView) view.findViewById(R.id.cert_chooser_install_message);
228 installTextView.setText(installMessage);
229
230 Button installButton = (Button) view.findViewById(R.id.cert_chooser_install_button);
231 installButton.setOnClickListener(new View.OnClickListener() {
232 @Override public void onClick(View v) {
233 // remove dialog so that we will recreate with
234 // possibly new content after install returns
235 removeDialog(DIALOG_CERT_CHOOSER);
236 Credentials.getInstance().install(KeyChainActivity.this);
237 }
238 });
239
240 Dialog dialog = builder.create();
241 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
242 @Override public void onCancel(DialogInterface dialog) {
243 finish(null);
244 }
245 });
246 return dialog;
247 }
248
249 private class CertificateAdapter extends BaseAdapter {
250 private final List<String> mAliases;
251 private final List<String> mSubjects = new ArrayList<String>();
252 private CertificateAdapter(List<String> aliases) {
253 mAliases = aliases;
254 mSubjects.addAll(Collections.nCopies(aliases.size(), (String) null));
255 }
256 @Override public int getCount() {
257 return mAliases.size();
258 }
259 @Override public String getItem(int position) {
260 return mAliases.get(position);
261 }
262 @Override public long getItemId(int position) {
263 return position;
264 }
265 @Override public View getView(final int position, View view, ViewGroup parent) {
266 ViewHolder holder;
267 if (view == null) {
268 LayoutInflater inflater = LayoutInflater.from(KeyChainActivity.this);
269 view = inflater.inflate(R.layout.cert_item, parent, false);
270 holder = new ViewHolder();
271 holder.mAliasTextView = (TextView) view.findViewById(R.id.cert_item_alias);
272 holder.mSubjectTextView = (TextView) view.findViewById(R.id.cert_item_subject);
273 holder.mRadioButton = (RadioButton) view.findViewById(R.id.cert_item_selected);
274 view.setTag(holder);
275 } else {
276 holder = (ViewHolder) view.getTag();
277 }
278
279 String alias = mAliases.get(position);
280
281 holder.mAliasTextView.setText(alias);
282
283 String subject = mSubjects.get(position);
284 if (subject == null) {
285 new CertLoader(position, holder.mSubjectTextView).execute();
286 } else {
287 holder.mSubjectTextView.setText(subject);
288 }
289
290 ListView lv = (ListView)parent;
291 holder.mRadioButton.setChecked(position == lv.getCheckedItemPosition());
292 return view;
293 }
294
295 private class CertLoader extends AsyncTask<Void, Void, String> {
296 private final int mPosition;
297 private final TextView mSubjectView;
298 private CertLoader(int position, TextView subjectView) {
299 mPosition = position;
300 mSubjectView = subjectView;
301 }
302 @Override protected String doInBackground(Void... params) {
303 String alias = mAliases.get(mPosition);
304 byte[] bytes = mKeyStore.get(Credentials.USER_CERTIFICATE + alias);
305 if (bytes == null) {
306 return null;
307 }
308 InputStream in = new ByteArrayInputStream(bytes);
309 X509Certificate cert;
310 try {
311 CertificateFactory cf = CertificateFactory.getInstance("X.509");
312 cert = (X509Certificate)cf.generateCertificate(in);
313 } catch (CertificateException ignored) {
314 return null;
315 }
316 // bouncycastle can handle the emailAddress OID of 1.2.840.113549.1.9.1
317 X500Principal subjectPrincipal = cert.getSubjectX500Principal();
318 X509Name subjectName = X509Name.getInstance(subjectPrincipal.getEncoded());
319 String subjectString = subjectName.toString(true, X509Name.DefaultSymbols);
320 return subjectString;
321 }
322 @Override protected void onPostExecute(String subjectString) {
323 mSubjects.set(mPosition, subjectString);
324 mSubjectView.setText(subjectString);
325 }
326 }
327 }
328
329 private static class ViewHolder {
330 TextView mAliasTextView;
331 TextView mSubjectTextView;
332 RadioButton mRadioButton;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700333 }
334
335 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
336 switch (requestCode) {
337 case REQUEST_UNLOCK:
338 if (isKeyStoreUnlocked()) {
Brian Carlstrom65e649e2011-06-24 02:13:28 -0700339 showDialog(DIALOG_CERT_CHOOSER);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700340 } else {
341 // user must have canceled unlock, give up
Brian Carlstrombb04f702011-05-24 21:54:51 -0700342 finish(null);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700343 }
344 return;
345 default:
346 throw new AssertionError();
347 }
348 }
349
Brian Carlstrombb04f702011-05-24 21:54:51 -0700350 private void finish(String alias) {
351 if (alias == null) {
352 setResult(RESULT_CANCELED);
353 } else {
354 Intent result = new Intent();
355 result.putExtra(Intent.EXTRA_TEXT, alias);
356 setResult(RESULT_OK, result);
357 }
Brian Carlstromf5b50a42011-06-09 16:05:09 -0700358 IKeyChainAliasCallback keyChainAliasResponse
359 = IKeyChainAliasCallback.Stub.asInterface(
Brian Carlstrombb04f702011-05-24 21:54:51 -0700360 getIntent().getIBinderExtra(KeyChain.EXTRA_RESPONSE));
361 if (keyChainAliasResponse != null) {
362 try {
363 keyChainAliasResponse.alias(alias);
Brian Carlstrom2a858832011-05-26 09:30:26 -0700364 } catch (Exception ignored) {
365 // don't just catch RemoteException, caller could
366 // throw back a RuntimeException across processes
367 // which we should protect against.
Brian Carlstrombb04f702011-05-24 21:54:51 -0700368 }
369 }
370 finish();
371 }
372
Brian Carlstrom9e606df2011-06-07 12:03:08 -0700373 @Override public void onBackPressed() {
374 finish(null);
375 }
376
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700377 @Override protected void onSaveInstanceState(Bundle savedState) {
378 super.onSaveInstanceState(savedState);
379 if (mState != State.INITIAL) {
380 savedState.putSerializable(KEY_STATE, mState);
381 }
382 }
383}