From 0b647ea5e7ff67747080b2ffcebc948da0fbecb5 Mon Sep 17 00:00:00 2001 From: cyBerta Date: Tue, 9 Jan 2018 20:55:10 +0100 Subject: 8773 refactoring ProviderAPI for testability, setting up basic unit test framework --- app/build.gradle | 14 +- .../java/se/leap/bitmaskclient/ProviderAPI.java | 422 -------- .../se/leap/bitmaskclient/ProviderApiManager.java | 430 ++++++++ app/src/main/AndroidManifest.xml | 2 +- .../bitmaskclient/BaseConfigurationWizard.java | 4 +- .../java/se/leap/bitmaskclient/ConfigHelper.java | 60 +- .../leap/bitmaskclient/DownloadFailedDialog.java | 16 +- .../leap/bitmaskclient/OkHttpClientGenerator.java | 166 +++ .../java/se/leap/bitmaskclient/ProviderAPI.java | 124 +++ .../bitmaskclient/ProviderAPIResultReceiver.java | 4 +- .../se/leap/bitmaskclient/ProviderApiBase.java | 1061 -------------------- .../leap/bitmaskclient/ProviderApiConnector.java | 102 ++ .../leap/bitmaskclient/ProviderApiManagerBase.java | 984 ++++++++++++++++++ .../bitmaskclient/userstatus/SessionDialog.java | 2 - .../java/se/leap/bitmaskclient/ProviderAPI.java | 327 ------ .../se/leap/bitmaskclient/ProviderApiManager.java | 340 +++++++ .../test/java/se/leap/bitmaskclient/TestUtils.java | 26 - .../bitmaskclient/eip/GatewaysManagerTest.java | 10 +- .../bitmaskclient/eip/ProviderApiManagerTest.java | 249 +++++ .../bitmaskclient/eip/VpnConfigGeneratorTest.java | 10 +- .../testutils/MockSharedPreferences.java | 165 +++ .../bitmaskclient/testutils/TestSetupHelper.java | 443 ++++++++ .../testutils/answers/BackendAnswerFabric.java | 82 ++ .../testutils/answers/NoErrorAnswer.java | 58 ++ .../testutils/matchers/BundleMatcher.java | 192 ++++ app/src/test/resources/error_messages.json | 16 + app/src/test/resources/riseup.net.json | 37 + app/src/test/resources/riseup.net.pem | 32 + app/src/test/resources/riseup.service.json | 93 ++ app/src/test/resources/secrets.json | 2 +- 30 files changed, 3589 insertions(+), 1884 deletions(-) delete mode 100644 app/src/insecure/java/se/leap/bitmaskclient/ProviderAPI.java create mode 100644 app/src/insecure/java/se/leap/bitmaskclient/ProviderApiManager.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/OkHttpClientGenerator.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java delete mode 100644 app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/ProviderApiConnector.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java delete mode 100644 app/src/production/java/se/leap/bitmaskclient/ProviderAPI.java create mode 100644 app/src/production/java/se/leap/bitmaskclient/ProviderApiManager.java delete mode 100644 app/src/test/java/se/leap/bitmaskclient/TestUtils.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/TestSetupHelper.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/answers/BackendAnswerFabric.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/answers/NoErrorAnswer.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/matchers/BundleMatcher.java create mode 100644 app/src/test/resources/error_messages.json create mode 100644 app/src/test/resources/riseup.net.json create mode 100644 app/src/test/resources/riseup.net.pem create mode 100644 app/src/test/resources/riseup.service.json diff --git a/app/build.gradle b/app/build.gradle index 048eb597..8b956944 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -64,7 +64,16 @@ android { } dependencies { - testCompile 'org.mockito:mockito-core:2.6.3' + testCompile 'junit:junit:4.12' + testCompile 'org.mockito:mockito-core:2.8.0' + testCompile 'org.powermock:powermock-api-mockito2:1.7.3' + testCompile 'org.powermock:powermock-module-junit4:1.7.3' + testCompile 'org.powermock:powermock-core:1.7.3' + testCompile 'org.powermock:powermock-module-junit4-rule:1.7.3' + testCompile 'com.madgag.spongycastle:bctls-jdk15on:1.58.0.0' + testCompile 'com.madgag.spongycastle:bcpkix-jdk15on:1.58.0.0' + testCompile 'com.madgag.spongycastle:bcpg-jdk15on:1.58.0.0' + androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.6.3' testCompile 'junit:junit:4.12' testCompile 'org.json:json:20170516' @@ -72,8 +81,7 @@ dependencies { provided 'com.squareup.dagger:dagger-compiler:1.2.2' compile 'com.github.pedrovgs:renderers:1.5' compile 'com.intellij:annotations:12.0' - compile 'com.google.code.gson:gson:2.4' - compile 'org.thoughtcrime.ssl.pinning:AndroidPinning:1.0.0' + compile 'com.google.code.gson:gson:2.7' compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'mbanje.kurt:fabbutton:1.1.4' compile "com.android.support:support-core-utils:26.1.0" diff --git a/app/src/insecure/java/se/leap/bitmaskclient/ProviderAPI.java b/app/src/insecure/java/se/leap/bitmaskclient/ProviderAPI.java deleted file mode 100644 index 5cb06115..00000000 --- a/app/src/insecure/java/se/leap/bitmaskclient/ProviderAPI.java +++ /dev/null @@ -1,422 +0,0 @@ -/** - * Copyright (c) 2013 LEAP Encryption Access Project and contributers - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package se.leap.bitmaskclient; - -import android.os.Bundle; -import android.util.Pair; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.List; -import java.util.Scanner; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import okhttp3.OkHttpClient; -import se.leap.bitmaskclient.ProviderListContent.ProviderItem; -import se.leap.bitmaskclient.eip.EIP; - -import static se.leap.bitmaskclient.R.string.certificate_error; -import static se.leap.bitmaskclient.R.string.malformed_url; - -/** - * Implements HTTP api methods used to manage communications with the provider server. - * It extends the abstract ProviderApiBase and implements the diverging method calls between the different flavors - * of ProviderAPI. - *

- * It extends an IntentService because it downloads data from the Internet, so it operates in the background. - * - * @author parmegv - * @author MeanderingCode - * @author cyberta - */ -public class ProviderAPI extends ProviderApiBase { - - private static boolean lastDangerOn = true; - - public static boolean lastDangerOn() { - return lastDangerOn; - } - - /** - * Downloads a provider.json from a given URL, adding a new provider using the given name. - * - * @param task containing a boolean meaning if the provider is custom or not, another boolean meaning if the user completely trusts this provider, the provider name and its provider.json url. - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. - */ - @Override - protected Bundle setUpProvider(Bundle task) { - int progress = 0; - Bundle currentDownload = new Bundle(); - - if (task != null) { - lastDangerOn = task.containsKey(ProviderItem.DANGER_ON) && task.getBoolean(ProviderItem.DANGER_ON); - lastProviderMainUrl = task.containsKey(Provider.MAIN_URL) ? - task.getString(Provider.MAIN_URL) : - ""; - providerCaCertFingerprint = task.containsKey(Provider.CA_CERT_FINGERPRINT) ? - task.getString(Provider.CA_CERT_FINGERPRINT) : - ""; - providerCaCert = task.containsKey(Provider.CA_CERT) ? - task.getString(Provider.CA_CERT) : - ""; - - try { - providerDefinition = task.containsKey(Provider.KEY) ? - new JSONObject(task.getString(Provider.KEY)) : - new JSONObject(); - } catch (JSONException e) { - e.printStackTrace(); - providerDefinition = new JSONObject(); - } - providerApiUrl = getApiUrlWithVersion(providerDefinition); - - checkPersistedProviderUpdates(); - currentDownload = validateProviderDetails(); - - //provider details invalid - if (currentDownload.containsKey(ERRORS)) { - return currentDownload; - } - - //no provider certificate available - if (currentDownload.containsKey(RESULT_KEY) && !currentDownload.getBoolean(RESULT_KEY)) { - resetProviderDetails(); - } - - EIP_SERVICE_JSON_DOWNLOADED = false; - go_ahead = true; - } - - if (!PROVIDER_JSON_DOWNLOADED) - currentDownload = getAndSetProviderJson(lastProviderMainUrl, lastDangerOn, providerCaCert, providerDefinition); - if (PROVIDER_JSON_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { - broadcastProgress(progress++); - PROVIDER_JSON_DOWNLOADED = true; - - if (!CA_CERT_DOWNLOADED) - currentDownload = downloadCACert(lastDangerOn); - if (CA_CERT_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { - broadcastProgress(progress++); - CA_CERT_DOWNLOADED = true; - currentDownload = getAndSetEipServiceJson(); - if (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY)) { - broadcastProgress(progress++); - EIP_SERVICE_JSON_DOWNLOADED = true; - } - } - } - - return currentDownload; - } - - private Bundle getAndSetProviderJson(String providerMainUrl, boolean dangerOn, String caCert, JSONObject providerDefinition) { - Bundle result = new Bundle(); - - if (go_ahead) { - String providerDotJsonString; - if(providerDefinition.length() == 0 || caCert.isEmpty()) - providerDotJsonString = downloadWithCommercialCA(providerMainUrl + "/provider.json", dangerOn); - else - providerDotJsonString = downloadFromApiUrlWithProviderCA("/provider.json", caCert, providerDefinition, dangerOn); - - if (!isValidJson(providerDotJsonString)) { - result.putString(ERRORS, getString(malformed_url)); - result.putBoolean(RESULT_KEY, false); - return result; - } - - try { - JSONObject providerJson = new JSONObject(providerDotJsonString); - String providerDomain = providerJson.getString(Provider.DOMAIN); - providerApiUrl = getApiUrlWithVersion(providerJson); - String name = providerJson.getString(Provider.NAME); - //TODO setProviderName(name); - - preferences.edit().putString(Provider.KEY, providerJson.toString()). - putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). - putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). - putString(Provider.KEY + "." + providerDomain, providerJson.toString()).commit(); - result.putBoolean(RESULT_KEY, true); - } catch (JSONException e) { - String reason_to_fail = pickErrorMessage(providerDotJsonString); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - } - return result; - } - - /** - * Downloads the eip-service.json from a given URL, and saves eip service capabilities including the offered gateways - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the download was successful. - */ - @Override - protected Bundle getAndSetEipServiceJson() { - Bundle result = new Bundle(); - String eip_service_json_string = ""; - if (go_ahead) { - try { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - String eip_service_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION) + "/" + EIP.SERVICE_API_PATH; - eip_service_json_string = downloadWithProviderCA(eip_service_url, lastDangerOn); - JSONObject eip_service_json = new JSONObject(eip_service_json_string); - eip_service_json.getInt(Provider.API_RETURN_SERIAL); - - preferences.edit().putString(Constants.PROVIDER_KEY, eip_service_json.toString()).commit(); - - result.putBoolean(RESULT_KEY, true); - } catch (NullPointerException | JSONException e) { - String reason_to_fail = pickErrorMessage(eip_service_json_string); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - } - return result; - } - - /** - * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. - * - * @return true if certificate was downloaded correctly, false if provider.json is not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. - */ - @Override - protected boolean updateVpnCertificate() { - try { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - - String provider_main_url = provider_json.getString(Provider.API_URL); - URL new_cert_string_url = new URL(provider_main_url + "/" + provider_json.getString(Provider.API_VERSION) + "/" + Constants.PROVIDER_VPN_CERTIFICATE); - - String cert_string = downloadWithProviderCA(new_cert_string_url.toString(), lastDangerOn); - - if (cert_string == null || cert_string.isEmpty() || ConfigHelper.checkErroneousDownload(cert_string)) - return false; - else - return loadCertificate(cert_string); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - } - - - private Bundle downloadCACert(boolean dangerOn) { - Bundle result = new Bundle(); - try { - JSONObject providerJson = new JSONObject(preferences.getString(Provider.KEY, "")); - String caCertUrl = providerJson.getString(Provider.CA_CERT_URI); - String providerDomain = providerJson.getString(Provider.DOMAIN); - - String certString = downloadWithCommercialCA(caCertUrl, dangerOn); - - if (validCertificate(certString) && go_ahead) { - preferences.edit().putString(Provider.CA_CERT, certString).commit(); - preferences.edit().putString(Provider.CA_CERT + "." + providerDomain, certString).commit(); - result.putBoolean(RESULT_KEY, true); - } else { - String reason_to_fail = pickErrorMessage(certString); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - } catch (JSONException e) { - String reason_to_fail = formatErrorMessage(malformed_url); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - - return result; - } - - /** - * Tries to download the contents of the provided url using commercially validated CA certificate from chosen provider. - *

- * If danger_on flag is true, SSL exceptions will be managed by futher methods that will try to use some bypass methods. - * - * @param string_url - * @param danger_on if the user completely trusts this provider - * @return - */ - private String downloadWithCommercialCA(String string_url, boolean danger_on) { - String responseString; - JSONObject errorJson = new JSONObject(); - - OkHttpClient okHttpClient = initCommercialCAHttpClient(errorJson); - if (okHttpClient == null) { - return errorJson.toString(); - } - - List> headerArgs = getAuthorizationHeader(); - - responseString = sendGetStringToServer(string_url, headerArgs, okHttpClient); - - if (responseString != null && responseString.contains(ERRORS)) { - try { - // try to download with provider CA on certificate error - JSONObject responseErrorJson = new JSONObject(responseString); - if (danger_on && responseErrorJson.getString(ERRORS).equals(getString(R.string.certificate_error))) { - responseString = downloadWithoutCA(string_url); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - return responseString; - } - - private String downloadFromApiUrlWithProviderCA(String path, String caCert, JSONObject providerDefinition, boolean dangerOn) { - String responseString; - JSONObject errorJson = new JSONObject(); - String baseUrl = getApiUrl(providerDefinition); - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(errorJson, caCert); - if (okHttpClient == null) { - return errorJson.toString(); - } - - String urlString = baseUrl + path; - List> headerArgs = getAuthorizationHeader(); - responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); - - if (responseString != null && responseString.contains(ERRORS)) { - try { - // try to download with provider CA on certificate error - JSONObject responseErrorJson = new JSONObject(responseString); - if (dangerOn && responseErrorJson.getString(ERRORS).equals(getString(R.string.certificate_error))) { - responseString = downloadWithCommercialCA(urlString, dangerOn); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - return responseString; - } - - /** - * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider. - * - * @param urlString as a string - * @param dangerOn true to download CA certificate in case it has not been downloaded. - * @return an empty string if it fails, the url content if not. - */ - private String downloadWithProviderCA(String urlString, boolean dangerOn) { - JSONObject initError = new JSONObject(); - String responseString; - - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(initError); - if (okHttpClient == null) { - return initError.toString(); - } - - List> headerArgs = getAuthorizationHeader(); - - responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); - - if (responseString.contains(ERRORS)) { - try { - // danger danger: try to download without CA on certificate error - JSONObject responseErrorJson = new JSONObject(responseString); - if (dangerOn && responseErrorJson.getString(ERRORS).equals(getString(R.string.certificate_error))) { - responseString = downloadWithoutCA(urlString); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - return responseString; - } - - /** - * Downloads the string that's in the url with any certificate. - */ - // This method is totally insecure anyways. So no need to refactor that in order to use okHttpClient, force modern TLS etc.. DO NOT USE IN PRODUCTION! - private String downloadWithoutCA(String url_string) { - String string = ""; - try { - - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - class DefaultTrustManager implements X509TrustManager { - - @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - } - - SSLContext context = SSLContext.getInstance("TLS"); - context.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom()); - - URL url = new URL(url_string); - HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); - urlConnection.setSSLSocketFactory(context.getSocketFactory()); - urlConnection.setHostnameVerifier(hostnameVerifier); - string = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next(); - System.out.println("String ignoring certificate = " + string); - } catch (FileNotFoundException e) { - e.printStackTrace(); - string = formatErrorMessage(malformed_url); - } catch (IOException e) { - // The downloaded certificate doesn't validate our https connection. - e.printStackTrace(); - string = formatErrorMessage(certificate_error); - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyManagementException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return string; - } - -} diff --git a/app/src/insecure/java/se/leap/bitmaskclient/ProviderApiManager.java b/app/src/insecure/java/se/leap/bitmaskclient/ProviderApiManager.java new file mode 100644 index 00000000..9c27fd1f --- /dev/null +++ b/app/src/insecure/java/se/leap/bitmaskclient/ProviderApiManager.java @@ -0,0 +1,430 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient; + +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.os.Bundle; +import android.util.Pair; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Scanner; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.eip.EIP; + +import static android.text.TextUtils.isEmpty; +import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CERTIFICATE_PINNING; +import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CORRUPTED_PROVIDER_JSON; +import static se.leap.bitmaskclient.ProviderAPI.ERRORS; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_KEY; +import static se.leap.bitmaskclient.R.string.certificate_error; +import static se.leap.bitmaskclient.R.string.malformed_url; + +/** + * Created by cyberta on 04.01.18. + */ + +public class ProviderApiManager extends ProviderApiManagerBase { + protected static boolean lastDangerOn = true; + + + public ProviderApiManager(SharedPreferences preferences, Resources resources, OkHttpClientGenerator clientGenerator, ProviderApiServiceCallback callback) { + super(preferences, resources, clientGenerator, callback); + } + + public static boolean lastDangerOn() { + return lastDangerOn; + } + + /** + * Downloads a provider.json from a given URL, adding a new provider using the given name. + * + * @param task containing a boolean meaning if the provider is custom or not, another boolean meaning if the user completely trusts this provider, the provider name and its provider.json url. + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. + */ + @Override + protected Bundle setUpProvider(Bundle task) { + int progress = 0; + Bundle currentDownload = new Bundle(); + + if (task != null) { + lastDangerOn = task.containsKey(ProviderListContent.ProviderItem.DANGER_ON) && task.getBoolean(ProviderListContent.ProviderItem.DANGER_ON); + lastProviderMainUrl = task.containsKey(Provider.MAIN_URL) ? + task.getString(Provider.MAIN_URL) : + ""; + + if (isEmpty(lastProviderMainUrl)) { + currentDownload.putBoolean(RESULT_KEY, false); + setErrorResult(currentDownload, resources.getString(R.string.malformed_url), null); + return currentDownload; + } + + providerCaCertFingerprint = task.containsKey(Provider.CA_CERT_FINGERPRINT) ? + task.getString(Provider.CA_CERT_FINGERPRINT) : + ""; + providerCaCert = task.containsKey(Provider.CA_CERT) ? + task.getString(Provider.CA_CERT) : + ""; + + try { + providerDefinition = task.containsKey(Provider.KEY) ? + new JSONObject(task.getString(Provider.KEY)) : + new JSONObject(); + } catch (JSONException e) { + e.printStackTrace(); + providerDefinition = new JSONObject(); + } + providerApiUrl = getApiUrlWithVersion(providerDefinition); + + checkPersistedProviderUpdates(); + currentDownload = validateProviderDetails(); + + //provider details invalid + if (currentDownload.containsKey(ERRORS)) { + return currentDownload; + } + + //no provider certificate available + if (currentDownload.containsKey(RESULT_KEY) && !currentDownload.getBoolean(RESULT_KEY)) { + resetProviderDetails(); + } + + EIP_SERVICE_JSON_DOWNLOADED = false; + go_ahead = true; + } + + if (!PROVIDER_JSON_DOWNLOADED) + currentDownload = getAndSetProviderJson(lastProviderMainUrl, lastDangerOn, providerCaCert, providerDefinition); + if (PROVIDER_JSON_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { + broadcastProgress(progress++); + PROVIDER_JSON_DOWNLOADED = true; + + if (!CA_CERT_DOWNLOADED) + currentDownload = downloadCACert(lastDangerOn); + if (CA_CERT_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { + broadcastProgress(progress++); + CA_CERT_DOWNLOADED = true; + currentDownload = getAndSetEipServiceJson(); + if (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY)) { + broadcastProgress(progress++); + EIP_SERVICE_JSON_DOWNLOADED = true; + } + } + } + + return currentDownload; + } + + private Bundle getAndSetProviderJson(String providerMainUrl, boolean dangerOn, String caCert, JSONObject providerDefinition) { + Bundle result = new Bundle(); + + if (go_ahead) { + String providerDotJsonString; + if(providerDefinition.length() == 0 || caCert.isEmpty()) + providerDotJsonString = downloadWithCommercialCA(providerMainUrl + "/provider.json", dangerOn); + else + providerDotJsonString = downloadFromApiUrlWithProviderCA("/provider.json", caCert, providerDefinition, dangerOn); + + if (!isValidJson(providerDotJsonString)) { + result.putString(ERRORS, resources.getString(malformed_url)); + result.putBoolean(RESULT_KEY, false); + return result; + } + + try { + JSONObject providerJson = new JSONObject(providerDotJsonString); + String providerDomain = getDomainFromMainURL(lastProviderMainUrl); + providerApiUrl = getApiUrlWithVersion(providerJson); + //String name = providerJson.getString(Provider.NAME); + //TODO setProviderName(name); + + preferences.edit().putString(Provider.KEY, providerJson.toString()). + putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). + putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). + putString(Provider.KEY + "." + providerDomain, providerJson.toString()).commit(); + result.putBoolean(RESULT_KEY, true); + } catch (JSONException e) { + String reason_to_fail = pickErrorMessage(providerDotJsonString); + result.putString(ERRORS, reason_to_fail); + result.putBoolean(RESULT_KEY, false); + } + } + return result; + } + + /** + * Downloads the eip-service.json from a given URL, and saves eip service capabilities including the offered gateways + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the download was successful. + */ + @Override + protected Bundle getAndSetEipServiceJson() { + Bundle result = new Bundle(); + String eip_service_json_string = ""; + if (go_ahead) { + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + String eip_service_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION) + "/" + EIP.SERVICE_API_PATH; + eip_service_json_string = downloadWithProviderCA(eip_service_url, lastDangerOn); + JSONObject eip_service_json = new JSONObject(eip_service_json_string); + eip_service_json.getInt(Provider.API_RETURN_SERIAL); + + preferences.edit().putString(Constants.PROVIDER_KEY, eip_service_json.toString()).commit(); + + result.putBoolean(RESULT_KEY, true); + } catch (NullPointerException | JSONException e) { + String reason_to_fail = pickErrorMessage(eip_service_json_string); + result.putString(ERRORS, reason_to_fail); + result.putBoolean(RESULT_KEY, false); + } + } + return result; + } + + /** + * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. + * + * @return true if certificate was downloaded correctly, false if provider.json is not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. + */ + @Override + protected boolean updateVpnCertificate() { + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + + String provider_main_url = provider_json.getString(Provider.API_URL); + URL new_cert_string_url = new URL(provider_main_url + "/" + provider_json.getString(Provider.API_VERSION) + "/" + Constants.PROVIDER_VPN_CERTIFICATE); + + String cert_string = downloadWithProviderCA(new_cert_string_url.toString(), lastDangerOn); + + if (cert_string == null || cert_string.isEmpty() || ConfigHelper.checkErroneousDownload(cert_string)) + return false; + else + return loadCertificate(cert_string); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + } + + + private Bundle downloadCACert(boolean dangerOn) { + Bundle result = new Bundle(); + try { + JSONObject providerJson = new JSONObject(preferences.getString(Provider.KEY, "")); + String caCertUrl = providerJson.getString(Provider.CA_CERT_URI); + String providerDomain = providerJson.getString(Provider.DOMAIN); + + String certString = downloadWithCommercialCA(caCertUrl, dangerOn); + + if (validCertificate(certString) && go_ahead) { + preferences.edit().putString(Provider.CA_CERT, certString).commit(); + preferences.edit().putString(Provider.CA_CERT + "." + providerDomain, certString).commit(); + result.putBoolean(RESULT_KEY, true); + } else { + setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_cert), ERROR_CERTIFICATE_PINNING.toString()); + result.putBoolean(RESULT_KEY, false); + } + } catch (JSONException e) { + setErrorResult(result, resources.getString(malformed_url), null); + result.putBoolean(RESULT_KEY, false); + } + + return result; + } + + /** + * Tries to download the contents of the provided url using commercially validated CA certificate from chosen provider. + *

+ * If danger_on flag is true, SSL exceptions will be managed by futher methods that will try to use some bypass methods. + * + * @param string_url + * @param danger_on if the user completely trusts this provider + * @return + */ + private String downloadWithCommercialCA(String string_url, boolean danger_on) { + String responseString; + JSONObject errorJson = new JSONObject(); + + OkHttpClient okHttpClient = clientGenerator.initCommercialCAHttpClient(errorJson); + if (okHttpClient == null) { + return errorJson.toString(); + } + + List> headerArgs = getAuthorizationHeader(); + + responseString = sendGetStringToServer(string_url, headerArgs, okHttpClient); + + if (responseString != null && responseString.contains(ERRORS)) { + try { + // try to download with provider CA on certificate error + JSONObject responseErrorJson = new JSONObject(responseString); + if (danger_on && responseErrorJson.getString(ERRORS).equals(resources.getString(R.string.certificate_error))) { + responseString = downloadWithoutCA(string_url); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + return responseString; + } + + private String downloadFromApiUrlWithProviderCA(String path, String caCert, JSONObject providerDefinition, boolean dangerOn) { + String responseString; + JSONObject errorJson = new JSONObject(); + String baseUrl = getApiUrl(providerDefinition); + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(errorJson, caCert); + if (okHttpClient == null) { + return errorJson.toString(); + } + + String urlString = baseUrl + path; + List> headerArgs = getAuthorizationHeader(); + responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); + + if (responseString != null && responseString.contains(ERRORS)) { + try { + // try to download with provider CA on certificate error + JSONObject responseErrorJson = new JSONObject(responseString); + if (dangerOn && responseErrorJson.getString(ERRORS).equals(resources.getString(R.string.certificate_error))) { + responseString = downloadWithCommercialCA(urlString, dangerOn); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + return responseString; + } + + /** + * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider. + * + * @param urlString as a string + * @param dangerOn true to download CA certificate in case it has not been downloaded. + * @return an empty string if it fails, the url content if not. + */ + private String downloadWithProviderCA(String urlString, boolean dangerOn) { + JSONObject initError = new JSONObject(); + String responseString; + + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(initError); + if (okHttpClient == null) { + return initError.toString(); + } + + List> headerArgs = getAuthorizationHeader(); + + responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); + + if (responseString.contains(ERRORS)) { + try { + // danger danger: try to download without CA on certificate error + JSONObject responseErrorJson = new JSONObject(responseString); + if (dangerOn && responseErrorJson.getString(ERRORS).equals(resources.getString(R.string.certificate_error))) { + responseString = downloadWithoutCA(urlString); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + return responseString; + } + + /** + * Downloads the string that's in the url with any certificate. + */ + // This method is totally insecure anyways. So no need to refactor that in order to use okHttpClient, force modern TLS etc.. DO NOT USE IN PRODUCTION! + private String downloadWithoutCA(String url_string) { + String string = ""; + try { + + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + class DefaultTrustManager implements X509TrustManager { + + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + } + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom()); + + URL url = new URL(url_string); + HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); + urlConnection.setSSLSocketFactory(context.getSocketFactory()); + urlConnection.setHostnameVerifier(hostnameVerifier); + string = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next(); + System.out.println("String ignoring certificate = " + string); + } catch (FileNotFoundException e) { + e.printStackTrace(); + string = formatErrorMessage(malformed_url); + } catch (IOException e) { + // The downloaded certificate doesn't validate our https connection. + e.printStackTrace(); + string = formatErrorMessage(certificate_error); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (KeyManagementException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return string; + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 4dd11143..c0e2d90c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -54,7 +54,7 @@ - + . + */ + +package se.leap.bitmaskclient; + +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.os.Build; +import android.support.annotation.NonNull; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import okhttp3.CipherSuite; +import okhttp3.ConnectionSpec; +import okhttp3.Cookie; +import okhttp3.CookieJar; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.TlsVersion; + +import static android.text.TextUtils.isEmpty; +import static se.leap.bitmaskclient.ProviderAPI.ERRORS; +import static se.leap.bitmaskclient.R.string.certificate_error; +import static se.leap.bitmaskclient.R.string.error_io_exception_user_message; +import static se.leap.bitmaskclient.R.string.error_no_such_algorithm_exception_user_message; +import static se.leap.bitmaskclient.R.string.keyChainAccessError; +import static se.leap.bitmaskclient.R.string.server_unreachable_message; + +/** + * Created by cyberta on 08.01.18. + */ + +public class OkHttpClientGenerator { + + SharedPreferences preferences; + Resources resources; + + public OkHttpClientGenerator(SharedPreferences preferences, Resources resources) { + this.preferences = preferences; + this.resources = resources; + } + + public OkHttpClient initCommercialCAHttpClient(JSONObject initError) { + return initHttpClient(initError, null); + } + + public OkHttpClient initSelfSignedCAHttpClient(JSONObject initError) { + String certificate = preferences.getString(Provider.CA_CERT, ""); + return initHttpClient(initError, certificate); + } + + public OkHttpClient initSelfSignedCAHttpClient(JSONObject initError, String certificate) { + return initHttpClient(initError, certificate); + } + + + private OkHttpClient initHttpClient(JSONObject initError, String certificate) { + try { + TLSCompatSocketFactory sslCompatFactory; + ConnectionSpec spec = getConnectionSpec(); + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); + + if (!isEmpty(certificate)) { + sslCompatFactory = new TLSCompatSocketFactory(certificate); + } else { + sslCompatFactory = new TLSCompatSocketFactory(); + } + sslCompatFactory.initSSLSocketFactory(clientBuilder); + clientBuilder.cookieJar(getCookieJar()) + .connectionSpecs(Collections.singletonList(spec)); + return clientBuilder.build(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + addErrorMessageToJson(initError, resources.getString(R.string.certificate_error)); + } catch (IllegalStateException | KeyManagementException | KeyStoreException e) { + e.printStackTrace(); + addErrorMessageToJson(initError, String.format(resources.getString(keyChainAccessError), e.getLocalizedMessage())); + } catch (NoSuchAlgorithmException | NoSuchProviderException e) { + e.printStackTrace(); + addErrorMessageToJson(initError, resources.getString(error_no_such_algorithm_exception_user_message)); + } catch (CertificateException e) { + e.printStackTrace(); + addErrorMessageToJson(initError, resources.getString(certificate_error)); + } catch (UnknownHostException e) { + e.printStackTrace(); + addErrorMessageToJson(initError, resources.getString(server_unreachable_message)); + } catch (IOException e) { + e.printStackTrace(); + addErrorMessageToJson(initError, resources.getString(error_io_exception_user_message)); + } + return null; + } + + + + @NonNull + private ConnectionSpec getConnectionSpec() { + ConnectionSpec.Builder connectionSpecbuilder = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) + .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_3); + //FIXME: restrict connection further to the following recommended cipher suites for ALL supported API levels + //figure out how to use bcjsse for that purpose + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) + connectionSpecbuilder.cipherSuites( + CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, + CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 + ); + return connectionSpecbuilder.build(); + } + + @NonNull + private CookieJar getCookieJar() { + return new CookieJar() { + private final HashMap> cookieStore = new HashMap<>(); + + @Override + public void saveFromResponse(HttpUrl url, List cookies) { + cookieStore.put(url.host(), cookies); + } + + @Override + public List loadForRequest(HttpUrl url) { + List cookies = cookieStore.get(url.host()); + return cookies != null ? cookies : new ArrayList(); + } + }; + } + + private void addErrorMessageToJson(JSONObject jsonObject, String errorMessage) { + try { + jsonObject.put(ERRORS, errorMessage); + } catch (JSONException e) { + e.printStackTrace(); + } + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java b/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java new file mode 100644 index 00000000..5a6aabc0 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) 2017 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package se.leap.bitmaskclient; + +import android.annotation.SuppressLint; +import android.app.IntentService; +import android.content.Intent; +import android.content.SharedPreferences; + +import de.blinkt.openvpn.core.Preferences; + +/** + * Implements HTTP api methods (encapsulated in {{@link ProviderApiManager}}) + * used to manage communications with the provider server. + *

+ * It's an IntentService because it downloads data from the Internet, so it operates in the background. + * + * @author parmegv + * @author MeanderingCode + * @author cyberta + */ + +public class ProviderAPI extends IntentService implements ProviderApiManagerBase.ProviderApiServiceCallback { + + final public static String + TAG = ProviderAPI.class.getSimpleName(), + SET_UP_PROVIDER = "setUpProvider", + UPDATE_PROVIDER_DETAILS = "updateProviderDetails", + DOWNLOAD_NEW_PROVIDER_DOTJSON = "downloadNewProviderDotJSON", + SIGN_UP = "srpRegister", + LOG_IN = "srpAuth", + LOG_OUT = "logOut", + DOWNLOAD_CERTIFICATE = "downloadUserAuthedCertificate", + PARAMETERS = "parameters", + RESULT_KEY = "result", + RECEIVER_KEY = "receiver", + ERRORS = "errors", + ERRORID = "errorId", + UPDATE_PROGRESSBAR = "update_progressbar", + CURRENT_PROGRESS = "current_progress", + DOWNLOAD_EIP_SERVICE = TAG + ".DOWNLOAD_EIP_SERVICE"; + + final public static int + SUCCESSFUL_LOGIN = 3, + FAILED_LOGIN = 4, + SUCCESSFUL_SIGNUP = 5, + FAILED_SIGNUP = 6, + SUCCESSFUL_LOGOUT = 7, + LOGOUT_FAILED = 8, + CORRECTLY_DOWNLOADED_CERTIFICATE = 9, + INCORRECTLY_DOWNLOADED_CERTIFICATE = 10, + PROVIDER_OK = 11, + PROVIDER_NOK = 12, + CORRECTLY_DOWNLOADED_EIP_SERVICE = 13, + INCORRECTLY_DOWNLOADED_EIP_SERVICE = 14; + + ProviderApiManager providerApiManager; + + + + public ProviderAPI() { + super(TAG); + } + + //TODO: refactor me, please! + public static void stop() { + ProviderApiManager.stop(); + } + + //TODO: refactor me, please! + public static boolean caCertDownloaded() { + return ProviderApiManager.caCertDownloaded(); + } + + //TODO: refactor me, please! + public static String lastProviderMainUrl() { + return ProviderApiManager.lastProviderMainUrl(); + } + + //TODO: refactor me, please! + //used in insecure flavor only + @SuppressLint("unused") + public static boolean lastDangerOn() { + return ProviderApiManager.lastDangerOn(); + } + + + @Override + public void onCreate() { + super.onCreate(); + providerApiManager = initApiManager(); + } + + @Override + public void broadcastProgress(Intent intent) { + sendBroadcast(intent); + } + + @Override + protected void onHandleIntent(Intent command) { + providerApiManager.handleIntent(command); + } + + + private ProviderApiManager initApiManager() { + SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + OkHttpClientGenerator clientGenerator = new OkHttpClientGenerator(preferences, getResources()); + return new ProviderApiManager(preferences, getResources(), clientGenerator, this); + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderAPIResultReceiver.java b/app/src/main/java/se/leap/bitmaskclient/ProviderAPIResultReceiver.java index 9b880f89..9b777e5a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderAPIResultReceiver.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderAPIResultReceiver.java @@ -16,7 +16,9 @@ */ package se.leap.bitmaskclient; -import android.os.*; +import android.os.Bundle; +import android.os.Handler; +import android.os.ResultReceiver; /** * Implements the ResultReceiver needed by Activities using ProviderAPI to receive the results of its operations. diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java deleted file mode 100644 index 0013d2c2..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java +++ /dev/null @@ -1,1061 +0,0 @@ -/** - * Copyright (c) 2017 LEAP Encryption Access Project and contributers - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package se.leap.bitmaskclient; - -import android.app.IntentService; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.res.Resources; -import android.os.Build; -import android.os.Bundle; -import android.os.ResultReceiver; -import android.support.annotation.NonNull; -import android.util.Base64; -import android.util.Pair; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.net.ConnectException; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.net.UnknownServiceException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Scanner; - -import javax.net.ssl.SSLHandshakeException; - -import okhttp3.CipherSuite; -import okhttp3.ConnectionSpec; -import okhttp3.Cookie; -import okhttp3.CookieJar; -import okhttp3.HttpUrl; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.TlsVersion; -import se.leap.bitmaskclient.userstatus.SessionDialog; -import se.leap.bitmaskclient.userstatus.User; -import se.leap.bitmaskclient.userstatus.UserStatus; - -import static android.text.TextUtils.isEmpty; -import static se.leap.bitmaskclient.ConfigHelper.base64toHex; -import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CERTIFICATE_PINNING; -import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CORRUPTED_PROVIDER_JSON; -import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_INVALID_CERTIFICATE; -import static se.leap.bitmaskclient.Provider.MAIN_URL; -import static se.leap.bitmaskclient.R.string.certificate_error; -import static se.leap.bitmaskclient.R.string.error_io_exception_user_message; -import static se.leap.bitmaskclient.R.string.error_json_exception_user_message; -import static se.leap.bitmaskclient.R.string.error_no_such_algorithm_exception_user_message; -import static se.leap.bitmaskclient.R.string.keyChainAccessError; -import static se.leap.bitmaskclient.R.string.malformed_url; -import static se.leap.bitmaskclient.R.string.server_unreachable_message; -import static se.leap.bitmaskclient.R.string.service_is_down_error; - -/** - * Implements HTTP api methods used to manage communications with the provider server. - * The implemented methods are commonly used by insecure's and production's flavor of ProviderAPI. - *

- * It's an IntentService because it downloads data from the Internet, so it operates in the background. - * - * @author parmegv - * @author MeanderingCode - * @author cyberta - */ - -public abstract class ProviderApiBase extends IntentService { - - final public static String - TAG = ProviderAPI.class.getSimpleName(), - SET_UP_PROVIDER = "setUpProvider", - UPDATE_PROVIDER_DETAILS = "updateProviderDetails", - DOWNLOAD_NEW_PROVIDER_DOTJSON = "downloadNewProviderDotJSON", - SIGN_UP = "srpRegister", - LOG_IN = "srpAuth", - LOG_OUT = "logOut", - DOWNLOAD_CERTIFICATE = "downloadUserAuthedCertificate", - PARAMETERS = "parameters", - RESULT_KEY = "result", - RECEIVER_KEY = "receiver", - ERRORS = "errors", - ERRORID = "errorId", - UPDATE_PROGRESSBAR = "update_progressbar", - CURRENT_PROGRESS = "current_progress", - DOWNLOAD_EIP_SERVICE = TAG + ".DOWNLOAD_EIP_SERVICE"; - - final public static int - SUCCESSFUL_LOGIN = 3, - FAILED_LOGIN = 4, - SUCCESSFUL_SIGNUP = 5, - FAILED_SIGNUP = 6, - SUCCESSFUL_LOGOUT = 7, - LOGOUT_FAILED = 8, - CORRECTLY_DOWNLOADED_CERTIFICATE = 9, - INCORRECTLY_DOWNLOADED_CERTIFICATE = 10, - PROVIDER_OK = 11, - PROVIDER_NOK = 12, - CORRECTLY_DOWNLOADED_EIP_SERVICE = 13, - INCORRECTLY_DOWNLOADED_EIP_SERVICE = 14; - - protected static boolean - CA_CERT_DOWNLOADED = false, - PROVIDER_JSON_DOWNLOADED = false, - EIP_SERVICE_JSON_DOWNLOADED = false; - - protected static String lastProviderMainUrl; - protected static boolean go_ahead = true; - protected static SharedPreferences preferences; - protected static String providerApiUrl; - protected static String providerCaCertFingerprint; - protected static String providerCaCert; - protected static JSONObject providerDefinition; - protected Resources resources; - - public static void stop() { - go_ahead = false; - } - - private final MediaType JSON - = MediaType.parse("application/json; charset=utf-8"); - - public ProviderApiBase() { - super(TAG); - } - - @Override - public void onCreate() { - super.onCreate(); - - preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); - resources = getResources(); - } - - public static String lastProviderMainUrl() { - return lastProviderMainUrl; - } - - @Override - protected void onHandleIntent(Intent command) { - final ResultReceiver receiver = command.getParcelableExtra(RECEIVER_KEY); - String action = command.getAction(); - Bundle parameters = command.getBundleExtra(PARAMETERS); - - if (providerApiUrl == null && preferences.contains(Provider.KEY)) { - try { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - providerApiUrl = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION); - go_ahead = true; - } catch (JSONException e) { - go_ahead = false; - } - } - if (action.equals(UPDATE_PROVIDER_DETAILS)) { - resetProviderDetails(); - Bundle task = new Bundle(); - task.putString(MAIN_URL, lastProviderMainUrl); - Bundle result = setUpProvider(task); - if (result.getBoolean(RESULT_KEY)) { - receiver.send(PROVIDER_OK, result); - } else { - receiver.send(PROVIDER_NOK, result); - } - } else if (action.equalsIgnoreCase(SET_UP_PROVIDER)) { - Bundle result = setUpProvider(parameters); - if (go_ahead) { - if (result.getBoolean(RESULT_KEY)) { - receiver.send(PROVIDER_OK, result); - } else { - receiver.send(PROVIDER_NOK, result); - } - } - } else if (action.equalsIgnoreCase(SIGN_UP)) { - UserStatus.updateStatus(UserStatus.SessionStatus.SIGNING_UP, resources); - Bundle result = tryToRegister(parameters); - if (result.getBoolean(RESULT_KEY)) { - receiver.send(SUCCESSFUL_SIGNUP, result); - } else { - receiver.send(FAILED_SIGNUP, result); - } - } else if (action.equalsIgnoreCase(LOG_IN)) { - UserStatus.updateStatus(UserStatus.SessionStatus.LOGGING_IN, resources); - Bundle result = tryToAuthenticate(parameters); - if (result.getBoolean(RESULT_KEY)) { - receiver.send(SUCCESSFUL_LOGIN, result); - UserStatus.updateStatus(UserStatus.SessionStatus.LOGGED_IN, resources); - } else { - receiver.send(FAILED_LOGIN, result); - UserStatus.updateStatus(UserStatus.SessionStatus.NOT_LOGGED_IN, resources); - } - } else if (action.equalsIgnoreCase(LOG_OUT)) { - UserStatus.updateStatus(UserStatus.SessionStatus.LOGGING_OUT, resources); - if (logOut()) { - receiver.send(SUCCESSFUL_LOGOUT, Bundle.EMPTY); - UserStatus.updateStatus(UserStatus.SessionStatus.LOGGED_OUT, resources); - } else { - receiver.send(LOGOUT_FAILED, Bundle.EMPTY); - UserStatus.updateStatus(UserStatus.SessionStatus.DIDNT_LOG_OUT, resources); - } - } else if (action.equalsIgnoreCase(DOWNLOAD_CERTIFICATE)) { - if (updateVpnCertificate()) { - receiver.send(CORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); - } else { - receiver.send(INCORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); - } - } else if (action.equalsIgnoreCase(DOWNLOAD_EIP_SERVICE)) { - Bundle result = getAndSetEipServiceJson(); - if (result.getBoolean(RESULT_KEY)) { - receiver.send(CORRECTLY_DOWNLOADED_EIP_SERVICE, result); - } else { - receiver.send(INCORRECTLY_DOWNLOADED_EIP_SERVICE, result); - } - } - } - - protected void resetProviderDetails() { - CA_CERT_DOWNLOADED = PROVIDER_JSON_DOWNLOADED = false; - deleteProviderDetailsFromPreferences(providerDefinition); - providerCaCert = ""; - providerDefinition = new JSONObject(); - } - - protected String formatErrorMessage(final int toastStringId) { - return formatErrorMessage(getResources().getString(toastStringId)); - } - - private String formatErrorMessage(String errorMessage) { - return "{ \"" + ERRORS + "\" : \"" + errorMessage + "\" }"; - } - - private JSONObject getErrorMessageAsJson(final int toastStringId) { - try { - return new JSONObject(formatErrorMessage(toastStringId)); - } catch (JSONException e) { - e.printStackTrace(); - return new JSONObject(); - } - } - - protected void addErrorMessageToJson(JSONObject jsonObject, String errorMessage) { - try { - jsonObject.put(ERRORS, errorMessage); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - protected void addErrorMessageToJson(JSONObject jsonObject, String errorMessage, String errorId) { - try { - jsonObject.put(ERRORS, errorMessage); - jsonObject.put(ERRORID, errorId); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - private OkHttpClient initHttpClient(JSONObject initError, String certificate) { - try { - TLSCompatSocketFactory sslCompatFactory; - ConnectionSpec spec = getConnectionSpec(); - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); - - if (!isEmpty(certificate)) { - sslCompatFactory = new TLSCompatSocketFactory(certificate); - } else { - sslCompatFactory = new TLSCompatSocketFactory(); - } - sslCompatFactory.initSSLSocketFactory(clientBuilder); - clientBuilder.cookieJar(getCookieJar()) - .connectionSpecs(Collections.singletonList(spec)); - return clientBuilder.build(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - addErrorMessageToJson(initError, resources.getString(R.string.certificate_error)); - } catch (IllegalStateException | KeyManagementException | KeyStoreException e) { - e.printStackTrace(); - addErrorMessageToJson(initError, String.format(resources.getString(keyChainAccessError), e.getLocalizedMessage())); - } catch (NoSuchAlgorithmException | NoSuchProviderException e) { - e.printStackTrace(); - addErrorMessageToJson(initError, resources.getString(error_no_such_algorithm_exception_user_message)); - } catch (CertificateException e) { - e.printStackTrace(); - addErrorMessageToJson(initError, resources.getString(certificate_error)); - } catch (UnknownHostException e) { - e.printStackTrace(); - addErrorMessageToJson(initError, resources.getString(server_unreachable_message)); - } catch (IOException e) { - e.printStackTrace(); - addErrorMessageToJson(initError, resources.getString(error_io_exception_user_message)); - } - return null; - } - - protected OkHttpClient initCommercialCAHttpClient(JSONObject initError) { - return initHttpClient(initError, null); - } - - protected OkHttpClient initSelfSignedCAHttpClient(JSONObject initError) { - String certificate = preferences.getString(Provider.CA_CERT, ""); - return initHttpClient(initError, certificate); - } - - protected OkHttpClient initSelfSignedCAHttpClient(JSONObject initError, String certificate) { - return initHttpClient(initError, certificate); - } - - @NonNull - private ConnectionSpec getConnectionSpec() { - ConnectionSpec.Builder connectionSpecbuilder = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_3); - //FIXME: restrict connection further to the following recommended cipher suites for ALL supported API levels - //figure out how to use bcjsse for that purpose - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) - connectionSpecbuilder.cipherSuites( - CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, - CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 - ); - return connectionSpecbuilder.build(); - } - - @NonNull - private CookieJar getCookieJar() { - return new CookieJar() { - private final HashMap> cookieStore = new HashMap<>(); - - @Override - public void saveFromResponse(HttpUrl url, List cookies) { - cookieStore.put(url.host(), cookies); - } - - @Override - public List loadForRequest(HttpUrl url) { - List cookies = cookieStore.get(url.host()); - return cookies != null ? cookies : new ArrayList(); - } - }; - } - - - private Bundle tryToRegister(Bundle task) { - Bundle result = new Bundle(); - int progress = 0; - - String username = User.userName(); - String password = task.getString(SessionDialog.PASSWORD); - - if (validUserLoginData(username, password)) { - result = register(username, password); - broadcastProgress(progress++); - } else { - if (!wellFormedPassword(password)) { - result.putBoolean(RESULT_KEY, false); - result.putString(SessionDialog.USERNAME, username); - result.putBoolean(SessionDialog.ERRORS.PASSWORD_INVALID_LENGTH.toString(), true); - } - if (!validUsername(username)) { - result.putBoolean(RESULT_KEY, false); - result.putBoolean(SessionDialog.ERRORS.USERNAME_MISSING.toString(), true); - } - } - - return result; - } - - private Bundle register(String username, String password) { - JSONObject stepResult = null; - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(stepResult); - if (okHttpClient == null) { - return authFailedNotification(stepResult, username); - } - - LeapSRPSession client = new LeapSRPSession(username, password); - byte[] salt = client.calculateNewSalt(); - - BigInteger password_verifier = client.calculateV(username, password, salt); - - JSONObject api_result = sendNewUserDataToSRPServer(providerApiUrl, username, new BigInteger(1, salt).toString(16), password_verifier.toString(16), okHttpClient); - - Bundle result = new Bundle(); - if (api_result.has(ERRORS)) - result = authFailedNotification(api_result, username); - else { - result.putString(SessionDialog.USERNAME, username); - result.putString(SessionDialog.PASSWORD, password); - result.putBoolean(RESULT_KEY, true); - } - - return result; - } - - /** - * Starts the authentication process using SRP protocol. - * - * @param task containing: username, password and api url. - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if authentication was successful. - */ - private Bundle tryToAuthenticate(Bundle task) { - Bundle result = new Bundle(); - int progress = 0; - - String username = User.userName(); - String password = task.getString(SessionDialog.PASSWORD); - if (validUserLoginData(username, password)) { - result = authenticate(username, password); - broadcastProgress(progress++); - } else { - if (!wellFormedPassword(password)) { - result.putBoolean(RESULT_KEY, false); - result.putString(SessionDialog.USERNAME, username); - result.putBoolean(SessionDialog.ERRORS.PASSWORD_INVALID_LENGTH.toString(), true); - } - if (!validUsername(username)) { - result.putBoolean(RESULT_KEY, false); - result.putBoolean(SessionDialog.ERRORS.USERNAME_MISSING.toString(), true); - } - } - - return result; - } - - private Bundle authenticate(String username, String password) { - Bundle result = new Bundle(); - JSONObject stepResult = new JSONObject(); - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(stepResult); - if (okHttpClient == null) { - return authFailedNotification(stepResult, username); - } - - LeapSRPSession client = new LeapSRPSession(username, password); - byte[] A = client.exponential(); - - JSONObject step_result = sendAToSRPServer(providerApiUrl, username, new BigInteger(1, A).toString(16), okHttpClient); - try { - String salt = step_result.getString(LeapSRPSession.SALT); - byte[] Bbytes = new BigInteger(step_result.getString("B"), 16).toByteArray(); - byte[] M1 = client.response(new BigInteger(salt, 16).toByteArray(), Bbytes); - if (M1 != null) { - step_result = sendM1ToSRPServer(providerApiUrl, username, M1, okHttpClient); - setTokenIfAvailable(step_result); - byte[] M2 = new BigInteger(step_result.getString(LeapSRPSession.M2), 16).toByteArray(); - if (client.verify(M2)) { - result.putBoolean(RESULT_KEY, true); - } else { - authFailedNotification(step_result, username); - } - } else { - result.putBoolean(RESULT_KEY, false); - result.putString(SessionDialog.USERNAME, username); - result.putString(resources.getString(R.string.user_message), resources.getString(R.string.error_srp_math_error_user_message)); - } - } catch (JSONException e) { - result = authFailedNotification(step_result, username); - e.printStackTrace(); - } - - return result; - } - - private boolean setTokenIfAvailable(JSONObject authentication_step_result) { - try { - LeapSRPSession.setToken(authentication_step_result.getString(LeapSRPSession.TOKEN)); - } catch (JSONException e) { // - return false; - } - return true; - } - - private Bundle authFailedNotification(JSONObject result, String username) { - Bundle userNotificationBundle = new Bundle(); - Object baseErrorMessage = result.opt(ERRORS); - if (baseErrorMessage != null) { - if (baseErrorMessage instanceof JSONObject) { - try { - JSONObject errorMessage = result.getJSONObject(ERRORS); - String errorType = errorMessage.keys().next().toString(); - String message = errorMessage.get(errorType).toString(); - userNotificationBundle.putString(resources.getString(R.string.user_message), message); - } catch (JSONException e) { - e.printStackTrace(); - } - } else if (baseErrorMessage instanceof String) { - try { - String errorMessage = result.getString(ERRORS); - userNotificationBundle.putString(resources.getString(R.string.user_message), errorMessage); - } catch (JSONException e) { - e.printStackTrace(); - } - } - } - - if (!username.isEmpty()) - userNotificationBundle.putString(SessionDialog.USERNAME, username); - userNotificationBundle.putBoolean(RESULT_KEY, false); - - return userNotificationBundle; - } - - /** - * Sets up an intent with the progress value passed as a parameter - * and sends it as a broadcast. - * - * @param progress - */ - protected void broadcastProgress(int progress) { - Intent intentUpdate = new Intent(); - intentUpdate.setAction(UPDATE_PROGRESSBAR); - intentUpdate.addCategory(Intent.CATEGORY_DEFAULT); - intentUpdate.putExtra(CURRENT_PROGRESS, progress); - sendBroadcast(intentUpdate); - } - - /** - * Validates parameters entered by the user to log in - * - * @param username - * @param password - * @return true if both parameters are present and the entered password length is greater or equal to eight (8). - */ - private boolean validUserLoginData(String username, String password) { - return validUsername(username) && wellFormedPassword(password); - } - - private boolean validUsername(String username) { - return username != null && !username.isEmpty(); - } - - /** - * Validates a password - * - * @param password - * @return true if the entered password length is greater or equal to eight (8). - */ - private boolean wellFormedPassword(String password) { - return password != null && password.length() >= 8; - } - - /** - * Sends an HTTP POST request to the authentication server with the SRP Parameter A. - * - * @param server_url - * @param username - * @param clientA First SRP parameter sent - * @param okHttpClient - * @return response from authentication server - */ - private JSONObject sendAToSRPServer(String server_url, String username, String clientA, OkHttpClient okHttpClient) { - SrpCredentials srpCredentials = new SrpCredentials(username, clientA); - return sendToServer(server_url + "/sessions.json", "POST", srpCredentials.toString(), okHttpClient); - } - - /** - * Sends an HTTP PUT request to the authentication server with the SRP Parameter M1 (or simply M). - * - * @param server_url - * @param username - * @param m1 Second SRP parameter sent - * @param okHttpClient - * @return response from authentication server - */ - private JSONObject sendM1ToSRPServer(String server_url, String username, byte[] m1, OkHttpClient okHttpClient) { - String m1json = "{\"client_auth\":\"" + new BigInteger(1, ConfigHelper.trim(m1)).toString(16)+ "\"}"; - return sendToServer(server_url + "/sessions/" + username + ".json", "PUT", m1json, okHttpClient); - } - - /** - * Sends an HTTP POST request to the api server to register a new user. - * - * @param server_url - * @param username - * @param salt - * @param password_verifier - * @param okHttpClient - * @return response from authentication server - */ - private JSONObject sendNewUserDataToSRPServer(String server_url, String username, String salt, String password_verifier, OkHttpClient okHttpClient) { - return sendToServer(server_url + "/users.json", "POST", new SrpRegistrationData(username, salt, password_verifier).toString(), okHttpClient); - } - - /** - * Executes an HTTP request expecting a JSON response. - * - * @param url - * @param request_method - * @return response from authentication server - */ - private JSONObject sendToServer(String url, String request_method, String jsonString, OkHttpClient okHttpClient) { - return requestJsonFromServer(url, request_method, jsonString, null, okHttpClient); - } - - protected String sendGetStringToServer(String url, List> headerArgs, OkHttpClient okHttpClient) { - return requestStringFromServer(url, "GET", null, headerArgs, okHttpClient); - } - - - - private JSONObject requestJsonFromServer(String url, String request_method, String jsonString, List> headerArgs, @NonNull OkHttpClient okHttpClient) { - JSONObject responseJson; - String plain_response = requestStringFromServer(url, request_method, jsonString, headerArgs, okHttpClient); - - try { - responseJson = new JSONObject(plain_response); - } catch (JSONException e) { - e.printStackTrace(); - responseJson = getErrorMessageAsJson(error_json_exception_user_message); - } - return responseJson; - - } - - private String requestStringFromServer(String url, String request_method, String jsonString, List> headerArgs, @NonNull OkHttpClient okHttpClient) { - Response response; - String plainResponseBody = null; - - RequestBody jsonBody = jsonString != null ? RequestBody.create(JSON, jsonString) : null; - Request.Builder requestBuilder = new Request.Builder() - .url(url) - .method(request_method, jsonBody); - if (headerArgs != null) { - for (Pair keyValPair : headerArgs) { - requestBuilder.addHeader(keyValPair.first, keyValPair.second); - } - } - //TODO: move to getHeaderArgs()? - String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry(); - requestBuilder.addHeader("Accept-Language", locale); - Request request = requestBuilder.build(); - - try { - response = okHttpClient.newCall(request).execute(); - - InputStream inputStream = response.body().byteStream(); - Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"); - if (scanner.hasNext()) { - plainResponseBody = scanner.next(); - } - - } catch (NullPointerException npe) { - plainResponseBody = formatErrorMessage(error_json_exception_user_message); - } catch (UnknownHostException | SocketTimeoutException e) { - plainResponseBody = formatErrorMessage(server_unreachable_message); - } catch (MalformedURLException e) { - plainResponseBody = formatErrorMessage(malformed_url); - } catch (SSLHandshakeException e) { - plainResponseBody = formatErrorMessage(certificate_error); - } catch (ConnectException e) { - plainResponseBody = formatErrorMessage(service_is_down_error); - } catch (IllegalArgumentException e) { - plainResponseBody = formatErrorMessage(error_no_such_algorithm_exception_user_message); - } catch (UnknownServiceException e) { - //unable to find acceptable protocols - tlsv1.2 not enabled? - plainResponseBody = formatErrorMessage(error_no_such_algorithm_exception_user_message); - } catch (IOException e) { - plainResponseBody = formatErrorMessage(error_io_exception_user_message); - } - - return plainResponseBody; - } - - /** - * Downloads a provider.json from a given URL, adding a new provider using the given name. - * - * @param task containing a boolean meaning if the provider is custom or not, another boolean meaning if the user completely trusts this provider, the provider name and its provider.json url. - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. - */ - protected abstract Bundle setUpProvider(Bundle task); - - /** - * Downloads the eip-service.json from a given URL, and saves eip service capabilities including the offered gateways - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the download was successful. - */ - protected abstract Bundle getAndSetEipServiceJson(); - - /** - * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. - * - * @return true if certificate was downloaded correctly, false if provider.json is not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. - */ - protected abstract boolean updateVpnCertificate(); - - - protected static boolean caCertDownloaded() { - return CA_CERT_DOWNLOADED; - } - - protected boolean isValidJson(String jsonString) { - try { - new JSONObject(jsonString); - return true; - } catch(JSONException e) { - return false; - } catch(NullPointerException e) { - e.printStackTrace(); - return false; - } - } - - protected boolean validCertificate(String cert_string) { - boolean result = false; - if (!ConfigHelper.checkErroneousDownload(cert_string)) { - X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string); - try { - if (certificate != null) { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - String fingerprint = provider_json.getString(Provider.CA_CERT_FINGERPRINT); - String encoding = fingerprint.split(":")[0]; - String expected_fingerprint = fingerprint.split(":")[1]; - String real_fingerprint = base64toHex(Base64.encodeToString( - MessageDigest.getInstance(encoding).digest(certificate.getEncoded()), - Base64.DEFAULT)); - - result = real_fingerprint.trim().equalsIgnoreCase(expected_fingerprint.trim()); - } else - result = false; - } catch (JSONException | NoSuchAlgorithmException | CertificateEncodingException e) { - result = false; - } - } - - return result; - } - - protected void checkPersistedProviderUpdates() { - String providerDomain = getProviderDomain(providerDefinition); - if (hasUpdatedProviderDetails(providerDomain)) { - providerCaCert = getPersistedProviderCA(providerDomain); - providerDefinition = getPersistedProviderDefinition(providerDomain); - providerCaCertFingerprint = getPersistedCaCertFingerprint(providerDomain); - providerApiUrl = getApiUrlWithVersion(providerDefinition); - } - } - - protected Bundle validateProviderDetails() { - Bundle result = validateCertificateForProvider(providerCaCert, providerDefinition, lastProviderMainUrl); - - //invalid certificate or no certificate - if (result.containsKey(ERRORS) || (result.containsKey(RESULT_KEY) && !result.getBoolean(RESULT_KEY)) ) { - return result; - } - - //valid certificate: skip download, save loaded provider CA cert and provider definition directly - try { - preferences.edit().putString(Provider.KEY, providerDefinition.toString()). - putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). - putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). - putString(Provider.CA_CERT, providerCaCert).commit(); - CA_CERT_DOWNLOADED = true; - PROVIDER_JSON_DOWNLOADED = true; - result.putBoolean(RESULT_KEY, true); - } catch (JSONException e) { - e.printStackTrace(); - result.putBoolean(RESULT_KEY, false); - result = setErrorResult(result, getString(R.string.warning_corrupted_provider_details), ERROR_CORRUPTED_PROVIDER_JSON.toString()); - } - - return result; - } - - protected Bundle validateCertificateForProvider(String cert_string, JSONObject providerDefinition, String mainUrl) { - Bundle result = new Bundle(); - result.putBoolean(RESULT_KEY, false); - - if (ConfigHelper.checkErroneousDownload(cert_string)) { - return result; - } - - X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string); - if (certificate == null) { - return setErrorResult(result, getString(R.string.warning_corrupted_provider_cert), ERROR_INVALID_CERTIFICATE.toString()); - } - try { - certificate.checkValidity(); - String fingerprint = getCaCertFingerprint(providerDefinition); - String encoding = fingerprint.split(":")[0]; - String expected_fingerprint = fingerprint.split(":")[1]; - String real_fingerprint = base64toHex(Base64.encodeToString( - MessageDigest.getInstance(encoding).digest(certificate.getEncoded()), - Base64.DEFAULT)); - if (!real_fingerprint.trim().equalsIgnoreCase(expected_fingerprint.trim())) { - return setErrorResult(result, getString(R.string.warning_corrupted_provider_cert), ERROR_CERTIFICATE_PINNING.toString()); - } - - if (!hasApiUrlExpectedDomain(providerDefinition, mainUrl)){ - return setErrorResult(result, getString(R.string.warning_corrupted_provider_details), ERROR_CORRUPTED_PROVIDER_JSON.toString()); - } - - if (!canConnect(cert_string, providerDefinition, result)) { - return result; - } - } catch (NoSuchAlgorithmException e ) { - return setErrorResult(result, resources.getString(error_no_such_algorithm_exception_user_message), null); - } catch (ArrayIndexOutOfBoundsException e) { - return setErrorResult(result, getString(R.string.warning_corrupted_provider_details), ERROR_CORRUPTED_PROVIDER_JSON.toString()); - } catch (CertificateEncodingException | CertificateNotYetValidException | CertificateExpiredException e) { - return setErrorResult(result, getString(R.string.warning_expired_provider_cert), ERROR_INVALID_CERTIFICATE.toString()); - } - - result.putBoolean(RESULT_KEY, true); - return result; - } - - protected Bundle setErrorResult(Bundle result, String errorMessage, String errorId) { - JSONObject errorJson = new JSONObject(); - if (errorId != null) { - addErrorMessageToJson(errorJson, errorMessage, errorId); - } else { - addErrorMessageToJson(errorJson, errorMessage); - } - result.putString(ERRORS, errorJson.toString()); - return result; - } - - /** - * This method aims to prevent attacks where the provider.json file got manipulated by a third party. - * The main url is visible to the provider when setting up a new provider. - * The user is responsible to check that this is the provider main url he intends to connect to. - * - * @param providerDefinition - * @param mainUrlString - * @return - */ - private boolean hasApiUrlExpectedDomain(JSONObject providerDefinition, String mainUrlString) { - // fix against "api_uri": "https://calyx.net.malicious.url.net:4430", - String apiUrlString = getApiUrl(providerDefinition); - String providerDomain = getProviderDomain(providerDefinition); - if (mainUrlString.contains(providerDomain) && apiUrlString.contains(providerDomain + ":")) { - return true; - } - return false; - } - - private boolean canConnect(String caCert, JSONObject providerDefinition, Bundle result) { - JSONObject errorJson = new JSONObject(); - String baseUrl = getApiUrl(providerDefinition); - - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(errorJson, caCert); - if (okHttpClient == null) { - result.putString(ERRORS, errorJson.toString()); - return false; - } - - List> headerArgs = getAuthorizationHeader(); - String plain_response = requestStringFromServer(baseUrl, "GET", null, headerArgs, okHttpClient); - - try { - if (new JSONObject(plain_response).has(ERRORS)) { - result.putString(ERRORS, plain_response); - return false; - } - } catch (JSONException e) { - //eat me - } - - return true; - } - - protected String getCaCertFingerprint(JSONObject providerDefinition) { - try { - return providerDefinition.getString(Provider.CA_CERT_FINGERPRINT); - } catch (JSONException e) { - e.printStackTrace(); - } - return ""; - } - - protected String getApiUrl(JSONObject providerDefinition) { - try { - return providerDefinition.getString(Provider.API_URL); - } catch (JSONException e) { - e.printStackTrace(); - } - return ""; - } - - protected String getApiUrlWithVersion(JSONObject providerDefinition) { - try { - return providerDefinition.getString(Provider.API_URL) + "/" + providerDefinition.getString(Provider.API_VERSION); - } catch (JSONException e) { - e.printStackTrace(); - } - return ""; - } - - protected void deleteProviderDetailsFromPreferences(JSONObject providerDefinition) { - String providerDomain = getProviderDomain(providerDefinition); - - if (preferences.contains(Provider.KEY + "." + providerDomain)) { - preferences.edit().remove(Provider.KEY + "." + providerDomain).apply(); - } - if (preferences.contains(Provider.CA_CERT + "." + providerDomain)) { - preferences.edit().remove(Provider.CA_CERT + "." + providerDomain).apply(); - } - if (preferences.contains(Provider.CA_CERT_FINGERPRINT + "." + providerDomain)) { - preferences.edit().remove(Provider.CA_CERT_FINGERPRINT + "." + providerDomain).apply(); - } - } - - protected String getPersistedCaCertFingerprint(String providerDomain) { - try { - return getPersistedProviderDefinition(providerDomain).getString(Provider.CA_CERT_FINGERPRINT); - } catch (JSONException e) { - e.printStackTrace(); - } - return ""; - } - - protected JSONObject getPersistedProviderDefinition(String providerDomain) { - try { - return new JSONObject(preferences.getString(Provider.KEY + "." + providerDomain, "")); - } catch (JSONException e) { - e.printStackTrace(); - return new JSONObject(); - } - } - - protected String getPersistedProviderCA(String providerDomain) { - return preferences.getString(Provider.CA_CERT + "." + providerDomain, ""); - } - - protected String getProviderDomain(JSONObject providerDefinition) { - try { - return providerDefinition.getString(Provider.DOMAIN); - } catch (JSONException e) { - e.printStackTrace(); - } - - return ""; - } - - protected boolean hasUpdatedProviderDetails(String providerDomain) { - return preferences.contains(Provider.KEY + "." + providerDomain) && preferences.contains(Provider.CA_CERT + "." + providerDomain); - } - - /** - * Interprets the error message as a JSON object and extract the "errors" keyword pair. - * If the error message is not a JSON object, then it is returned untouched. - * - * @param string_json_error_message - * @return final error message - */ - protected String pickErrorMessage(String string_json_error_message) { - String error_message = ""; - try { - JSONObject json_error_message = new JSONObject(string_json_error_message); - error_message = json_error_message.getString(ERRORS); - } catch (JSONException e) { - // TODO Auto-generated catch block - error_message = string_json_error_message; - } - - return error_message; - } - - @NonNull - protected List> getAuthorizationHeader() { - List> headerArgs = new ArrayList<>(); - if (!LeapSRPSession.getToken().isEmpty()) { - Pair authorizationHeaderPair = new Pair<>(LeapSRPSession.AUTHORIZATION_HEADER, "Token token=" + LeapSRPSession.getToken()); - headerArgs.add(authorizationHeaderPair); - } - return headerArgs; - } - - private boolean logOut() { - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(new JSONObject()); - if (okHttpClient == null) { - return false; - } - - String deleteUrl = providerApiUrl + "/logout"; - int progress = 0; - - Request.Builder requestBuilder = new Request.Builder() - .url(deleteUrl) - .delete(); - Request request = requestBuilder.build(); - - try { - Response response = okHttpClient.newCall(request).execute(); - // v---- was already not authorized - if (response.isSuccessful() || response.code() == 401) { - broadcastProgress(progress++); - LeapSRPSession.setToken(""); - } - - } catch (IOException e) { - return false; - } - return true; - } - - //FIXME: don't save private keys in shared preferences! use the keystore - protected boolean loadCertificate(String cert_string) { - if (cert_string == null) { - return false; - } - - try { - // API returns concatenated cert & key. Split them for OpenVPN options - String certificateString = null, keyString = null; - String[] certAndKey = cert_string.split("(?<=-\n)"); - for (int i = 0; i < certAndKey.length - 1; i++) { - if (certAndKey[i].contains("KEY")) { - keyString = certAndKey[i++] + certAndKey[i]; - } else if (certAndKey[i].contains("CERTIFICATE")) { - certificateString = certAndKey[i++] + certAndKey[i]; - } - } - - RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); - keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); - - X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); - certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PROVIDER_VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); - return true; - } catch (CertificateException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - } -} diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiConnector.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiConnector.java new file mode 100644 index 00000000..9aad14d5 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiConnector.java @@ -0,0 +1,102 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient; + +import android.support.annotation.NonNull; +import android.util.Pair; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Locale; +import java.util.Scanner; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +/** + * Created by cyberta on 08.01.18. + */ + +public class ProviderApiConnector { + + private static final MediaType JSON + = MediaType.parse("application/json; charset=utf-8"); + + + public static boolean delete(OkHttpClient okHttpClient, String deleteUrl) { + try { + Request.Builder requestBuilder = new Request.Builder() + .url(deleteUrl) + .delete(); + Request request = requestBuilder.build(); + + Response response = okHttpClient.newCall(request).execute(); + if (response.isSuccessful() || response.code() == 401) { + return true; + } + } catch (IOException | RuntimeException e) { + return false; + } + + return false; + } + + public static boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) { + try { + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .method("GET", null); + Request request = requestBuilder.build(); + + Response response = okHttpClient.newCall(request).execute(); + return response.isSuccessful(); + } catch (RuntimeException | IOException e) { + return false; + } + + } + + public static String requestStringFromServer(@NonNull String url, @NonNull String request_method, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + + RequestBody jsonBody = jsonString != null ? RequestBody.create(JSON, jsonString) : null; + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .method(request_method, jsonBody); + if (headerArgs != null) { + for (Pair keyValPair : headerArgs) { + requestBuilder.addHeader(keyValPair.first, keyValPair.second); + } + } + //TODO: move to getHeaderArgs()? + String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry(); + requestBuilder.addHeader("Accept-Language", locale); + Request request = requestBuilder.build(); + + Response response = okHttpClient.newCall(request).execute(); + InputStream inputStream = response.body().byteStream(); + Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"); + if (scanner.hasNext()) { + return scanner.next(); + } + return null; + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java new file mode 100644 index 00000000..396d642b --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java @@ -0,0 +1,984 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.os.Bundle; +import android.os.ResultReceiver; +import android.support.annotation.NonNull; +import android.util.Base64; +import android.util.Pair; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.net.ConnectException; +import java.net.MalformedURLException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.net.UnknownServiceException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPrivateKey; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Scanner; + +import javax.net.ssl.SSLHandshakeException; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import se.leap.bitmaskclient.userstatus.SessionDialog; +import se.leap.bitmaskclient.userstatus.User; +import se.leap.bitmaskclient.userstatus.UserStatus; + +import static se.leap.bitmaskclient.ConfigHelper.getFingerprintFromCertificate; +import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CERTIFICATE_PINNING; +import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CORRUPTED_PROVIDER_JSON; +import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_INVALID_CERTIFICATE; +import static se.leap.bitmaskclient.Provider.MAIN_URL; +import static se.leap.bitmaskclient.ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE; +import static se.leap.bitmaskclient.ProviderAPI.CORRECTLY_DOWNLOADED_EIP_SERVICE; +import static se.leap.bitmaskclient.ProviderAPI.CURRENT_PROGRESS; +import static se.leap.bitmaskclient.ProviderAPI.DOWNLOAD_CERTIFICATE; +import static se.leap.bitmaskclient.ProviderAPI.DOWNLOAD_EIP_SERVICE; +import static se.leap.bitmaskclient.ProviderAPI.ERRORID; +import static se.leap.bitmaskclient.ProviderAPI.ERRORS; +import static se.leap.bitmaskclient.ProviderAPI.FAILED_LOGIN; +import static se.leap.bitmaskclient.ProviderAPI.FAILED_SIGNUP; +import static se.leap.bitmaskclient.ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE; +import static se.leap.bitmaskclient.ProviderAPI.INCORRECTLY_DOWNLOADED_EIP_SERVICE; +import static se.leap.bitmaskclient.ProviderAPI.LOGOUT_FAILED; +import static se.leap.bitmaskclient.ProviderAPI.LOG_IN; +import static se.leap.bitmaskclient.ProviderAPI.LOG_OUT; +import static se.leap.bitmaskclient.ProviderAPI.PARAMETERS; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_NOK; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_OK; +import static se.leap.bitmaskclient.ProviderAPI.RECEIVER_KEY; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_KEY; +import static se.leap.bitmaskclient.ProviderAPI.SET_UP_PROVIDER; +import static se.leap.bitmaskclient.ProviderAPI.SIGN_UP; +import static se.leap.bitmaskclient.ProviderAPI.SUCCESSFUL_LOGIN; +import static se.leap.bitmaskclient.ProviderAPI.SUCCESSFUL_LOGOUT; +import static se.leap.bitmaskclient.ProviderAPI.SUCCESSFUL_SIGNUP; +import static se.leap.bitmaskclient.ProviderAPI.UPDATE_PROGRESSBAR; +import static se.leap.bitmaskclient.ProviderAPI.UPDATE_PROVIDER_DETAILS; +import static se.leap.bitmaskclient.R.string.certificate_error; +import static se.leap.bitmaskclient.R.string.error_io_exception_user_message; +import static se.leap.bitmaskclient.R.string.error_json_exception_user_message; +import static se.leap.bitmaskclient.R.string.error_no_such_algorithm_exception_user_message; +import static se.leap.bitmaskclient.R.string.malformed_url; +import static se.leap.bitmaskclient.R.string.retry; +import static se.leap.bitmaskclient.R.string.server_unreachable_message; +import static se.leap.bitmaskclient.R.string.service_is_down_error; + +/** + * Implements the logic of the http api calls. The methods of this class needs to be called from + * a background thread. + */ + +public abstract class ProviderApiManagerBase { + + public interface ProviderApiServiceCallback { + void broadcastProgress(Intent intent); + } + + private ProviderApiServiceCallback serviceCallback; + + protected static volatile boolean + CA_CERT_DOWNLOADED = false, + PROVIDER_JSON_DOWNLOADED = false, + EIP_SERVICE_JSON_DOWNLOADED = false; + + protected static String lastProviderMainUrl; + protected static boolean go_ahead = true; + protected static SharedPreferences preferences; + protected static String providerApiUrl; + protected static String providerCaCertFingerprint; + protected static String providerCaCert; + protected static JSONObject providerDefinition; + protected Resources resources; + protected OkHttpClientGenerator clientGenerator; + + public static void stop() { + go_ahead = false; + } + + public static String lastProviderMainUrl() { + return lastProviderMainUrl; + } + + + private final MediaType JSON + = MediaType.parse("application/json; charset=utf-8"); + + public ProviderApiManagerBase(SharedPreferences preferences, Resources resources, OkHttpClientGenerator clientGenerator, ProviderApiServiceCallback callback) { + this.preferences = preferences; + this.resources = resources; + this.serviceCallback = callback; + this.clientGenerator = clientGenerator; + } + + public void handleIntent(Intent command) { + final ResultReceiver receiver = command.getParcelableExtra(RECEIVER_KEY); + String action = command.getAction(); + Bundle parameters = command.getBundleExtra(PARAMETERS); + + if (providerApiUrl == null && preferences.contains(Provider.KEY)) { + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + providerApiUrl = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION); + go_ahead = true; + } catch (JSONException e) { + go_ahead = false; + } + } + + if (action.equals(UPDATE_PROVIDER_DETAILS)) { + resetProviderDetails(); + Bundle task = new Bundle(); + task.putString(MAIN_URL, lastProviderMainUrl); + Bundle result = setUpProvider(task); + if (result.getBoolean(RESULT_KEY)) { + receiver.send(PROVIDER_OK, result); + } else { + receiver.send(PROVIDER_NOK, result); + } + } else if (action.equalsIgnoreCase(SET_UP_PROVIDER)) { + Bundle result = setUpProvider(parameters); + if (go_ahead) { + if (result.getBoolean(RESULT_KEY)) { + receiver.send(PROVIDER_OK, result); + } else { + receiver.send(PROVIDER_NOK, result); + } + } + } else if (action.equalsIgnoreCase(SIGN_UP)) { + UserStatus.updateStatus(UserStatus.SessionStatus.SIGNING_UP, resources); + Bundle result = tryToRegister(parameters); + if (result.getBoolean(RESULT_KEY)) { + receiver.send(SUCCESSFUL_SIGNUP, result); + } else { + receiver.send(FAILED_SIGNUP, result); + } + } else if (action.equalsIgnoreCase(LOG_IN)) { + UserStatus.updateStatus(UserStatus.SessionStatus.LOGGING_IN, resources); + Bundle result = tryToAuthenticate(parameters); + if (result.getBoolean(RESULT_KEY)) { + receiver.send(SUCCESSFUL_LOGIN, result); + UserStatus.updateStatus(UserStatus.SessionStatus.LOGGED_IN, resources); + } else { + receiver.send(FAILED_LOGIN, result); + UserStatus.updateStatus(UserStatus.SessionStatus.NOT_LOGGED_IN, resources); + } + } else if (action.equalsIgnoreCase(LOG_OUT)) { + UserStatus.updateStatus(UserStatus.SessionStatus.LOGGING_OUT, resources); + if (logOut()) { + receiver.send(SUCCESSFUL_LOGOUT, Bundle.EMPTY); + UserStatus.updateStatus(UserStatus.SessionStatus.LOGGED_OUT, resources); + } else { + receiver.send(LOGOUT_FAILED, Bundle.EMPTY); + UserStatus.updateStatus(UserStatus.SessionStatus.DIDNT_LOG_OUT, resources); + } + } else if (action.equalsIgnoreCase(DOWNLOAD_CERTIFICATE)) { + if (updateVpnCertificate()) { + receiver.send(CORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); + } else { + receiver.send(INCORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); + } + } else if (action.equalsIgnoreCase(DOWNLOAD_EIP_SERVICE)) { + Bundle result = getAndSetEipServiceJson(); + if (result.getBoolean(RESULT_KEY)) { + receiver.send(CORRECTLY_DOWNLOADED_EIP_SERVICE, result); + } else { + receiver.send(INCORRECTLY_DOWNLOADED_EIP_SERVICE, result); + } + } + } + + protected void resetProviderDetails() { + CA_CERT_DOWNLOADED = PROVIDER_JSON_DOWNLOADED = false; + deleteProviderDetailsFromPreferences(providerDefinition); + providerCaCert = ""; + providerDefinition = new JSONObject(); + } + + protected String formatErrorMessage(final int toastStringId) { + return formatErrorMessage(resources.getString(toastStringId)); + } + + private String formatErrorMessage(String errorMessage) { + return "{ \"" + ERRORS + "\" : \"" + errorMessage + "\" }"; + } + + private JSONObject getErrorMessageAsJson(final int toastStringId) { + try { + return new JSONObject(formatErrorMessage(toastStringId)); + } catch (JSONException e) { + e.printStackTrace(); + return new JSONObject(); + } + } + + protected void addErrorMessageToJson(JSONObject jsonObject, String errorMessage) { + try { + jsonObject.put(ERRORS, errorMessage); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + protected void addErrorMessageToJson(JSONObject jsonObject, String errorMessage, String errorId) { + try { + jsonObject.put(ERRORS, errorMessage); + jsonObject.put(ERRORID, errorId); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + + + + private Bundle tryToRegister(Bundle task) { + Bundle result = new Bundle(); + int progress = 0; + + String username = User.userName(); + String password = task.getString(SessionDialog.PASSWORD); + + if (validUserLoginData(username, password)) { + result = register(username, password); + broadcastProgress(progress++); + } else { + if (!wellFormedPassword(password)) { + result.putBoolean(RESULT_KEY, false); + result.putString(SessionDialog.USERNAME, username); + result.putBoolean(SessionDialog.ERRORS.PASSWORD_INVALID_LENGTH.toString(), true); + } + if (!validUsername(username)) { + result.putBoolean(RESULT_KEY, false); + result.putBoolean(SessionDialog.ERRORS.USERNAME_MISSING.toString(), true); + } + } + + return result; + } + + private Bundle register(String username, String password) { + JSONObject stepResult = null; + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(stepResult); + if (okHttpClient == null) { + return authFailedNotification(stepResult, username); + } + + LeapSRPSession client = new LeapSRPSession(username, password); + byte[] salt = client.calculateNewSalt(); + + BigInteger password_verifier = client.calculateV(username, password, salt); + + JSONObject api_result = sendNewUserDataToSRPServer(providerApiUrl, username, new BigInteger(1, salt).toString(16), password_verifier.toString(16), okHttpClient); + + Bundle result = new Bundle(); + if (api_result.has(ERRORS)) + result = authFailedNotification(api_result, username); + else { + result.putString(SessionDialog.USERNAME, username); + result.putString(SessionDialog.PASSWORD, password); + result.putBoolean(RESULT_KEY, true); + } + + return result; + } + + /** + * Starts the authentication process using SRP protocol. + * + * @param task containing: username, password and api url. + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if authentication was successful. + */ + private Bundle tryToAuthenticate(Bundle task) { + Bundle result = new Bundle(); + int progress = 0; + + String username = User.userName(); + String password = task.getString(SessionDialog.PASSWORD); + if (validUserLoginData(username, password)) { + result = authenticate(username, password); + broadcastProgress(progress++); + } else { + if (!wellFormedPassword(password)) { + result.putBoolean(RESULT_KEY, false); + result.putString(SessionDialog.USERNAME, username); + result.putBoolean(SessionDialog.ERRORS.PASSWORD_INVALID_LENGTH.toString(), true); + } + if (!validUsername(username)) { + result.putBoolean(RESULT_KEY, false); + result.putBoolean(SessionDialog.ERRORS.USERNAME_MISSING.toString(), true); + } + } + + return result; + } + + private Bundle authenticate(String username, String password) { + Bundle result = new Bundle(); + JSONObject stepResult = new JSONObject(); + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(stepResult); + if (okHttpClient == null) { + return authFailedNotification(stepResult, username); + } + + LeapSRPSession client = new LeapSRPSession(username, password); + byte[] A = client.exponential(); + + JSONObject step_result = sendAToSRPServer(providerApiUrl, username, new BigInteger(1, A).toString(16), okHttpClient); + try { + String salt = step_result.getString(LeapSRPSession.SALT); + byte[] Bbytes = new BigInteger(step_result.getString("B"), 16).toByteArray(); + byte[] M1 = client.response(new BigInteger(salt, 16).toByteArray(), Bbytes); + if (M1 != null) { + step_result = sendM1ToSRPServer(providerApiUrl, username, M1, okHttpClient); + setTokenIfAvailable(step_result); + byte[] M2 = new BigInteger(step_result.getString(LeapSRPSession.M2), 16).toByteArray(); + if (client.verify(M2)) { + result.putBoolean(RESULT_KEY, true); + } else { + authFailedNotification(step_result, username); + } + } else { + result.putBoolean(RESULT_KEY, false); + result.putString(SessionDialog.USERNAME, username); + result.putString(resources.getString(R.string.user_message), resources.getString(R.string.error_srp_math_error_user_message)); + } + } catch (JSONException e) { + result = authFailedNotification(step_result, username); + e.printStackTrace(); + } + + return result; + } + + private boolean setTokenIfAvailable(JSONObject authentication_step_result) { + try { + LeapSRPSession.setToken(authentication_step_result.getString(LeapSRPSession.TOKEN)); + } catch (JSONException e) { // + return false; + } + return true; + } + + private Bundle authFailedNotification(JSONObject result, String username) { + Bundle userNotificationBundle = new Bundle(); + Object baseErrorMessage = result.opt(ERRORS); + if (baseErrorMessage != null) { + if (baseErrorMessage instanceof JSONObject) { + try { + JSONObject errorMessage = result.getJSONObject(ERRORS); + String errorType = errorMessage.keys().next().toString(); + String message = errorMessage.get(errorType).toString(); + userNotificationBundle.putString(resources.getString(R.string.user_message), message); + } catch (JSONException e) { + e.printStackTrace(); + } + } else if (baseErrorMessage instanceof String) { + try { + String errorMessage = result.getString(ERRORS); + userNotificationBundle.putString(resources.getString(R.string.user_message), errorMessage); + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + + if (!username.isEmpty()) + userNotificationBundle.putString(SessionDialog.USERNAME, username); + userNotificationBundle.putBoolean(RESULT_KEY, false); + + return userNotificationBundle; + } + + /** + * Sets up an intent with the progress value passed as a parameter + * and sends it as a broadcast. + * + * @param progress + */ + protected void broadcastProgress(int progress) { + Intent intentUpdate = new Intent(); + intentUpdate.setAction(UPDATE_PROGRESSBAR); + intentUpdate.addCategory(Intent.CATEGORY_DEFAULT); + intentUpdate.putExtra(CURRENT_PROGRESS, progress); + serviceCallback.broadcastProgress(intentUpdate); + //sendBroadcast(intentUpdate); + } + + /** + * Validates parameters entered by the user to log in + * + * @param username + * @param password + * @return true if both parameters are present and the entered password length is greater or equal to eight (8). + */ + private boolean validUserLoginData(String username, String password) { + return validUsername(username) && wellFormedPassword(password); + } + + private boolean validUsername(String username) { + return username != null && !username.isEmpty(); + } + + /** + * Validates a password + * + * @param password + * @return true if the entered password length is greater or equal to eight (8). + */ + private boolean wellFormedPassword(String password) { + return password != null && password.length() >= 8; + } + + /** + * Sends an HTTP POST request to the authentication server with the SRP Parameter A. + * + * @param server_url + * @param username + * @param clientA First SRP parameter sent + * @param okHttpClient + * @return response from authentication server + */ + private JSONObject sendAToSRPServer(String server_url, String username, String clientA, OkHttpClient okHttpClient) { + SrpCredentials srpCredentials = new SrpCredentials(username, clientA); + return sendToServer(server_url + "/sessions.json", "POST", srpCredentials.toString(), okHttpClient); + } + + /** + * Sends an HTTP PUT request to the authentication server with the SRP Parameter M1 (or simply M). + * + * @param server_url + * @param username + * @param m1 Second SRP parameter sent + * @param okHttpClient + * @return response from authentication server + */ + private JSONObject sendM1ToSRPServer(String server_url, String username, byte[] m1, OkHttpClient okHttpClient) { + String m1json = "{\"client_auth\":\"" + new BigInteger(1, ConfigHelper.trim(m1)).toString(16)+ "\"}"; + return sendToServer(server_url + "/sessions/" + username + ".json", "PUT", m1json, okHttpClient); + } + + /** + * Sends an HTTP POST request to the api server to register a new user. + * + * @param server_url + * @param username + * @param salt + * @param password_verifier + * @param okHttpClient + * @return response from authentication server + */ + private JSONObject sendNewUserDataToSRPServer(String server_url, String username, String salt, String password_verifier, OkHttpClient okHttpClient) { + return sendToServer(server_url + "/users.json", "POST", new SrpRegistrationData(username, salt, password_verifier).toString(), okHttpClient); + } + + /** + * Executes an HTTP request expecting a JSON response. + * + * @param url + * @param request_method + * @return response from authentication server + */ + private JSONObject sendToServer(String url, String request_method, String jsonString, OkHttpClient okHttpClient) { + return requestJsonFromServer(url, request_method, jsonString, null, okHttpClient); + } + + protected String sendGetStringToServer(String url, List> headerArgs, OkHttpClient okHttpClient) { + return requestStringFromServer(url, "GET", null, headerArgs, okHttpClient); + } + + + + private JSONObject requestJsonFromServer(String url, String request_method, String jsonString, List> headerArgs, @NonNull OkHttpClient okHttpClient) { + JSONObject responseJson; + String plain_response = requestStringFromServer(url, request_method, jsonString, headerArgs, okHttpClient); + + try { + responseJson = new JSONObject(plain_response); + } catch (JSONException e) { + e.printStackTrace(); + responseJson = getErrorMessageAsJson(error_json_exception_user_message); + } + return responseJson; + + } + + private String requestStringFromServer(String url, String request_method, String jsonString, List> headerArgs, @NonNull OkHttpClient okHttpClient) { + //Response response; + String plainResponseBody = null; + + /*RequestBody jsonBody = jsonString != null ? RequestBody.create(JSON, jsonString) : null; + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .method(request_method, jsonBody); + if (headerArgs != null) { + for (Pair keyValPair : headerArgs) { + requestBuilder.addHeader(keyValPair.first, keyValPair.second); + } + } + //TODO: move to getHeaderArgs()? + String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry(); + requestBuilder.addHeader("Accept-Language", locale); + Request request = requestBuilder.build(); +*/ + try { + //response = okHttpClient.newCall(request).execute(); + //response = ProviderApiConnector.requestStringFromServer(url, request_method, jsonString, headerArgs, okHttpClient); + //InputStream inputStream = response.body().byteStream(); + //Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"); + //if (scanner.hasNext()) { + // plainResponseBody = scanner.next(); + //} + + plainResponseBody = ProviderApiConnector.requestStringFromServer(url, request_method, jsonString, headerArgs, okHttpClient); + } catch (NullPointerException npe) { + plainResponseBody = formatErrorMessage(error_json_exception_user_message); + } catch (UnknownHostException | SocketTimeoutException e) { + plainResponseBody = formatErrorMessage(server_unreachable_message); + } catch (MalformedURLException e) { + plainResponseBody = formatErrorMessage(malformed_url); + } catch (SSLHandshakeException e) { + plainResponseBody = formatErrorMessage(certificate_error); + } catch (ConnectException e) { + plainResponseBody = formatErrorMessage(service_is_down_error); + } catch (IllegalArgumentException e) { + plainResponseBody = formatErrorMessage(error_no_such_algorithm_exception_user_message); + } catch (UnknownServiceException e) { + //unable to find acceptable protocols - tlsv1.2 not enabled? + plainResponseBody = formatErrorMessage(error_no_such_algorithm_exception_user_message); + } catch (IOException e) { + plainResponseBody = formatErrorMessage(error_io_exception_user_message); + } + + return plainResponseBody; + } + + /** + * Downloads a provider.json from a given URL, adding a new provider using the given name. + * + * @param task containing a boolean meaning if the provider is custom or not, another boolean meaning if the user completely trusts this provider, the provider name and its provider.json url. + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. + */ + protected abstract Bundle setUpProvider(Bundle task); + + /** + * Downloads the eip-service.json from a given URL, and saves eip service capabilities including the offered gateways + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the download was successful. + */ + protected abstract Bundle getAndSetEipServiceJson(); + + /** + * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. + * + * @return true if certificate was downloaded correctly, false if provider.json is not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. + */ + protected abstract boolean updateVpnCertificate(); + + + protected static boolean caCertDownloaded() { + return CA_CERT_DOWNLOADED; + } + + protected boolean isValidJson(String jsonString) { + try { + new JSONObject(jsonString); + return true; + } catch(JSONException e) { + return false; + } catch(NullPointerException e) { + e.printStackTrace(); + return false; + } + } + + protected boolean validCertificate(String cert_string) { + boolean result = false; + if (!ConfigHelper.checkErroneousDownload(cert_string)) { + X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string); + try { + if (certificate != null) { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + String fingerprint = provider_json.getString(Provider.CA_CERT_FINGERPRINT); + String encoding = fingerprint.split(":")[0]; + String expected_fingerprint = fingerprint.split(":")[1]; + String real_fingerprint = getFingerprintFromCertificate(certificate, encoding); + + result = real_fingerprint.trim().equalsIgnoreCase(expected_fingerprint.trim()); + } else + result = false; + } catch (JSONException | NoSuchAlgorithmException | CertificateEncodingException /*| UnsupportedEncodingException*/ e) { + result = false; + } + } + + return result; + } + + + + protected void checkPersistedProviderUpdates() { + //String providerDomain = getProviderDomain(providerDefinition); + String providerDomain = getDomainFromMainURL(lastProviderMainUrl); + if (hasUpdatedProviderDetails(providerDomain)) { + providerCaCert = getPersistedProviderCA(providerDomain); + providerDefinition = getPersistedProviderDefinition(providerDomain); + providerCaCertFingerprint = getPersistedCaCertFingerprint(providerDomain); + providerApiUrl = getApiUrlWithVersion(providerDefinition); + } + } + + protected Bundle validateProviderDetails() { + Bundle result = validateCertificateForProvider(providerCaCert, providerDefinition, lastProviderMainUrl); + + //invalid certificate or no certificate + if (result.containsKey(ERRORS) || (result.containsKey(RESULT_KEY) && !result.getBoolean(RESULT_KEY)) ) { + return result; + } + + //valid certificate: skip download, save loaded provider CA cert and provider definition directly + try { + preferences.edit().putString(Provider.KEY, providerDefinition.toString()). + putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). + putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). + putString(Provider.CA_CERT, providerCaCert).commit(); + CA_CERT_DOWNLOADED = true; + PROVIDER_JSON_DOWNLOADED = true; + result.putBoolean(RESULT_KEY, true); + } catch (JSONException e) { + e.printStackTrace(); + result.putBoolean(RESULT_KEY, false); + result = setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_details), ERROR_CORRUPTED_PROVIDER_JSON.toString()); + } + + return result; + } + + protected Bundle validateCertificateForProvider(String cert_string, JSONObject providerDefinition, String mainUrl) { + Bundle result = new Bundle(); + result.putBoolean(RESULT_KEY, false); + + if (ConfigHelper.checkErroneousDownload(cert_string)) { + return result; + } + + X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string); + if (certificate == null) { + return setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_cert), ERROR_INVALID_CERTIFICATE.toString()); + } + try { + certificate.checkValidity(); + String fingerprint = getCaCertFingerprint(providerDefinition); + String encoding = fingerprint.split(":")[0]; + String expected_fingerprint = fingerprint.split(":")[1]; + String real_fingerprint = getFingerprintFromCertificate(certificate, encoding); + if (!real_fingerprint.trim().equalsIgnoreCase(expected_fingerprint.trim())) { + return setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_cert), ERROR_CERTIFICATE_PINNING.toString()); + } + + + if (!hasApiUrlExpectedDomain(providerDefinition, mainUrl)){ + return setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_details), ERROR_CORRUPTED_PROVIDER_JSON.toString()); + } + + if (!canConnect(cert_string, providerDefinition, result)) { + return result; + } + } catch (NoSuchAlgorithmException e ) { + return setErrorResult(result, resources.getString(error_no_such_algorithm_exception_user_message), null); + } catch (ArrayIndexOutOfBoundsException e) { + return setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_details), ERROR_CORRUPTED_PROVIDER_JSON.toString()); + } catch (CertificateEncodingException | CertificateNotYetValidException | CertificateExpiredException e) { + return setErrorResult(result, resources.getString(R.string.warning_expired_provider_cert), ERROR_INVALID_CERTIFICATE.toString()); + } /*catch (UnsupportedEncodingException e) { + return setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_cert), ERROR_CERTIFICATE_PINNING.toString()); + }*/ + + result.putBoolean(RESULT_KEY, true); + return result; + } + + protected Bundle setErrorResult(Bundle result, String errorMessage, String errorId) { + JSONObject errorJson = new JSONObject(); + if (errorId != null) { + addErrorMessageToJson(errorJson, errorMessage, errorId); + } else { + addErrorMessageToJson(errorJson, errorMessage); + } + result.putString(ERRORS, errorJson.toString()); + return result; + } + + /** + * This method aims to prevent attacks where the provider.json file got manipulated by a third party. + * The main url is visible to the provider when setting up a new provider. + * The user is responsible to check that this is the provider main url he intends to connect to. + * + * @param providerDefinition + * @param mainUrlString + * @return + */ + private boolean hasApiUrlExpectedDomain(JSONObject providerDefinition, String mainUrlString) { + // fix against "api_uri": "https://calyx.net.malicious.url.net:4430", + String apiUrlString = getApiUrl(providerDefinition); + String providerDomain = getProviderDomain(providerDefinition); + if (mainUrlString.contains(providerDomain) && apiUrlString.contains(providerDomain + ":")) { + return true; + } + return false; + } + + private boolean canConnect(String caCert, JSONObject providerDefinition, Bundle result) { + JSONObject errorJson = new JSONObject(); + String baseUrl = getApiUrl(providerDefinition); + + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(errorJson, caCert); + if (okHttpClient == null) { + result.putString(ERRORS, errorJson.toString()); + return false; + } + + //try { + + return ProviderApiConnector.canConnect(okHttpClient, baseUrl); + /*} catch (RuntimeException | IOException e) { + e.printStackTrace(); + }*/ + + //return false; + + + /*List> headerArgs = getAuthorizationHeader(); + String plain_response = requestStringFromServer(baseUrl, "GET", null, headerArgs, okHttpClient); + + try { + if (new JSONObject(plain_response).has(ERRORS)) { + result.putString(ERRORS, plain_response); + return false; + } + } catch (JSONException e) { + //eat me + } + + return true;*/ + } + + protected String getCaCertFingerprint(JSONObject providerDefinition) { + try { + return providerDefinition.getString(Provider.CA_CERT_FINGERPRINT); + } catch (JSONException e) { + e.printStackTrace(); + } + return ""; + } + + protected String getApiUrl(JSONObject providerDefinition) { + try { + return providerDefinition.getString(Provider.API_URL); + } catch (JSONException e) { + e.printStackTrace(); + } + return ""; + } + + protected String getApiUrlWithVersion(JSONObject providerDefinition) { + try { + return providerDefinition.getString(Provider.API_URL) + "/" + providerDefinition.getString(Provider.API_VERSION); + } catch (JSONException e) { + e.printStackTrace(); + } + return ""; + } + + protected void deleteProviderDetailsFromPreferences(JSONObject providerDefinition) { + String providerDomain = getProviderDomain(providerDefinition); + + if (preferences.contains(Provider.KEY + "." + providerDomain)) { + preferences.edit().remove(Provider.KEY + "." + providerDomain).apply(); + } + if (preferences.contains(Provider.CA_CERT + "." + providerDomain)) { + preferences.edit().remove(Provider.CA_CERT + "." + providerDomain).apply(); + } + if (preferences.contains(Provider.CA_CERT_FINGERPRINT + "." + providerDomain)) { + preferences.edit().remove(Provider.CA_CERT_FINGERPRINT + "." + providerDomain).apply(); + } + } + + protected String getPersistedCaCertFingerprint(String providerDomain) { + try { + return getPersistedProviderDefinition(providerDomain).getString(Provider.CA_CERT_FINGERPRINT); + } catch (JSONException e) { + e.printStackTrace(); + } + return ""; + } + + protected JSONObject getPersistedProviderDefinition(String providerDomain) { + try { + return new JSONObject(preferences.getString(Provider.KEY + "." + providerDomain, "")); + } catch (JSONException e) { + e.printStackTrace(); + return new JSONObject(); + } + } + + protected String getPersistedProviderCA(String providerDomain) { + return preferences.getString(Provider.CA_CERT + "." + providerDomain, ""); + } + + protected String getProviderDomain(JSONObject providerDefinition) { + try { + return providerDefinition.getString(Provider.DOMAIN); + } catch (JSONException e) { + e.printStackTrace(); + } + + return ""; + } + + protected boolean hasUpdatedProviderDetails(String domain) { + return preferences.contains(Provider.KEY + "." + domain) && preferences.contains(Provider.CA_CERT + "." + domain); + } + + protected String getDomainFromMainURL(String mainUrl) { + return mainUrl.replaceFirst("http[s]?://", "").replaceFirst("/.*", ""); + + } + + /** + * Interprets the error message as a JSON object and extract the "errors" keyword pair. + * If the error message is not a JSON object, then it is returned untouched. + * + * @param string_json_error_message + * @return final error message + */ + protected String pickErrorMessage(String string_json_error_message) { + String error_message = ""; + try { + JSONObject json_error_message = new JSONObject(string_json_error_message); + error_message = json_error_message.getString(ERRORS); + } catch (JSONException e) { + // TODO Auto-generated catch block + error_message = string_json_error_message; + } catch (NullPointerException e) { + //do nothing + } + + return error_message; + } + + @NonNull + protected List> getAuthorizationHeader() { + List> headerArgs = new ArrayList<>(); + if (!LeapSRPSession.getToken().isEmpty()) { + Pair authorizationHeaderPair = new Pair<>(LeapSRPSession.AUTHORIZATION_HEADER, "Token token=" + LeapSRPSession.getToken()); + headerArgs.add(authorizationHeaderPair); + } + return headerArgs; + } + + private boolean logOut() { + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(new JSONObject()); + if (okHttpClient == null) { + return false; + } + + String deleteUrl = providerApiUrl + "/logout"; + int progress = 0; + + /* Request.Builder requestBuilder = new Request.Builder() + .url(deleteUrl) + .delete(); + Request request = requestBuilder.build();*/ + + //try { + + //Response response = okHttpClient.newCall(request).execute(); +// Response response = ProviderApiConnector.delete(okHttpClient, deleteUrl); +// // v---- was already not authorized +// if (response.isSuccessful() || response.code() == 401) { +// broadcastProgress(progress++); +// LeapSRPSession.setToken(""); +// } +// +// } catch (IOException | RuntimeException e) { +// return false; +// } +// return true; + + if (ProviderApiConnector.delete(okHttpClient, deleteUrl)) { + broadcastProgress(progress++); + LeapSRPSession.setToken(""); + return true; + } + return false; + } + + //FIXME: don't save private keys in shared preferences! use the keystore + protected boolean loadCertificate(String cert_string) { + if (cert_string == null) { + return false; + } + + try { + // API returns concatenated cert & key. Split them for OpenVPN options + String certificateString = null, keyString = null; + String[] certAndKey = cert_string.split("(?<=-\n)"); + for (int i = 0; i < certAndKey.length - 1; i++) { + if (certAndKey[i].contains("KEY")) { + keyString = certAndKey[i++] + certAndKey[i]; + } else if (certAndKey[i].contains("CERTIFICATE")) { + certificateString = certAndKey[i++] + certAndKey[i]; + } + } + + RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); + keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); + preferences.edit().putString(Constants.PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); + + X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); + certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); + preferences.edit().putString(Constants.PROVIDER_VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); + return true; + } catch (CertificateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java index 61349490..bd9324bb 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java @@ -23,8 +23,6 @@ import android.view.*; import android.widget.*; import butterknife.*; -import se.leap.bitmaskclient.ProviderAPI; -import se.leap.bitmaskclient.VpnFragment; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.R; diff --git a/app/src/production/java/se/leap/bitmaskclient/ProviderAPI.java b/app/src/production/java/se/leap/bitmaskclient/ProviderAPI.java deleted file mode 100644 index 39651a43..00000000 --- a/app/src/production/java/se/leap/bitmaskclient/ProviderAPI.java +++ /dev/null @@ -1,327 +0,0 @@ - -/** - * Copyright (c) 2013 LEAP Encryption Access Project and contributers - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package se.leap.bitmaskclient; - -import android.os.Bundle; -import android.util.Pair; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.net.URL; -import java.util.List; - -import okhttp3.OkHttpClient; -import se.leap.bitmaskclient.eip.EIP; - -import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CORRUPTED_PROVIDER_JSON; -import static se.leap.bitmaskclient.R.string.malformed_url; - -/** - * Implements HTTP api methods used to manage communications with the provider server. - * It extends the abstract ProviderApiBase and implements the diverging method calls between the different flavors - * of ProviderAPI. - *

- * It extends an IntentService because it downloads data from the Internet, so it operates in the background. - * - * @author parmegv - * @author MeanderingCode - * @author cyberta - */ -public class ProviderAPI extends ProviderApiBase { - - /** - * Downloads a provider.json from a given URL, adding a new provider using the given name. - * - * @param task containing a boolean meaning if the provider is custom or not, another boolean meaning if the user completely trusts this provider, the provider name and its provider.json url. - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. - */ - @Override - protected Bundle setUpProvider(Bundle task) { - int progress = 0; - Bundle currentDownload = new Bundle(); - - if (task != null) { - //FIXME: this should be refactored in order to avoid static variables all over here - lastProviderMainUrl = task.containsKey(Provider.MAIN_URL) ? - task.getString(Provider.MAIN_URL) : - ""; - //TODO: remove that - providerCaCertFingerprint = task.containsKey(Provider.CA_CERT_FINGERPRINT) ? - task.getString(Provider.CA_CERT_FINGERPRINT) : - ""; - providerCaCert = task.containsKey(Provider.CA_CERT) ? - task.getString(Provider.CA_CERT) : - ""; - - try { - providerDefinition = task.containsKey(Provider.KEY) ? - new JSONObject(task.getString(Provider.KEY)) : - new JSONObject(); - } catch (JSONException e) { - e.printStackTrace(); - providerDefinition = new JSONObject(); - } - providerApiUrl = getApiUrlWithVersion(providerDefinition); - - checkPersistedProviderUpdates(); - currentDownload = validateProviderDetails(); - - //provider details invalid - if (currentDownload.containsKey(ERRORS)) { - return currentDownload; - } - - //no provider certificate available - if (currentDownload.containsKey(RESULT_KEY) && !currentDownload.getBoolean(RESULT_KEY)) { - resetProviderDetails(); - } - - EIP_SERVICE_JSON_DOWNLOADED = false; - go_ahead = true; - } - - if (!PROVIDER_JSON_DOWNLOADED) - currentDownload = getAndSetProviderJson(lastProviderMainUrl, providerCaCert, providerDefinition); - if (PROVIDER_JSON_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { - broadcastProgress(progress++); - PROVIDER_JSON_DOWNLOADED = true; - - if (!CA_CERT_DOWNLOADED) - currentDownload = downloadCACert(); - if (CA_CERT_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { - broadcastProgress(progress++); - CA_CERT_DOWNLOADED = true; - currentDownload = getAndSetEipServiceJson(); - if (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY)) { - broadcastProgress(progress++); - EIP_SERVICE_JSON_DOWNLOADED = true; - } - } - } - - return currentDownload; - } - - - private Bundle getAndSetProviderJson(String providerMainUrl, String caCert, JSONObject providerDefinition) { - Bundle result = new Bundle(); - - if (go_ahead) { - String providerDotJsonString; - if(providerDefinition.length() == 0 || caCert.isEmpty()) - providerDotJsonString = downloadWithCommercialCA(providerMainUrl + "/provider.json"); - else { - providerDotJsonString = downloadFromApiUrlWithProviderCA("/provider.json", caCert, providerDefinition); - } - - if (!isValidJson(providerDotJsonString)) { - result.putString(ERRORS, getString(malformed_url)); - result.putBoolean(RESULT_KEY, false); - return result; - } - - try { - JSONObject providerJson = new JSONObject(providerDotJsonString); - String providerDomain = providerJson.getString(Provider.DOMAIN); - providerApiUrl = getApiUrlWithVersion(providerJson); - String name = providerJson.getString(Provider.NAME); - //TODO setProviderName(name); - - preferences.edit().putString(Provider.KEY, providerJson.toString()). - putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). - putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). - putString(Provider.KEY + "." + providerDomain, providerJson.toString()).commit(); - result.putBoolean(RESULT_KEY, true); - } catch (JSONException e) { - String reason_to_fail = pickErrorMessage(providerDotJsonString); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - } - return result; - } - - /** - * Downloads the eip-service.json from a given URL, and saves eip service capabilities including the offered gateways - * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the download was successful. - */ - @Override - protected Bundle getAndSetEipServiceJson() { - Bundle result = new Bundle(); - String eip_service_json_string = ""; - if (go_ahead) { - try { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - String eip_service_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION) + "/" + EIP.SERVICE_API_PATH; - eip_service_json_string = downloadWithProviderCA(eip_service_url); - JSONObject eip_service_json = new JSONObject(eip_service_json_string); - eip_service_json.getInt(Provider.API_RETURN_SERIAL); - - preferences.edit().putString(Constants.PROVIDER_KEY, eip_service_json.toString()).commit(); - - result.putBoolean(RESULT_KEY, true); - } catch (NullPointerException | JSONException e) { - String reason_to_fail = pickErrorMessage(eip_service_json_string); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - } - return result; - } - - /** - * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. - * - * @return true if certificate was downloaded correctly, false if provider.json is not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. - */ - @Override - protected boolean updateVpnCertificate() { - try { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - - String provider_main_url = provider_json.getString(Provider.API_URL); - URL new_cert_string_url = new URL(provider_main_url + "/" + provider_json.getString(Provider.API_VERSION) + "/" + Constants.PROVIDER_VPN_CERTIFICATE); - - String cert_string = downloadWithProviderCA(new_cert_string_url.toString()); - - if (ConfigHelper.checkErroneousDownload(cert_string)) - return false; - else - return loadCertificate(cert_string); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - } - - private Bundle downloadCACert() { - Bundle result = new Bundle(); - try { - JSONObject providerJson = new JSONObject(preferences.getString(Provider.KEY, "")); - String caCertUrl = providerJson.getString(Provider.CA_CERT_URI); - String providerDomain = providerJson.getString(Provider.DOMAIN); - - String cert_string = downloadWithCommercialCA(caCertUrl); - - if (validCertificate(cert_string) && go_ahead) { - preferences.edit().putString(Provider.CA_CERT, cert_string).commit(); - preferences.edit().putString(Provider.CA_CERT + "." + providerDomain, cert_string).commit(); - result.putBoolean(RESULT_KEY, true); - } else { - String reason_to_fail = pickErrorMessage(cert_string); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - } catch (JSONException e) { - String reason_to_fail = formatErrorMessage(malformed_url); - result.putString(ERRORS, reason_to_fail); - result.putBoolean(RESULT_KEY, false); - } - - return result; - } - - /** - * Tries to download the contents of the provided url using commercially validated CA certificate from chosen provider. - * - * @param string_url - * @return - */ - protected String downloadWithCommercialCA(String string_url) { - String responseString; - JSONObject errorJson = new JSONObject(); - - OkHttpClient okHttpClient = initCommercialCAHttpClient(errorJson); - if (okHttpClient == null) { - return errorJson.toString(); - } - - List> headerArgs = getAuthorizationHeader(); - - responseString = sendGetStringToServer(string_url, headerArgs, okHttpClient); - - if (responseString != null && responseString.contains(ERRORS)) { - try { - // try to download with provider CA on certificate error - JSONObject responseErrorJson = new JSONObject(responseString); - if (responseErrorJson.getString(ERRORS).equals(getString(R.string.certificate_error))) { - responseString = downloadWithProviderCA(string_url); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - return responseString; - } - - - /** - * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider. - * - * @return an empty string if it fails, the response body if not. - */ - private String downloadFromApiUrlWithProviderCA(String path, String caCert, JSONObject providerDefinition) { - String responseString; - JSONObject errorJson = new JSONObject(); - String baseUrl = getApiUrl(providerDefinition); - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(errorJson, caCert); - if (okHttpClient == null) { - return errorJson.toString(); - } - - String urlString = baseUrl + path; - List> headerArgs = getAuthorizationHeader(); - responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); - - return responseString; - - } - - - - /** - * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider. - * - * @param urlString as a string - * @return an empty string if it fails, the url content if not. - */ - protected String downloadWithProviderCA(String urlString) { - JSONObject initError = new JSONObject(); - String responseString; - - OkHttpClient okHttpClient = initSelfSignedCAHttpClient(initError); - if (okHttpClient == null) { - return initError.toString(); - } - - List> headerArgs = getAuthorizationHeader(); - - responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); - - return responseString; - } - -} diff --git a/app/src/production/java/se/leap/bitmaskclient/ProviderApiManager.java b/app/src/production/java/se/leap/bitmaskclient/ProviderApiManager.java new file mode 100644 index 00000000..31c63d01 --- /dev/null +++ b/app/src/production/java/se/leap/bitmaskclient/ProviderApiManager.java @@ -0,0 +1,340 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient; + +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.os.Bundle; +import android.util.Pair; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.net.URL; +import java.util.List; + +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.eip.EIP; + +import static android.text.TextUtils.isEmpty; +import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CERTIFICATE_PINNING; +import static se.leap.bitmaskclient.ProviderAPI.ERRORS; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_KEY; +import static se.leap.bitmaskclient.R.string.malformed_url; + +/** + * Implements the logic of the provider api http requests. The methods of this class need to be called from + * a background thread. + */ + + +public class ProviderApiManager extends ProviderApiManagerBase { + + public ProviderApiManager(SharedPreferences preferences, Resources resources, OkHttpClientGenerator clientGenerator, ProviderApiServiceCallback callback) { + super(preferences, resources, clientGenerator, callback); + } + + /** + * Only used in insecure flavor. + */ + static boolean lastDangerOn() { + return false; + } + + /** + * Downloads a provider.json from a given URL, adding a new provider using the given name. + * + * @param task containing a boolean meaning if the provider is custom or not, another boolean meaning if the user completely trusts this provider, the provider name and its provider.json url. + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. + */ + @Override + protected Bundle setUpProvider(Bundle task) { + int progress = 0; + Bundle currentDownload = new Bundle(); + + if (task != null) { + //FIXME: this should be refactored in order to avoid static variables all over here + lastProviderMainUrl = task.containsKey(Provider.MAIN_URL) ? + task.getString(Provider.MAIN_URL) : + ""; + + if (isEmpty(lastProviderMainUrl)) { + currentDownload.putBoolean(RESULT_KEY, false); + setErrorResult(currentDownload, resources.getString(R.string.malformed_url), null); + return currentDownload; + } + + //TODO: remove that + providerCaCertFingerprint = task.containsKey(Provider.CA_CERT_FINGERPRINT) ? + task.getString(Provider.CA_CERT_FINGERPRINT) : + ""; + providerCaCert = task.containsKey(Provider.CA_CERT) ? + task.getString(Provider.CA_CERT) : + ""; + + try { + providerDefinition = task.containsKey(Provider.KEY) ? + new JSONObject(task.getString(Provider.KEY)) : + new JSONObject(); + } catch (JSONException e) { + e.printStackTrace(); + providerDefinition = new JSONObject(); + } + providerApiUrl = getApiUrlWithVersion(providerDefinition); + + checkPersistedProviderUpdates(); + currentDownload = validateProviderDetails(); + + //provider details invalid + if (currentDownload.containsKey(ERRORS)) { + return currentDownload; + } + + //no provider certificate available + if (currentDownload.containsKey(RESULT_KEY) && !currentDownload.getBoolean(RESULT_KEY)) { + resetProviderDetails(); + } + + EIP_SERVICE_JSON_DOWNLOADED = false; + go_ahead = true; + } + + if (!PROVIDER_JSON_DOWNLOADED) + currentDownload = getAndSetProviderJson(lastProviderMainUrl, providerCaCert, providerDefinition); + if (PROVIDER_JSON_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { + broadcastProgress(progress++); + PROVIDER_JSON_DOWNLOADED = true; + + if (!CA_CERT_DOWNLOADED) + currentDownload = downloadCACert(); + if (CA_CERT_DOWNLOADED || (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY))) { + broadcastProgress(progress++); + CA_CERT_DOWNLOADED = true; + currentDownload = getAndSetEipServiceJson(); + if (currentDownload.containsKey(RESULT_KEY) && currentDownload.getBoolean(RESULT_KEY)) { + broadcastProgress(progress++); + EIP_SERVICE_JSON_DOWNLOADED = true; + } + } + } + + return currentDownload; + } + + + private Bundle getAndSetProviderJson(String providerMainUrl, String caCert, JSONObject providerDefinition) { + Bundle result = new Bundle(); + + if (go_ahead) { + String providerDotJsonString; + if(providerDefinition.length() == 0 || caCert.isEmpty()) + providerDotJsonString = downloadWithCommercialCA(providerMainUrl + "/provider.json"); + else { + providerDotJsonString = downloadFromApiUrlWithProviderCA("/provider.json", caCert, providerDefinition); + } + + if (!isValidJson(providerDotJsonString)) { + result.putString(ERRORS, resources.getString(malformed_url)); + result.putBoolean(RESULT_KEY, false); + return result; + } + + try { + JSONObject providerJson = new JSONObject(providerDotJsonString); + String providerDomain = getDomainFromMainURL(lastProviderMainUrl); + providerApiUrl = getApiUrlWithVersion(providerJson); + //String name = providerJson.getString(Provider.NAME); + //TODO setProviderName(name); + + preferences.edit().putString(Provider.KEY, providerJson.toString()). + putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). + putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerJson.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). + putString(Provider.KEY + "." + providerDomain, providerJson.toString()).commit(); + result.putBoolean(RESULT_KEY, true); + } catch (JSONException e) { + String reason_to_fail = pickErrorMessage(providerDotJsonString); + result.putString(ERRORS, reason_to_fail); + result.putBoolean(RESULT_KEY, false); + } + } + return result; + } + + /** + * Downloads the eip-service.json from a given URL, and saves eip service capabilities including the offered gateways + * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the download was successful. + */ + @Override + protected Bundle getAndSetEipServiceJson() { + Bundle result = new Bundle(); + String eip_service_json_string = ""; + if (go_ahead) { + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + String eip_service_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION) + "/" + EIP.SERVICE_API_PATH; + eip_service_json_string = downloadWithProviderCA(eip_service_url); + JSONObject eip_service_json = new JSONObject(eip_service_json_string); + eip_service_json.getInt(Provider.API_RETURN_SERIAL); + + preferences.edit().putString(Constants.PROVIDER_KEY, eip_service_json.toString()).commit(); + + result.putBoolean(RESULT_KEY, true); + } catch (NullPointerException | JSONException e) { + String reason_to_fail = pickErrorMessage(eip_service_json_string); + result.putString(ERRORS, reason_to_fail); + result.putBoolean(RESULT_KEY, false); + } + } + return result; + } + + /** + * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. + * + * @return true if certificate was downloaded correctly, false if provider.json is not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. + */ + @Override + protected boolean updateVpnCertificate() { + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + + String provider_main_url = provider_json.getString(Provider.API_URL); + URL new_cert_string_url = new URL(provider_main_url + "/" + provider_json.getString(Provider.API_VERSION) + "/" + Constants.PROVIDER_VPN_CERTIFICATE); + + String cert_string = downloadWithProviderCA(new_cert_string_url.toString()); + + if (ConfigHelper.checkErroneousDownload(cert_string)) + return false; + else + return loadCertificate(cert_string); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + } + + private Bundle downloadCACert() { + Bundle result = new Bundle(); + try { + JSONObject providerJson = new JSONObject(preferences.getString(Provider.KEY, "")); + String caCertUrl = providerJson.getString(Provider.CA_CERT_URI); + String providerDomain = getDomainFromMainURL(lastProviderMainUrl); + String cert_string = downloadWithCommercialCA(caCertUrl); + + if (validCertificate(cert_string) && go_ahead) { + preferences.edit().putString(Provider.CA_CERT, cert_string).commit(); + preferences.edit().putString(Provider.CA_CERT + "." + providerDomain, cert_string).commit(); + result.putBoolean(RESULT_KEY, true); + } else { + setErrorResult(result, resources.getString(R.string.warning_corrupted_provider_cert), ERROR_CERTIFICATE_PINNING.toString()); + result.putBoolean(RESULT_KEY, false); + } + } catch (JSONException e) { + setErrorResult(result, resources.getString(malformed_url), null); + result.putBoolean(RESULT_KEY, false); + } + + return result; + } + + /** + * Tries to download the contents of the provided url using commercially validated CA certificate from chosen provider. + * + * @param string_url + * @return + */ + private String downloadWithCommercialCA(String string_url) { + String responseString; + JSONObject errorJson = new JSONObject(); + + OkHttpClient okHttpClient = clientGenerator.initCommercialCAHttpClient(errorJson); + if (okHttpClient == null) { + return errorJson.toString(); + } + + List> headerArgs = getAuthorizationHeader(); + + responseString = sendGetStringToServer(string_url, headerArgs, okHttpClient); + + if (responseString != null && responseString.contains(ERRORS)) { + try { + // try to download with provider CA on certificate error + JSONObject responseErrorJson = new JSONObject(responseString); + if (responseErrorJson.getString(ERRORS).equals(resources.getString(R.string.certificate_error))) { + responseString = downloadWithProviderCA(string_url); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + return responseString; + } + + + /** + * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider. + * + * @return an empty string if it fails, the response body if not. + */ + private String downloadFromApiUrlWithProviderCA(String path, String caCert, JSONObject providerDefinition) { + String responseString; + JSONObject errorJson = new JSONObject(); + String baseUrl = getApiUrl(providerDefinition); + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(errorJson, caCert); + if (okHttpClient == null) { + return errorJson.toString(); + } + + String urlString = baseUrl + path; + List> headerArgs = getAuthorizationHeader(); + responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); + + return responseString; + + } + + + /** + * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider. + * + * @param urlString as a string + * @return an empty string if it fails, the url content if not. + */ + private String downloadWithProviderCA(String urlString) { + JSONObject initError = new JSONObject(); + String responseString; + + OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(initError); + if (okHttpClient == null) { + return initError.toString(); + } + + List> headerArgs = getAuthorizationHeader(); + + responseString = sendGetStringToServer(urlString, headerArgs, okHttpClient); + + return responseString; + } +} diff --git a/app/src/test/java/se/leap/bitmaskclient/TestUtils.java b/app/src/test/java/se/leap/bitmaskclient/TestUtils.java deleted file mode 100644 index 96b11df6..00000000 --- a/app/src/test/java/se/leap/bitmaskclient/TestUtils.java +++ /dev/null @@ -1,26 +0,0 @@ -package se.leap.bitmaskclient; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -/** - * Created by cyberta on 08.10.17. - */ - -public class TestUtils { - - public static String getInputAsString(InputStream fileAsInputStream) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(fileAsInputStream)); - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - while (line != null) { - sb.append(line); - line = br.readLine(); - } - - return sb.toString(); - } - -} diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java index ea212480..4726cab7 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java @@ -16,7 +16,7 @@ import java.io.IOException; import se.leap.bitmaskclient.Constants; import se.leap.bitmaskclient.Provider; -import se.leap.bitmaskclient.TestUtils; +import se.leap.bitmaskclient.testutils.TestSetupHelper; import static junit.framework.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyInt; @@ -61,17 +61,17 @@ public class GatewaysManagerTest { @Test public void testFromEipServiceJson_ignoreDuplicateGateways() throws Exception { - String eipServiceJson = TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-two-gateways.json")); + String eipServiceJson = TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-two-gateways.json")); gatewaysManager.fromEipServiceJson(new JSONObject(eipServiceJson)); assertEquals(2, gatewaysManager.size()); - eipServiceJson = TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-one-gateway.json")); + eipServiceJson = TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-one-gateway.json")); gatewaysManager.fromEipServiceJson(new JSONObject(eipServiceJson)); assertEquals(2, gatewaysManager.size()); } @Test public void testClearGatewaysAndProfiles_resetGateways() throws Exception { - String eipServiceJson = TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-two-gateways.json")); + String eipServiceJson = TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-two-gateways.json")); gatewaysManager.fromEipServiceJson(new JSONObject(eipServiceJson)); assertEquals(2, gatewaysManager.size()); gatewaysManager.clearGatewaysAndProfiles(); @@ -79,7 +79,7 @@ public class GatewaysManagerTest { } private String getJsonStringFor(String filename) throws IOException { - return TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream(filename)); + return TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream(filename)); } } \ No newline at end of file diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java new file mode 100644 index 00000000..c39681c4 --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java @@ -0,0 +1,249 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient.eip; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.os.Bundle; +import android.text.TextUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Answers; +import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateEncodingException; + +import se.leap.bitmaskclient.ConfigHelper; +import se.leap.bitmaskclient.Provider; +import se.leap.bitmaskclient.ProviderAPI; +import se.leap.bitmaskclient.ProviderApiConnector; +import se.leap.bitmaskclient.ProviderApiManager; +import se.leap.bitmaskclient.ProviderApiManagerBase; +import se.leap.bitmaskclient.testutils.MockSharedPreferences; + +import static se.leap.bitmaskclient.ProviderAPI.ERRORS; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_NOK; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_OK; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_KEY; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockBundle; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockClientGenerator; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockFingerprintForCertificate; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockIntent; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockProviderApiConnector; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockResources; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockResultReceiver; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.mockTextUtils; +import static se.leap.bitmaskclient.testutils.answers.BackendAnswerFabric.TestBackendErrorCase.NO_ERROR; + +/** + * Created by cyberta on 04.01.18. + */ + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ProviderApiManager.class, TextUtils.class, ConfigHelper.class, ProviderApiConnector.class}) +public class ProviderApiManagerTest { + + private SharedPreferences mockPreferences; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Resources mockResources; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Context mockContext; + + private ProviderApiManager providerApiManager; + + class TestProviderApiServiceCallback implements ProviderApiManagerBase.ProviderApiServiceCallback { + + //Intent expectedIntent; + TestProviderApiServiceCallback(/*Intent expectedIntent*/) { + //this.expectedIntent = expectedIntent; + } + + @Override + public void broadcastProgress(Intent intent) { + //assertEquals("expected intent: ", expectedIntent, intent); + } + } + + @Before + public void setUp() throws Exception { + + Bundle bundle = mockBundle(); + PowerMockito.whenNew(Bundle.class).withAnyArguments().thenReturn(bundle); + Intent intent = mockIntent(); + PowerMockito.whenNew(Intent.class).withAnyArguments().thenReturn(intent); + mockTextUtils(); + mockPreferences = new MockSharedPreferences(); + mockResources = mockResources(getClass().getClassLoader().getResourceAsStream("error_messages.json")); + } + + + @Test + public void test_handleIntentSetupProvider_noProviderMainURL() { + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, false); + expectedResult.putString(ERRORS, "{\"errors\":\"It doesn't seem to be a Bitmask provider.\"}"); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, ""); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + @Test + public void test_handleIntentSetupProvider_happyPath_preseededProviderAndCA() throws IOException, CertificateEncodingException, NoSuchAlgorithmException { + mockFingerprintForCertificate(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + mockProviderApiConnector(NO_ERROR); + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, true); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, "https://riseup.net"); + parameters.putString(Provider.CA_CERT, getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"))); + parameters.putString(Provider.KEY, getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"))); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + @Test + public void test_handleIntentSetupProvider_happyPath_no_preseededProviderAndCA() throws IOException, CertificateEncodingException, NoSuchAlgorithmException { + mockFingerprintForCertificate("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + mockProviderApiConnector(NO_ERROR); + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, true); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, "https://riseup.net"); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + @Test + public void test_handleIntentSetupProvider_happyPath_storedProviderAndCAFromPreviousSetup() throws IOException, CertificateEncodingException, NoSuchAlgorithmException { + mockFingerprintForCertificate("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + mockProviderApiConnector(NO_ERROR); + mockPreferences.edit().putString(Provider.KEY + ".riseup.net", getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"))).apply(); + mockPreferences.edit().putString(Provider.CA_CERT + ".riseup.net", getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"))).apply(); + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, true); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, "https://riseup.net"); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + @Test + public void test_handleIntentSetupProvider_preseededProviderAndCA_failedCAPinning() throws IOException, CertificateEncodingException, NoSuchAlgorithmException { + mockFingerprintForCertificate(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); + mockProviderApiConnector(NO_ERROR); + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, false); + expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_CERTIFICATE_PINNING\",\"errors\":\"Stored provider certificate is corrupted. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, "https://riseup.net"); + parameters.putString(Provider.CA_CERT, getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"))); + parameters.putString(Provider.KEY, getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"))); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + @Test + public void test_handleIntentSetupProvider_no_preseededProviderAndCA_failedPinning() throws IOException, CertificateEncodingException, NoSuchAlgorithmException { + mockFingerprintForCertificate("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); + mockProviderApiConnector(NO_ERROR); + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, false); + expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_CERTIFICATE_PINNING\",\"errors\":\"Stored provider certificate is corrupted. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, "https://riseup.net"); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + @Test + public void test_handleIntentSetupProvider_storedProviderAndCAFromPreviousSetup_failedPinning() throws IOException, CertificateEncodingException, NoSuchAlgorithmException { + mockFingerprintForCertificate("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); + mockProviderApiConnector(NO_ERROR); + mockPreferences.edit().putString(Provider.KEY + ".riseup.net", getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"))).apply(); + mockPreferences.edit().putString(Provider.CA_CERT + ".riseup.net", getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"))).apply(); + providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + Bundle expectedResult = mockBundle(); + expectedResult.putBoolean(RESULT_KEY, false); + expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_CERTIFICATE_PINNING\",\"errors\":\"Stored provider certificate is corrupted. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); + + Intent provider_API_command = mockIntent(); + Bundle parameters = mockBundle(); + parameters.putString(Provider.MAIN_URL, "https://riseup.net"); + + provider_API_command.setAction(ProviderAPI.SET_UP_PROVIDER); + provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); + + providerApiManager.handleIntent(provider_API_command); + } + + +} diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java index 7e60edb9..8c8cdb61 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java @@ -4,7 +4,7 @@ import org.json.JSONObject; import org.junit.Before; import org.junit.Test; -import se.leap.bitmaskclient.TestUtils; +import se.leap.bitmaskclient.testutils.TestSetupHelper; import static junit.framework.Assert.assertTrue; @@ -217,13 +217,13 @@ public class VpnConfigGeneratorTest { @Before public void setUp() throws Exception { - generalConfig = new JSONObject(TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("general_configuration.json"))); - secrets = new JSONObject(TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("secrets.json"))); + generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("general_configuration.json"))); + secrets = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("secrets.json"))); } @Test public void testGenerate_tcp_udp() throws Exception { - gateway = new JSONObject(TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_tcp_udp.json"))); + gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_tcp_udp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway); String vpnConfig = vpnConfigGenerator.generate(); @@ -232,7 +232,7 @@ public class VpnConfigGeneratorTest { @Test public void testGenerate_udp_tcp() throws Exception { - gateway = new JSONObject(TestUtils.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_udp_tcp.json"))); + gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_udp_tcp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway); String vpnConfig = vpnConfigGenerator.generate(); diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java b/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java new file mode 100644 index 00000000..af35af31 --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java @@ -0,0 +1,165 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient.testutils; + +import android.content.SharedPreferences; +import android.support.annotation.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Created by cyberta on 09.01.18. + */ + +public class MockSharedPreferences implements SharedPreferences { + HashMap mockedStringPrefs = new HashMap<>(); + HashMap mockedIntPrefs = new HashMap<>(); + HashMap mockedBooleanPrefs = new HashMap<>(); + + @Override + public Map getAll() { + return null; + } + + @Nullable + @Override + public String getString(String key, @Nullable String defValue) { + String value = mockedStringPrefs.get(key); + return value != null ? value : defValue; + } + + @Nullable + @Override + public Set getStringSet(String key, @Nullable Set defValues) { + return null; + } + + @Override + public int getInt(String key, int defValue) { + Integer value = mockedIntPrefs.get(key); + return value != null ? value : defValue; + } + + @Override + public long getLong(String key, long defValue) { + return 0; + } + + @Override + public float getFloat(String key, float defValue) { + return 0; + } + + @Override + public boolean getBoolean(String key, boolean defValue) { + Boolean value = mockedBooleanPrefs.get(key); + return value != null ? value : defValue; + } + + @Override + public boolean contains(String key) { + return mockedStringPrefs.containsKey(key) || + mockedBooleanPrefs.containsKey(key) || + mockedIntPrefs.containsKey(key); + } + + @Override + public Editor edit() { + return new Editor() { + private HashMap tempStrings = new HashMap<>(mockedStringPrefs); + private HashMap tempIntegers = new HashMap<>(mockedIntPrefs); + private HashMap tempBoolean = new HashMap<>(mockedBooleanPrefs); + + @Override + public Editor putString(String key, @Nullable String value) { + tempStrings.put(key, value); + return this; + } + + @Override + public Editor putStringSet(String key, @Nullable Set values) { + return null; + } + + @Override + public Editor putInt(String key, int value) { + tempIntegers.put(key, value); + return this; + } + + @Override + public Editor putLong(String key, long value) { + return null; + } + + @Override + public Editor putFloat(String key, float value) { + return null; + } + + @Override + public Editor putBoolean(String key, boolean value) { + tempBoolean.put(key, value); + return this; + } + + @Override + public Editor remove(String key) { + tempBoolean.remove(key); + tempStrings.remove(key); + tempIntegers.remove(key); + return this; + } + + @Override + public Editor clear() { + tempBoolean.clear(); + tempStrings.clear(); + tempIntegers.clear(); + return this; + } + + @Override + public boolean commit() { + mockedStringPrefs = new HashMap<>(tempStrings); + mockedBooleanPrefs = new HashMap<>(tempBoolean); + mockedIntPrefs = new HashMap<>(tempIntegers); + return true; + } + + @Override + public void apply() { + mockedStringPrefs = new HashMap<>(tempStrings); + mockedBooleanPrefs = new HashMap<>(tempBoolean); + mockedIntPrefs = new HashMap<>(tempIntegers); + } + }; + } + + @Override + public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { + + } + + @Override + public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { + + } +} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/TestSetupHelper.java b/app/src/test/java/se/leap/bitmaskclient/testutils/TestSetupHelper.java new file mode 100644 index 00000000..19d7e13f --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/TestSetupHelper.java @@ -0,0 +1,443 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient.testutils; + +import android.content.Intent; +import android.content.res.Resources; +import android.os.Bundle; +import android.os.Parcelable; +import android.os.ResultReceiver; +import android.support.annotation.NonNull; +import android.text.TextUtils; +import android.util.Pair; + +import org.json.JSONException; +import org.json.JSONObject; +import org.mockito.ArgumentMatchers; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.ConfigHelper; +import se.leap.bitmaskclient.OkHttpClientGenerator; +import se.leap.bitmaskclient.ProviderApiConnector; +import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.testutils.answers.BackendAnswerFabric; +import se.leap.bitmaskclient.testutils.matchers.BundleMatcher; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static se.leap.bitmaskclient.testutils.answers.BackendAnswerFabric.TestBackendErrorCase.ERROR_NO_CONNECTION; +import static se.leap.bitmaskclient.testutils.answers.BackendAnswerFabric.getAnswerForErrorcase; + +/** + * Created by cyberta on 08.10.17. + */ + +public class TestSetupHelper { + + + + public static String getInputAsString(InputStream fileAsInputStream) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(fileAsInputStream)); + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + line = br.readLine(); + } + + return sb.toString(); + } + + @NonNull + public static Bundle mockBundle() { + final Map fakeBooleanBundle = new HashMap<>(); + final Map fakeStringBundle = new HashMap<>(); + final Map fakeIntBundle = new HashMap<>(); + final Map fakeParcelableBundle = new HashMap<>(); + + Bundle bundle = mock(Bundle.class); + + //mock String values in Bundle + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + String value = ((String) arguments[1]); + fakeStringBundle.put(key, value); + return null; + } + }).when(bundle).putString(anyString(), anyString()); + when(bundle.getString(anyString())).thenAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + return fakeStringBundle.get(key); + } + }); + + //mock Boolean values in Bundle + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + Boolean value = ((boolean) arguments[1]); + fakeBooleanBundle.put(key, value); + return null; + } + }).when(bundle).putBoolean(anyString(), anyBoolean()); + when(bundle.getBoolean(anyString())).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + return fakeBooleanBundle.get(key); + } + }); + + //mock Integer values in Bundle + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + Integer value = ((int) arguments[1]); + fakeIntBundle.put(key, value); + return null; + } + }).when(bundle).putInt(anyString(), anyInt()); + when(bundle.getInt(anyString())).thenAnswer(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + return fakeIntBundle.get(key); + } + }); + + //mock Parcelable values in Bundle + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + Parcelable value = ((Parcelable) arguments[1]); + fakeParcelableBundle.put(key, value); + return null; + } + }).when(bundle).putParcelable(anyString(), any(Parcelable.class)); + when(bundle.getParcelable(anyString())).thenAnswer(new Answer() { + @Override + public Parcelable answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + return fakeParcelableBundle.get(key); + } + }); + + //mock get + when(bundle.get(anyString())).thenAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + if (fakeBooleanBundle.containsKey(key)) { + return fakeBooleanBundle.get(key); + } else if (fakeIntBundle.containsKey(key)) { + return fakeIntBundle.get(key); + } else if (fakeStringBundle.containsKey(key)) { + return fakeStringBundle.get(key); + } else { + return fakeParcelableBundle.get(key); + } + } + }); + + //mock getKeySet + when(bundle.keySet()).thenAnswer(new Answer>() { + @Override + public Set answer(InvocationOnMock invocation) throws Throwable { + //this whole approach as a drawback: + //you should not add the same keys for values of different types + HashSet keys = new HashSet(); + keys.addAll(fakeBooleanBundle.keySet()); + keys.addAll(fakeIntBundle.keySet()); + keys.addAll(fakeStringBundle.keySet()); + keys.addAll(fakeParcelableBundle.keySet()); + return keys; + } + }); + + //mock containsKey + when(bundle.containsKey(anyString())).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + String key = (String) invocation.getArguments()[0]; + return fakeBooleanBundle.containsKey(key) || + fakeStringBundle.containsKey(key) || + fakeIntBundle.containsKey(key) || + fakeParcelableBundle.containsKey(key); + } + }); + + return bundle; + } + + public static Intent mockIntent() { + Intent intent = mock(Intent.class); + final String[] action = new String[1]; + final Map fakeExtras = new HashMap<>(); + final List categories = new ArrayList<>(); + + + //mock Action in intent + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + action[0] = ((String) arguments[0]); + return null; + } + }).when(intent).setAction(anyString()); + when(intent.getAction()).thenAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + return action[0]; + } + }); + + //mock Bundle in intent extras + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + Bundle value = ((Bundle) arguments[1]); + fakeExtras.put(key, value); + return null; + } + }).when(intent).putExtra(anyString(), any(Bundle.class)); + when(intent.getBundleExtra(anyString())).thenAnswer(new Answer() { + @Override + public Bundle answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + return (Bundle) fakeExtras.get(key); + } + }); + + //mock Parcelable in intent extras + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + Parcelable value = ((Parcelable) arguments[1]); + fakeExtras.put(key, value); + return null; + } + }).when(intent).putExtra(anyString(), any(Parcelable.class)); + when(intent.getParcelableExtra(anyString())).thenAnswer(new Answer() { + @Override + public Parcelable answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + String key = ((String) arguments[0]); + return (Parcelable) fakeExtras.get(key); + } + }); + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + categories.add(((String) arguments[0])); + return null; + } + }).when(intent).addCategory(anyString()); + + when(intent.getCategories()).thenAnswer(new Answer>() { + @Override + public Set answer(InvocationOnMock invocation) throws Throwable { + return new HashSet<>(categories); + } + }); + + return intent; + } + + public static void mockTextUtils() { + mockStatic(TextUtils.class); + + when(TextUtils.equals(any(CharSequence.class), any(CharSequence.class))).thenAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + CharSequence a = (CharSequence) invocation.getArguments()[0]; + CharSequence b = (CharSequence) invocation.getArguments()[1]; + if (a == b) return true; + int length; + if (a != null && b != null && (length = a.length()) == b.length()) { + if (a instanceof String && b instanceof String) { + return a.equals(b); + } else { + for (int i = 0; i < length; i++) { + if (a.charAt(i) != b.charAt(i)) return false; + } + return true; + } + } + return false; + } + }); + + when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + CharSequence param = (CharSequence) invocation.getArguments()[0]; + return param == null || param.length() == 0; + } + }); + } + + + public static ResultReceiver mockResultReceiver(final int expectedResultCode, final Bundle expectedBundle) { + ResultReceiver resultReceiver = mock(ResultReceiver.class); + + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] arguments = invocation.getArguments(); + int resultCode = (int) arguments[0]; + Bundle bundle = (Bundle) arguments[1]; + Set keys = expectedBundle.keySet(); + Iterator iterator = keys.iterator(); + HashMap expectedIntegers = new HashMap<>(); + HashMap expectedStrings = new HashMap<>(); + HashMap expectedBooleans = new HashMap<>(); + HashMap expectedParcelables = new HashMap<>(); + while (iterator.hasNext()) { + String key = iterator.next(); + Object value = expectedBundle.get(key); + + if (value instanceof Boolean) { + expectedBooleans.put(key, (Boolean) value); + } else if (value instanceof Integer) { + expectedIntegers.put(key, (Integer) value); + } else if (value instanceof String) { + expectedStrings.put(key, (String) value); + } else if (value instanceof Parcelable) { + expectedParcelables.put(key, (Parcelable) value); + } + } + assertThat("expected bundle: ", bundle, new BundleMatcher(expectedIntegers, expectedStrings, expectedBooleans, expectedParcelables)); + assertEquals("expected resultCode: ", expectedResultCode, resultCode); + return null; + } + }).when(resultReceiver).send(anyInt(), any(Bundle.class)); + return resultReceiver; + } + + public static void mockFingerprintForCertificate(String mockedFingerprint) throws CertificateEncodingException, NoSuchAlgorithmException { + mockStatic(ConfigHelper.class); + when(ConfigHelper.getFingerprintFromCertificate(any(X509Certificate.class), anyString())).thenReturn(mockedFingerprint); + when(ConfigHelper.checkErroneousDownload(anyString())).thenCallRealMethod(); + when(ConfigHelper.base64toHex(anyString())).thenCallRealMethod(); + when(ConfigHelper.parseX509CertificateFromString(anyString())).thenCallRealMethod(); + } + + public static void mockProviderApiConnector(final BackendAnswerFabric.TestBackendErrorCase errorCase) throws IOException { + mockStatic(ProviderApiConnector.class); + when(ProviderApiConnector.canConnect(any(OkHttpClient.class), anyString())).thenReturn(errorCase != ERROR_NO_CONNECTION); + when(ProviderApiConnector.requestStringFromServer(anyString(), anyString(), nullable(String.class), ArgumentMatchers.>anyList(), any(OkHttpClient.class))).thenAnswer(getAnswerForErrorcase(errorCase)); + } + + public static OkHttpClientGenerator mockClientGenerator() { + OkHttpClientGenerator mockClientGenerator = mock(OkHttpClientGenerator.class); + OkHttpClient mockedOkHttpClient = mock(OkHttpClient.class); + when(mockClientGenerator.initCommercialCAHttpClient(any(JSONObject.class))).thenReturn(mockedOkHttpClient); + when(mockClientGenerator.initSelfSignedCAHttpClient(any(JSONObject.class))).thenReturn(mockedOkHttpClient); + when(mockClientGenerator.initSelfSignedCAHttpClient(any(JSONObject.class), anyString())).thenReturn(mockedOkHttpClient); + return mockClientGenerator; + } + + public static Resources mockResources(InputStream inputStream) throws IOException, JSONException { + Resources mockedResources = mock(Resources.class, RETURNS_DEEP_STUBS); + JSONObject errorMessages = new JSONObject(getInputAsString(inputStream)); + + + when(mockedResources.getString(R.string.warning_corrupted_provider_details)). + thenReturn(errorMessages.getString("warning_corrupted_provider_details")); + when(mockedResources.getString(R.string.server_unreachable_message)). + thenReturn(errorMessages.getString("server_unreachable_message")); + when(mockedResources.getString(R.string.error_security_pinnedcertificate)). + thenReturn(errorMessages.getString("error.security.pinnedcertificate")); + when(mockedResources.getString(R.string.malformed_url)). + thenReturn(errorMessages.getString("malformed_url")); + when(mockedResources.getString(R.string.certificate_error)). + thenReturn(errorMessages.getString("certificate_error")); + when(mockedResources.getString(R.string.error_srp_math_error_user_message)). + thenReturn(errorMessages.getString("error_srp_math_error_user_message")); + when(mockedResources.getString(R.string.error_bad_user_password_user_message)). + thenReturn(errorMessages.getString("error_bad_user_password_user_message")); + when(mockedResources.getString(R.string.error_not_valid_password_user_message)). + thenReturn(errorMessages.getString("error_not_valid_password_user_message")); + when(mockedResources.getString(R.string.error_client_http_user_message)). + thenReturn(errorMessages.getString("error_client_http_user_message")); + when(mockedResources.getString(R.string.error_io_exception_user_message)). + thenReturn(errorMessages.getString("error_io_exception_user_message")); + when(mockedResources.getString(R.string.error_json_exception_user_message)). + thenReturn(errorMessages.getString("error_json_exception_user_message")); + when(mockedResources.getString(R.string.error_no_such_algorithm_exception_user_message)). + thenReturn(errorMessages.getString("error_no_such_algorithm_exception_user_message")); + when(mockedResources.getString(R.string.warning_corrupted_provider_details)). + thenReturn(errorMessages.getString("warning_corrupted_provider_details")); + when(mockedResources.getString(R.string.warning_corrupted_provider_cert)). + thenReturn(errorMessages.getString("warning_corrupted_provider_cert")); + when(mockedResources.getString(R.string.warning_expired_provider_cert)). + thenReturn(errorMessages.getString("warning_expired_provider_cert")); + return mockedResources; + } + +} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/answers/BackendAnswerFabric.java b/app/src/test/java/se/leap/bitmaskclient/testutils/answers/BackendAnswerFabric.java new file mode 100644 index 00000000..00e276f4 --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/answers/BackendAnswerFabric.java @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient.testutils.answers; + +import org.mockito.stubbing.Answer; + +/** + * Created by cyberta on 09.01.18. + */ + +public class BackendAnswerFabric { + /** + * This enum can be useful to provide different responses from a mocked ProviderApiConnector + * in order to test different error scenarios + */ + public enum TestBackendErrorCase { + NO_ERROR, + ERROR_NO_RESPONSE_BODY, // => NullPointerException + ERROR_DNS_RESOLUTION_ERROR, // => UnkownHostException + ERROR_SOCKET_TIMEOUT, // => SocketTimeoutException + ERROR_WRONG_PROTOCOL, // => MalformedURLException + ERROR_CERTIFICATE_INVALID, // => SSLHandshakeException + ERROR_WRONG_PORT, // => ConnectException + ERROR_PAYLOAD_MISSING, // => IllegalArgumentException + ERROR_TLS_1_2_NOT_SUPPORTED, // => UnknownServiceException + ERROR_UNKNOWN_IO_EXCEPTION, // => IOException + ERROR_NO_ACCESS, + ERROR_INVALID_SESSION_TOKEN, + ERROR_NO_CONNECTION, + ERROR_WRONG_SRP_CREDENTIALS + } + + public static Answer getAnswerForErrorcase(TestBackendErrorCase errorCase) { + switch (errorCase) { + case NO_ERROR: + return new NoErrorAnswer(); + case ERROR_NO_RESPONSE_BODY: + break; + case ERROR_DNS_RESOLUTION_ERROR: + break; + case ERROR_SOCKET_TIMEOUT: + break; + case ERROR_WRONG_PROTOCOL: + break; + case ERROR_CERTIFICATE_INVALID: + break; + case ERROR_WRONG_PORT: + break; + case ERROR_PAYLOAD_MISSING: + break; + case ERROR_TLS_1_2_NOT_SUPPORTED: + break; + case ERROR_UNKNOWN_IO_EXCEPTION: + break; + case ERROR_NO_ACCESS: + break; + case ERROR_INVALID_SESSION_TOKEN: + break; + case ERROR_NO_CONNECTION: + break; + case ERROR_WRONG_SRP_CREDENTIALS: + break; + } + return null; + } + +} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/answers/NoErrorAnswer.java b/app/src/test/java/se/leap/bitmaskclient/testutils/answers/NoErrorAnswer.java new file mode 100644 index 00000000..cbf9f6b8 --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/answers/NoErrorAnswer.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package se.leap.bitmaskclient.testutils.answers; + +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +/** + * Created by cyberta on 09.01.18. + */ + +public class NoErrorAnswer implements Answer { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + String url = (String) invocation.getArguments()[0]; + String requestMethod = (String) invocation.getArguments()[1]; + String jsonPayload = (String) invocation.getArguments()[2]; + + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); + } else if (url.contains("/users.json")) { + //create new user + //TODO: implement me + } else if (url.contains("/sessions.json")) { + //srp auth: sendAToSRPServer + //TODO: implement me + } else if (url.contains("/sessions/parmegvtest10.json")){ + //srp auth: sendM1ToSRPServer + //TODO: implement me + } + + return null; + } +} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/matchers/BundleMatcher.java b/app/src/test/java/se/leap/bitmaskclient/testutils/matchers/BundleMatcher.java new file mode 100644 index 00000000..a7867e08 --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/matchers/BundleMatcher.java @@ -0,0 +1,192 @@ +package se.leap.bitmaskclient.testutils.matchers; + +import android.os.Bundle; +import android.os.Parcelable; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + +/** + * Created by cyberta on 09.01.18. + */ + +public class BundleMatcher extends BaseMatcher { + + private final HashMap expectedIntegers; + private final HashMap expectedStrings; + private final HashMap expectedBooleans; + private final HashMap expectedParcelables; + private HashMap unfoundExpectedInteger = new HashMap<>(); + private HashMap unfoundExpectedBoolean = new HashMap<>(); + private HashMap unfoundExpectedString = new HashMap<>(); + private HashMap unfoundExpectedParcelable = new HashMap<>(); + private HashMap unexpectedAdditionalObjects = new HashMap<>(); + + public BundleMatcher(HashMap expectedIntegers, HashMap expectedStrings, HashMap expectedBooleans, HashMap expectedParcelables) { + this.expectedBooleans = expectedBooleans; + this.expectedIntegers = expectedIntegers; + this.expectedStrings = expectedStrings; + this.expectedParcelables = expectedParcelables; + } + + @Override + public boolean matches(Object item) { + if (item instanceof Bundle) { + Bundle actualBundle = (Bundle) item; + return checkActualBundleHasAllExpectedBooleanValues(actualBundle) && + checkActualBundleHasAllExpectedStringValues(actualBundle) && + checkActualBundleHasAllExpectedIntValues(actualBundle) && + checkActualBundleHasAllExpectedParcelableValues(actualBundle) && + checkUnexpectedAdditionalValuesIn(actualBundle); + } + return false; + } + + @Override + public void describeTo(Description description) { + description.appendText("Bundle didn't match expectation!"); + + if (!unfoundExpectedInteger.isEmpty()) { + Iterator iterator = unfoundExpectedInteger.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + if (unfoundExpectedInteger.get(key) == null) { + description.appendText("\n unfound Integer in actual Bundle: ").appendValue(iterator.next()); + } else { + description.appendText("\n expected Integer for key " + key).appendValue(expectedIntegers.get(key)). + appendText("\n found Integer was: ").appendValue(unfoundExpectedInteger.get(key)); + } + } + } + if (!unfoundExpectedBoolean.isEmpty()) { + Iterator iterator = unfoundExpectedBoolean.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + if (unfoundExpectedBoolean.get(key) == null) { + description.appendText("\n unfound Boolean in actual Bundle: ").appendValue(iterator.next()); + } else { + description.appendText("\n expected Boolean for key " + key).appendValue(expectedBooleans.get(key)). + appendText("\n found Boolean was: ").appendValue(unfoundExpectedBoolean.get(key)); + } + } + } + if (!unfoundExpectedString.isEmpty()) { + Iterator iterator = unfoundExpectedString.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + if (unfoundExpectedString.get(key) == null) { + description.appendText("\n unfound String in actual Bundle: ").appendValue(iterator.next()); + } else { + description.appendText("\n expected String for key " + key).appendValue(expectedStrings.get(key)). + appendText("\n found String was: ").appendValue(unfoundExpectedString.get(key)); + } + } + } + if (!unfoundExpectedParcelable.isEmpty()) { + Iterator iterator = unfoundExpectedInteger.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + if (unfoundExpectedParcelable.get(key) == null) { + description.appendText("\n unfound Parcelable in actual Bundle: ").appendValue(iterator.next()); + } else { + description.appendText("\n expected Parcelable or key " + key).appendValue(expectedParcelables.get(key)). + appendText("\n found Parcelable was: ").appendValue(unfoundExpectedParcelable.get(key)); + } + } + } + + if (!unexpectedAdditionalObjects.isEmpty()) { + Iterator iterator = unexpectedAdditionalObjects.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + Object value = unexpectedAdditionalObjects.get(key); + if (value instanceof String) { + description.appendText("\n unexpected String found in actual Bundle: ").appendValue(key).appendText(", ").appendValue(value); + } else if (value instanceof Boolean) { + description.appendText("\n unexpected Boolean found in actual Bundle: ").appendValue(key).appendText(", ").appendValue(value); + } else if (value instanceof Integer) { + description.appendText("\n unexpected Integer found in actual Bundle: ").appendValue(key).appendText(", ").appendValue(value); + } else if (value instanceof Parcelable) { + description.appendText("\n unexpected Parcelable found in actual Bundle: ").appendValue(key).appendText(", ").appendValue(value); + } else { + description.appendText("\n unexpected Object found in actual Bundle: ").appendValue(key).appendText(", ").appendValue(value); + } + } + } + } + + private boolean checkActualBundleHasAllExpectedBooleanValues(Bundle actualBundle) { + Set booleanKeys = expectedBooleans.keySet(); + for (String key : booleanKeys) { + Object valueObject = actualBundle.get(key); + if (valueObject == null || + !(valueObject instanceof Boolean) || + valueObject != expectedBooleans.get(key)) { + unfoundExpectedBoolean.put(key, (Boolean) valueObject); + return false; + } + } + return true; + } + + private boolean checkActualBundleHasAllExpectedStringValues(Bundle actualBundle) { + Set stringKeys = expectedStrings.keySet(); + for (String key : stringKeys) { + Object valueObject = actualBundle.get(key); + if (valueObject == null || + !(valueObject instanceof String) || + !valueObject.equals(expectedStrings.get(key))) { + unfoundExpectedString.put(key, (String) valueObject); + return false; + } + } + return true; + } + + private boolean checkActualBundleHasAllExpectedIntValues(Bundle actualBundle) { + Set stringKeys = expectedIntegers.keySet(); + for (String key : stringKeys) { + Object valueObject = actualBundle.get(key); + if (valueObject == null || + !(valueObject instanceof Integer) || + ((Integer) valueObject).compareTo(expectedIntegers.get(key)) != 0) { + unfoundExpectedInteger.put(key, (Integer) valueObject); + return false; + } + } + return true; + } + + private boolean checkActualBundleHasAllExpectedParcelableValues(Bundle actualBundle) { + Set stringKeys = expectedParcelables.keySet(); + for (String key : stringKeys) { + Object valueObject = actualBundle.get(key); + if (valueObject == null || + !(valueObject instanceof Parcelable) || + !valueObject.equals(expectedParcelables.get(key))) { + unfoundExpectedParcelable.put(key, (Parcelable) valueObject); + return false; + } + } + return true; + } + + private boolean checkUnexpectedAdditionalValuesIn(Bundle actualBundle) { + Set keys = actualBundle.keySet(); + + for (String key : keys) { + if (!expectedStrings.containsKey(key) && + !expectedIntegers.containsKey(key) && + !expectedBooleans.containsKey(key) && + !expectedParcelables.containsKey(key) + ) { + unexpectedAdditionalObjects.put(key, actualBundle.getString(key)); + } + } + return unexpectedAdditionalObjects.isEmpty(); + } +} diff --git a/app/src/test/resources/error_messages.json b/app/src/test/resources/error_messages.json new file mode 100644 index 00000000..486a3dab --- /dev/null +++ b/app/src/test/resources/error_messages.json @@ -0,0 +1,16 @@ +{ + "server_unreachable_message": "Server is unreachable, please try again.", +"error.security.pinnedcertificate": "Security error, update the app or choose another provider.", +"malformed_url": "It doesn't seem to be a Bitmask provider.", +"certificate_error": "This is not a trusted Bitmask provider.", +"error_srp_math_error_user_message": "Try again: server math error.", +"error_bad_user_password_user_message": "Incorrect username or password.", +"error_not_valid_password_user_message": "It should have at least 8 characters.", +"error_client_http_user_message": "Try again: Client HTTP error", +"error_io_exception_user_message": "Try again: I/O error", +"error_json_exception_user_message": "Try again: Bad response from the server", +"error_no_such_algorithm_exception_user_message": "Encryption algorithm not found. Please update your OS!", +"warning_corrupted_provider_details": "Stored provider details are corrupted. You can either update Bitmask (recommended) or update the provider details using a commercial CA certificate.", +"warning_corrupted_provider_cert": "Stored provider certificate is corrupted. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.", +"warning_expired_provider_cert": "Stored provider certificate is expired. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate." +} \ No newline at end of file diff --git a/app/src/test/resources/riseup.net.json b/app/src/test/resources/riseup.net.json new file mode 100644 index 00000000..9a5ec79e --- /dev/null +++ b/app/src/test/resources/riseup.net.json @@ -0,0 +1,37 @@ +{ + "api_uri": "https://api.black.riseup.net:443", + "api_version": "1", + "ca_cert_fingerprint": "SHA256: a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494", + "ca_cert_uri": "https://black.riseup.net/ca.crt", + "default_language": "en", + "description": { + "en": "Riseup is a non-profit collective in Seattle that provides online communication tools for people and groups working toward liberatory social change." + }, + "domain": "riseup.net", + "enrollment_policy": "open", + "languages": [ + "en" + ], + "name": { + "en": "Riseup Networks" + }, + "service": { + "allow_anonymous": false, + "allow_free": true, + "allow_limited_bandwidth": false, + "allow_paid": false, + "allow_registration": true, + "allow_unlimited_bandwidth": true, + "bandwidth_limit": 102400, + "default_service_level": 1, + "levels": { + "1": { + "description": "Please donate.", + "name": "free" + } + } + }, + "services": [ + "openvpn" + ] +} \ No newline at end of file diff --git a/app/src/test/resources/riseup.net.pem b/app/src/test/resources/riseup.net.pem new file mode 100644 index 00000000..c890aff4 --- /dev/null +++ b/app/src/test/resources/riseup.net.pem @@ -0,0 +1,32 @@ +-----BEGIN CERTIFICATE----- +MIIFjTCCA3WgAwIBAgIBATANBgkqhkiG9w0BAQ0FADBZMRgwFgYDVQQKDA9SaXNl +dXAgTmV0d29ya3MxGzAZBgNVBAsMEmh0dHBzOi8vcmlzZXVwLm5ldDEgMB4GA1UE +AwwXUmlzZXVwIE5ldHdvcmtzIFJvb3QgQ0EwHhcNMTQwNDI4MDAwMDAwWhcNMjQw +NDI4MDAwMDAwWjBZMRgwFgYDVQQKDA9S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S8jx1j/6/Luk6PpFbT7QYm4QLs1f4BlfZOti2KE8r7KRDPIecUsUXW6P/ +3GJAVYH/+7OjA39za9AieM7+H5BELGccGrM5wfl7JeEz8in+V2ZWDzHQO4hMkiTQ +4ZckuaL201F68YpiItBNnJ9N5nHr1MRiGyApHmLXY/wvlrOpclh95qn+lG6/2jk7 +3AmihLOKYMlPwPakJg4PYczm3icFLgTpjV5sq2md9bRyAg3oPGfAuWHmKj2Ikqch +Td5CHKGxEEWbGUWEMP0s1A/JHWiCbDigc4Cfxhy56CWG4q0tYtnc2GMw8OAUO6Wf +Xu5pYKNkzKSEtT/MrNJt44tTZWbKV/Pi/N2Fx36my7TgTUj7g3xcE9eF4JV2H/sg +tsK3pwE0FEqGnT4qMFbixQmc8bGyuakr23wjMvfO7eZUxBuWYR2SkcP26sozF9PF +tGhbZHQVGZUTVPyvwahMUEhbPGVerOW0IYpxkm0x/eaWdTc4vPpf/rIlgbAjarnJ +UN9SaWRlWKSdP4haujnzCoJbM7dU9bjvlGZNyXEekgeT0W2qFeGGp+yyUWw8tNsp +0BuC1b7uW/bBn/xKm319wXVDvBgZgcktMolak39V7DVO +-----END CERTIFICATE----- \ No newline at end of file diff --git a/app/src/test/resources/riseup.service.json b/app/src/test/resources/riseup.service.json new file mode 100644 index 00000000..05f23bc1 --- /dev/null +++ b/app/src/test/resources/riseup.service.json @@ -0,0 +1,93 @@ +{ + "gateways":[ + { + "capabilities":{ + "adblock":false, + "filter_dns":false, + "limited":false, + "ports":[ + "443" + ], + "protocols":[ + "tcp" + ], + "transport":[ + "openvpn" + ], + "user_ips":false + }, + "host":"garza.riseup.net", + "ip_address":"198.252.153.28", + "location":"seattle" + }, + { + "capabilities":{ + "adblock":false, + "filter_dns":false, + "limited":false, + "ports":[ + "443" + ], + "protocols":[ + "tcp" + ], + "transport":[ + "openvpn" + ], + "user_ips":false + }, + "host":"tenca.riseup.net", + "ip_address":"5.79.86.180", + "location":"amsterdam" + }, + { + "capabilities":{ + "adblock":false, + "filter_dns":false, + "limited":false, + "ports":[ + "443" + ], + "protocols":[ + "tcp" + ], + "transport":[ + "openvpn" + ], + "user_ips":false + }, + "host":"yal.riseup.net", + "ip_address":"199.58.81.145", + "location":"montreal" + } + ], + "locations":{ + "amsterdam":{ + "country_code":"NL", + "hemisphere":"N", + "name":"Amsterdam", + "timezone":"+2" + }, + "montreal":{ + "country_code":"CA", + "hemisphere":"N", + "name":"Montreal", + "timezone":"-5" + }, + "seattle":{ + "country_code":"US", + "hemisphere":"N", + "name":"Seattle", + "timezone":"-7" + } + }, + "openvpn_configuration":{ + "auth":"SHA1", + "cipher":"AES-128-CBC", + "keepalive":"10 30", + "tls-cipher":"DHE-RSA-AES128-SHA", + "tun-ipv6":true + }, + "serial":1, + "version":1 +} \ No newline at end of file diff --git a/app/src/test/resources/secrets.json b/app/src/test/resources/secrets.json index 36ba5977..f3b68919 100644 --- a/app/src/test/resources/secrets.json +++ b/app/src/test/resources/secrets.json @@ -1 +1 @@ -{"ca_cert":"-----BEGIN CERTIFICATE-----\nMIIFbzCCA1egAwIBAgIBATANBgkqhkiG9w0BAQ0FADBKMRgwFgYDVQQDDA9CaXRt\nYXNrIFJvb3QgQ0ExEDAOBgNVBAoMB0JpdG1hc2sxHDAaBgNVBAsME2h0dHBzOi8v\nYml0bWFzay5uZXQwHhcNMTIxMTA2MDAwMDAwWhcNMjIxMTA2MDAwMDAwWjBKMRgw\nFgYDVQQDDA9CaXRtYXNrIFJvb3QgQ0ExEDAOBgNVBAoMB0JpdG1hc2sxHDAaBgNV\nBAsME2h0dHBzOi8vYml0bWFzay5uZXQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw\nggIKAoICAQC1eV4YvayaU+maJbWrD4OHo3d7S1BtDlcvkIRS1Fw3iYDjsyDkZxai\ndHp4EUasfNQ+EVtXUvtk6170EmLco6Elg8SJBQ27trE6nielPRPCfX3fQzETRfvB\n7tNvGw4Jn2YKiYoMD79kkjgyZjkJ2r\/bEHUSevmR09BR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