diff options
Diffstat (limited to 'app/src/debug/java/se/leap/bitmaskclient/ProviderAPI.java')
-rw-r--r-- | app/src/debug/java/se/leap/bitmaskclient/ProviderAPI.java | 483 |
1 files changed, 239 insertions, 244 deletions
diff --git a/app/src/debug/java/se/leap/bitmaskclient/ProviderAPI.java b/app/src/debug/java/se/leap/bitmaskclient/ProviderAPI.java index e729d0bc..52645631 100644 --- a/app/src/debug/java/se/leap/bitmaskclient/ProviderAPI.java +++ b/app/src/debug/java/se/leap/bitmaskclient/ProviderAPI.java @@ -14,12 +14,12 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - package se.leap.bitmaskclient; +package se.leap.bitmaskclient; import android.app.IntentService; import android.content.Intent; +import android.content.SharedPreferences; import android.os.Bundle; -import android.os.Handler; import android.os.ResultReceiver; import android.util.Base64; import android.util.Log; @@ -43,6 +43,7 @@ import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; +import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateEncodingException; @@ -65,7 +66,6 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.http.client.ClientProtocolException; -import org.jboss.security.srp.SRPParameters; import org.json.JSONException; import org.json.JSONObject; import se.leap.bitmaskclient.ProviderListContent.ProviderItem; @@ -83,8 +83,6 @@ import se.leap.bitmaskclient.R; */ public class ProviderAPI extends IntentService { - private Handler mHandler; - final public static String SET_UP_PROVIDER = "setUpProvider", DOWNLOAD_NEW_PROVIDER_DOTJSON = "downloadNewProviderDotJSON", @@ -95,12 +93,10 @@ public class ProviderAPI extends IntentService { PARAMETERS = "parameters", RESULT_KEY = "result", RECEIVER_KEY = "receiver", - SESSION_ID_COOKIE_KEY = "session_id_cookie_key", - SESSION_ID_KEY = "session_id", ERRORS = "errors", UPDATE_PROGRESSBAR = "update_progressbar", CURRENT_PROGRESS = "current_progress", - TAG = "provider_api_tag" + TAG = ProviderAPI.class.getSimpleName(); ; final public static int @@ -128,6 +124,8 @@ public class ProviderAPI extends IntentService { private static String last_provider_main_url; private static boolean last_danger_on = false; private static boolean setting_up_provider = true; + private static SharedPreferences preferences; + private static String provider_api_url; public static void stop() { setting_up_provider = false; @@ -138,12 +136,13 @@ public class ProviderAPI extends IntentService { Log.v("ClassName", "Provider API"); } - @Override - public void onCreate() { - super.onCreate(); - mHandler = new Handler(); - CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER) ); - } + @Override + public void onCreate() { + super.onCreate(); + + preferences = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE); + CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER) ); + } public static String lastProviderMainUrl() { return last_provider_main_url; @@ -162,7 +161,15 @@ public class ProviderAPI extends IntentService { final ResultReceiver receiver = command.getParcelableExtra(RECEIVER_KEY); String action = command.getAction(); Bundle parameters = command.getBundleExtra(PARAMETERS); - setting_up_provider = true; + if(provider_api_url == null) { + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "no provider")); + provider_api_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION); + } catch (JSONException e) { + } + } + + setting_up_provider = true; if(action.equalsIgnoreCase(SET_UP_PROVIDER)) { Bundle result = setUpProvider(parameters); @@ -174,21 +181,21 @@ public class ProviderAPI extends IntentService { } } } else if (action.equalsIgnoreCase(SRP_REGISTER)) { - Bundle session_id_bundle = registerWithSRP(parameters); + Bundle session_id_bundle = tryToRegister(parameters); if(session_id_bundle.getBoolean(RESULT_KEY)) { receiver.send(SRP_REGISTRATION_SUCCESSFUL, session_id_bundle); } else { receiver.send(SRP_REGISTRATION_FAILED, session_id_bundle); } } else if (action.equalsIgnoreCase(SRP_AUTH)) { - Bundle session_id_bundle = authenticateBySRP(parameters); + Bundle session_id_bundle = tryToAuthenticate(parameters); if(session_id_bundle.getBoolean(RESULT_KEY)) { receiver.send(SRP_AUTHENTICATION_SUCCESSFUL, session_id_bundle); } else { receiver.send(SRP_AUTHENTICATION_FAILED, session_id_bundle); } } else if (action.equalsIgnoreCase(LOG_OUT)) { - if(logOut(parameters)) { + if(logOut()) { receiver.send(LOGOUT_SUCCESSFUL, Bundle.EMPTY); } else { receiver.send(LOGOUT_FAILED, Bundle.EMPTY); @@ -202,108 +209,113 @@ public class ProviderAPI extends IntentService { } } - private Bundle registerWithSRP(Bundle task) { + private Bundle tryToRegister(Bundle task) { Bundle session_id_bundle = new Bundle(); int progress = 0; - String username = (String) task.get(LogInDialog.USERNAME); - String password = (String) task.get(LogInDialog.PASSWORD); - String authentication_server = (String) task.get(Provider.API_URL); + String username = (String) task.get(SessionDialogInterface.USERNAME); + String password = (String) task.get(SessionDialogInterface.PASSWORD); + if(validUserLoginData(username, password)) { - - SRPParameters params = new SRPParameters(new BigInteger(ConfigHelper.NG_1024, 16).toByteArray(), ConfigHelper.G.toByteArray(), BigInteger.ZERO.toByteArray(), "SHA-256"); - LeapSRPSession client = new LeapSRPSession(username, password, params); - byte[] salt = ConfigHelper.trim(client.calculateNewSalt()); - // byte[] salted_password = client.calculatePasswordHash(username, password, salt); - /* Calculate password verifier */ - BigInteger password_verifier = client.calculateV(username, password, salt); - /* Send to the server */ - JSONObject result = sendNewUserDataToSRPServer(authentication_server, username, new BigInteger(1, salt).toString(16), password_verifier.toString(16)); - if(result.has(ERRORS)) - session_id_bundle = authFailedNotification(result, username); - else { - session_id_bundle.putString(LogInDialog.USERNAME, username); - session_id_bundle.putString(LogInDialog.PASSWORD, password); - session_id_bundle.putBoolean(RESULT_KEY, true); - } - Log.d(TAG, result.toString()); + session_id_bundle = register(username, password); broadcast_progress(progress++); } else { if(!wellFormedPassword(password)) { session_id_bundle.putBoolean(RESULT_KEY, false); - session_id_bundle.putString(LogInDialog.USERNAME, username); - session_id_bundle.putBoolean(LogInDialog.PASSWORD_INVALID_LENGTH, true); + session_id_bundle.putString(SessionDialogInterface.USERNAME, username); + session_id_bundle.putBoolean(SessionDialogInterface.PASSWORD_INVALID_LENGTH, true); } if(username.isEmpty()) { session_id_bundle.putBoolean(RESULT_KEY, false); - session_id_bundle.putBoolean(LogInDialog.USERNAME_MISSING, true); + session_id_bundle.putBoolean(SessionDialogInterface.USERNAME_MISSING, true); } } return session_id_bundle; } + + private Bundle register(String username, String password) { + LeapSRPSession client = new LeapSRPSession(username, password); + byte[] salt = client.calculateNewSalt(); + + BigInteger password_verifier = client.calculateV(username, password, salt); + + JSONObject api_result = sendNewUserDataToSRPServer(provider_api_url, username, new BigInteger(1, salt).toString(16), password_verifier.toString(16)); + + Bundle result = new Bundle(); + if(api_result.has(ERRORS)) + result = authFailedNotification(api_result, username); + else { + result.putString(SessionDialogInterface.USERNAME, username); + result.putString(SessionDialogInterface.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 authenticateBySRP(Bundle task) { - Bundle session_id_bundle = new Bundle(); + private Bundle tryToAuthenticate(Bundle task) { + Bundle result = new Bundle(); int progress = 0; - String username = (String) task.get(LogInDialog.USERNAME); - String password = (String) task.get(LogInDialog.PASSWORD); - if(validUserLoginData(username, password)) { - - String authentication_server = (String) task.get(Provider.API_URL); - JSONObject authentication_step_result = new JSONObject(); - - SRPParameters params = new SRPParameters(new BigInteger(ConfigHelper.NG_1024, 16).toByteArray(), ConfigHelper.G.toByteArray(), BigInteger.ZERO.toByteArray(), "SHA-256"); - LeapSRPSession client = new LeapSRPSession(username, password, params); - byte[] A = client.exponential(); - broadcast_progress(progress++); - authentication_step_result = sendAToSRPServer(authentication_server, username, new BigInteger(1, A).toString(16)); - try { - String salt = authentication_step_result.getString(LeapSRPSession.SALT); - broadcast_progress(progress++); - byte[] Bbytes = new BigInteger(authentication_step_result.getString("B"), 16).toByteArray(); - byte[] M1 = client.response(new BigInteger(salt, 16).toByteArray(), Bbytes); - if(M1 != null) { - broadcast_progress(progress++); - authentication_step_result = sendM1ToSRPServer(authentication_server, username, M1); - setTokenIfAvailable(authentication_step_result); - byte[] M2 = new BigInteger(authentication_step_result.getString(LeapSRPSession.M2), 16).toByteArray(); - if(client.verify(M2)) { - session_id_bundle.putBoolean(RESULT_KEY, true); - broadcast_progress(progress++); - } else { - authFailedNotification(authentication_step_result, username); - } - } else { - session_id_bundle.putBoolean(RESULT_KEY, false); - session_id_bundle.putString(LogInDialog.USERNAME, username); - session_id_bundle.putString(getResources().getString(R.string.user_message), getResources().getString(R.string.error_srp_math_error_user_message)); - } - } catch (JSONException e) { - session_id_bundle = authFailedNotification(authentication_step_result, username); - e.printStackTrace(); - } + String username = (String) task.get(SessionDialogInterface.USERNAME); + String password = (String) task.get(SessionDialogInterface.PASSWORD); + if(validUserLoginData(username, password)) { + result = authenticate(username, password); broadcast_progress(progress++); } else { if(!wellFormedPassword(password)) { - session_id_bundle.putBoolean(RESULT_KEY, false); - session_id_bundle.putString(LogInDialog.USERNAME, username); - session_id_bundle.putBoolean(LogInDialog.PASSWORD_INVALID_LENGTH, true); + result.putBoolean(RESULT_KEY, false); + result.putString(SessionDialogInterface.USERNAME, username); + result.putBoolean(SessionDialogInterface.PASSWORD_INVALID_LENGTH, true); } if(username.isEmpty()) { - session_id_bundle.putBoolean(RESULT_KEY, false); - session_id_bundle.putBoolean(LogInDialog.USERNAME_MISSING, true); + result.putBoolean(RESULT_KEY, false); + result.putBoolean(SessionDialogInterface.USERNAME_MISSING, true); } } - return session_id_bundle; + return result; + } + + + private Bundle authenticate(String username, String password) { + Bundle result = new Bundle(); + + LeapSRPSession client = new LeapSRPSession(username, password); + byte[] A = client.exponential(); + + JSONObject step_result = sendAToSRPServer(provider_api_url, username, new BigInteger(1, A).toString(16)); + 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(provider_api_url, username, M1); + 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(SessionDialogInterface.USERNAME, username); + result.putString(getResources().getString(R.string.user_message), getResources().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 { @@ -325,7 +337,7 @@ public class ProviderAPI extends IntentService { } catch(JSONException e) {} if(!username.isEmpty()) - user_notification_bundle.putString(LogInDialog.USERNAME, username); + user_notification_bundle.putString(SessionDialogInterface.USERNAME, username); user_notification_bundle.putBoolean(RESULT_KEY, false); return user_notification_bundle; @@ -369,13 +381,6 @@ public class ProviderAPI extends IntentService { * @param username * @param clientA First SRP parameter sent * @return response from authentication server - * @throws ClientProtocolException - * @throws IOException - * @throws JSONException - * @throws CertificateException - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * @throws KeyManagementException */ private JSONObject sendAToSRPServer(String server_url, String username, String clientA) { Map<String, String> parameters = new HashMap<String, String>(); @@ -390,13 +395,6 @@ public class ProviderAPI extends IntentService { * @param username * @param m1 Second SRP parameter sent * @return response from authentication server - * @throws ClientProtocolException - * @throws IOException - * @throws JSONException - * @throws CertificateException - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * @throws KeyManagementException */ private JSONObject sendM1ToSRPServer(String server_url, String username, byte[] m1) { Map<String, String> parameters = new HashMap<String, String>(); @@ -412,13 +410,6 @@ public class ProviderAPI extends IntentService { * @param salted_password * @param password_verifier * @return response from authentication server - * @throws ClientProtocolException - * @throws IOException - * @throws JSONException - * @throws CertificateException - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * @throws KeyManagementException */ private JSONObject sendNewUserDataToSRPServer(String server_url, String username, String salt, String password_verifier) { Map<String, String> parameters = new HashMap<String, String>(); @@ -563,12 +554,12 @@ public class ProviderAPI extends IntentService { private Bundle downloadCACert(boolean danger_on) { Bundle result = new Bundle(); try { - JSONObject provider_json = new JSONObject(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.KEY, "")); + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); String ca_cert_url = provider_json.getString(Provider.CA_CERT_URI); String cert_string = downloadWithCommercialCA(ca_cert_url, danger_on); if(validCertificate(cert_string) && setting_up_provider) { - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(Provider.CA_CERT, cert_string).commit(); + preferences.edit().putString(Provider.CA_CERT, cert_string).commit(); result.putBoolean(RESULT_KEY, true); } else { String reason_to_fail = pickErrorMessage(cert_string); @@ -584,26 +575,47 @@ public class ProviderAPI extends IntentService { return result; } - public static boolean caCertDownloaded() { return CA_CERT_DOWNLOADED; } - private boolean validCertificate(String cert_string) { - boolean result = false; - if(!ConfigHelper.checkErroneousDownload(cert_string)) { - X509Certificate certCert = ConfigHelper.parseX509CertificateFromString(cert_string); - try { - Base64.encodeToString( certCert.getEncoded(), Base64.DEFAULT); - result = true; - } catch (CertificateEncodingException e) { - Log.d(TAG, e.getLocalizedMessage()); - } - } + private boolean validCertificate(String cert_string) { + boolean result = false; + if(!ConfigHelper.checkErroneousDownload(cert_string)) { + X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string); + try { + 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()); + } catch (JSONException e) { + result = false; + } catch (NoSuchAlgorithmException e) { + result = false; + } catch (CertificateEncodingException e) { + result = false; + } + } - return result; + return result; + } + + private String base64toHex(String base64_input) { + byte[] byteArray = Base64.decode(base64_input, Base64.DEFAULT); + int readBytes = byteArray.length; + StringBuffer hexData = new StringBuffer(); + int onebyte; + for (int i=0; i < readBytes; i++) { + onebyte = ((0x000000ff & byteArray[i]) | 0xffffff00); + hexData.append(Integer.toHexString(onebyte).substring(6)); } - + return hexData.toString(); + } private Bundle getAndSetProviderJson(String provider_main_url, boolean danger_on) { Bundle result = new Bundle(); @@ -612,12 +624,13 @@ public class ProviderAPI extends IntentService { try { JSONObject provider_json = new JSONObject(provider_dot_json_string); + provider_api_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION); String name = provider_json.getString(Provider.NAME); //TODO setProviderName(name); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(Provider.KEY, provider_json.toString()).commit(); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(EIP.ALLOWED_ANON, provider_json.getJSONObject(Provider.SERVICE).getBoolean(EIP.ALLOWED_ANON)).commit(); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(EIP.ALLOWED_REGISTERED, provider_json.getJSONObject(Provider.SERVICE).getBoolean(EIP.ALLOWED_REGISTERED)).commit(); + preferences.edit().putString(Provider.KEY, provider_json.toString()).commit(); + preferences.edit().putBoolean(EIP.ALLOWED_ANON, provider_json.getJSONObject(Provider.SERVICE).getBoolean(EIP.ALLOWED_ANON)).commit(); + preferences.edit().putBoolean(EIP.ALLOWED_REGISTERED, provider_json.getJSONObject(Provider.SERVICE).getBoolean(EIP.ALLOWED_REGISTERED)).commit(); result.putBoolean(RESULT_KEY, true); } catch (JSONException e) { @@ -630,24 +643,18 @@ public class ProviderAPI extends IntentService { return result; } - - - public static boolean providerJsonDownloaded() { - return PROVIDER_JSON_DOWNLOADED; - } - private Bundle getAndSetEipServiceJson() { Bundle result = new Bundle(); String eip_service_json_string = ""; if(setting_up_provider) { try { - JSONObject provider_json = new JSONObject(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.KEY, "")); + 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, true); JSONObject eip_service_json = new JSONObject(eip_service_json_string); eip_service_json.getInt(Provider.API_RETURN_SERIAL); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.KEY, eip_service_json.toString()).commit(); + preferences.edit().putString(EIP.KEY, eip_service_json.toString()).commit(); result.putBoolean(RESULT_KEY, true); } catch (JSONException e) { @@ -658,10 +665,6 @@ public class ProviderAPI extends IntentService { } return result; } - - public static boolean eipServiceDownloaded() { - return EIP_SERVICE_JSON_DOWNLOADED; - } /** * Interprets the error message as a JSON object and extract the "errors" keyword pair. @@ -748,6 +751,7 @@ public class ProviderAPI extends IntentService { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { + e.printStackTrace(); json_file_content = formatErrorMessage(R.string.server_unreachable_message); } catch (IOException e) { // The downloaded certificate doesn't validate our https connection. @@ -766,13 +770,14 @@ public class ProviderAPI extends IntentService { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchElementException e) { + e.printStackTrace(); json_file_content = formatErrorMessage(R.string.server_unreachable_message); } return json_file_content; } private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { - String provider_cert_string = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.CA_CERT,""); + String provider_cert_string = preferences.getString(Provider.CA_CERT,""); java.security.cert.Certificate provider_certificate = ConfigHelper.parseX509CertificateFromString(provider_cert_string); @@ -853,125 +858,115 @@ public class ProviderAPI extends IntentService { * @param task containing api url from which the user will log out * @return true if there were no exceptions */ - private boolean logOut(Bundle task) { - try { - String delete_url = task.getString(Provider.API_URL) + "/logout"; - int progress = 0; + private boolean logOut() { + try { + String delete_url = provider_api_url + "/logout"; + int progress = 0; - HttpsURLConnection urlConnection = (HttpsURLConnection)new URL(delete_url).openConnection(); - urlConnection.setRequestMethod("DELETE"); - urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory()); + HttpsURLConnection urlConnection = (HttpsURLConnection)new URL(delete_url).openConnection(); + urlConnection.setRequestMethod("DELETE"); + urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory()); - int responseCode = urlConnection.getResponseCode(); - broadcast_progress(progress++); - LeapSRPSession.setToken(""); - Log.d(TAG, Integer.toString(responseCode)); - } catch (ClientProtocolException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (IndexOutOfBoundsException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (KeyManagementException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyStoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (CertificateException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return true; + int responseCode = urlConnection.getResponseCode(); + broadcast_progress(progress++); + LeapSRPSession.setToken(""); + Log.d(TAG, Integer.toString(responseCode)); + } catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (IndexOutOfBoundsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (KeyManagementException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (KeyStoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (CertificateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + return true; + } private boolean updateVpnCertificate() { getNewCert(); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putInt(EIP.PARSED_SERIAL, 0).commit(); Intent updateEIP = new Intent(getApplicationContext(), EIP.class); updateEIP.setAction(EIP.ACTION_UPDATE_EIP_SERVICE); startService(updateEIP); return true; } - /** - * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. - * - * @return true if certificate was downloaded correctly, false if provider.json or danger_on flag are not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. - */ - private boolean getNewCert() { - - try { - JSONObject provider_json = new JSONObject(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.KEY, "")); + + /** + * Downloads a new OpenVPN certificate, attaching authenticated cookie for authenticated certificate. + * + * @return true if certificate was downloaded correctly, false if provider.json or danger_on flag are not present in SharedPreferences, or if the certificate url could not be parsed as a URI, or if there was an SSL error. + */ + private boolean getNewCert() { + 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) + "/" + EIP.CERTIFICATE); + 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) + "/" + EIP.CERTIFICATE); - boolean danger_on = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getBoolean(ProviderItem.DANGER_ON, false); + boolean danger_on = preferences.getBoolean(ProviderItem.DANGER_ON, false); - String cert_string = downloadWithProviderCA(new_cert_string_url.toString(), danger_on); - if(!cert_string.isEmpty()) { - if(ConfigHelper.checkErroneousDownload(cert_string)) { - String reason_to_fail = provider_json.getString(ERRORS); - //result.putString(ConfigHelper.ERRORS_KEY, reason_to_fail); - //result.putBoolean(ConfigHelper.RESULT_KEY, false); - return false; - } else { - - // 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]; - } - } - try { - RSAPrivateKey keyCert = ConfigHelper.parseRsaKeyFromString(keyString); - keyString = Base64.encodeToString( keyCert.getEncoded(), Base64.DEFAULT ); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n"+keyString+"-----END RSA PRIVATE KEY-----").commit(); - - X509Certificate certCert = ConfigHelper.parseX509CertificateFromString(certificateString); - certificateString = Base64.encodeToString( certCert.getEncoded(), Base64.DEFAULT); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.CERTIFICATE, "-----BEGIN CERTIFICATE-----\n"+certificateString+"-----END CERTIFICATE-----").commit(); - getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.DATE_FROM_CERTIFICATE, EIP.certificate_date_format.format(Calendar.getInstance().getTime())).commit(); - - return true; - } catch (CertificateException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - } - } else { - return false; - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } /*catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - }*/ + String cert_string = downloadWithProviderCA(new_cert_string_url.toString(), danger_on); + + if(cert_string.isEmpty() || ConfigHelper.checkErroneousDownload(cert_string)) + return false; + else + return loadCertificate(cert_string); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (MalformedURLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + } + + private boolean loadCertificate(String cert_string) { + 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 keyCert = ConfigHelper.parseRsaKeyFromString(keyString); + keyString = Base64.encodeToString( keyCert.getEncoded(), Base64.DEFAULT ); + preferences.edit().putString(EIP.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n"+keyString+"-----END RSA PRIVATE KEY-----").commit(); + + X509Certificate certCert = ConfigHelper.parseX509CertificateFromString(certificateString); + certificateString = Base64.encodeToString( certCert.getEncoded(), Base64.DEFAULT); + preferences.edit().putString(EIP.CERTIFICATE, "-----BEGIN CERTIFICATE-----\n"+certificateString+"-----END CERTIFICATE-----").commit(); + preferences.edit().putString(EIP.DATE_FROM_CERTIFICATE, EIP.certificate_date_format.format(Calendar.getInstance().getTime())).commit(); + return true; + } catch (CertificateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; } + } } |