clients.cpp 27 KB

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