2 * Copyright (C) 2012-2014 Tobias Brunner
3 * Copyright (C) 2012 Giuliano Grassi
4 * Copyright (C) 2012 Ralf Sager
5 * Hochschule fuer Technik Rapperswil
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 package org
.strongswan
.android
.ui
;
20 import java
.security
.cert
.X509Certificate
;
22 import org
.strongswan
.android
.R
;
23 import org
.strongswan
.android
.data
.VpnProfile
;
24 import org
.strongswan
.android
.data
.VpnProfileDataSource
;
25 import org
.strongswan
.android
.data
.VpnType
;
26 import org
.strongswan
.android
.data
.VpnType
.VpnTypeFeature
;
27 import org
.strongswan
.android
.logic
.TrustedCertificateManager
;
28 import org
.strongswan
.android
.security
.TrustedCertificateEntry
;
30 import android
.app
.Activity
;
31 import android
.app
.AlertDialog
;
32 import android
.app
.Dialog
;
33 import android
.app
.DialogFragment
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.os
.AsyncTask
;
38 import android
.os
.Bundle
;
39 import android
.security
.KeyChain
;
40 import android
.security
.KeyChainAliasCallback
;
41 import android
.security
.KeyChainException
;
42 import android
.text
.Html
;
43 import android
.util
.Log
;
44 import android
.view
.Menu
;
45 import android
.view
.MenuInflater
;
46 import android
.view
.MenuItem
;
47 import android
.view
.View
;
48 import android
.view
.View
.OnClickListener
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.AdapterView
;
51 import android
.widget
.AdapterView
.OnItemSelectedListener
;
52 import android
.widget
.CheckBox
;
53 import android
.widget
.CompoundButton
;
54 import android
.widget
.CompoundButton
.OnCheckedChangeListener
;
55 import android
.widget
.EditText
;
56 import android
.widget
.RelativeLayout
;
57 import android
.widget
.Spinner
;
58 import android
.widget
.TextView
;
60 public class VpnProfileDetailActivity
extends Activity
62 private static final int SELECT_TRUSTED_CERTIFICATE
= 0;
63 private static final int MTU_MIN
= 1280;
64 private static final int MTU_MAX
= 1500;
66 private VpnProfileDataSource mDataSource
;
68 private TrustedCertificateEntry mCertEntry
;
69 private String mUserCertLoading
;
70 private TrustedCertificateEntry mUserCertEntry
;
71 private VpnType mVpnType
= VpnType
.IKEV2_EAP
;
72 private VpnProfile mProfile
;
73 private EditText mName
;
74 private EditText mGateway
;
75 private Spinner mSelectVpnType
;
76 private ViewGroup mUsernamePassword
;
77 private EditText mUsername
;
78 private EditText mPassword
;
79 private ViewGroup mUserCertificate
;
80 private RelativeLayout mSelectUserCert
;
81 private CheckBox mCheckAuto
;
82 private RelativeLayout mSelectCert
;
83 private RelativeLayout mTncNotice
;
84 private CheckBox mShowAdvanced
;
85 private ViewGroup mAdvancedSettings
;
86 private EditText mMTU
;
87 private EditText mPort
;
88 private CheckBox mBlockIPv4
;
89 private CheckBox mBlockIPv6
;
92 public void onCreate(Bundle savedInstanceState
)
94 super.onCreate(savedInstanceState
);
96 /* the title is set when we load the profile, if any */
97 getActionBar().setDisplayHomeAsUpEnabled(true);
99 mDataSource
= new VpnProfileDataSource(this);
102 setContentView(R
.layout
.profile_detail_view
);
104 mName
= (EditText
)findViewById(R
.id
.name
);
105 mGateway
= (EditText
)findViewById(R
.id
.gateway
);
106 mSelectVpnType
= (Spinner
)findViewById(R
.id
.vpn_type
);
107 mTncNotice
= (RelativeLayout
)findViewById(R
.id
.tnc_notice
);
109 mUsernamePassword
= (ViewGroup
)findViewById(R
.id
.username_password_group
);
110 mUsername
= (EditText
)findViewById(R
.id
.username
);
111 mPassword
= (EditText
)findViewById(R
.id
.password
);
113 mUserCertificate
= (ViewGroup
)findViewById(R
.id
.user_certificate_group
);
114 mSelectUserCert
= (RelativeLayout
)findViewById(R
.id
.select_user_certificate
);
116 mCheckAuto
= (CheckBox
)findViewById(R
.id
.ca_auto
);
117 mSelectCert
= (RelativeLayout
)findViewById(R
.id
.select_certificate
);
119 mShowAdvanced
= (CheckBox
)findViewById(R
.id
.show_advanced
);
120 mAdvancedSettings
= (ViewGroup
)findViewById(R
.id
.advanced_settings
);
122 mMTU
= (EditText
)findViewById(R
.id
.mtu
);
123 mPort
= (EditText
)findViewById(R
.id
.port
);
124 mBlockIPv4
= (CheckBox
)findViewById(R
.id
.split_tunneling_v4
);
125 mBlockIPv6
= (CheckBox
)findViewById(R
.id
.split_tunneling_v6
);
127 mSelectVpnType
.setOnItemSelectedListener(new OnItemSelectedListener() {
129 public void onItemSelected(AdapterView
<?
> parent
, View view
, int position
, long id
)
131 mVpnType
= VpnType
.values()[position
];
132 updateCredentialView();
136 public void onNothingSelected(AdapterView
<?
> parent
)
137 { /* should not happen */
138 mVpnType
= VpnType
.IKEV2_EAP
;
139 updateCredentialView();
143 ((TextView
)mTncNotice
.findViewById(android
.R
.id
.text1
)).setText(R
.string
.tnc_notice_title
);
144 ((TextView
)mTncNotice
.findViewById(android
.R
.id
.text2
)).setText(R
.string
.tnc_notice_subtitle
);
145 mTncNotice
.setOnClickListener(new OnClickListener() {
147 public void onClick(View v
)
149 new TncNoticeDialog().show(VpnProfileDetailActivity
.this.getFragmentManager(), "TncNotice");
153 mSelectUserCert
.setOnClickListener(new SelectUserCertOnClickListener());
155 mCheckAuto
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
157 public void onCheckedChanged(CompoundButton buttonView
, boolean isChecked
)
159 updateCertificateSelector();
163 mSelectCert
.setOnClickListener(new OnClickListener() {
165 public void onClick(View v
)
167 Intent intent
= new Intent(VpnProfileDetailActivity
.this, TrustedCertificatesActivity
.class);
168 intent
.setAction(TrustedCertificatesActivity
.SELECT_CERTIFICATE
);
169 startActivityForResult(intent
, SELECT_TRUSTED_CERTIFICATE
);
173 mShowAdvanced
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
175 public void onCheckedChanged(CompoundButton buttonView
, boolean isChecked
)
177 updateAdvancedSettings();
181 mId
= savedInstanceState
== null ?
null : savedInstanceState
.getLong(VpnProfileDataSource
.KEY_ID
);
184 Bundle extras
= getIntent().getExtras();
185 mId
= extras
== null ?
null : extras
.getLong(VpnProfileDataSource
.KEY_ID
);
188 loadProfileData(savedInstanceState
);
190 updateCredentialView();
191 updateCertificateSelector();
192 updateAdvancedSettings();
196 protected void onDestroy()
203 protected void onSaveInstanceState(Bundle outState
)
205 super.onSaveInstanceState(outState
);
208 outState
.putLong(VpnProfileDataSource
.KEY_ID
, mId
);
210 if (mUserCertEntry
!= null)
212 outState
.putString(VpnProfileDataSource
.KEY_USER_CERTIFICATE
, mUserCertEntry
.getAlias());
214 if (mCertEntry
!= null)
216 outState
.putString(VpnProfileDataSource
.KEY_CERTIFICATE
, mCertEntry
.getAlias());
221 public boolean onCreateOptionsMenu(Menu menu
)
223 MenuInflater inflater
= getMenuInflater();
224 inflater
.inflate(R
.menu
.profile_edit
, menu
);
229 public boolean onOptionsItemSelected(MenuItem item
)
231 switch (item
.getItemId())
233 case android
.R
.id
.home
:
234 case R
.id
.menu_cancel
:
237 case R
.id
.menu_accept
:
241 return super.onOptionsItemSelected(item
);
246 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
)
250 case SELECT_TRUSTED_CERTIFICATE
:
251 if (resultCode
== RESULT_OK
)
253 String alias
= data
.getStringExtra(VpnProfileDataSource
.KEY_CERTIFICATE
);
254 X509Certificate certificate
= TrustedCertificateManager
.getInstance().getCACertificateFromAlias(alias
);
255 mCertEntry
= certificate
== null ?
null : new TrustedCertificateEntry(alias
, certificate
);
256 updateCertificateSelector();
260 super.onActivityResult(requestCode
, resultCode
, data
);
265 * Update the UI to enter credentials depending on the type of VPN currently selected
267 private void updateCredentialView()
269 mUsernamePassword
.setVisibility(mVpnType
.has(VpnTypeFeature
.USER_PASS
) ? View
.VISIBLE
: View
.GONE
);
270 mUserCertificate
.setVisibility(mVpnType
.has(VpnTypeFeature
.CERTIFICATE
) ? View
.VISIBLE
: View
.GONE
);
271 mTncNotice
.setVisibility(mVpnType
.has(VpnTypeFeature
.BYOD
) ? View
.VISIBLE
: View
.GONE
);
273 if (mVpnType
.has(VpnTypeFeature
.CERTIFICATE
))
275 if (mUserCertLoading
!= null)
277 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text1
)).setText(mUserCertLoading
);
278 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text2
)).setText(R
.string
.loading
);
280 else if (mUserCertEntry
!= null)
281 { /* clear any errors and set the new data */
282 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text1
)).setError(null);
283 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text1
)).setText(mUserCertEntry
.getAlias());
284 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text2
)).setText(mUserCertEntry
.getCertificate().getSubjectDN().toString());
288 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text1
)).setText(R
.string
.profile_user_select_certificate_label
);
289 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text2
)).setText(R
.string
.profile_user_select_certificate
);
295 * Show an alert in case the previously selected certificate is not found anymore
296 * or the user did not select a certificate in the spinner.
298 private void showCertificateAlert()
300 AlertDialog
.Builder adb
= new AlertDialog
.Builder(VpnProfileDetailActivity
.this);
301 adb
.setTitle(R
.string
.alert_text_nocertfound_title
);
302 adb
.setMessage(R
.string
.alert_text_nocertfound
);
303 adb
.setPositiveButton(android
.R
.string
.ok
, new DialogInterface
.OnClickListener() {
305 public void onClick(DialogInterface dialog
, int id
)
314 * Update the CA certificate selection UI depending on whether the
315 * certificate should be automatically selected or not.
317 private void updateCertificateSelector()
319 if (!mCheckAuto
.isChecked())
321 mSelectCert
.setEnabled(true);
322 mSelectCert
.setVisibility(View
.VISIBLE
);
324 if (mCertEntry
!= null)
326 ((TextView
)mSelectCert
.findViewById(android
.R
.id
.text1
)).setText(mCertEntry
.getSubjectPrimary());
327 ((TextView
)mSelectCert
.findViewById(android
.R
.id
.text2
)).setText(mCertEntry
.getSubjectSecondary());
331 ((TextView
)mSelectCert
.findViewById(android
.R
.id
.text1
)).setText(R
.string
.profile_ca_select_certificate_label
);
332 ((TextView
)mSelectCert
.findViewById(android
.R
.id
.text2
)).setText(R
.string
.profile_ca_select_certificate
);
337 mSelectCert
.setEnabled(false);
338 mSelectCert
.setVisibility(View
.GONE
);
343 * Update the advanced settings UI depending on whether any advanced
344 * settings have already been made.
346 private void updateAdvancedSettings()
348 boolean show
= mShowAdvanced
.isChecked();
349 if (!show
&& mProfile
!= null)
351 Integer st
= mProfile
.getSplitTunneling();
352 show
= mProfile
.getMTU() != null || mProfile
.getPort() != null || (st
!= null && st
!= 0);
354 mShowAdvanced
.setVisibility(!show ? View
.VISIBLE
: View
.GONE
);
355 mAdvancedSettings
.setVisibility(show ? View
.VISIBLE
: View
.GONE
);
359 * Save or update the profile depending on whether we actually have a
360 * profile object or not (this was created in updateProfileData)
362 private void saveProfile()
366 if (mProfile
!= null)
369 mDataSource
.updateVpnProfile(mProfile
);
373 mProfile
= new VpnProfile();
375 mDataSource
.insertProfile(mProfile
);
377 setResult(RESULT_OK
, new Intent().putExtra(VpnProfileDataSource
.KEY_ID
, mProfile
.getId()));
383 * Verify the user input and display error messages.
384 * @return true if the input is valid
386 private boolean verifyInput()
388 boolean valid
= true;
389 if (mGateway
.getText().toString().trim().isEmpty())
391 mGateway
.setError(getString(R
.string
.alert_text_no_input_gateway
));
394 if (mVpnType
.has(VpnTypeFeature
.USER_PASS
))
396 if (mUsername
.getText().toString().trim().isEmpty())
398 mUsername
.setError(getString(R
.string
.alert_text_no_input_username
));
402 if (mVpnType
.has(VpnTypeFeature
.CERTIFICATE
) && mUserCertEntry
== null)
403 { /* let's show an error icon */
404 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text1
)).setError("");
407 if (!mCheckAuto
.isChecked() && mCertEntry
== null)
409 showCertificateAlert();
412 Integer mtu
= getInteger(mMTU
);
413 if (mtu
!= null && (mtu
< MTU_MIN
|| mtu
> MTU_MAX
))
415 mMTU
.setError(String
.format(getString(R
.string
.alert_text_out_of_range
), MTU_MIN
, MTU_MAX
));
418 Integer port
= getInteger(mPort
);
419 if (port
!= null && (port
< 1 || port
> 65535))
421 mPort
.setError(String
.format(getString(R
.string
.alert_text_out_of_range
), 1, 65535));
428 * Update the profile object with the data entered by the user
430 private void updateProfileData()
432 /* the name is optional, we default to the gateway if none is given */
433 String name
= mName
.getText().toString().trim();
434 String gateway
= mGateway
.getText().toString().trim();
435 mProfile
.setName(name
.isEmpty() ? gateway
: name
);
436 mProfile
.setGateway(gateway
);
437 mProfile
.setVpnType(mVpnType
);
438 if (mVpnType
.has(VpnTypeFeature
.USER_PASS
))
440 mProfile
.setUsername(mUsername
.getText().toString().trim());
441 String password
= mPassword
.getText().toString().trim();
442 password
= password
.isEmpty() ?
null : password
;
443 mProfile
.setPassword(password
);
445 if (mVpnType
.has(VpnTypeFeature
.CERTIFICATE
))
447 mProfile
.setUserCertificateAlias(mUserCertEntry
.getAlias());
449 String certAlias
= mCheckAuto
.isChecked() ?
null : mCertEntry
.getAlias();
450 mProfile
.setCertificateAlias(certAlias
);
451 mProfile
.setMTU(getInteger(mMTU
));
452 mProfile
.setPort(getInteger(mPort
));
454 st
|= mBlockIPv4
.isChecked() ? VpnProfile
.SPLIT_TUNNELING_BLOCK_IPV4
: 0;
455 st
|= mBlockIPv6
.isChecked() ? VpnProfile
.SPLIT_TUNNELING_BLOCK_IPV6
: 0;
456 mProfile
.setSplitTunneling(st
== 0 ?
null : st
);
460 * Load an existing profile if we got an ID
462 * @param savedInstanceState previously saved state
464 private void loadProfileData(Bundle savedInstanceState
)
466 String useralias
= null, alias
= null;
468 getActionBar().setTitle(R
.string
.add_profile
);
469 if (mId
!= null && mId
!= 0)
471 mProfile
= mDataSource
.getVpnProfile(mId
);
472 if (mProfile
!= null)
474 mName
.setText(mProfile
.getName());
475 mGateway
.setText(mProfile
.getGateway());
476 mVpnType
= mProfile
.getVpnType();
477 mUsername
.setText(mProfile
.getUsername());
478 mPassword
.setText(mProfile
.getPassword());
479 mMTU
.setText(mProfile
.getMTU() != null ? mProfile
.getMTU().toString() : null);
480 mPort
.setText(mProfile
.getPort() != null ? mProfile
.getPort().toString() : null);
481 mBlockIPv4
.setChecked(mProfile
.getSplitTunneling() != null ?
(mProfile
.getSplitTunneling() & VpnProfile
.SPLIT_TUNNELING_BLOCK_IPV4
) != 0 : false);
482 mBlockIPv6
.setChecked(mProfile
.getSplitTunneling() != null ?
(mProfile
.getSplitTunneling() & VpnProfile
.SPLIT_TUNNELING_BLOCK_IPV6
) != 0 : false);
483 useralias
= mProfile
.getUserCertificateAlias();
484 alias
= mProfile
.getCertificateAlias();
485 getActionBar().setTitle(mProfile
.getName());
489 Log
.e(VpnProfileDetailActivity
.class.getSimpleName(),
490 "VPN profile with id " + mId
+ " not found");
495 mSelectVpnType
.setSelection(mVpnType
.ordinal());
497 /* check if the user selected a user certificate previously */
498 useralias
= savedInstanceState
== null ? useralias
: savedInstanceState
.getString(VpnProfileDataSource
.KEY_USER_CERTIFICATE
);
499 if (useralias
!= null)
501 UserCertificateLoader loader
= new UserCertificateLoader(this, useralias
);
502 mUserCertLoading
= useralias
;
506 /* check if the user selected a CA certificate previously */
507 alias
= savedInstanceState
== null ? alias
: savedInstanceState
.getString(VpnProfileDataSource
.KEY_CERTIFICATE
);
508 mCheckAuto
.setChecked(alias
== null);
511 X509Certificate certificate
= TrustedCertificateManager
.getInstance().getCACertificateFromAlias(alias
);
512 if (certificate
!= null)
514 mCertEntry
= new TrustedCertificateEntry(alias
, certificate
);
517 { /* previously selected certificate is not here anymore */
518 showCertificateAlert();
525 * Get the integer value in the given text box or null if empty
527 * @param view text box (numeric entry assumed)
529 private Integer
getInteger(EditText view
)
531 String value
= view
.getText().toString().trim();
532 return value
.isEmpty() ?
null : Integer
.valueOf(value
);
535 private class SelectUserCertOnClickListener
implements OnClickListener
, KeyChainAliasCallback
538 public void onClick(View v
)
540 String useralias
= mUserCertEntry
!= null ? mUserCertEntry
.getAlias() : null;
541 KeyChain
.choosePrivateKeyAlias(VpnProfileDetailActivity
.this, this, new String
[] { "RSA" }, null, null, -1, useralias
);
545 public void alias(final String alias
)
548 { /* otherwise the dialog was canceled, the request denied */
551 final X509Certificate
[] chain
= KeyChain
.getCertificateChain(VpnProfileDetailActivity
.this, alias
);
552 /* alias() is not called from our main thread */
553 runOnUiThread(new Runnable() {
557 if (chain
!= null && chain
.length
> 0)
559 mUserCertEntry
= new TrustedCertificateEntry(alias
, chain
[0]);
561 updateCredentialView();
565 catch (KeyChainException e
)
569 catch (InterruptedException e
)
578 * Load the selected user certificate asynchronously. This cannot be done
579 * from the main thread as getCertificateChain() calls back to our main
580 * thread to bind to the KeyChain service resulting in a deadlock.
582 private class UserCertificateLoader
extends AsyncTask
<Void
, Void
, X509Certificate
>
584 private final Context mContext
;
585 private final String mAlias
;
587 public UserCertificateLoader(Context context
, String alias
)
594 protected X509Certificate
doInBackground(Void
... params
)
596 X509Certificate
[] chain
= null;
599 chain
= KeyChain
.getCertificateChain(mContext
, mAlias
);
601 catch (KeyChainException e
)
605 catch (InterruptedException e
)
609 if (chain
!= null && chain
.length
> 0)
617 protected void onPostExecute(X509Certificate result
)
621 mUserCertEntry
= new TrustedCertificateEntry(mAlias
, result
);
624 { /* previously selected certificate is not here anymore */
625 ((TextView
)mSelectUserCert
.findViewById(android
.R
.id
.text1
)).setError("");
626 mUserCertEntry
= null;
628 mUserCertLoading
= null;
629 updateCredentialView();
634 * Dialog with notification message if EAP-TNC is used.
636 public static class TncNoticeDialog
extends DialogFragment
639 public Dialog
onCreateDialog(Bundle savedInstanceState
)
641 return new AlertDialog
.Builder(getActivity())
642 .setTitle(R
.string
.tnc_notice_title
)
643 .setMessage(Html
.fromHtml(getString(R
.string
.tnc_notice_details
)))
644 .setPositiveButton(android
.R
.string
.ok
, new DialogInterface
.OnClickListener() {
646 public void onClick(DialogInterface dialog
, int id
)