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
117 * Builds the URL for the given request.
119 IoTString *CloudComm::buildRequest(bool isput, int64_t sequencenumber, int64_t maxentries) {
120 const char *reqstring = isput ? "req=putslot" : "req=getslot";
121 char *buffer = (char *) malloc(baseurl->length() + 200);
122 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
123 int offset = baseurl->length();
124 offset += sprintf(&buffer[offset], "?%s&seq=%" PRId64, reqstring, sequencenumber);
126 sprintf(&buffer[offset], "&max=%" PRId64, maxentries);
127 IoTString *urlstr = new IoTString(buffer);
132 void loopWrite(TCPClient * client, char *array, int bytestowrite) {
133 int byteswritten = 0;
134 while (bytestowrite) {
135 int bytes = client->write((const unsigned char *) &array[byteswritten], bytestowrite);
137 byteswritten += bytes;
138 bytestowrite -= bytes;
140 //printf("Error in write\n");
146 void loopRead(TCPClient * client, char *array, int bytestoread) {
148 while (bytestoread) {
149 int bytes = client->read((unsigned char *) &array[bytesread], bytestoread);
152 bytestoread -= bytes;
154 //printf("Error in read\n");
160 WebConnection openURL(IoTString *url) {
161 if (url->length() < 7 || memcmp(url->internalBytes()->internalArray(), "http://", 7)) {
162 //printf("BOGUS URL\n");
166 for (; i < url->length(); i++)
167 if (url->get(i) == '/')
170 if ( i == url->length()) {
171 //printf("ERROR in openURL\n");
175 char *host = (char *) malloc(i - 6);
176 memcpy(host, &url->internalBytes()->internalArray()[7], i - 7);
178 //printf("%s\n", host);
180 char *message = (char *)malloc(sizeof("POST HTTP/1.1\r\n") + sizeof("Host: \r\n") + 2 * url->length());
182 /* fill in the parameters */
183 int post = sprintf(message,"POST ");
185 memcpy(&message[post], &url->internalBytes()->internalArray()[i], url->length() - i);
186 int endpost = sprintf(&message[post + url->length() - i], " HTTP/1.1\r\n");
188 int hostlen = sprintf(&message[endpost + post + url->length() - i], "Host: ");
189 memcpy(&message[endpost + post + url->length() + hostlen - i], host, i - 7);
190 sprintf(&message[endpost + post + url->length() + hostlen - 7], "\r\n");
196 if (!wc.client.connect(host, 80)) {
197 myerror("ERROR connecting\n");
201 /* send the request */
202 int total = strlen(message);
203 loopWrite(&wc.client, message, total);
208 TCPClient createSocket(IoTString *name, int port) {
209 char *host = (char *) malloc(name->length() + 1);
210 memcpy(host, name->internalBytes()->internalArray(), name->length());
211 host[name->length()] = 0;
212 //printf("%s\n", host);
214 /* lookup the ip address */
216 if (!client.connect(host, port)) {
217 myerror("ERROR connecting\n");
224 void writeSocketData(TCPClient * fd, Array<char> *data) {
225 loopWrite(fd, data->internalArray(), data->length());
228 void writeSocketInt(TCPClient * fd, int32_t value) {
230 array[0] = value >> 24;
231 array[1] = (value >> 16) & 0xff;
232 array[2] = (value >> 8) & 0xff;
233 array[3] = value & 0xff;
234 loopWrite(fd, array, 4);
237 int readSocketInt(TCPClient * fd) {
239 loopRead(fd, array, 4);
240 return (((int32_t)(unsigned char) array[0]) << 24) |
241 (((int32_t)(unsigned char) array[1]) << 16) |
242 (((int32_t)(unsigned char) array[2]) << 8) |
243 ((int32_t)(unsigned char) array[3]);
246 void readSocketData(TCPClient * fd, Array<char> *data) {
247 loopRead(fd, data->internalArray(), data->length());
250 void writeURLDataAndClose(WebConnection *wc, Array<char> *data) {
252 sprintf(buffer, "Content-Length: %d\r\n\r\n", data->length());
253 wc->client.print(buffer);
254 loopWrite(&wc->client, data->internalArray(), data->length());
257 void closeURLReq(WebConnection *wc) {
258 wc->client.println("");
261 void readURLData(WebConnection *wc, Array<char> *output) {
262 loopRead(&wc->client, output->internalArray(), output->length());
265 int readURLInt(WebConnection *wc) {
267 loopRead(&wc->client, array, 4);
268 return (((int32_t)(unsigned char) array[0]) << 24) |
269 (((int32_t)(unsigned char) array[1]) << 16) |
270 (((int32_t)(unsigned char) array[2]) << 8) |
271 ((int32_t)(unsigned char) array[3]);
274 void readLine(WebConnection *wc, char *response, int numBytes) {
278 int bytes = wc->client.read((unsigned char *) &newchar, 1);
281 if (offset == (numBytes - 1)) {
282 //printf("Response too long");
285 response[offset++] = newchar;
289 response[offset] = 0;
292 int getResponseCode(WebConnection *wc) {
294 readLine(wc, response, sizeof(response));
295 int ver1 = 0, ver2 = 0, respcode = 0;
296 sscanf(response, "HTTP/%d.%d %d", &ver1, &ver2, &respcode);
297 //printf("Response code %d\n", respcode);
301 void readHeaders(WebConnection *wc) {
306 readLine(wc, response, sizeof(response));
307 if (response[0] == '\r')
309 else if (memcmp(response, "Content-Length:", sizeof("Content-Length:") - 1) == 0) {
310 sscanf(response, "Content-Length: %d", &numBytes);
311 wc->numBytes = numBytes;
316 void CloudComm::setSalt() {
318 // Salt already sent to server so don't set it again
322 WebConnection wc = {-1, -1};
324 Array<char> *saltTmp = new Array<char>(CloudComm_SALT_SIZE);
325 random->nextBytes(saltTmp);
327 char *buffer = (char *) malloc(baseurl->length() + 100);
328 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
329 int offset = baseurl->length();
330 offset += sprintf(&buffer[offset], "?req=setsalt");
331 IoTString *urlstr = new IoTString(buffer);
335 wc = openURL(urlstr);
337 writeURLDataAndClose(&wc, saltTmp);
339 int responsecode = getResponseCode(&wc);
340 if (responsecode != HttpURLConnection_HTTP_OK) {
341 //throw new Error("Invalid response");
342 myerror("Invalid response\n");
348 /* } catch (Exception *e) {
350 throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
354 bool CloudComm::getSalt() {
357 IoTString *urlstr = NULL;
360 char *buffer = (char *) malloc(baseurl->length() + 100);
361 memcpy(buffer, baseurl->internalBytes()->internalArray(), baseurl->length());
362 int offset = baseurl->length();
363 offset += sprintf(&buffer[offset], "?req=getsalt");
364 urlstr = new IoTString(buffer);
366 /* } catch (Exception *e) {
367 throw new Error("getSlot failed");
371 wc = openURL(urlstr);
376 /* } catch (SocketTimeoutException *e) {
380 throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
381 } catch (Exception *e) {
384 throw new Error("getSlot failed");
389 int responsecode = getResponseCode(&wc);
391 if (responsecode != HttpURLConnection_HTTP_OK) {
392 //throw new Error("Invalid response");
393 myerror("Invalid response\n");
395 if (wc.numBytes == 0) {
402 int salt_length = readURLInt(&wc);
403 Array<char> *tmp = new Array<char>(salt_length);
404 readURLData(&wc, tmp);
410 /* } catch (SocketTimeoutException *e) {
412 throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
413 } catch (Exception *e) {
414 throw new Error("getSlot failed");
418 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
419 ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
420 buffer->putLong(machineId);
421 int64_t localSequenceNumberShifted = localSequenceNumber << 16;
422 buffer->putLong(localSequenceNumberShifted);
423 return buffer->array();
426 Array<char> *AESEncrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
427 Array<char> *output = new Array<char>(data->length());
428 aes_encrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *) output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
432 Array<char> *AESDecrypt(Array<char> *ivBytes, AESKey *key, Array<char> *data) {
433 Array<char> *output = new Array<char>(data->length());
434 aes_decrypt_ctr((BYTE *)data->internalArray(), data->length(), (BYTE *)output->internalArray(), (WORD *)key->getKeySchedule(), key->getKey()->length() * 8, (BYTE *)ivBytes->internalArray());
438 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
440 Array<char> *encryptedBytes = AESEncrypt(ivBytes, key, rawData);
441 Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
442 System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
443 System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
444 delete encryptedBytes;
446 /* } catch (Exception *e) {
447 throw new Error("Failed To Encrypt");
451 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
453 Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
454 Array<char> *encryptedBytes = new Array<char>(rawData->length() - CloudComm_IV_SIZE);
455 System_arraycopy(rawData, 0, ivBytes, 0, CloudComm_IV_SIZE);
456 System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length());
457 Array<char> * data = AESDecrypt(ivBytes, key, encryptedBytes);
458 delete encryptedBytes;
461 /* } catch (Exception *e) {
462 throw new Error("Failed To Decrypt");
467 * API for putting a slot into the queue. Returns NULL on success.
468 * On failure, the server will send slots with newer sequence
471 Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
472 WebConnection wc = {-1, -1};
476 // throw new ServerException("putSlot failed", ServerException_TypeSalt);
477 myerror("putSlot failed\n");
482 int64_t sequencenumber = slot->getSequenceNumber();
483 Array<char> *slotBytes = slot->encode(mac);
484 Array<char> * ivBytes = slot->getSlotCryptIV();
485 Array<char> *chars = encryptSlotAndPrependIV(slotBytes, ivBytes);
488 IoTString *url = buildRequest(true, sequencenumber, max);
492 writeURLDataAndClose(&wc, chars);
495 /* } catch (ServerException *e) {
498 } catch (SocketTimeoutException *e) {
500 throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
501 } catch (Exception *e) {
502 throw new Error("putSlot failed");
505 Array<char> *resptype = NULL;
507 int respcode = getResponseCode(&wc);
510 resptype = new Array<char>(7);
511 readURLData(&wc, resptype);
514 if (resptype->equals(getslot)) {
516 Array<Slot *> *tmp = processSlots(&wc);
519 } else if (resptype->equals(putslot)) {
526 //throw new Error("Bad response to putslot");
527 myerror("Bad response to putslot\n");
529 /* } catch (SocketTimeoutException *e) {
530 if (resptype != NULL)
534 throw new ServerException("putSlot failed", ServerException_TypeInputTimeout);
535 } catch (Exception *e) {
536 if (resptype != NULL)
538 throw new Error("putSlot failed");
543 * Request the server to send all slots with the given
544 * sequencenumber or newer->
546 Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
547 WebConnection wc = {-1, -1};
551 //throw new ServerException("getSlots failed", ServerException_TypeSalt);
552 myerror("getSlots failed\n");
557 IoTString *url = buildRequest(false, sequencenumber, 0);
563 /* } catch (SocketTimeoutException *e) {
565 throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
566 } catch (ServerException *e) {
570 } catch (Exception *e) {
571 throw new Error("getSlots failed");
576 int responsecode = getResponseCode(&wc);
578 Array<char> *resptype = new Array<char>(7);
579 readURLData(&wc, resptype);
581 if (!resptype->equals(getslot))
582 // throw new Error("Bad Response: ");
583 myerror("Bad Response: \n");
586 Array<Slot *> *tmp = processSlots(&wc);
589 /* } catch (SocketTimeoutException *e) {
592 throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
593 } catch (Exception *e) {
594 throw new Error("getSlots failed");
599 * Method that actually handles building Slot objects from the
600 * server response. Shared by both putSlot and getSlots.
602 Array<Slot *> *CloudComm::processSlots(WebConnection *wc) {
603 int numberofslots = readURLInt(wc);
604 Array<int> *sizesofslots = new Array<int>(numberofslots);
605 Array<Slot *> *slots = new Array<Slot *>(numberofslots);
607 for (int i = 0; i < numberofslots; i++)
608 sizesofslots->set(i, readURLInt(wc));
609 for (int i = 0; i < numberofslots; i++) {
610 Array<char> *rawData = new Array<char>(sizesofslots->get(i));
611 readURLData(wc, rawData);
612 Array<char> *data = stripIVAndDecryptSlot(rawData);
614 slots->set(i, Slot_decode(table, data, mac));
621 Array<char> *CloudComm::sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, IoTString *host, int port) {
625 //printf("Passing Locally\n");
626 mac->update(sendData, 0, sendData->length());
627 Array<char> *genmac = mac->doFinal();
628 Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
629 System_arraycopy(sendData, 0, totalData, 0, sendData->length());
630 System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
632 // Encrypt the data for sending
633 Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
634 Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
636 // Open a TCP socket connection to a local device
637 TCPClient socket = createSocket(host, port);
640 // Send data to output (length of data, the data)
641 writeSocketInt(&socket, encryptedData->length());
642 writeSocketData(&socket, encryptedData);
644 int lengthOfReturnData = readSocketInt(&socket);
645 Array<char> *returnData = new Array<char>(lengthOfReturnData);
646 readSocketData(&socket, returnData);
648 returnData = stripIVAndDecryptSlot(returnData);
650 // We are done with this socket
652 mac->update(returnData, 0, returnData->length() - CloudComm_HMAC_SIZE);
653 Array<char> *realmac = mac->doFinal();
654 Array<char> *recmac = new Array<char>(CloudComm_HMAC_SIZE);
655 System_arraycopy(returnData, returnData->length() - realmac->length(), recmac, 0, realmac->length());
657 if (!recmac->equals(realmac))
658 // throw new Error("Local Error: Invalid HMAC! Potential Attack!");
659 myerror("Local Error: Invalid HMAC! Potential Attack!\n");
661 Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
662 System_arraycopy(returnData, 0, returnData2, 0, returnData2->length());
665 /* } catch (Exception *e) {
666 printf("Exception\n");
672 void CloudComm::closeCloud() {
675 /* if (listeningPort > 0) {
676 if (pthread_join(localServerThread, NULL) != 0)
677 throw new Error("Local Server thread join issue...");