clients.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. #include <iostream>
  2. #include <functional>
  3. #include "../App/appconfig.hpp"
  4. // The next line suppresses a deprecation warning within boost
  5. #define BOOST_BIND_GLOBAL_PLACEHOLDERS
  6. #include "boost/property_tree/ptree.hpp"
  7. #include "boost/property_tree/json_parser.hpp"
  8. #include <boost/thread.hpp>
  9. #include <boost/asio.hpp>
  10. #include "gcm.h"
  11. #include "sgx_tcrypto.h"
  12. #include "clients.hpp"
  13. #define CEILDIV(x,y) (((x)+(y)-1)/(y))
  14. Config config;
  15. Client *clients;
  16. aes_key ESK, TSK;
  17. std::vector<NodeConfig> ingestion_nodes, storage_nodes;
  18. std::vector<uint16_t> storage_map;
  19. std::vector<uint16_t> ingestion_map;
  20. unsigned long setup_time;
  21. // Split a hostport string like "127.0.0.1:12000" at the rightmost colon
  22. // into a host part "127.0.0.1" and a port part "12000".
  23. static bool split_host_port(std::string &host, std::string &port,
  24. const std::string &hostport)
  25. {
  26. size_t colon = hostport.find_last_of(':');
  27. if (colon == std::string::npos) {
  28. std::cerr << "Cannot parse \"" << hostport << "\" as host:port\n";
  29. return false;
  30. }
  31. host = hostport.substr(0, colon);
  32. port = hostport.substr(colon+1);
  33. return true;
  34. }
  35. // Convert a single hex character into its value from 0 to 15. Return
  36. // true on success, false if it wasn't a hex character.
  37. static inline bool hextoval(unsigned char &val, char hex)
  38. {
  39. if (hex >= '0' && hex <= '9') {
  40. val = ((unsigned char)hex)-'0';
  41. } else if (hex >= 'a' && hex <= 'f') {
  42. val = ((unsigned char)hex)-'a'+10;
  43. } else if (hex >= 'A' && hex <= 'F') {
  44. val = ((unsigned char)hex)-'A'+10;
  45. } else {
  46. return false;
  47. }
  48. return true;
  49. }
  50. // Convert a 2*len hex character string into a len-byte buffer. Return
  51. // true on success, false on failure.
  52. static bool hextobuf(unsigned char *buf, const char *str, size_t len)
  53. {
  54. if (strlen(str) != 2*len) {
  55. std::cerr << "Hex string was not the expected size\n";
  56. return false;
  57. }
  58. for (size_t i=0;i<len;++i) {
  59. unsigned char hi, lo;
  60. if (!hextoval(hi, str[2*i]) || !hextoval(lo, str[2*i+1])) {
  61. std::cerr << "Cannot parse string as hex\n";
  62. return false;
  63. }
  64. buf[i] = (unsigned char)((hi << 4) + lo);
  65. }
  66. return true;
  67. }
  68. void displayMessage(unsigned char *msg, uint16_t msg_size)
  69. {
  70. clientid_t sid, rid;
  71. unsigned char *ptr = msg;
  72. sid = *((clientid_t*) ptr);
  73. ptr+=sizeof(sid);
  74. rid = *((clientid_t*) ptr);
  75. ptr+=sizeof(sid);
  76. printf("Sender ID: %d, Receiver ID: %d, Token: N/A\n", sid, rid );
  77. printf("Message: ");
  78. for(int j = 0; j<msg_size - sizeof(sid)*2; j++) {
  79. printf("%x", (*ptr));
  80. ptr++;
  81. }
  82. printf("\n");
  83. }
  84. void displayPtMessageBundle(unsigned char *bundle, uint16_t priv_out,
  85. uint16_t msg_size)
  86. {
  87. unsigned char *ptr = bundle;
  88. for(int i=0; i<priv_out; i++) {
  89. displayMessage(ptr, msg_size);
  90. printf("\n");
  91. ptr+=msg_size;
  92. }
  93. printf("\n");
  94. }
  95. void displayEncMessageBundle(unsigned char *bundle, uint16_t priv_out,
  96. uint16_t msg_size)
  97. {
  98. unsigned char *ptr = bundle;
  99. uint64_t header = *((uint64_t*) ptr);
  100. ptr+=sizeof(uint64_t);
  101. printf("IV: ");
  102. for(int i=0; i<SGX_AESGCM_IV_SIZE; i++) {
  103. printf("%x", ptr[i]);
  104. }
  105. printf("\n");
  106. ptr+= SGX_AESGCM_IV_SIZE;
  107. for(int i=0; i<priv_out; i++) {
  108. displayMessage(ptr, msg_size);
  109. ptr+=msg_size;
  110. }
  111. printf("MAC: ");
  112. for(int i=0; i<SGX_AESGCM_MAC_SIZE; i++) {
  113. printf("%x", ptr[i]);
  114. }
  115. printf("\n");
  116. }
  117. static inline uint32_t encMsgBundleSize(uint16_t priv_out, uint16_t msg_size)
  118. {
  119. return(SGX_AESGCM_IV_SIZE + (priv_out * (msg_size + TOKEN_SIZE)) + SGX_AESGCM_MAC_SIZE);
  120. }
  121. static inline uint32_t ptMsgBundleSize(uint16_t priv_out, uint16_t msg_size)
  122. {
  123. return(priv_out * (msg_size + TOKEN_SIZE));
  124. }
  125. static inline uint32_t encMailboxSize(uint16_t priv_in, uint16_t msg_size)
  126. {
  127. return(SGX_AESGCM_IV_SIZE + (priv_in * msg_size) + SGX_AESGCM_MAC_SIZE);
  128. }
  129. static inline uint32_t ptMailboxSize(uint16_t priv_in, uint16_t msg_size)
  130. {
  131. return(priv_in * msg_size);
  132. }
  133. bool config_parse(Config &config, const std::string configstr,
  134. std::vector<NodeConfig> &ingestion_nodes,
  135. std::vector<NodeConfig> &storage_nodes,
  136. std::vector<uint16_t> &storage_map)
  137. {
  138. bool found_params = false;
  139. bool ret = true;
  140. std::istringstream configstream(configstr);
  141. boost::property_tree::ptree conftree;
  142. read_json(configstream, conftree);
  143. uint16_t node_num = 0;
  144. for (auto & entry : conftree) {
  145. if (!entry.first.compare("params")) {
  146. for (auto & pentry : entry.second) {
  147. if (!pentry.first.compare("msg_size")) {
  148. config.msg_size = pentry.second.get_value<uint16_t>();
  149. } else if (!pentry.first.compare("user_count")) {
  150. config.user_count = pentry.second.get_value<uint32_t>();
  151. } else if (!pentry.first.compare("priv_out")) {
  152. config.m_priv_out = pentry.second.get_value<uint8_t>();
  153. } else if (!pentry.first.compare("priv_in")) {
  154. config.m_priv_in = pentry.second.get_value<uint8_t>();
  155. } else if (!pentry.first.compare("pub_out")) {
  156. config.m_pub_out = pentry.second.get_value<uint8_t>();
  157. } else if (!pentry.first.compare("pub_in")) {
  158. config.m_pub_in = pentry.second.get_value<uint8_t>();
  159. // A hardcoded shared secret to derive various
  160. // keys for client -> server communications and tokens
  161. } else if (!pentry.first.compare("master_secret")) {
  162. std::string hex_key = pentry.second.data();
  163. memcpy(config.master_secret, hex_key.c_str(), SGX_AESGCM_KEY_SIZE);
  164. } else {
  165. std::cerr << "Unknown field in params: " <<
  166. pentry.first << "\n";
  167. ret = false;
  168. }
  169. }
  170. found_params = true;
  171. } else if (!entry.first.compare("nodes")) {
  172. for (auto & node : entry.second) {
  173. NodeConfig nc;
  174. // All nodes need to be assigned their role in manifest.yaml
  175. nc.roles = 0;
  176. for (auto & nentry : node.second) {
  177. if (!nentry.first.compare("name")) {
  178. nc.name = nentry.second.get_value<std::string>();
  179. } else if (!nentry.first.compare("pubkey")) {
  180. ret &= hextobuf((unsigned char *)&nc.pubkey,
  181. nentry.second.get_value<std::string>().c_str(),
  182. sizeof(nc.pubkey));
  183. } else if (!nentry.first.compare("weight")) {
  184. nc.weight = nentry.second.get_value<std::uint8_t>();
  185. } else if (!nentry.first.compare("listen")) {
  186. ret &= split_host_port(nc.listenhost, nc.listenport,
  187. nentry.second.get_value<std::string>());
  188. } else if (!nentry.first.compare("clisten")) {
  189. ret &= split_host_port(nc.clistenhost, nc.clistenport,
  190. nentry.second.get_value<std::string>());
  191. } else if (!nentry.first.compare("slisten")) {
  192. ret &= split_host_port(nc.slistenhost, nc.slistenport,
  193. nentry.second.get_value<std::string>());
  194. } else if (!nentry.first.compare("roles")) {
  195. nc.roles = nentry.second.get_value<std::uint8_t>();
  196. } else {
  197. std::cerr << "Unknown field in host config: " <<
  198. nentry.first << "\n";
  199. ret = false;
  200. }
  201. }
  202. if(nc.roles & ROLE_INGESTION) {
  203. ingestion_nodes.push_back(nc);
  204. ingestion_map.push_back(node_num);
  205. }
  206. if(nc.roles & ROLE_STORAGE) {
  207. storage_nodes.push_back(std::move(nc));
  208. storage_map.push_back(node_num);
  209. }
  210. node_num++;
  211. }
  212. } else {
  213. std::cerr << "Unknown key in config: " <<
  214. entry.first << "\n";
  215. ret = false;
  216. }
  217. }
  218. if (!found_params) {
  219. std::cerr << "Could not find params in config\n";
  220. ret = false;
  221. }
  222. return ret;
  223. }
  224. static void usage(const char *argv0)
  225. {
  226. fprintf(stderr, "%s [-t nthreads] < config.json\n",
  227. argv0);
  228. exit(1);
  229. }
  230. /*
  231. Generate ESK (Encryption Secret Key) and TSK (Token Secret Key)
  232. */
  233. int generateMasterKeys(sgx_aes_gcm_128bit_key_t master_secret,
  234. aes_key &ESK, aes_key &TSK )
  235. {
  236. unsigned char zeroes[SGX_AESGCM_KEY_SIZE];
  237. unsigned char iv[SGX_AESGCM_IV_SIZE];
  238. unsigned char mac[SGX_AESGCM_MAC_SIZE];
  239. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  240. memset(zeroes, 0, SGX_AESGCM_KEY_SIZE);
  241. memcpy(iv, "Encryption", sizeof("Encryption"));
  242. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0,
  243. master_secret, iv, SGX_AESGCM_IV_SIZE, ESK, mac)) {
  244. printf("Client: generateMasterKeys FAIL\n");
  245. return -1;
  246. }
  247. printf("\n\nEncryption Master Key: ");
  248. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  249. printf("%x", ESK[i]);
  250. }
  251. printf("\n");
  252. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  253. memcpy(iv, "Token", sizeof("Token"));
  254. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0,
  255. master_secret, iv, SGX_AESGCM_IV_SIZE, TSK, mac)) {
  256. printf("generateMasterKeys failed\n");
  257. return -1;
  258. }
  259. printf("Token Master Key: ");
  260. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  261. printf("%x", TSK[i]);
  262. }
  263. printf("\n\n");
  264. return 1;
  265. }
  266. /*
  267. Takes the client_number, the master aes_key for generating client keys
  268. for encrypted communication with ingestion (client_ing_key) and
  269. storage servers (client_stg_key)
  270. */
  271. int generateClientKeys(clientid_t client_number, aes_key &ESK,
  272. aes_key &client_ing_key, aes_key &client_stg_key)
  273. {
  274. unsigned char zeroes[SGX_AESGCM_KEY_SIZE];
  275. unsigned char iv[SGX_AESGCM_IV_SIZE];
  276. unsigned char tag[SGX_AESGCM_MAC_SIZE];
  277. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  278. memset(zeroes, 0, SGX_AESGCM_KEY_SIZE);
  279. memset(tag, 0, SGX_AESGCM_KEY_SIZE);
  280. memcpy(iv, &client_number, sizeof(client_number));
  281. /*
  282. printf("Client Key: (before Gen) ");
  283. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  284. printf("%x", client_ing_key[i]);
  285. }
  286. printf("\n");
  287. */
  288. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, ESK,
  289. iv, SGX_AESGCM_IV_SIZE, client_ing_key, tag)) {
  290. printf("generateClientKeys failed\n");
  291. return -1;
  292. }
  293. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  294. memcpy(iv, &client_number, sizeof(client_number));
  295. memcpy(iv +sizeof(client_number), "STG", sizeof("STG"));
  296. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, ESK,
  297. iv, SGX_AESGCM_IV_SIZE, client_stg_key, tag)) {
  298. printf("generateClientKeys failed\n");
  299. return -1;
  300. }
  301. /*
  302. printf("Client %d Ingestion: (after Gen) ", client_number);
  303. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  304. printf("%x", client_ing_key[i]);
  305. }
  306. printf("\n");
  307. */
  308. return 1;
  309. }
  310. void Client::initClient(clientid_t cid, uint16_t stg_id,
  311. aes_key ikey, aes_key skey)
  312. {
  313. uint16_t num_storage_nodes = storage_nodes.size();
  314. sim_id = cid;
  315. id = stg_id << DEST_UID_BITS;
  316. id += (cid/num_storage_nodes);
  317. token_list = new token[config.m_priv_out];
  318. memcpy(ing_key, ikey, SGX_AESGCM_KEY_SIZE);
  319. memcpy(stg_key, skey, SGX_AESGCM_KEY_SIZE);
  320. }
  321. void Client::initializeStgSocket(boost::asio::io_context &ioc,
  322. NodeConfig &stg_server)
  323. {
  324. boost::system::error_code err;
  325. boost::asio::ip::tcp::resolver resolver(ioc);
  326. while(1) {
  327. #ifdef VERBOSE_CLIENT
  328. std::cerr << "Connecting to " << stg_server.name << "...\n";
  329. std::cout << stg_server.slistenhost << ":" << stg_server.slistenport;
  330. #endif
  331. storage_sock = new boost::asio::ip::tcp::socket(ioc);
  332. boost::asio::connect(*storage_sock,
  333. resolver.resolve(stg_server.slistenhost,
  334. stg_server.slistenport), err);
  335. if (!err) break;
  336. std::cerr << "Connection to " << stg_server.name <<
  337. " refused, will , epoch_noretry.\n";
  338. sleep(1);
  339. }
  340. }
  341. void Client::initializeIngSocket(boost::asio::io_context &ioc,
  342. NodeConfig &ing_server)
  343. {
  344. boost::system::error_code err;
  345. boost::asio::ip::tcp::resolver resolver(ioc);
  346. while(1) {
  347. #ifdef VERBOSE_CLIENT
  348. std::cerr << "Connecting to " << ing_server.name << "...\n";
  349. std::cout << ing_server.clistenhost << ":" << ing_server.clistenport;
  350. #endif
  351. ingestion_sock = new boost::asio::ip::tcp::socket(ioc);
  352. boost::asio::connect(*ingestion_sock,
  353. resolver.resolve(ing_server.clistenhost,
  354. ing_server.clistenport), err);
  355. if (!err) break;
  356. std::cerr << "Connection to " << ing_server.name <<
  357. " refused, will , epoch_noretry.\n";
  358. sleep(1);
  359. }
  360. }
  361. /*
  362. Populates the buffer pt_msgbundle with a valid message pt_msgbundle.
  363. Assumes that it is supplied with a pt_msgbundle buffer of the correct length
  364. Correct length for pt_msgbundle = 8 + (priv_out)*(msg_size) + 16 bytes
  365. */
  366. void Client::generateMessageBundle(uint8_t priv_out, uint32_t msg_size,
  367. unsigned char *pt_msgbundle)
  368. {
  369. unsigned char *ptr = pt_msgbundle;
  370. // Setup message pt_msgbundle
  371. for(uint32_t i = 0; i < priv_out; i++) {
  372. memcpy(ptr, &id, sizeof(id));
  373. ptr+=(sizeof(id));
  374. memcpy(ptr, &id, sizeof(id));
  375. ptr+=(sizeof(id));
  376. uint32_t remaining_message_size = msg_size - (sizeof(id)*2);
  377. memset(ptr, 0, remaining_message_size);
  378. ptr+=(remaining_message_size);
  379. }
  380. // Add the tokens for this msgbundle
  381. memcpy(ptr, token_list, config.m_priv_out * TOKEN_SIZE);
  382. }
  383. bool Client::encryptMessageBundle(uint32_t enc_bundle_size, unsigned char *pt_msgbundle,
  384. unsigned char *enc_msgbundle)
  385. {
  386. // Encrypt the pt_msgbundle
  387. unsigned char *pt_msgbundle_start = pt_msgbundle;
  388. unsigned char *enc_msgbundle_start = enc_msgbundle + SGX_AESGCM_IV_SIZE;
  389. unsigned char *enc_tag = enc_msgbundle + enc_bundle_size - SGX_AESGCM_MAC_SIZE;
  390. size_t bytes_to_encrypt = enc_bundle_size - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE;
  391. if (bytes_to_encrypt != gcm_encrypt(pt_msgbundle_start, bytes_to_encrypt,
  392. NULL, 0, ing_key, ing_iv, SGX_AESGCM_IV_SIZE, enc_msgbundle_start, enc_tag)) {
  393. printf("Client: encryptMessageBundle FAIL\n");
  394. return 0;
  395. }
  396. // Copy IV into the bundle
  397. memcpy(enc_msgbundle, ing_iv, SGX_AESGCM_IV_SIZE);
  398. // Update IV
  399. uint64_t *iv_ctr = (uint64_t*) ing_iv;
  400. (*iv_ctr)+=1;
  401. return 1;
  402. }
  403. void Client::sendMessageBundle()
  404. {
  405. uint16_t priv_out = config.m_priv_out;
  406. uint16_t msg_size = config.msg_size;
  407. uint32_t send_pt_msgbundle_size = ptMsgBundleSize(priv_out, msg_size);
  408. uint32_t send_enc_msgbundle_size = encMsgBundleSize(priv_out, msg_size);
  409. unsigned char *send_pt_msgbundle = (unsigned char*) malloc (send_pt_msgbundle_size);
  410. unsigned char *send_enc_msgbundle = (unsigned char*) malloc (send_enc_msgbundle_size);
  411. generateMessageBundle(priv_out, msg_size, send_pt_msgbundle);
  412. encryptMessageBundle(send_enc_msgbundle_size, send_pt_msgbundle, send_enc_msgbundle);
  413. #ifdef VERBOSE_CLIENT
  414. displayPtMessageBundle(send_pt_msgbundle, priv_out, msg_size);
  415. #endif
  416. boost::asio::async_write(*ingestion_sock,
  417. boost::asio::buffer(send_enc_msgbundle, send_enc_msgbundle_size),
  418. [this, send_enc_msgbundle] (boost::system::error_code ecc, std::size_t) {
  419. #ifdef VERBOSE_CLIENT
  420. if(sim_id==0){
  421. printf("TEST: Client 0 send their msgbundle\n");
  422. }
  423. #endif
  424. if (ecc) {
  425. if(ecc == boost::asio::error::eof) {
  426. delete(storage_sock);
  427. }
  428. else {
  429. printf("Error %s\n", ecc.message().c_str());
  430. }
  431. printf("Client: boost async_write failed for sending message bundle\n");
  432. return;
  433. }
  434. free(send_enc_msgbundle);
  435. });
  436. free(send_pt_msgbundle);
  437. }
  438. int Client::sendIngAuthMessage(unsigned long epoch_no)
  439. {
  440. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) + SGX_AESGCM_KEY_SIZE;
  441. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  442. unsigned char *am_ptr = auth_message;
  443. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  444. am_ptr+=sizeof(sim_id);
  445. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  446. am_ptr+=sizeof(unsigned long);
  447. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  448. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  449. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  450. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  451. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, ing_key,
  452. epoch_iv, SGX_AESGCM_IV_SIZE, am_ptr, tag)) {
  453. printf("generateClientKeys failed\n");
  454. return -1;
  455. }
  456. #ifdef VERBOSE_CLIENT
  457. printf("Client %d auth_message: \n", id);
  458. for(int i=0; i<auth_size; i++) {
  459. printf("%x", auth_message[i]);
  460. }
  461. printf("\n");
  462. #endif
  463. boost::asio::write(*ingestion_sock,
  464. boost::asio::buffer(auth_message, auth_size));
  465. return 1;
  466. }
  467. int Client::sendStgAuthMessage(unsigned long epoch_no)
  468. {
  469. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) + SGX_AESGCM_KEY_SIZE;
  470. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  471. unsigned char *am_ptr = auth_message;
  472. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  473. am_ptr+=sizeof(sim_id);
  474. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  475. am_ptr+=sizeof(unsigned long);
  476. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  477. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  478. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  479. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  480. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, stg_key,
  481. epoch_iv, SGX_AESGCM_IV_SIZE, am_ptr, tag)) {
  482. printf("generateClientKeys failed\n");
  483. return -1;
  484. }
  485. #ifdef VERBOSE_CLIENT
  486. printf("Client %d auth_message: \n", id);
  487. for(int i=0; i<auth_size; i++) {
  488. printf("%x", auth_message[i]);
  489. }
  490. printf("\n");
  491. #endif
  492. boost::asio::async_write(*storage_sock,
  493. boost::asio::buffer(auth_message, auth_size),
  494. [this] (boost::system::error_code ecc, std::size_t) {
  495. if (ecc) {
  496. if(ecc == boost::asio::error::eof) {
  497. delete(storage_sock);
  498. }
  499. else {
  500. printf("Error %s\n", ecc.message().c_str());
  501. }
  502. printf("Client::sendStgAuthMessage boost async_write failed\n");
  503. return;
  504. }
  505. });
  506. return 1;
  507. }
  508. void Client::setup_client(boost::asio::io_context &io_context,
  509. uint32_t sim_id, uint16_t ing_node_id, uint16_t stg_node_id)
  510. {
  511. // Setup the client's
  512. // (i) client_id
  513. // (ii) symmetric keys shared with their ingestion and storage server
  514. // (iii) sockets to their ingestion and storage server
  515. aes_key client_ing_key;
  516. aes_key client_stg_key;
  517. int ret = generateClientKeys(sim_id, ESK, client_ing_key, client_stg_key);
  518. initClient(sim_id, stg_node_id, client_ing_key, client_stg_key);
  519. initializeStgSocket(io_context, storage_nodes[stg_node_id]);
  520. initializeIngSocket(io_context, ingestion_nodes[ing_node_id]);
  521. // Authenticate clients to their ingestion and storage servers
  522. struct timespec ep;
  523. clock_gettime(CLOCK_REALTIME_COARSE, &ep);
  524. unsigned long time_in_ns = ep.tv_sec * 1000000 + ep.tv_nsec/1000;
  525. unsigned long epoch_no = CEILDIV(time_in_ns, EPOCH_INTERVAL);
  526. sendStgAuthMessage(epoch_no);
  527. sendIngAuthMessage(epoch_no);
  528. }
  529. void generateClients(boost::asio::io_context &io_context,
  530. uint32_t cstart, uint32_t cstop)
  531. {
  532. uint32_t num_clients_total = config.user_count;
  533. uint16_t num_stg_nodes = storage_nodes.size();
  534. uint16_t num_ing_nodes = ingestion_nodes.size();
  535. for(uint32_t i=cstart; i<cstop; i++) {
  536. uint16_t ing_no = i % num_ing_nodes;
  537. uint16_t stg_no = i % num_stg_nodes;
  538. uint16_t stg_node_id = storage_map[stg_no];
  539. uint16_t ing_node_id = ingestion_map[ing_no];
  540. clients[i].setup_client(io_context, i, ing_node_id, stg_node_id);
  541. }
  542. }
  543. /*
  544. Epochs are server driven.
  545. In a single epoch, each client waits to receive from their storage server
  546. (i) a token bundle for this epoch and (ii) their messages from the last epoch
  547. The client then sends their messages for this epoch to their ingestion servers
  548. using the tokens they received in this epoch
  549. */
  550. void Client::epoch_process() {
  551. uint32_t pt_token_size = (config.m_priv_out * SGX_AESGCM_KEY_SIZE);
  552. uint32_t token_bundle_size = pt_token_size + SGX_AESGCM_IV_SIZE
  553. + SGX_AESGCM_MAC_SIZE;
  554. unsigned char *enc_tokens = (unsigned char*) malloc (token_bundle_size);
  555. //Async read the encrypted tokens for this epoch
  556. boost::asio::async_read(*storage_sock, boost::asio::buffer(enc_tokens, token_bundle_size),
  557. [this, enc_tokens, token_bundle_size, pt_token_size]
  558. (boost::system::error_code ec, std::size_t) {
  559. if (ec) {
  560. if(ec == boost::asio::error::eof) {
  561. delete(storage_sock);
  562. }
  563. else {
  564. printf("Error %s\n", ec.message().c_str());
  565. }
  566. printf("Client::epoch_process boost async_read_tokens failed\n");
  567. return;
  568. }
  569. #ifdef VERBOSE_CLIENT
  570. if(sim_id == 0) {
  571. printf("TEST: Client 0: Encrypted token bundle received:\n");
  572. for(uint32_t i = 0; i < token_bundle_size; i++) {
  573. printf("%x", enc_tokens[i]);
  574. }
  575. printf("\n");
  576. }
  577. #endif
  578. // Decrypt the token bundle
  579. unsigned char *enc_tkn_ptr = enc_tokens + SGX_AESGCM_IV_SIZE;
  580. unsigned char *enc_tkn_tag = enc_tokens + SGX_AESGCM_IV_SIZE + pt_token_size;
  581. int decrypted_bytes = gcm_decrypt(enc_tkn_ptr, pt_token_size,
  582. NULL, 0, enc_tkn_tag, (unsigned char*) &(this->stg_key),
  583. enc_tokens, SGX_AESGCM_IV_SIZE, (unsigned char*) (this->token_list));
  584. if(decrypted_bytes != pt_token_size) {
  585. printf("Client::epoch_process gcm_decrypt tokens failed. decrypted_bytes = %d \n", decrypted_bytes);
  586. }
  587. free(enc_tokens);
  588. /*
  589. unsigned char *tkn_ptr = (unsigned char*) this->token_list;
  590. if(sim_id==0) {
  591. printf("TEST: Client 0: Decrypted client tokens:\n");
  592. for(int i = 0; i < 2 * SGX_AESGCM_KEY_SIZE; i++) {
  593. printf("%x", tkn_ptr[i]);
  594. }
  595. printf("\n");
  596. }
  597. */
  598. // Async read the messages recieved in the last epoch
  599. uint16_t priv_in = config.m_priv_in;
  600. uint16_t msg_size = config.msg_size;
  601. uint32_t recv_pt_mailbox_size = ptMailboxSize(priv_in, msg_size);
  602. uint32_t recv_enc_mailbox_size = encMailboxSize(priv_in, msg_size);
  603. unsigned char *recv_pt_mailbox = (unsigned char*) malloc (recv_pt_mailbox_size);
  604. unsigned char *recv_enc_mailbox = (unsigned char*) malloc (recv_enc_mailbox_size);
  605. boost::asio::async_read(*storage_sock,
  606. boost::asio::buffer(recv_enc_mailbox, recv_enc_mailbox_size),
  607. [this, recv_pt_mailbox, recv_enc_mailbox]
  608. (boost::system::error_code ecc, std::size_t) {
  609. if (ecc) {
  610. if(ecc == boost::asio::error::eof) {
  611. delete(storage_sock);
  612. }
  613. else {
  614. printf("Error %s\n", ecc.message().c_str());
  615. }
  616. printf("Client: boost async_read failed for recieving msg_bundle\n");
  617. return;
  618. }
  619. #ifdef VERBOSE_CLIENT
  620. if(sim_id == 0) {
  621. printf("TEST: Client 0: Encrypted msgbundle received\n");
  622. }
  623. #endif
  624. // Do whatever processing with the received messages here
  625. free(recv_enc_mailbox);
  626. free(recv_pt_mailbox);
  627. // Send this epoch's message bundle
  628. sendMessageBundle();
  629. epoch_process();
  630. });
  631. });
  632. }
  633. void client_epoch_process(uint32_t cstart, uint32_t cstop)
  634. {
  635. for(uint32_t i=cstart; i<cstop; i++) {
  636. clients[i].epoch_process();
  637. }
  638. }
  639. void initializeClients(boost::asio::io_context &io_context, uint16_t nthreads)
  640. {
  641. std::vector<boost::thread> threads;
  642. uint32_t num_clients_total = config.user_count;
  643. size_t clients_per_thread = CEILDIV(num_clients_total, nthreads);
  644. // Generate all the clients for the experiment
  645. for(int i=0; i<nthreads; i++) {
  646. uint32_t cstart, cstop;
  647. cstart = i * clients_per_thread;
  648. cstop = (i==(nthreads-1))? num_clients_total: (i+1) * clients_per_thread;
  649. #ifdef VERBOSE_CLIENT
  650. printf("Thread %d, cstart = %d, cstop = %d\n", i, cstart, cstop);
  651. #endif
  652. threads.emplace_back(boost::thread(generateClients,
  653. boost::ref(io_context), cstart, cstop));
  654. }
  655. for(int i=0; i<nthreads; i++) {
  656. threads[i].join();
  657. }
  658. }
  659. void run_epochs(int nthreads) {
  660. size_t num_clients_total = config.user_count;
  661. size_t clients_per_thread = CEILDIV(num_clients_total, nthreads);
  662. std::vector<boost::thread> threads;
  663. for(int i=0; i<nthreads; i++) {
  664. uint32_t cstart, cstop;
  665. cstart = i * clients_per_thread;
  666. cstop = (i==nthreads-1)? num_clients_total: (i+1) * clients_per_thread;
  667. threads.emplace_back(boost::thread(client_epoch_process,
  668. cstart, cstop));
  669. }
  670. for(int i=0; i<nthreads; i++) {
  671. threads[i].join();
  672. }
  673. }
  674. int main(int argc, char **argv)
  675. {
  676. // Unbuffer stdout
  677. setbuf(stdout, NULL);
  678. uint16_t nthreads = 1;
  679. const char *progname = argv[0];
  680. ++argv;
  681. // Parse options
  682. while (*argv && (*argv)[0] == '-') {
  683. if (!strcmp(*argv, "-t")) {
  684. if (argv[1] == NULL) {
  685. usage(progname);
  686. }
  687. nthreads = uint16_t(atoi(argv[1]));
  688. argv += 2;
  689. } else {
  690. usage(progname);
  691. }
  692. }
  693. // Read the config.json from the first line of stdin. We have to do
  694. // this before outputting anything to avoid potential deadlock with
  695. // the launch program.
  696. std::string configstr;
  697. std::getline(std::cin, configstr);
  698. boost::asio::io_context io_context;
  699. if (!config_parse(config, configstr, ingestion_nodes,
  700. storage_nodes, storage_map)) {
  701. exit(1);
  702. }
  703. clients = new Client[config.user_count];
  704. #ifdef VERBOSE_CLIENT
  705. printf("Number of ingestion_nodes = %ld, Number of storage_node = %ld\n",
  706. ingestion_nodes.size(), storage_nodes.size());
  707. #endif
  708. generateMasterKeys(config.master_secret, ESK, TSK);
  709. // Queue up the actual work
  710. boost::asio::post(io_context, [&]{
  711. initializeClients(io_context, nthreads);
  712. run_epochs(nthreads);
  713. });
  714. // Start another thread; one will perform the work and the other
  715. // will execute the async_write handlers
  716. boost::thread t([&]{io_context.run();});
  717. io_context.run();
  718. t.join();
  719. delete [] clients;
  720. }