Browse Source

Correctly linking version of refactored code.
Yet to add in Post-LA protobufs for headers, data.

dettanym 4 years ago
parent
commit
ced26efb23

+ 1 - 0
LAInitiator/LA.cpp

@@ -0,0 +1 @@
+../../commonVerifierPHPfiles/LAInitiator/LA.cpp

+ 1 - 0
LAInitiator/Tramsforms.cpp

@@ -0,0 +1 @@
+../../commonVerifierPHPfiles/LAInitiator/Transforms.cpp

+ 184 - 5
MainLogic.cpp

@@ -3,14 +3,193 @@
 //
 
 #include "MainLogic.h"
-int MainLogic::deployment_stage() {
-    return 0;
+#include "crypto.h"
+#include "stdio.h"
+#include <errno.h>
+#include <string.h>
+
+// For socket programming
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+#define DECRYPTOR_PORT_DATA 3825
+#define DECRYPTOR_PORT_HEADERS 3830
+
+// Sets up a socket connected to the port passed as input - returns the socket FD on success and -1 on error.
+// Also prints the errno on error.
+int MainLogic::set_up_socket_connect(int port)
+{
+    int sock = 0;
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
+    {
+        printf("\n Error in socket call - errno is %d \n", errno); fflush(stdout);
+        return -1;
+    }
+
+    struct sockaddr_in serv_addr;
+    memset(&serv_addr, '0', sizeof(serv_addr));
+
+    serv_addr.sin_family = AF_INET;
+    serv_addr.sin_port = htons(port);
+
+    // Convert IPv4 and IPv6 addresses from text to binary form
+    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
+    {
+        printf("\nError in inet_pton - errno is %d\n", errno); fflush(stdout);
+        return -1;
+    }
+
+    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
+    {
+        printf("\nError in connect - errno is %d \n", errno); fflush(stdout);
+        return -1;
+    }
+
+    return sock;
 }
 
-int MainLogic::decrypt_values(std::vector <string> &base64_fields, std::vector <string> &plaintext_fields) {
-    return 0;
+int MainLogic::conduct_la_get_initial_header(int data_fd, int headers_fd)
+{
+    uint8_t key[16];
+    uint32_t ret_status;
+
+    // Conduct LA.
+    ret_status = laInitiator.conduct_la(data_fd);
+    if (ret_status != 0) {
+        printf("LA initiator returned an error: %d\n", ret_status);
+        fflush(stdout);
+        return ret_status;
+    }
+    printf("\nSuccessful LA with port %d.\n", data_fd);
+    fflush(stdout);
+
+    printf("Setting up fds for post LA messaging.\n");
+    fflush(stdout);
+    // Use the same channel for sending client data as the one used above for LA messages.
+    postLaMessagingData.set_fd(data_fd);
+    // Use a different channel for receiving headers asynchronously.
+    postLaMessagingHeaders.set_fd(headers_fd);
+
+    // Use the symmetric key from LA to send messages for the rest of the deployment stage.
+    printf("Retrieving key from LA inititator.\n ");
+    fflush(stdout);
+    laInitiator.get_la_symmetric_key(key);
+    printf("Setting key for post LA messaging for both data and headers channels.\n ");
+    fflush(stdout);
+    postLaMessagingData.set_la_symmetric_key(key);
+    postLaMessagingHeaders.set_la_symmetric_key(key);
+
+    //     Mitigator-Public-Key:
+    return postLaMessagingHeaders.receive_secure_msg(last_header_value);
 }
 
-int MainLogic::get_mitigator_header(std::string header_value, int *value_length) {
+int MainLogic::decode_base64_fields_list(std::vector <std::string> &base64_fields_list, std::vector <std::string> &binary_fields_list)
+{
+    uint32_t binary_field_size, base64_field_size;
+    const char* base64_field_ptr;
+    unsigned char* binary_field_ptr = NULL;
+
+    for (auto &base64_field : base64_fields_list)
+    {
+        base64_field_size = base64_field.size();
+        base64_field_ptr = base64_field.c_str();
+        // upper limit - the binary data will always be smaller than this (base64 length ~= 4/3 * binary length)
+        binary_field_ptr = (unsigned char*) realloc(binary_field_ptr, base64_field_size);
+        binary_field_size = base64_decoding_wrapper(base64_field_ptr, base64_field_size, binary_field_ptr);
+        if(binary_field_size <= 0)
+        {
+            free(binary_field_ptr);
+            return 0x1;
+        }
+        binary_fields_list.push_back(std::string(reinterpret_cast<const char*> (binary_field_ptr), binary_field_size));
+    }
     return 0;
 }
+
+void MainLogic::deployment_stage() {
+    setbuf(stdout,NULL);
+    int data_fd = set_up_socket_connect(DECRYPTOR_PORT_DATA);
+    if(data_fd <= 0)
+    {
+        // TODO: Proper error handling.
+        printf("Could not set up a socket with port %d\n", DECRYPTOR_PORT_DATA);
+        fflush(stdout);
+        return;
+    }
+
+    int headers_fd = set_up_socket_connect(DECRYPTOR_PORT_HEADERS);
+    if(headers_fd <= 0)
+    {
+        // TODO: Proper error handling.
+        printf("Could not set up a socket with port %d\n", DECRYPTOR_PORT_HEADERS);
+        fflush(stdout);
+        return;
+    }
+
+    int ret_status = conduct_la_get_initial_header(data_fd, headers_fd);
+    if(ret_status != 0) {
+        printf("Error in deployment stage: %d.\n", ret_status);
+        fflush(stdout);
+        return;
+    }
+
+    // time_file_fd=open("target_time.txt", O_APPEND | O_WRONLY);
+}
+
+Php::Value MainLogic::php_decrypt_wrapper(Php::Parameters &params  ) {
+    std::vector <std::string> base64_fields_list, binary_fields_list, plaintext_fields_list;
+    uint32_t ret_status;
+    Php::Object ret_object;
+    ret_object["success"]="false";
+
+    base64_fields_list = Php::array_values(params);
+    ret_status = decode_base64_fields_list(base64_fields_list, binary_fields_list);
+    if(ret_status != 0)
+    {
+        printf("Could not perform base64 decoding correctly."); fflush(stdout);
+        ret_object["error"]="Could not perform base64 decoding correctly.";
+        return ret_object;
+    }
+
+    ret_status = postLaMessagingData.send_secure_msgs(binary_fields_list);
+    if(ret_status != 0)
+    {
+        printf("Cannot send messages to the decryptor.\n"); fflush(stdout);
+        ret_object["error"]="Cannot send messages to the decryptor.\n";
+        return ret_object;
+    }
+
+    ret_status = postLaMessagingData.receive_secure_msgs(plaintext_fields_list);
+    if(ret_status != 0)
+    {
+        printf("Cannot receive messages from the decryptor.\n"); fflush(stdout);
+        ret_object["error"]="Cannot receive messages from the decryptor.\n";
+        return ret_object;
+    }
+    ret_object["success"]="true";
+    ret_object["fields"]=Php::Array(plaintext_fields_list);
+
+    return ret_object;
+}
+
+Php::Value MainLogic::get_mitigator_header() {
+    std::string header_value;
+    uint32_t ret_status;
+    if(header_refresh_counter < 100)
+    {
+        header_value = last_header_value;
+        header_refresh_counter++;
+    }
+    else
+    {
+        ret_status = postLaMessagingHeaders.receive_secure_msg(header_value);
+        if(ret_status != 0)
+        {
+            printf(" Cannot obtain a header from the decryptor.\n"); fflush(stdout);
+            header_value = "!! Cannot obtain a header from the decryptor.";
+        }
+        header_refresh_counter = 0;
+    }
+    return header_value;
+}

+ 18 - 8
Makefile

@@ -2,9 +2,9 @@ CXX             = g++
 RM              = rm -f
 CXX_FLAGS       = -Wall  -O2 -std=c++11 -fpic
 LD              = ${CXX} -v
-LD_FLAGS        = -Wall -shared -Wl,--no-undefined -Wl,--verbose
+LD_FLAGS        = -Wall -shared -Wl,--no-undefined
 
-OBJECTS := systemMain.o ProtobufLAInitiator.o SgxProtobufLAInitiator.o SgxProtobufLAInitiator_Transforms.o ProtobufLAMessages.pb.o crypto.o 
+OBJECTS := systemMain.o MainLogic.o PostLA/PostLAMessaging.o LAInitiator/LA.o LAInitiator/Tramsforms.o ProtobufMessageRW.o  ProtobufLAMessages.pb.o crypto.o
 
 #SGX_SDK := /home/m2mazmud/sgx2.1_installation/sgxsdk
 SGX_SDK := /opt/intel/sgxsdk
@@ -18,14 +18,11 @@ Openssl_Path := /home/m2mazmud/plain-openssl
 
 Uae_Library_Name := sgx_uae_service
 
-all:	localattestation_decryption.so ${OBJECTS}
+all: localattestation_decryption.so ${OBJECTS}
 
 clean:
 	${RM} *.obj *~* ${OBJECTS} localattestation_decryption.so
 
-Sgx%.o: Sgx%.cpp
-	${CXX} -I./include -I$(SGX_SDK)/include ${CXX_FLAGS} -c $^ -o $@
-
 Protobuf%.o: Protobuf%.cpp
 	${CXX} -I./include ${CXX_FLAGS} -c $^ -o $@
 
@@ -35,11 +32,24 @@ PostLAMessages.pb.o: PostLAMessages.pb.cpp
 system%.o: system%.cpp
 	g++ -I./include ${CXX_FLAGS} -c $^ -o $@
 
+MainLogic.o: MainLogic.cpp
+	g++ -I./include ${CXX_FLAGS} -c $^ -o $@
+
+PostLA/%.o: PostLA/%.cpp
+	g++ -I./include -I$(SGX_SDK)/include ${CXX_FLAGS} -c $^ -o $@
+
+LAInitiator/%.o: LAInitiator/%.cpp
+	g++ -I./include -I$(SGX_SDK)/include ${CXX_FLAGS} -c $^ -o $@
+
+ProtobufMessageRW.o: ProtobufMessageRW.cpp
+	g++ -I./include ${CXX_FLAGS} -c $^ -o $@
+
 crypto.o: crypto.cpp 
 	g++ -I${Openssl_Path}/include ${CXX_FLAGS} -c $^ -o $@
 
-localattestation_decryption.so:  systemMain.o ProtobufLAInitiator.o SgxProtobufLAInitiator.o SgxProtobufLAInitiator_Transforms.o ProtobufLAMessages.pb.o PostLAMessages.pb.o crypto.o
-	${CXX} ${LD_FLAGS} systemMain.o ProtobufLAInitiator.o SgxProtobufLAInitiator.o SgxProtobufLAInitiator_Transforms.o ProtobufLAMessages.pb.o PostLAMessages.pb.o crypto.o  -lphpcpp -L./ -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive  -l$(Service_Library_Name) -l$(Crypto_Library_Name) -lsgx_tstdc -lprotobuf -Wl,--rpath /home/m2mazmud/plain-openssl/lib    -L${Openssl_Path}/lib -lssl -lcrypto   -Wl,-Bsymbolic -Wl,-pie,-eenclave_entry -Wl,--export-dynamic  -o $@
+localattestation_decryption.so: systemMain.o MainLogic.o PostLA/PostLAMessaging.o LAInitiator/LA.o LAInitiator/Tramsforms.o ProtobufMessageRW.o  ProtobufLAMessages.pb.o crypto.o
+#systemMain.o ProtobufLAInitiator.o SgxProtobufLAInitiator.o SgxProtobufLAInitiator_Transforms.o ProtobufLAMessages.pb.o PostLAMessages.pb.o crypto.o
+	${CXX} ${LD_FLAGS} systemMain.o MainLogic.o PostLA/PostLAMessaging.o LAInitiator/LA.o LAInitiator/Tramsforms.o ProtobufMessageRW.o  ProtobufLAMessages.pb.o crypto.o  -lphpcpp -L./ -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive  -l$(Service_Library_Name) -l$(Crypto_Library_Name) -lsgx_tstdc -lprotobuf -Wl,--rpath /home/m2mazmud/plain-openssl/lib    -L${Openssl_Path}/lib -lssl -lcrypto   -Wl,-Bsymbolic -Wl,-pie,-eenclave_entry -Wl,--export-dynamic  -o $@
 #ProtobufLAInitiator.o SgxProtobufLAInitiator.o SgxProtobufLAInitiator_Transforms.o ProtobufLAMessages.pb.o crypto.o 
 # -L./ -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive  -l$(Service_Library_Name) -l$(Crypto_Library_Name) -lsgx_tstdc -lprotobuf -Wl,--rpath /home/m2mazmud/plain-openssl/lib   -L${Openssl_Path}/lib -lssl -lcrypto  -Wl,-Bsymbolic -Wl,-pie,-eenclave_entry -Wl,--export-dynamic  -Wl,--verbose -lphpcpp -lprotobuf  -o $@
 #ProtobufLAInitiator.o SgxProtobufLAInitiator.o SgxProtobufLAInitiator_Transforms.o ProtobufLAMessages.pb.o crypto.o 

+ 141 - 0
PostLA/PostLAMessaging.cpp

@@ -0,0 +1,141 @@
+//
+// Created by miti on 2019-12-24.
+//
+
+#include "PostLAMessaging.h"
+#include "sgx_trts.h" // for sgx_read_rand
+#include "crypto.h" // for aes_gcm_128
+#include <unistd.h>
+#include <stdio.h>
+uint32_t PostLAMessaging::aes_gcm_wrapper(int enc, uint8_t* plaintext, uint32_t plaintext_length, uint8_t* ciphertext, uint32_t* ciphertext_length)
+{
+    uint32_t actual_plaintext_length=plaintext_length;
+    uint8_t tag[16];uint32_t counter, return_status;
+    uint8_t iv[12];
+    if(enc == 0)
+    {
+        for(counter=0;counter<16;counter++)
+            tag[counter]=plaintext[counter+plaintext_length-16];
+        for(counter=0;counter<12;counter++)
+            iv[counter]=plaintext[counter+plaintext_length-28];
+        actual_plaintext_length-=28;
+    }
+    else
+    {
+        return_status=sgx_read_rand(iv, 12);
+        if(return_status != 0)
+            return return_status;
+    }
+    return_status = aes_gcm_128(enc, key, iv, plaintext, actual_plaintext_length, ciphertext, ciphertext_length, tag);
+    if(enc == 1 && return_status == 0)
+    {
+        for(counter=0;counter<12;counter++)
+            ciphertext[counter + *ciphertext_length] = iv[counter];
+        for(counter=0;counter<16;counter++)
+            ciphertext[counter + 12 + *ciphertext_length] = tag[counter];
+        *ciphertext_length=*ciphertext_length + 28;
+    }
+    return return_status;
+}
+
+void PostLAMessaging::set_la_symmetric_key(uint8_t* given_key) {
+    uint32_t counter;
+    for(counter=0; counter<16; counter++)
+    {
+        key[counter] = given_key[counter];
+    }
+}
+
+void PostLAMessaging::set_fd(int given_fd)
+{
+    protobufReaderWriter.set_fd(given_fd);
+}
+
+uint32_t PostLAMessaging::encrypt_decrypt_msgs(int encrypt_decrypt, std::vector<std::string>& input_msgs,
+                         std::vector<std::string>& output_msgs)
+{
+    unsigned char *input; unsigned char *output;
+    uint32_t input_size, output_size, ret;
+    output=NULL;
+
+    for (std::string msg:input_msgs)
+    {
+        input_size = msg.length();
+        input = (unsigned char*) msg.c_str();
+        output = (unsigned char*) realloc(output, input_size + 28); // 16 for tag, 12 for IV
+        ret = aes_gcm_wrapper(encrypt_decrypt, input, input_size, output, &output_size );
+        if(ret!=0)
+        {
+            free(output);
+            printf("Failed to encrypt an input field.\n"); fflush(stdout);
+            return 0x2;
+        }
+        output_msgs.push_back(std::string(reinterpret_cast<const char *> (output), output_size));
+    }
+    free(output);
+
+    return 0;
+}
+
+
+/*
+ * virtual void create_vector_from_protobuf(google::protobuf::MessageLite& protobuf_msg,
+                                         std::vector<std::string> &native_msg_list) {}
+*/
+
+uint32_t PostLAMessaging::receive_secure_msgs(std::vector<std::string> &plaintext_msg_list) {
+    std::vector<std::string> ciphertext_msg_list;
+
+    /*google::protobuf::MessageLite protobuf_msg;
+
+    // read encrypted data
+    if(!protobufReaderWriter.read_msg(protobuf_msg))
+    {
+        printf("Not all of the decryptor's message was read\n"); fflush(stdout);
+        return 0xf3;
+    }
+
+    create_vector_from_protobuf(protobuf_msg, ciphertext_msg_list);
+    */
+
+    return encrypt_decrypt_msgs(0, ciphertext_msg_list, plaintext_msg_list);
+}
+
+uint32_t PostLAMessaging::receive_secure_msg(std::string &plaintext_msg) {
+    std::vector<std::string> ip_msg_list;
+    uint32_t ret_status;
+
+    ret_status = receive_secure_msgs(ip_msg_list);
+    if(ret_status != 0)
+        return ret_status;
+
+    plaintext_msg = ip_msg_list.front();
+    return 0;
+}
+
+
+uint32_t PostLAMessaging::send_secure_msgs(std::vector<std::string> &plaintext_msg_list)
+{
+    uint32_t ret;
+    std::vector<std::string> ciphertext_msg_list;
+
+    ret=encrypt_decrypt_msgs(1, plaintext_msg_list, ciphertext_msg_list);
+    if(ret!=0)
+        return ret;
+
+    // TODO: Fix with correct protobuf references. (write)
+    /*
+    // write message to decryptor
+    create_protobuf_from_vector(ciphertext_msg_list, protobuf_msg);
+
+    google::protobuf::MessageLite protobuf_msg;
+    if(!protobufReaderWriter.write_msg(protobuf_msg))
+    {
+        printf("Not all of the client's pub key and ciphertext data was written\n"); fflush(stdout);
+        return 0xfe;
+    }
+    */
+    return 0;
+}
+
+

+ 0 - 318
ProtobufLAInitiator.cpp

@@ -1,318 +0,0 @@
-// Knows only protobuf_sgx objects, protobuf header.
-#include<stdlib.h>
-#include<string.h>
-#include<errno.h>
-#include<unistd.h>
-#include<stdio.h>
-#include"ProtobufLAMessages.pb.h"
-#include"PostLAMessages.pb.h"
-#include<google/protobuf/io/coded_stream.h>
-#include<google/protobuf/io/zero_copy_stream_impl.h>
-#include"SgxProtobufLAInitiator.h"
-#include"crypto.h"
-// For socket programming
-#include<arpa/inet.h>
-#include<sys/socket.h>
-#include<netinet/in.h>
-#include<queue>
-using namespace google::protobuf::io;
-
-int global_decryptor_fd;
-#define TOKEN_H_MAX_LENGTH 300
-uint8_t ciphertext_to_decryptor[4092]; 
-
-// TODO: Make these private functions
-// TODO: Rewrite read, write calls for protobuf msgs to and from fds to use message.SerializeToFileDescriptor and ParseFromFileDescriptor
-bool read_protobuf_msg_from_fd(int accept_fd, google::protobuf::MessageLite& message)
-{
-    //message.SerializeToFileDescriptor(accept_fd);
-  ZeroCopyInputStream* raw_input;
-  CodedInputStream* coded_input;
-  uint32_t size;
-  CodedInputStream::Limit limit;
-  raw_input = new FileInputStream(accept_fd);
-  coded_input = new CodedInputStream(raw_input);
-  if(!coded_input->ReadVarint32(&size))
-  {
-    printf("Error in reading size of msg\n");
-    fflush(stdout);
-    return false;
-  }
-  //  printf("size of msg was read to be %d \n", size);
-  //  fflush(stdout);
-  limit = coded_input->PushLimit(size);
-  if(!message.ParseFromCodedStream(coded_input))
-  {
-    printf("Error in parsing msg\n");
-    fflush(stdout);
-    return false;
-  }
-  //  printf("Done parsing msg\n"); fflush(stdout);
-  coded_input->PopLimit(limit);
-  return true;
-}
-
-// TODO: private functions
-bool write_protobuf_msg_to_fd(int accept_fd, google::protobuf::MessageLite& message)
-{
-    //return message.ParseFromFileDescriptor(accept_fd);
-  ZeroCopyOutputStream* raw_output = new FileOutputStream(accept_fd);
-  CodedOutputStream* coded_output  = new CodedOutputStream(raw_output);
-  coded_output->WriteVarint32(message.ByteSize());
-  if(!message.SerializeToCodedStream(coded_output))
-  {
-    printf("SerializeToCodedStream failed\n");
-    fflush(stdout);
-    return false;
-  }
-  // As per this - https://stackoverflow.com/questions/22881876/protocol-buffers-how-to-serialize-and-deserialize-multiple-messages-into-a-file?noredirect=1&lq=1
-  // TODO: There may be a better way to do this - 1) this happens with every accept now and 2) make it happen on the stack vs heap - destructor will be called on return from this function (main) and the items will then be written out. (We probably don't want that, actually)
-  delete coded_output;
-  delete raw_output;
-  //  fflush(stdout);
-  return true;
-}
-
-void create_vector_from_protobuf(extension_to_decryptor_enclosed_msg &protobuf_ext_to_decryptor,
-                                 std::vector<std::string> &binary_ciphertext_client_data)
-{
-    uint32_t temp_size, counter;
-
-    binary_ciphertext_client_data.push_back(protobuf_ext_to_decryptor.ciphertext_client_public_key());
-    temp_size=protobuf_ext_to_decryptor.ciphertext_fields_size();
-    for(counter=0; counter<temp_size; counter++)
-        binary_ciphertext_client_data.push_back(protobuf_ext_to_decryptor.ciphertext_fields(counter).field());
-}
-
-void create_protobuf_from_vector(std::vector<std::string> &double_ciphertext_client_data,
-                                 extension_to_decryptor_enclosed_msg &protobuf_ext_decryptor_msg)
-{
-    uint32_t counter, temp_size;
-
-    protobuf_ext_decryptor_msg.set_ciphertext_client_public_key(double_ciphertext_client_data[0]);
-    temp_size=double_ciphertext_client_data.size()-1; // 1 for the public key.
-    for(counter=0; counter<temp_size; counter++)
-        protobuf_ext_decryptor_msg.mutable_ciphertext_fields(counter)->set_field(double_ciphertext_client_data[counter]);
-}
-
-
-// Sets up a socket connected to the port passed as input - returns the socket FD on success and -1 on error.
-// Also prints the errno on error.
-int set_up_socket_connect(int port)
-{
-  int sock = 0;
-  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
-  {
-    printf("\n Error in socket call - errno is %d \n", errno);
-    return -1;
-  }
-
-  struct sockaddr_in serv_addr;
-  memset(&serv_addr, '0', sizeof(serv_addr));
-
-  serv_addr.sin_family = AF_INET;
-  serv_addr.sin_port = htons(port);
-
-  // Convert IPv4 and IPv6 addresses from text to binary form
-  if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
-  {
-    printf("\nError in inet_pton - errno is %d\n", errno);
-    return -1;
-  }
-
-  if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
-  {
-    printf("\nError in connect - errno is %d \n", errno);
-    return -1;
-  }
-
-  return sock;
-}
-
-int local_attestation_initiator(int port)
-{
-  // declare msg1, msg2, msg3 protobuf objects
-  protobuf_sgx_dh_msg1_t protobuf_msg1;
-  protobuf_sgx_dh_msg2_t protobuf_msg2;
-  protobuf_sgx_dh_msg3_t protobuf_msg3;
-  uint32_t protobuf_sgx_ret;
-
-  uint32_t session_id;
-  int decryptor_fd;
-
-  setbuf(stdout,NULL);
-  decryptor_fd=set_up_socket_connect(port);
-  if(decryptor_fd == -1)
-  {
-    perror("\nCould not set up the socket: had the following error: ");
-    fflush(stderr);
-  }
-  global_decryptor_fd=decryptor_fd;
-
-  // Reading msg 1 from decryptor enclave.
-  if(! read_protobuf_msg_from_fd(decryptor_fd, protobuf_msg1))
-    return -1;
-
-  // Generating message 2 given message 1 as input
-  protobuf_sgx_ret = process_protobuf_dh_msg1_generate_protobuf_dh_msg2(protobuf_msg1, protobuf_msg2, &session_id);
-  if(protobuf_sgx_ret != 0)
-  {
-    printf("Error in process_protobuf_dh_msg1_generate_protobuf_dh_msg2: 0x%x", protobuf_sgx_ret); fflush(stdout); return protobuf_sgx_ret;
-  }
-
-  // Writing msg 2 to decryptor enclave.
-  if(!write_protobuf_msg_to_fd(decryptor_fd, protobuf_msg2))
-    return -1;
-
-  // Reading msg3 from decryptor enclave
-  if(!read_protobuf_msg_from_fd(decryptor_fd, protobuf_msg3))
-    return -1;
-
-  // Process message 3
-  protobuf_sgx_ret = process_protobuf_dh_msg3(protobuf_msg3, &session_id);
-  if(protobuf_sgx_ret != 0)
-  {
-      printf("Error in process_protobuf_dh_msg3: 0x%x", protobuf_sgx_ret); fflush(stdout); return protobuf_sgx_ret;
-  }
-  return 0;
-}
-
-
-uint32_t post_local_attestation_get_mitigator_header(unsigned char* base64_encoded_token_H, uint32_t* base64_encoded_token_H_length)
-{
-  unsigned char* encrypted_token_H_and_tag, *plaintext_token_H;
-  uint32_t encrypted_token_H_and_tag_length, plaintext_token_H_length;
-  protobuf_post_LA_encrypted_msg_t protobuf_encrypted_msg;
-  uint32_t count;
-  uint32_t internal_return_status;
-
-  // Reading the encrypted token H from the
-  if(!read_protobuf_msg_from_fd(global_decryptor_fd, protobuf_encrypted_msg))
-  {
-    printf("Not all of the post-LA message was read\n"); fflush(stdout); return 0xfe;
-  }
-
-  std::string protobuf_encrypted_msg_string(protobuf_encrypted_msg.msg());
-  encrypted_token_H_and_tag_length=protobuf_encrypted_msg_string.length();
-  encrypted_token_H_and_tag = (unsigned char*) malloc(encrypted_token_H_and_tag_length);
-  memcpy(encrypted_token_H_and_tag, protobuf_encrypted_msg_string.c_str(), protobuf_encrypted_msg_string.length());
-  
-  printf("Read the following encrypted token T and tag from the decryptor socket.\n"); fflush(stdout);
-	printf("Encrypted data:\n");
-	for(count=0; count<encrypted_token_H_and_tag_length; count++)
-		printf("0x%02x ", encrypted_token_H_and_tag[count]);
-	printf("\n"); fflush(stdout);
- plaintext_token_H=(unsigned char*) malloc(encrypted_token_H_and_tag_length); 
-	internal_return_status = aes_gcm_wrapper(0, encrypted_token_H_and_tag, encrypted_token_H_and_tag_length, plaintext_token_H, &plaintext_token_H_length);
-	if(internal_return_status != 0)
-	{
-		free(encrypted_token_H_and_tag); 
-		free(plaintext_token_H); 
-		printf("Error in decryption 0x%x", internal_return_status); fflush(stdout); return internal_return_status;
-	}
-
-  printf("Decryptor's short-term public key\n");
-  for(count=0;count<64;count++)
-    printf("0x%02x ", plaintext_token_H[count]);
-	printf("\n"); fflush(stdout);
-
-	printf("Verifier mrenclave\n");
-	for(count=64;count<96;count++)
-    printf("0x%02x ", plaintext_token_H[count]);
-	printf("\n"); fflush(stdout);
-	 
-	*base64_encoded_token_H_length=base64_encoding_wrapper(base64_encoded_token_H, plaintext_token_H, plaintext_token_H_length);
-  
-  // TODO: Better return value handling.
-  //if(!(base64_encoded_token_H_length <= 4 * Math.ceil(plaintext_token_H_length/3) && base64_encoded_token_H_length > 4 * (Math.ceil(plaintext_token_H_length/3) - 1)))
-  //{
-  //  printf("Somehow not the entire token was encoded in base64:0x%x\n", base64_encoded_token_H_length); fflush(stdout); return 0x55;
-  //}
-  
-        free(encrypted_token_H_and_tag); 
-        free(plaintext_token_H); 
-	fflush(stdout);
-	return 0;
-}
-
-
-uint32_t base64_decoding_on_all_client_data(unsigned char* ip_base64_client_public_key_ciphertext, 
-  uint32_t ip_base64_client_public_key_ciphertext_length,
-  unsigned char* op_client_public_key_ciphertext,
-  uint32_t* op_client_public_key_ciphertext_length
-)
-{
-/*    uint32_t openssl_ret_status;
-    openssl_ret_status=base64_decoding_wrapper(ip_base64_client_public_key_ciphertext, op_client_public_key_ciphertext, ip_base64_client_public_key_ciphertext_length);
-    if(openssl_ret_status == -1)
-      	return 0xfe;
-    *op_client_public_key_ciphertext_length = openssl_ret_status; 
-*/
-    return 0;
-
-}
-
-int encrypt_decrypt_ciphertexts(int encrypt_decrypt, std::vector<std::string> &binary_ciphertext_client_data,
-        std::vector<std::string> &double_ciphertext_client_data)
-{
-    unsigned char *ciphertext; unsigned char *double_ciphertext;
-    uint32_t ciphertext_size, double_ciphertext_size, ret;
-    double_ciphertext=NULL;
-
-    for (std::string ciphertext_from_client:binary_ciphertext_client_data)
-    {
-        ciphertext_size = ciphertext_from_client.length();
-        ciphertext = (unsigned char*) ciphertext_from_client.c_str();
-        double_ciphertext=(unsigned char*) realloc(double_ciphertext, ciphertext_size + 28); // 16 for tag, 12 for IV
-        ret = aes_gcm_wrapper(encrypt_decrypt, ciphertext, ciphertext_size, double_ciphertext, &double_ciphertext_size );
-        if(ret!=0)
-        {
-            free(double_ciphertext);
-            printf("Failed to encrypt a ciphertext field.\n"); fflush(stdout);
-            return 0x2;
-        }
-        double_ciphertext_client_data.push_back(std::string(reinterpret_cast<const char *> (double_ciphertext), double_ciphertext_size));
-    }
-    free(double_ciphertext);
-
-    return 0;
-}
-
-int decrypt_client_data_through_decryptor( std::vector<std::string> &binary_ciphertext_client_data,
-        std::vector<std::string> &plaintext_client_data)
-{
-    uint32_t ret;
-    std::vector<std::string> double_ciphertext_client_data;
-    std::vector<std::string> received_ciphertext_client_data;
-    extension_to_decryptor_enclosed_msg protobuf_extension_decryptor_msg;
-
-    ret=encrypt_decrypt_ciphertexts(1, binary_ciphertext_client_data, double_ciphertext_client_data);
-    if(ret!=0)
-        return ret;
-
-    create_protobuf_from_vector(double_ciphertext_client_data,
-                                protobuf_extension_decryptor_msg);
-
-    // write message to decryptor
-    if(!write_protobuf_msg_to_fd(global_decryptor_fd, protobuf_extension_decryptor_msg))
-    {
-        printf("Not all of the client's pub key and ciphertext data was written\n"); fflush(stdout);
-        return 0xfe;
-    }
-
-    protobuf_extension_decryptor_msg.clear_ciphertext_fields();
-    protobuf_extension_decryptor_msg.clear_ciphertext_client_public_key(); // not necessary.
-
-    // read encrypted data
-    if(!read_protobuf_msg_from_fd(global_decryptor_fd, protobuf_extension_decryptor_msg))
-    {
-        printf("Not all of the decryptor's message was read\n"); fflush(stdout);
-        return 0xf3;
-    }
-
-    create_vector_from_protobuf(protobuf_extension_decryptor_msg, received_ciphertext_client_data);
-
-    ret=encrypt_decrypt_ciphertexts(0, received_ciphertext_client_data,
-            plaintext_client_data);
-    return ret;
-}

+ 1 - 0
ProtobufMessageRW.cpp

@@ -0,0 +1 @@
+../commonVerifierPHPfiles/ProtobufMessageRW.cpp

+ 0 - 113
SgxProtobufLAInitiator.cpp

@@ -1,113 +0,0 @@
-#include "sgx_eid.h"
-#define __STDC_FORMAT_MACROS
-#include <inttypes.h>
-#include "ProtobufLAMessages.pb.h"
-#include <stdio.h>
-#include <sys/mman.h>
-#include "sgx_trts.h"
-#include "sgx_utils.h"
-#include "error_codes.h"
-#include "sgx_ecp_types.h"
-#include "sgx_thread.h"
-#include <map>
-#include "sgx_dh.h"
-#include "dh_session_protocol.h"
-#include "sgx_tcrypto.h"
-#include "datatypes.h"
-#include "SgxProtobufLAInitiator_Transforms.h"
-#define MAX_SESSION_COUNT  16
-#define SGX_CAST(type, item) ((type)(item))
-#include <string.h>
-#include "crypto.h"
-#include "stdio.h"
-#include <errno.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-dh_session_t global_session_info;
-sgx_dh_session_t sgx_dh_session;
-uint8_t key[16];
-
-uint32_t process_protobuf_dh_msg1_generate_protobuf_dh_msg2(protobuf_sgx_dh_msg1_t& protobuf_msg1, protobuf_sgx_dh_msg2_t& protobuf_msg2, uint32_t* session_id)
-{
-  sgx_dh_msg1_t dh_msg1;            //Diffie-Hellman Message 1
-  sgx_dh_msg2_t dh_msg2;
-  memset(&dh_msg1, 0, sizeof(sgx_dh_msg1_t));
-  uint32_t ret_status;
-
-  if(decode_msg1_from_protobuf(protobuf_msg1, &dh_msg1)!=0)
-    return -1;
-
-  //Intialize the session as a session initiator
-  ret_status = sgx_dh_init_session(SGX_DH_SESSION_INITIATOR, &sgx_dh_session);
-  if(ret_status != SGX_SUCCESS)
-    return ret_status;
-
-  //Process the message 1 obtained from desination enclave and generate message 2
-  ret_status = sgx_dh_initiator_proc_msg1(&dh_msg1, &dh_msg2, &sgx_dh_session);
-  if(SGX_SUCCESS != ret_status)
-    return ret_status;
-
-  encode_msg2_to_protobuf(protobuf_msg2, &dh_msg2);
-  return 0;
-}
-
-uint32_t process_protobuf_dh_msg3(protobuf_sgx_dh_msg3_t& protobuf_msg3, uint32_t* session_id) {
-
-  uint32_t ret_status;
-  sgx_dh_msg3_t dh_msg3;
-  sgx_key_128bit_t dh_aek;        // Session Key
-  sgx_dh_session_enclave_identity_t responder_identity;
-
-  memset(&dh_aek,0, sizeof(sgx_key_128bit_t));
-
-  if(decode_msg3_from_protobuf(protobuf_msg3, &dh_msg3)!=0)
-    return -1;
-
-  //Process Message 3 obtained from the destination enclave
-  ret_status = sgx_dh_initiator_proc_msg3(&dh_msg3, &sgx_dh_session, &dh_aek, &responder_identity);
-  if(SGX_SUCCESS != ret_status)
-    return ret_status;
-
-  //No verification checks here: no security guarantees obtained from any such checks
-  memcpy(key, &dh_aek, sizeof(sgx_key_128bit_t));
-  //memcpy(global_session_info.active.AEK, &dh_aek, sizeof(sgx_key_128bit_t));
-  global_session_info.session_id = 1; // TODO: session_id;
-  global_session_info.active.counter = 0;
-  global_session_info.status = ACTIVE;
-  memset(&dh_aek,0, sizeof(sgx_key_128bit_t));
-
-  return 0;
-}
-
- uint32_t aes_gcm_wrapper(int enc, uint8_t* plaintext, uint32_t plaintext_length, uint8_t* ciphertext, uint32_t* ciphertext_length)
-  {
-    uint32_t actual_plaintext_length=plaintext_length; 
-    uint8_t tag[16];uint32_t counter, return_status;
-	uint8_t iv[12]; 
-    if(enc == 0)
-	{
-                for(counter=0;counter<16;counter++)
-                        tag[counter]=plaintext[counter+plaintext_length-16]; 
-		for(counter=0;counter<12;counter++)
-			iv[counter]=plaintext[counter+plaintext_length-28]; 
-		actual_plaintext_length-=28; 
-	}
-	else
-	{
-		return_status=sgx_read_rand(iv, 12); 
-		if(return_status != 0)
-			return return_status;
-	}
-    return_status = aes_gcm_128(enc, key, iv, plaintext, actual_plaintext_length, ciphertext, ciphertext_length, tag);
-	if(enc == 1 && return_status == 0)
-	{
-                for(counter=0;counter<12;counter++)
-                        ciphertext[counter + *ciphertext_length] = iv[counter];
-		for(counter=0;counter<16;counter++)
-			ciphertext[counter + 12 + *ciphertext_length] = tag[counter];
-		*ciphertext_length=*ciphertext_length + 28;
-	}
-    return return_status;
-  }
-

+ 0 - 452
SgxProtobufLAInitiator_Transforms.cpp

@@ -1,452 +0,0 @@
-#include "sgx_eid.h"
-#include "error_codes.h"
-#include "datatypes.h"
-#include "sgx_urts.h"
-#include "sgx_dh.h"
-
-// For msg1
-#define SGX_TARGET_INFO_RESERVED1_BYTES 4
-#define SGX_TARGET_INFO_RESERVED2_BYTES 456
-#define SGX_ECP256_KEY_SIZE 32
-#define SGX_HASH_SIZE 32 /* SHA256 */
-// For msg2
-#define SGX_REPORT_DATA_SIZE 64
-#define SGX_KEYID_SIZE 32
-#define SGX_DH_MAC_SIZE 16
-#define SGX_REPORT_BODY_RESERVED1 28
-#define SGX_REPORT_BODY_RESERVED2 32
-#define SGX_REPORT_BODY_RESERVED3 96
-#define SGX_REPORT_BODY_RESERVED4 60
-
-
-#include <stdio.h>
-// For google protobufs and deserialization/serialization
-#include "ProtobufLAMessages.pb.h"
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
-using namespace google::protobuf::io;
-#include <inttypes.h>
-
-// TODO: PRIVATE
-int fit_32_into_uint8_t(google::protobuf::uint32 temp32, uint8_t* temp8)
-{
- if(temp32 > UINT8_MAX)
-	 return -1;
- else
- {
-	 //		 *temp8 = *(uint8_t*)&temp32; // Probably works irrespective of endianness but not sure.
-	 *temp8 = (uint8_t)temp32;
-	 return 0;
- }
-}
-
-// TODO: PRIVATE
-int fit_32_into_uint16_t(google::protobuf::uint32 temp32, uint16_t* temp16)
-{
- if(temp32 > UINT16_MAX)
-         return -1;
- else
- {
-         //              *temp8 = *(uint8_t*)&temp32; // Probably works irrespective of endianness but not sure.
-         *temp16 = (uint16_t)temp32;
-         return 0;
- }
-}
-
-// TODO: PRIVATE
-void encode_ec256_public_key_to_protobuf(protobuf_sgx_ec256_public_t* protobuf_g_a , sgx_ec256_public_t* g_a)
-{
-	printf("\n ec256 public key gx and gy \n");
-	int counter; google::protobuf::uint32 temp32;
-	for(counter=0;counter<SGX_ECP256_KEY_SIZE;counter++)
-	{
-		temp32 = g_a->gx[counter];
-		protobuf_g_a->add_gx(temp32);
-		printf("%d ", temp32);
-		temp32 = g_a->gy[counter];
-		protobuf_g_a->add_gy(temp32);
-		printf("%d ", temp32);
-	}
-	printf("\n");
-}
-
-// TODO: PRIVATE
-void encode_attributes_to_protobuf(protobuf_sgx_attributes_t* protobuf_attributes, sgx_attributes_t* attributes)
-{
-	protobuf_attributes->set_flags(attributes->flags); // 64 bit
-	protobuf_attributes->set_xfrm(attributes->xfrm); // 64 bit
-}
-
-// TODO: PRIVATE
-void encode_report_to_protobuf(protobuf_sgx_report_t* protobuf_report, sgx_report_t* report)
-{
-	printf("\n OWN report \n key id \n");
-	int counter; google::protobuf::uint32 temp32;
-	for(counter=0;counter<SGX_KEYID_SIZE;counter++)
-	{
-		temp32=report->key_id.id[counter];
-		protobuf_report->add_key_id(temp32);
-		printf("%d ",temp32);
-	}
-
-	printf("\n mac \n");
-	for(counter=0;counter<SGX_MAC_SIZE;counter++)
-	{
-		temp32=report->mac[counter];
-		protobuf_report->add_mac(temp32);
-		printf("%d ", temp32);
-	}
-
-	protobuf_report->mutable_body()->set_misc_select(report->body.misc_select); // 32 bit
-	protobuf_report->mutable_body()->set_isv_svn(report->body.isv_svn); // 16 bit
-	protobuf_report->mutable_body()->set_isv_prod_id(report->body.isv_prod_id); // 16 bit
-	encode_attributes_to_protobuf(protobuf_report->mutable_body()->mutable_attributes(), &(report->body.attributes));
-
-	for(counter=0;counter<SGX_CPUSVN_SIZE;counter++)
-	{
-		temp32=report->body.cpu_svn.svn[counter];
-		protobuf_report->mutable_body()->add_cpu_svn(temp32);
-	}
-
-	for(counter=0;counter<SGX_REPORT_BODY_RESERVED1;counter++)
-	{
-		temp32=report->body.reserved1[counter]; // TODO: Could be optimized out - if these are determined to be 0s.
-		protobuf_report->mutable_body()->add_reserved1(temp32);
- 	}
-
-	for(counter=0;counter<SGX_REPORT_BODY_RESERVED2;counter++)
-	{
-		temp32=report->body.reserved2[counter]; // TODO: Could be optimized out - if these are determined to be 0s.
-		protobuf_report->mutable_body()->add_reserved2(temp32);
-	}
-
-	for(counter=0;counter<SGX_REPORT_BODY_RESERVED3;counter++)
-	{
-		temp32=report->body.reserved3[counter]; // TODO: Could be optimized out - if these are determined to be 0s.
-		protobuf_report->mutable_body()->add_reserved3(temp32);
- 	}
-
-	for(counter=0;counter<SGX_REPORT_BODY_RESERVED4;counter++)
-	{
-		temp32=report->body.reserved4[counter]; // TODO: Could be optimized out - if these are determined to be 0s.
-		protobuf_report->mutable_body()->add_reserved4(temp32);
- 	}
-
-	printf("\nmr enclave\n");
-	fflush(stdout);
-	for(counter=0;counter<SGX_HASH_SIZE;counter++)
-	{
-		temp32=report->body.mr_enclave.m[counter];
-		protobuf_report->mutable_body()->add_mr_enclave(temp32);
-		printf("%02x", temp32);
- 	}
-
-	printf("\n mr signer\n");  fflush(stdout);
-	for(counter=0;counter<SGX_HASH_SIZE;counter++)
-	{
-		temp32=report->body.mr_signer.m[counter];
-		protobuf_report->mutable_body()->add_mr_signer(temp32);
-		printf("0x%02x,", temp32);
- 	}
-	printf("\n"); fflush(stdout); 
-	
-	for(counter=0;counter<SGX_REPORT_DATA_SIZE;counter++)
-	{
-		temp32=report->body.report_data.d[counter];
-		protobuf_report->mutable_body()->add_report_data(temp32);
- 	}
-}
-
-// TODO: PRIVATE
-int decode_attributes_from_protobuf(protobuf_sgx_attributes_t* protobuf_attributes, sgx_attributes_t* attributes)
-{
-        attributes->flags = protobuf_attributes->flags();
-  printf("\n flags %" PRIu64 " \n", attributes->flags);
-        attributes->xfrm = protobuf_attributes->xfrm();
-  printf("\n xfrm %" PRIu64 " \n", attributes->xfrm);
-        return 0;
-}
-
-// TODO: PRIVATE
-int decode_report_from_protobuf(protobuf_sgx_report_t* protobuf_report, sgx_report_t* report)
-{
-  int counter; google::protobuf::uint32 temp32;
-  printf("\n----------------------Decoding received msg3 ------------------------\n");
-  printf("\nreport body keyid\n");
-  for(counter=0;counter<SGX_KEYID_SIZE;counter++)
-  {
-    temp32=protobuf_report->key_id(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->key_id.id[counter]))!=0)
-		  return -1;
-    printf("%d ", report->key_id.id[counter]);
-  }
-
-  printf("\nreport mac\n");
-  for(counter=0;counter<SGX_MAC_SIZE;counter++)
-  {
-    temp32=protobuf_report->mac(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->mac[counter]))!=0)
-      return -1;
-    printf("%d ", report->mac[counter]);
-  }
-
-  report->body.misc_select=protobuf_report->mutable_body()->misc_select(); // 32 bit
-  temp32=protobuf_report->mutable_body()->isv_svn();
-  if(fit_32_into_uint16_t(temp32, &(report->body.isv_svn))!=0)
-   return -1;
-  printf("\nmisc select %d \n", report->body.misc_select);
-
-  temp32=protobuf_report->mutable_body()->isv_prod_id();
-   if(fit_32_into_uint16_t(temp32, &(report->body.isv_prod_id))!=0)
-    return -1;
-  printf("\nprod id %d \n", report->body.isv_prod_id);
-
-  decode_attributes_from_protobuf(protobuf_report->mutable_body()->mutable_attributes(), &(report->body.attributes));
-
-  printf("\n cpu svn\n");
-  for(counter=0;counter<SGX_CPUSVN_SIZE;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->cpu_svn(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.cpu_svn.svn[counter]))!=0)
-      return -1;
-    printf("%d ", report->body.cpu_svn.svn[counter]);
-
-  }
-
-  printf("\n reserved1 \n");
-  for(counter=0;counter<SGX_REPORT_BODY_RESERVED1;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->reserved1(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.reserved1[counter]))!=0)
-      return -1;
-    printf("%d ", report->body.reserved1[counter]);
-  }
-
-  printf("\n reserved2 \n");
-  for(counter=0;counter<SGX_REPORT_BODY_RESERVED2;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->reserved2(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.reserved2[counter]))!=0)
-      return -1;
-    printf("%d ", report->body.reserved2[counter]);
-  }
-
-  printf("\n reserved3 \n");
-  for(counter=0;counter<SGX_REPORT_BODY_RESERVED3;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->reserved3(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.reserved3[counter]))!=0)
-      return -1;
-    printf("%d ", report->body.reserved3[counter]);
-  }
-
-  printf("\n reserved4 \n");
-  for(counter=0;counter<SGX_REPORT_BODY_RESERVED4;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->reserved4(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.reserved4[counter]))!=0)
-      return -1;
-    printf("%d ", report->body.reserved4[counter]);
-
-  }
-
-  printf("\n mrenclave \n");
-  for(counter=0;counter<SGX_HASH_SIZE;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->mr_enclave(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.mr_enclave.m[counter]))!=0)
-      return -1;
-    printf("%x ", report->body.mr_enclave.m[counter]);
-  }
-
-  printf("\n mrsigner \n");
-  for(counter=0;counter<SGX_HASH_SIZE;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->mr_signer(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.mr_signer.m[counter]))!=0)
-      return -1;
-    printf("%x ", report->body.mr_signer.m[counter]);
-  }
-
-  printf("\n report data\n");
-  for(counter=0;counter<SGX_REPORT_DATA_SIZE;counter++)
-  {
-    temp32=protobuf_report->mutable_body()->report_data(counter);
-    if(fit_32_into_uint8_t(temp32, &(report->body.report_data.d[counter]))!=0)
-      return -1;
-    printf("%d ", report->body.report_data.d[counter]);
-  }
-  printf("\n------------------------ end of msg3 --------------------------\n");
-	return 0;
-}
-
-int decode_msg1_from_protobuf( protobuf_sgx_dh_msg1_t& protobuf_dhmsg1, sgx_dh_msg1_t* native_dhmsg1)
-{
-	int counter; google::protobuf::uint32 temp32;// google::protobuf::uint64 temp64;
-
-	for(counter=0;counter<SGX_ECP256_KEY_SIZE;counter++)
-	{
-		temp32 = protobuf_dhmsg1.mutable_g_a()->gx(counter);
-		if(fit_32_into_uint8_t(temp32, &(native_dhmsg1->g_a.gx[counter]))!=0)
-		 return -1;
-		temp32 = protobuf_dhmsg1.mutable_g_a()->gy(counter);
-		if(fit_32_into_uint8_t(temp32, &(native_dhmsg1->g_a.gy[counter]))!=0)
-		 return -1;
-	}
-
-	for(counter=0;counter<SGX_HASH_SIZE;counter++)
-	{
-		temp32 = protobuf_dhmsg1.mutable_target()->mr_enclave(counter);
-		if(fit_32_into_uint8_t(temp32, &(native_dhmsg1->target.mr_enclave.m[counter]))!=0)
-		 return -1;
-	}
-
-	for(counter=0;counter<SGX_TARGET_INFO_RESERVED1_BYTES;counter++)
-	{
-		temp32 = protobuf_dhmsg1.mutable_target()->reserved1(counter);
-		if(fit_32_into_uint8_t(temp32, &(native_dhmsg1->target.reserved1[counter]))!=0)
-		 return -1;
-	}
-
-	for(counter=0;counter<SGX_TARGET_INFO_RESERVED2_BYTES;counter++)
-	{
-		temp32 = protobuf_dhmsg1.mutable_target()->reserved2(counter);
-		if(fit_32_into_uint8_t(temp32, &(native_dhmsg1->target.reserved2[counter]))!=0)
-		 return -1;
-	}
-
-	native_dhmsg1->target.attributes.flags = protobuf_dhmsg1.mutable_target()->mutable_attributes()->flags();
-	native_dhmsg1->target.attributes.xfrm = protobuf_dhmsg1.mutable_target()->mutable_attributes()->xfrm();
-	native_dhmsg1->target.misc_select = protobuf_dhmsg1.mutable_target()->misc_select();
-	return 0;
-}
-
-int decode_msg3_from_protobuf(protobuf_sgx_dh_msg3_t& protobuf_dhmsg3, sgx_dh_msg3_t* native_dhmsg3)
-{
-  int counter; google::protobuf::uint32 temp32;
-  for(counter=0;counter<SGX_DH_MAC_SIZE;counter++)
-  {
-		temp32=protobuf_dhmsg3.cmac(counter);
-    if(fit_32_into_uint8_t(temp32, &(native_dhmsg3->cmac[counter]))!=0)
-      return -1;
-  }
-
-  if(decode_report_from_protobuf(protobuf_dhmsg3.mutable_msg3_body()->mutable_report(), &(native_dhmsg3->msg3_body.report))==-1)
-    return -1;
-  int max_counter=protobuf_dhmsg3.mutable_msg3_body()->additional_prop_size();
-  native_dhmsg3->msg3_body.additional_prop_length=max_counter;
-  // TODO: Need to assign a variable on the heap and then pass it as an argument to this function - set it to null if protobuf_dhmsg3.mutable_msg3_body()->additional_prop_size() is 0
-  // TODO: And then free it in that function (create_session) when it is done. It is likely that it is 0 in the SGX SDK sample code. And SDK people probably didn't deserialize it - as it may contain a pointer in the general case - to the array of additional_properties.
-  if(max_counter!=0)
-    return -1;
-  return 0;
-}
-
-/*
-// TODO: PRIVATE - OR EVEN GET RID OF IT
-int print_initialized_msg1( protobuf_sgx_dh_msg1_t& protobuf_dhmsg1)
-{
-	int counter;
-	printf("gx\n");
-	for(counter=0;counter<SGX_ECP256_KEY_SIZE;counter++)
-	{
-		 printf("%d ", protobuf_dhmsg1.g_a().gx(counter));
-	}
-
-	printf("\ngy\n");
-	for(counter=0;counter<SGX_ECP256_KEY_SIZE;counter++)
-	{
-		 printf("%d ", protobuf_dhmsg1.g_a().gy(counter));
-	}
-
-	printf("\nmrenclave in target\n");
-	for(counter=0;counter<SGX_HASH_SIZE;counter++)
-	{
-		 printf("%" PRIu32 " ", protobuf_dhmsg1.target().mr_enclave(counter));
-	}
-
-	printf("\nreserved1 in target\n");
-	for(counter=0;counter<SGX_TARGET_INFO_RESERVED1_BYTES;counter++)
-	{
-		 printf("%" PRIu32 " ", protobuf_dhmsg1.target().reserved1(counter));
-	}
-
-	printf("\nreserved2 in target\n");
-	for(counter=0;counter<SGX_TARGET_INFO_RESERVED2_BYTES;counter++)
-	{
-		 printf("%" PRIu32 " ", protobuf_dhmsg1.target().reserved2(counter));
-	}
-
-	printf("\n %" PRIu64 "\n", protobuf_dhmsg1.target().attributes().flags());
-	printf("\n %" PRIu64 "\n", protobuf_dhmsg1.target().attributes().xfrm());
-	printf("\n %" PRIu32 "\n", protobuf_dhmsg1.target().misc_select());
-
-	return 0;
-}
-*/
-
-void encode_msg2_to_protobuf( protobuf_sgx_dh_msg2_t& protobuf_dhmsg2, sgx_dh_msg2_t* native_dhmsg2)
-{
-	int counter; google::protobuf::uint32 temp32;
-	printf("\n msg2 cmac \n");
-	for(counter=0;counter<SGX_DH_MAC_SIZE;counter++)
-	{
-		temp32=native_dhmsg2->cmac[counter];
-		protobuf_dhmsg2.add_cmac(temp32);
-		printf("%d ", temp32);
-	}
-
-	encode_ec256_public_key_to_protobuf(protobuf_dhmsg2.mutable_g_b(), &(native_dhmsg2->g_b));
-
-	encode_report_to_protobuf(protobuf_dhmsg2.mutable_report(), &(native_dhmsg2->report));
-}
-/*
-// Got rid of the session ID - figure out its role.
-//message1 from the destination enclave through a socket set up before.
-// TODO: What do we do about session id?
-int session_request_call(int fd, sgx_dh_msg1_t* dh_msg1) //, uint32_t* session_id)
-{
-	protobuf_sgx_dh_msg1_t protobuf_msg1;
-	printf("reading msg1\n");
-	fflush(stdout);
-	if(read_protobuf_msg_from_fd(fd, protobuf_msg1)!=0)
-		return -1;
-	print_initialized_msg1(protobuf_msg1);
-	printf("\n done reading msg1 --------------------\n");
-	fflush(stdout);
-  if(decode_msg1_from_protobuf(protobuf_msg1, dh_msg1)!=0)
-    return -1;
-  return 0;
-}
-
-// Source enclave for exchange_report_ocall (like other ocalls) will be the PHP enclave and the destination enclave will be the decryptor one.
-//Makes an sgx_ecall to the destination enclave sends message2 from the source enclave and gets message 3 from the destination enclave
-// TODO: What do we do about session id?
-int exchange_report_call(int fd, sgx_dh_msg2_t *dh_msg2, sgx_dh_msg3_t *dh_msg3) // , uint32_t* session_id)
-{
-	protobuf_sgx_dh_msg2_t protobuf_msg2;
-  protobuf_sgx_dh_msg3_t protobuf_msg3;
-	printf("\n------------------------------------- generating msg2 --------\n");
-	// Fill protobuf class for dhmsg2 with contents from its native C struct.
-	encode_msg2_to_protobuf(protobuf_msg2, dh_msg2);
-	// Write msg length and then write the raw msg.
-	if(write_protobuf_msg_to_fd(fd, protobuf_msg2)!=0)
-		return -1;
-	printf("Wrote msg2 to protobuf ------------------------------------------\n");
-	fflush(stdout);
-	// Read from socket dh_msg3
-	if(read_protobuf_msg_from_fd(fd, protobuf_msg3)!=0)
-		return -1;
- 	// Decode msg3 from protobuf to native structs
-	if(decode_msg3_from_protobuf(protobuf_msg3, dh_msg3)!=0)
-		return -1;
- 	return 0;
-
-}
-
-//Make an sgx_ecall to the destination enclave to close the session
-int end_session_ocall()
-{
-  return SGX_SUCCESS;
-}
-*/

