clients.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. num_out is either priv_out or pub_out, depending on whether we're
  462. doing private or public routing
  463. Correct length for pt_msgbundle = (num_out)*(msg_size) +
  464. (only for private routing) (num_out)*TOKEN_SIZE
  465. */
  466. void Client::generateMessageBundle(uint8_t num_out, uint32_t msg_size,
  467. unsigned char *pt_msgbundle)
  468. {
  469. unsigned char *ptr = pt_msgbundle;
  470. // Setup message pt_msgbundle
  471. for(uint32_t i = 0; i < num_out; i++) {
  472. // For benchmarking, each client just sends messages to
  473. // themselves, so the destination and source ids are the same.
  474. // Destination id
  475. unsigned char *start_ptr = ptr;
  476. memcpy(ptr, &id, sizeof(id));
  477. ptr+=(sizeof(id));
  478. // Priority (for public routing only)
  479. if (!private_routing) {
  480. memset(ptr, 0, sizeof(uint32_t));
  481. ptr+=sizeof(uint32_t);
  482. }
  483. // Source id
  484. memcpy(ptr, &id, sizeof(id));
  485. ptr+=(sizeof(id));
  486. uint32_t remaining_message_size = start_ptr + msg_size - ptr;
  487. memset(ptr, 0, remaining_message_size);
  488. ptr+=(remaining_message_size);
  489. }
  490. if(private_routing) {
  491. // Add the tokens for this msgbundle
  492. memcpy(ptr, token_list, config.m_priv_out * TOKEN_SIZE);
  493. }
  494. }
  495. bool Client::encryptMessageBundle(uint32_t enc_bundle_size,
  496. unsigned char *pt_msgbundle, unsigned char *enc_msgbundle)
  497. {
  498. // Encrypt the pt_msgbundle
  499. unsigned char *pt_msgbundle_start = pt_msgbundle;
  500. unsigned char *enc_msgbundle_start = enc_msgbundle + SGX_AESGCM_IV_SIZE;
  501. unsigned char *enc_tag = enc_msgbundle + enc_bundle_size - SGX_AESGCM_MAC_SIZE;
  502. size_t bytes_to_encrypt = enc_bundle_size - SGX_AESGCM_MAC_SIZE -
  503. SGX_AESGCM_IV_SIZE;
  504. if (bytes_to_encrypt != gcm_encrypt(pt_msgbundle_start, bytes_to_encrypt,
  505. NULL, 0, ing_key, ing_iv, SGX_AESGCM_IV_SIZE, enc_msgbundle_start,
  506. enc_tag)) {
  507. printf("Client: encryptMessageBundle FAIL\n");
  508. return 0;
  509. }
  510. // Copy IV into the bundle
  511. memcpy(enc_msgbundle, ing_iv, SGX_AESGCM_IV_SIZE);
  512. // Update IV
  513. uint64_t *iv_ctr = (uint64_t*) ing_iv;
  514. (*iv_ctr)+=1;
  515. return 1;
  516. }
  517. #ifdef TRACE_SOCKIO
  518. class LimitLogger {
  519. std::string label;
  520. std::string thrid;
  521. struct timeval last_log;
  522. size_t num_items;
  523. public:
  524. LimitLogger(const char *_label): label(_label), last_log({0,0}),
  525. num_items(0) {
  526. std::stringstream ss;
  527. ss << boost::this_thread::get_id();
  528. thrid = ss.str();
  529. }
  530. void log() {
  531. struct timeval now;
  532. gettimeofday(&now, NULL);
  533. long elapsedus = (now.tv_sec - last_log.tv_sec) * 1000000
  534. + (now.tv_usec - last_log.tv_usec);
  535. if (num_items > 0 && elapsedus > 500000) {
  536. printf("%lu.%06lu: Thread %s end %s of %lu items\n",
  537. last_log.tv_sec, last_log.tv_usec,
  538. thrid.c_str(), label.c_str(),
  539. num_items);
  540. num_items = 0;
  541. }
  542. if (num_items == 0) {
  543. printf("%lu.%06lu: Thread %s begin %s\n", now.tv_sec,
  544. now.tv_usec, thrid.c_str(), label.c_str());
  545. }
  546. gettimeofday(&last_log, NULL);
  547. ++num_items;
  548. }
  549. };
  550. static thread_local LimitLogger
  551. recvlogger("recv"), queuelogger("queue"), sentlogger("sent");
  552. #endif
  553. void Client::sendMessageBundle()
  554. {
  555. uint16_t priv_out = config.m_priv_out;
  556. uint16_t pub_out = config.m_pub_out;
  557. uint16_t msg_size = config.msg_size;
  558. uint32_t send_pt_msgbundle_size, send_enc_msgbundle_size;
  559. if(private_routing) {
  560. send_pt_msgbundle_size = ptMsgBundleSize(priv_out, msg_size);
  561. send_enc_msgbundle_size = encMsgBundleSize(priv_out, msg_size);
  562. } else {
  563. send_pt_msgbundle_size = ptPubMsgBundleSize(pub_out, msg_size);
  564. send_enc_msgbundle_size = encPubMsgBundleSize(pub_out, msg_size);
  565. }
  566. unsigned char *send_pt_msgbundle =
  567. (unsigned char*) malloc (send_pt_msgbundle_size);
  568. unsigned char *send_enc_msgbundle =
  569. (unsigned char*) malloc (send_enc_msgbundle_size);
  570. if(private_routing) {
  571. generateMessageBundle(priv_out, msg_size, send_pt_msgbundle);
  572. } else {
  573. generateMessageBundle(pub_out, msg_size, send_pt_msgbundle);
  574. }
  575. encryptMessageBundle(send_enc_msgbundle_size, send_pt_msgbundle,
  576. send_enc_msgbundle);
  577. #ifdef VERBOSE_CLIENT
  578. displayPtMessageBundle(send_pt_msgbundle, priv_out, msg_size);
  579. #endif
  580. free(send_pt_msgbundle);
  581. #ifdef TRACE_SOCKIO
  582. queuelogger.log();
  583. #endif
  584. boost::asio::async_write(*ingestion_sock,
  585. boost::asio::buffer(send_enc_msgbundle, send_enc_msgbundle_size),
  586. [this, send_enc_msgbundle] (boost::system::error_code ecc, std::size_t) {
  587. #ifdef TRACE_SOCKIO
  588. sentlogger.log();
  589. #endif
  590. #ifdef VERBOSE_CLIENT
  591. if(sim_id==0){
  592. printf("TEST: Client 0 send their msgbundle\n");
  593. }
  594. #endif
  595. free(send_enc_msgbundle);
  596. if (ecc) {
  597. if(ecc == boost::asio::error::eof) {
  598. delete storage_sock;
  599. storage_sock = nullptr;
  600. } else {
  601. printf("Client: boost async_write failed for sending "
  602. "message bundle\n");
  603. printf("Error %s\n", ecc.message().c_str());
  604. }
  605. return;
  606. }
  607. });
  608. }
  609. int Client::sendIngAuthMessage(unsigned long epoch_no)
  610. {
  611. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) +
  612. SGX_AESGCM_KEY_SIZE;
  613. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  614. unsigned char *am_ptr = auth_message;
  615. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  616. am_ptr+=sizeof(sim_id);
  617. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  618. am_ptr+=sizeof(unsigned long);
  619. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  620. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  621. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  622. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  623. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE,
  624. NULL, 0, ing_key, epoch_iv, SGX_AESGCM_IV_SIZE,
  625. am_ptr, tag)) {
  626. printf("sendIngAuthMessage failed\n");
  627. return -1;
  628. }
  629. #ifdef VERBOSE_CLIENT
  630. printf("Client %d auth_message: \n", id);
  631. for(int i=0; i<auth_size; i++) {
  632. printf("%x", auth_message[i]);
  633. }
  634. printf("\n");
  635. #endif
  636. /*
  637. if(sim_id%7919==0) {
  638. printf("Client %d auth_message: \n", sim_id);
  639. for(int i=0; i<TOKEN_SIZE; i++) {
  640. printf("%x", am_ptr[i]);
  641. }
  642. printf("\n");
  643. }
  644. */
  645. boost::asio::write(*ingestion_sock,
  646. boost::asio::buffer(auth_message, auth_size));
  647. return 1;
  648. }
  649. int Client::sendStgAuthMessage(unsigned long epoch_no)
  650. {
  651. uint32_t auth_size = sizeof(clientid_t) + sizeof(unsigned long) +
  652. SGX_AESGCM_KEY_SIZE;
  653. unsigned char *auth_message = (unsigned char*) malloc(auth_size);
  654. unsigned char *am_ptr = auth_message;
  655. memcpy(am_ptr, &sim_id, sizeof(sim_id));
  656. am_ptr+=sizeof(sim_id);
  657. memcpy(am_ptr, &epoch_no, sizeof(unsigned long));
  658. am_ptr+=sizeof(unsigned long);
  659. unsigned char zeroes[SGX_AESGCM_KEY_SIZE] = {0};
  660. unsigned char tag[SGX_AESGCM_MAC_SIZE] = {0};
  661. unsigned char epoch_iv[SGX_AESGCM_IV_SIZE] = {0};
  662. memcpy(epoch_iv, &epoch_no, sizeof(epoch_no));
  663. if (sizeof(zeroes) != gcm_encrypt(zeroes, SGX_AESGCM_KEY_SIZE,
  664. NULL, 0, stg_key, epoch_iv, SGX_AESGCM_IV_SIZE,
  665. am_ptr, tag)) {
  666. printf("sendStgAuthMessage failed\n");
  667. return -1;
  668. }
  669. #ifdef VERBOSE_CLIENT
  670. printf("Client %d auth_message: \n", id);
  671. for(int i=0; i<auth_size; i++) {
  672. printf("%x", auth_message[i]);
  673. }
  674. printf("\n");
  675. #endif
  676. boost::asio::async_write(*storage_sock,
  677. boost::asio::buffer(auth_message, auth_size),
  678. [this, auth_message] (boost::system::error_code ecc, std::size_t) {
  679. free(auth_message);
  680. if (ecc) {
  681. if(ecc == boost::asio::error::eof) {
  682. delete storage_sock;
  683. storage_sock = nullptr;
  684. } else {
  685. printf("Error %s\n", ecc.message().c_str());
  686. }
  687. printf("Client::sendStgAuthMessage boost async_write failed\n");
  688. return;
  689. }
  690. });
  691. return 1;
  692. }
  693. void Client::setup_client(boost::asio::io_context &io_context,
  694. uint32_t sim_id, uint16_t ing_node_id, uint16_t stg_node_id,
  695. ip_addr *curr_ip, uint16_t &port_no)
  696. {
  697. // Set up the client's
  698. // (i) client_id
  699. // (ii) symmetric keys shared with their ingestion and storage server
  700. // (iii) sockets to their ingestion and storage server
  701. aes_key client_ing_key;
  702. aes_key client_stg_key;
  703. int ret = generateClientKeys(sim_id, ESK, client_ing_key, client_stg_key);
  704. initClient(sim_id, stg_node_id, client_ing_key, client_stg_key);
  705. initializeStgSocket(io_context, storage_nodes[stg_node_id], curr_ip, port_no);
  706. port_no++;
  707. initializeIngSocket(io_context, ingestion_nodes[ing_node_id], curr_ip, port_no);
  708. port_no++;
  709. // Authenticate clients to their ingestion and storage servers
  710. struct timespec ep;
  711. clock_gettime(CLOCK_REALTIME_COARSE, &ep);
  712. unsigned long time_in_us = ep.tv_sec * 1000000 + ep.tv_nsec/1000;
  713. unsigned long epoch_no = CEILDIV(time_in_us, 5000000);
  714. sendStgAuthMessage(epoch_no);
  715. sendIngAuthMessage(epoch_no);
  716. epoch_process();
  717. }
  718. void generateClients(boost::asio::io_context &io_context,
  719. uint32_t cstart, uint32_t cstop, uint8_t thread_no)
  720. {
  721. uint32_t num_clients_total = config.user_count;
  722. uint16_t num_stg_nodes = storage_nodes.size();
  723. uint16_t num_ing_nodes = ingestion_nodes.size();
  724. uint16_t port_no = PORT_START;
  725. ip_addr curr_ip;
  726. curr_ip.ip1 = 127;
  727. curr_ip.ip2 = 1 + thread_no;
  728. curr_ip.ip3 = 0;
  729. curr_ip.ip4 = 0;
  730. for(uint32_t i=cstart; i<cstop; i++) {
  731. // Compute client's ip and port
  732. #ifdef CLIENT_UNIQUE_IP
  733. if(port_no>=PORT_END) {
  734. port_no = PORT_START;
  735. }
  736. curr_ip.increment(nthreads);
  737. #else
  738. if(port_no>=PORT_END) {
  739. port_no = PORT_START;
  740. curr_ip.increment(nthreads);
  741. }
  742. #endif
  743. uint16_t ing_no = i % num_ing_nodes;
  744. uint16_t stg_no = i % num_stg_nodes;
  745. uint16_t stg_node_id = storage_map[stg_no];
  746. uint16_t ing_node_id = ingestion_map[ing_no];
  747. clients[i].setup_client(io_context, i, ing_node_id, stg_node_id,
  748. &curr_ip, port_no);
  749. }
  750. printf("Done with all client_setup calls. Thread_no = %d\n", thread_no);
  751. }
  752. /*
  753. Epochs are server driven.
  754. In a single epoch, each client waits to receive from their storage server
  755. (i) a token bundle for this epoch and (ii) their messages from the last epoch
  756. The client then sends their messages for this epoch to their ingestion servers
  757. using the tokens they received in this epoch
  758. */
  759. void Client::epoch_process() {
  760. uint32_t pt_token_size = uint32_t(config.m_priv_out) * TOKEN_SIZE;
  761. uint32_t token_bundle_size = pt_token_size + SGX_AESGCM_IV_SIZE
  762. + SGX_AESGCM_MAC_SIZE;
  763. unsigned char *enc_tokens = nullptr;
  764. uint16_t num_in = config.m_pub_in;
  765. std::vector<boost::asio::mutable_buffer> toreceive;
  766. if (private_routing) {
  767. enc_tokens = (unsigned char*) malloc (token_bundle_size);
  768. toreceive.push_back(boost::asio::buffer(enc_tokens,
  769. token_bundle_size));
  770. num_in = config.m_priv_in;
  771. }
  772. uint16_t msg_size = config.msg_size;
  773. uint32_t recv_pt_mailbox_size = ptMailboxSize(num_in, msg_size);
  774. uint32_t recv_enc_mailbox_size = encMailboxSize(num_in, msg_size);
  775. unsigned char *recv_pt_mailbox =
  776. (unsigned char*) malloc (recv_pt_mailbox_size);
  777. unsigned char *recv_enc_mailbox =
  778. (unsigned char*) malloc (recv_enc_mailbox_size);
  779. toreceive.push_back(boost::asio::buffer(recv_enc_mailbox,
  780. recv_enc_mailbox_size));
  781. // Async read the encrypted tokens (for private routing only) and
  782. // encrypted mailbox (both private and public routing) for this
  783. // epoch
  784. boost::asio::async_read(*storage_sock, toreceive,
  785. [this, enc_tokens, token_bundle_size, pt_token_size,
  786. recv_pt_mailbox, recv_enc_mailbox]
  787. (boost::system::error_code ec, std::size_t) {
  788. if (ec) {
  789. if(ec == boost::asio::error::eof) {
  790. delete storage_sock;
  791. storage_sock = nullptr;
  792. } else {
  793. printf("Error %s\n", ec.message().c_str());
  794. printf("Client::epoch_process boost "
  795. "async_read_tokens failed\n");
  796. }
  797. free(enc_tokens);
  798. free(recv_pt_mailbox);
  799. free(recv_enc_mailbox);
  800. return;
  801. }
  802. #ifdef TRACE_SOCKIO
  803. recvlogger.log();
  804. #endif
  805. #ifdef VERBOSE_CLIENT
  806. if(sim_id == 0) {
  807. printf("TEST: Client 0: Encrypted token bundle received:\n");
  808. for(uint32_t i = 0; i < token_bundle_size; i++) {
  809. printf("%02x", enc_tokens[i]);
  810. }
  811. printf("\n");
  812. printf("TEST: Client 0: Encrypted msgbundle received\n");
  813. }
  814. #endif
  815. if (private_routing) {
  816. // Decrypt the token bundle
  817. unsigned char *enc_tkn_ptr = enc_tokens + SGX_AESGCM_IV_SIZE;
  818. unsigned char *enc_tkn_tag = enc_tokens + SGX_AESGCM_IV_SIZE +
  819. pt_token_size;
  820. int decrypted_bytes = gcm_decrypt(enc_tkn_ptr, pt_token_size,
  821. NULL, 0, enc_tkn_tag, (unsigned char*) &(this->stg_key),
  822. enc_tokens, SGX_AESGCM_IV_SIZE,
  823. (unsigned char*) (this->token_list));
  824. if(decrypted_bytes != pt_token_size) {
  825. printf("Client::epoch_process gcm_decrypt tokens failed. "
  826. "decrypted_bytes = %d\n", decrypted_bytes);
  827. }
  828. free(enc_tokens);
  829. /*
  830. unsigned char *tkn_ptr = (unsigned char*) this->token_list;
  831. if(sim_id==0) {
  832. printf("TEST: Client 0: Decrypted client tokens:\n");
  833. for(int i = 0; i < pt_token_size; i++) {
  834. printf("%02x", tkn_ptr[i]);
  835. }
  836. printf("\n");
  837. }
  838. */
  839. }
  840. // Do whatever processing with the received messages here
  841. // but for the benchmark, we just ignore the received
  842. // messages
  843. free(recv_enc_mailbox);
  844. free(recv_pt_mailbox);
  845. // Send this epoch's message bundle
  846. sendMessageBundle();
  847. epoch_process();
  848. });
  849. }
  850. void initializeClients(boost::asio::io_context &io_context, uint16_t nthreads)
  851. {
  852. std::vector<boost::thread> threads;
  853. uint32_t num_clients_total = config.user_count;
  854. size_t clients_per_thread = CEILDIV(num_clients_total, nthreads);
  855. // Generate all the clients for the experiment
  856. for(int i=0; i<nthreads; i++) {
  857. uint32_t cstart, cstop;
  858. cstart = i * clients_per_thread;
  859. cstop = (i==(nthreads-1))? num_clients_total: (i+1) * clients_per_thread;
  860. #ifdef VERBOSE_CLIENT
  861. printf("Thread %d, cstart = %d, cstop = %d\n", i, cstart, cstop);
  862. #endif
  863. threads.emplace_back(boost::thread(generateClients,
  864. boost::ref(io_context), cstart, cstop, i));
  865. }
  866. for(int i=0; i<nthreads; i++) {
  867. threads[i].join();
  868. }
  869. }
  870. int main(int argc, char **argv)
  871. {
  872. // Unbuffer stdout
  873. setbuf(stdout, NULL);
  874. const char *progname = argv[0];
  875. ++argv;
  876. // Parse options
  877. while (*argv && (*argv)[0] == '-') {
  878. if (!strcmp(*argv, "-t")) {
  879. if (argv[1] == NULL) {
  880. usage(progname);
  881. }
  882. nthreads = uint16_t(atoi(argv[1]));
  883. argv += 2;
  884. } else {
  885. usage(progname);
  886. }
  887. }
  888. // Read the config.json from the first line of stdin. We have to do
  889. // this before outputting anything to avoid potential deadlock with
  890. // the launch program.
  891. std::string configstr;
  892. std::getline(std::cin, configstr);
  893. boost::asio::io_context io_context;
  894. if (!config_parse(config, configstr, ingestion_nodes,
  895. storage_nodes, storage_map)) {
  896. exit(1);
  897. }
  898. private_routing = config.private_routing;
  899. clients = new Client[config.user_count];
  900. #ifdef VERBOSE_CLIENT
  901. printf("Number of ingestion_nodes = %ld, Number of storage_node = %ld\n",
  902. ingestion_nodes.size(), storage_nodes.size());
  903. #endif
  904. generateMasterKeys(config.master_secret, ESK, TSK);
  905. // Queue up the actual work
  906. boost::asio::post(io_context, [&]{
  907. initializeClients(io_context, nthreads);
  908. });
  909. // Start background threads; one thread will perform the work and the
  910. // others will execute the async_write/async_read handlers
  911. std::vector<boost::thread> threads;
  912. for (int i=0; i<nthreads; i++) {
  913. threads.emplace_back([&]{io_context.run();});
  914. }
  915. io_context.run();
  916. for (int i=0; i<nthreads; i++) {
  917. threads[i].join();
  918. }
  919. delete [] clients;
  920. }