summaryrefslogtreecommitdiff
path: root/src/se/leap/leapclient/ProviderAPI.java
blob: 41612d1662d3dbe59c849de1054e6811983a472d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package se.leap.leapclient;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.agreement.srp.SRP6Client;
import org.bouncycastle.crypto.agreement.srp.SRP6VerifierGenerator;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.prng.RandomGenerator;
import org.bouncycastle.jcajce.provider.digest.Whirlpool.Digest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import se.leap.leapclient.ProviderListContent.ProviderItem;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

public class ProviderAPI extends IntentService {
	
	public ProviderAPI() {
		super("ProviderAPI");
		Log.v("ClassName", "Provider API");
	}

	@Override
	protected void onHandleIntent(Intent task_for) {
		final ResultReceiver receiver = task_for.getParcelableExtra("receiver");
		
		Bundle task;
		System.out.println("onHandleIntent called");
		if((task = task_for.getBundleExtra(ConfigHelper.downloadJsonFilesBundleExtra)) != null) {
			if(!downloadJsonFiles(task))
				receiver.send(ConfigHelper.INCORRECTLY_DOWNLOADED_JSON_FILES, Bundle.EMPTY);
			else
				receiver.send(ConfigHelper.CORRECTLY_DOWNLOADED_JSON_FILES, Bundle.EMPTY);
		}
		else if ((task = task_for.getBundleExtra(ConfigHelper.downloadNewProviderDotJSON)) != null) {
			boolean custom = true;
			String provider_main_url = (String) task.get(ConfigHelper.provider_key_url);
			String provider_name = provider_main_url.replaceFirst("http[s]?://", "").replaceFirst("\\/", "_");
			String provider_json_url = guessURL(provider_main_url);
			try {
				JSONObject provider_json = getJSONFromProvider(provider_json_url);
				String filename = provider_name + "_provider.json".replaceFirst("__", "_");
				ConfigHelper.saveFile(filename, provider_json.toString());
        		ProviderListContent.addItem(new ProviderItem(provider_name, ConfigHelper.openFileInputStream(filename), custom));
        		receiver.send(ConfigHelper.CUSTOM_PROVIDER_ADDED, Bundle.EMPTY);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if ((task = task_for.getBundleExtra(ConfigHelper.srpRegister)) != null) {
			if(!registerWithSRP(task))
				receiver.send(ConfigHelper.SRP_REGISTRATION_FAILED, Bundle.EMPTY);
			else
				receiver.send(ConfigHelper.SRP_REGISTRATION_SUCCESSFUL, Bundle.EMPTY);
		}
		else if ((task = task_for.getBundleExtra(ConfigHelper.srpAuth)) != null) {
			if(!authenticateBySRP(task))
				receiver.send(ConfigHelper.SRP_AUTHENTICATION_FAILED, Bundle.EMPTY);
			else
				receiver.send(ConfigHelper.SRP_AUTHENTICATION_SUCCESSFUL, Bundle.EMPTY);
		}
	}

	private boolean downloadJsonFiles(Bundle task) {
		String cert_url = (String) task.get(ConfigHelper.cert_key);
		String eip_service_json_url = (String) task.get(ConfigHelper.eip_service_key);
		try {
			String cert_string = getStringFromProvider(cert_url);
			JSONObject cert_json = new JSONObject("{ \"certificate\" : \"" + cert_string + "\"}");
			ConfigHelper.saveSharedPref(ConfigHelper.cert_key, cert_json);
			JSONObject eip_service_json = getJSONFromProvider(eip_service_json_url);
			ConfigHelper.saveSharedPref(ConfigHelper.eip_service_key, eip_service_json);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			ConfigHelper.rescueJSONException(e);
			return false;
		} catch(Exception e) {
			e.printStackTrace();
			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.srp_server_url_key);
		
		BigInteger ng_1024 = new BigInteger(ConfigHelper.NG_1024, 16);
		BigInteger salt = ng_1024.probablePrime(1024, null);
		byte[] salt_in_bytes = salt.toByteArray();
		
		SRP6VerifierGenerator verifier_generator = new SRP6VerifierGenerator();
		verifier_generator.init(ng_1024, ConfigHelper.g, new SHA256Digest());
		BigInteger verifier = verifier_generator.generateVerifier(salt_in_bytes, username.getBytes(), password.getBytes());
		
		return sendRegisterMessage(authentication_server, salt.toString(16), verifier.toString(), username);
	}
	
	private boolean sendRegisterMessage(String server_url, String password_salt, String password_verifier, String login) {
		DefaultHttpClient client = new LeapHttpClient(getApplicationContext());
		String parameter_chain = "user[password_salt]" + "=" + password_salt + "&" + "user[password_verifier]" + "=" + password_verifier + "&" + "user[login]" + "=" + login;
		HttpPost post = new HttpPost(server_url + "/users.json" + "?" + parameter_chain);

		HttpResponse getResponse;
		try {
			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.getString("errors").isEmpty()) {
				return false;
			}
			else if(json_response.getString("password_salt").equalsIgnoreCase(password_salt) && json_response.getString("login").equalsIgnoreCase(login))
				return true;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			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;
		}
		
		return false;
	}
	
	private boolean authenticateBySRP(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.srp_server_url_key);
		SRP6Client srp_client = new SRP6Client();
		srp_client.init(new BigInteger(ConfigHelper.NG_1024, 16), ConfigHelper.g, new SHA256Digest(), new SecureRandom());
		// Receive salt from server
		Random random_number_generator = new Random();
		BigInteger ng_1024 = new BigInteger(ConfigHelper.NG_1024, 16);
		byte[] salt_in_bytes = ng_1024.probablePrime(1024, null).toByteArray();
		//int salt = random_number_generator.nextInt(Integer.parseInt(ConfigHelper.NG_1024, 16));
		//byte[] salt_in_bytes = ByteBuffer.allocate(4).putInt(salt).array();
		BigInteger clientA = srp_client.generateClientCredentials(salt_in_bytes, username.getBytes(), password.getBytes());
		//Send A to the server. Doing a http response with cookies?
		//Receive server generated serverB
		try {
			BigInteger serverB = sendAToSRPServer(authentication_server, username, clientA);
			if(serverB == BigInteger.ZERO)
				return false; // TODO Show error: error trying to start authentication with provider
			BigInteger s = srp_client.calculateSecret(serverB);
			MessageDigest digest_of_S = MessageDigest.getInstance("SHA-256");
			digest_of_S.update(s.toByteArray(), 0, s.toByteArray().length);
			BigInteger k = new BigInteger(digest_of_S.digest());
			BigInteger m1 = generateM1(k, clientA, serverB, username);
			BigInteger m2 = sendM1ToSRPServer(authentication_server, "M1", m1);
			if(m2 == BigInteger.ZERO)
				return false; // TODO Show error: error in M1
			boolean verified = verifyM2(m2, k, clientA, serverB, username);
			return verified; // TODO If false, Username or password are not correct -> Show a warning and get back to login fragment
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// From sendAToSRPServer or from sendM1ToSRPServer
			e.printStackTrace();
			return false;
		} catch (CryptoException e) {
			// TODO Auto-generated catch block
			// From calculateSecret
			e.printStackTrace();
			return false;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			// From MessageDigest.getInstance
			e.printStackTrace();
			return false;
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	private BigInteger generateM1(BigInteger K, BigInteger clientA, BigInteger serverB, String username) throws NoSuchAlgorithmException {
		/* https://github.com/leapcode/srp_js/blob/master/src/srp_session.js
		var hashN = SHA256(hex2a(N.toString(16)))
			    var hashG = SHA256(hex2a(g.toString(16)))
			    var hexString = hexXor(hashN, hashG);
			    hexString += SHA256(I);
			    hexString += salt;
			    hexString += Astr;
			    hexString += Bstr;
			    hexString += K
			    M = SHA256(hex2a(hexString));
			    //M2 = H(A, M, K)
			    M2 = SHA256(hex2a(Astr + M + K));
		*/
		String digest_of_N_as_string = new BigInteger(MessageDigest.getInstance("SHA-256").digest(ConfigHelper.NG_1024.getBytes())).toString(16);
		
		String digest_of_G_as_string = new BigInteger(1, MessageDigest.getInstance("SHA-256").digest(ConfigHelper.g.toString(16).getBytes())).toString(16);
		//String digest_of_G_as_string = new BigInteger(MessageDigest.getInstance("SHA-256").digest(ConfigHelper.g.toByteArray())).toString(16);
		
		String xor_n_and_g = hexXor(digest_of_N_as_string, digest_of_G_as_string);
		
		String digest_of_username_as_string = new BigInteger(MessageDigest.getInstance("SHA-256").digest(username.getBytes())).toString(16);
		
		String m1_source_string = xor_n_and_g + digest_of_username_as_string + clientA.toString(16) + serverB.toString(16) + K.toString(16);
		
		return new BigInteger(1, MessageDigest.getInstance("SHA-256").digest(m1_source_string.getBytes()));
	}

	private boolean verifyM2(BigInteger M2, BigInteger K, BigInteger clientA, BigInteger serverB, String username) throws NoSuchAlgorithmException {
		/* https://github.com/leapcode/srp_js/blob/master/src/srp_session.js
		var hashN = SHA256(hex2a(N.toString(16)))
			    var hashG = SHA256(hex2a(g.toString(16)))
			    var hexString = hexXor(hashN, hashG);
			    hexString += SHA256(I);
			    hexString += salt;
			    hexString += Astr;
			    hexString += Bstr;
			    hexString += K
			    M = SHA256(hex2a(hexString));
			    //M2 = H(A, M, K)
			    M2 = SHA256(hex2a(Astr + M + K));
		*/
		MessageDigest digest_of_N = MessageDigest.getInstance("SHA-256");
		digest_of_N.update(ConfigHelper.NG_1024.getBytes());
		String digest_of_N_as_string = new BigInteger(digest_of_N.digest()).toString();
		
		MessageDigest digest_of_G = MessageDigest.getInstance("SHA-256");
		digest_of_G.update(ConfigHelper.g.toByteArray());
		String digest_of_G_as_string = new BigInteger(digest_of_G.digest()).toString();
		
		String xor_n_and_g = hexXor(digest_of_N_as_string, digest_of_G_as_string);
		
		MessageDigest digest_of_username = MessageDigest.getInstance("SHA-256");
		digest_of_username.update(username.getBytes());
		String digest_of_username_as_string = new BigInteger(digest_of_username.digest()).toString();
		
		MessageDigest my_M1 = MessageDigest.getInstance("SHA-256");
		String m1_source_string = xor_n_and_g + digest_of_username_as_string + clientA.toString() + serverB.toString() + K.toString();
		my_M1.update(m1_source_string.getBytes());
		
		MessageDigest my_own_M2 = MessageDigest.getInstance("SHA-256");
		String m2_source_string = clientA.toString() + new BigInteger(my_M1.digest()).toString() + K.toString();
		
		my_own_M2.update(m2_source_string.getBytes());
		
		return M2 == new BigInteger(my_own_M2.digest());
	}

	private String hexXor(String a, String b) {
	    String str = "";
	    for (int i = 0; i < a.length(); i += 2) {
	      int xor = Integer.parseInt(a.substring(i, 2 + i), 16) ^ Integer.parseInt(b.substring(i, 2 + i), 16);
	      String xor_string = String.valueOf(Integer.valueOf(String.valueOf(xor), 16));
	      str += (xor_string.length() == 1) ? ("0" + xor) : xor_string;
	    }
	    return stringToHex(str);
	  }
	
	private String stringToHex(String base)
    {
     StringBuffer buffer = new StringBuffer();
     int intValue;
     for(int x = 0; x < base.length(); x++)
         {
         int cursor = 0;
         intValue = base.charAt(x);
         String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
         for(int i = 0; i < binaryChar.length(); i++)
             {
             if(binaryChar.charAt(i) == '1')
                 {
                 cursor += 1;
             }
         }
         if((cursor % 2) > 0)
             {
             intValue += 128;
         }
         buffer.append(Integer.toHexString(intValue) + "");
     }
     return buffer.toString().toUpperCase();
}

	private BigInteger sendAToSRPServer(String server_url, String username, BigInteger clientA) throws ClientProtocolException, IOException, NumberFormatException, JSONException {
		DefaultHttpClient client = new LeapHttpClient(getApplicationContext());
		String parameter_chain = "A" + "=" + clientA.toString() + "&" + "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")) {
			return BigInteger.ZERO;
		}
		List<Cookie> cookies = client.getCookieStore().getCookies();
		if(!cookies.isEmpty()) {
			String session_id = cookies.get(0).getValue();
		}
		return new BigInteger(json_response.getString("B"), 16);
	}
	private BigInteger sendM1ToSRPServer(String server_url, String parameter_name, BigInteger parameter) throws ClientProtocolException, IOException, JSONException {
		DefaultHttpClient client = new LeapHttpClient(getApplicationContext());
		String parameter_chain = parameter_name + "=" + parameter.toString();
		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 BigInteger.ZERO;
		}
		
		List<Cookie> cookies = client.getCookieStore().getCookies();
		String session_id = cookies.get(0).getValue();
		return new BigInteger(json_response.getString("M2"), 16);
	}

	private String guessURL(String provider_main_url) {
		return provider_main_url + "/provider.json";
	}

	private String getStringFromProvider(String string_url) throws IOException {
		
		String json_file_content = "";
		
		DefaultHttpClient client = new LeapHttpClient(getApplicationContext());
		HttpGet get = new HttpGet(string_url);
		// Execute the GET call and obtain the response
		HttpResponse getResponse = client.execute(get);
		HttpEntity responseEntity = getResponse.getEntity();
		
		json_file_content = new Scanner(responseEntity.getContent()).useDelimiter("\\A").next();
		
		return json_file_content;
	}
	private JSONObject getJSONFromProvider(String json_url) throws IOException, JSONException {
		String json_file_content = getStringFromProvider(json_url);
		return new JSONObject(json_file_content);
	}
}