+ 2 - 2
crypto.cpp

@@ -138,13 +138,13 @@ int aes_gcm_128(int enc, unsigned char *key, unsigned char *iv, unsigned char* p
 	return 0;
 }
 
-uint32_t base64_encoding_wrapper(unsigned char* dest, unsigned char* src, uint32_t length)
+uint32_t base64_encoding_wrapper(unsigned char* src, uint32_t length, unsigned char* dest)
 {
 	return EVP_EncodeBlock(dest, src, length);
 
 }
 
-uint32_t base64_decoding_wrapper(unsigned char* dest, const char* src, uint32_t length)
+uint32_t base64_decoding_wrapper(const char* src, uint32_t length, unsigned char* dest)
 {
         int length_with_padding = EVP_DecodeBlock(dest, (const unsigned char*) src, length);
         if(length_with_padding == -1)

+ 15 - 7
include/MainLogic.h

@@ -4,17 +4,25 @@
 
 #ifndef APACHE_PHP_EXTENSION_MAINLOGIC_H
 #define APACHE_PHP_EXTENSION_MAINLOGIC_H
-#include <LA.h>
-#include <PostLAMessaging.h>
+#include "LA.h"
+#include "PostLAMessaging.h"
 #include <string>
 #include <vector>
-class MainLogic {
+#include <phpcpp.h>
+
+class MainLogic : public Php::Base {
     LA laInitiator;
-    PostLAMessaging postLaMessaging;
+    PostLAMessaging postLaMessagingData;
+    PostLAMessaging postLaMessagingHeaders;
+    uint32_t header_refresh_counter;
+    std::string last_header_value;
+    int set_up_socket_connect(int port);
+    int conduct_la_get_initial_header(int fd1, int fd2);
+    int decode_base64_fields_list(std::vector <std::string> &base64_fields_list, std::vector <std::string> &binary_fields_list);
 public:
-    int deployment_stage();
-    int get_mitigator_header(std::string header_value, int* value_length);
-    int decrypt_values(std::vector<std::string>& base64_fields, std::vector<std::string>& plaintext_fields);
+    void deployment_stage();
+    Php::Value get_mitigator_header();
+    Php::Value php_decrypt_wrapper(Php::Parameters &params  );
 };
 
 

+ 16 - 0
include/PostLAMessaging.h

@@ -4,5 +4,21 @@
 
 #ifndef APACHE_PHP_EXTENSION_POSTLAMESSAGING_H
 #define APACHE_PHP_EXTENSION_POSTLAMESSAGING_H
+#include "ProtobufMessageRW.h"
+#include <string>
+#include <vector>
+class PostLAMessaging {
+    uint8_t key[16];
+    ProtobufMessageRW protobufReaderWriter;
+    uint32_t aes_gcm_wrapper(int enc, uint8_t* plaintext, uint32_t plaintext_length, uint8_t* ciphertext, uint32_t* ciphertext_length);
+    uint32_t encrypt_decrypt_msgs(int encrypt_decrypt, std::vector<std::string> &input_msgs,
+                                              std::vector<std::string> &output_msgs);
+public:
+    void set_la_symmetric_key(uint8_t* given_key);
+    void set_fd(int given_fd);
+    uint32_t receive_secure_msg(std::string& output_msg);
+    uint32_t receive_secure_msgs(std::vector<std::string>& output_msgs);
+    uint32_t send_secure_msgs(std::vector<std::string>& input_msgs);
+};
 
 #endif //APACHE_PHP_EXTENSION_POSTLAMESSAGING_H

+ 0 - 11
include/ProtobufLAInitiator.h

@@ -1,11 +0,0 @@
-int local_attestation_initiator(int port);
-int decrypt_client_data_through_decryptor( std::vector<std::string> &binary_ciphertext_client_data,
-                                           std::vector<std::string> &plaintext_client_data);
-int exchange_ciphertext_fields_with_decryptor(unsigned char* input, uint32_t input_size,
-                                              unsigned char* output, uint32_t* output_size);
-uint32_t post_local_attestation_get_mitigator_header(unsigned char* base64_encoded_token_H, uint32_t* base64_encoded_token_H_length);
-uint32_t base64_decoding_on_all_client_data(unsigned char* ip_base64_client_public_key_ciphertext, 
-  uint32_t ip_base64_client_public_key_ciphertext_length,
-  unsigned char* op_client_public_key_ciphertext,
-  uint32_t* op_client_public_key_ciphertext_length
-);

+ 0 - 1
include/SgxLAInititator.h

@@ -1 +0,0 @@
-int create_session(int fd, uint8_t* mr_enclave, uint8_t* mr_signer, uint8_t* send_mr_signer);

+ 0 - 3
include/SgxProtobufLAInitiator.h

@@ -1,3 +0,0 @@
-uint32_t process_protobuf_dh_msg1_generate_protobuf_dh_msg2(protobuf_sgx_dh_msg1_t& protobuf_msg1, protobuf_sgx_dh_msg2_t& protobuf_msg2, uint32_t* session_id);
-uint32_t process_protobuf_dh_msg3(protobuf_sgx_dh_msg3_t& protobuf_msg3, uint32_t* session_id);
-uint32_t aes_gcm_wrapper(int enc, unsigned char* ciphertext, uint32_t ciphertext_len, unsigned char* op_plaintext, uint32_t* op_plaintext_len);

+ 0 - 3
include/SgxProtobufLAInitiator_Transforms.h

@@ -1,3 +0,0 @@
-int decode_msg1_from_protobuf( protobuf_sgx_dh_msg1_t& protobuf_dhmsg1, sgx_dh_msg1_t* native_dhmsg1);
-int decode_msg3_from_protobuf(protobuf_sgx_dh_msg3_t& protobuf_dhmsg3, sgx_dh_msg3_t* native_dhmsg3);
-void encode_msg2_to_protobuf( protobuf_sgx_dh_msg2_t& protobuf_dhmsg2, sgx_dh_msg2_t* native_dhmsg2);

+ 2 - 2
include/crypto.h

@@ -1,3 +1,3 @@
 int aes_gcm_128(int enc, unsigned char *key, unsigned char *iv, unsigned char* plaintext, uint32_t plaintext_len, unsigned char *ciphertext,  uint32_t* op_ciphertext_len, unsigned char* tag); 
-uint32_t base64_encoding_wrapper(unsigned char* dest, unsigned char* src, uint32_t length);
-uint32_t base64_decoding_wrapper(unsigned char* dest, const char* src, uint32_t length);
+uint32_t base64_encoding_wrapper(unsigned char* src, uint32_t length, unsigned char* dest);
+uint32_t base64_decoding_wrapper(const char* src, uint32_t length, unsigned char* dest);

+ 11 - 130
systemMain.cpp

@@ -8,148 +8,29 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <stdio.h>
-#include "crypto.h"
-#include "ProtobufLAInitiator.h"
+#include "MainLogic.h"
 using namespace std;
 
-#define DECRYPTOR_PORT 3825
-int local_attestation_successful=0;
 int __ImageBase=0;
 
-class Mitigator : public Php::Base
-{
-	private:
-		static std::string mitigator_pubkey_header_value;
-		static std::string mitigator_pubkey_header;
-		static int time_file_fd;
-	public:
-		Mitigator() = default;
-		virtual ~Mitigator() = default;
+// Mitigator-Public-Key:
 
-		static void local_attestation_initiator_wrapper()
-		{
-			setbuf(stdout,NULL);
-			uint32_t return_sgx, base64_encoded_token_H_length;
-			unsigned char* base64_encoded_mitigator_header_and_value;
-
-			base64_encoded_mitigator_header_and_value = (unsigned char*) malloc( 400 ); 
-			//		unsigned char base64_encoded_mitigator_header[229] ; //216=(ceil(160/3) * 4) + 1 (for null character) + 21 for "Mitigator-Public-Key"
-			memcpy(base64_encoded_mitigator_header_and_value, mitigator_pubkey_header.c_str(), mitigator_pubkey_header.length());
-			return_sgx = local_attestation_initiator(DECRYPTOR_PORT);
-			if(return_sgx != 0)
-			{
-				if(return_sgx== 0xFFFFFFFF)
-				{
-					perror("\nCould not set up the socket: had the following error: "); fflush(stderr);
-				}
-				else
-				{
-					printf("\nHad the following error in SGX local attestation: 0x%x", return_sgx);
-					fflush(stdout);
-				}
-			}
-			else {
-				printf("\nSuccessful LA with port %d.\n", DECRYPTOR_PORT);
-				fflush(stdout);
-				return_sgx= post_local_attestation_get_mitigator_header(base64_encoded_mitigator_header_and_value + mitigator_pubkey_header.length(),
-					&base64_encoded_token_H_length);
-				if(return_sgx != 0)
-				{
-					printf("\nHad the following error in SGX POST local attestation: 0x%x", return_sgx);
-					fflush(stdout);
-				}
-				mitigator_pubkey_header_value=std::string((char*)base64_encoded_mitigator_header_and_value,mitigator_pubkey_header.length()+base64_encoded_token_H_length);
-			}
-			free(base64_encoded_mitigator_header_and_value); 
-			time_file_fd=open("target_time.txt", O_APPEND | O_WRONLY);
-		}
-
-		static Php::Value get_mitigator_header()
-		{
-			return mitigator_pubkey_header_value;
-		}
-
-		static Php::Value php_decrypt_wrapper(Php::Parameters &params   )
-		{
-            // struct timeval  tv1, tv2;
-			// char time_buf[60] = {0};
-			// unsigned long int new_time, old_time;
-
-			// gettimeofday(&tv1, NULL);
-
-            uint32_t ret_status, field_size;
-            std::vector<std::string> base64_fields, binary_ciphertext_client_fields, plaintext_client_fields;
-            unsigned char *binary_ciphertext_client_field;
-            const char* temp_ptr;
-            Php::Object ret_object;
-            Php::Value input_base64_array;
-
-            ret_object["success"]="false";
-
-			if(params.size() < 2 )
-            {
-                ret_object["error"]="Need to pass 2 or more arguments.";
-                return ret_object;
-            }
-
-            input_base64_array = params;
-            base64_fields = Php::array_values(input_base64_array);
-            /*
-            for (auto &base64_field : base64_fields)
-            {
-                field_size= base64_field.size();
-                temp_ptr = base64_field.c_str();
-                // upper limit - the binary data will always be smaller than this (base64 length ~= 4/3 * binary length)
-                binary_ciphertext_client_field = (unsigned char*) malloc(field_size);
-                ret_status = base64_decoding_wrapper(binary_ciphertext_client_field, temp_ptr, field_size);
-                if(ret_status <= 0)
-                {
-                    free(binary_ciphertext_client_field);
-                    ret_object["error"]="Could not perform base64 decoding correctly for this field: " + base64_field;
-                    return ret_object;
-                }
-                binary_ciphertext_client_fields.push_back(std::string(reinterpret_cast<const char*> (binary_ciphertext_client_field), ret_status));
-            }
-
-            ret_status=decrypt_client_data_through_decryptor(binary_ciphertext_client_fields, plaintext_client_fields);
-			if(ret_status != 0)
-			{
-			    ret_object["error"]="Received the following error code when trying to decrypt data thru decryptor " + std::to_string(ret_status);
-				return ret_object;
-			}
-            */
-            ret_object["success"]="true";
-            ret_object["fields"]=Php::Array(base64_fields);
-            //ret_object["fields"]=Php::Array(plaintext_client_fields);
-
-			/*gettimeofday(&tv2, NULL);
-			new_time=tv2.tv_usec + tv2.tv_sec * 1000000;
-			old_time=tv1.tv_usec + tv1.tv_sec * 1000000;
-			bytes_written=sprintf(time_buf,  "%lu %lu\n", old_time, new_time);
-			write(time_file_fd, time_buf, bytes_written);
-			*/
-			return ret_object;
-		}
-};
-
-std::string Mitigator::mitigator_pubkey_header_value=std::string("!");
-std::string Mitigator::mitigator_pubkey_header=std::string("Mitigator-Public-Key:");
-int Mitigator::time_file_fd=0; 
 extern "C" {
-
     // export the "get_module" function that will be called by the Zend engine
     PHPCPP_EXPORT void *get_module()
     {
         // create extension
         static Php::Extension extension("decryptor_la_setup_and_decryption","1.0");
-
-        Php::Class<Mitigator> mitigator("Mitigator");
-	mitigator.method<&Mitigator::get_mitigator_header>("get_mitigator_header");
-	mitigator.method<&Mitigator::local_attestation_initiator_wrapper>("local_attestation_initiator_wrapper");
-	mitigator.method<&Mitigator::php_decrypt_wrapper>("php_decrypt_wrapper", { Php::ByVal("string", Php::Type::String), Php::ByVal("string", Php::Type::String) }   );
-        extension.onStartup(&Mitigator::local_attestation_initiator_wrapper);
+        MainLogic nativeMainLogic;
+
+        Php::Class<MainLogic> myMainLogic("MainLogic");
+        myMainLogic.method<&MainLogic::get_mitigator_header>("get_mitigator_header");
+        myMainLogic.method<&MainLogic::deployment_stage>("deployment_stage");
+        myMainLogic.method<&MainLogic::php_decrypt_wrapper>("php_decrypt_wrapper", { Php::ByVal("string", Php::Type::String), Php::ByVal("string", Php::Type::String) }   );
+        std::function<void()> startup_callback_fn = std::bind(&MainLogic::deployment_stage, nativeMainLogic); //nativeMainLogic.deployment_stage;
+        extension.onStartup(startup_callback_fn);
         // return the extension module
-	extension.add(mitigator);
+    	extension.add(myMainLogic);
         return extension.module();
     }
 }