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() :
34 timer(TimingSingleton_getInstance()),
35 getslot(new Array<char>("getslot", 7)),
36 putslot(new Array<char>("putslot", 7))
41 * Constructor for actual use. Takes in the url and password.
43 CloudComm::CloudComm(Table *_table, IoTString *_baseurl, IoTString *_password, int _listeningPort) :
44 baseurl(_baseurl->acquireRef()),
47 password(_password->acquireRef()),
48 random(new SecureRandom()),
52 listeningPort(_listeningPort),
54 timer(TimingSingleton_getInstance()),
55 getslot(new Array<char>("getslot", 7)),
56 putslot(new Array<char>("putslot", 7)) {
57 /* if (listeningPort > 0) {
58 pthread_create(&localServerThread, NULL, threadWrapper, this);
62 CloudComm::~CloudComm() {
70 password->releaseRef();
74 baseurl->releaseRef();
82 * Generates Key from password.
84 AESKey *CloudComm::initKey() {
85 AESKey *key = new AESKey(password->internalBytes(),
93 * Inits all the security stuff
96 void CloudComm::initSecurity() {
97 // try to get the salt and if one does not exist set one
107 * Inits the HMAC generator.
109 void CloudComm::initCrypt() {
110 if (password == NULL) {
114 password->releaseRef();
115 password = NULL;// drop password
120 char * toStr(char * buffer, int64_t num) {
123 buffer[index++] = '0';
126 buffer[index++] = (char) ('0' + (num % 10));
132 while(init < index) {
133 char tmp = buffer[init];
134 buffer[init] = buffer[index];
143 * Builds the URL for the given request.
145 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
146 const char *reqstring = isput ? "req=putslot" : "req=getslot";
147 char *buffer = (char *) malloc(baseurl->length() + 200);
149 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
150 int offset = baseurl->length();
151 offset += sprintf(&buffer[offset], "?%s&seq=%s" , reqstring, toStr(prbuffer,sequencenumber));
153 sprintf(&buffer[offset], "&max=%s" , toStr(prbuffer,maxentries));
154 IoTString *urlstr = new IoTString(buffer);
159 void loopWrite(TCPClient * client, char *array, int bytestowrite) {
160 int byteswritten = 0;
161 while (bytestowrite) {
162 int bytes = client->write((const unsigned char *) &array[byteswritten], bytestowrite);
164 byteswritten += bytes;
165 bytestowrite -= bytes;
167 Serial.println("Error in write");
173 void loopRead(TCPClient * client, char *array, int bytestoread) {
175 while (bytestoread) {
176 int bytes = client->read((unsigned char *) &array[bytesread], bytestoread);
179 bytestoread -= bytes;
181 if (!client->connected()) {
182 Serial.println("Client disconnected");
189 WebConnection openURL(IoTString *url) {
190 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
191 //printf("BOGUS URL\n");
195 for (; i < url->length(); i++)
196 if (url->get(i) == '/')
200 if ( i == url->length()) {
201 //printf("ERROR in openURL\n");
205 char *host = (char *) malloc(i - 6);
206 memcpy(host, &url->internalBytes()->internalArray()[7], i - 7);
208 //printf("%s\n", host);
209 char *message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2 * url->length());
211 /* fill in the parameters */
212 int post = sprintf(message,"POST ");
214 memcpy(&message[post], &url->internalBytes()->internalArray()[i], url->length() - i);
215 int endpost = sprintf(&message[post + url->length() - i], " HTTP/1.1\r\n");
216 int hostlen = sprintf(&message[endpost + post + url->length() - i], "Host: ");
217 memcpy(&message[endpost + post + url->length() + hostlen - i], host, i - 7);
218 sprintf(&message[endpost + post + url->length() + hostlen - 7], "\r\n");
222 if (!wc.client.connect(host, 80)) {
223 myerror("ERROR connecting\n");
226 /* send the request */
227 int total = strlen(message);
228 loopWrite(&wc.client, message, total);
233 TCPClient createSocket(IoTString *name, int port) {
234 char *host = (char *) malloc(name->length() + 1);
235 memcpy(host, name->internalBytes()->internalArray(), name->length());
236 host[name->length()] = 0;
237 //printf("%s\n", host);
239 /* lookup the ip address */
241 if (!client.connect(host, port)) {
242 myerror("ERROR connecting\n");
249 void writeSocketData(TCPClient * fd, Array<char> *data) {
250 loopWrite(fd, data->internalArray(), data->length());
253 void writeSocketInt(TCPClient * fd, int32_t value) {
255 array[0] = value >> 24;
256 array[1] = (value >> 16) & 0xff;
257 array[2] = (value >> 8) & 0xff;
258 array[3] = value & 0xff;
259 loopWrite(fd, array, 4);
262 int readSocketInt(TCPClient * fd) {
264 loopRead(fd, array, 4);
265 return (((int32_t)(unsigned char) array[0]) << 24) |
266 (((int32_t)(unsigned char) array[1]) << 16) |
267 (((int32_t)(unsigned char) array[2]) << 8) |
268 ((int32_t)(unsigned char) array[3]);
271 void readSocketData(TCPClient * fd, Array<char> *data) {
272 loopRead(fd, data->internalArray(), data->length());
275 void writeURLDataAndClose(WebConnection *wc, Array<char> *data) {
277 sprintf(buffer, "Content-Length: %d\r\n\r\n", data->length());
278 wc->client.print(buffer);
279 loopWrite(&wc->client, data->internalArray(), data->length());
282 void closeURLReq(WebConnection *wc) {
283 wc->client.println("");
286 void readURLData(WebConnection *wc, Array<char> *output) {
287 loopRead(&wc->client, output->internalArray(), output->length());
290 int readURLInt(WebConnection *wc) {
292 loopRead(&wc->client, array, 4);
293 return (((int32_t)(unsigned char) array[0]) << 24) |
294 (((int32_t)(unsigned char) array[1]) << 16) |
295 (((int32_t)(unsigned char) array[2]) << 8) |
296 ((int32_t)(unsigned char) array[3]);
299 void readLine(WebConnection *wc, char *response, int numBytes) {
303 int bytes = wc->client.read((unsigned char *) &newchar, 1);
304 if (!wc->client.connected())
309 if (offset == (numBytes - 1)) {
310 //printf("Response too long");
313 response[offset++] = newchar;
317 response[offset] = 0;
320 int getResponseCode(WebConnection *wc) {
322 readLine(wc, response, sizeof(response));
323 int ver1 = 0, ver2 = 0, respcode = 0;
324 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
325 //printf("Response code %d\n", respcode);
329 void readHeaders(WebConnection *wc) {
333 readLine(wc, response, sizeof(response));
334 if (response[0] == '\r') {
337 else if (memcmp(response, "Content-Length:", sizeof("Content-Length:") - 1) == 0) {
338 sscanf(response, "Content-Length: %d", &numBytes);
339 wc->numBytes = numBytes;
344 void CloudComm::setSalt() {
346 // Salt already sent to server so don't set it again
350 WebConnection wc = {-1, -1};
352 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
353 random->nextBytes(saltTmp);
355 char *buffer = (char *) malloc(baseurl->length() + 100);
356 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
357 int offset = baseurl->length();
358 offset += sprintf(&buffer[offset], "?req=setsalt");
359 IoTString *urlstr = new IoTString(buffer);
363 wc = openURL(urlstr);
365 writeURLDataAndClose(&wc, saltTmp);
367 int responsecode = getResponseCode(&wc);
368 if (responsecode != HttpURLConnection_HTTP_OK) {
369 //throw new Error("Invalid response");
370 myerror("Invalid response\n");
376 /* } catch (Exception *e) {
378 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
382 bool CloudComm::getSalt() {
385 IoTString *urlstr = NULL;
388 char *buffer = (char *) malloc(baseurl->length() + 100);
389 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
390 int offset = baseurl->length();
391 offset += sprintf(&buffer[offset], "?req=getsalt");
392 urlstr = new IoTString(buffer);
394 /* } catch (Exception *e) {
395 throw new Error("getSlot failed");
399 wc = openURL(urlstr);
404 /* } catch (SocketTimeoutException *e) {
408 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
409 } catch (Exception *e) {
412 throw new Error("getSlot failed");
417 int responsecode = getResponseCode(&wc);
419 if (responsecode != HttpURLConnection_HTTP_OK) {
420 //throw new Error("Invalid response");
421 myerror("Invalid response\n");
423 if (wc.numBytes == 0) {
430 int salt_length = readURLInt(&wc);
431 Array<char> *tmp = new Array<char>(salt_length);
432 readURLData(&wc, tmp);
438 /* } catch (SocketTimeoutException *e) {
440 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
441 } catch (Exception *e) {
442 throw new Error("getSlot failed");
446 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
447 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
448 buffer->putLong(machineId);
449 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
450 buffer->putLong(localSequenceNumberShifted);
451 return buffer->array();
454 void CloudComm::createIV() {
455 if (ivArray == NULL) {
456 ivArray = new Array<char>(CloudComm_IV_SIZE);
457 random->nextBytes(ivArray);
461 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
462 Array<char> *output = new Array<char>(data->length());
463 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
467 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
468 Array<char> *output = new Array<char>(data->length());
469 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
473 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
475 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
476 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
477 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
478 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
479 delete encryptedBytes;
481 /* } catch (Exception *e) {
482 throw new Error("Failed To Encrypt");
486 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
488 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
489 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
490 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
491 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
492 Array<char> * data = AESDecrypt(ivBytes, key, encryptedBytes);
493 delete encryptedBytes;
496 /* } catch (Exception *e) {
497 throw new Error("Failed To Decrypt");
502 * API for putting a slot into the queue. Returns NULL on success.
503 * On failure, the server will send slots with newer sequence
506 Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
507 WebConnection wc = {-1, -1};
511 // throw new ServerException("putSlot failed", ServerException_TypeSalt);
512 myerror("putSlot failed\n");
517 int64_t sequencenumber = slot->getSequenceNumber();
518 Array<char> *slotBytes = slot->encode(mac);
519 //Array<char> * ivBytes = slot->getSlotCryptIV();
520 //Array<char> *chars = encryptSlotAndPrependIV(slotBytes, ivBytes);
523 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, ivArray);
525 IoTString *url = buildRequest(true, sequencenumber, max);
529 writeURLDataAndClose(&wc, chars);
532 /* } catch (ServerException *e) {
535 } catch (SocketTimeoutException *e) {
537 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
538 } catch (Exception *e) {
539 throw new Error("putSlot failed");
542 Array<char> *resptype = NULL;
544 int respcode = getResponseCode(&wc);
547 resptype = new Array<char>(7);
548 readURLData(&wc, resptype);
551 if (resptype->equals(getslot)) {
553 Array<Slot *> *tmp = processSlots(&wc);
556 } else if (resptype->equals(putslot)) {
563 Serial.println("Bad response to putslot");
565 /* } catch (SocketTimeoutException *e) {
566 if (resptype != NULL)
570 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
571 } catch (Exception *e) {
572 if (resptype != NULL)
574 throw new Error("putSlot failed");
579 * Request the server to send all slots with the given
580 * sequencenumber or newer->
582 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
583 WebConnection wc = {-1, -1};
587 //throw new ServerException("getSlots failed", ServerException_TypeSalt);
588 myerror("getSlots failed\n");
593 IoTString *url = buildRequest(false, sequencenumber, 0);
599 /* } catch (SocketTimeoutException *e) {
601 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
602 } catch (ServerException *e) {
606 } catch (Exception *e) {
607 throw new Error("getSlots failed");
612 int responsecode = getResponseCode(&wc);
614 Array<char> *resptype = new Array<char>(7);
615 readURLData(&wc, resptype);
617 if (!resptype->equals(getslot))
618 // throw new Error("Bad Response: ");
619 myerror("Bad Response: \n");
622 Array<Slot *> *tmp = processSlots(&wc);
625 /* } catch (SocketTimeoutException *e) {
628 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
629 } catch (Exception *e) {
630 throw new Error("getSlots failed");
635 * Method that actually handles building Slot objects from the
636 * server response. Shared by both putSlot and getSlots.
638 Array<Slot *> *CloudComm::processSlots(WebConnection *wc) {
639 int numberofslots = readURLInt(wc);
640 Array<int> *sizesofslots = new Array<int>(numberofslots);
641 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
643 for (int i = 0; i < numberofslots; i++)
644 sizesofslots->set(i, readURLInt(wc));
645 for (int i = 0; i < numberofslots; i++) {
646 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
647 readURLData(wc, rawData);
648 Array<char> *data = stripIVAndDecryptSlot(rawData);
650 slots->set(i, Slot_decode(table, data, mac));
657 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
661 //printf("Passing Locally\n");
662 mac->update(sendData, 0, sendData->length());
663 Array<char> *genmac = mac->doFinal();
664 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
665 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
666 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
668 // Encrypt the data for sending
669 //Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
670 //Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
672 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, ivArray);
674 // Open a TCP socket connection to a local device
675 TCPClient socket = createSocket(host, port);
678 // Send data to output (length of data, the data)
679 writeSocketInt(&socket, encryptedData->length());
680 writeSocketData(&socket, encryptedData);
682 int lengthOfReturnData = readSocketInt(&socket);
683 Array<char> *returnData = new Array<char>(lengthOfReturnData);
684 readSocketData(&socket, returnData);
686 returnData = stripIVAndDecryptSlot(returnData);
688 // We are done with this socket
690 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
691 Array<char> *realmac = mac->doFinal();
692 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
693 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
695 if (!recmac->equals(realmac))
696 // throw new Error("Local Error: Invalid HMAC! Potential Attack!");
697 myerror("Local Error: Invalid HMAC! Potential Attack!\n");
699 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
700 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
703 /* } catch (Exception *e) {
704 printf("Exception\n");
710 void CloudComm::closeCloud() {
713 /* if (listeningPort > 0) {
714 if (pthread_join(localServerThread, NULL) != 0)
715 throw new Error("Local Server thread join issue...");