5 import java.util.Arrays;
7 import javax.crypto.spec.*;
8 import java.security.SecureRandom;
10 import java.nio.charset.StandardCharsets;
11 import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator;
12 import org.spongycastle.crypto.digests.SHA256Digest;
13 import org.spongycastle.crypto.params.KeyParameter;
14 import org.spongycastle.crypto.PBEParametersGenerator;
15 import android.content.*;
16 import java.nio.ByteBuffer;
20 * This class provides a communication API to the webserver. It also
21 * validates the HMACs on the slots and handles encryption.
22 * @author Brian Demsky <bdemsky@uci.edu>
28 private static final int SALT_SIZE = 8;
29 private static final int TIMEOUT_MILLIS = 2000; // 100
30 public static final int IV_SIZE = 16;
32 /** Sets the size for the HMAC. */
33 static final int HMAC_SIZE = 32;
35 private String baseurl;
36 private SecretKeySpec key;
38 private String password;
39 private SecureRandom random;
42 private int listeningPort = -1;
43 private Thread localServerThread = null;
44 private boolean doEnd = false;
46 private TimingSingleton timer = null;
48 private Context context;
54 * Empty Constructor needed for child class.
57 timer = TimingSingleton.getInstance();
60 private void deleteFile(Context context) {
61 File fd = context.getFileStreamPath("config.txt");
66 private void writeToFile(byte[] data,Context context) {
68 // OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
69 // outputStreamWriter.write(data);
70 // outputStreamWriter.close();
72 FileOutputStream outputStreamWriter = context.openFileOutput("config.txt", Context.MODE_PRIVATE);
73 outputStreamWriter.write(data);
74 outputStreamWriter.close();
77 catch (IOException e) {
78 Log.e("Exception", "File write failed: " + e.toString());
82 private byte[] readFromFile(Context context) throws FileNotFoundException {
87 InputStream inputStream = context.openFileInput("config.txt");
89 if ( inputStream != null ) {
92 ret1 = new byte[inputStream.available()];
93 for(int i = 0; i < ret1.length;i++)
95 ret1[i] = (byte)inputStream.read();
101 // InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
102 // BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
103 // String receiveString = "";
104 // StringBuilder stringBuilder = new StringBuilder();
106 // while ( (receiveString = bufferedReader.readLine()) != null ) {
107 // stringBuilder.append(receiveString);
111 // ret = stringBuilder.toString();
114 catch (FileNotFoundException e) {
115 Log.e("login activity", "File not found: " + e.toString());
118 } catch (IOException e) {
119 Log.e("login activity", "Can not read file: " + e.toString());
128 * Constructor for actual use. Takes in the url and password.
130 CloudComm(Table _table, String _baseurl, String _password, int _listeningPort, Context _context) {
131 timer = TimingSingleton.getInstance();
133 this.baseurl = _baseurl;
134 this.password = _password;
135 this.random = new SecureRandom();
136 this.listeningPort = _listeningPort;
137 this.context = _context;
140 if (this.listeningPort > 0) {
141 localServerThread = new Thread(new Runnable() {
143 localServerWorkerFunction();
146 localServerThread.start();
151 * Generates Key from password.
153 private SecretKeySpec initKey() {
156 Log.e("Ali:::::", "KEY KEY KEY......");
160 boolean doCrypt = false;
162 byte[] keySaved = null;
165 // String file = readFromFile(context);
166 byte[] dat = readFromFile(context);//file.getBytes();
168 boolean saltMatch = true;
169 for(int i = 0; i < salt.length; i++)
172 Log.e("ALIasdasdaS:", " " + ((int) salt[i] & 255) + " " + ((int) dat[i] & 255));
174 if(dat[i] != salt[i])
183 keySaved = new byte[dat.length - salt.length];
184 for(int i = salt.length; i < dat.length;i++)
186 keySaved[i-salt.length] = dat[i];
192 Log.e("Ali:::::", "Salt No Match......");
209 Log.e("Ali:::::", "Doing Crypt......");
210 PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
211 generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toCharArray()), salt, 65536);
212 KeyParameter key = (KeyParameter) generator.generateDerivedMacParameters(128);
215 // PBEKeySpec keyspec = new PBEKeySpec(password.toCharArray(),
219 // SecretKey tmpkey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(keyspec);
220 // SecretKey tmpkey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keyspec);
223 // return new SecretKeySpec(tmpkey.getEncoded(), "AES");
226 byte[] keyDat = key.getKey();
227 byte[] saveDat = new byte[salt.length + keyDat.length];
229 for (int i = 0 ; i < salt.length;i++)
231 saveDat[i] = salt[i];
234 for (int i = 0 ; i < keyDat.length;i++)
236 saveDat[i + salt.length] = keyDat[i];
241 writeToFile(saveDat, context);
243 return new SecretKeySpec(key.getKey(), "AES");
247 Log.e("Ali:::::", "Using Saved......");
249 return new SecretKeySpec(keySaved, "AES");
253 } catch (Exception e) {
254 StringWriter sw = new StringWriter();
255 PrintWriter pw = new PrintWriter(sw);
256 e.printStackTrace(pw);
257 // stack trace as a string
260 throw new Error("Failed generating key. " + sw.toString());
265 * Inits all the security stuff
267 public void initSecurity() throws ServerException {
268 // try to get the salt and if one does not exist set one
278 * Inits the HMAC generator.
281 * Inits the HMAC generator.
283 private void initCrypt() {
285 if (password == null) {
291 password = null; // drop password
292 mac = Mac.getInstance("HmacSHA256");
294 } catch (Exception e) {
296 throw new Error("Failed To Initialize Ciphers");
302 * Builds the URL for the given request.
304 private URL buildRequest(boolean isput, long sequencenumber, long maxentries) throws IOException {
305 String reqstring = isput ? "req=putslot" : "req=getslot";
306 String urlstr = baseurl + "?" + reqstring + "&seq=" + sequencenumber;
308 urlstr += "&max=" + maxentries;
309 return new URL(urlstr);
312 private void setSalt() throws ServerException {
315 // Salt already sent to server so dont set it again
320 byte[] saltTmp = new byte[SALT_SIZE];
321 random.nextBytes(saltTmp);
323 URL url = new URL(baseurl + "?req=setsalt");
326 URLConnection con = url.openConnection();
327 HttpURLConnection http = (HttpURLConnection) con;
329 http.setRequestMethod("POST");
330 http.setFixedLengthStreamingMode(saltTmp.length);
331 http.setDoOutput(true);
332 http.setConnectTimeout(TIMEOUT_MILLIS);
337 OutputStream os = http.getOutputStream();
341 int responsecode = http.getResponseCode();
342 if (responsecode != HttpURLConnection.HTTP_OK) {
343 // TODO: Remove this print
344 System.out.println(responsecode);
345 throw new Error("Invalid response");
351 } catch (Exception e) {
352 // e.printStackTrace();
354 throw new ServerException("Failed setting salt", ServerException.TypeConnectTimeout);
358 private boolean getSalt() throws ServerException {
360 URLConnection con = null;
361 HttpURLConnection http = null;
364 url = new URL(baseurl + "?req=getsalt");
365 } catch (Exception e) {
366 // e.printStackTrace();
367 throw new Error("getSlot failed");
372 con = url.openConnection();
373 http = (HttpURLConnection) con;
374 http.setRequestMethod("POST");
375 http.setConnectTimeout(TIMEOUT_MILLIS);
376 http.setReadTimeout(TIMEOUT_MILLIS);
383 } catch (SocketTimeoutException e) {
385 throw new ServerException("getSalt failed", ServerException.TypeConnectTimeout);
386 } catch (Exception e) {
387 // e.printStackTrace();
388 throw new Error("getSlot failed " + e.toString());
395 int responsecode = http.getResponseCode();
396 if (responsecode != HttpURLConnection.HTTP_OK) {
397 // TODO: Remove this print
398 // System.out.println(responsecode);
399 throw new Error("Invalid response");
402 // Log.e("Aaaaa", "Code " + responsecode);
405 InputStream is = http.getInputStream();
408 // BufferedReader rd= new BufferedReader(new InputStreamReader(is));
410 // StringBuilder sb= new StringBuilder();
411 // while ((line = rd.read())!= -1)
413 // sb.append((char)line);
414 // Log.e("Aaaaa", "line " + line);
419 // int sdfsdfds = (int)sb.toString().charAt(0);
420 // Log.e("Aaaaa", "length " + (int)sb.toString().charAt(0));
421 // Log.e("Aaaaa", "Res " + sb.toString().length());
424 // is = new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8));
427 // if (is.available() > 0) {
428 // if (sb.toString().length() > 0) {
432 DataInputStream dis = new DataInputStream(is);
433 int salt_length = dis.readInt();
434 byte[] tmp = new byte[salt_length];
435 // byte [] tmp = new byte[8];
439 for (int i = 0; i < 8; i++) {
440 Log.e("ALIasdasdaS:", "asd " + ((int) salt[i] & 255));
452 Log.e("Aaaaa", "Salt No Data");
462 } catch (SocketTimeoutException e) {
465 throw new ServerException("getSalt failed", ServerException.TypeInputTimeout);
466 } catch (Exception e) {
468 throw new Error("getSlot failed + " + e);
473 private byte[] createIV(long machineId, long localSequenceNumber) {
474 ByteBuffer buffer = ByteBuffer.allocate(IV_SIZE);
475 buffer.putLong(machineId);
476 long localSequenceNumberShifted = localSequenceNumber << 16;
477 buffer.putLong(localSequenceNumberShifted);
478 return buffer.array();
482 private byte[] encryptSlotAndPrependIV(byte[] rawData, byte[] ivBytes) {
484 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
485 Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
486 cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
488 byte[] encryptedBytes = cipher.doFinal(rawData);
490 byte[] bytes = new byte[encryptedBytes.length + IV_SIZE];
491 System.arraycopy(ivBytes, 0, bytes, 0, ivBytes.length);
492 System.arraycopy(encryptedBytes, 0, bytes, IV_SIZE, encryptedBytes.length);
496 } catch (Exception e) {
498 throw new Error("Failed To Encrypt");
503 private byte[] stripIVAndDecryptSlot(byte[] rawData) {
505 byte[] ivBytes = new byte[IV_SIZE];
506 byte[] encryptedBytes = new byte[rawData.length - IV_SIZE];
507 System.arraycopy(rawData, 0, ivBytes, 0, IV_SIZE);
508 System.arraycopy(rawData, IV_SIZE, encryptedBytes, 0 , encryptedBytes.length);
510 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
512 Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
513 cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
515 return cipher.doFinal(encryptedBytes);
517 } catch (Exception e) {
519 throw new Error("Failed To Decrypt");
524 * API for putting a slot into the queue. Returns null on success.
525 * On failure, the server will send slots with newer sequence
528 public Slot[] putSlot(Slot slot, int max) throws ServerException {
530 URLConnection con = null;
531 HttpURLConnection http = null;
536 throw new ServerException("putSlot failed", ServerException.TypeSalt);
540 long sequencenumber = slot.getSequenceNumber();
541 byte[] slotBytes = slot.encode(mac);
542 // slotBytes = encryptCipher.doFinal(slotBytes);
544 // byte[] iVBytes = slot.getSlotCryptIV();
546 // byte[] bytes = new byte[slotBytes.length + IV_SIZE];
547 // System.arraycopy(iVBytes, 0, bytes, 0, iVBytes.length);
548 // System.arraycopy(slotBytes, 0, bytes, IV_SIZE, slotBytes.length);
551 byte[] bytes = encryptSlotAndPrependIV(slotBytes, slot.getSlotCryptIV());
555 url = buildRequest(true, sequencenumber, max);
558 con = url.openConnection();
559 http = (HttpURLConnection) con;
561 http.setRequestMethod("POST");
562 http.setFixedLengthStreamingMode(bytes.length);
563 http.setDoOutput(true);
564 http.setConnectTimeout(TIMEOUT_MILLIS);
565 http.setReadTimeout(TIMEOUT_MILLIS);
568 OutputStream os = http.getOutputStream();
575 // System.out.println("Bytes Sent: " + bytes.length);
576 } catch (ServerException e) {
580 } catch (SocketTimeoutException e) {
583 throw new ServerException("putSlot failed", ServerException.TypeConnectTimeout);
584 } catch (Exception e) {
585 // e.printStackTrace();
586 throw new Error("putSlot failed");
593 InputStream is = http.getInputStream();
594 DataInputStream dis = new DataInputStream(is);
595 byte[] resptype = new byte[7];
596 dis.readFully(resptype);
599 if (Arrays.equals(resptype, "getslot".getBytes()))
601 return processSlots(dis);
603 else if (Arrays.equals(resptype, "putslot".getBytes()))
608 throw new Error("Bad response to putslot");
610 } catch (SocketTimeoutException e) {
612 throw new ServerException("putSlot failed", ServerException.TypeInputTimeout);
613 } catch (Exception e) {
614 // e.printStackTrace();
615 throw new Error("putSlot failed");
620 * Request the server to send all slots with the given
621 * sequencenumber or newer.
623 public Slot[] getSlots(long sequencenumber) throws ServerException {
625 URLConnection con = null;
626 HttpURLConnection http = null;
631 throw new ServerException("getSlots failed", ServerException.TypeSalt);
636 url = buildRequest(false, sequencenumber, 0);
638 con = url.openConnection();
639 http = (HttpURLConnection) con;
640 http.setRequestMethod("POST");
641 http.setConnectTimeout(TIMEOUT_MILLIS);
642 http.setReadTimeout(TIMEOUT_MILLIS);
649 } catch (SocketTimeoutException e) {
652 throw new ServerException("getSlots failed", ServerException.TypeConnectTimeout);
653 } catch (ServerException e) {
657 } catch (Exception e) {
658 // e.printStackTrace();
659 throw new Error("getSlots failed " + e.toString());
665 InputStream is = http.getInputStream();
666 DataInputStream dis = new DataInputStream(is);
667 byte[] resptype = new byte[7];
669 dis.readFully(resptype);
672 if (!Arrays.equals(resptype, "getslot".getBytes()))
673 throw new Error("Bad Response: " + new String(resptype));
675 return processSlots(dis);
676 } catch (SocketTimeoutException e) {
679 throw new ServerException("getSlots failed", ServerException.TypeInputTimeout);
680 } catch (Exception e) {
681 // e.printStackTrace();
682 StringWriter sw = new StringWriter();
683 PrintWriter pw = new PrintWriter(sw);
684 e.printStackTrace(pw);
685 throw new Error("getSlots failed " + sw.toString());
690 * Method that actually handles building Slot objects from the
691 * server response. Shared by both putSlot and getSlots.
693 private Slot[] processSlots(DataInputStream dis) throws Exception {
694 int numberofslots = dis.readInt();
695 int[] sizesofslots = new int[numberofslots];
697 Slot[] slots = new Slot[numberofslots];
698 for (int i = 0; i < numberofslots; i++)
699 sizesofslots[i] = dis.readInt();
701 for (int i = 0; i < numberofslots; i++) {
703 byte[] rawData = new byte[sizesofslots[i]];
704 dis.readFully(rawData);
707 // byte[] data = new byte[rawData.length - IV_SIZE];
708 // System.arraycopy(rawData, IV_SIZE, data, 0, data.length);
711 byte[] data = stripIVAndDecryptSlot(rawData);
713 slots[i] = Slot.decode(table, data, mac);
715 Log.e("Ali::::", "Slot Process");
721 public byte[] sendLocalData(byte[] sendData, long localSequenceNumber, String host, int port) {
728 System.out.println("Passing Locally");
730 mac.update(sendData);
731 byte[] genmac = mac.doFinal();
732 byte[] totalData = new byte[sendData.length + genmac.length];
733 System.arraycopy(sendData, 0, totalData, 0, sendData.length);
734 System.arraycopy(genmac, 0, totalData, sendData.length, genmac.length);
736 // Encrypt the data for sending
737 // byte[] encryptedData = encryptCipher.doFinal(totalData);
738 // byte[] encryptedData = encryptCipher.doFinal(totalData);
740 byte[] iv = createIV(table.getMachineId(), table.getLocalSequenceNumber());
741 byte[] encryptedData = encryptSlotAndPrependIV(totalData, iv);
745 // Open a TCP socket connection to a local device
746 Socket socket = new Socket(host, port);
747 socket.setReuseAddress(true);
748 DataOutputStream output = new DataOutputStream(socket.getOutputStream());
749 DataInputStream input = new DataInputStream(socket.getInputStream());
753 // Send data to output (length of data, the data)
754 output.writeInt(encryptedData.length);
755 output.write(encryptedData, 0, encryptedData.length);
758 int lengthOfReturnData = input.readInt();
759 byte[] returnData = new byte[lengthOfReturnData];
760 input.readFully(returnData);
764 // returnData = decryptCipher.doFinal(returnData);
765 returnData = stripIVAndDecryptSlot(returnData);
767 // We are done with this socket
770 mac.update(returnData, 0, returnData.length - HMAC_SIZE);
771 byte[] realmac = mac.doFinal();
772 byte[] recmac = new byte[HMAC_SIZE];
773 System.arraycopy(returnData, returnData.length - realmac.length, recmac, 0, realmac.length);
775 if (!Arrays.equals(recmac, realmac))
776 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
778 byte[] returnData2 = new byte[lengthOfReturnData - recmac.length];
779 System.arraycopy(returnData, 0, returnData2, 0, returnData2.length);
782 } catch (Exception e) {
784 // throw new Error("Local comms failure...");
791 private void localServerWorkerFunction() {
793 ServerSocket inputSocket = null;
796 // Local server socket
797 inputSocket = new ServerSocket(listeningPort);
798 inputSocket.setReuseAddress(true);
799 inputSocket.setSoTimeout(TIMEOUT_MILLIS);
800 } catch (Exception e) {
802 throw new Error("Local server setup failure...");
808 // Accept incoming socket
809 Socket socket = inputSocket.accept();
811 DataInputStream input = new DataInputStream(socket.getInputStream());
812 DataOutputStream output = new DataOutputStream(socket.getOutputStream());
814 // Get the encrypted data from the server
815 int dataSize = input.readInt();
816 byte[] readData = new byte[dataSize];
817 input.readFully(readData);
822 // readData = decryptCipher.doFinal(readData);
823 readData = stripIVAndDecryptSlot(readData);
826 mac.update(readData, 0, readData.length - HMAC_SIZE);
827 byte[] genmac = mac.doFinal();
828 byte[] recmac = new byte[HMAC_SIZE];
829 System.arraycopy(readData, readData.length - recmac.length, recmac, 0, recmac.length);
831 if (!Arrays.equals(recmac, genmac))
832 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
834 byte[] returnData = new byte[readData.length - recmac.length];
835 System.arraycopy(readData, 0, returnData, 0, returnData.length);
838 // byte[] sendData = table.acceptDataFromLocal(readData);
839 byte[] sendData = table.acceptDataFromLocal(returnData);
841 mac.update(sendData);
842 byte[] realmac = mac.doFinal();
843 byte[] totalData = new byte[sendData.length + realmac.length];
844 System.arraycopy(sendData, 0, totalData, 0, sendData.length);
845 System.arraycopy(realmac, 0, totalData, sendData.length, realmac.length);
847 // Encrypt the data for sending
848 // byte[] encryptedData = encryptCipher.doFinal(totalData);
849 byte[] iv = createIV(table.getMachineId(), table.getLocalSequenceNumber());
850 byte[] encryptedData = encryptSlotAndPrependIV(totalData, iv);
854 // Send data to output (length of data, the data)
855 output.writeInt(encryptedData.length);
856 output.write(encryptedData, 0, encryptedData.length);
861 } catch (Exception e) {
863 // throw new Error("Local comms failure...");
868 if (inputSocket != null) {
871 } catch (Exception e) {
873 throw new Error("Local server close failure...");
878 public void close() {
881 if (localServerThread != null) {
883 localServerThread.join();
884 } catch (Exception e) {
886 throw new Error("Local Server thread join issue...");
890 // System.out.println("Done Closing Cloud Comm");
893 protected void finalize() throws Throwable {
895 close(); // close open files