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) :
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() {
73 * Generates Key from password.
75 AESKey *CloudComm::initKey() {
77 AESKey *key = new AESKey(password->internalBytes(),
82 } catch (Exception *e) {
83 throw new Error("Failed generating key.");
88 * Inits all the security stuff
91 void CloudComm::initSecurity() {
92 // try to get the salt and if one does not exist set one
102 * Inits the HMAC generator.
104 void CloudComm::initCrypt() {
105 if (password == NULL) {
111 password = NULL;// drop password
114 } catch (Exception *e) {
115 throw new Error("Failed To Initialize Ciphers");
120 * Builds the URL for the given request.
122 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
123 const char *reqstring = isput ? "req=putslot" : "req=getslot";
124 char *buffer = (char *) malloc(baseurl->length() + 200);
125 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
126 int offset = baseurl->length();
127 offset += sprintf(&buffer[offset], "?%s&seq=%" PRId64, reqstring, sequencenumber);
129 sprintf(&buffer[offset], "&max=%" PRId64, maxentries);
130 IoTString *urlstr = new IoTString(buffer);
134 void loopWrite(int fd, char *array, int bytestowrite) {
135 int byteswritten = 0;
136 while (bytestowrite) {
137 int bytes = write(fd, &array[byteswritten], bytestowrite);
139 byteswritten += bytes;
140 bytestowrite -= bytes;
142 printf("Error in write\n");
148 void loopRead(int fd, char *array, int bytestoread) {
150 while (bytestoread) {
151 int bytes = read(fd, &array[bytesread], bytestoread);
154 bytestoread -= bytes;
156 printf("Error in read\n");
162 WebConnection openURL(IoTString *url) {
163 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
164 printf("BOGUS URL\n");
168 for (; i < url->length(); i++)
169 if (url->get(i) == '/')
172 if ( i == url->length()) {
173 printf("ERROR in openURL\n");
177 char *host = (char *) malloc(i - 6);
178 memcpy(host, &url->internalBytes()->internalArray()[7], i - 7);
180 printf("%s\n", host);
182 char *message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2 * url->length());
184 /* fill in the parameters */
185 int post = sprintf(message,"POST ");
187 memcpy(&message[post], &url->internalBytes()->internalArray()[i], url->length() - i);
188 int endpost = sprintf(&message[post + url->length() - i], " HTTP/1.1\r\n");
190 int hostlen = sprintf(&message[endpost + post + url->length() - i], "Host: ");
191 memcpy(&message[endpost + post + url->length() + hostlen - i], host, i - 7);
192 sprintf(&message[endpost + post + url->length() + hostlen - 7], "\r\n");
194 /* create the socket */
195 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
196 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
198 /* lookup the ip address */
199 struct hostent *server = gethostbyname(host);
202 if (server == NULL) {printf("ERROR, no such host"); exit(-1);}
204 /* fill in the structure */
205 struct sockaddr_in serv_addr;
207 memset(&serv_addr,0,sizeof(serv_addr));
208 serv_addr.sin_family = AF_INET;
209 serv_addr.sin_port = htons(80);
210 memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
212 /* connect the socket */
213 if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
214 printf("ERROR connecting");
218 /* send the request */
219 int total = strlen(message);
220 loopWrite(sockfd, message, total);
221 return (WebConnection) {sockfd, -1};
224 int createSocket(IoTString *name, int port) {
225 char *host = (char *) malloc(name->length() + 1);
226 memcpy(host, name->internalBytes()->internalArray(), name->length());
227 host[name->length()] = 0;
228 printf("%s\n", host);
229 /* How big is the message? */
231 /* create the socket */
232 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
233 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
235 /* lookup the ip address */
236 struct hostent *server = gethostbyname(host);
239 if (server == NULL) {printf("ERROR, no such host"); exit(-1);}
241 /* fill in the structure */
242 struct sockaddr_in serv_addr;
244 memset(&serv_addr,0,sizeof(serv_addr));
245 serv_addr.sin_family = AF_INET;
246 serv_addr.sin_port = htons(port);
247 memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
249 /* connect the socket */
250 if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
251 printf("ERROR connecting");
258 int createSocket(int port) {
260 struct sockaddr_in sin;
262 bzero(&sin, sizeof(sin));
263 sin.sin_family = AF_INET;
264 sin.sin_port = htons(port);
265 sin.sin_addr.s_addr = htonl(INADDR_ANY);
266 fd = socket(AF_INET, SOCK_STREAM, 0);
268 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof (n)) < 0) {
270 printf("Create Socket Error\n");
273 if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
277 if (listen(fd, 5) < 0) {
284 int acceptSocket(int socket) {
285 struct sockaddr_in sin;
286 unsigned int sinlen = sizeof(sin);
287 int newfd = accept(socket, (struct sockaddr *)&sin, &sinlen);
289 setsockopt(newfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(flag));
291 printf("Accept Error\n");
297 void writeSocketData(int fd, Array<char> *data) {
298 loopWrite(fd, data->internalArray(), data->length());
301 void writeSocketInt(int fd, int32_t value) {
303 array[0] = value >> 24;
304 array[1] = (value >> 16) & 0xff;
305 array[2] = (value >> 8) & 0xff;
306 array[3] = value & 0xff;
307 loopWrite(fd, array, 4);
310 int readSocketInt(int fd) {
312 loopRead(fd, array, 4);
313 return (((int32_t)(unsigned char) array[0]) << 24) |
314 (((int32_t)(unsigned char) array[1]) << 16) |
315 (((int32_t)(unsigned char) array[2]) << 8) |
316 ((int32_t)(unsigned char) array[3]);
319 void readSocketData(int fd, Array<char> *data) {
320 loopRead(fd, data->internalArray(), data->length());
323 void writeURLDataAndClose(WebConnection *wc, Array<char> *data) {
324 dprintf(wc->fd, "Content-Length: %d\r\n\r\n", data->length());
325 loopWrite(wc->fd, data->internalArray(), data->length());
328 void closeURLReq(WebConnection *wc) {
329 dprintf(wc->fd, "\r\n");
332 void readURLData(WebConnection *wc, Array<char> *output) {
333 loopRead(wc->fd, output->internalArray(), output->length());
336 int readURLInt(WebConnection *wc) {
338 loopRead(wc->fd, array, 4);
339 return (((int32_t)(unsigned char) array[0]) << 24) |
340 (((int32_t)(unsigned char) array[1]) << 16) |
341 (((int32_t)(unsigned char) array[2]) << 8) |
342 ((int32_t)(unsigned char) array[3]);
345 void readLine(WebConnection *wc, char *response, int numBytes) {
349 int bytes = read(wc->fd, &newchar, 1);
352 if (offset == (numBytes - 1)) {
353 printf("Response too long");
356 response[offset++] = newchar;
360 response[offset] = 0;
363 int getResponseCode(WebConnection *wc) {
365 readLine(wc, response, sizeof(response));
366 int ver1 = 0, ver2 = 0, respcode = 0;
367 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
368 printf("Response code %d\n", respcode);
372 void readHeaders(WebConnection *wc) {
377 readLine(wc, response, sizeof(response));
378 if (response[0] == '\r')
380 else if (memcmp(response, "Content-Length:", sizeof("Content-Length:") - 1) == 0) {
381 sscanf(response, "Content-Length: %d", &numBytes);
382 wc->numBytes = numBytes;
387 void CloudComm::setSalt() {
389 // Salt already sent to server so don't set it again
393 WebConnection wc = {-1, -1};
395 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
396 random->nextBytes(saltTmp);
398 char *buffer = (char *) malloc(baseurl->length() + 100);
399 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
400 int offset = baseurl->length();
401 offset += sprintf(&buffer[offset], "?req=setsalt");
402 IoTString *urlstr = new IoTString(buffer);
406 wc = openURL(urlstr);
407 writeURLDataAndClose(&wc, saltTmp);
409 int responsecode = getResponseCode(&wc);
410 if (responsecode != HttpURLConnection_HTTP_OK) {
411 throw new Error("Invalid response");
417 } catch (Exception *e) {
419 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
423 bool CloudComm::getSalt() {
424 WebConnection wc = {-1, -1};
425 IoTString *urlstr = NULL;
428 char *buffer = (char *) malloc(baseurl->length() + 100);
429 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
430 int offset = baseurl->length();
431 offset += sprintf(&buffer[offset], "?req=getsalt");
432 urlstr = new IoTString(buffer);
434 } catch (Exception *e) {
435 throw new Error("getSlot failed");
439 wc = openURL(urlstr);
442 } catch (SocketTimeoutException *e) {
444 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
445 } catch (Exception *e) {
446 throw new Error("getSlot failed");
451 int responsecode = getResponseCode(&wc);
453 if (responsecode != HttpURLConnection_HTTP_OK) {
454 throw new Error("Invalid response");
456 if (wc.numBytes == 0) {
463 int salt_length = readURLInt(&wc);
464 Array<char> *tmp = new Array<char>(salt_length);
465 readURLData(&wc, tmp);
471 } catch (SocketTimeoutException *e) {
473 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
474 } catch (Exception *e) {
475 throw new Error("getSlot failed");
479 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
480 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
481 buffer->putLong(machineId);
482 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
483 buffer->putLong(localSequenceNumberShifted);
484 return buffer->array();
487 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
488 Array<char> *output = new Array<char>(data->length());
489 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
493 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
494 Array<char> *output = new Array<char>(data->length());
495 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
499 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
501 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
502 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
503 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
504 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
505 delete encryptedBytes;
507 } catch (Exception *e) {
508 throw new Error("Failed To Encrypt");
512 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
514 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
515 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
516 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
517 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
518 Array<char> * data = AESDecrypt(ivBytes, key, encryptedBytes);
519 delete encryptedBytes;
522 } catch (Exception *e) {
523 throw new Error("Failed To Decrypt");
528 * API for putting a slot into the queue. Returns NULL on success.
529 * On failure, the server will send slots with newer sequence
532 Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
533 WebConnection wc = {-1, -1};
537 throw new ServerException("putSlot failed", ServerException_TypeSalt);
542 int64_t sequencenumber = slot->getSequenceNumber();
543 Array<char> *slotBytes = slot->encode(mac);
544 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, slot->getSlotCryptIV());
546 IoTString *url = buildRequest(true, sequencenumber, max);
549 writeURLDataAndClose(&wc, chars);
552 } catch (ServerException *e) {
555 } catch (SocketTimeoutException *e) {
557 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
558 } catch (Exception *e) {
559 throw new Error("putSlot failed");
563 int respcode = getResponseCode(&wc);
566 Array<char> *resptype = new Array<char>(7);
567 readURLData(&wc, resptype);
570 if (resptype->equals(getslot)) {
571 Array<Slot *> *tmp = processSlots(&wc);
574 } else if (resptype->equals(putslot)) {
579 throw new Error("Bad response to putslot");
581 } catch (SocketTimeoutException *e) {
584 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
585 } catch (Exception *e) {
586 throw new Error("putSlot failed");
591 * Request the server to send all slots with the given
592 * sequencenumber or newer->
594 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
595 WebConnection wc = {-1, -1};
599 throw new ServerException("getSlots failed", ServerException_TypeSalt);
604 IoTString *url = buildRequest(false, sequencenumber, 0);
609 } catch (SocketTimeoutException *e) {
611 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
612 } catch (ServerException *e) {
616 } catch (Exception *e) {
617 throw new Error("getSlots failed");
622 int responsecode = getResponseCode(&wc);
624 Array<char> *resptype = new Array<char>(7);
625 readURLData(&wc, resptype);
627 if (!resptype->equals(getslot))
628 throw new Error("Bad Response: ");
630 Array<Slot *> *tmp = processSlots(&wc);
633 } catch (SocketTimeoutException *e) {
636 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
637 } catch (Exception *e) {
638 throw new Error("getSlots failed");
643 * Method that actually handles building Slot objects from the
644 * server response. Shared by both putSlot and getSlots.
646 Array<Slot *> *CloudComm::processSlots(WebConnection *wc) {
647 int numberofslots = readURLInt(wc);
648 Array<int> *sizesofslots = new Array<int>(numberofslots);
649 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
651 for (int i = 0; i < numberofslots; i++)
652 sizesofslots->set(i, readURLInt(wc));
653 for (int i = 0; i < numberofslots; i++) {
654 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
655 readURLData(wc, rawData);
656 Array<char> *data = stripIVAndDecryptSlot(rawData);
658 slots->set(i, Slot_decode(table, data, mac));
664 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
668 printf("Passing Locally\n");
669 mac->update(sendData, 0, sendData->length());
670 Array<char> *genmac = mac->doFinal();
671 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
672 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
673 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
675 // Encrypt the data for sending
676 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
677 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
679 // Open a TCP socket connection to a local device
680 int socket = createSocket(host, port);
683 // Send data to output (length of data, the data)
684 writeSocketInt(socket, encryptedData->length());
685 writeSocketData(socket, encryptedData);
687 int lengthOfReturnData = readSocketInt(socket);
688 Array<char> *returnData = new Array<char>(lengthOfReturnData);
689 readSocketData(socket, returnData);
691 returnData = stripIVAndDecryptSlot(returnData);
693 // We are done with this socket
695 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
696 Array<char> *realmac = mac->doFinal();
697 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
698 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
700 if (!recmac->equals(realmac))
701 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
703 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
704 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
707 } catch (Exception *e) {
708 printf("Exception\n");
714 void CloudComm::localServerWorkerFunction() {
715 int inputSocket = -1;
718 // Local server socket
719 inputSocket = createSocket(listeningPort);
720 } catch (Exception *e) {
721 throw new Error("Local server setup failure...");
726 // Accept incoming socket
727 int socket = acceptSocket(inputSocket);
729 // Get the encrypted data from the server
730 int dataSize = readSocketInt(socket);
731 Array<char> *readData = new Array<char>(dataSize);
732 readSocketData(socket, readData);
736 readData = stripIVAndDecryptSlot(readData);
737 mac->update(readData, 0, readData->length() - CloudComm_HMAC_SIZE);
738 Array<char> *genmac = mac->doFinal();
739 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
740 System_arraycopy(readData, readData->length() - recmac->length(), recmac, 0, recmac->length());
742 if (!recmac->equals(genmac))
743 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
745 Array<char> *returnData = new Array<char>(readData->length() - recmac->length());
746 System_arraycopy(readData, 0, returnData, 0, returnData->length());
749 Array<char> *sendData = table->acceptDataFromLocal(returnData);
750 mac->update(sendData, 0, sendData->length());
751 Array<char> *realmac = mac->doFinal();
752 Array<char> *totalData = new Array<char>(sendData->length() + realmac->length());
753 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
754 System_arraycopy(realmac, 0, totalData, sendData->length(), realmac->length());
756 // Encrypt the data for sending
757 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
758 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
761 // Send data to output (length of data, the data)
762 writeSocketInt(socket, encryptedData->length());
763 writeSocketData(socket, encryptedData);
765 } catch (Exception *e) {
769 if (inputSocket != -1) {
772 } catch (Exception *e) {
773 throw new Error("Local server close failure...");
778 void CloudComm::closeCloud() {
781 if (listeningPort > 0) {
782 if (pthread_join(localServerThread, NULL) != 0)
783 throw new Error("Local Server thread join issue...");