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))
40 * Constructor for actual use. Takes in the url and password.
42 CloudComm::CloudComm(Table *_table, IoTString *_baseurl, IoTString *_password, int _listeningPort) :
43 baseurl(_baseurl->acquireRef()),
46 password(_password->acquireRef()),
47 random(new SecureRandom()),
50 listeningPort(_listeningPort),
52 timer(TimingSingleton_getInstance()),
53 getslot(new Array<char>("getslot", 7)),
54 putslot(new Array<char>("putslot", 7)) {
55 /* if (listeningPort > 0) {
56 pthread_create(&localServerThread, NULL, threadWrapper, this);
60 CloudComm::~CloudComm() {
66 password->releaseRef();
70 baseurl->releaseRef();
78 * Generates Key from password.
80 AESKey *CloudComm::initKey() {
81 AESKey *key = new AESKey(password->internalBytes(),
89 * Inits all the security stuff
92 void CloudComm::initSecurity() {
93 // try to get the salt and if one does not exist set one
103 * Inits the HMAC generator.
105 void CloudComm::initCrypt() {
106 if (password == NULL) {
110 password->releaseRef();
111 password = NULL;// drop password
116 char * toStr(char * buffer, int64_t num) {
119 buffer[index++] = '0';
122 buffer[index++] = (char) ('0' + (num % 10));
128 while(init < index) {
129 char tmp = buffer[init];
130 buffer[init] = buffer[index];
139 * Builds the URL for the given request.
141 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
142 const char *reqstring = isput ? "req=putslot" : "req=getslot";
143 char *buffer = (char *) malloc(baseurl->length() + 200);
145 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
146 int offset = baseurl->length();
147 offset += sprintf(&buffer[offset], "?%s&seq=%s" , reqstring, toStr(prbuffer,sequencenumber));
149 sprintf(&buffer[offset], "&max=%s" , toStr(prbuffer,maxentries));
150 IoTString *urlstr = new IoTString(buffer);
155 void loopWrite(TCPClient * client, char *array, int bytestowrite) {
156 int byteswritten = 0;
157 while (bytestowrite) {
158 int bytes = client->write((const unsigned char *) &array[byteswritten], bytestowrite);
160 byteswritten += bytes;
161 bytestowrite -= bytes;
163 Serial.println("Error in write");
169 void loopRead(TCPClient * client, char *array, int bytestoread) {
171 while (bytestoread) {
172 int bytes = client->read((unsigned char *) &array[bytesread], bytestoread);
175 bytestoread -= bytes;
177 if (!client->connected()) {
178 Serial.println("Client disconnected");
185 WebConnection openURL(IoTString *url) {
186 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
187 //printf("BOGUS URL\n");
191 for (; i < url->length(); i++)
192 if (url->get(i) == '/')
196 if ( i == url->length()) {
197 //printf("ERROR in openURL\n");
201 char *host = (char *) malloc(i - 6);
202 memcpy(host, &url->internalBytes()->internalArray()[7], i - 7);
204 //printf("%s\n", host);
205 char *message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2 * url->length());
207 /* fill in the parameters */
208 int post = sprintf(message,"POST ");
210 memcpy(&message[post], &url->internalBytes()->internalArray()[i], url->length() - i);
211 int endpost = sprintf(&message[post + url->length() - i], " HTTP/1.1\r\n");
212 int hostlen = sprintf(&message[endpost + post + url->length() - i], "Host: ");
213 memcpy(&message[endpost + post + url->length() + hostlen - i], host, i - 7);
214 sprintf(&message[endpost + post + url->length() + hostlen - 7], "\r\n");
218 if (!wc.client.connect(host, 80)) {
219 myerror("ERROR connecting\n");
222 /* send the request */
223 int total = strlen(message);
224 loopWrite(&wc.client, message, total);
229 TCPClient createSocket(IoTString *name, int port) {
230 char *host = (char *) malloc(name->length() + 1);
231 memcpy(host, name->internalBytes()->internalArray(), name->length());
232 host[name->length()] = 0;
233 //printf("%s\n", host);
235 /* lookup the ip address */
237 if (!client.connect(host, port)) {
238 myerror("ERROR connecting\n");
245 void writeSocketData(TCPClient * fd, Array<char> *data) {
246 loopWrite(fd, data->internalArray(), data->length());
249 void writeSocketInt(TCPClient * fd, int32_t value) {
251 array[0] = value >> 24;
252 array[1] = (value >> 16) & 0xff;
253 array[2] = (value >> 8) & 0xff;
254 array[3] = value & 0xff;
255 loopWrite(fd, array, 4);
258 int readSocketInt(TCPClient * fd) {
260 loopRead(fd, array, 4);
261 return (((int32_t)(unsigned char) array[0]) << 24) |
262 (((int32_t)(unsigned char) array[1]) << 16) |
263 (((int32_t)(unsigned char) array[2]) << 8) |
264 ((int32_t)(unsigned char) array[3]);
267 void readSocketData(TCPClient * fd, Array<char> *data) {
268 loopRead(fd, data->internalArray(), data->length());
271 void writeURLDataAndClose(WebConnection *wc, Array<char> *data) {
273 sprintf(buffer, "Content-Length: %d\r\n\r\n", data->length());
274 wc->client.print(buffer);
275 loopWrite(&wc->client, data->internalArray(), data->length());
278 void closeURLReq(WebConnection *wc) {
279 wc->client.println("");
282 void readURLData(WebConnection *wc, Array<char> *output) {
283 loopRead(&wc->client, output->internalArray(), output->length());
286 int readURLInt(WebConnection *wc) {
288 loopRead(&wc->client, array, 4);
289 return (((int32_t)(unsigned char) array[0]) << 24) |
290 (((int32_t)(unsigned char) array[1]) << 16) |
291 (((int32_t)(unsigned char) array[2]) << 8) |
292 ((int32_t)(unsigned char) array[3]);
295 void readLine(WebConnection *wc, char *response, int numBytes) {
299 int bytes = wc->client.read((unsigned char *) &newchar, 1);
300 if (!wc->client.connected())
305 if (offset == (numBytes - 1)) {
306 //printf("Response too long");
309 response[offset++] = newchar;
313 response[offset] = 0;
316 int getResponseCode(WebConnection *wc) {
318 readLine(wc, response, sizeof(response));
319 int ver1 = 0, ver2 = 0, respcode = 0;
320 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
321 //printf("Response code %d\n", respcode);
325 void readHeaders(WebConnection *wc) {
329 readLine(wc, response, sizeof(response));
330 if (response[0] == '\r') {
333 else if (memcmp(response, "Content-Length:", sizeof("Content-Length:") - 1) == 0) {
334 sscanf(response, "Content-Length: %d", &numBytes);
335 wc->numBytes = numBytes;
340 void CloudComm::setSalt() {
342 // Salt already sent to server so don't set it again
346 WebConnection wc = {-1, -1};
348 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
349 random->nextBytes(saltTmp);
351 char *buffer = (char *) malloc(baseurl->length() + 100);
352 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
353 int offset = baseurl->length();
354 offset += sprintf(&buffer[offset], "?req=setsalt");
355 IoTString *urlstr = new IoTString(buffer);
359 wc = openURL(urlstr);
361 writeURLDataAndClose(&wc, saltTmp);
363 int responsecode = getResponseCode(&wc);
364 if (responsecode != HttpURLConnection_HTTP_OK) {
365 //throw new Error("Invalid response");
366 myerror("Invalid response\n");
372 /* } catch (Exception *e) {
374 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
378 bool CloudComm::getSalt() {
381 IoTString *urlstr = NULL;
384 char *buffer = (char *) malloc(baseurl->length() + 100);
385 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
386 int offset = baseurl->length();
387 offset += sprintf(&buffer[offset], "?req=getsalt");
388 urlstr = new IoTString(buffer);
390 /* } catch (Exception *e) {
391 throw new Error("getSlot failed");
395 wc = openURL(urlstr);
400 /* } catch (SocketTimeoutException *e) {
404 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
405 } catch (Exception *e) {
408 throw new Error("getSlot failed");
413 int responsecode = getResponseCode(&wc);
415 if (responsecode != HttpURLConnection_HTTP_OK) {
416 //throw new Error("Invalid response");
417 myerror("Invalid response\n");
419 if (wc.numBytes == 0) {
426 int salt_length = readURLInt(&wc);
427 Array<char> *tmp = new Array<char>(salt_length);
428 readURLData(&wc, tmp);
434 /* } catch (SocketTimeoutException *e) {
436 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
437 } catch (Exception *e) {
438 throw new Error("getSlot failed");
442 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
443 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
444 buffer->putLong(machineId);
445 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
446 buffer->putLong(localSequenceNumberShifted);
447 return buffer->array();
450 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
451 Array<char> *output = new Array<char>(data->length());
452 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
456 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
457 Array<char> *output = new Array<char>(data->length());
458 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
462 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
464 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
465 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
466 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
467 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
468 delete encryptedBytes;
470 /* } catch (Exception *e) {
471 throw new Error("Failed To Encrypt");
475 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
477 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
478 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
479 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
480 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
481 Array<char> * data = AESDecrypt(ivBytes, key, encryptedBytes);
482 delete encryptedBytes;
485 /* } catch (Exception *e) {
486 throw new Error("Failed To Decrypt");
491 * API for putting a slot into the queue. Returns NULL on success.
492 * On failure, the server will send slots with newer sequence
495 Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
496 WebConnection wc = {-1, -1};
500 // throw new ServerException("putSlot failed", ServerException_TypeSalt);
501 myerror("putSlot failed\n");
506 int64_t sequencenumber = slot->getSequenceNumber();
507 Array<char> *slotBytes = slot->encode(mac);
508 Array<char> * ivBytes = slot->getSlotCryptIV();
509 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, ivBytes);
512 IoTString *url = buildRequest(true, sequencenumber, max);
516 writeURLDataAndClose(&wc, chars);
519 /* } catch (ServerException *e) {
522 } catch (SocketTimeoutException *e) {
524 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
525 } catch (Exception *e) {
526 throw new Error("putSlot failed");
529 Array<char> *resptype = NULL;
531 int respcode = getResponseCode(&wc);
534 resptype = new Array<char>(7);
535 readURLData(&wc, resptype);
538 if (resptype->equals(getslot)) {
540 Array<Slot *> *tmp = processSlots(&wc);
543 } else if (resptype->equals(putslot)) {
550 Serial.println("Bad response to putslot");
552 /* } catch (SocketTimeoutException *e) {
553 if (resptype != NULL)
557 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
558 } catch (Exception *e) {
559 if (resptype != NULL)
561 throw new Error("putSlot failed");
566 * Request the server to send all slots with the given
567 * sequencenumber or newer->
569 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
570 WebConnection wc = {-1, -1};
574 //throw new ServerException("getSlots failed", ServerException_TypeSalt);
575 myerror("getSlots failed\n");
580 IoTString *url = buildRequest(false, sequencenumber, 0);
586 /* } catch (SocketTimeoutException *e) {
588 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
589 } catch (ServerException *e) {
593 } catch (Exception *e) {
594 throw new Error("getSlots failed");
599 int responsecode = getResponseCode(&wc);
601 Array<char> *resptype = new Array<char>(7);
602 readURLData(&wc, resptype);
604 if (!resptype->equals(getslot))
605 // throw new Error("Bad Response: ");
606 myerror("Bad Response: \n");
609 Array<Slot *> *tmp = processSlots(&wc);
612 /* } catch (SocketTimeoutException *e) {
615 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
616 } catch (Exception *e) {
617 throw new Error("getSlots failed");
622 * Method that actually handles building Slot objects from the
623 * server response. Shared by both putSlot and getSlots.
625 Array<Slot *> *CloudComm::processSlots(WebConnection *wc) {
626 int numberofslots = readURLInt(wc);
627 Array<int> *sizesofslots = new Array<int>(numberofslots);
628 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
630 for (int i = 0; i < numberofslots; i++)
631 sizesofslots->set(i, readURLInt(wc));
632 for (int i = 0; i < numberofslots; i++) {
633 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
634 readURLData(wc, rawData);
635 Array<char> *data = stripIVAndDecryptSlot(rawData);
637 slots->set(i, Slot_decode(table, data, mac));
644 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
648 //printf("Passing Locally\n");
649 mac->update(sendData, 0, sendData->length());
650 Array<char> *genmac = mac->doFinal();
651 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
652 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
653 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
655 // Encrypt the data for sending
656 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
657 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
659 // Open a TCP socket connection to a local device
660 TCPClient socket = createSocket(host, port);
663 // Send data to output (length of data, the data)
664 writeSocketInt(&socket, encryptedData->length());
665 writeSocketData(&socket, encryptedData);
667 int lengthOfReturnData = readSocketInt(&socket);
668 Array<char> *returnData = new Array<char>(lengthOfReturnData);
669 readSocketData(&socket, returnData);
671 returnData = stripIVAndDecryptSlot(returnData);
673 // We are done with this socket
675 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
676 Array<char> *realmac = mac->doFinal();
677 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
678 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
680 if (!recmac->equals(realmac))
681 // throw new Error("Local Error: Invalid HMAC! Potential Attack!");
682 myerror("Local Error: Invalid HMAC! Potential Attack!\n");
684 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
685 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
688 /* } catch (Exception *e) {
689 printf("Exception\n");
695 void CloudComm::closeCloud() {
698 /* if (listeningPort > 0) {
699 if (pthread_join(localServerThread, NULL) != 0)
700 throw new Error("Local Server thread join issue...");