diff options
author | Parménides GV <parmegv@sdf.org> | 2013-05-13 20:39:34 +0200 |
---|---|---|
committer | Parménides GV <parmegv@sdf.org> | 2013-05-13 20:39:34 +0200 |
commit | 80a8106afc8956008beb9d1ed9396f1d695d5b7b (patch) | |
tree | b0ba5869a5d739949bc4178b399536dd4857c5c4 | |
parent | 84a11bb1620d2b9080992427c847b58007f2304a (diff) |
A bit more clean.
I've upper cased ConfigHelper constants.
I've created a new method in ConfigHelper, to send requests to a server,
that it's used when sending A and M1.
-rw-r--r-- | src/se/leap/leapclient/ConfigHelper.java | 185 | ||||
-rw-r--r-- | src/se/leap/leapclient/ConfigurationWizard.java | 210 | ||||
-rw-r--r-- | src/se/leap/leapclient/Dashboard.java | 40 | ||||
-rw-r--r-- | src/se/leap/leapclient/LeapHttpClient.java | 96 | ||||
-rw-r--r-- | src/se/leap/leapclient/LeapSRPSession.java | 39 | ||||
-rw-r--r-- | src/se/leap/leapclient/LogInDialog.java | 67 | ||||
-rw-r--r-- | src/se/leap/leapclient/NewProviderDialog.java | 7 | ||||
-rw-r--r-- | src/se/leap/leapclient/Provider.java | 2 | ||||
-rw-r--r-- | src/se/leap/leapclient/ProviderAPI.java | 289 | ||||
-rw-r--r-- | src/se/leap/leapclient/ProviderListContent.java | 2 |
10 files changed, 391 insertions, 546 deletions
diff --git a/src/se/leap/leapclient/ConfigHelper.java b/src/se/leap/leapclient/ConfigHelper.java index 0dab26f4..5d44f004 100644 --- a/src/se/leap/leapclient/ConfigHelper.java +++ b/src/se/leap/leapclient/ConfigHelper.java @@ -1,6 +1,5 @@ package se.leap.leapclient; - import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; @@ -28,103 +27,94 @@ public class ConfigHelper { public static SharedPreferences shared_preferences; private static KeyStore keystore_trusted; - final static String downloadJsonFilesBundleExtra = "downloadJSONFiles"; - final static String updateProviderDotJSON = "updateProviderDotJSON"; - final static String downloadNewProviderDotJSON = "downloadNewProviderDotJSON"; - final public static String logInDialog = "logInDialog"; - final public static String newProviderDialog = "logInDialog"; - final public static String srpRegister = "srpRegister"; - final public static String srpAuth = "srpAuth"; - public static String logIn = "logIn"; - public static String logOut = "logOut"; - public static String downloadUserAuthedCertificate = "downloadUserAuthedCertificate"; - public static String api_version_key = "api_version"; - final public static String resultKey = "result"; - final static String provider_key = "provider"; - final static String service_key = "service"; - final static String main_cert_key = "main_cert"; - final static String cert_key = "cert"; - final static String eip_service_key = "eip"; - final static String session_id_cookie_key = "session_id_cookie_key"; - final static String session_id_key = "session_id"; - public static final String PREFERENCES_KEY = "LEAPPreferences"; - public static final String user_directory = "leap_android"; - final public static String provider_name = "provider_name"; - final public static String provider_main_url = "provider_main_url"; - final public static String provider_json_url = "provider_json_url"; - final public static String custom = "custom"; - final public static String danger_on = "danger_on"; - final public static String api_url_key = "api_uri"; - final public static String username_key = "username"; - final public static String password_key = "password"; - final public static String allow_registration_key = "allow_registration"; - final public static String eip_service_api_path = "config/eip-service.json"; + final public static String + DOWNLOAD_JSON_FILES_BUNDLE_EXTRA = "downloadJSONFiles", + UPDATE_PROVIDER_DOTJSON = "updateProviderDotJSON", + DOWNLOAD_NEW_PROVIDER_DOTJSON = "downloadNewProviderDotJSON", + LOG_IN_DIALOG = "logInDialog", + NEW_PROVIDER_DIALOG = "logInDialog", + SRP_REGISTER = "srpRegister", + SRP_AUTH = "srpAuth", + LOG_IN = "logIn", + LOG_OUT = "logOut", + DOWNLOAD_USER_AUTHED_CERTIFICATE = "downloadUserAuthedCertificate", + API_VERSION_KEY = "api_version", + RESULT_KEY = "result", + PROVIDER_KEY = "provider", + SERVICE_KEY = "service", + MAIN_CERT_KEY = "main_cert", + CERT_KEY = "cert", + EIP_SERVICE_KEY = "eip", + SALT_KEY = "salt", + SESSION_ID_COOKIE_KEY = "session_id_cookie_key", + SESSION_ID_KEY = "session_id", + PREFERENCES_KEY = "LEAPPreferences", + USER_DIRECTORY = "leap_android", + PROVIDER_NAME = "provider_name", + PROVIDER_MAIN_URL = "provider_main_url", + PROVIDER_JSON_URL = "provider_json_url", + CUSTOM = "custom", + DANGER_ON = "danger_on", + API_URL_KEY = "api_uri", + USERNAME_KEY = "username", + PASSWORD_KEY = "password", + ALLOW_REGISTRATION_KEY = "allow_registration", + EIP_SERVICE_API_PATH = "config/eip-service.json" + ; - final public static String NG_1024 = - "eeaf0ab9adb38dd69c33f80afa8fc5e86072618775ff3c0b9ea2314c9c256576d674df7496ea81d3383b4813d692c6e0e0d5d8e250b98be48e495c1d6089dad15dc7d7b46154d6b6ce8ef4ad69b15d4982559b297bcf1885c529f566660e57ec68edbc3c05726cc02fd4cbf4976eaa9afd5138fe8376435b9fc61d2fc0eb06e3"; - final public static BigInteger g = BigInteger.valueOf(2); + final public static String NG_1024 = + "eeaf0ab9adb38dd69c33f80afa8fc5e86072618775ff3c0b9ea2314c9c256576d674df7496ea81d3383b4813d692c6e0e0d5d8e250b98be48e495c1d6089dad15dc7d7b46154d6b6ce8ef4ad69b15d4982559b297bcf1885c529f566660e57ec68edbc3c05726cc02fd4cbf4976eaa9afd5138fe8376435b9fc61d2fc0eb06e3"; + final public static BigInteger G = new BigInteger("2"); + + final public static int + CUSTOM_PROVIDER_ADDED = 0, + CORRECTLY_DOWNLOADED_JSON_FILES = 1, + INCORRECTLY_DOWNLOADED_JSON_FILES = 2, + SRP_AUTHENTICATION_SUCCESSFUL = 3, + SRP_AUTHENTICATION_FAILED = 4, + SRP_REGISTRATION_SUCCESSFUL = 5, + SRP_REGISTRATION_FAILED = 6, + LOGOUT_SUCCESSFUL = 7, + LOGOUT_FAILED = 8, + CORRECTLY_DOWNLOADED_AUTHED_USER_CERTIFICATE = 9, + INCORRECTLY_DOWNLOADED_AUTHED_USER_CERTIFICATE = 10, + CORRECTLY_UPDATED_PROVIDER_DOT_JSON = 11, + INCORRECTLY_UPDATED_PROVIDER_DOT_JSON = 12 + ; - final public static int CUSTOM_PROVIDER_ADDED = 0; - final public static int CORRECTLY_DOWNLOADED_JSON_FILES = 1; - final public static int INCORRECTLY_DOWNLOADED_JSON_FILES = 2; - final public static int SRP_AUTHENTICATION_SUCCESSFUL = 3; - final public static int SRP_AUTHENTICATION_FAILED = 4; - final public static int SRP_REGISTRATION_SUCCESSFUL = 5; - final public static int SRP_REGISTRATION_FAILED = 6; - final public static int LOGOUT_SUCCESSFUL = 7; - final public static int LOGOUT_FAILED = 8; - final public static int CORRECTLY_DOWNLOADED_AUTHED_USER_CERTIFICATE = 9; - final public static int INCORRECTLY_DOWNLOADED_AUTHED_USER_CERTIFICATE = 10; - final public static int CORRECTLY_UPDATED_PROVIDER_DOT_JSON = 11; - final public static int INCORRECTLY_UPDATED_PROVIDER_DOT_JSON = 12; + public static void saveSharedPref(String shared_preferences_key, JSONObject content) { + + SharedPreferences.Editor shared_preferences_editor = shared_preferences + .edit(); + shared_preferences_editor.putString(shared_preferences_key, + content.toString()); + shared_preferences_editor.commit(); + } - static String getStringFromSharedPref(String shared_preferences_key) { + public static String getStringFromSharedPref(String shared_preferences_key) { String value = ""; - //TODO This is not OK -> when reading provider.json it only shows "open" if(shared_preferences != null) { String content = shared_preferences.getString(shared_preferences_key, ""); try { JSONObject json_object = new JSONObject(content); value = json_object.toString(); - /*JSONArray names = json_object.names(); - String key = names.getString(0); - value = json_object.getString(key);*/ } catch (JSONException e) { value = content; } } return value; } - - static void saveSharedPref(String shared_preferences_key, JSONObject content) { - - SharedPreferences.Editor shared_preferences_editor = shared_preferences - .edit(); - shared_preferences_editor.putString(shared_preferences_key, - content.toString()); - shared_preferences_editor.commit(); - System.out.println("Shared preferences updated: key = " - + shared_preferences_key - + " Content = " - + shared_preferences.getString( - shared_preferences_key, "Default")); - } - static void rescueJSONException(JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - static void saveFile(String filename, String content) { + public static void saveFile(String filename, String content) { File root = Environment.getExternalStorageDirectory(); - File leap_dir = new File(root.getAbsolutePath() + File.separator + user_directory); + File leap_dir = new File(root.getAbsolutePath() + File.separator + USER_DIRECTORY); if (!leap_dir.isDirectory()) { leap_dir.mkdir(); } try { if (!leap_dir.isDirectory()) { throw new IOException( - "Unable to create directory " + user_directory + ". Maybe the SD card is mounted?"); + "Unable to create directory " + USER_DIRECTORY + ". Maybe the SD card is mounted?"); } File outputFile = new File(leap_dir, filename); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); @@ -135,10 +125,10 @@ public class ConfigHelper { } } - static FileInputStream openFileInputStream(String filename) { + public static FileInputStream openFileInputStream(String filename) { FileInputStream input_stream = null; File root = Environment.getExternalStorageDirectory(); - File leap_dir = new File(root.getAbsolutePath() + File.separator + user_directory); + File leap_dir = new File(root.getAbsolutePath() + File.separator + USER_DIRECTORY); try { input_stream = new FileInputStream(leap_dir + File.separator + filename); } catch (FileNotFoundException e) { @@ -178,7 +168,8 @@ public class ConfigHelper { X509Certificate cert = (X509Certificate)cf.generateCertificate(openFileInputStream(filename_to_save)); if(keystore_trusted == null) { - getNewKeystore(null); + keystore_trusted = KeyStore.getInstance("BKS"); + keystore_trusted.load(null); } keystore_trusted.setCertificateEntry(provider, cert); } catch (CertificateException e) { @@ -187,50 +178,16 @@ public class ConfigHelper { } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); - } - } - - public static KeyStore getKeystore() { - return keystore_trusted; - } - - public static void getNewKeystore(InputStream leap_keystore) { - try { - keystore_trusted = KeyStore.getInstance("BKS"); - try { - // Initialize the keystore with the provided trusted certificates - // Also provide the password of the keystore - if(leap_keystore != null) { - //keystore_trusted.load(leap_keystore, "uer92jf".toCharArray()); - keystore_trusted.load(null, null); - } else { - keystore_trusted.load(null, null); - } - } finally { - if(leap_keystore != null) - leap_keystore.close(); - } - } 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(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } - - public static int getSrpAuthenticationFailed() { - return SRP_AUTHENTICATION_FAILED; - } - static String extractProviderName(String provider_main_url) { - - return null; + public static KeyStore getKeystore() { + return keystore_trusted; } } diff --git a/src/se/leap/leapclient/ConfigurationWizard.java b/src/se/leap/leapclient/ConfigurationWizard.java index ba17f9bb..78ac0462 100644 --- a/src/se/leap/leapclient/ConfigurationWizard.java +++ b/src/se/leap/leapclient/ConfigurationWizard.java @@ -1,9 +1,6 @@ package se.leap.leapclient;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
import java.util.Iterator;
import java.util.Scanner;
@@ -12,6 +9,9 @@ import org.json.JSONObject; import se.leap.leapclient.ProviderAPIResultReceiver.Receiver;
import se.leap.leapclient.ProviderListContent.ProviderItem;
+import se.leap.leapclient.R;
+import se.leap.leapclient.R.id;
+import se.leap.leapclient.R.layout;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
@@ -24,23 +24,6 @@ import android.os.Handler; import android.view.View;
import android.widget.Toast;
-
-/**
- * An activity representing a list of Providers. This activity
- * has different presentations for handset and tablet-size devices. On
- * handsets, the activity presents a list of items, which when touched,
- * lead to a {@link DashboardActivity} representing
- * item details. On tablets, the activity presents the list of items and
- * item details side-by-side using two vertical panes.
- * <p>
- * The activity makes heavy use of fragments. The list of items is a
- * {@link ProviderListFragment} and the item details
- * (if present) is a {@link DashboardFragment}.
- * <p>
- * This activity also implements the required
- * {@link ProviderListFragment.Callbacks} interface
- * to listen for item selections.
- */
public class ConfigurationWizard extends Activity
implements ProviderListFragment.Callbacks, NewProviderDialog.NewProviderDialogInterface, Receiver {
@@ -63,11 +46,6 @@ public class ConfigurationWizard extends Activity loadPreseededProviders();
- if(ConfigHelper.getKeystore() == null) {
- InputStream keystore_input_stream = getResources().openRawResource(R.raw.leapkeystore);
- ConfigHelper.getNewKeystore(keystore_input_stream);
- }
-
// Only create our fragments if we're not restoring a saved instance
if ( savedInstanceState == null ){
// TODO Some welcome screen?
@@ -83,7 +61,67 @@ public class ConfigurationWizard extends Activity // TODO: If exposing deep links into your app, handle intents here.
}
- private void loadPreseededProviders() {
+ @Override
+ public void onReceiveResult(int resultCode, Bundle resultData) {
+ if(resultCode == ConfigHelper.CUSTOM_PROVIDER_ADDED){
+ ProviderListFragment providerList = new ProviderListFragment();
+
+ FragmentManager fragmentManager = getFragmentManager();
+ fragmentManager.beginTransaction()
+ .replace(R.id.configuration_wizard_layout, providerList, "providerlist")
+ .commit();
+ }
+ else if(resultCode == ConfigHelper.CORRECTLY_DOWNLOADED_JSON_FILES) {
+ setResult(RESULT_OK);
+ finish();
+ }
+ else if(resultCode == ConfigHelper.INCORRECTLY_DOWNLOADED_JSON_FILES) {
+ setResult(RESULT_CANCELED);
+ Toast.makeText(getApplicationContext(), "You have not entered a LEAP provider URL or it is unavailable", Toast.LENGTH_LONG).show();
+ }
+ else if(resultCode == ConfigHelper.CORRECTLY_UPDATED_PROVIDER_DOT_JSON) {
+ JSONObject provider_json;
+ try {
+ provider_json = new JSONObject(resultData.getString(ConfigHelper.PROVIDER_KEY));
+ boolean danger_on = resultData.getBoolean(ConfigHelper.DANGER_ON);
+ ConfigHelper.saveSharedPref(ConfigHelper.PROVIDER_KEY, provider_json);
+ ConfigHelper.saveSharedPref(ConfigHelper.DANGER_ON, new JSONObject().put(ConfigHelper.DANGER_ON, danger_on));
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ else if(resultCode == ConfigHelper.INCORRECTLY_UPDATED_PROVIDER_DOT_JSON) {
+ Toast.makeText(getApplicationContext(), "Install a new version of this app.", Toast.LENGTH_LONG).show();
+ }
+ }
+
+ /**
+ * Callback method from {@link ProviderListFragment.Callbacks}
+ * indicating that the item with the given ID was selected.
+ */
+ @Override
+ public void onItemSelected(String id) {
+ //TODO Code 2 pane view
+ Iterator<ProviderItem> preseeded_providers_iterator = ProviderListContent.ITEMS.iterator();
+ while(preseeded_providers_iterator.hasNext())
+ {
+ ProviderItem current_provider_item = preseeded_providers_iterator.next();
+ if(current_provider_item.id.equalsIgnoreCase(id))
+ {
+ try {
+ saveProviderJson(current_provider_item);
+ downloadJSONFiles(current_provider_item);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ private boolean loadPreseededProviders() {
+ boolean loaded_preseeded_providers = false;
AssetManager asset_manager = getAssets();
String[] urls_filepaths = null;
try {
@@ -97,65 +135,33 @@ public class ConfigurationWizard extends Activity provider_name = url_filepath.subSequence(0, url_filepath.indexOf(".")).toString();
if(ProviderListContent.ITEMS.isEmpty()) //TODO I have to implement a way of checking if a provider new or is already present in that ITEMS list
ProviderListContent.addItem(new ProviderItem(provider_name, asset_manager.open(url_files_folder + "/" + url_filepath), custom, true)); // By default, it trusts the provider
+ loaded_preseeded_providers = true;
}
} catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ loaded_preseeded_providers = false;
+ }
+
+ return loaded_preseeded_providers;
}
- /**
- * Callback method from {@link ProviderListFragment.Callbacks}
- * indicating that the item with the given ID was selected.
- */
- @Override
- public void onItemSelected(String id) {
- if (mTwoPane) {
- // TODO Hmmm...is this how we should do this? What if it /is/ two pane?
- } else {
- // In single-pane mode, simply start the detail activity
- // for the selected item ID.
-
- Iterator<ProviderItem> preseeded_providers_iterator = ProviderListContent.ITEMS.iterator();
- while(preseeded_providers_iterator.hasNext())
- {
- ProviderItem current_provider_item = preseeded_providers_iterator.next();
- if(current_provider_item.id.equalsIgnoreCase(id))
- {
- try {
- saveProviderJson(current_provider_item);
- downloadJSONFiles(current_provider_item);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
-
- private void saveProviderJson(ProviderItem current_provider_item) {
+ private boolean saveProviderJson(ProviderItem current_provider_item) {
JSONObject provider_json = new JSONObject();
try {
String provider_contents = "";
if(!current_provider_item.custom) {
- //provider_contents = new Scanner(new InputStreamReader(assets_manager.open(current_provider_item.provider_json_filename))).useDelimiter("\\A").next();
updateProviderDotJson(current_provider_item.name, current_provider_item.provider_json_url, current_provider_item.danger_on);
+ return true;
} else {
provider_contents = new Scanner(ConfigHelper.openFileInputStream(current_provider_item.provider_json_filename)).useDelimiter("\\A").next();
provider_json = new JSONObject(provider_contents);
- ConfigHelper.saveSharedPref(ConfigHelper.provider_key, provider_json);
- try {
- ConfigHelper.saveSharedPref(ConfigHelper.danger_on, new JSONObject().put(ConfigHelper.danger_on, current_provider_item.danger_on));
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ ConfigHelper.saveSharedPref(ConfigHelper.PROVIDER_KEY, provider_json);
+ ConfigHelper.saveSharedPref(ConfigHelper.DANGER_ON, new JSONObject().put(ConfigHelper.DANGER_ON, current_provider_item.danger_on));
+ return true;
}
} catch (JSONException e) {
- ConfigHelper.rescueJSONException(e);
+ return false;
}
- }
+ }
private void downloadJSONFiles(ProviderItem current_provider_item) throws IOException {
providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler());
@@ -165,12 +171,12 @@ public class ConfigurationWizard extends Activity Bundle method_and_parameters = new Bundle();
- method_and_parameters.putString(ConfigHelper.provider_key, current_provider_item.name);
- method_and_parameters.putString(ConfigHelper.main_cert_key, current_provider_item.cert_json_url);
- method_and_parameters.putString(ConfigHelper.eip_service_key, current_provider_item.eip_service_json_url);
- method_and_parameters.putBoolean(ConfigHelper.danger_on, current_provider_item.danger_on);
+ method_and_parameters.putString(ConfigHelper.PROVIDER_KEY, current_provider_item.name);
+ method_and_parameters.putString(ConfigHelper.MAIN_CERT_KEY, current_provider_item.cert_json_url);
+ method_and_parameters.putString(ConfigHelper.EIP_SERVICE_KEY, current_provider_item.eip_service_json_url);
+ method_and_parameters.putBoolean(ConfigHelper.DANGER_ON, current_provider_item.danger_on);
- provider_API_command.putExtra(ConfigHelper.downloadJsonFilesBundleExtra, method_and_parameters);
+ provider_API_command.putExtra(ConfigHelper.DOWNLOAD_JSON_FILES_BUNDLE_EXTRA, method_and_parameters);
provider_API_command.putExtra("receiver", providerAPI_result_receiver);
startService(provider_API_command);
@@ -178,14 +184,14 @@ public class ConfigurationWizard extends Activity public void addNewProvider(View view) {
FragmentTransaction fragment_transaction = getFragmentManager().beginTransaction();
- Fragment previous_new_provider_dialog = getFragmentManager().findFragmentByTag(ConfigHelper.newProviderDialog);
+ Fragment previous_new_provider_dialog = getFragmentManager().findFragmentByTag(ConfigHelper.NEW_PROVIDER_DIALOG);
if (previous_new_provider_dialog != null) {
fragment_transaction.remove(previous_new_provider_dialog);
}
fragment_transaction.addToBackStack(null);
DialogFragment newFragment = NewProviderDialog.newInstance();
- newFragment.show(fragment_transaction, ConfigHelper.newProviderDialog);
+ newFragment.show(fragment_transaction, ConfigHelper.NEW_PROVIDER_DIALOG);
}
@Override
@@ -196,10 +202,10 @@ public class ConfigurationWizard extends Activity Intent provider_API_command = new Intent(this, ProviderAPI.class);
Bundle method_and_parameters = new Bundle();
- method_and_parameters.putString(ConfigHelper.provider_main_url, provider_main_url);
- method_and_parameters.putBoolean(ConfigHelper.danger_on, danger_on);
+ method_and_parameters.putString(ConfigHelper.PROVIDER_MAIN_URL, provider_main_url);
+ method_and_parameters.putBoolean(ConfigHelper.DANGER_ON, danger_on);
- provider_API_command.putExtra(ConfigHelper.downloadNewProviderDotJSON, method_and_parameters);
+ provider_API_command.putExtra(ConfigHelper.DOWNLOAD_NEW_PROVIDER_DOTJSON, method_and_parameters);
provider_API_command.putExtra("receiver", providerAPI_result_receiver);
startService(provider_API_command);
@@ -212,49 +218,13 @@ public class ConfigurationWizard extends Activity Intent provider_API_command = new Intent(this, ProviderAPI.class);
Bundle method_and_parameters = new Bundle();
- method_and_parameters.putString(ConfigHelper.provider_name, provider_name);
- method_and_parameters.putString(ConfigHelper.provider_json_url, provider_json_url);
- method_and_parameters.putBoolean(ConfigHelper.danger_on, danger_on);
+ method_and_parameters.putString(ConfigHelper.PROVIDER_NAME, provider_name);
+ method_and_parameters.putString(ConfigHelper.PROVIDER_JSON_URL, provider_json_url);
+ method_and_parameters.putBoolean(ConfigHelper.DANGER_ON, danger_on);
- provider_API_command.putExtra(ConfigHelper.updateProviderDotJSON, method_and_parameters);
+ provider_API_command.putExtra(ConfigHelper.UPDATE_PROVIDER_DOTJSON, method_and_parameters);
provider_API_command.putExtra("receiver", providerAPI_result_receiver);
startService(provider_API_command);
}
-
- @Override
- public void onReceiveResult(int resultCode, Bundle resultData) {
- if(resultCode == ConfigHelper.CUSTOM_PROVIDER_ADDED){
- ProviderListFragment providerList = new ProviderListFragment();
-
- FragmentManager fragmentManager = getFragmentManager();
- fragmentManager.beginTransaction()
- .replace(R.id.configuration_wizard_layout, providerList, "providerlist")
- .commit();
- } - else if(resultCode == ConfigHelper.CORRECTLY_DOWNLOADED_JSON_FILES) {
- setResult(RESULT_OK);
- finish();
- }
- else if(resultCode == ConfigHelper.INCORRECTLY_DOWNLOADED_JSON_FILES) {
- setResult(RESULT_CANCELED);
- Toast.makeText(getApplicationContext(), "You have not entered a LEAP provider URL", Toast.LENGTH_LONG).show(); - }
- else if(resultCode == ConfigHelper.CORRECTLY_UPDATED_PROVIDER_DOT_JSON) {
- JSONObject provider_json;
- try {
- provider_json = new JSONObject(resultData.getString(ConfigHelper.provider_key));
- boolean danger_on = resultData.getBoolean(ConfigHelper.danger_on);
- ConfigHelper.saveSharedPref(ConfigHelper.provider_key, provider_json);
- ConfigHelper.saveSharedPref(ConfigHelper.danger_on, new JSONObject().put(ConfigHelper.danger_on, danger_on));
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- else if(resultCode == ConfigHelper.INCORRECTLY_UPDATED_PROVIDER_DOT_JSON) {
- Toast.makeText(getApplicationContext(), "Install a new version of this app.", Toast.LENGTH_LONG).show();
- }
-
- }
}
diff --git a/src/se/leap/leapclient/Dashboard.java b/src/se/leap/leapclient/Dashboard.java index c8cbc5a3..b937c949 100644 --- a/src/se/leap/leapclient/Dashboard.java +++ b/src/se/leap/leapclient/Dashboard.java @@ -6,6 +6,10 @@ import org.json.JSONException; import org.json.JSONObject; import se.leap.leapclient.ProviderAPIResultReceiver.Receiver; +import se.leap.leapclient.R; +import se.leap.leapclient.R.id; +import se.leap.leapclient.R.layout; +import se.leap.leapclient.R.menu; import se.leap.openvpn.AboutFragment; import se.leap.openvpn.MainActivity; import android.app.Activity; @@ -116,11 +120,11 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf @Override public boolean onPrepareOptionsMenu(Menu menu) { - String provider_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.provider_key); + String provider_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.PROVIDER_KEY); try { JSONObject provider_json = new JSONObject(provider_json_string); - JSONObject service_description = provider_json.getJSONObject(ConfigHelper.service_key); - if(service_description.getBoolean(ConfigHelper.allow_registration_key)) { + JSONObject service_description = provider_json.getJSONObject(ConfigHelper.SERVICE_KEY); + if(service_description.getBoolean(ConfigHelper.ALLOW_REGISTRATION_KEY)) { menu.findItem(R.id.login_button).setVisible(true); menu.findItem(R.id.logout_button).setVisible(true); return true; @@ -187,19 +191,19 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf Intent provider_API_command = new Intent(this, ProviderAPI.class); Bundle method_and_parameters = new Bundle(); - method_and_parameters.putString(ConfigHelper.username_key, username); - method_and_parameters.putString(ConfigHelper.password_key, password); + method_and_parameters.putString(ConfigHelper.USERNAME_KEY, username); + method_and_parameters.putString(ConfigHelper.PASSWORD_KEY, password); JSONObject provider_json; try { - provider_json = new JSONObject(preferences.getString(ConfigHelper.provider_key, "")); - method_and_parameters.putString(ConfigHelper.api_url_key, provider_json.getString(ConfigHelper.api_url_key) + "/" + provider_json.getString(ConfigHelper.api_version_key)); + provider_json = new JSONObject(preferences.getString(ConfigHelper.PROVIDER_KEY, "")); + method_and_parameters.putString(ConfigHelper.API_URL_KEY, provider_json.getString(ConfigHelper.API_URL_KEY) + "/" + provider_json.getString(ConfigHelper.API_VERSION_KEY)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } - provider_API_command.putExtra(ConfigHelper.srpAuth, method_and_parameters); + provider_API_command.putExtra(ConfigHelper.SRP_AUTH, method_and_parameters); provider_API_command.putExtra("receiver", providerAPI_result_receiver); startService(provider_API_command); @@ -214,14 +218,14 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf JSONObject provider_json; try { - provider_json = new JSONObject(preferences.getString(ConfigHelper.provider_key, "")); - method_and_parameters.putString(ConfigHelper.api_url_key, provider_json.getString(ConfigHelper.api_url_key) + "/" + provider_json.getString(ConfigHelper.api_version_key)); + provider_json = new JSONObject(preferences.getString(ConfigHelper.PROVIDER_KEY, "")); + method_and_parameters.putString(ConfigHelper.API_URL_KEY, provider_json.getString(ConfigHelper.API_URL_KEY) + "/" + provider_json.getString(ConfigHelper.API_VERSION_KEY)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } - provider_API_command.putExtra(ConfigHelper.logOut, method_and_parameters); + provider_API_command.putExtra(ConfigHelper.LOG_OUT, method_and_parameters); provider_API_command.putExtra("receiver", providerAPI_result_receiver); startService(provider_API_command); @@ -229,14 +233,14 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf public void logInDialog(View view) { FragmentTransaction fragment_transaction = getFragmentManager().beginTransaction(); - Fragment previous_log_in_dialog = getFragmentManager().findFragmentByTag(ConfigHelper.logInDialog); + Fragment previous_log_in_dialog = getFragmentManager().findFragmentByTag(ConfigHelper.LOG_IN_DIALOG); if (previous_log_in_dialog != null) { fragment_transaction.remove(previous_log_in_dialog); } fragment_transaction.addToBackStack(null); DialogFragment newFragment = LogInDialog.newInstance(); - newFragment.show(fragment_transaction, ConfigHelper.logInDialog); + newFragment.show(fragment_transaction, ConfigHelper.LOG_IN_DIALOG); } private void downloadAuthedUserCertificate(Cookie session_id) { @@ -246,10 +250,10 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf Intent provider_API_command = new Intent(this, ProviderAPI.class); Bundle method_and_parameters = new Bundle(); - method_and_parameters.putString(ConfigHelper.session_id_cookie_key, session_id.getName()); - method_and_parameters.putString(ConfigHelper.session_id_key, session_id.getValue()); + method_and_parameters.putString(ConfigHelper.SESSION_ID_COOKIE_KEY, session_id.getName()); + method_and_parameters.putString(ConfigHelper.SESSION_ID_KEY, session_id.getValue()); - provider_API_command.putExtra(ConfigHelper.downloadUserAuthedCertificate, method_and_parameters); + provider_API_command.putExtra(ConfigHelper.DOWNLOAD_USER_AUTHED_CERTIFICATE, method_and_parameters); provider_API_command.putExtra("receiver", providerAPI_result_receiver); startService(provider_API_command); @@ -258,8 +262,8 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf @Override public void onReceiveResult(int resultCode, Bundle resultData) { if(resultCode == ConfigHelper.SRP_AUTHENTICATION_SUCCESSFUL){ - String session_id_cookie_key = resultData.getString(ConfigHelper.session_id_cookie_key); - String session_id_string = resultData.getString(ConfigHelper.session_id_key); + String session_id_cookie_key = resultData.getString(ConfigHelper.SESSION_ID_COOKIE_KEY); + String session_id_string = resultData.getString(ConfigHelper.SESSION_ID_KEY); setResult(RESULT_OK); Toast.makeText(getApplicationContext(), "Authentication succeeded", Toast.LENGTH_LONG).show(); diff --git a/src/se/leap/leapclient/LeapHttpClient.java b/src/se/leap/leapclient/LeapHttpClient.java index 4de7ae08..a2ee8ad6 100644 --- a/src/se/leap/leapclient/LeapHttpClient.java +++ b/src/se/leap/leapclient/LeapHttpClient.java @@ -16,57 +16,57 @@ import android.content.Context; public class LeapHttpClient extends DefaultHttpClient { final Context context; - + private static LeapHttpClient client; - public LeapHttpClient(Context context) { - this.context = context; - } + public static LeapHttpClient getInstance(Context context) { + if(client == null) { + client = new LeapHttpClient(context); + String cert_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.MAIN_CERT_KEY); + String cert_string; + try { + cert_string = new JSONObject(cert_json_string).getString(ConfigHelper.MAIN_CERT_KEY); + if(!cert_string.isEmpty()) { + ConfigHelper.addTrustedCertificate("recovered_certificate", cert_string); + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return client; + } + + @Override + protected ClientConnectionManager createClientConnectionManager() { + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + // Register for port 443 our SSLSocketFactory with our keystore + // to the ConnectionManager + registry.register(new Scheme("https", newSslSocketFactory(), 443)); + return new SingleClientConnManager(getParams(), registry); + } + + private SSLSocketFactory newSslSocketFactory() { + try { + // Get an instance of the Bouncy Castle KeyStore format + KeyStore trusted = ConfigHelper.getKeystore(); + + // Pass the keystore to the SSLSocketFactory. The factory is responsible + // for the verification of the server certificate. + SSLSocketFactory sf = new SSLSocketFactory(trusted); - @Override - protected ClientConnectionManager createClientConnectionManager() { - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - // Register for port 443 our SSLSocketFactory with our keystore - // to the ConnectionManager - registry.register(new Scheme("https", newSslSocketFactory(), 443)); - return new SingleClientConnManager(getParams(), registry); - } + // Hostname verification from certificate + // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 + sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - private SSLSocketFactory newSslSocketFactory() { - try { - // Get an instance of the Bouncy Castle KeyStore format - KeyStore trusted = ConfigHelper.getKeystore(); - - // Pass the keystore to the SSLSocketFactory. The factory is responsible - // for the verification of the server certificate. - SSLSocketFactory sf = new SSLSocketFactory(trusted); - - // Hostname verification from certificate - // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 - sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - return sf; - } catch (Exception e) { - throw new AssertionError(e); - } - } + return sf; + } catch (Exception e) { + throw new AssertionError(e); + } + } - public static LeapHttpClient getInstance(Context context) { - if(client == null) { - client = new LeapHttpClient(context); - String cert_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.main_cert_key); - String cert_string; - try { - cert_string = new JSONObject(cert_json_string).getString(ConfigHelper.main_cert_key); - if(!cert_string.isEmpty()) { - ConfigHelper.addTrustedCertificate("recovered_certificate", cert_string); - } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return client; - } + public LeapHttpClient(Context context) { + this.context = context; + } } diff --git a/src/se/leap/leapclient/LeapSRPSession.java b/src/se/leap/leapclient/LeapSRPSession.java index f9037de9..7b32e791 100644 --- a/src/se/leap/leapclient/LeapSRPSession.java +++ b/src/se/leap/leapclient/LeapSRPSession.java @@ -47,8 +47,7 @@ public class LeapSRPSession { @param username, the user ID @param password, the user clear text password @param params, the SRP parameters for the session - @param abytes, the random exponent used in the A public key. This must be - 8 bytes in length. + @param abytes, the random exponent used in the A public key */ public LeapSRPSession(String username, String password, SRPParameters params, byte[] abytes) { @@ -177,8 +176,9 @@ public class LeapSRPSession { /** * Calculates the parameter M1, to be sent to the SRP server. * It also updates hashes of client and server for further calculations in other methods. + * It uses a predefined k. + * @param salt_bytes * @param Bbytes the parameter received from the server, in bytes - * @param bs * @return the parameter M1 * @throws NoSuchAlgorithmException */ @@ -190,8 +190,6 @@ public class LeapSRPSession { // Calculate v = kg^x mod N String k_string = "bf66c44a428916cad64aa7c679f3fd897ad4c375e9bbb4cbf2f5de241d618ef0"; this.v = calculateV(k_string); - //String v_string = v.toString(16); - // H(N) byte[] digest_of_n = newDigest().digest(N_bytes); @@ -201,54 +199,45 @@ public class LeapSRPSession { // clientHash = H(N) xor H(g) byte[] xor_digest = xor(digest_of_n, digest_of_g, digest_of_g.length); - //String hxg_string = new BigInteger(1, xor_digest).toString(16); clientHash.update(xor_digest); // clientHash = H(N) xor H(g) | H(U) byte[] username_digest = newDigest().digest(Util.trim(username.getBytes())); username_digest = Util.trim(username_digest); - //String username_digest_string = new BigInteger(1, username_digest).toString(16); clientHash.update(username_digest); // clientHash = H(N) xor H(g) | H(U) | s - //String salt_string = new BigInteger(1, salt_bytes).toString(16); clientHash.update(Util.trim(salt_bytes)); K = null; - - // clientHash = H(N) xor H(g) | H(U) | s | A | B - - byte[] Abytes = Util.trim(A.toByteArray()); - //String Abytes_string = new BigInteger(1, Abytes).toString(16); // clientHash = H(N) xor H(g) | H(U) | A + byte[] Abytes = Util.trim(A.toByteArray()); clientHash.update(Abytes); // clientHash = H(N) xor H(g) | H(U) | s | A | B Bbytes = Util.trim(Bbytes); - //String Bbytes_string = new BigInteger(1, Bbytes).toString(16); clientHash.update(Bbytes); // Calculate S = (B - kg^x) ^ (a + u * x) % N BigInteger S = calculateS(Bbytes); byte[] S_bytes = Util.trim(S.toByteArray()); - //String S_bytes_string = new BigInteger(1, S_bytes).toString(16); // K = SessionHash(S) String hash_algorithm = params.hashAlgorithm; MessageDigest sessionDigest = MessageDigest.getInstance(hash_algorithm); K = Util.trim(sessionDigest.digest(S_bytes)); - //K = Util.trim(K); - //String K_bytes_string = new BigInteger(1, K).toString(16); // clientHash = H(N) xor H(g) | H(U) | A | B | K clientHash.update(K); + byte[] M1 = Util.trim(clientHash.digest()); // serverHash = Astr + M + K serverHash.update(Abytes); serverHash.update(M1); serverHash.update(K); + return M1; } @@ -263,13 +252,10 @@ public class LeapSRPSession { byte[] u_bytes = getU(Abytes, Bbytes); BigInteger B = new BigInteger(1, Bbytes); - //String Bstring = B.toString(16); BigInteger u = new BigInteger(1, u_bytes); - //String u_string = u.toString(16); BigInteger B_minus_v = B.subtract(v); BigInteger a_ux = a.add(u.multiply(x)); - //String a_ux_string = a_ux.toString(16); BigInteger S = B_minus_v.modPow(a_ux, N); return S; @@ -285,7 +271,7 @@ public class LeapSRPSession { MessageDigest u_digest = newDigest(); u_digest.update(Util.trim(Abytes)); u_digest.update(Util.trim(Bbytes)); - byte[] u_digest_bytes = u_digest.digest();//Util.trim(u_digest.digest()); + byte[] u_digest_bytes = u_digest.digest(); return Util.trim(new BigInteger(1, u_digest_bytes).toByteArray()); } @@ -302,17 +288,6 @@ public class LeapSRPSession { return valid; } - /** Returns the negotiated session K, K = SHA_Interleave(S) - @return the private session K byte[] - @throws SecurityException - if the current thread does not have an - getSessionKey SRPPermission. - */ - public byte[] getSessionKey() throws SecurityException - { - return K; - } - - /** * @return a new SHA-256 digest. */ diff --git a/src/se/leap/leapclient/LogInDialog.java b/src/se/leap/leapclient/LogInDialog.java index 30984db6..370a138c 100644 --- a/src/se/leap/leapclient/LogInDialog.java +++ b/src/se/leap/leapclient/LogInDialog.java @@ -1,8 +1,11 @@ package se.leap.leapclient; +import se.leap.leapclient.R; +import se.leap.leapclient.R.id; +import se.leap.leapclient.R.layout; +import se.leap.leapclient.R.string; import android.app.Activity; import android.app.AlertDialog; -import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; @@ -12,49 +15,25 @@ import android.widget.EditText; import android.widget.Toast; public class LogInDialog extends DialogFragment { - - public interface LogInDialogInterface { - public void authenticate(String username, String password); - } - - LogInDialogInterface interface_with_Dashboard; - - public static DialogFragment newInstance() { - LogInDialog dialog_fragment = new LogInDialog(); - return dialog_fragment; - } - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - // Verify that the host activity implements the callback interface - try { - // Instantiate the NoticeDialogListener so we can send events to the host - interface_with_Dashboard = (LogInDialogInterface) activity; - } catch (ClassCastException e) { - // The activity doesn't implement the interface, throw exception - throw new ClassCastException(activity.toString() - + " must implement NoticeDialogListener"); - } - } - public Dialog onCreateDialog(Bundle savedInstanceState) { + public AlertDialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View log_in_dialog_view = inflater.inflate(R.layout.log_in_dialog, null); + final EditText username_field = (EditText)log_in_dialog_view.findViewById(R.id.username_entered); final EditText password_field = (EditText)log_in_dialog_view.findViewById(R.id.password_entered); + builder.setView(log_in_dialog_view) .setPositiveButton(R.string.log_in_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String username = username_field.getText().toString().trim(); String password = password_field.getText().toString().trim(); - if(validPassword(password)) { + if(wellFormedPassword(password)) { interface_with_Dashboard.authenticate(username, password); - Toast.makeText(getActivity().getApplicationContext(), "Your password is valid", Toast.LENGTH_LONG).show(); } else { password_field.setText(""); - Toast.makeText(getActivity().getApplicationContext(), "Your password is not valid: it should have at least 8 characters", Toast.LENGTH_LONG).show(); + Toast.makeText(getActivity().getApplicationContext(), "Your password is not well-formed: it should have at least 8 characters", Toast.LENGTH_LONG).show(); } } }) @@ -63,11 +42,33 @@ public class LogInDialog extends DialogFragment { dialog.cancel(); } }); - // Create the AlertDialog object and return it + return builder.create(); } - boolean validPassword(String entered_password) { - return entered_password.length() > 4; + boolean wellFormedPassword(String entered_password) { + return entered_password.length() > 8; } + + public interface LogInDialogInterface { + public void authenticate(String username, String password); + } + + LogInDialogInterface interface_with_Dashboard; + + public static DialogFragment newInstance() { + LogInDialog dialog_fragment = new LogInDialog(); + return dialog_fragment; + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + try { + interface_with_Dashboard = (LogInDialogInterface) activity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + + " must implement NoticeDialogListener"); + } + } } diff --git a/src/se/leap/leapclient/NewProviderDialog.java b/src/se/leap/leapclient/NewProviderDialog.java index 61018463..99788001 100644 --- a/src/se/leap/leapclient/NewProviderDialog.java +++ b/src/se/leap/leapclient/NewProviderDialog.java @@ -1,5 +1,9 @@ package se.leap.leapclient; +import se.leap.leapclient.R; +import se.leap.leapclient.R.id; +import se.leap.leapclient.R.layout; +import se.leap.leapclient.R.string; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; @@ -28,12 +32,9 @@ public class NewProviderDialog extends DialogFragment { @Override public void onAttach(Activity activity) { super.onAttach(activity); - // Verify that the host activity implements the callback interface try { - // Instantiate the NoticeDialogListener so we can send events to the host interface_with_ConfigurationWizard = (NewProviderDialogInterface) activity; } catch (ClassCastException e) { - // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement NoticeDialogListener"); } diff --git a/src/se/leap/leapclient/Provider.java b/src/se/leap/leapclient/Provider.java index 4235acfd..f86bbf59 100644 --- a/src/se/leap/leapclient/Provider.java +++ b/src/se/leap/leapclient/Provider.java @@ -18,7 +18,7 @@ import android.content.SharedPreferences; * @author Sean Leonard <meanderingcode@aetherislands.net> * */ -final class Provider implements Serializable { +public final class Provider implements Serializable { private static final long serialVersionUID = 6003835972151761353L; diff --git a/src/se/leap/leapclient/ProviderAPI.java b/src/se/leap/leapclient/ProviderAPI.java index b44c9971..00033440 100644 --- a/src/se/leap/leapclient/ProviderAPI.java +++ b/src/se/leap/leapclient/ProviderAPI.java @@ -11,7 +11,6 @@ import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.List; import java.net.CookieHandler; import java.net.CookieManager; import java.net.HttpCookie; @@ -32,6 +31,7 @@ import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; @@ -63,89 +63,72 @@ public class ProviderAPI extends IntentService { final ResultReceiver receiver = task_for.getParcelableExtra("receiver"); Bundle task; - if((task = task_for.getBundleExtra(ConfigHelper.downloadJsonFilesBundleExtra)) != null) { - if(!downloadJsonFiles(task)) + if((task = task_for.getBundleExtra(ConfigHelper.DOWNLOAD_JSON_FILES_BUNDLE_EXTRA)) != null) { + if(!downloadJsonFiles(task)) { receiver.send(ConfigHelper.INCORRECTLY_DOWNLOADED_JSON_FILES, Bundle.EMPTY); - else + } else { receiver.send(ConfigHelper.CORRECTLY_DOWNLOADED_JSON_FILES, Bundle.EMPTY); + } } - else if ((task = task_for.getBundleExtra(ConfigHelper.updateProviderDotJSON)) != null) { - JSONObject result = updateProviderDotJSON(task); - boolean successful; - try { - successful = result.getBoolean(ConfigHelper.resultKey); - if(successful) { - Bundle provider_dot_json_and_danger_on = new Bundle(); - provider_dot_json_and_danger_on.putBoolean(ConfigHelper.danger_on, result.getBoolean(ConfigHelper.danger_on)); - provider_dot_json_and_danger_on.putString(ConfigHelper.provider_key, result.getJSONObject(ConfigHelper.provider_key).toString()); - receiver.send(ConfigHelper.CORRECTLY_UPDATED_PROVIDER_DOT_JSON, provider_dot_json_and_danger_on); - } else { - receiver.send(ConfigHelper.INCORRECTLY_UPDATED_PROVIDER_DOT_JSON, Bundle.EMPTY); - } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + else if ((task = task_for.getBundleExtra(ConfigHelper.UPDATE_PROVIDER_DOTJSON)) != null) { + Bundle result = updateProviderDotJSON(task); + if(result.getBoolean(ConfigHelper.RESULT_KEY)) { + receiver.send(ConfigHelper.CORRECTLY_UPDATED_PROVIDER_DOT_JSON, result); + } else { + receiver.send(ConfigHelper.INCORRECTLY_UPDATED_PROVIDER_DOT_JSON, Bundle.EMPTY); } } - else if ((task = task_for.getBundleExtra(ConfigHelper.downloadNewProviderDotJSON)) != null) { - if(downloadNewProviderDotJSON(task)) + else if ((task = task_for.getBundleExtra(ConfigHelper.DOWNLOAD_NEW_PROVIDER_DOTJSON)) != null) { + if(downloadNewProviderDotJSON(task)) { receiver.send(ConfigHelper.CUSTOM_PROVIDER_ADDED, Bundle.EMPTY); - else + } else { receiver.send(ConfigHelper.INCORRECTLY_DOWNLOADED_JSON_FILES, Bundle.EMPTY); + } } - else if ((task = task_for.getBundleExtra(ConfigHelper.srpAuth)) != null) { - try { - JSONObject session_idAndResult = authenticateBySRP(task); - if(session_idAndResult.getBoolean(ConfigHelper.resultKey)) { - Bundle session_id_bundle = new Bundle(); - session_id_bundle.putString(ConfigHelper.session_id_cookie_key, session_idAndResult.getString(ConfigHelper.session_id_cookie_key)); - session_id_bundle.putString(ConfigHelper.session_id_key, session_idAndResult.getString(ConfigHelper.session_id_key)); - receiver.send(ConfigHelper.SRP_AUTHENTICATION_SUCCESSFUL, session_id_bundle); - } else { - receiver.send(ConfigHelper.SRP_AUTHENTICATION_FAILED, Bundle.EMPTY); - } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + else if ((task = task_for.getBundleExtra(ConfigHelper.SRP_AUTH)) != null) { + Bundle session_id_bundle = authenticateBySRP(task); + if(session_id_bundle.getBoolean(ConfigHelper.RESULT_KEY)) { + receiver.send(ConfigHelper.SRP_AUTHENTICATION_SUCCESSFUL, session_id_bundle); + } else { + receiver.send(ConfigHelper.SRP_AUTHENTICATION_FAILED, Bundle.EMPTY); } } - else if ((task = task_for.getBundleExtra(ConfigHelper.logOut)) != null) { - if(logOut(task)) + else if ((task = task_for.getBundleExtra(ConfigHelper.LOG_OUT)) != null) { + if(logOut(task)) { receiver.send(ConfigHelper.LOGOUT_SUCCESSFUL, Bundle.EMPTY); - else + } else { receiver.send(ConfigHelper.LOGOUT_FAILED, Bundle.EMPTY); + } } - else if ((task = task_for.getBundleExtra(ConfigHelper.downloadUserAuthedCertificate)) != null) { - if(getNewCert(task)) + else if ((task = task_for.getBundleExtra(ConfigHelper.DOWNLOAD_USER_AUTHED_CERTIFICATE)) != null) { + if(getNewCert(task)) { receiver.send(ConfigHelper.CORRECTLY_DOWNLOADED_AUTHED_USER_CERTIFICATE, Bundle.EMPTY); - else + } else { receiver.send(ConfigHelper.INCORRECTLY_DOWNLOADED_AUTHED_USER_CERTIFICATE, Bundle.EMPTY); + } } } private boolean downloadJsonFiles(Bundle task) { - //String provider_name = task.getString(ConfigHelper.provider_key); - String cert_url = task.getString(ConfigHelper.main_cert_key); - String eip_service_json_url = task.getString(ConfigHelper.eip_service_key); - boolean danger_on = task.getBoolean(ConfigHelper.danger_on); + String cert_url = task.getString(ConfigHelper.MAIN_CERT_KEY); + String eip_service_json_url = task.getString(ConfigHelper.EIP_SERVICE_KEY); + boolean danger_on = task.getBoolean(ConfigHelper.DANGER_ON); try { String cert_string = getStringFromProvider(cert_url, danger_on); - //ConfigHelper.addTrustedCertificate(provider_name, cert_string); - JSONObject cert_json = new JSONObject().put(ConfigHelper.main_cert_key, cert_string); - ConfigHelper.saveSharedPref(ConfigHelper.main_cert_key, cert_json); + JSONObject cert_json = new JSONObject().put(ConfigHelper.MAIN_CERT_KEY, cert_string); + ConfigHelper.saveSharedPref(ConfigHelper.MAIN_CERT_KEY, cert_json); JSONObject eip_service_json = getJSONFromProvider(eip_service_json_url, danger_on); - ConfigHelper.saveSharedPref(ConfigHelper.eip_service_key, eip_service_json); + ConfigHelper.saveSharedPref(ConfigHelper.EIP_SERVICE_KEY, eip_service_json); return true; } catch (JSONException e) { - ConfigHelper.rescueJSONException(e); return false; } } private boolean registerWithSRP(Bundle task) { - String username = (String) task.get(ConfigHelper.username_key); - String password = (String) task.get(ConfigHelper.password_key); - String authentication_server = (String) task.get(ConfigHelper.api_url_key); + String username = (String) task.get(ConfigHelper.USERNAME_KEY); + String password = (String) task.get(ConfigHelper.PASSWORD_KEY); + String authentication_server = (String) task.get(ConfigHelper.API_URL_KEY); BigInteger ng_1024 = new BigInteger(ConfigHelper.NG_1024, 16); BigInteger salt = ng_1024.probablePrime(1024, null); @@ -154,173 +137,127 @@ public class ProviderAPI extends IntentService { return false; } - private JSONObject authenticateBySRP(Bundle task) { - JSONObject successfulAndsession_id = new JSONObject(); - - String username = (String) task.get(ConfigHelper.username_key); - String password = (String) task.get(ConfigHelper.password_key); - String authentication_server = (String) task.get(ConfigHelper.api_url_key); + private Bundle authenticateBySRP(Bundle task) { + Bundle session_id_bundle = new Bundle(); - String salt = "abcd"; + String username = (String) task.get(ConfigHelper.USERNAME_KEY); + String password = (String) task.get(ConfigHelper.PASSWORD_KEY); + String authentication_server = (String) task.get(ConfigHelper.API_URL_KEY); - SRPParameters params = new SRPParameters(new BigInteger(ConfigHelper.NG_1024, 16).toByteArray(), new BigInteger("2").toByteArray(), new BigInteger(salt, 16).toByteArray(), "SHA-256"); - //SRPClientSession client = new SRPClientSession(username, password.toCharArray(), params); + 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(); try { JSONObject saltAndB = sendAToSRPServer(authentication_server, username, new BigInteger(1, A).toString(16)); if(saltAndB.length() > 0) { - salt = saltAndB.getString("salt"); + String salt = saltAndB.getString(ConfigHelper.SALT_KEY); byte[] Bbytes = new BigInteger(saltAndB.getString("B"), 16).toByteArray(); byte[] M1 = client.response(new BigInteger(salt, 16).toByteArray(), Bbytes); - //byte[] M2 = sendM1ToSRPServer(authentication_server, username, M1); JSONObject session_idAndM2 = sendM1ToSRPServer(authentication_server, username, M1); if( client.verify((byte[])session_idAndM2.get("M2")) == false ) { - //throw new SecurityException("Failed to validate server reply: M2 = " + new BigInteger(1, M2).toString(16)); - successfulAndsession_id.put(ConfigHelper.resultKey, false); - return successfulAndsession_id; + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, false); } else { - successfulAndsession_id.put(ConfigHelper.resultKey, true); - successfulAndsession_id.put(ConfigHelper.session_id_key, session_idAndM2.getString(ConfigHelper.session_id_key)); - successfulAndsession_id.put(ConfigHelper.session_id_cookie_key, session_idAndM2.getString(ConfigHelper.session_id_cookie_key)); - return successfulAndsession_id; + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, true); + session_id_bundle.putString(ConfigHelper.SESSION_ID_KEY, session_idAndM2.getString(ConfigHelper.SESSION_ID_KEY)); + session_id_bundle.putString(ConfigHelper.SESSION_ID_COOKIE_KEY, session_idAndM2.getString(ConfigHelper.SESSION_ID_COOKIE_KEY)); } } else { - successfulAndsession_id.put(ConfigHelper.resultKey, false); - return successfulAndsession_id; + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, false); } - } catch (ClientProtocolException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (JSONException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + } catch (ClientProtocolException e) { + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, false); + } catch (IOException e) { + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, false); + } catch (JSONException e) { + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, false); } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + session_id_bundle.putBoolean(ConfigHelper.RESULT_KEY, false); } - return successfulAndsession_id; + + return session_id_bundle; } private JSONObject sendAToSRPServer(String server_url, String username, String clientA) throws ClientProtocolException, IOException, JSONException { - DefaultHttpClient client = LeapHttpClient.getInstance(getApplicationContext()); - String parameter_chain = "A" + "=" + clientA + "&" + "login" + "=" + username; - HttpPost post = new HttpPost(server_url + "/sessions.json" + "?" + parameter_chain); - - HttpResponse getResponse = client.execute(post); - HttpEntity responseEntity = getResponse.getEntity(); - String plain_response = new Scanner(responseEntity.getContent()).useDelimiter("\\A").next(); - JSONObject json_response = new JSONObject(plain_response); - if(!json_response.isNull("errors") || json_response.has("errors")) { - return new JSONObject(); - } - - String session_id = ""; - List<Cookie> cookies = client.getCookieStore().getCookies(); - if(!cookies.isEmpty()) { - session_id = cookies.get(0).getValue(); - } - return json_response; + HttpPost post = new HttpPost(server_url + "/sessions.json" + "?" + "login=" + username + "&&" + "A=" + clientA); + return sendToServer(post); } private JSONObject sendM1ToSRPServer(String server_url, String username, byte[] m1) throws ClientProtocolException, IOException, JSONException { + HttpPut put = new HttpPut(server_url + "/sessions/" + username +".json" + "?" + "client_auth" + "=" + new BigInteger(1, Util.trim(m1)).toString(16)); + JSONObject json_response = sendToServer(put); + JSONObject session_idAndM2 = new JSONObject(); + if(json_response.length() > 0) { + byte[] M2_not_trimmed = new BigInteger(json_response.getString("M2"), 16).toByteArray(); + Cookie session_id_cookie = LeapHttpClient.getInstance(getApplicationContext()).getCookieStore().getCookies().get(0); + session_idAndM2.put(ConfigHelper.SESSION_ID_COOKIE_KEY, session_id_cookie.getName()); + session_idAndM2.put(ConfigHelper.SESSION_ID_KEY, session_id_cookie.getValue()); + session_idAndM2.put("M2", Util.trim(M2_not_trimmed)); + } + return session_idAndM2; + } + + private JSONObject sendToServer(HttpUriRequest request) throws ClientProtocolException, IOException, JSONException { DefaultHttpClient client = LeapHttpClient.getInstance(getApplicationContext()); - String parameter_chain = "client_auth" + "=" + new BigInteger(1, Util.trim(m1)).toString(16); - HttpPut put = new HttpPut(server_url + "/sessions/" + username +".json" + "?" + parameter_chain); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, client.getCookieStore()); - String session_id = client.getCookieStore().getCookies().get(0).getValue(); - int number_of_cookies = client.getCookieStore().getCookies().size(); - HttpResponse getResponse = client.execute(put, localContext); + HttpResponse getResponse = client.execute(request, localContext); HttpEntity responseEntity = getResponse.getEntity(); String plain_response = new Scanner(responseEntity.getContent()).useDelimiter("\\A").next(); JSONObject json_response = new JSONObject(plain_response); if(!json_response.isNull("errors") || json_response.has("errors")) { - return session_idAndM2; + return new JSONObject(); } - number_of_cookies = client.getCookieStore().getCookies().size(); - byte[] M2_not_trimmed = new BigInteger(json_response.getString("M2"), 16).toByteArray(); - session_idAndM2.put(ConfigHelper.session_id_cookie_key, client.getCookieStore().getCookies().get(0).getName()); - session_idAndM2.put(ConfigHelper.session_id_key, client.getCookieStore().getCookies().get(0).getValue()); - session_idAndM2.put("M2", Util.trim(M2_not_trimmed)); - return session_idAndM2; + return json_response; } - private JSONObject updateProviderDotJSON(Bundle task) { - JSONObject result = new JSONObject(); - boolean custom = task.getBoolean(ConfigHelper.custom); - boolean danger_on = task.getBoolean(ConfigHelper.danger_on); - String provider_json_url = task.getString(ConfigHelper.provider_json_url); - String provider_name = task.getString(ConfigHelper.provider_name); + private Bundle updateProviderDotJSON(Bundle task) { + Bundle result = new Bundle(); + boolean custom = task.getBoolean(ConfigHelper.CUSTOM); + boolean danger_on = task.getBoolean(ConfigHelper.DANGER_ON); + String provider_json_url = task.getString(ConfigHelper.PROVIDER_JSON_URL); + String provider_name = task.getString(ConfigHelper.PROVIDER_NAME); - JSONObject provider_json = null; try { - provider_json = getJSONFromProvider(provider_json_url, danger_on); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - try { - return result.put(ConfigHelper.resultKey, false); - } catch (JSONException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - if(provider_json == null) { - try { - return result.put(ConfigHelper.resultKey, false); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } else { - String filename = provider_name + "_provider.json".replaceFirst("__", "_"); - ConfigHelper.saveFile(filename, provider_json.toString()); - //ConfigHelper.saveSharedPref(ConfigHelper.provider_key, provider_json); + JSONObject provider_json = getJSONFromProvider(provider_json_url, danger_on); + if(provider_json == null) { + result.putBoolean(ConfigHelper.RESULT_KEY, false); + } else { + String filename = provider_name + "_provider.json".replaceFirst("__", "_"); + ConfigHelper.saveFile(filename, provider_json.toString()); - ProviderListContent.addItem(new ProviderItem(provider_name, provider_json_url, filename, custom, danger_on)); - try { - return result.put(ConfigHelper.resultKey, true).put(ConfigHelper.provider_key, provider_json).put(ConfigHelper.danger_on, danger_on); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + ProviderListContent.addItem(new ProviderItem(provider_name, provider_json_url, filename, custom, danger_on)); + result.putBoolean(ConfigHelper.RESULT_KEY, true); + result.putString(ConfigHelper.PROVIDER_KEY, provider_json.toString()); + result.putBoolean(ConfigHelper.DANGER_ON, danger_on); } + } catch (JSONException e) { + result.putBoolean(ConfigHelper.RESULT_KEY, false); } + return result; } private boolean downloadNewProviderDotJSON(Bundle task) { boolean custom = true; - boolean danger_on = task.getBoolean(ConfigHelper.danger_on); + boolean danger_on = task.getBoolean(ConfigHelper.DANGER_ON); - String provider_main_url = (String) task.get(ConfigHelper.provider_main_url); + String provider_main_url = (String) task.get(ConfigHelper.PROVIDER_MAIN_URL); String provider_name = provider_main_url.replaceFirst("http[s]?://", "").replaceFirst("\\/", "_"); String provider_json_url = guessURL(provider_main_url); JSONObject provider_json = null; try { provider_json = getJSONFromProvider(provider_json_url, danger_on); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - - if(provider_json == null) { - return false; - } else { + String filename = provider_name + "_provider.json".replaceFirst("__", "_"); ConfigHelper.saveFile(filename, provider_json.toString()); - //ConfigHelper.saveSharedPref(ConfigHelper.provider_key, provider_json); ProviderListContent.addItem(new ProviderItem(provider_name, provider_json_url, filename, custom, danger_on)); return true; + } catch (JSONException e) { + return false; } } @@ -385,8 +322,8 @@ public class ProviderAPI extends IntentService { try { cf = CertificateFactory.getInstance("X.509"); - String cert_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.main_cert_key); - String cert_string = new JSONObject(cert_json_string).getString(ConfigHelper.main_cert_key); + String cert_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.MAIN_CERT_KEY); + String cert_string = new JSONObject(cert_json_string).getString(ConfigHelper.MAIN_CERT_KEY); cert_string = cert_string.replaceFirst("-----BEGIN CERTIFICATE-----", "").replaceFirst("-----END CERTIFICATE-----", "").trim(); byte[] cert_bytes = Base64.decode(cert_string, Base64.DEFAULT); InputStream caInput = new ByteArrayInputStream(cert_bytes); @@ -454,7 +391,7 @@ public class ProviderAPI extends IntentService { int session_id_index = 0; //String delete_url = task.getString(ConfigHelper.srp_server_url_key) + "/sessions/" + client.getCookieStore().getCookies().get(0).getValue(); try { - String delete_url = task.getString(ConfigHelper.api_url_key) + "/logout" + "?authenticity_token=" + client.getCookieStore().getCookies().get(session_id_index).getValue(); + String delete_url = task.getString(ConfigHelper.API_URL_KEY) + "/logout" + "?authenticity_token=" + client.getCookieStore().getCookies().get(session_id_index).getValue(); HttpDelete delete = new HttpDelete(delete_url); HttpResponse getResponse = client.execute(delete); HttpEntity responseEntity = getResponse.getEntity(); @@ -476,24 +413,24 @@ public class ProviderAPI extends IntentService { } private boolean getNewCert(Bundle task) { - String provider_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.provider_key); - HttpCookie session_id_cookie = new HttpCookie(task.getString(ConfigHelper.session_id_cookie_key), task.getString(ConfigHelper.session_id_key)); + String provider_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.PROVIDER_KEY); + HttpCookie session_id_cookie = new HttpCookie(task.getString(ConfigHelper.SESSION_ID_COOKIE_KEY), task.getString(ConfigHelper.SESSION_ID_KEY)); try { JSONObject provider_json = new JSONObject(provider_json_string); - URL provider_main_url = new URL(provider_json.getString(ConfigHelper.api_url_key).replace("api.", "")); - String new_cert_string_url = provider_main_url.getProtocol() + "://" + provider_main_url.getHost() + "/" + provider_json.getString(ConfigHelper.api_version_key) + "/" + ConfigHelper.cert_key; + URL provider_main_url = new URL(provider_json.getString(ConfigHelper.API_URL_KEY).replace("api.", "")); + String new_cert_string_url = provider_main_url.getProtocol() + "://" + provider_main_url.getHost() + "/" + provider_json.getString(ConfigHelper.API_VERSION_KEY) + "/" + ConfigHelper.CERT_KEY; CookieManager cookieManager = new CookieManager(); cookieManager.getCookieStore().add(provider_main_url.toURI(), session_id_cookie); CookieHandler.setDefault(cookieManager); - String danger_on_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.danger_on); - boolean danger_on = new JSONObject(danger_on_json_string).getBoolean(ConfigHelper.danger_on); + String danger_on_json_string = ConfigHelper.getStringFromSharedPref(ConfigHelper.DANGER_ON); + boolean danger_on = new JSONObject(danger_on_json_string).getBoolean(ConfigHelper.DANGER_ON); String cert_string = getStringFromProvider(new_cert_string_url, danger_on); if(!cert_string.isEmpty()) { - JSONObject cert_json = new JSONObject().put(ConfigHelper.cert_key, cert_string); - ConfigHelper.saveSharedPref(ConfigHelper.cert_key, cert_json); + JSONObject cert_json = new JSONObject().put(ConfigHelper.CERT_KEY, cert_string); + ConfigHelper.saveSharedPref(ConfigHelper.CERT_KEY, cert_json); return true; } else { return false; diff --git a/src/se/leap/leapclient/ProviderListContent.java b/src/se/leap/leapclient/ProviderListContent.java index d4bb6a9a..b83bbd8e 100644 --- a/src/se/leap/leapclient/ProviderListContent.java +++ b/src/se/leap/leapclient/ProviderListContent.java @@ -91,7 +91,7 @@ public class ProviderListContent { this.name = name;
this.provider_json_url = provider_json_url;
this.provider_json_filename = provider_json_filename;
- eip_service_json_url = file_contents.getString("api_uri") + "/" + file_contents.getString("api_version") + "/" + ConfigHelper.eip_service_api_path;
+ eip_service_json_url = file_contents.getString("api_uri") + "/" + file_contents.getString("api_version") + "/" + ConfigHelper.EIP_SERVICE_API_PATH;
cert_json_url = (String) file_contents.get("ca_cert_uri");
this.custom = custom;
this.danger_on = danger_on;
|