clients.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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. #include <cstdlib>
  14. #define CEILDIV(x,y) (((x)+(y)-1)/(y))
  15. Config config;
  16. Client *clients;
  17. aes_key ESK, TSK;
  18. std::vector<NodeConfig> ingestion_nodes, storage_nodes;
  19. std::vector<uint16_t> storage_map;
  20. std::vector<uint16_t> ingestion_map;
  21. unsigned long setup_time;
  22. uint16_t nthreads = 1;
  23. bool private_routing;
  24. // Split a hostport string like "127.0.0.1:12000" at the rightmost colon
  25. // into a host part "127.0.0.1" and a port part "12000".
  26. static bool split_host_port(std::string &host, std::string &port,
  27. const std::string &hostport)
  28. {
  29. size_t colon = hostport.find_last_of(':');
  30. if (colon == std::string::npos) {
  31. std::cerr << "Cannot parse \"" << hostport << "\" as host:port\n";
  32. return false;
  33. }
  34. host = hostport.substr(0, colon);
  35. port = hostport.substr(colon+1);
  36. return true;
  37. }
  38. // Convert a single hex character into its value from 0 to 15. Return
  39. // true on success, false if it wasn't a hex character.
  40. static inline bool hextoval(unsigned char &val, char hex)
  41. {
  42. if (hex >= '0' && hex <= '9') {
  43. val = ((unsigned char)hex)-'0';
  44. } else if (hex >= 'a' && hex <= 'f') {
  45. val = ((unsigned char)hex)-'a'+10;
  46. } else if (hex >= 'A' && hex <= 'F') {
  47. val = ((unsigned char)hex)-'A'+10;
  48. } else {
  49. return false;
  50. }
  51. return true;
  52. }
  53. // Convert a 2*len hex character string into a len-byte buffer. Return
  54. // true on success, false on failure.
  55. static bool hextobuf(unsigned char *buf, const char *str, size_t len)
  56. {
  57. if (strlen(str) != 2*len) {
  58. std::cerr << "Hex string was not the expected size\n";
  59. return false;
  60. }
  61. for (size_t i=0;i<len;++i) {
  62. unsigned char hi, lo;
  63. if (!hextoval(hi, str[2*i]) || !hextoval(lo, str[2*i+1])) {
  64. std::cerr << "Cannot parse string as hex\n";
  65. return false;
  66. }
  67. buf[i] = (unsigned char)((hi << 4) + lo);
  68. }
  69. return true;
  70. }
  71. void displayMessage(unsigned char *msg, uint16_t msg_size)
  72. {
  73. clientid_t sid, rid;
  74. unsigned char *ptr = msg;
  75. sid = *((clientid_t*) ptr);
  76. ptr+=sizeof(sid);
  77. rid = *((clientid_t*) ptr);
  78. ptr+=sizeof(sid);
  79. printf("Sender ID: %d, Receiver ID: %d, Token: N/A\n", sid, rid );
  80. printf("Message: ");
  81. for(int j = 0; j<msg_size - sizeof(sid)*2; j++) {
  82. printf("%02x", (*ptr));
  83. ptr++;
  84. }
  85. printf("\n");
  86. }
  87. void displayPtMessageBundle(unsigned char *bundle, uint16_t priv_out,
  88. uint16_t msg_size)
  89. {
  90. unsigned char *ptr = bundle;
  91. for(int i=0; i<priv_out; i++) {
  92. displayMessage(ptr, msg_size);
  93. printf("\n");
  94. ptr+=msg_size;
  95. }
  96. printf("\n");
  97. }
  98. void displayEncMessageBundle(unsigned char *bundle, uint16_t priv_out,
  99. uint16_t msg_size)
  100. {
  101. unsigned char *ptr = bundle;
  102. uint64_t header = *((uint64_t*) ptr);
  103. ptr+=sizeof(uint64_t);
  104. printf("IV: ");
  105. for(int i=0; i<SGX_AESGCM_IV_SIZE; i++) {
  106. printf("%x", ptr[i]);
  107. }
  108. printf("\n");
  109. ptr+= SGX_AESGCM_IV_SIZE;
  110. for(int i=0; i<priv_out; i++) {
  111. displayMessage(ptr, msg_size);
  112. ptr+=msg_size;
  113. }
  114. printf("MAC: ");
  115. for(int i=0; i<SGX_AESGCM_MAC_SIZE; i++) {
  116. printf("%x", ptr[i]);
  117. }
  118. printf("\n");
  119. }
  120. static inline uint32_t encPubMsgBundleSize(uint16_t pub_out, uint16_t msg_size)
  121. {
  122. return SGX_AESGCM_IV_SIZE + (uint32_t(pub_out) * msg_size)
  123. + SGX_AESGCM_MAC_SIZE;
  124. }
  125. static inline uint32_t ptPubMsgBundleSize(uint16_t pub_out, uint16_t msg_size)
  126. {
  127. return uint32_t(pub_out) * msg_size;
  128. }
  129. static inline uint32_t encMsgBundleSize(uint16_t priv_out, uint16_t msg_size)
  130. {
  131. return SGX_AESGCM_IV_SIZE + (uint32_t(priv_out) * (msg_size + TOKEN_SIZE))
  132. + SGX_AESGCM_MAC_SIZE;
  133. }
  134. static inline uint32_t ptMsgBundleSize(uint16_t priv_out, uint16_t msg_size)
  135. {
  136. return uint32_t(priv_out) * (msg_size + TOKEN_SIZE);
  137. }
  138. static inline uint32_t encMailboxSize(uint16_t priv_in, uint16_t msg_size)
  139. {
  140. return SGX_AESGCM_IV_SIZE + (uint32_t(priv_in) * msg_size)
  141. + SGX_AESGCM_MAC_SIZE;
  142. }
  143. static inline uint32_t ptMailboxSize(uint16_t priv_in, uint16_t msg_size)
  144. {
  145. return uint32_t(priv_in) * msg_size;
  146. }
  147. bool config_parse(Config &config, const std::string configstr,
  148. std::vector<NodeConfig> &ingestion_nodes,
  149. std::vector<NodeConfig> &storage_nodes,
  150. std::vector<uint16_t> &storage_map)
  151. {
  152. bool found_params = false;
  153. bool ret = true;
  154. std::istringstream configstream(configstr);
  155. boost::property_tree::ptree conftree;
  156. read_json(configstream, conftree);
  157. uint16_t node_num = 0;
  158. for (auto & entry : conftree) {
  159. if (!entry.first.compare("params")) {
  160. for (auto & pentry : entry.second) {
  161. if (!pentry.first.compare("msg_size")) {
  162. config.msg_size = pentry.second.get_value<uint16_t>();
  163. } else if (!pentry.first.compare("user_count")) {
  164. config.user_count = pentry.second.get_value<uint32_t>();
  165. } else if (!pentry.first.compare("priv_out")) {
  166. config.m_priv_out = pentry.second.get_value<uint8_t>();
  167. } else if (!pentry.first.compare("priv_in")) {
  168. config.m_priv_in = pentry.second.get_value<uint8_t>();
  169. } else if (!pentry.first.compare("pub_out")) {
  170. config.m_pub_out = pentry.second.get_value<uint8_t>();
  171. } else if (!pentry.first.compare("pub_in")) {
  172. config.m_pub_in = pentry.second.get_value<uint8_t>();
  173. // A stub hardcoded shared secret to derive various
  174. // keys for client <-> server communications and tokens
  175. // In reality, this would be a key exchange
  176. } else if (!pentry.first.compare("master_secret")) {
  177. std::string hex_key = pentry.second.data();
  178. memcpy(config.master_secret, hex_key.c_str(),
  179. SGX_AESGCM_KEY_SIZE);
  180. } else if (!pentry.first.compare("private_routing")) {
  181. config.private_routing = pentry.second.get_value<bool>();
  182. } else {
  183. std::cerr << "Unknown field in params: " <<
  184. pentry.first << "\n";
  185. ret = false;
  186. }
  187. }
  188. found_params = true;
  189. } else if (!entry.first.compare("nodes")) {
  190. for (auto & node : entry.second) {
  191. NodeConfig nc;
  192. // All nodes need to be assigned their role in manifest.yaml
  193. nc.roles = 0;
  194. for (auto & nentry : node.second) {
  195. if (!nentry.first.compare("name")) {
  196. nc.name = nentry.second.get_value<std::string>();
  197. } else if (!nentry.first.compare("pubkey")) {
  198. ret &= hextobuf((unsigned char *)&nc.pubkey,
  199. nentry.second.get_value<std::string>().c_str(),
  200. sizeof(nc.pubkey));
  201. } else if (!nentry.first.compare("weight")) {
  202. nc.weight = nentry.second.get_value<std::uint8_t>();
  203. } else if (!nentry.first.compare("listen")) {
  204. ret &= split_host_port(nc.listenhost, nc.listenport,
  205. nentry.second.get_value<std::string>());
  206. } else if (!nentry.first.compare("clisten")) {
  207. ret &= split_host_port(nc.clistenhost, nc.clistenport,
  208. nentry.second.get_value<std::string>());
  209. } else if (!nentry.first.compare("slisten")) {
  210. ret &= split_host_port(nc.slistenhost, nc.slistenport,
  211. nentry.second.get_value<std::string>());
  212. } else if (!nentry.first.compare("roles")) {
  213. nc.roles = nentry.second.get_value<std::uint8_t>();
  214. } else {
  215. std::cerr << "Unknown field in host config: " <<
  216. nentry.first << "\n";
  217. ret = false;
  218. }
  219. }
  220. if(nc.roles & ROLE_INGESTION) {
  221. ingestion_nodes.push_back(nc);
  222. ingestion_map.push_back(node_num);
  223. }
  224. if(nc.roles & ROLE_STORAGE) {
  225. storage_nodes.push_back(std::move(nc));
  226. storage_map.push_back(node_num);
  227. }
  228. node_num++;
  229. }
  230. } else {
  231. std::cerr << "Unknown key in config: " <<
  232. entry.first << "\n";
  233. ret = false;
  234. }
  235. }
  236. if (!found_params) {
  237. std::cerr << "Could not find params in config\n";
  238. ret = false;
  239. }
  240. return ret;
  241. }
  242. static void usage(const char *argv0)
  243. {
  244. fprintf(stderr, "%s [-t nthreads] < config.json\n",
  245. argv0);
  246. exit(1);
  247. }
  248. /*
  249. Generate ESK (Encryption Secret Key) and TSK (Token Secret Key)
  250. */
  251. int generateMasterKeys(sgx_aes_gcm_128bit_key_t master_secret,
  252. aes_key &ESK, aes_key &TSK )
  253. {
  254. unsigned char zeroes[SGX_AESGCM_KEY_SIZE];
  255. unsigned char iv[SGX_AESGCM_IV_SIZE];
  256. unsigned char mac[SGX_AESGCM_MAC_SIZE];
  257. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  258. memset(zeroes, 0, SGX_AESGCM_KEY_SIZE);
  259. memcpy(iv, "Encryption", sizeof("Encryption"));
  260. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0,
  261. master_secret, iv, SGX_AESGCM_IV_SIZE, ESK, mac)) {
  262. printf("Client: generateMasterKeys FAIL\n");
  263. return -1;
  264. }
  265. printf("\n\nEncryption Master Key: ");
  266. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  267. printf("%x", ESK[i]);
  268. }
  269. printf("\n");
  270. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  271. memcpy(iv, "Token", sizeof("Token"));
  272. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0,
  273. master_secret, iv, SGX_AESGCM_IV_SIZE, TSK, mac)) {
  274. printf("generateMasterKeys failed\n");
  275. return -1;
  276. }
  277. printf("Token Master Key: ");
  278. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  279. printf("%x", TSK[i]);
  280. }
  281. printf("\n\n");
  282. return 1;
  283. }
  284. /*
  285. Takes the client_number, the master aes_key for generating client keys
  286. for encrypted communication with ingestion (client_ing_key) and
  287. storage servers (client_stg_key)
  288. */
  289. int generateClientKeys(clientid_t client_number, aes_key &ESK,
  290. aes_key &client_ing_key, aes_key &client_stg_key)
  291. {
  292. unsigned char zeroes[SGX_AESGCM_KEY_SIZE];
  293. unsigned char iv[SGX_AESGCM_IV_SIZE];
  294. unsigned char tag[SGX_AESGCM_MAC_SIZE];
  295. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  296. memset(zeroes, 0, SGX_AESGCM_KEY_SIZE);
  297. memset(tag, 0, SGX_AESGCM_KEY_SIZE);
  298. memcpy(iv, &client_number, sizeof(client_number));
  299. /*
  300. printf("Client Key: (before Gen) ");
  301. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  302. printf("%x", client_ing_key[i]);
  303. }
  304. printf("\n");
  305. */
  306. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, ESK,
  307. iv, SGX_AESGCM_IV_SIZE, client_ing_key, tag)) {
  308. printf("generateClientKeys failed\n");
  309. return -1;
  310. }
  311. memset(iv, 0, SGX_AESGCM_IV_SIZE);
  312. memcpy(iv, &client_number, sizeof(client_number));
  313. memcpy(iv +sizeof(client_number), "STG", sizeof("STG"));
  314. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE, NULL, 0, ESK,
  315. iv, SGX_AESGCM_IV_SIZE, client_stg_key, tag)) {
  316. printf("generateClientKeys failed\n");
  317. return -1;
  318. }
  319. /*
  320. printf("Client %d Ingestion: (after Gen) ", client_number);
  321. for(int i=0;i<SGX_AESGCM_KEY_SIZE;i++) {
  322. printf("%x", client_ing_key[i]);
  323. }
  324. printf("\n");
  325. */
  326. return 1;
  327. }
  328. void Client::initClient(clientid_t cid, uint16_t stg_id,
  329. aes_key ikey, aes_key skey)
  330. {
  331. uint16_t num_storage_nodes = storage_nodes.size();
  332. sim_id = cid;
  333. id = stg_id << DEST_UID_BITS;
  334. id += (cid/num_storage_nodes);
  335. token_list = new token[config.m_priv_out];
  336. memcpy(ing_key, ikey, SGX_AESGCM_KEY_SIZE);
  337. memcpy(stg_key, skey, SGX_AESGCM_KEY_SIZE);
  338. }
  339. void Client::initializeStgSocket(boost::asio::io_context &ioc,
  340. NodeConfig &stg_server, ip_addr *curr_ip, uint16_t &port_no)
  341. {
  342. boost::system::error_code err;
  343. while(1) {
  344. #ifdef VERBOSE_CLIENT
  345. std::cerr << "Connecting to " << stg_server.name << "...\n";
  346. std::cout << stg_server.slistenhost << ":" << stg_server.slistenport;
  347. #endif
  348. std::string ip_str = curr_ip->ip_str();
  349. boost::asio::ip::address ip_address =
  350. boost::asio::ip::address::from_string(ip_str, err);
  351. if(err) {
  352. printf("initializeStgSocket::Invalid IP address\n");
  353. }
  354. storage_sock = new boost::asio::ip::tcp::socket(ioc);
  355. storage_sock->open(boost::asio::ip::tcp::v4(), err);
  356. while(1) {
  357. boost::asio::ip::tcp::endpoint ep(ip_address, port_no);
  358. storage_sock->bind(ep, err);
  359. if (!err) {
  360. break;
  361. } else {
  362. printf("STG: Error %s. (%s:%d)\n", err.message().c_str(),
  363. (curr_ip->ip_str()).c_str(), port_no);
  364. port_no++;
  365. if(port_no >= PORT_END) {
  366. port_no = PORT_START;
  367. curr_ip->increment(nthreads);
  368. }
  369. }
  370. }
  371. boost::asio::ip::address stg_ip =
  372. boost::asio::ip::address::from_string(stg_server.slistenhost, err);
  373. boost::asio::ip::tcp::endpoint
  374. stg_ep(stg_ip, std::stoi(stg_server.slistenport));
  375. // just for printing
  376. // boost::asio::ip::tcp::endpoint ep(ip_address, port_no);
  377. storage_sock->connect(stg_ep, err);
  378. if (!err) {
  379. break;
  380. }
  381. std::cerr <<"STG: Connection from " <<
  382. curr_ip->ip_str() << ":" << port_no <<
  383. " to " << stg_server.name << " refused, will retry.\n";
  384. #ifdef RANDOMIZE_CLIENT_RETRY_SLEEP_TIME
  385. int sleep_delay = rand() % 100000;
  386. usleep(sleep_delay);
  387. #else
  388. usleep(1000000);
  389. #endif
  390. delete storage_sock;
  391. storage_sock = nullptr;
  392. }
  393. }
  394. void Client::initializeIngSocket(boost::asio::io_context &ioc,
  395. NodeConfig &ing_server, ip_addr *curr_ip, uint16_t &port_no)
  396. {
  397. boost::system::error_code err;
  398. boost::asio::ip::tcp::resolver resolver(ioc);
  399. while(1) {
  400. #ifdef VERBOSE_CLIENT
  401. std::cerr << "Connecting to " << ing_server.name << "...\n";
  402. std::cout << ing_server.clistenhost << ":" << ing_server.clistenport;
  403. #endif
  404. std::string ip_str = curr_ip->ip_str();
  405. boost::asio::ip::address ip_address =
  406. boost::asio::ip::address::from_string(ip_str, err);
  407. if(err) {
  408. printf("initializeIngSocket::Invalid IP address\n");
  409. }
  410. ingestion_sock = new boost::asio::ip::tcp::socket(ioc);
  411. ingestion_sock->open(boost::asio::ip::tcp::v4(), err);
  412. while(1) {
  413. boost::asio::ip::tcp::endpoint ep(ip_address, port_no);
  414. ingestion_sock->bind(ep, err);
  415. if (!err) {
  416. break;
  417. } else {
  418. printf("ING: Error %s. (%s:%d)\n", err.message().c_str(),
  419. (curr_ip->ip_str()).c_str(), port_no);
  420. port_no++;
  421. if(port_no >= PORT_END) {
  422. port_no = PORT_START;
  423. curr_ip->increment(nthreads);
  424. }
  425. }
  426. }
  427. // just for printing
  428. boost::asio::ip::tcp::endpoint ep(ip_address, port_no);
  429. boost::asio::ip::address ing_ip =
  430. boost::asio::ip::address::from_string(ing_server.clistenhost, err);
  431. boost::asio::ip::tcp::endpoint
  432. ing_ep(ing_ip, std::stoi(ing_server.clistenport));
  433. //std::cout << "Ing endpoint:" << ing_ep << "\n";
  434. //std::cout<<"ING: Attempting to connect client " << ep << " -> " << ing_ep <<"\n";
  435. ingestion_sock->connect(ing_ep, err);
  436. /*
  437. boost::asio::connect(*ingestion_sock,
  438. resolver.resolve(ing_server.clistenhost,
  439. ing_server.clistenport), err);
  440. */
  441. if (!err) {
  442. //std::cout<<"ING: Connected client " << ep << " -> " << ing_ep <<"\n";
  443. break;
  444. }
  445. std::cerr << "ING: Connection from " <<
  446. curr_ip->ip_str() << ":" << port_no <<
  447. " to " << ing_server.name << " refused, will retry.\n";
  448. #ifdef RANDOMIZE_CLIENT_RETRY_SLEEP_TIME
  449. int sleep_delay = rand() % 100000;
  450. usleep(sleep_delay);
  451. #else
  452. usleep(1000000);
  453. #endif
  454. delete ingestion_sock;
  455. ingestion_sock = nullptr;
  456. }
  457. }
  458. /*
  459. Populates the buffer pt_msgbundle with a valid message pt_msgbundle.
  460. Assumes that it is supplied with a pt_msgbundle buffer of the correct length
  461. Correct length for pt_msgbundle = 8 + (priv_out)*(msg_size) + 16 bytes
  462. */
  463. void Client::generateMessageBundle(uint8_t priv_out, uint32_t msg_size,
  464. unsigned char *pt_msgbundle)
  465. {
  466. unsigned char *ptr = pt_msgbundle;
  467. // Setup message pt_msgbundle
  468. for(uint32_t i = 0; i < priv_out; i++) {
  469. // For benchmarking, each client just sends messages to
  470. // themselves, so the destination and source ids are the same.
  471. memcpy(ptr, &id, sizeof(id));
  472. ptr+=(sizeof(id));
  473. memcpy(ptr, &id, sizeof(id));
  474. ptr+=(sizeof(id));
  475. uint32_t remaining_message_size = msg_size - (sizeof(id)*2);
  476. memset(ptr, 0, remaining_message_size);
  477. ptr+=(remaining_message_size);
  478. }
  479. if(private_routing) {
  480. // Add the tokens for this msgbundle
  481. memcpy(ptr, token_list, config.m_priv_out * TOKEN_SIZE);
  482. }
  483. }
  484. bool Client::encryptMessageBundle(uint32_t enc_bundle_size,
  485. unsigned char *pt_msgbundle, unsigned char *enc_msgbundle)
  486. {
  487. // Encrypt the pt_msgbundle
  488. unsigned char *pt_msgbundle_start = pt_msgbundle;
  489. unsigned char *enc_msgbundle_start = enc_msgbundle + SGX_AESGCM_IV_SIZE;
  490. unsigned char *enc_tag = enc_msgbundle + enc_bundle_size - SGX_AESGCM_MAC_SIZE;
  491. size_t bytes_to_encrypt = enc_bundle_size - SGX_AESGCM_MAC_SIZE -
  492. SGX_AESGCM_IV_SIZE;
  493. if (bytes_to_encrypt != gcm_encrypt(pt_msgbundle_start, bytes_to_encrypt,
  494. NULL, 0, ing_key, ing_iv, SGX_AESGCM_IV_SIZE, enc_msgbundle_start,
  495. enc_tag)) {
  496. printf("Client: encryptMessageBundle FAIL\n");
  497. return 0;
  498. }
  499. // Copy IV into the bundle
  500. memcpy(enc_msgbundle, ing_iv, SGX_AESGCM_IV_SIZE);
  501. // Update IV
  502. uint64_t *iv_ctr = (uint64_t*) ing_iv;
  503. (*iv_ctr)+=1;
  504. return 1;
  505. }
  506. #ifdef TRACE_SOCKIO
  507. class LimitLogger {
  508. std::string label;
  509. std::string thrid;
  510. struct timeval last_log;
  511. size_t num_items;
  512. public:
  513. LimitLogger(const char *_label): label(_label), last_log({0,0}),
  514. num_items(0) {
  515. std::stringstream ss;
  516. ss << boost::this_thread::get_id();
  517. thrid = ss.str();
  518. }
  519. void log() {
  520. struct timeval now;
  521. gettimeofday(&now, NULL);
  522. long elapsedus = (now.tv_sec - last_log.tv_sec) * 1000000
  523. + (now.tv_usec - last_log.tv_usec);
  524. if (num_items > 0 && elapsedus > 500000) {
  525. printf("%lu.%06lu: Thread %s end %s of %lu items\n",
  526. last_log.tv_sec, last_log.tv_usec,
  527. thrid.c_str(), label.c_str(),
  528. num_items);
  529. num_items = 0;
  530. }
  531. if (num_items == 0) {
  532. printf("%lu.%06lu: Thread %s begin %s\n", now.tv_sec,
  533. now.tv_usec, thrid.c_str(), label.c_str());
  534. }
  535. gettimeofday(&last_log, NULL);
  536. ++num_items;
  537. }
  538. };
  539. static thread_local LimitLogger
  540. recvlogger("recv"), queuelogger("queue"), sentlogger("sent");
  541. #endif
  542. void Client::sendMessageBundle()
  543. {
  544. uint16_t priv_out = config.m_priv_out;
  545. uint16_t pub_out = config.m_pub_out;
  546. uint16_t msg_size = config.msg_size;
  547. uint32_t send_pt_msgbundle_size, send_enc_msgbundle_size;
  548. if(private_routing) {
  549. send_pt_msgbundle_size = ptMsgBundleSize(priv_out, msg_size);
  550. send_enc_msgbundle_size = encMsgBundleSize(priv_out, msg_size);
  551. } else {
  552. send_pt_msgbundle_size = ptPubMsgBundleSize(pub_out, msg_size);
  553. send_enc_msgbundle_size = encPubMsgBundleSize(pub_out, msg_size);
  554. }
  555. unsigned char *send_pt_msgbundle =
  556. (unsigned char*) malloc (send_pt_msgbundle_size);
  557. unsigned char *send_enc_msgbundle =
  558. (unsigned char*) malloc (send_enc_msgbundle_size);
  559. if(private_routing) {
  560. generateMessageBundle(priv_out, msg_size, send_pt_msgbundle);
  561. } else {
  562. generateMessageBundle(pub_out, msg_size, send_pt_msgbundle);
  563. }
  564. encryptMessageBundle(send_enc_msgbundle_size, send_pt_msgbundle,
  565. send_enc_msgbundle);
  566. #ifdef VERBOSE_CLIENT
  567. displayPtMessageBundle(send_pt_msgbundle, priv_out, msg_size);
  568. #endif
  569. free(send_pt_msgbundle);
  570. #ifdef TRACE_SOCKIO
  571. queuelogger.log();
  572. #endif
  573. boost::asio::async_write(*ingestion_sock,
  574. boost::asio::buffer(send_enc_msgbundle, send_enc_msgbundle_size),
  575. [this, send_enc_msgbundle] (boost::system::error_code ecc, std::size_t) {
  576. #ifdef TRACE_SOCKIO
  577. sentlogger.log();
  578. #endif
  579. #ifdef VERBOSE_CLIENT
  580. if(sim_id==0){
  581. printf("TEST: Client 0 send their msgbundle\n");
  582. }
  583. #endif
  584. free(send_enc_msgbundle);
  585. if (ecc) {
  586. if(ecc == boost::asio::error::eof) {
  587. delete storage_sock;
  588. storage_sock = nullptr;
  589. } else {
  590. printf("Client: boost async_write failed for sending "
  591. "message bundle\n");
  592. printf("Error %s\n", ecc.message().c_str());
  593. }
  594. return;
  595. }
  596. });
  597. }
  598. int Client::sendIngAuthMessage(unsigned long epoch_no)
  599. {
  600. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) +
  601. SGX_AESGCM_KEY_SIZE;
  602. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  603. unsigned char *am_ptr = auth_message;
  604. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  605. am_ptr+=sizeof(sim_id);
  606. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  607. am_ptr+=sizeof(unsigned long);
  608. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  609. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  610. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  611. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  612. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE,
  613. NULL, 0, ing_key, epoch_iv, SGX_AESGCM_IV_SIZE,
  614. am_ptr, tag)) {
  615. printf("sendIngAuthMessage failed\n");
  616. return -1;
  617. }
  618. #ifdef VERBOSE_CLIENT
  619. printf("Client %d auth_message: \n", id);
  620. for(int i=0; i<auth_size; i++) {
  621. printf("%x", auth_message[i]);
  622. }
  623. printf("\n");
  624. #endif
  625. /*
  626. if(sim_id%7919==0) {
  627. printf("Client %d auth_message: \n", sim_id);
  628. for(int i=0; i<TOKEN_SIZE; i++) {
  629. printf("%x", am_ptr[i]);
  630. }
  631. printf("\n");
  632. }
  633. */
  634. boost::asio::write(*ingestion_sock,
  635. boost::asio::buffer(auth_message, auth_size));
  636. return 1;
  637. }
  638. int Client::sendStgAuthMessage(unsigned long epoch_no)
  639. {
  640. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) +
  641. SGX_AESGCM_KEY_SIZE;
  642. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  643. unsigned char *am_ptr = auth_message;
  644. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  645. am_ptr+=sizeof(sim_id);
  646. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  647. am_ptr+=sizeof(unsigned long);
  648. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  649. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  650. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  651. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  652. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE,
  653. NULL, 0, stg_key, epoch_iv, SGX_AESGCM_IV_SIZE,
  654. am_ptr, tag)) {
  655. printf("sendStgAuthMessage failed\n");
  656. return -1;
  657. }
  658. #ifdef VERBOSE_CLIENT
  659. printf("Client %d auth_message: \n", id);
  660. for(int i=0; i<auth_size; i++) {
  661. printf("%x", auth_message[i]);
  662. }
  663. printf("\n");
  664. #endif
  665. boost::asio::async_write(*storage_sock,
  666. boost::asio::buffer(auth_message, auth_size),
  667. [this, auth_message] (boost::system::error_code ecc, std::size_t) {
  668. free(auth_message);
  669. if (ecc) {
  670. if(ecc == boost::asio::error::eof) {
  671. delete storage_sock;
  672. storage_sock = nullptr;
  673. } else {
  674. printf("Error %s\n", ecc.message().c_str());
  675. }
  676. printf("Client::sendStgAuthMessage boost async_write failed\n");
  677. return;
  678. }
  679. });
  680. return 1;
  681. }
  682. void Client::setup_client(boost::asio::io_context &io_context,
  683. uint32_t sim_id, uint16_t ing_node_id, uint16_t stg_node_id,
  684. ip_addr *curr_ip, uint16_t &port_no)
  685. {
  686. // Set up the client's
  687. // (i) client_id
  688. // (ii) symmetric keys shared with their ingestion and storage server
  689. // (iii) sockets to their ingestion and storage server
  690. aes_key client_ing_key;
  691. aes_key client_stg_key;
  692. int ret = generateClientKeys(sim_id, ESK, client_ing_key, client_stg_key);
  693. initClient(sim_id, stg_node_id, client_ing_key, client_stg_key);
  694. initializeStgSocket(io_context, storage_nodes[stg_node_id], curr_ip, port_no);
  695. port_no++;
  696. initializeIngSocket(io_context, ingestion_nodes[ing_node_id], curr_ip, port_no);
  697. port_no++;
  698. // Authenticate clients to their ingestion and storage servers
  699. struct timespec ep;
  700. clock_gettime(CLOCK_REALTIME_COARSE, &ep);
  701. unsigned long time_in_us = ep.tv_sec * 1000000 + ep.tv_nsec/1000;
  702. unsigned long epoch_no = CEILDIV(time_in_us, 5000000);
  703. sendStgAuthMessage(epoch_no);
  704. sendIngAuthMessage(epoch_no);
  705. epoch_process();
  706. }
  707. void generateClients(boost::asio::io_context &io_context,
  708. uint32_t cstart, uint32_t cstop, uint8_t thread_no)
  709. {
  710. uint32_t num_clients_total = config.user_count;
  711. uint16_t num_stg_nodes = storage_nodes.size();
  712. uint16_t num_ing_nodes = ingestion_nodes.size();
  713. uint16_t port_no = PORT_START;
  714. ip_addr curr_ip;
  715. curr_ip.ip1 = 127;
  716. curr_ip.ip2 = 1 + thread_no;
  717. curr_ip.ip3 = 0;
  718. curr_ip.ip4 = 0;
  719. for(uint32_t i=cstart; i<cstop; i++) {
  720. // Compute client's ip and port
  721. #ifdef CLIENT_UNIQUE_IP
  722. if(port_no>=PORT_END) {
  723. port_no = PORT_START;
  724. }
  725. curr_ip.increment(nthreads);
  726. #else
  727. if(port_no>=PORT_END) {
  728. port_no = PORT_START;
  729. curr_ip.increment(nthreads);
  730. }
  731. #endif
  732. uint16_t ing_no = i % num_ing_nodes;
  733. uint16_t stg_no = i % num_stg_nodes;
  734. uint16_t stg_node_id = storage_map[stg_no];
  735. uint16_t ing_node_id = ingestion_map[ing_no];
  736. clients[i].setup_client(io_context, i, ing_node_id, stg_node_id,
  737. &curr_ip, port_no);
  738. }
  739. printf("Done with all client_setup calls. Thread_no = %d\n", thread_no);
  740. }
  741. /*
  742. Epochs are server driven.
  743. In a single epoch, each client waits to receive from their storage server
  744. (i) a token bundle for this epoch and (ii) their messages from the last epoch
  745. The client then sends their messages for this epoch to their ingestion servers
  746. using the tokens they received in this epoch
  747. */
  748. void Client::epoch_process() {
  749. uint32_t pt_token_size = uint32_t(config.m_priv_out) * SGX_AESGCM_KEY_SIZE;
  750. uint32_t token_bundle_size = pt_token_size + SGX_AESGCM_IV_SIZE
  751. + SGX_AESGCM_MAC_SIZE;
  752. unsigned char *enc_tokens = (unsigned char*) malloc (token_bundle_size);
  753. if(private_routing) {
  754. //Async read the encrypted tokens for this epoch
  755. boost::asio::async_read(*storage_sock, boost::asio::buffer(enc_tokens, token_bundle_size),
  756. [this, enc_tokens, token_bundle_size, pt_token_size]
  757. (boost::system::error_code ec, std::size_t) {
  758. if (ec) {
  759. if(ec == boost::asio::error::eof) {
  760. delete storage_sock;
  761. storage_sock = nullptr;
  762. } else {
  763. printf("Error %s\n", ec.message().c_str());
  764. printf("Client::epoch_process boost "
  765. "async_read_tokens failed\n");
  766. }
  767. free(enc_tokens);
  768. return;
  769. }
  770. #ifdef VERBOSE_CLIENT
  771. if(sim_id == 0) {
  772. printf("TEST: Client 0: Encrypted token bundle received:\n");
  773. for(uint32_t i = 0; i < token_bundle_size; i++) {
  774. printf("%x", enc_tokens[i]);
  775. }
  776. printf("\n");
  777. }
  778. #endif
  779. // Decrypt the token bundle
  780. unsigned char *enc_tkn_ptr = enc_tokens + SGX_AESGCM_IV_SIZE;
  781. unsigned char *enc_tkn_tag = enc_tokens + SGX_AESGCM_IV_SIZE +
  782. pt_token_size;
  783. int decrypted_bytes = gcm_decrypt(enc_tkn_ptr, pt_token_size,
  784. NULL, 0, enc_tkn_tag, (unsigned char*) &(this->stg_key),
  785. enc_tokens, SGX_AESGCM_IV_SIZE,
  786. (unsigned char*) (this->token_list));
  787. if(decrypted_bytes != pt_token_size) {
  788. printf("Client::epoch_process gcm_decrypt tokens failed. "
  789. "decrypted_bytes = %d\n", decrypted_bytes);
  790. }
  791. free(enc_tokens);
  792. /*
  793. unsigned char *tkn_ptr = (unsigned char*) this->token_list;
  794. if(sim_id==0) {
  795. printf("TEST: Client 0: Decrypted client tokens:\n");
  796. for(int i = 0; i < 2 * SGX_AESGCM_KEY_SIZE; i++) {
  797. printf("%x", tkn_ptr[i]);
  798. }
  799. printf("\n");
  800. }
  801. */
  802. // Async read the messages received in the last epoch
  803. uint16_t priv_in = config.m_priv_in;
  804. uint16_t msg_size = config.msg_size;
  805. uint32_t recv_pt_mailbox_size = ptMailboxSize(priv_in, msg_size);
  806. uint32_t recv_enc_mailbox_size = encMailboxSize(priv_in, msg_size);
  807. unsigned char *recv_pt_mailbox =
  808. (unsigned char*) malloc (recv_pt_mailbox_size);
  809. unsigned char *recv_enc_mailbox =
  810. (unsigned char*) malloc (recv_enc_mailbox_size);
  811. boost::asio::async_read(*storage_sock,
  812. boost::asio::buffer(recv_enc_mailbox, recv_enc_mailbox_size),
  813. [this, recv_pt_mailbox, recv_enc_mailbox]
  814. (boost::system::error_code ecc, std::size_t) {
  815. #ifdef TRACE_SOCKIO
  816. recvlogger.log();
  817. #endif
  818. if (ecc) {
  819. if(ecc == boost::asio::error::eof) {
  820. delete storage_sock;
  821. storage_sock = nullptr;
  822. } else {
  823. printf("Client: boost async_read failed for "
  824. "receiving msg_bundle\n");
  825. printf("Error %s\n", ecc.message().c_str());
  826. }
  827. free(recv_pt_mailbox);
  828. free(recv_enc_mailbox);
  829. return;
  830. }
  831. #ifdef VERBOSE_CLIENT
  832. if(sim_id == 0) {
  833. printf("TEST: Client 0: Encrypted msgbundle received\n");
  834. }
  835. #endif
  836. // Do whatever processing with the received messages here
  837. // but for the benchmark, we just ignore the received
  838. // messages
  839. free(recv_enc_mailbox);
  840. free(recv_pt_mailbox);
  841. // Send this epoch's message bundle
  842. sendMessageBundle();
  843. epoch_process();
  844. });
  845. });
  846. } else {
  847. // Async read the messages received in the last epoch
  848. uint16_t pub_in = config.m_pub_in;
  849. uint16_t msg_size = config.msg_size;
  850. uint32_t recv_pt_mailbox_size = ptMailboxSize(pub_in, msg_size);
  851. uint32_t recv_enc_mailbox_size = encMailboxSize(pub_in, msg_size);
  852. unsigned char *recv_pt_mailbox =
  853. (unsigned char*) malloc (recv_pt_mailbox_size);
  854. unsigned char *recv_enc_mailbox =
  855. (unsigned char*) malloc (recv_enc_mailbox_size);
  856. boost::asio::async_read(*storage_sock,
  857. boost::asio::buffer(recv_enc_mailbox, recv_enc_mailbox_size),
  858. [this, recv_pt_mailbox, recv_enc_mailbox]
  859. (boost::system::error_code ecc, std::size_t) {
  860. #ifdef TRACE_SOCKIO
  861. recvlogger.log();
  862. #endif
  863. if (ecc) {
  864. if(ecc == boost::asio::error::eof) {
  865. delete storage_sock;
  866. storage_sock = nullptr;
  867. } else {
  868. printf("Client: boost async_read failed for "
  869. "receiving msg_bundle\n");
  870. printf("Error %s\n", ecc.message().c_str());
  871. }
  872. free(recv_pt_mailbox);
  873. free(recv_enc_mailbox);
  874. return;
  875. }
  876. // Do whatever processing with the received messages here
  877. // but for the benchmark, we just ignore the received
  878. // messages
  879. free(recv_enc_mailbox);
  880. free(recv_pt_mailbox);
  881. // Send this epoch's message bundle
  882. sendMessageBundle();
  883. epoch_process();
  884. });
  885. }
  886. }
  887. void initializeClients(boost::asio::io_context &io_context, uint16_t nthreads)
  888. {
  889. std::vector<boost::thread> threads;
  890. uint32_t num_clients_total = config.user_count;
  891. size_t clients_per_thread = CEILDIV(num_clients_total, nthreads);
  892. // Generate all the clients for the experiment
  893. for(int i=0; i<nthreads; i++) {
  894. uint32_t cstart, cstop;
  895. cstart = i * clients_per_thread;
  896. cstop = (i==(nthreads-1))? num_clients_total: (i+1) * clients_per_thread;
  897. #ifdef VERBOSE_CLIENT
  898. printf("Thread %d, cstart = %d, cstop = %d\n", i, cstart, cstop);
  899. #endif
  900. threads.emplace_back(boost::thread(generateClients,
  901. boost::ref(io_context), cstart, cstop, i));
  902. }
  903. for(int i=0; i<nthreads; i++) {
  904. threads[i].join();
  905. }
  906. }
  907. int main(int argc, char **argv)
  908. {
  909. // Unbuffer stdout
  910. setbuf(stdout, NULL);
  911. const char *progname = argv[0];
  912. ++argv;
  913. // Parse options
  914. while (*argv && (*argv)[0] == '-') {
  915. if (!strcmp(*argv, "-t")) {
  916. if (argv[1] == NULL) {
  917. usage(progname);
  918. }
  919. nthreads = uint16_t(atoi(argv[1]));
  920. argv += 2;
  921. } else {
  922. usage(progname);
  923. }
  924. }
  925. // Read the config.json from the first line of stdin. We have to do
  926. // this before outputting anything to avoid potential deadlock with
  927. // the launch program.
  928. std::string configstr;
  929. std::getline(std::cin, configstr);
  930. boost::asio::io_context io_context;
  931. if (!config_parse(config, configstr, ingestion_nodes,
  932. storage_nodes, storage_map)) {
  933. exit(1);
  934. }
  935. private_routing = config.private_routing;
  936. clients = new Client[config.user_count];
  937. #ifdef VERBOSE_CLIENT
  938. printf("Number of ingestion_nodes = %ld, Number of storage_node = %ld\n",
  939. ingestion_nodes.size(), storage_nodes.size());
  940. #endif
  941. generateMasterKeys(config.master_secret, ESK, TSK);
  942. // Queue up the actual work
  943. boost::asio::post(io_context, [&]{
  944. initializeClients(io_context, nthreads);
  945. });
  946. // Start background threads; one thread will perform the work and the
  947. // others will execute the async_write/async_read handlers
  948. std::vector<boost::thread> threads;
  949. for (int i=0; i<nthreads; i++) {
  950. threads.emplace_back([&]{io_context.run();});
  951. }
  952. io_context.run();
  953. for (int i=0; i<nthreads; i++) {
  954. threads[i].join();
  955. }
  956. delete [] clients;
  957. }