clients.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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. if(client_number % 10 == 0) {
  303. printf("Client %d Storage Key: (after Gen) ", client_number);
  304. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  305. printf("%x", client_stg_key[i]);
  306. }
  307. printf("\n");
  308. }
  309. */
  310. return 1;
  311. }
  312. void Client::initClient(clientid_t cid, uint16_t stg_id,
  313. aes_key ikey, aes_key skey)
  314. {
  315. uint16_t num_storage_nodes = storage_nodes.size();
  316. sim_id = cid;
  317. id = stg_id << DEST_UID_BITS;
  318. id += (cid/num_storage_nodes);
  319. token_list = new token[config.m_priv_out];
  320. memcpy(ing_key, ikey, SGX_AESGCM_KEY_SIZE);
  321. memcpy(stg_key, skey, SGX_AESGCM_KEY_SIZE);
  322. }
  323. void Client::initializeStgSocket(boost::asio::io_context &ioc,
  324. NodeConfig &stg_server)
  325. {
  326. boost::system::error_code err;
  327. boost::asio::ip::tcp::resolver resolver(ioc);
  328. while(1) {
  329. #ifdef VERBOSE_CLIENT
  330. std::cerr << "Connecting to " << stg_server.name << "...\n";
  331. std::cout << stg_server.slistenhost << ":" << stg_server.slistenport;
  332. #endif
  333. storage_sock = new boost::asio::ip::tcp::socket(ioc);
  334. boost::asio::connect(*storage_sock,
  335. resolver.resolve(stg_server.slistenhost,
  336. stg_server.slistenport), err);
  337. if (!err) break;
  338. std::cerr << "Connection to " << stg_server.name <<
  339. " refused, will , epoch_noretry.\n";
  340. sleep(1);
  341. }
  342. }
  343. void Client::initializeIngSocket(boost::asio::io_context &ioc,
  344. NodeConfig &ing_server)
  345. {
  346. boost::system::error_code err;
  347. boost::asio::ip::tcp::resolver resolver(ioc);
  348. while(1) {
  349. #ifdef VERBOSE_CLIENT
  350. std::cerr << "Connecting to " << ing_server.name << "...\n";
  351. std::cout << ing_server.clistenhost << ":" << ing_server.clistenport;
  352. #endif
  353. ingestion_sock = new boost::asio::ip::tcp::socket(ioc);
  354. boost::asio::connect(*ingestion_sock,
  355. resolver.resolve(ing_server.clistenhost,
  356. ing_server.clistenport), err);
  357. if (!err) break;
  358. std::cerr << "Connection to " << ing_server.name <<
  359. " refused, will , epoch_noretry.\n";
  360. sleep(1);
  361. }
  362. }
  363. /*
  364. Populates the buffer pt_msgbundle with a valid message pt_msgbundle.
  365. Assumes that it is supplied with a pt_msgbundle buffer of the correct length
  366. Correct length for pt_msgbundle = 8 + (priv_out)*(msg_size) + 16 bytes
  367. */
  368. void Client::generateMessageBundle(uint8_t priv_out, uint32_t msg_size,
  369. unsigned char *pt_msgbundle)
  370. {
  371. unsigned char *ptr = pt_msgbundle;
  372. // Setup message pt_msgbundle
  373. for(uint32_t i = 0; i < priv_out; i++) {
  374. memcpy(ptr, &id, sizeof(id));
  375. ptr+=(sizeof(id));
  376. memcpy(ptr, &id, sizeof(id));
  377. ptr+=(sizeof(id));
  378. uint32_t remaining_message_size = msg_size - (sizeof(id)*2);
  379. memset(ptr, 0, remaining_message_size);
  380. ptr+=(remaining_message_size);
  381. }
  382. // Add the tokens for this msgbundle
  383. memcpy(ptr, token_list, config.m_priv_out * TOKEN_SIZE);
  384. }
  385. bool Client::encryptMessageBundle(uint32_t enc_bundle_size, unsigned char *pt_msgbundle,
  386. unsigned char *enc_msgbundle)
  387. {
  388. // Encrypt the pt_msgbundle
  389. unsigned char *pt_msgbundle_start = pt_msgbundle;
  390. unsigned char *enc_msgbundle_start = enc_msgbundle + SGX_AESGCM_IV_SIZE;
  391. unsigned char *enc_tag = enc_msgbundle + enc_bundle_size - SGX_AESGCM_MAC_SIZE;
  392. size_t bytes_to_encrypt = enc_bundle_size - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE;
  393. if (bytes_to_encrypt != gcm_encrypt(pt_msgbundle_start, bytes_to_encrypt,
  394. NULL, 0, ing_key, ing_iv, SGX_AESGCM_IV_SIZE, enc_msgbundle_start, enc_tag)) {
  395. printf("Client: encryptMessageBundle FAIL\n");
  396. return 0;
  397. }
  398. // Copy IV into the bundle
  399. memcpy(enc_msgbundle, ing_iv, SGX_AESGCM_IV_SIZE);
  400. // Update IV
  401. uint64_t *iv_ctr = (uint64_t*) ing_iv;
  402. (*iv_ctr)+=1;
  403. return 1;
  404. }
  405. void Client::sendMessageBundle()
  406. {
  407. uint16_t priv_out = config.m_priv_out;
  408. uint16_t msg_size = config.msg_size;
  409. uint32_t send_pt_msgbundle_size = ptMsgBundleSize(priv_out, msg_size);
  410. uint32_t send_enc_msgbundle_size = encMsgBundleSize(priv_out, msg_size);
  411. unsigned char *send_pt_msgbundle = (unsigned char*) malloc (send_pt_msgbundle_size);
  412. unsigned char *send_enc_msgbundle = (unsigned char*) malloc (send_enc_msgbundle_size);
  413. generateMessageBundle(priv_out, msg_size, send_pt_msgbundle);
  414. encryptMessageBundle(send_enc_msgbundle_size, send_pt_msgbundle, send_enc_msgbundle);
  415. #ifdef VERBOSE_CLIENT
  416. displayPtMessageBundle(send_pt_msgbundle, priv_out, msg_size);
  417. #endif
  418. boost::asio::async_write(*ingestion_sock,
  419. boost::asio::buffer(send_enc_msgbundle, send_enc_msgbundle_size),
  420. [this, send_enc_msgbundle] (boost::system::error_code ecc, std::size_t) {
  421. #ifdef VERBOSE_CLIENT
  422. if(sim_id==0){
  423. printf("TEST: Client 0 send their msgbundle\n");
  424. }
  425. #endif
  426. if (ecc) {
  427. if(ecc == boost::asio::error::eof) {
  428. delete(storage_sock);
  429. }
  430. else {
  431. printf("Error %s\n", ecc.message().c_str());
  432. }
  433. printf("Client: boost async_write failed for sending message bundle\n");
  434. return;
  435. }
  436. free(send_enc_msgbundle);
  437. });
  438. free(send_pt_msgbundle);
  439. }
  440. int Client::sendIngAuthMessage(unsigned long epoch_no)
  441. {
  442. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) + SGX_AESGCM_KEY_SIZE;
  443. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  444. unsigned char *am_ptr = auth_message;
  445. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  446. am_ptr+=sizeof(sim_id);
  447. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  448. am_ptr+=sizeof(unsigned long);
  449. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  450. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  451. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  452. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  453. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, ing_key,
  454. epoch_iv, SGX_AESGCM_IV_SIZE, am_ptr, tag)) {
  455. printf("generateClientKeys failed\n");
  456. return -1;
  457. }
  458. #ifdef VERBOSE_CLIENT
  459. printf("Client %d auth_message: \n", id);
  460. for(int i=0; i<auth_size; i++) {
  461. printf("%x", auth_message[i]);
  462. }
  463. printf("\n");
  464. #endif
  465. boost::asio::write(*ingestion_sock,
  466. boost::asio::buffer(auth_message, auth_size));
  467. return 1;
  468. }
  469. int Client::sendStgAuthMessage(unsigned long epoch_no)
  470. {
  471. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) + SGX_AESGCM_KEY_SIZE;
  472. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  473. unsigned char *am_ptr = auth_message;
  474. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  475. am_ptr+=sizeof(sim_id);
  476. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  477. am_ptr+=sizeof(unsigned long);
  478. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  479. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  480. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  481. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  482. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, stg_key,
  483. epoch_iv, SGX_AESGCM_IV_SIZE, am_ptr, tag)) {
  484. printf("generateClientKeys failed\n");
  485. return -1;
  486. }
  487. #ifdef VERBOSE_CLIENT
  488. printf("Client %d auth_message: \n", id);
  489. for(int i=0; i<auth_size; i++) {
  490. printf("%x", auth_message[i]);
  491. }
  492. printf("\n");
  493. #endif
  494. boost::asio::async_write(*storage_sock,
  495. boost::asio::buffer(auth_message, auth_size),
  496. [this] (boost::system::error_code ecc, std::size_t) {
  497. if (ecc) {
  498. if(ecc == boost::asio::error::eof) {
  499. delete(storage_sock);
  500. }
  501. else {
  502. printf("Error %s\n", ecc.message().c_str());
  503. }
  504. printf("Client::sendStgAuthMessage boost async_write failed\n");
  505. return;
  506. }
  507. });
  508. return 1;
  509. }
  510. void Client::setup_client(boost::asio::io_context &io_context,
  511. uint32_t sim_id, uint16_t ing_node_id, uint16_t stg_node_id)
  512. {
  513. // Setup the client's
  514. // (i) client_id
  515. // (ii) symmetric keys shared with their ingestion and storage server
  516. // (iii) sockets to their ingestion and storage server
  517. aes_key client_ing_key;
  518. aes_key client_stg_key;
  519. int ret = generateClientKeys(sim_id, ESK, client_ing_key, client_stg_key);
  520. initClient(sim_id, stg_node_id, client_ing_key, client_stg_key);
  521. initializeStgSocket(io_context, storage_nodes[stg_node_id]);
  522. initializeIngSocket(io_context, ingestion_nodes[ing_node_id]);
  523. // Authenticate clients to their ingestion and storage servers
  524. struct timespec ep;
  525. clock_gettime(CLOCK_REALTIME_COARSE, &ep);
  526. unsigned long time_in_ns = ep.tv_sec * 1000000 + ep.tv_nsec/1000;
  527. unsigned long epoch_no = CEILDIV(time_in_ns, EPOCH_INTERVAL);
  528. sendStgAuthMessage(epoch_no);
  529. sendIngAuthMessage(epoch_no);
  530. }
  531. void generateClients(boost::asio::io_context &io_context,
  532. uint32_t cstart, uint32_t cstop)
  533. {
  534. uint32_t num_clients_total = config.user_count;
  535. uint16_t num_stg_nodes = storage_nodes.size();
  536. uint16_t num_ing_nodes = ingestion_nodes.size();
  537. uint32_t clients_per_ing = CEILDIV(num_clients_total, num_ing_nodes);
  538. uint16_t ing_with_additional = num_clients_total % num_ing_nodes;
  539. for(uint32_t i=cstart; i<cstop; i++) {
  540. uint16_t ing_no = i/clients_per_ing;
  541. if(ing_no > ing_with_additional && ing_with_additional!=0) {
  542. uint16_t leftover = num_clients_total - (ing_with_additional * clients_per_ing);
  543. ing_no = ing_with_additional + (leftover / (clients_per_ing-1));
  544. }
  545. uint16_t stg_no = i % num_stg_nodes;
  546. uint16_t stg_node_id = storage_map[stg_no];
  547. uint16_t ing_node_id = ingestion_map[ing_no];
  548. clients[i].setup_client(io_context, i, ing_node_id, stg_node_id);
  549. }
  550. }
  551. /*
  552. Epochs are server driven.
  553. In a single epoch, each client waits to receive from their storage server
  554. (i) a token bundle for this epoch and (ii) their messages from the last epoch
  555. The client then sends their messages for this epoch to their ingestion servers
  556. using the tokens they received in this epoch
  557. */
  558. void Client::epoch_process() {
  559. uint32_t pt_token_size = (config.m_priv_out * SGX_AESGCM_KEY_SIZE);
  560. uint32_t token_bundle_size = pt_token_size + SGX_AESGCM_IV_SIZE
  561. + SGX_AESGCM_MAC_SIZE;
  562. unsigned char *enc_tokens = (unsigned char*) malloc (token_bundle_size);
  563. //Async read the encrypted tokens for this epoch
  564. boost::asio::async_read(*storage_sock, boost::asio::buffer(enc_tokens, token_bundle_size),
  565. [this, enc_tokens, token_bundle_size, pt_token_size]
  566. (boost::system::error_code ec, std::size_t) {
  567. if (ec) {
  568. if(ec == boost::asio::error::eof) {
  569. delete(storage_sock);
  570. }
  571. else {
  572. printf("Error %s\n", ec.message().c_str());
  573. }
  574. printf("Client::epoch_process boost async_read_tokens failed\n");
  575. return;
  576. }
  577. #ifdef VERBOSE_CLIENT
  578. if(sim_id == 0) {
  579. printf("TEST: Client 0: Encrypted token bundle received:\n");
  580. for(uint32_t i = 0; i < token_bundle_size; i++) {
  581. printf("%x", enc_tokens[i]);
  582. }
  583. printf("\n");
  584. }
  585. #endif
  586. // Decrypt the token bundle
  587. unsigned char *enc_tkn_ptr = enc_tokens + SGX_AESGCM_IV_SIZE;
  588. unsigned char *enc_tkn_tag = enc_tokens + SGX_AESGCM_IV_SIZE + pt_token_size;
  589. int decrypted_bytes = gcm_decrypt(enc_tkn_ptr, pt_token_size,
  590. NULL, 0, enc_tkn_tag, (unsigned char*) &(this->stg_key),
  591. enc_tokens, SGX_AESGCM_IV_SIZE, (unsigned char*) (this->token_list));
  592. if(decrypted_bytes != pt_token_size) {
  593. printf("Client::epoch_process gcm_decrypt tokens failed. decrypted_bytes = %d \n", decrypted_bytes);
  594. }
  595. free(enc_tokens);
  596. /*
  597. unsigned char *tkn_ptr = (unsigned char*) this->token_list;
  598. if(sim_id==0) {
  599. printf("TEST: Client 0: Decrypted client tokens:\n");
  600. for(int i = 0; i < 2 * SGX_AESGCM_KEY_SIZE; i++) {
  601. printf("%x", tkn_ptr[i]);
  602. }
  603. printf("\n");
  604. }
  605. */
  606. // Async read the messages recieved in the last epoch
  607. uint16_t priv_in = config.m_priv_in;
  608. uint16_t msg_size = config.msg_size;
  609. uint32_t recv_pt_mailbox_size = ptMailboxSize(priv_in, msg_size);
  610. uint32_t recv_enc_mailbox_size = encMailboxSize(priv_in, msg_size);
  611. unsigned char *recv_pt_mailbox = (unsigned char*) malloc (recv_pt_mailbox_size);
  612. unsigned char *recv_enc_mailbox = (unsigned char*) malloc (recv_enc_mailbox_size);
  613. boost::asio::async_read(*storage_sock,
  614. boost::asio::buffer(recv_enc_mailbox, recv_enc_mailbox_size),
  615. [this, recv_pt_mailbox, recv_enc_mailbox]
  616. (boost::system::error_code ecc, std::size_t) {
  617. if (ecc) {
  618. if(ecc == boost::asio::error::eof) {
  619. delete(storage_sock);
  620. }
  621. else {
  622. printf("Error %s\n", ecc.message().c_str());
  623. }
  624. printf("Client: boost async_read failed for recieving msg_bundle\n");
  625. return;
  626. }
  627. #ifdef VERBOSE_CLIENT
  628. if(sim_id == 0) {
  629. printf("TEST: Client 0: Encrypted msgbundle received\n");
  630. }
  631. #endif
  632. // Do whatever processing with the received messages here
  633. free(recv_enc_mailbox);
  634. free(recv_pt_mailbox);
  635. // Send this epoch's message bundle
  636. sendMessageBundle();
  637. epoch_process();
  638. });
  639. });
  640. }
  641. void client_epoch_process(uint32_t cstart, uint32_t cstop)
  642. {
  643. for(uint32_t i=cstart; i<cstop; i++) {
  644. clients[i].epoch_process();
  645. }
  646. }
  647. void initializeClients(boost::asio::io_context &io_context, uint16_t nthreads)
  648. {
  649. std::vector<boost::thread> threads;
  650. uint32_t num_clients_total = config.user_count;
  651. size_t clients_per_thread = CEILDIV(num_clients_total, nthreads);
  652. // Generate all the clients for the experiment
  653. for(int i=0; i<nthreads; i++) {
  654. uint32_t cstart, cstop;
  655. cstart = i * clients_per_thread;
  656. cstop = (i==nthreads-1)? num_clients_total: (i+1) * clients_per_thread;
  657. #ifdef VERBOSE_CLIENT
  658. printf("Thread %d, cstart = %d, cstop = %d\n", i, cstart, cstop);
  659. #endif
  660. threads.emplace_back(boost::thread(generateClients,
  661. boost::ref(io_context), cstart, cstop));
  662. }
  663. for(int i=0; i<nthreads; i++) {
  664. threads[i].join();
  665. }
  666. }
  667. void run_epochs(int nthreads) {
  668. size_t num_clients_total = config.user_count;
  669. size_t clients_per_thread = CEILDIV(num_clients_total, nthreads);
  670. std::vector<boost::thread> threads;
  671. for(int i=0; i<nthreads; i++) {
  672. uint32_t cstart, cstop;
  673. cstart = i * clients_per_thread;
  674. cstop = (i==nthreads-1)? num_clients_total: (i+1) * clients_per_thread;
  675. threads.emplace_back(boost::thread(client_epoch_process,
  676. cstart, cstop));
  677. }
  678. for(int i=0; i<nthreads; i++) {
  679. threads[i].join();
  680. }
  681. }
  682. int main(int argc, char **argv)
  683. {
  684. // Unbuffer stdout
  685. setbuf(stdout, NULL);
  686. uint16_t nthreads = 1;
  687. const char *progname = argv[0];
  688. ++argv;
  689. // Parse options
  690. while (*argv && (*argv)[0] == '-') {
  691. if (!strcmp(*argv, "-t")) {
  692. if (argv[1] == NULL) {
  693. usage(progname);
  694. }
  695. nthreads = uint16_t(atoi(argv[1]));
  696. argv += 2;
  697. } else {
  698. usage(progname);
  699. }
  700. }
  701. // Read the config.json from the first line of stdin. We have to do
  702. // this before outputting anything to avoid potential deadlock with
  703. // the launch program.
  704. std::string configstr;
  705. std::getline(std::cin, configstr);
  706. boost::asio::io_context io_context;
  707. if (!config_parse(config, configstr, ingestion_nodes,
  708. storage_nodes, storage_map)) {
  709. exit(1);
  710. }
  711. clients = new Client[config.user_count];
  712. #ifdef VERBOSE_CLIENT
  713. printf("Number of ingestion_nodes = %ld, Number of storage_node = %ld\n",
  714. ingestion_nodes.size(), storage_nodes.size());
  715. #endif
  716. generateMasterKeys(config.master_secret, ESK, TSK);
  717. // Queue up the actual work
  718. boost::asio::post(io_context, [&]{
  719. initializeClients(io_context, nthreads);
  720. run_epochs(nthreads);
  721. });
  722. // Start another thread; one will perform the work and the other
  723. // will execute the async_write handlers
  724. boost::thread t([&]{io_context.run();});
  725. io_context.run();
  726. t.join();
  727. delete [] clients;
  728. }