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() {
80 * Generates Key from password.
82 AESKey *CloudComm::initKey() {
84 AESKey *key = new AESKey(password->internalBytes(),
89 } catch (Exception *e) {
90 throw new Error("Failed generating key.");
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) {
118 password = NULL;// drop password
121 } catch (Exception *e) {
122 throw new Error("Failed To Initialize Ciphers");
127 * Builds the URL for the given request.
129 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
130 const char *reqstring = isput ? "req=putslot" : "req=getslot";
131 char *buffer = (char *) malloc(baseurl->length() + 200);
132 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
133 int offset = baseurl->length();
134 offset += sprintf(&buffer[offset], "?%s&seq=%" PRId64, reqstring, sequencenumber);
136 sprintf(&buffer[offset], "&max=%" PRId64, maxentries);
137 IoTString *urlstr = new IoTString(buffer);
141 void loopWrite(int fd, char *array, int bytestowrite) {
142 int byteswritten = 0;
143 while (bytestowrite) {
144 int bytes = write(fd, &array[byteswritten], bytestowrite);
146 byteswritten += bytes;
147 bytestowrite -= bytes;
149 printf("Error in write\n");
155 void loopRead(int fd, char *array, int bytestoread) {
157 while (bytestoread) {
158 int bytes = read(fd, &array[bytesread], bytestoread);
161 bytestoread -= bytes;
163 printf("Error in read\n");
169 WebConnection openURL(IoTString *url) {
170 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
171 printf("BOGUS URL\n");
175 for (; i < url->length(); i++)
176 if (url->get(i) == '/')
179 if ( i == url->length()) {
180 printf("ERROR in openURL\n");
184 char *host = (char *) malloc(i - 6);
185 memcpy(host, &url->internalBytes()->internalArray()[7], i - 7);
187 printf("%s\n", host);
189 char *message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2 * url->length());
191 /* fill in the parameters */
192 int post = sprintf(message,"POST ");
194 memcpy(&message[post], &url->internalBytes()->internalArray()[i], url->length() - i);
195 int endpost = sprintf(&message[post + url->length() - i], " HTTP/1.1\r\n");
197 int hostlen = sprintf(&message[endpost + post + url->length() - i], "Host: ");
198 memcpy(&message[endpost + post + url->length() + hostlen - i], host, i - 7);
199 sprintf(&message[endpost + post + url->length() + hostlen - 7], "\r\n");
201 /* create the socket */
202 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
203 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
205 /* lookup the ip address */
206 struct hostent *server = gethostbyname(host);
209 if (server == NULL) {printf("ERROR, no such host"); exit(-1);}
211 /* fill in the structure */
212 struct sockaddr_in serv_addr;
214 memset(&serv_addr,0,sizeof(serv_addr));
215 serv_addr.sin_family = AF_INET;
216 serv_addr.sin_port = htons(80);
217 memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
219 /* connect the socket */
220 if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
221 printf("ERROR connecting");
225 /* send the request */
226 int total = strlen(message);
227 loopWrite(sockfd, message, total);
228 return (WebConnection) {sockfd, -1};
231 int createSocket(IoTString *name, int port) {
232 char *host = (char *) malloc(name->length() + 1);
233 memcpy(host, name->internalBytes()->internalArray(), name->length());
234 host[name->length()] = 0;
235 printf("%s\n", host);
236 /* How big is the message? */
238 /* create the socket */
239 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
240 if (sockfd < 0) {printf("ERROR opening socket\n"); exit(-1);}
242 /* lookup the ip address */
243 struct hostent *server = gethostbyname(host);
246 if (server == NULL) {printf("ERROR, no such host"); exit(-1);}
248 /* fill in the structure */
249 struct sockaddr_in serv_addr;
251 memset(&serv_addr,0,sizeof(serv_addr));
252 serv_addr.sin_family = AF_INET;
253 serv_addr.sin_port = htons(port);
254 memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
256 /* connect the socket */
257 if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
258 printf("ERROR connecting");
265 int createSocket(int port) {
267 struct sockaddr_in sin;
269 bzero(&sin, sizeof(sin));
270 sin.sin_family = AF_INET;
271 sin.sin_port = htons(port);
272 sin.sin_addr.s_addr = htonl(INADDR_ANY);
273 fd = socket(AF_INET, SOCK_STREAM, 0);
275 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof (n)) < 0) {
277 printf("Create Socket Error\n");
280 if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
284 if (listen(fd, 5) < 0) {
291 int acceptSocket(int socket) {
292 struct sockaddr_in sin;
293 unsigned int sinlen = sizeof(sin);
294 int newfd = accept(socket, (struct sockaddr *)&sin, &sinlen);
296 setsockopt(newfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(flag));
298 printf("Accept Error\n");
304 void writeSocketData(int fd, Array<char> *data) {
305 loopWrite(fd, data->internalArray(), data->length());
308 void writeSocketInt(int fd, int32_t value) {
310 array[0] = value >> 24;
311 array[1] = (value >> 16) & 0xff;
312 array[2] = (value >> 8) & 0xff;
313 array[3] = value & 0xff;
314 loopWrite(fd, array, 4);
317 int readSocketInt(int fd) {
319 loopRead(fd, array, 4);
320 return (((int32_t)(unsigned char) array[0]) << 24) |
321 (((int32_t)(unsigned char) array[1]) << 16) |
322 (((int32_t)(unsigned char) array[2]) << 8) |
323 ((int32_t)(unsigned char) array[3]);
326 void readSocketData(int fd, Array<char> *data) {
327 loopRead(fd, data->internalArray(), data->length());
330 void writeURLDataAndClose(WebConnection *wc, Array<char> *data) {
331 dprintf(wc->fd, "Content-Length: %d\r\n\r\n", data->length());
332 loopWrite(wc->fd, data->internalArray(), data->length());
335 void closeURLReq(WebConnection *wc) {
336 dprintf(wc->fd, "\r\n");
339 void readURLData(WebConnection *wc, Array<char> *output) {
340 loopRead(wc->fd, output->internalArray(), output->length());
343 int readURLInt(WebConnection *wc) {
345 loopRead(wc->fd, array, 4);
346 return (((int32_t)(unsigned char) array[0]) << 24) |
347 (((int32_t)(unsigned char) array[1]) << 16) |
348 (((int32_t)(unsigned char) array[2]) << 8) |
349 ((int32_t)(unsigned char) array[3]);
352 void readLine(WebConnection *wc, char *response, int numBytes) {
356 int bytes = read(wc->fd, &newchar, 1);
359 if (offset == (numBytes - 1)) {
360 printf("Response too long");
363 response[offset++] = newchar;
367 response[offset] = 0;
370 int getResponseCode(WebConnection *wc) {
372 readLine(wc, response, sizeof(response));
373 int ver1 = 0, ver2 = 0, respcode = 0;
374 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
375 printf("Response code %d\n", respcode);
379 void readHeaders(WebConnection *wc) {
384 readLine(wc, response, sizeof(response));
385 if (response[0] == '\r')
387 else if (memcmp(response, "Content-Length:", sizeof("Content-Length:") - 1) == 0) {
388 sscanf(response, "Content-Length: %d", &numBytes);
389 wc->numBytes = numBytes;
394 void CloudComm::setSalt() {
396 // Salt already sent to server so don't set it again
400 WebConnection wc = {-1, -1};
402 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
403 random->nextBytes(saltTmp);
405 char *buffer = (char *) malloc(baseurl->length() + 100);
406 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
407 int offset = baseurl->length();
408 offset += sprintf(&buffer[offset], "?req=setsalt");
409 IoTString *urlstr = new IoTString(buffer);
413 wc = openURL(urlstr);
414 writeURLDataAndClose(&wc, saltTmp);
416 int responsecode = getResponseCode(&wc);
417 if (responsecode != HttpURLConnection_HTTP_OK) {
418 throw new Error("Invalid response");
424 } catch (Exception *e) {
426 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
430 bool CloudComm::getSalt() {
431 WebConnection wc = {-1, -1};
432 IoTString *urlstr = NULL;
435 char *buffer = (char *) malloc(baseurl->length() + 100);
436 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
437 int offset = baseurl->length();
438 offset += sprintf(&buffer[offset], "?req=getsalt");
439 urlstr = new IoTString(buffer);
441 } catch (Exception *e) {
442 throw new Error("getSlot failed");
446 wc = openURL(urlstr);
451 } catch (SocketTimeoutException *e) {
455 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
456 } catch (Exception *e) {
459 throw new Error("getSlot failed");
464 int responsecode = getResponseCode(&wc);
466 if (responsecode != HttpURLConnection_HTTP_OK) {
467 throw new Error("Invalid response");
469 if (wc.numBytes == 0) {
476 int salt_length = readURLInt(&wc);
477 Array<char> *tmp = new Array<char>(salt_length);
478 readURLData(&wc, tmp);
484 } catch (SocketTimeoutException *e) {
486 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
487 } catch (Exception *e) {
488 throw new Error("getSlot failed");
492 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
493 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
494 buffer->putLong(machineId);
495 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
496 buffer->putLong(localSequenceNumberShifted);
497 return buffer->array();
500 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
501 Array<char> *output = new Array<char>(data->length());
502 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
506 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
507 Array<char> *output = new Array<char>(data->length());
508 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
512 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
514 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
515 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
516 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
517 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
518 delete encryptedBytes;
520 } catch (Exception *e) {
521 throw new Error("Failed To Encrypt");
525 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
527 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
528 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
529 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
530 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
531 Array<char> * data = AESDecrypt(ivBytes, key, encryptedBytes);
532 delete encryptedBytes;
535 } catch (Exception *e) {
536 throw new Error("Failed To Decrypt");
541 * API for putting a slot into the queue. Returns NULL on success.
542 * On failure, the server will send slots with newer sequence
545 Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
546 WebConnection wc = {-1, -1};
550 throw new ServerException("putSlot failed", ServerException_TypeSalt);
555 int64_t sequencenumber = slot->getSequenceNumber();
556 Array<char> *slotBytes = slot->encode(mac);
557 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, slot->getSlotCryptIV());
559 IoTString *url = buildRequest(true, sequencenumber, max);
562 writeURLDataAndClose(&wc, chars);
565 } catch (ServerException *e) {
568 } catch (SocketTimeoutException *e) {
570 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
571 } catch (Exception *e) {
572 throw new Error("putSlot failed");
575 Array<char> *resptype = NULL;
577 int respcode = getResponseCode(&wc);
580 resptype = new Array<char>(7);
581 readURLData(&wc, resptype);
584 if (resptype->equals(getslot)) {
586 Array<Slot *> *tmp = processSlots(&wc);
589 } else if (resptype->equals(putslot)) {
596 throw new Error("Bad response to putslot");
598 } catch (SocketTimeoutException *e) {
599 if (resptype != NULL)
603 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
604 } catch (Exception *e) {
605 if (resptype != NULL)
607 throw new Error("putSlot failed");
612 * Request the server to send all slots with the given
613 * sequencenumber or newer->
615 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
616 WebConnection wc = {-1, -1};
620 throw new ServerException("getSlots failed", ServerException_TypeSalt);
625 IoTString *url = buildRequest(false, sequencenumber, 0);
630 } catch (SocketTimeoutException *e) {
632 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
633 } catch (ServerException *e) {
637 } catch (Exception *e) {
638 throw new Error("getSlots failed");
643 int responsecode = getResponseCode(&wc);
645 Array<char> *resptype = new Array<char>(7);
646 readURLData(&wc, resptype);
648 if (!resptype->equals(getslot))
649 throw new Error("Bad Response: ");
652 Array<Slot *> *tmp = processSlots(&wc);
655 } catch (SocketTimeoutException *e) {
658 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
659 } catch (Exception *e) {
660 throw new Error("getSlots failed");
665 * Method that actually handles building Slot objects from the
666 * server response. Shared by both putSlot and getSlots.
668 Array<Slot *> *CloudComm::processSlots(WebConnection *wc) {
669 int numberofslots = readURLInt(wc);
670 Array<int> *sizesofslots = new Array<int>(numberofslots);
671 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
673 for (int i = 0; i < numberofslots; i++)
674 sizesofslots->set(i, readURLInt(wc));
675 for (int i = 0; i < numberofslots; i++) {
676 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
677 readURLData(wc, rawData);
678 Array<char> *data = stripIVAndDecryptSlot(rawData);
680 slots->set(i, Slot_decode(table, data, mac));
687 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
691 printf("Passing Locally\n");
692 mac->update(sendData, 0, sendData->length());
693 Array<char> *genmac = mac->doFinal();
694 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
695 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
696 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
698 // Encrypt the data for sending
699 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
700 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
702 // Open a TCP socket connection to a local device
703 int socket = createSocket(host, port);
706 // Send data to output (length of data, the data)
707 writeSocketInt(socket, encryptedData->length());
708 writeSocketData(socket, encryptedData);
710 int lengthOfReturnData = readSocketInt(socket);
711 Array<char> *returnData = new Array<char>(lengthOfReturnData);
712 readSocketData(socket, returnData);
714 returnData = stripIVAndDecryptSlot(returnData);
716 // We are done with this socket
718 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
719 Array<char> *realmac = mac->doFinal();
720 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
721 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
723 if (!recmac->equals(realmac))
724 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
726 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
727 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
730 } catch (Exception *e) {
731 printf("Exception\n");
737 void CloudComm::localServerWorkerFunction() {
738 int inputSocket = -1;
741 // Local server socket
742 inputSocket = createSocket(listeningPort);
743 } catch (Exception *e) {
744 throw new Error("Local server setup failure...");
749 // Accept incoming socket
750 int socket = acceptSocket(inputSocket);
752 // Get the encrypted data from the server
753 int dataSize = readSocketInt(socket);
754 Array<char> *readData = new Array<char>(dataSize);
755 readSocketData(socket, readData);
759 readData = stripIVAndDecryptSlot(readData);
760 mac->update(readData, 0, readData->length() - CloudComm_HMAC_SIZE);
761 Array<char> *genmac = mac->doFinal();
762 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
763 System_arraycopy(readData, readData->length() - recmac->length(), recmac, 0, recmac->length());
765 if (!recmac->equals(genmac))
766 throw new Error("Local Error: Invalid HMAC! Potential Attack!");
768 Array<char> *returnData = new Array<char>(readData->length() - recmac->length());
769 System_arraycopy(readData, 0, returnData, 0, returnData->length());
772 Array<char> *sendData = table->acceptDataFromLocal(returnData);
773 mac->update(sendData, 0, sendData->length());
774 Array<char> *realmac = mac->doFinal();
775 Array<char> *totalData = new Array<char>(sendData->length() + realmac->length());
776 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
777 System_arraycopy(realmac, 0, totalData, sendData->length(), realmac->length());
779 // Encrypt the data for sending
780 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
781 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
784 // Send data to output (length of data, the data)
785 writeSocketInt(socket, encryptedData->length());
786 writeSocketData(socket, encryptedData);
788 } catch (Exception *e) {
792 if (inputSocket != -1) {
795 } catch (Exception *e) {
796 throw new Error("Local server close failure...");
801 void CloudComm::closeCloud() {
804 if (listeningPort > 0) {
805 if (pthread_join(localServerThread, NULL) != 0)
806 throw new Error("Local Server thread join issue...");