2 #include "TimingSingleton.h"
3 #include "SecureRandom.h"
11 #include "ByteBuffer.h"
13 #include <sys/types.h>
14 //#include <sys/socket.h>
15 //#include <arpa/inet.h>
16 //#include <netinet/tcp.h>
21 * Empty Constructor needed for child class.
23 CloudComm::CloudComm() :
33 timer(TimingSingleton_getInstance()),
34 getslot(new Array<char>("getslot", 7)),
35 putslot(new Array<char>("putslot", 7))
39 void *threadWrapper(void *cloud) {
40 CloudComm *c = (CloudComm *) cloud;
41 c->localServerWorkerFunction();
46 * Constructor for actual use. Takes in the url and password.
48 CloudComm::CloudComm(Table *_table, IoTString *_baseurl, IoTString *_password, int _listeningPort) :
49 baseurl(new IoTString(_baseurl)),
52 password(new IoTString(_password)),
53 random(new SecureRandom()),
56 listeningPort(_listeningPort),
58 timer(TimingSingleton_getInstance()),
59 getslot(new Array<char>("getslot", 7)),
60 putslot(new Array<char>("putslot", 7)) {
61 /* if (listeningPort > 0) {
62 pthread_create(&localServerThread, NULL, threadWrapper, this);
66 CloudComm::~CloudComm() {
84 * Generates Key from password.
86 AESKey *CloudComm::initKey() {
87 AESKey *key = new AESKey(password->internalBytes(),
95 * Inits all the security stuff
98 void CloudComm::initSecurity() {
99 // try to get the salt and if one does not exist set one
109 * Inits the HMAC generator.
111 void CloudComm::initCrypt() {
112 if (password == NULL) {
117 password = NULL;// drop password
123 * Builds the URL for the given request.
125 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
126 const char *reqstring = isput ? "req=putslot" : "req=getslot";
127 char *buffer = (char *) malloc(baseurl->length() + 200);
128 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
129 int offset = baseurl->length();
130 offset += sprintf(&buffer[offset], "?%s&seq=%" PRId64, reqstring, sequencenumber);
132 sprintf(&buffer[offset], "&max=%" PRId64, maxentries);
133 IoTString *urlstr = new IoTString(buffer);
138 void loopWrite(TCPClient * client, char *array, int bytestowrite) {
139 int byteswritten = 0;
140 while (bytestowrite) {
141 int bytes = client->write((const unsigned char *) &array[byteswritten], bytestowrite);
143 byteswritten += bytes;
144 bytestowrite -= bytes;
146 printf("Error in write\n");
152 void loopRead(TCPClient * client, char *array, int bytestoread) {
154 while (bytestoread) {
155 int bytes = client->read((unsigned char *) &array[bytesread], bytestoread);
158 bytestoread -= bytes;
160 printf("Error in read\n");
166 WebConnection openURL(IoTString *url) {
167 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
168 printf("BOGUS URL\n");
172 for (; i < url->length(); i++)
173 if (url->get(i) == '/')
176 if ( i == url->length()) {
177 printf("ERROR in openURL\n");
181 char *host = (char *) malloc(i - 6);
182 memcpy(host, &url->internalBytes()->internalArray()[7], i - 7);
184 printf("%s\n", host);
186 char *message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2 * url->length());
188 /* fill in the parameters */
189 int post = sprintf(message,"POST ");
191 memcpy(&message[post], &url->internalBytes()->internalArray()[i], url->length() - i);
192 int endpost = sprintf(&message[post + url->length() - i], " HTTP/1.1\r\n");
194 int hostlen = sprintf(&message[endpost + post + url->length() - i], "Host: ");
195 memcpy(&message[endpost + post + url->length() + hostlen - i], host, i - 7);
196 sprintf(&message[endpost + post + url->length() + hostlen - 7], "\r\n");
202 if (!wc.client.connect(host, 80)) {
203 myerror("ERROR connecting\n");
207 /* send the request */
208 int total = strlen(message);
209 loopWrite(&wc.client, message, total);
214 TCPClient createSocket(IoTString *name, int port) {
215 char *host = (char *) malloc(name->length() + 1);
216 memcpy(host, name->internalBytes()->internalArray(), name->length());
217 host[name->length()] = 0;
218 printf("%s\n", host);
219 /* How big is the message? */
221 /* create the socket */
222 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
223 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
225 /* lookup the ip address */
227 if (!client.connect(host, port)) {
228 myerror("ERROR connecting\n");
235 TCPServer createSocket(int port) {
237 TCPServer server = TCPServer(port);
244 void writeSocketData(TCPClient * fd, Array<char> *data) {
245 loopWrite(fd, data->internalArray(), data->length());
248 void writeSocketInt(TCPClient * fd, int32_t value) {
250 array[0] = value >> 24;
251 array[1] = (value >> 16) & 0xff;
252 array[2] = (value >> 8) & 0xff;
253 array[3] = value & 0xff;
254 loopWrite(fd, array, 4);
257 int readSocketInt(TCPClient * fd) {
259 loopRead(fd, array, 4);
260 return (((int32_t)(unsigned char) array[0]) << 24) |
261 (((int32_t)(unsigned char) array[1]) << 16) |
262 (((int32_t)(unsigned char) array[2]) << 8) |
263 ((int32_t)(unsigned char) array[3]);
266 void readSocketData(TCPClient * fd, Array<char> *data) {
267 loopRead(fd, data->internalArray(), data->length());
270 void writeURLDataAndClose(WebConnection *wc, Array<char> *data) {
272 sprintf(buffer, "Content-Length: %d\r\n\r\n", data->length());
273 wc->client.print(buffer);
274 loopWrite(&wc->client, data->internalArray(), data->length());
277 void closeURLReq(WebConnection *wc) {
278 wc->client.println("");
281 void readURLData(WebConnection *wc, Array<char> *output) {
282 loopRead(&wc->client, output->internalArray(), output->length());
285 int readURLInt(WebConnection *wc) {
287 loopRead(&wc->client, array, 4);
288 return (((int32_t)(unsigned char) array[0]) << 24) |
289 (((int32_t)(unsigned char) array[1]) << 16) |
290 (((int32_t)(unsigned char) array[2]) << 8) |
291 ((int32_t)(unsigned char) array[3]);
294 void readLine(WebConnection *wc, char *response, int numBytes) {
298 int bytes = wc->client.read((unsigned char *) &newchar, 1);
301 if (offset == (numBytes - 1)) {
302 printf("Response too long");
305 response[offset++] = newchar;
309 response[offset] = 0;
312 int getResponseCode(WebConnection *wc) {
314 readLine(wc, response, sizeof(response));
315 int ver1 = 0, ver2 = 0, respcode = 0;
316 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
317 printf("Response code %d\n", respcode);
321 void readHeaders(WebConnection *wc) {
326 readLine(wc, response, sizeof(response));
327 if (response[0] == '\r')
329 else if (memcmp(response, "Content-Length:", sizeof("Content-Length:") - 1) == 0) {
330 sscanf(response, "Content-Length: %d", &numBytes);
331 wc->numBytes = numBytes;
336 void CloudComm::setSalt() {
338 // Salt already sent to server so don't set it again
342 WebConnection wc = {-1, -1};
344 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
345 random->nextBytes(saltTmp);
347 char *buffer = (char *) malloc(baseurl->length() + 100);
348 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
349 int offset = baseurl->length();
350 offset += sprintf(&buffer[offset], "?req=setsalt");
351 IoTString *urlstr = new IoTString(buffer);
355 wc = openURL(urlstr);
357 writeURLDataAndClose(&wc, saltTmp);
359 int responsecode = getResponseCode(&wc);
360 if (responsecode != HttpURLConnection_HTTP_OK) {
361 //throw new Error("Invalid response");
362 myerror("Invalid response\n");
368 /* } catch (Exception *e) {
370 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
374 bool CloudComm::getSalt() {
377 IoTString *urlstr = NULL;
380 char *buffer = (char *) malloc(baseurl->length() + 100);
381 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
382 int offset = baseurl->length();
383 offset += sprintf(&buffer[offset], "?req=getsalt");
384 urlstr = new IoTString(buffer);
386 /* } catch (Exception *e) {
387 throw new Error("getSlot failed");
391 wc = openURL(urlstr);
396 /* } catch (SocketTimeoutException *e) {
400 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
401 } catch (Exception *e) {
404 throw new Error("getSlot failed");
409 int responsecode = getResponseCode(&wc);
411 if (responsecode != HttpURLConnection_HTTP_OK) {
412 //throw new Error("Invalid response");
413 myerror("Invalid response\n");
415 if (wc.numBytes == 0) {
422 int salt_length = readURLInt(&wc);
423 Array<char> *tmp = new Array<char>(salt_length);
424 readURLData(&wc, tmp);
430 /* } catch (SocketTimeoutException *e) {
432 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
433 } catch (Exception *e) {
434 throw new Error("getSlot failed");
438 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
439 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
440 buffer->putLong(machineId);
441 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
442 buffer->putLong(localSequenceNumberShifted);
443 return buffer->array();
446 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
447 Array<char> *output = new Array<char>(data->length());
448 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
452 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
453 Array<char> *output = new Array<char>(data->length());
454 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
458 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
460 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
461 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
462 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
463 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
464 delete encryptedBytes;
466 /* } catch (Exception *e) {
467 throw new Error("Failed To Encrypt");
471 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
473 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
474 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
475 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
476 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
477 Array<char> * data = AESDecrypt(ivBytes, key, encryptedBytes);
478 delete encryptedBytes;
481 /* } catch (Exception *e) {
482 throw new Error("Failed To Decrypt");
487 * API for putting a slot into the queue. Returns NULL on success.
488 * On failure, the server will send slots with newer sequence
491 Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
492 WebConnection wc = {-1, -1};
496 // throw new ServerException("putSlot failed", ServerException_TypeSalt);
497 myerror("putSlot failed\n");
502 int64_t sequencenumber = slot->getSequenceNumber();
503 Array<char> *slotBytes = slot->encode(mac);
504 Array<char> * ivBytes = slot->getSlotCryptIV();
505 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, ivBytes);
508 IoTString *url = buildRequest(true, sequencenumber, max);
512 writeURLDataAndClose(&wc, chars);
515 /* } catch (ServerException *e) {
518 } catch (SocketTimeoutException *e) {
520 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
521 } catch (Exception *e) {
522 throw new Error("putSlot failed");
525 Array<char> *resptype = NULL;
527 int respcode = getResponseCode(&wc);
530 resptype = new Array<char>(7);
531 readURLData(&wc, resptype);
534 if (resptype->equals(getslot)) {
536 Array<Slot *> *tmp = processSlots(&wc);
539 } else if (resptype->equals(putslot)) {
546 //throw new Error("Bad response to putslot");
547 myerror("Bad response to putslot\n");
549 /* } catch (SocketTimeoutException *e) {
550 if (resptype != NULL)
554 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
555 } catch (Exception *e) {
556 if (resptype != NULL)
558 throw new Error("putSlot failed");
563 * Request the server to send all slots with the given
564 * sequencenumber or newer->
566 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
567 WebConnection wc = {-1, -1};
571 //throw new ServerException("getSlots failed", ServerException_TypeSalt);
572 myerror("getSlots failed\n");
577 IoTString *url = buildRequest(false, sequencenumber, 0);
583 /* } catch (SocketTimeoutException *e) {
585 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
586 } catch (ServerException *e) {
590 } catch (Exception *e) {
591 throw new Error("getSlots failed");
596 int responsecode = getResponseCode(&wc);
598 Array<char> *resptype = new Array<char>(7);
599 readURLData(&wc, resptype);
601 if (!resptype->equals(getslot))
602 // throw new Error("Bad Response: ");
603 myerror("Bad Response: \n");
606 Array<Slot *> *tmp = processSlots(&wc);
609 /* } catch (SocketTimeoutException *e) {
612 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
613 } catch (Exception *e) {
614 throw new Error("getSlots failed");
619 * Method that actually handles building Slot objects from the
620 * server response. Shared by both putSlot and getSlots.
622 Array<Slot *> *CloudComm::processSlots(WebConnection *wc) {
623 int numberofslots = readURLInt(wc);
624 Array<int> *sizesofslots = new Array<int>(numberofslots);
625 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
627 for (int i = 0; i < numberofslots; i++)
628 sizesofslots->set(i, readURLInt(wc));
629 for (int i = 0; i < numberofslots; i++) {
630 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
631 readURLData(wc, rawData);
632 Array<char> *data = stripIVAndDecryptSlot(rawData);
634 slots->set(i, Slot_decode(table, data, mac));
641 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
645 printf("Passing Locally\n");
646 mac->update(sendData, 0, sendData->length());
647 Array<char> *genmac = mac->doFinal();
648 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
649 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
650 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
652 // Encrypt the data for sending
653 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
654 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
656 // Open a TCP socket connection to a local device
657 TCPClient socket = createSocket(host, port);
660 // Send data to output (length of data, the data)
661 writeSocketInt(&socket, encryptedData->length());
662 writeSocketData(&socket, encryptedData);
664 int lengthOfReturnData = readSocketInt(&socket);
665 Array<char> *returnData = new Array<char>(lengthOfReturnData);
666 readSocketData(&socket, returnData);
668 returnData = stripIVAndDecryptSlot(returnData);
670 // We are done with this socket
672 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
673 Array<char> *realmac = mac->doFinal();
674 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
675 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
677 if (!recmac->equals(realmac))
678 // throw new Error("Local Error: Invalid HMAC! Potential Attack!");
679 myerror("Local Error: Invalid HMAC! Potential Attack!\n");
681 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
682 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
685 /* } catch (Exception *e) {
686 printf("Exception\n");
692 void CloudComm::localServerWorkerFunction() {
693 /* int inputSocket = -1;
696 // Local server socket
697 inputSocket = createSocket(listeningPort);
698 } catch (Exception *e) {
699 throw new Error("Local server setup failure...");
704 // Accept incoming socket
705 int socket = acceptSocket(inputSocket);
707 // Get the encrypted data from the server
708 int dataSize = readSocketInt(socket);
709 Array<char> *readData = new Array<char>(dataSize);
710 readSocketData(socket, readData);
714 readData = stripIVAndDecryptSlot(readData);
715 mac->update(readData, 0, readData->length() - CloudComm_HMAC_SIZE);
716 Array<char> *genmac = mac->doFinal();
717 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
718 System_arraycopy(readData, readData->length() - recmac->length(), recmac, 0, recmac->length());
720 if (!recmac->equals(genmac))
721 // throw new Error("Local Error: Invalid HMAC! Potential Attack!");
722 error("Local Error: Invalid HMAC! Potential Attack!\n");
724 Array<char> *returnData = new Array<char>(readData->length() - recmac->length());
725 System_arraycopy(readData, 0, returnData, 0, returnData->length());
728 Array<char> *sendData = table->acceptDataFromLocal(returnData);
729 mac->update(sendData, 0, sendData->length());
730 Array<char> *realmac = mac->doFinal();
731 Array<char> *totalData = new Array<char>(sendData->length() + realmac->length());
732 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
733 System_arraycopy(realmac, 0, totalData, sendData->length(), realmac->length());
735 // Encrypt the data for sending
736 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
737 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
740 // Send data to output (length of data, the data)
741 writeSocketInt(socket, encryptedData->length());
742 writeSocketData(socket, encryptedData);
744 } catch (Exception *e) {
748 if (inputSocket != -1) {
751 } catch (Exception *e) {
752 throw new Error("Local server close failure...");
757 void CloudComm::closeCloud() {
760 /* if (listeningPort > 0) {
761 if (pthread_join(localServerThread, NULL) != 0)
762 throw new Error("Local Server thread join issue...");