5 import java.util.Arrays;
7 import javax.crypto.spec.*;
8 import java.security.SecureRandom;
11 * This class provides a communication API to the webserver. It also
12 * validates the HMACs on the slots and handles encryption.
13 * @author Brian Demsky <bdemsky@uci.edu>
19 private static final int SALT_SIZE = 8;
20 private static final int TIMEOUT_MILLIS = 2000; // 100
22 /** Sets the size for the HMAC. */
23 static final int HMAC_SIZE = 32;
25 private String baseurl;
26 private Cipher encryptCipher;
27 private Cipher decryptCipher;
29 private String password;
30 private SecureRandom random;
33 private int listeningPort = -1;
34 private Thread localServerThread = null;
35 private boolean doEnd = false;
37 private TimingSingleton timer = null;
40 * Empty Constructor needed for child class.
43 timer = TimingSingleton.getInstance();
47 * Constructor for actual use. Takes in the url and password.
49 CloudComm(Table _table, String _baseurl, String _password, int _listeningPort) {
50 timer = TimingSingleton.getInstance();
52 this.baseurl = _baseurl;
53 this.password = _password;
54 this.random = new SecureRandom();
55 this.listeningPort = _listeningPort;
57 if (this.listeningPort > 0) {
58 localServerThread = new Thread(new Runnable() {
60 localServerWorkerFunction();
63 localServerThread.start();
68 * Generates Key from password.
70 private SecretKeySpec initKey() {
72 PBEKeySpec keyspec = new PBEKeySpec(password.toCharArray(),
76 SecretKey tmpkey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keyspec);
77 return new SecretKeySpec(tmpkey.getEncoded(), "AES");
78 } catch (Exception e) {
80 throw new Error("Failed generating key.");
85 * Inits all the security stuff
87 public void initSecurity() throws ServerException {
88 // try to get the salt and if one does not exist set one
98 * Inits the HMAC generator.
100 private void initCrypt() {
102 if (password == null) {
107 SecretKeySpec key = initKey();
108 password = null; // drop password
109 mac = Mac.getInstance("HmacSHA256");
111 encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
112 encryptCipher.init(Cipher.ENCRYPT_MODE, key);
113 decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
114 decryptCipher.init(Cipher.DECRYPT_MODE, key);
115 } catch (Exception e) {
117 throw new Error("Failed To Initialize Ciphers");
122 * Builds the URL for the given request.
124 private URL buildRequest(boolean isput, long sequencenumber, long maxentries) throws IOException {
125 String reqstring = isput ? "req=putslot" : "req=getslot";
126 String urlstr = baseurl + "?" + reqstring + "&seq=" + sequencenumber;
128 urlstr += "&max=" + maxentries;
129 return new URL(urlstr);
132 private void setSalt() throws ServerException {
135 // Salt already sent to server so dont set it again
140 byte[] saltTmp = new byte[SALT_SIZE];
141 random.nextBytes(saltTmp);
143 URL url = new URL(baseurl + "?req=setsalt");
146 URLConnection con = url.openConnection();
147 HttpURLConnection http = (HttpURLConnection) con;
149 http.setRequestMethod("POST");
150 http.setFixedLengthStreamingMode(saltTmp.length);
151 http.setDoOutput(true);
152 http.setConnectTimeout(TIMEOUT_MILLIS);
157 OutputStream os = http.getOutputStream();
161 int responsecode = http.getResponseCode();
162 if (responsecode != HttpURLConnection.HTTP_OK) {
163 // TODO: Remove this print
164 System.out.println(responsecode);
165 throw new Error("Invalid response");
171 } catch (Exception e) {
172 // e.printStackTrace();
174 throw new ServerException("Failed setting salt", ServerException.TypeConnectTimeout);
178 private boolean getSalt() throws ServerException {
180 URLConnection con = null;
181 HttpURLConnection http = null;
184 url = new URL(baseurl + "?req=getsalt");
185 } catch (Exception e) {
186 // e.printStackTrace();
187 throw new Error("getSlot failed");
192 con = url.openConnection();
193 http = (HttpURLConnection) con;
194 http.setRequestMethod("POST");
195 http.setConnectTimeout(TIMEOUT_MILLIS);
196 http.setReadTimeout(TIMEOUT_MILLIS);
201 } catch (SocketTimeoutException e) {
203 throw new ServerException("getSalt failed", ServerException.TypeConnectTimeout);
204 } catch (Exception e) {
205 // e.printStackTrace();
206 throw new Error("getSlot failed");
213 int responsecode = http.getResponseCode();
214 if (responsecode != HttpURLConnection.HTTP_OK) {
215 // TODO: Remove this print
216 // System.out.println(responsecode);
217 throw new Error("Invalid response");
220 InputStream is = http.getInputStream();
221 if (is.available() > 0) {
222 DataInputStream dis = new DataInputStream(is);
223 int salt_length = dis.readInt();
224 byte [] tmp = new byte[salt_length];
235 } catch (SocketTimeoutException e) {
238 throw new ServerException("getSalt failed", ServerException.TypeInputTimeout);
239 } catch (Exception e) {
240 // e.printStackTrace();
241 throw new Error("getSlot failed");
246 * API for putting a slot into the queue. Returns null on success.
247 * On failure, the server will send slots with newer sequence
250 public Slot[] putSlot(Slot slot, int max) throws ServerException {
252 URLConnection con = null;
253 HttpURLConnection http = null;
258 throw new ServerException("putSlot failed", ServerException.TypeSalt);
263 long sequencenumber = slot.getSequenceNumber();
264 byte[] bytes = slot.encode(mac);
265 bytes = encryptCipher.doFinal(bytes);
270 url = buildRequest(true, sequencenumber, max);
273 con = url.openConnection();
274 http = (HttpURLConnection) con;
276 http.setRequestMethod("POST");
277 http.setFixedLengthStreamingMode(bytes.length);
278 http.setDoOutput(true);
279 http.setConnectTimeout(TIMEOUT_MILLIS);
280 http.setReadTimeout(TIMEOUT_MILLIS);
283 OutputStream os = http.getOutputStream();
290 // System.out.println("Bytes Sent: " + bytes.length);
291 } catch (ServerException e) {
295 } catch (SocketTimeoutException e) {
298 throw new ServerException("putSlot failed", ServerException.TypeConnectTimeout);
299 } catch (Exception e) {
300 // e.printStackTrace();
301 throw new Error("putSlot failed");
308 InputStream is = http.getInputStream();
309 DataInputStream dis = new DataInputStream(is);
310 byte[] resptype = new byte[7];
311 dis.readFully(resptype);
314 if (Arrays.equals(resptype, "getslot".getBytes()))
316 return processSlots(dis);
318 else if (Arrays.equals(resptype, "putslot".getBytes()))
323 throw new Error("Bad response to putslot");
325 } catch (SocketTimeoutException e) {
327 throw new ServerException("putSlot failed", ServerException.TypeInputTimeout);
328 } catch (Exception e) {
329 // e.printStackTrace();
330 throw new Error("putSlot failed");
335 * Request the server to send all slots with the given
336 * sequencenumber or newer.
338 public Slot[] getSlots(long sequencenumber) throws ServerException {
340 URLConnection con = null;
341 HttpURLConnection http = null;
346 throw new ServerException("getSlots failed", ServerException.TypeSalt);
351 url = buildRequest(false, sequencenumber, 0);
353 con = url.openConnection();
354 http = (HttpURLConnection) con;
355 http.setRequestMethod("POST");
356 http.setConnectTimeout(TIMEOUT_MILLIS);
357 http.setReadTimeout(TIMEOUT_MILLIS);
364 } catch (SocketTimeoutException e) {
367 throw new ServerException("getSlots failed", ServerException.TypeConnectTimeout);
368 } catch (ServerException e) {
372 } catch (Exception e) {
373 // e.printStackTrace();
374 throw new Error("getSlots failed");
380 InputStream is = http.getInputStream();
381 DataInputStream dis = new DataInputStream(is);
382 byte[] resptype = new byte[7];
384 dis.readFully(resptype);
387 if (!Arrays.equals(resptype, "getslot".getBytes()))
388 throw new Error("Bad Response: " + new String(resptype));
390 return processSlots(dis);
391 } catch (SocketTimeoutException e) {
394 throw new ServerException("getSlots failed", ServerException.TypeInputTimeout);
395 } catch (Exception e) {
396 // e.printStackTrace();
397 throw new Error("getSlots failed");
402 * Method that actually handles building Slot objects from the
403 * server response. Shared by both putSlot and getSlots.
405 private Slot[] processSlots(DataInputStream dis) throws Exception {
406 int numberofslots = dis.readInt();
407 int[] sizesofslots = new int[numberofslots];
409 Slot[] slots = new Slot[numberofslots];
410 for (int i = 0; i < numberofslots; i++)
411 sizesofslots[i] = dis.readInt();
413 for (int i = 0; i < numberofslots; i++) {
415 byte[] data = new byte[sizesofslots[i]];
418 data = decryptCipher.doFinal(data);
420 slots[i] = Slot.decode(table, data, mac);
426 public byte[] sendLocalData(byte[] sendData, String host, int port) {
433 System.out.println("Passing Locally");
435 mac.update(sendData);
436 byte[] genmac = mac.doFinal();
437 byte[] totalData = new byte[sendData.length + genmac.length];
438 System.arraycopy(sendData, 0, totalData, 0, sendData.length);
439 System.arraycopy(genmac, 0, totalData, sendData.length, genmac.length);
441 // Encrypt the data for sending
442 // byte[] encryptedData = encryptCipher.doFinal(totalData);
443 byte[] encryptedData = encryptCipher.doFinal(totalData);
445 // Open a TCP socket connection to a local device
446 Socket socket = new Socket(host, port);
447 socket.setReuseAddress(true);
448 DataOutputStream output = new DataOutputStream(socket.getOutputStream());
449 DataInputStream input = new DataInputStream(socket.getInputStream());
453 // Send data to output (length of data, the data)
454 output.writeInt(encryptedData.length);
455 output.write(encryptedData, 0, encryptedData.length);
458 int lengthOfReturnData = input.readInt();
459 byte[] returnData = new byte[lengthOfReturnData];
460 input.readFully(returnData);
464 returnData = decryptCipher.doFinal(returnData);
466 // We are done with this socket
469 mac.update(returnData, 0, returnData.length - HMAC_SIZE);
470 byte[] realmac = mac.doFinal();
471 byte[] recmac = new byte[HMAC_SIZE];
472 System.arraycopy(returnData, returnData.length - realmac.length, recmac, 0, realmac.length);
474 if (!Arrays.equals(recmac, realmac))
475 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
477 byte[] returnData2 = new byte[lengthOfReturnData - recmac.length];
478 System.arraycopy(returnData, 0, returnData2, 0, returnData2.length);
481 } catch (SocketTimeoutException e) {
483 } catch (BadPaddingException e) {
485 } catch (IllegalBlockSizeException e) {
487 } catch (UnknownHostException e) {
489 } catch (IOException e) {
496 private void localServerWorkerFunction() {
498 ServerSocket inputSocket = null;
501 // Local server socket
502 inputSocket = new ServerSocket(listeningPort);
503 inputSocket.setReuseAddress(true);
504 inputSocket.setSoTimeout(TIMEOUT_MILLIS);
505 } catch (Exception e) {
507 throw new Error("Local server setup failure...");
513 // Accept incoming socket
514 Socket socket = inputSocket.accept();
516 DataInputStream input = new DataInputStream(socket.getInputStream());
517 DataOutputStream output = new DataOutputStream(socket.getOutputStream());
519 // Get the encrypted data from the server
520 int dataSize = input.readInt();
521 byte[] readData = new byte[dataSize];
522 input.readFully(readData);
527 readData = decryptCipher.doFinal(readData);
529 mac.update(readData, 0, readData.length - HMAC_SIZE);
530 byte[] genmac = mac.doFinal();
531 byte[] recmac = new byte[HMAC_SIZE];
532 System.arraycopy(readData, readData.length - recmac.length, recmac, 0, recmac.length);
534 if (!Arrays.equals(recmac, genmac))
535 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
537 byte[] returnData = new byte[readData.length - recmac.length];
538 System.arraycopy(readData, 0, returnData, 0, returnData.length);
541 // byte[] sendData = table.acceptDataFromLocal(readData);
542 byte[] sendData = table.acceptDataFromLocal(returnData);
544 mac.update(sendData);
545 byte[] realmac = mac.doFinal();
546 byte[] totalData = new byte[sendData.length + realmac.length];
547 System.arraycopy(sendData, 0, totalData, 0, sendData.length);
548 System.arraycopy(realmac, 0, totalData, sendData.length, realmac.length);
550 // Encrypt the data for sending
551 byte[] encryptedData = encryptCipher.doFinal(totalData);
555 // Send data to output (length of data, the data)
556 output.writeInt(encryptedData.length);
557 output.write(encryptedData, 0, encryptedData.length);
562 } catch (SocketTimeoutException e) {
564 } catch (BadPaddingException e) {
566 } catch (IllegalBlockSizeException e) {
568 } catch (UnknownHostException e) {
570 } catch (IOException e) {
575 if (inputSocket != null) {
578 } catch (Exception e) {
580 throw new Error("Local server close failure...");
585 public void close() {
588 if (localServerThread != null) {
590 localServerThread.join();
591 } catch (Exception e) {
593 throw new Error("Local Server thread join issue...");
597 // System.out.println("Done Closing Cloud Comm");
600 protected void finalize() throws Throwable {
602 close(); // close open files