android: Avoid IllegalStateException when importing certificates
[strongswan.git] / src / frontends / android / app / src / main / java / org / strongswan / android / ui / TrustedCertificateImportActivity.java
1 /*
2 * Copyright (C) 2014 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 package org.strongswan.android.ui;
17
18 import android.annotation.TargetApi;
19 import android.app.Activity;
20 import android.app.Dialog;
21 import android.content.DialogInterface;
22 import android.content.Intent;
23 import android.net.Uri;
24 import android.os.Build;
25 import android.os.Bundle;
26 import android.support.v4.app.FragmentTransaction;
27 import android.support.v7.app.AlertDialog;
28 import android.support.v7.app.AppCompatActivity;
29 import android.support.v7.app.AppCompatDialogFragment;
30 import android.widget.Toast;
31
32 import org.strongswan.android.R;
33 import org.strongswan.android.data.VpnProfileDataSource;
34 import org.strongswan.android.logic.TrustedCertificateManager;
35
36 import java.io.FileNotFoundException;
37 import java.io.InputStream;
38 import java.security.KeyStore;
39 import java.security.cert.CertificateException;
40 import java.security.cert.CertificateFactory;
41 import java.security.cert.X509Certificate;
42
43 public class TrustedCertificateImportActivity extends AppCompatActivity
44 {
45 private static final int OPEN_DOCUMENT = 0;
46 private static final String DIALOG_TAG = "Dialog";
47
48 /* same as those listed in the manifest */
49 private static final String[] ACCEPTED_MIME_TYPES = {
50 "application/x-x509-ca-cert",
51 "application/x-x509-server-cert",
52 "application/x-pem-file",
53 "application/pkix-cert"
54 };
55 private Uri mCertificateUri;
56
57 @TargetApi(Build.VERSION_CODES.KITKAT)
58 @Override
59 public void onCreate(Bundle savedInstanceState)
60 {
61 super.onCreate(savedInstanceState);
62
63 if (savedInstanceState != null)
64 { /* do nothing when we are restoring */
65 return;
66 }
67
68 Intent intent = getIntent();
69 String action = intent.getAction();
70 if (Intent.ACTION_VIEW.equals(action))
71 {
72 importCertificate(intent.getData());
73 }
74 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
75 {
76 Intent openIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
77 openIntent.setType("*/*");
78 openIntent.putExtra(Intent.EXTRA_MIME_TYPES, ACCEPTED_MIME_TYPES);
79 startActivityForResult(openIntent, OPEN_DOCUMENT);
80 }
81 }
82
83 @Override
84 protected void onActivityResult(int requestCode, int resultCode, Intent data)
85 {
86 super.onActivityResult(requestCode, resultCode, data);
87 switch (requestCode)
88 {
89 case OPEN_DOCUMENT:
90 if (resultCode == Activity.RESULT_OK && data != null)
91 {
92 mCertificateUri = data.getData();
93 return;
94 }
95 finish();
96 return;
97 }
98 }
99
100 @Override
101 protected void onPostResume()
102 {
103 super.onPostResume();
104 if (mCertificateUri != null)
105 {
106 importCertificate(mCertificateUri);
107 mCertificateUri = null;
108 }
109 }
110
111 /**
112 * Import the file pointed to by the given URI as a certificate.
113 *
114 * @param uri
115 */
116 private void importCertificate(Uri uri)
117 {
118 X509Certificate certificate = parseCertificate(uri);
119 if (certificate == null)
120 {
121 Toast.makeText(this, R.string.cert_import_failed, Toast.LENGTH_LONG).show();
122 finish();
123 return;
124 }
125 /* Ask the user whether to import the certificate. This is particularly
126 * necessary because the import activity can be triggered by any app on
127 * the system. Also, if our app is the only one that is registered to
128 * open certificate files by MIME type the user would have no idea really
129 * where the file was imported just by reading the Toast we display. */
130 ConfirmImportDialog dialog = new ConfirmImportDialog();
131 Bundle args = new Bundle();
132 args.putSerializable(VpnProfileDataSource.KEY_CERTIFICATE, certificate);
133 dialog.setArguments(args);
134 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
135 ft.add(dialog, DIALOG_TAG);
136 ft.commit();
137 }
138
139 /**
140 * Load the file from the given URI and try to parse it as X.509 certificate.
141 *
142 * @param uri
143 * @return certificate or null
144 */
145 private X509Certificate parseCertificate(Uri uri)
146 {
147 X509Certificate certificate = null;
148 try
149 {
150 CertificateFactory factory = CertificateFactory.getInstance("X.509");
151 InputStream in = getContentResolver().openInputStream(uri);
152 certificate = (X509Certificate)factory.generateCertificate(in);
153 /* we don't check whether it's actually a CA certificate or not */
154 }
155 catch (CertificateException e)
156 {
157 e.printStackTrace();
158 }
159 catch (FileNotFoundException e)
160 {
161 e.printStackTrace();
162 }
163 return certificate;
164 }
165
166
167 /**
168 * Try to store the given certificate in the KeyStore.
169 *
170 * @param certificate
171 * @return whether it was successfully stored
172 */
173 private boolean storeCertificate(X509Certificate certificate)
174 {
175 try
176 {
177 KeyStore store = KeyStore.getInstance("LocalCertificateStore");
178 store.load(null, null);
179 store.setCertificateEntry(null, certificate);
180 TrustedCertificateManager.getInstance().reset();
181 return true;
182 }
183 catch (Exception e)
184 {
185 e.printStackTrace();
186 return false;
187 }
188 }
189
190 /**
191 * Class that displays a confirmation dialog when a certificate should get
192 * imported. If the user confirms the import we try to store it.
193 */
194 public static class ConfirmImportDialog extends AppCompatDialogFragment
195 {
196 @Override
197 public Dialog onCreateDialog(Bundle savedInstanceState)
198 {
199 final X509Certificate certificate;
200
201 certificate = (X509Certificate)getArguments().getSerializable(VpnProfileDataSource.KEY_CERTIFICATE);
202
203 return new AlertDialog.Builder(getActivity())
204 .setIcon(R.drawable.ic_launcher)
205 .setTitle(R.string.import_certificate)
206 .setMessage(certificate.getSubjectDN().toString())
207 .setPositiveButton(R.string.import_certificate, new DialogInterface.OnClickListener()
208 {
209 @Override
210 public void onClick(DialogInterface dialog, int whichButton)
211 {
212 TrustedCertificateImportActivity activity = (TrustedCertificateImportActivity)getActivity();
213 if (activity.storeCertificate(certificate))
214 {
215 Toast.makeText(getActivity(), R.string.cert_imported_successfully, Toast.LENGTH_LONG).show();
216 getActivity().setResult(Activity.RESULT_OK);
217 }
218 else
219 {
220 Toast.makeText(getActivity(), R.string.cert_import_failed, Toast.LENGTH_LONG).show();
221 }
222 getActivity().finish();
223 }
224 })
225 .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
226 {
227 @Override
228 public void onClick(DialogInterface dialog, int which)
229 {
230 getActivity().finish();
231 }
232 }).create();
233 }
234
235 @Override
236 public void onCancel(DialogInterface dialog)
237 {
238 getActivity().finish();
239 }
240 }
241 }