5 import java.util.Arrays;
7 import javax.crypto.spec.*;
8 import java.security.SecureRandom;
9 import java.nio.ByteBuffer;
12 * This class provides a communication API to the webserver. It also
13 * validates the HMACs on the slots and handles encryption.
14 * @author Brian Demsky <bdemsky@uci.edu>
20 private static final int SALT_SIZE = 8;
21 private static final int TIMEOUT_MILLIS = 2000; // 100
22 public static final int IV_SIZE = 16;
24 /** Sets the size for the HMAC. */
25 static final int HMAC_SIZE = 32;
27 private String baseurl;
28 private SecretKeySpec key;
30 private String password;
31 private SecureRandom random;
34 private int listeningPort = -1;
35 private Thread localServerThread = null;
36 private boolean doEnd = false;
38 private TimingSingleton timer = null;
41 * Empty Constructor needed for child class.
44 timer = TimingSingleton.getInstance();
48 * Constructor for actual use. Takes in the url and password.
50 CloudComm(Table _table, String _baseurl, String _password, int _listeningPort) {
51 timer = TimingSingleton.getInstance();
53 this.baseurl = _baseurl;
54 this.password = _password;
55 this.random = new SecureRandom();
56 this.listeningPort = _listeningPort;
58 if (this.listeningPort > 0) {
59 localServerThread = new Thread(new Runnable() {
61 localServerWorkerFunction();
64 localServerThread.start();
69 * Generates Key from password.
71 private SecretKeySpec initKey() {
73 PBEKeySpec keyspec = new PBEKeySpec(password.toCharArray(),
77 SecretKey tmpkey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keyspec);
78 return new SecretKeySpec(tmpkey.getEncoded(), "AES");
79 } catch (Exception e) {
81 throw new Error("Failed generating key.");
86 * Inits all the security stuff
88 public void initSecurity() throws ServerException {
89 // try to get the salt and if one does not exist set one
99 * Inits the HMAC generator.
101 private void initCrypt() {
103 if (password == null) {
109 password = null; // drop password
110 mac = Mac.getInstance("HmacSHA256");
112 } catch (Exception e) {
114 throw new Error("Failed To Initialize Ciphers");
119 * Builds the URL for the given request.
121 private URL buildRequest(boolean isput, long sequencenumber, long maxentries) throws IOException {
122 String reqstring = isput ? "req=putslot" : "req=getslot";
123 String urlstr = baseurl + "?" + reqstring + "&seq=" + sequencenumber;
125 urlstr += "&max=" + maxentries;
126 return new URL(urlstr);
129 private void setSalt() throws ServerException {
132 // Salt already sent to server so dont set it again
137 byte[] saltTmp = new byte[SALT_SIZE];
138 random.nextBytes(saltTmp);
140 for (int i = 0; i < SALT_SIZE; i++) {
141 System.out.println((int)saltTmp[i] & 255);
145 URL url = new URL(baseurl + "?req=setsalt");
148 URLConnection con = url.openConnection();
149 HttpURLConnection http = (HttpURLConnection) con;
151 http.setRequestMethod("POST");
152 http.setFixedLengthStreamingMode(saltTmp.length);
153 http.setDoOutput(true);
154 http.setConnectTimeout(TIMEOUT_MILLIS);
159 OutputStream os = http.getOutputStream();
163 int responsecode = http.getResponseCode();
164 if (responsecode != HttpURLConnection.HTTP_OK) {
165 // TODO: Remove this print
166 System.out.println(responsecode);
167 throw new Error("Invalid response");
173 } catch (Exception e) {
174 // e.printStackTrace();
176 throw new ServerException("Failed setting salt", ServerException.TypeConnectTimeout);
180 private boolean getSalt() throws ServerException {
182 URLConnection con = null;
183 HttpURLConnection http = null;
186 url = new URL(baseurl + "?req=getsalt");
187 } catch (Exception e) {
188 // e.printStackTrace();
189 throw new Error("getSlot failed");
194 con = url.openConnection();
195 http = (HttpURLConnection) con;
196 http.setRequestMethod("POST");
197 http.setConnectTimeout(TIMEOUT_MILLIS);
198 http.setReadTimeout(TIMEOUT_MILLIS);
203 } catch (SocketTimeoutException e) {
205 throw new ServerException("getSalt failed", ServerException.TypeConnectTimeout);
206 } catch (Exception e) {
207 // e.printStackTrace();
208 throw new Error("getSlot failed");
215 int responsecode = http.getResponseCode();
216 if (responsecode != HttpURLConnection.HTTP_OK) {
217 // TODO: Remove this print
218 // System.out.println(responsecode);
219 throw new Error("Invalid response");
222 InputStream is = http.getInputStream();
223 if (is.available() > 0) {
224 DataInputStream dis = new DataInputStream(is);
225 int salt_length = dis.readInt();
226 byte [] tmp = new byte[salt_length];
237 } catch (SocketTimeoutException e) {
240 throw new ServerException("getSalt failed", ServerException.TypeInputTimeout);
241 } catch (Exception e) {
242 // e.printStackTrace();
243 throw new Error("getSlot failed");
247 private byte[] createIV(long machineId, long localSequenceNumber) {
248 ByteBuffer buffer = ByteBuffer.allocate(IV_SIZE);
249 buffer.putLong(machineId);
250 buffer.putLong(localSequenceNumber);
251 return buffer.array();
255 private byte[] encryptSlotAndPrependIV(byte[] rawData, byte[] ivBytes) {
257 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
258 Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
259 cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
261 byte[] encryptedBytes = cipher.doFinal(rawData);
263 byte[] bytes = new byte[encryptedBytes.length + IV_SIZE];
264 System.arraycopy(ivBytes, 0, bytes, 0, ivBytes.length);
265 System.arraycopy(encryptedBytes, 0, bytes, IV_SIZE, encryptedBytes.length);
269 } catch (Exception e) {
271 throw new Error("Failed To Encrypt");
276 private byte[] stripIVAndDecryptSlot(byte[] rawData) {
278 byte[] ivBytes = new byte[IV_SIZE];
279 byte[] encryptedBytes = new byte[rawData.length - IV_SIZE];
280 System.arraycopy(rawData, 0, ivBytes, 0, IV_SIZE);
281 System.arraycopy(rawData, IV_SIZE, encryptedBytes, 0 , encryptedBytes.length);
283 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
285 Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
286 cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
288 return cipher.doFinal(encryptedBytes);
290 } catch (Exception e) {
292 throw new Error("Failed To Decrypt");
298 * API for putting a slot into the queue. Returns null on success.
299 * On failure, the server will send slots with newer sequence
302 public Slot[] putSlot(Slot slot, int max) throws ServerException {
304 URLConnection con = null;
305 HttpURLConnection http = null;
310 throw new ServerException("putSlot failed", ServerException.TypeSalt);
315 long sequencenumber = slot.getSequenceNumber();
316 byte[] slotBytes = slot.encode(mac);
317 // slotBytes = encryptCipher.doFinal(slotBytes);
319 // byte[] iVBytes = slot.getSlotCryptIV();
321 // byte[] bytes = new byte[slotBytes.length + IV_SIZE];
322 // System.arraycopy(iVBytes, 0, bytes, 0, iVBytes.length);
323 // System.arraycopy(slotBytes, 0, bytes, IV_SIZE, slotBytes.length);
326 byte[] bytes = encryptSlotAndPrependIV(slotBytes, slot.getSlotCryptIV());
328 url = buildRequest(true, sequencenumber, max);
331 con = url.openConnection();
332 http = (HttpURLConnection) con;
334 http.setRequestMethod("POST");
335 http.setFixedLengthStreamingMode(bytes.length);
336 http.setDoOutput(true);
337 http.setConnectTimeout(TIMEOUT_MILLIS);
338 http.setReadTimeout(TIMEOUT_MILLIS);
341 OutputStream os = http.getOutputStream();
348 // System.out.println("Bytes Sent: " + bytes.length);
349 } catch (ServerException e) {
353 } catch (SocketTimeoutException e) {
356 throw new ServerException("putSlot failed", ServerException.TypeConnectTimeout);
357 } catch (Exception e) {
358 // e.printStackTrace();
359 throw new Error("putSlot failed");
366 InputStream is = http.getInputStream();
367 DataInputStream dis = new DataInputStream(is);
368 byte[] resptype = new byte[7];
369 dis.readFully(resptype);
372 if (Arrays.equals(resptype, "getslot".getBytes())) {
373 return processSlots(dis);
374 } else if (Arrays.equals(resptype, "putslot".getBytes())) {
377 throw new Error("Bad response to putslot");
379 } catch (SocketTimeoutException e) {
381 throw new ServerException("putSlot failed", ServerException.TypeInputTimeout);
382 } catch (Exception e) {
383 // e.printStackTrace();
384 throw new Error("putSlot failed");
389 * Request the server to send all slots with the given
390 * sequencenumber or newer.
392 public Slot[] getSlots(long sequencenumber) throws ServerException {
394 URLConnection con = null;
395 HttpURLConnection http = null;
400 throw new ServerException("getSlots failed", ServerException.TypeSalt);
405 url = buildRequest(false, sequencenumber, 0);
407 con = url.openConnection();
408 http = (HttpURLConnection) con;
409 http.setRequestMethod("POST");
410 http.setConnectTimeout(TIMEOUT_MILLIS);
411 http.setReadTimeout(TIMEOUT_MILLIS);
418 } catch (SocketTimeoutException e) {
421 throw new ServerException("getSlots failed", ServerException.TypeConnectTimeout);
422 } catch (ServerException e) {
426 } catch (Exception e) {
427 // e.printStackTrace();
428 throw new Error("getSlots failed");
434 InputStream is = http.getInputStream();
435 DataInputStream dis = new DataInputStream(is);
436 byte[] resptype = new byte[7];
438 dis.readFully(resptype);
441 if (!Arrays.equals(resptype, "getslot".getBytes()))
442 throw new Error("Bad Response: " + new String(resptype));
444 return processSlots(dis);
445 } catch (SocketTimeoutException e) {
448 throw new ServerException("getSlots failed", ServerException.TypeInputTimeout);
449 } catch (Exception e) {
450 // e.printStackTrace();
451 throw new Error("getSlots failed");
456 * Method that actually handles building Slot objects from the
457 * server response. Shared by both putSlot and getSlots.
459 private Slot[] processSlots(DataInputStream dis) throws Exception {
460 int numberofslots = dis.readInt();
461 int[] sizesofslots = new int[numberofslots];
463 Slot[] slots = new Slot[numberofslots];
464 for (int i = 0; i < numberofslots; i++)
465 sizesofslots[i] = dis.readInt();
467 for (int i = 0; i < numberofslots; i++) {
469 byte[] rawData = new byte[sizesofslots[i]];
470 dis.readFully(rawData);
473 // byte[] data = new byte[rawData.length - IV_SIZE];
474 // System.arraycopy(rawData, IV_SIZE, data, 0, data.length);
477 byte[] data = stripIVAndDecryptSlot(rawData);
479 // data = decryptCipher.doFinal(data);
481 slots[i] = Slot.decode(table, data, mac);
487 public byte[] sendLocalData(byte[] sendData, long localSequenceNumber, String host, int port) {
493 System.out.println("Passing Locally");
495 mac.update(sendData);
496 byte[] genmac = mac.doFinal();
497 byte[] totalData = new byte[sendData.length + genmac.length];
498 System.arraycopy(sendData, 0, totalData, 0, sendData.length);
499 System.arraycopy(genmac, 0, totalData, sendData.length, genmac.length);
501 // Encrypt the data for sending
502 // byte[] encryptedData = encryptCipher.doFinal(totalData);
503 // byte[] encryptedData = encryptCipher.doFinal(totalData);
504 byte[] iv = createIV(table.getMachineId(), table.getLocalSequenceNumber());
505 byte[] encryptedData = encryptSlotAndPrependIV(totalData, iv);
507 // Open a TCP socket connection to a local device
508 Socket socket = new Socket(host, port);
509 socket.setReuseAddress(true);
510 DataOutputStream output = new DataOutputStream(socket.getOutputStream());
511 DataInputStream input = new DataInputStream(socket.getInputStream());
515 // Send data to output (length of data, the data)
516 output.writeInt(encryptedData.length);
517 output.write(encryptedData, 0, encryptedData.length);
520 int lengthOfReturnData = input.readInt();
521 byte[] returnData = new byte[lengthOfReturnData];
522 input.readFully(returnData);
526 // returnData = decryptCipher.doFinal(returnData);
527 returnData = stripIVAndDecryptSlot(returnData);
528 // returnData = decryptCipher.doFinal(returnData);
530 // We are done with this socket
533 mac.update(returnData, 0, returnData.length - HMAC_SIZE);
534 byte[] realmac = mac.doFinal();
535 byte[] recmac = new byte[HMAC_SIZE];
536 System.arraycopy(returnData, returnData.length - realmac.length, recmac, 0, realmac.length);
538 if (!Arrays.equals(recmac, realmac))
539 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
541 byte[] returnData2 = new byte[lengthOfReturnData - recmac.length];
542 System.arraycopy(returnData, 0, returnData2, 0, returnData2.length);
545 } catch (Exception e) {
547 // throw new Error("Local comms failure...");
554 private void localServerWorkerFunction() {
556 ServerSocket inputSocket = null;
559 // Local server socket
560 inputSocket = new ServerSocket(listeningPort);
561 inputSocket.setReuseAddress(true);
562 inputSocket.setSoTimeout(TIMEOUT_MILLIS);
563 } catch (Exception e) {
565 throw new Error("Local server setup failure...");
571 // Accept incoming socket
572 Socket socket = inputSocket.accept();
574 DataInputStream input = new DataInputStream(socket.getInputStream());
575 DataOutputStream output = new DataOutputStream(socket.getOutputStream());
577 // Get the encrypted data from the server
578 int dataSize = input.readInt();
579 byte[] readData = new byte[dataSize];
580 input.readFully(readData);
585 // readData = decryptCipher.doFinal(readData);
586 readData = stripIVAndDecryptSlot(readData);
588 mac.update(readData, 0, readData.length - HMAC_SIZE);
589 byte[] genmac = mac.doFinal();
590 byte[] recmac = new byte[HMAC_SIZE];
591 System.arraycopy(readData, readData.length - recmac.length, recmac, 0, recmac.length);
593 if (!Arrays.equals(recmac, genmac))
594 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
596 byte[] returnData = new byte[readData.length - recmac.length];
597 System.arraycopy(readData, 0, returnData, 0, returnData.length);
600 // byte[] sendData = table.acceptDataFromLocal(readData);
601 byte[] sendData = table.acceptDataFromLocal(returnData);
604 mac.update(sendData);
605 byte[] realmac = mac.doFinal();
606 byte[] totalData = new byte[sendData.length + realmac.length];
607 System.arraycopy(sendData, 0, totalData, 0, sendData.length);
608 System.arraycopy(realmac, 0, totalData, sendData.length, realmac.length);
610 // Encrypt the data for sending
611 // byte[] encryptedData = encryptCipher.doFinal(totalData);
612 byte[] iv = createIV(table.getMachineId(), table.getLocalSequenceNumber());
613 byte[] encryptedData = encryptSlotAndPrependIV(totalData, iv);
617 // Send data to output (length of data, the data)
618 output.writeInt(encryptedData.length);
619 output.write(encryptedData, 0, encryptedData.length);
624 } catch (Exception e) {
629 if (inputSocket != null) {
632 } catch (Exception e) {
634 throw new Error("Local server close failure...");
639 public void close() {
642 if (localServerThread != null) {
644 localServerThread.join();
645 } catch (Exception e) {
647 throw new Error("Local Server thread join issue...");
651 // System.out.println("Done Closing Cloud Comm");
654 protected void finalize() throws Throwable {
656 close(); // close open files