From 3315ceaa78a45c39196a99d1dda35b1a9b59ec00 Mon Sep 17 00:00:00 2001 From: Robin Lee Date: Tue, 26 Jul 2016 16:16:22 +0100 Subject: Fix KeyChain crash (#530) This happens due to a race condition in background threads that use an activity context to call long-running RPCs in keychain and keystore. If the activity goes away while services are still bound, its context will be disposed of and any attempts to unbind those services will raise an IllegalStateException. The right thing to do is make these calls using an application context instead. --- main/src/main/java/de/blinkt/openvpn/VpnProfile.java | 4 ++++ main/src/main/java/de/blinkt/openvpn/fragments/Settings_Basic.java | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) (limited to 'main') diff --git a/main/src/main/java/de/blinkt/openvpn/VpnProfile.java b/main/src/main/java/de/blinkt/openvpn/VpnProfile.java index a082ce8e..fe8cb19a 100644 --- a/main/src/main/java/de/blinkt/openvpn/VpnProfile.java +++ b/main/src/main/java/de/blinkt/openvpn/VpnProfile.java @@ -747,6 +747,10 @@ public class VpnProfile implements Serializable, Cloneable { } synchronized String[] getKeyStoreCertificates(Context context, int tries) { + // Force application context- KeyChain methods will block long enough that by the time they + // are finished and try to unbind, the original activity context might have been destroyed. + context = context.getApplicationContext(); + try { PrivateKey privateKey = KeyChain.getPrivateKey(context, mAlias); mPrivateKey = privateKey; diff --git a/main/src/main/java/de/blinkt/openvpn/fragments/Settings_Basic.java b/main/src/main/java/de/blinkt/openvpn/fragments/Settings_Basic.java index 78976c44..ea8768d3 100644 --- a/main/src/main/java/de/blinkt/openvpn/fragments/Settings_Basic.java +++ b/main/src/main/java/de/blinkt/openvpn/fragments/Settings_Basic.java @@ -81,7 +81,7 @@ public class Settings_Basic extends Settings_Fragment implements View.OnClickLis public void run() { String certstr=""; try { - X509Certificate cert = KeyChain.getCertificateChain(getActivity(), mProfile.mAlias)[0]; + X509Certificate cert = KeyChain.getCertificateChain(getActivity().getApplicationContext(), mProfile.mAlias)[0]; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { { @@ -111,7 +111,7 @@ public class Settings_Basic extends Settings_Fragment implements View.OnClickLis @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private boolean isInHardwareKeystore() throws KeyChainException, InterruptedException { - String algorithm = KeyChain.getPrivateKey(getActivity(), mProfile.mAlias).getAlgorithm(); + String algorithm = KeyChain.getPrivateKey(getActivity().getApplicationContext(), mProfile.mAlias).getAlgorithm(); return KeyChain.isBoundKeyAlgorithm(algorithm); } -- cgit v1.2.3