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) :
53 random(new SecureRandom()),
56 listeningPort(_listeningPort),
58 timer(TimingSingleton_getInstance()) {
59 if (listeningPort > 0) {
60 pthread_create(&localServerThread, NULL, threadWrapper, this);
65 * Generates Key from password.
67 AESKey *CloudComm::initKey() {
69 AESKey *key = new AESKey(password->internalBytes(),
74 } catch (Exception *e) {
75 throw new Error("Failed generating key.");
80 * Inits all the security stuff
83 void CloudComm::initSecurity() {
84 // try to get the salt and if one does not exist set one
94 * Inits the HMAC generator.
96 void CloudComm::initCrypt() {
97 if (password == NULL) {
102 password = NULL;// drop password
105 } catch (Exception *e) {
106 throw new Error("Failed To Initialize Ciphers");
111 * Builds the URL for the given request.
113 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
114 const char *reqstring = isput ? "req=putslot" : "req=getslot";
115 char *buffer = (char *) malloc(baseurl->length() + 200);
116 memcpy(buffer, baseurl->internalBytes(), baseurl->length());
117 int offset = baseurl->length();
118 offset += sprintf(&buffer[offset], "?%s&seq=%" PRId64, reqstring, sequencenumber);
120 sprintf(&buffer[offset], "&max=%" PRId64, maxentries);
121 IoTString *urlstr = new IoTString(buffer);
125 void loopWrite(int fd, char * array, int bytestowrite) {
126 int byteswritten = 0;
127 while (bytestowrite) {
128 int bytes = write(fd, & array[byteswritten], bytestowrite);
130 byteswritten += bytes;
131 bytestowrite -= bytes;
133 printf("Error in write\n");
139 void loopRead(int fd, char * array, int bytestoread) {
141 while (bytestoread) {
142 int bytes = read(fd, & array[bytesread], bytestoread);
145 bytestoread -= bytes;
147 printf("Error in read\n");
153 int openURL(IoTString *url) {
154 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
155 printf("BOGUS URL\n");
159 for(; i < url->length(); i++)
160 if (url->get(i) == '/')
163 if ( i == url->length()) {
164 printf("ERROR in openURL\n");
168 char * host = (char *) malloc(i - 6);
169 memcpy(host, &url->internalBytes()->internalArray()[7], i-7);
171 printf("%s\n", host);
173 char * message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2*url->length());
175 /* fill in the parameters */
176 int post = sprintf(message,"POST ");
178 memcpy(&message[post], url->internalBytes()->internalArray(), url->length());
179 int endpost = sprintf(&message[post+url->length()], " HTTP/1.1\r\n");
181 int hostlen = sprintf(&message[endpost + post + url->length()], "Host: ");
182 memcpy(&message[endpost + post + url->length()+hostlen], url->internalBytes()->internalArray(), url->length());
183 sprintf(&message[endpost + post + 2*url->length()+hostlen], "\r\n");
185 /* create the socket */
186 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
187 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
189 /* lookup the ip address */
190 struct hostent *server = gethostbyname(host);
193 if (server == NULL) {printf("ERROR, no such host"); exit(-1);}
195 /* fill in the structure */
196 struct sockaddr_in serv_addr;
198 memset(&serv_addr,0,sizeof(serv_addr));
199 serv_addr.sin_family = AF_INET;
200 serv_addr.sin_port = htons(80);
201 memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
203 /* connect the socket */
204 if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
205 printf("ERROR connecting");
209 /* send the request */
210 int total = strlen(message);
211 loopWrite(sockfd, message, total);
216 int createSocket(IoTString *name, int port) {
217 char * host = (char *) malloc(name->length()+1);
218 memcpy(host, name->internalBytes()->internalArray(), name->length());
219 host[name->length()] = 0;
220 printf("%s\n", host);
221 /* How big is the message? */
223 /* create the socket */
224 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
225 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
227 /* lookup the ip address */
228 struct hostent *server = gethostbyname(host);
231 if (server == NULL) {printf("ERROR, no such host"); exit(-1);}
233 /* fill in the structure */
234 struct sockaddr_in serv_addr;
236 memset(&serv_addr,0,sizeof(serv_addr));
237 serv_addr.sin_family = AF_INET;
238 serv_addr.sin_port = htons(port);
239 memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
241 /* connect the socket */
242 if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
243 printf("ERROR connecting");
250 int createSocket(int port) {
252 struct sockaddr_in sin;
254 bzero(&sin, sizeof(sin));
255 sin.sin_family = AF_INET;
256 sin.sin_port = htons(port);
257 sin.sin_addr.s_addr = htonl(INADDR_ANY);
258 fd=socket(AF_INET, SOCK_STREAM, 0);
260 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof (n)) < 0) {
262 printf("Create Socket Error\n");
265 if (bind(fd, (struct sockaddr *) &sin, sizeof(sin))<0) {
269 if (listen(fd, 5)<0) {
276 int acceptSocket(int socket) {
277 struct sockaddr_in sin;
278 unsigned int sinlen=sizeof(sin);
279 int newfd = accept(socket, (struct sockaddr *)&sin, &sinlen);
281 setsockopt(newfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(flag));
283 printf("Accept Error\n");
289 void writeSocketData(int fd, Array<char> *data) {
290 loopWrite(fd, data->internalArray(), data->length());
293 void writeSocketInt(int fd, int32_t value) {
295 array[0] = value >> 24;
296 array[1] = (value >> 16) & 0xff;
297 array[2] = (value >> 8) & 0xff;
298 array[3] = (value >> 8) & 0xff;
299 loopWrite(fd, array, 4);
302 int readSocketInt(int fd) {
304 loopRead(fd, array, 4);
305 return (((int32_t) array[0]) << 24) |
306 (((int32_t) array[1]) << 16) |
307 (((int32_t) array[2]) << 8) |
308 ((int32_t) array[3]);
311 void readSocketData(int fd, Array<char> *data) {
312 loopRead(fd, data->internalArray(), data->length());
315 void writeURLDataAndClose(int fd, Array<char> *data) {
316 dprintf(fd, "Content-Length: %d\r\n\r\n", data->length());
317 loopWrite(fd, data->internalArray(), data->length());
320 void closeURLReq(int fd) {
324 void readURLData(int fd, Array<char> *output) {
325 loopRead(fd, output->internalArray(), output->length());
328 int readURLInt(int fd) {
330 loopRead(fd, array, 4);
331 return (((int32_t) array[0]) << 24) |
332 (((int32_t) array[1]) << 16) |
333 (((int32_t) array[2]) << 8) |
334 ((int32_t) array[3]);
337 int getResponseCode(int fd) {
342 int bytes = read(fd, &newchar, 1);
345 if (offset == (sizeof(response) - 1)) {
346 printf("Response too long");
349 response[offset++] = newchar;
353 response[offset] = 0;
354 int ver1 = 0, ver2 = 0, respcode = 0;
355 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
356 printf("Response code %d\n", respcode);
360 void CloudComm::setSalt() {
362 // Salt already sent to server so don't set it again
368 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
369 random->nextBytes(saltTmp);
371 char *buffer = (char *) malloc(baseurl->length() + 100);
372 memcpy(buffer, baseurl->internalBytes(), baseurl->length());
373 int offset = baseurl->length();
374 offset += sprintf(&buffer[offset], "?req=setsalt");
375 IoTString *urlstr = new IoTString(buffer);
379 fd = openURL(urlstr);
380 writeURLDataAndClose(fd, saltTmp);
382 int responsecode = getResponseCode(fd);
383 if (responsecode != HttpURLConnection_HTTP_OK) {
384 throw new Error("Invalid response");
389 } catch (Exception *e) {
391 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
395 bool CloudComm::getSalt() {
397 IoTString *urlstr = NULL;
400 char *buffer = (char *) malloc(baseurl->length() + 100);
401 memcpy(buffer, baseurl->internalBytes(), baseurl->length());
402 int offset = baseurl->length();
403 offset += sprintf(&buffer[offset], "?req=getsalt");
404 urlstr = new IoTString(buffer);
406 } catch (Exception *e) {
407 throw new Error("getSlot failed");
411 fd = openURL(urlstr);
414 } catch (SocketTimeoutException *e) {
416 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
417 } catch (Exception *e) {
418 throw new Error("getSlot failed");
423 int responsecode = getResponseCode(fd);
424 if (responsecode != HttpURLConnection_HTTP_OK) {
425 throw new Error("Invalid response");
427 int salt_length = readURLInt(fd);
428 Array<char> *tmp = new Array<char>(salt_length);
429 readURLData(fd, tmp);
433 } catch (SocketTimeoutException *e) {
435 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
436 } catch (Exception *e) {
437 throw new Error("getSlot failed");
441 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
442 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
443 buffer->putLong(machineId);
444 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
445 buffer->putLong(localSequenceNumberShifted);
446 return buffer->array();
449 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
450 Array<char> * output=new Array<char>(data->length());
451 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKey()->internalArray(), key->getKey()->length()/(sizeof(WORD)/sizeof(BYTE)), (BYTE *)ivBytes->internalArray());
455 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
456 Array<char> * output=new Array<char>(data->length());
457 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKey()->internalArray(), key->getKey()->length()/(sizeof(WORD)/sizeof(BYTE)), (BYTE *)ivBytes->internalArray());
461 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
463 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
464 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
465 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
466 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
469 } catch (Exception *e) {
470 throw new Error("Failed To Encrypt");
474 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
476 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
477 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
478 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
479 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
480 return AESDecrypt(ivBytes, key, 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) {
496 throw new ServerException("putSlot failed", ServerException_TypeSalt);
501 int64_t sequencenumber = slot->getSequenceNumber();
502 Array<char> *slotBytes = slot->encode(mac);
503 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, slot->getSlotCryptIV());
504 IoTString *url = buildRequest(true, sequencenumber, max);
507 writeURLDataAndClose(fd, chars);
509 } catch (ServerException *e) {
512 } catch (SocketTimeoutException *e) {
514 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
515 } catch (Exception *e) {
516 throw new Error("putSlot failed");
520 int respcode = getResponseCode(fd);
522 Array<char> *resptype = new Array<char>(7);
523 readURLData(fd, resptype);
526 if (resptype->equals(getslot)) {
527 return processSlots(fd);
528 } else if (resptype->equals(putslot)) {
531 throw new Error("Bad response to putslot");
532 } catch (SocketTimeoutException *e) {
534 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
535 } catch (Exception *e) {
536 throw new Error("putSlot failed");
541 * Request the server to send all slots with the given
542 * sequencenumber or newer->
544 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
549 throw new ServerException("getSlots failed", ServerException_TypeSalt);
554 IoTString *url = buildRequest(false, sequencenumber, 0);
559 } catch (SocketTimeoutException *e) {
561 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
562 } catch (ServerException *e) {
566 } catch (Exception *e) {
567 throw new Error("getSlots failed");
572 int responsecode = getResponseCode(fd);
573 Array<char> *resptype = new Array<char>(7);
574 readURLData(fd, resptype);
576 if (!resptype->equals(getslot))
577 throw new Error("Bad Response: ");
579 return processSlots(fd);
580 } catch (SocketTimeoutException *e) {
582 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
583 } catch (Exception *e) {
584 throw new Error("getSlots failed");
589 * Method that actually handles building Slot objects from the
590 * server response. Shared by both putSlot and getSlots.
592 Array<Slot *> *CloudComm::processSlots(int fd) {
593 int numberofslots = readURLInt(fd);
594 Array<int> *sizesofslots = new Array<int>(numberofslots);
595 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
597 for (int i = 0; i < numberofslots; i++)
598 sizesofslots->set(i, readURLInt(fd));
599 for (int i = 0; i < numberofslots; i++) {
600 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
601 readURLData(fd, rawData);
602 Array<char> *data = stripIVAndDecryptSlot(rawData);
603 slots->set(i, Slot_decode(table, data, mac));
608 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
612 printf("Passing Locally\n");
613 mac->update(sendData, 0, sendData->length());
614 Array<char> *genmac = mac->doFinal();
615 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
616 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
617 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
619 // Encrypt the data for sending
620 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
621 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
623 // Open a TCP socket connection to a local device
624 int socket = createSocket(host, port);
627 // Send data to output (length of data, the data)
628 writeSocketInt(socket, encryptedData->length());
629 writeSocketData(socket, encryptedData);
631 int lengthOfReturnData = readSocketInt(socket);
632 Array<char> *returnData = new Array<char>(lengthOfReturnData);
633 readSocketData(socket, returnData);
635 returnData = stripIVAndDecryptSlot(returnData);
637 // We are done with this socket
639 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
640 Array<char> *realmac = mac->doFinal();
641 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
642 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
644 if (!recmac->equals(realmac))
645 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
647 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
648 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
651 } catch (Exception *e) {
652 printf("Exception\n");
658 void CloudComm::localServerWorkerFunction() {
659 int inputSocket = -1;
662 // Local server socket
663 inputSocket = createSocket(listeningPort);
664 } catch (Exception *e) {
665 throw new Error("Local server setup failure...");
670 // Accept incoming socket
671 int socket = acceptSocket(inputSocket);
673 // Get the encrypted data from the server
674 int dataSize = readSocketInt(socket);
675 Array<char> *readData = new Array<char>(dataSize);
676 readSocketData(socket, readData);
680 readData = stripIVAndDecryptSlot(readData);
681 mac->update(readData, 0, readData->length() - CloudComm_HMAC_SIZE);
682 Array<char> *genmac = mac->doFinal();
683 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
684 System_arraycopy(readData, readData->length() - recmac->length(), recmac, 0, recmac->length());
686 if (!recmac->equals(genmac))
687 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
689 Array<char> *returnData = new Array<char>(readData->length() - recmac->length());
690 System_arraycopy(readData, 0, returnData, 0, returnData->length());
693 Array<char> *sendData = table->acceptDataFromLocal(returnData);
694 mac->update(sendData, 0, sendData->length());
695 Array<char> *realmac = mac->doFinal();
696 Array<char> *totalData = new Array<char>(sendData->length() + realmac->length());
697 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
698 System_arraycopy(realmac, 0, totalData, sendData->length(), realmac->length());
700 // Encrypt the data for sending
701 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
702 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
705 // Send data to output (length of data, the data)
706 writeSocketInt(socket, encryptedData->length());
707 writeSocketData(socket, encryptedData);
709 } catch (Exception *e) {
713 if (inputSocket != -1) {
716 } catch (Exception *e) {
717 throw new Error("Local server close failure...");
722 void CloudComm::closeCloud() {
725 if (listeningPort > 0) {
726 if (pthread_join(localServerThread, NULL) != 0)
727 throw new Error("Local Server thread join issue...");