net.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. #include <iostream>
  2. #include "Enclave_u.h"
  3. #include "Untrusted.hpp"
  4. #include "net.hpp"
  5. // The command type byte values
  6. #define COMMAND_EPOCH 0x00
  7. #define COMMAND_MESSAGE 0x01
  8. #define COMMAND_CHUNK 0x02
  9. #define VERBOSE_NET
  10. // #define DEBUG_NET_CLIENTS
  11. #define CEILDIV(x,y) (((x)+(y)-1)/(y))
  12. NetIO *g_netio = NULL;
  13. size_t client_count = 0;
  14. NodeIO::NodeIO(tcp::socket &&socket, nodenum_t nodenum) :
  15. sock(std::move(socket)), node_num(nodenum), msgsize_inflight(0),
  16. chunksize_inflight(0), recv_msgsize_inflight(0),
  17. recv_chunksize_inflight(0)
  18. {
  19. }
  20. uint8_t *NodeIO::request_frame()
  21. {
  22. if (frames_available.empty()) {
  23. // Allocate a new frame. Note that this memory will (at this
  24. // time) never get deallocated. In theory, we could deallocate
  25. // it in return_frame, but if a certain number of frames were
  26. // allocated here, it means we had that much data in flight
  27. // (queued but not accepted for sending by the OS), and we're
  28. // likely to need that much again. Subsequent messages will
  29. // _reuse_ the allocated data, though, so the used memory won't
  30. // grow forever, and will be limited to the amount of in-flight
  31. // data needed.
  32. return new uint8_t[FRAME_SIZE];
  33. }
  34. // Copy the pointer to the frame out of the deque and remove it from
  35. // the deque. Note this is _not_ taking the address of the element
  36. // *in* the deque (and then popping it, which would invalidate that
  37. // pointer).
  38. frame_deque_lock.lock();
  39. uint8_t *frame = frames_available.back();
  40. frames_available.pop_back();
  41. frame_deque_lock.unlock();
  42. return frame;
  43. }
  44. void NodeIO::return_frame(uint8_t *frame)
  45. {
  46. if (!frame) return;
  47. // We push the frame back on to the end of the deque so that it will
  48. // be the next one used. This may lead to better cache behaviour?
  49. frame_deque_lock.lock();
  50. frames_available.push_back(frame);
  51. frame_deque_lock.unlock();
  52. }
  53. void NodeIO::send_header_data(uint64_t header, uint8_t *data, size_t len)
  54. {
  55. commands_deque_lock.lock();
  56. commands_inflight.push_back({header, data, len});
  57. if (commands_inflight.size() == 1) {
  58. async_send_commands();
  59. }
  60. commands_deque_lock.unlock();
  61. }
  62. void NodeIO::async_send_commands()
  63. {
  64. std::vector<boost::asio::const_buffer> tosend;
  65. CommandTuple *commandp = &(commands_inflight.front());
  66. tosend.push_back(boost::asio::buffer(&(std::get<0>(*commandp)), 5));
  67. if (std::get<1>(*commandp) != NULL && std::get<2>(*commandp) > 0) {
  68. tosend.push_back(boost::asio::buffer(std::get<1>(*commandp),
  69. std::get<2>(*commandp)));
  70. }
  71. boost::asio::async_write(sock, tosend,
  72. [this, commandp](boost::system::error_code, std::size_t){
  73. // When the write completes, pop the command from the deque
  74. // (which should now be in the front)
  75. commands_deque_lock.lock();
  76. assert(!commands_inflight.empty() &&
  77. &(commands_inflight.front()) == commandp);
  78. uint8_t *data = std::get<1>(*commandp);
  79. commands_inflight.pop_front();
  80. if (commands_inflight.size() > 0) {
  81. async_send_commands();
  82. }
  83. // And return the frame
  84. return_frame(data);
  85. commands_deque_lock.unlock();
  86. });
  87. }
  88. void NodeIO::send_epoch(uint32_t epoch_num)
  89. {
  90. uint64_t header = (uint64_t(epoch_num) << 8) + COMMAND_EPOCH;
  91. send_header_data(header, NULL, 0);
  92. }
  93. void NodeIO::send_message_header(uint32_t tot_message_len)
  94. {
  95. uint64_t header = (uint64_t(tot_message_len) << 8) + COMMAND_MESSAGE;
  96. send_header_data(header, NULL, 0);
  97. // If we're sending a new message header, we have to have finished
  98. // sending the previous message.
  99. assert(chunksize_inflight == msgsize_inflight);
  100. msgsize_inflight = tot_message_len;
  101. chunksize_inflight = 0;
  102. }
  103. bool NodeIO::send_chunk(uint8_t *data, uint32_t chunk_len)
  104. {
  105. assert(chunk_len <= FRAME_SIZE);
  106. uint64_t header = (uint64_t(chunk_len) << 8) + COMMAND_CHUNK;
  107. send_header_data(header, data, chunk_len);
  108. chunksize_inflight += chunk_len;
  109. assert(chunksize_inflight <= msgsize_inflight);
  110. return (chunksize_inflight < msgsize_inflight);
  111. }
  112. void NodeIO::recv_commands(
  113. std::function<void(boost::system::error_code)> error_cb,
  114. std::function<void(uint32_t)> epoch_cb)
  115. {
  116. // Asynchronously read the header
  117. receive_header = 0;
  118. boost::asio::async_read(sock, boost::asio::buffer(&receive_header, 5),
  119. [this, error_cb, epoch_cb]
  120. (boost::system::error_code ec, std::size_t) {
  121. if (ec) {
  122. error_cb(ec);
  123. return;
  124. }
  125. if ((receive_header & 0xff) == COMMAND_EPOCH) {
  126. epoch_cb(uint32_t(receive_header >> 8));
  127. recv_commands(error_cb, epoch_cb);
  128. } else if ((receive_header & 0xff) == COMMAND_MESSAGE) {
  129. assert(recv_msgsize_inflight == recv_chunksize_inflight);
  130. recv_msgsize_inflight = uint32_t(receive_header >> 8);
  131. recv_chunksize_inflight = 0;
  132. if (ecall_message(node_num, recv_msgsize_inflight)) {
  133. recv_commands(error_cb, epoch_cb);
  134. } else {
  135. printf("ecall_message failed\n");
  136. }
  137. } else if ((receive_header & 0xff) == COMMAND_CHUNK) {
  138. uint32_t this_chunk_size = uint32_t(receive_header >> 8);
  139. assert(recv_chunksize_inflight + this_chunk_size <=
  140. recv_msgsize_inflight);
  141. recv_chunksize_inflight += this_chunk_size;
  142. boost::asio::async_read(sock, boost::asio::buffer(
  143. receive_frame, this_chunk_size),
  144. [this, error_cb, epoch_cb, this_chunk_size]
  145. (boost::system::error_code ecc, std::size_t) {
  146. if (ecc) {
  147. error_cb(ecc);
  148. return;
  149. }
  150. if (ecall_chunk(node_num, receive_frame,
  151. this_chunk_size)) {
  152. recv_commands(error_cb, epoch_cb);
  153. } else {
  154. printf("ecall_chunk failed\n");
  155. }
  156. });
  157. } else {
  158. error_cb(boost::system::errc::make_error_code(
  159. boost::system::errc::errc_t::invalid_argument));
  160. }
  161. });
  162. }
  163. /*
  164. Receive clients dropped off messages, i.e. a CLIENT_MESSAGE_BUNDLE
  165. */
  166. void NetIO::ing_receive_msgbundle(tcp::socket* csocket, clientid_t c_simid)
  167. {
  168. unsigned char *msgbundle = (unsigned char*) malloc(msgbundle_size);
  169. boost::asio::async_read(*csocket, boost::asio::buffer(msgbundle, msgbundle_size),
  170. [this, csocket, msgbundle, c_simid]
  171. (boost::system::error_code ec, std::size_t) {
  172. if (ec) {
  173. if(ec == boost::asio::error::eof) {
  174. // Client connection terminated so we delete this socket
  175. delete(csocket);
  176. }
  177. else {
  178. printf("Error ing_receive_msgbundle : %s\n", ec.message().c_str());
  179. }
  180. return;
  181. }
  182. //Ingest the message_bundle
  183. bool ret = ecall_ingest_msgbundle(c_simid, msgbundle, conf.m_priv_out);
  184. free(msgbundle);
  185. // Continue to async receive client message bundles
  186. ing_receive_msgbundle(csocket, c_simid);
  187. });
  188. }
  189. /*
  190. Handle new client connections.
  191. New clients always send an authentication message.
  192. For ingestion this is then followed by their msg_bundles every epoch.
  193. */
  194. void NetIO::ing_authenticate_new_client(tcp::socket* csocket,
  195. const boost::system::error_code& error)
  196. {
  197. if(error) {
  198. printf("Accept handler failed\n");
  199. return;
  200. }
  201. #ifdef DEBUG_NET_CLIENTS
  202. printf("Accept handler success\n");
  203. #endif
  204. unsigned char* auth_message = (unsigned char*) malloc(auth_size);
  205. boost::asio::async_read(*csocket, boost::asio::buffer(auth_message, auth_size),
  206. [this, csocket, auth_message]
  207. (boost::system::error_code ec, std::size_t) {
  208. if (ec) {
  209. if(ec == boost::asio::error::eof) {
  210. // Client connection terminated so we delete this socket
  211. delete(csocket);
  212. } else {
  213. printf("Error ing_auth_new_client : %s\n", ec.message().c_str());
  214. }
  215. return;
  216. }
  217. else {
  218. clientid_t c_simid = *((clientid_t *)(auth_message));
  219. // Read the authentication token
  220. unsigned char *auth_ptr = auth_message + sizeof(clientid_t);
  221. bool ret = ecall_authenticate(c_simid, auth_ptr);
  222. free(auth_message);
  223. // Receive client message bundles on this socket
  224. // for client sim_id c_simid
  225. if(ret) {
  226. client_count++;
  227. ing_receive_msgbundle(csocket, c_simid);
  228. } else{
  229. printf("Client <-> Ingestion authentication failed\n");
  230. delete(csocket);
  231. }
  232. }
  233. });
  234. ing_start_accept();
  235. }
  236. /*
  237. Handle new client connections.
  238. New clients always send an authentication message.
  239. For storage this is then followed by the storage servers sending them
  240. their mailbox every epoch.
  241. */
  242. void NetIO::stg_authenticate_new_client(tcp::socket* csocket,
  243. const boost::system::error_code& error)
  244. {
  245. if(error) {
  246. printf("Accept handler failed\n");
  247. return;
  248. }
  249. #ifdef DEBUG_NET_CLIENTS
  250. printf("Accept handler success\n");
  251. #endif
  252. unsigned char* auth_message = (unsigned char*) malloc(auth_size);
  253. boost::asio::async_read(*csocket, boost::asio::buffer(auth_message, auth_size),
  254. [this, csocket, auth_message]
  255. (boost::system::error_code ec, std::size_t) {
  256. if (ec) {
  257. if(ec == boost::asio::error::eof) {
  258. // Client connection terminated so we delete this socket
  259. delete(csocket);
  260. } else {
  261. printf("Error stg_auth_new_client: %s\n", ec.message().c_str());
  262. }
  263. return;
  264. }
  265. else {
  266. clientid_t c_simid = *((clientid_t *)(auth_message));
  267. // Read the authentication token
  268. unsigned char *auth_ptr = auth_message + sizeof(clientid_t);
  269. bool ret = ecall_storage_authenticate(c_simid, auth_ptr);
  270. free(auth_message);
  271. // If the auth is successful, store this socket into
  272. // a client socket array at the local_c_simid index
  273. // for storage servers to send clients their mailbox periodically.
  274. if(ret) {
  275. uint32_t lcid = c_simid / num_stg_nodes;
  276. client_sockets[lcid] = csocket;
  277. }
  278. else{
  279. printf("Client <-> Storage authentication failed\n");
  280. delete (csocket);
  281. }
  282. }
  283. });
  284. stg_start_accept();
  285. }
  286. /*
  287. Asynchronously accept new client connections
  288. */
  289. void NetIO::ing_start_accept()
  290. {
  291. tcp::socket *csocket = new tcp::socket(io_context());
  292. #ifdef DEBUG_NET_CLIENTS
  293. std::cout << "Accepting on " << myconf.clistenhost << ":" << myconf.clistenport << "\n";
  294. #endif
  295. ingestion_acceptor->async_accept(*csocket,
  296. boost::bind(&NetIO::ing_authenticate_new_client, this, csocket,
  297. boost::asio::placeholders::error));
  298. }
  299. void NetIO::stg_start_accept()
  300. {
  301. tcp::socket *csocket = new tcp::socket(io_context());
  302. #ifdef DEBUG_NET_CLIENTS
  303. std::cout << "Accepting on " << myconf.slistenhost << ":" << myconf.slistenport << "\n";
  304. #endif
  305. storage_acceptor->async_accept(*csocket,
  306. boost::bind(&NetIO::stg_authenticate_new_client, this, csocket,
  307. boost::asio::placeholders::error));
  308. }
  309. void NetIO::send_client_mailbox()
  310. {
  311. // Send each client their tokens for the next epoch
  312. for(uint32_t lcid = 0; lcid < num_clients_per_stg; lcid++)
  313. {
  314. unsigned char *tkn_ptr = epoch_tokens + lcid * token_bundle_size;
  315. unsigned char *buf_ptr = epoch_mailboxes + lcid * mailbox_size;
  316. if(client_sockets[lcid]!=nullptr) {
  317. boost::asio::async_write(*(client_sockets[lcid]),
  318. boost::asio::buffer(tkn_ptr, token_bundle_size),
  319. [this, lcid, buf_ptr](boost::system::error_code ec, std::size_t){
  320. if (ec) {
  321. if(ec == boost::asio::error::eof) {
  322. // Client connection terminated so we delete this socket
  323. delete(client_sockets[lcid]);
  324. printf("Client socket terminated!\n");
  325. } else {
  326. printf("Error send_client_mailbox tokens: %s\n", ec.message().c_str());
  327. }
  328. return;
  329. }
  330. boost::asio::async_write(*(client_sockets[lcid]),
  331. boost::asio::buffer(buf_ptr, mailbox_size),
  332. [this, lcid](boost::system::error_code ecc, std::size_t){
  333. //printf("NetIO::send_client_mailbox, Client %d messages was sent\n", lcid);
  334. if (ecc) {
  335. if(ecc == boost::asio::error::eof) {
  336. // Client connection terminated so we delete this socket
  337. delete(client_sockets[lcid]);
  338. printf("Client socket terminated!\n");
  339. } else {
  340. printf("Error send_client_mailbox mailbox (lcid = %d): %s\n",
  341. lcid, ecc.message().c_str());
  342. }
  343. return;
  344. }
  345. });
  346. });
  347. }
  348. /*
  349. else {
  350. printf("Client did not have a socket!\n");
  351. }
  352. */
  353. }
  354. }
  355. NetIO::NetIO(boost::asio::io_context &io_context, const Config &config)
  356. : context(io_context), conf(config),
  357. myconf(config.nodes[config.my_node_num])
  358. {
  359. num_nodes = nodenum_t(conf.nodes.size());
  360. nodeios.resize(num_nodes);
  361. me = conf.my_node_num;
  362. // Node number n will accept connections from nodes 0, ..., n-1 and
  363. // make connections to nodes n+1, ..., num_nodes-1. This is all
  364. // single threaded, but it doesn't deadlock because node 0 isn't
  365. // waiting for any incoming connections, so it immediately makes
  366. // outgoing connections. When it connects to node 1, that node
  367. // accepts its (only) incoming connection, and then starts making
  368. // its outgoing connections, etc.
  369. tcp::resolver resolver(io_context);
  370. tcp::acceptor acceptor(io_context,
  371. resolver.resolve(myconf.listenhost, myconf.listenport)->endpoint());
  372. for(size_t i=0; i<me; ++i) {
  373. #ifdef VERBOSE_NET
  374. std::cerr << "Accepting number " << i << "\n";
  375. #endif
  376. tcp::socket nodesock = acceptor.accept();
  377. #ifdef VERBOSE_NET
  378. std::cerr << "Accepted number " << i << "\n";
  379. #endif
  380. // Read 2 bytes from the socket, which will be the
  381. // connecting node's node number
  382. unsigned short node_num;
  383. boost::asio::read(nodesock,
  384. boost::asio::buffer(&node_num, sizeof(node_num)));
  385. if (node_num >= num_nodes) {
  386. std::cerr << "Received bad node number\n";
  387. } else {
  388. nodeios[node_num].emplace(std::move(nodesock), node_num);
  389. #ifdef VERBOSE_NET
  390. std::cerr << "Received connection from " <<
  391. config.nodes[node_num].name << "\n";
  392. #endif
  393. }
  394. }
  395. for(size_t i=me+1; i<num_nodes; ++i) {
  396. boost::system::error_code err;
  397. tcp::socket nodesock(io_context);
  398. while(1) {
  399. #ifdef VERBOSE_NET
  400. std::cerr << "Connecting to " << config.nodes[i].name << "...\n";
  401. #endif
  402. boost::asio::connect(nodesock,
  403. resolver.resolve(config.nodes[i].listenhost,
  404. config.nodes[i].listenport), err);
  405. if (!err) break;
  406. std::cerr << "Connection to " << config.nodes[i].name <<
  407. " refused, will retry.\n";
  408. sleep(1);
  409. }
  410. // Write 2 bytes to the socket to tell the peer node our node
  411. // number
  412. nodenum_t node_num = (nodenum_t)me;
  413. boost::asio::write(nodesock,
  414. boost::asio::buffer(&node_num, sizeof(node_num)));
  415. nodeios[i].emplace(std::move(nodesock), i);
  416. #ifdef VERBOSE_NET
  417. std::cerr << "Connected to " << config.nodes[i].name << "\n";
  418. #endif
  419. }
  420. auth_size = sizeof(clientid_t) + sizeof(unsigned long) + SGX_AESGCM_KEY_SIZE;
  421. msgbundle_size = SGX_AESGCM_IV_SIZE
  422. + (conf.m_priv_out * (conf.msg_size + TOKEN_SIZE))
  423. + SGX_AESGCM_MAC_SIZE;
  424. uint16_t priv_out = config.m_priv_out;
  425. token_bundle_size = ((priv_out * TOKEN_SIZE)
  426. + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE);
  427. uint16_t priv_in = conf.m_priv_in;
  428. mailbox_size = (priv_in * conf.msg_size) + SGX_AESGCM_IV_SIZE
  429. + SGX_AESGCM_MAC_SIZE;
  430. if(myconf.roles & ROLE_STORAGE) {
  431. // Setup the client sockets
  432. // Compute no_of_clients per storage_server
  433. uint32_t num_users = config.user_count;
  434. NodeConfig nc;
  435. num_stg_nodes = 0;
  436. for (nodenum_t i=0; i<num_nodes; ++i) {
  437. nc = conf.nodes[i];
  438. if(nc.roles & ROLE_STORAGE) {
  439. num_stg_nodes++;
  440. }
  441. }
  442. num_clients_per_stg = CEILDIV(num_users, num_stg_nodes);
  443. for(uint32_t i = 0; i<num_clients_per_stg; i++) {
  444. client_sockets.emplace_back(nullptr);
  445. }
  446. uint32_t epoch_mailboxes_size = num_clients_per_stg * mailbox_size;
  447. uint32_t epoch_tokens_size = num_clients_per_stg * token_bundle_size;
  448. epoch_mailboxes = (unsigned char *) malloc(epoch_mailboxes_size);
  449. epoch_tokens = (unsigned char *) malloc (epoch_tokens_size);
  450. ecall_supply_storage_buffers(epoch_mailboxes, epoch_mailboxes_size,
  451. epoch_tokens, epoch_tokens_size);
  452. storage_acceptor = std::shared_ptr<tcp::acceptor>(
  453. new tcp::acceptor(io_context,
  454. resolver.resolve(this->myconf.slistenhost,
  455. this->myconf.slistenport)->endpoint()));
  456. stg_start_accept();
  457. }
  458. if(myconf.roles & ROLE_INGESTION) {
  459. ingestion_acceptor = std::shared_ptr<tcp::acceptor>(
  460. new tcp::acceptor(io_context,
  461. resolver.resolve(this->myconf.clistenhost,
  462. this->myconf.clistenport)->endpoint()));
  463. ing_start_accept();
  464. }
  465. }
  466. void NetIO::recv_commands(
  467. std::function<void(boost::system::error_code)> error_cb,
  468. std::function<void(uint32_t)> epoch_cb)
  469. {
  470. for (nodenum_t node_num = 0; node_num < num_nodes; ++node_num) {
  471. if (node_num == me) continue;
  472. NodeIO &n = node(node_num);
  473. n.recv_commands(error_cb, epoch_cb);
  474. }
  475. }
  476. void NetIO::close()
  477. {
  478. for (nodenum_t node_num = 0; node_num < num_nodes; ++node_num) {
  479. if (node_num == me) continue;
  480. NodeIO &n = node(node_num);
  481. n.close();
  482. }
  483. }
  484. /* The enclave calls this to inform the untrusted app that there's a new
  485. * messaage to send. The return value is the frame the enclave should
  486. * use to store the first (encrypted) chunk of this message. */
  487. uint8_t *ocall_message(nodenum_t node_num, uint32_t message_len)
  488. {
  489. assert(g_netio != NULL);
  490. NodeIO &node = g_netio->node(node_num);
  491. node.send_message_header(message_len);
  492. return node.request_frame();
  493. }
  494. /* The enclave calls this to inform the untrusted app that there's a new
  495. * chunk to send. The return value is the frame the enclave should use
  496. * to store the next (encrypted) chunk of this message, or NULL if this
  497. * was the last chunk. */
  498. uint8_t *ocall_chunk(nodenum_t node_num, uint8_t *chunkdata,
  499. uint32_t chunklen)
  500. {
  501. assert(g_netio != NULL);
  502. NodeIO &node = g_netio->node(node_num);
  503. bool morechunks = node.send_chunk(chunkdata, chunklen);
  504. if (morechunks) {
  505. return node.request_frame();
  506. }
  507. return NULL;
  508. }