clients.cpp 34 KB

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