comms.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #include <vector>
  2. #include <functional>
  3. #include <cstring>
  4. #include "sgx_tcrypto.h"
  5. #include "sgx_tseal.h"
  6. #include "Enclave_t.h"
  7. #include "utils.hpp"
  8. #include "config.hpp"
  9. // Our public and private identity keys
  10. static sgx_ec256_private_t g_privkey;
  11. static sgx_ec256_public_t g_pubkey;
  12. // What step of the handshake are we on?
  13. enum HandshakeStep {
  14. HANDSHAKE_NONE,
  15. HANDSHAKE_C_SENT_1,
  16. HANDSHAKE_S_SENT_2,
  17. HANDSHAKE_COMPLETE
  18. };
  19. // Communication state for a node
  20. struct NodeCommState {
  21. sgx_ec256_public_t pubkey;
  22. nodenum_t node_num;
  23. HandshakeStep handshake_step;
  24. // Our DH keypair during the handshake
  25. sgx_ec256_private_t handshake_privkey;
  26. sgx_ec256_public_t handshake_pubkey;
  27. // The peer's DH public key during the handshake
  28. sgx_ec256_public_t handshake_peer_pubkey;
  29. // The outgoing and incoming AES keys after the handshake
  30. sgx_aes_gcm_128bit_key_t out_aes_key, in_aes_key;
  31. // The outgoing and incoming IV counters
  32. uint8_t out_aes_iv[SGX_AESGCM_IV_SIZE];
  33. uint8_t in_aes_iv[SGX_AESGCM_IV_SIZE];
  34. // The GCM state for incrementally building each outgoing chunk
  35. sgx_aes_state_handle_t out_aes_gcm_state;
  36. // The current outgoing frame and the current offset into it
  37. uint8_t *frame;
  38. uint32_t frame_offset;
  39. // The current outgoing message ciphertext size and the offset into
  40. // it of the start of the current frame
  41. uint32_t msg_size;
  42. uint32_t msg_frame_offset;
  43. // The current outgoing message plaintext size, how many plaintext
  44. // bytes we've already processed with message_data, and how many
  45. // plaintext bytes remain for the current chunk
  46. uint32_t msg_plaintext_size;
  47. uint32_t msg_plaintext_processed;
  48. uint32_t msg_plaintext_chunk_remain;
  49. // The current incoming message ciphertext size and the offset into
  50. // it of all previous chunks of this message
  51. uint32_t in_msg_size;
  52. uint32_t in_msg_offset;
  53. // The current incoming message number of plaintext bytes processed
  54. uint32_t in_msg_plaintext_processed;
  55. // The internal buffer where we're storing the (decrypted) message
  56. uint8_t *in_msg_buf;
  57. // The function to call when a new incoming message header arrives.
  58. // This function should return a pointer to enough memory to hold
  59. // the (decrypted) chunks of the message. Remember that the length
  60. // passed here is the total size of the _encrypted_ chunks. This
  61. // function should not itself modify the in_msg_size, in_msg_offset,
  62. // or in_msg_buf members. This function will usually allocate an
  63. // appropriate amount of memory and return the pointer to it, but
  64. // may do other things, like return a pointer to the middle of a
  65. // previously allocated region of memory.
  66. std::function<uint8_t*(NodeCommState&,uint32_t)> in_msg_get_buf;
  67. // The function to call after the last chunk of a message has been
  68. // received. If in_msg_get_buf allocated memory, this function
  69. // should deallocate it. in_msg_size, in_msg_offset, and in_msg_buf
  70. // will already have been reset when this function is called. The
  71. // uint32_t that is passed are the total size of the _decrypted_
  72. // data and the original total size of the _encrypted_ chunks that
  73. // was passed to in_msg_get_buf.
  74. std::function<void(NodeCommState&,uint8_t*,uint32_t,uint32_t)>
  75. in_msg_received;
  76. NodeCommState(const sgx_ec256_public_t* conf_pubkey, nodenum_t i) :
  77. node_num(i), handshake_step(HANDSHAKE_NONE),
  78. out_aes_gcm_state(NULL), frame(NULL),
  79. frame_offset(0), msg_size(0), msg_frame_offset(0),
  80. msg_plaintext_size(0), msg_plaintext_processed(0),
  81. msg_plaintext_chunk_remain(0),
  82. in_msg_size(0), in_msg_offset(0),
  83. in_msg_plaintext_processed(0), in_msg_buf(NULL),
  84. in_msg_get_buf(NULL), in_msg_received(NULL) {
  85. memmove(&pubkey, conf_pubkey, sizeof(pubkey));
  86. }
  87. void message_start(uint32_t plaintext_len);
  88. void message_data(uint8_t *data, uint32_t len);
  89. };
  90. // A typical default in_msg_get_buf handler. It computes the maximum
  91. // possible size of the decrypted data, allocates that much memory, and
  92. // returns a pointer to it.
  93. static uint8_t* default_in_msg_get_buf(NodeCommState &commst,
  94. uint32_t tot_enc_chunk_size)
  95. {
  96. uint32_t max_plaintext_bytes = tot_enc_chunk_size;
  97. // If the handshake is complete, chunks will be encrypted and have a
  98. // MAC tag attached which will not correspond to plaintext bytes, so
  99. // we can trim them.
  100. if (commst.handshake_step == HANDSHAKE_COMPLETE) {
  101. // The minimum number of chunks needed to transmit this message
  102. uint32_t min_num_chunks =
  103. (tot_enc_chunk_size + (FRAME_SIZE-1)) / FRAME_SIZE;
  104. // The maximum number of plaintext bytes this message could contain
  105. max_plaintext_bytes = tot_enc_chunk_size -
  106. SGX_AESGCM_MAC_SIZE * min_num_chunks;
  107. }
  108. return new uint8_t[max_plaintext_bytes];
  109. }
  110. // Receive (at the server) the first handshake message
  111. static void handshake_1_msg_received(NodeCommState &nodest,
  112. uint8_t *data, uint32_t plaintext_len, uint32_t message_len)
  113. {
  114. printf("Received handshake_1 message of %u bytes:\n", plaintext_len);
  115. for (uint32_t i=0;i<plaintext_len;++i) {
  116. printf("%02x", data[i]);
  117. }
  118. printf("\n");
  119. delete[] data;
  120. }
  121. // Start a new outgoing message. Pass the number of _plaintext_ bytes
  122. // the message will be.
  123. void NodeCommState::message_start(uint32_t plaintext_len)
  124. {
  125. uint32_t ciphertext_len = plaintext_len;
  126. // If the handshake is complete, add SGX_AESGCM_MAC_SIZE bytes for
  127. // every FRAME_SIZE-SGX_AESGCM_MAC_SIZE bytes of plaintext.
  128. if (handshake_step == HANDSHAKE_COMPLETE) {
  129. uint32_t num_chunks = (plaintext_len +
  130. FRAME_SIZE - SGX_AESGCM_MAC_SIZE - 1) /
  131. (FRAME_SIZE - SGX_AESGCM_MAC_SIZE);
  132. ciphertext_len = plaintext_len +
  133. num_chunks * SGX_AESGCM_MAC_SIZE;
  134. }
  135. ocall_message(&frame, node_num, ciphertext_len);
  136. frame_offset = 0;
  137. msg_size = ciphertext_len;
  138. msg_frame_offset = 0;
  139. msg_plaintext_size = plaintext_len;
  140. msg_plaintext_processed = 0;
  141. if (plaintext_len < FRAME_SIZE - SGX_AESGCM_MAC_SIZE) {
  142. msg_plaintext_chunk_remain = plaintext_len;
  143. } else {
  144. msg_plaintext_chunk_remain = FRAME_SIZE - SGX_AESGCM_MAC_SIZE;
  145. }
  146. if (!frame) {
  147. printf("Received NULL back from ocall_message\n");
  148. }
  149. if (msg_plaintext_chunk_remain > 0) {
  150. *(size_t*)out_aes_iv += 1;
  151. sgx_aes_gcm128_enc_init(out_aes_key, out_aes_iv, SGX_AESGCM_IV_SIZE,
  152. NULL, 0, &out_aes_gcm_state);
  153. }
  154. }
  155. // Process len bytes of plaintext data into the current message.
  156. void NodeCommState::message_data(uint8_t *data, uint32_t len)
  157. {
  158. while (len > 0) {
  159. if (msg_plaintext_chunk_remain == 0) {
  160. printf("Attempt to queue too much message data\n");
  161. return;
  162. }
  163. uint32_t bytes_to_process = len;
  164. if (bytes_to_process > msg_plaintext_chunk_remain) {
  165. bytes_to_process = msg_plaintext_chunk_remain;
  166. }
  167. if (frame == NULL) {
  168. printf("frame is NULL when queueing message data\n");
  169. return;
  170. }
  171. if (handshake_step == HANDSHAKE_COMPLETE) {
  172. // Encrypt the data
  173. sgx_aes_gcm128_enc_update(data, bytes_to_process,
  174. frame+frame_offset, out_aes_gcm_state);
  175. } else {
  176. // Just copy the plaintext data during the handshake
  177. memmove(frame+frame_offset, data, bytes_to_process);
  178. }
  179. frame_offset += bytes_to_process;
  180. msg_plaintext_processed += bytes_to_process;
  181. msg_plaintext_chunk_remain -= bytes_to_process;
  182. len -= bytes_to_process;
  183. data += bytes_to_process;
  184. if (msg_plaintext_chunk_remain == 0) {
  185. // Complete and send this chunk
  186. if (handshake_step == HANDSHAKE_COMPLETE) {
  187. sgx_aes_gcm128_enc_get_mac(frame+frame_offset,
  188. out_aes_gcm_state);
  189. frame_offset += SGX_AESGCM_MAC_SIZE;
  190. }
  191. uint8_t *nextframe = NULL;
  192. ocall_chunk(&nextframe, node_num, frame, frame_offset);
  193. frame = nextframe;
  194. msg_frame_offset += frame_offset;
  195. frame_offset = 0;
  196. msg_plaintext_chunk_remain =
  197. msg_plaintext_size - msg_plaintext_processed;
  198. if (msg_plaintext_chunk_remain >
  199. FRAME_SIZE - SGX_AESGCM_MAC_SIZE) {
  200. msg_plaintext_chunk_remain =
  201. FRAME_SIZE - SGX_AESGCM_MAC_SIZE;
  202. }
  203. if (handshake_step == HANDSHAKE_COMPLETE) {
  204. sgx_aes_gcm_close(out_aes_gcm_state);
  205. if (msg_plaintext_chunk_remain > 0) {
  206. *(size_t*)out_aes_iv += 1;
  207. sgx_aes_gcm128_enc_init(out_aes_key, out_aes_iv,
  208. SGX_AESGCM_IV_SIZE, NULL, 0, &out_aes_gcm_state);
  209. }
  210. }
  211. }
  212. }
  213. }
  214. // The communication states for all the nodes. There's an entry for
  215. // ourselves in here, but it is unused.
  216. static std::vector<NodeCommState> commstates;
  217. static nodenum_t tot_nodes;
  218. // Generate a new identity signature key. Output the public key and the
  219. // sealed private key. outsealedpriv must point to SEALEDPRIVKEY_SIZE =
  220. // sizeof(sgx_sealed_data_t) + sizeof(sgx_ec256_private_t) + 18 bytes of
  221. // memory.
  222. void ecall_identity_key_new(sgx_ec256_public_t *outpub,
  223. sgx_sealed_data_t *outsealedpriv)
  224. {
  225. sgx_ecc_state_handle_t ecc_handle;
  226. sgx_ecc256_open_context(&ecc_handle);
  227. sgx_ecc256_create_key_pair(&g_privkey, &g_pubkey, ecc_handle);
  228. memmove(outpub, &g_pubkey, sizeof(g_pubkey));
  229. sgx_ecc256_close_context(ecc_handle);
  230. sgx_seal_data(18, (const uint8_t*)"TEEMS Identity key",
  231. sizeof(g_privkey), (const uint8_t*)&g_privkey,
  232. SEALED_PRIVKEY_SIZE, outsealedpriv);
  233. }
  234. // Load an identity key from a sealed privkey. Output the resulting
  235. // public key. insealedpriv must point to sizeof(sgx_sealed_data_t) +
  236. // sizeof(sgx_ec256_private_t) bytes of memory. Returns true for
  237. // success, false for failure.
  238. bool ecall_identity_key_load(sgx_ec256_public_t *outpub,
  239. const sgx_sealed_data_t *insealedpriv)
  240. {
  241. sgx_ecc_state_handle_t ecc_handle;
  242. char aad[18];
  243. uint32_t aadsize = sizeof(aad);
  244. sgx_ec256_private_t privkey;
  245. uint32_t privkeysize = sizeof(privkey);
  246. sgx_status_t res = sgx_unseal_data(
  247. insealedpriv, (uint8_t*)aad, &aadsize,
  248. (uint8_t*)&privkey, &privkeysize);
  249. if (res || aadsize != sizeof(aad) || privkeysize != sizeof(privkey)
  250. || memcmp(aad, "TEEMS Identity key", sizeof(aad))) {
  251. return false;
  252. }
  253. sgx_ecc256_open_context(&ecc_handle);
  254. sgx_ec256_public_t pubkey;
  255. int valid;
  256. if (sgx_ecc256_calculate_pub_from_priv(&privkey, &pubkey) ||
  257. sgx_ecc256_check_point(&pubkey, ecc_handle, &valid) ||
  258. !valid) {
  259. sgx_ecc256_close_context(ecc_handle);
  260. return false;
  261. }
  262. sgx_ecc256_close_context(ecc_handle);
  263. memmove(&g_pubkey, &pubkey, sizeof(pubkey));
  264. memmove(&g_privkey, &privkey, sizeof(privkey));
  265. memmove(outpub, &pubkey, sizeof(pubkey));
  266. return true;
  267. }
  268. bool comms_init_nodestate(const EnclaveAPINodeConfig *apinodeconfigs,
  269. nodenum_t num_nodes, nodenum_t my_node_num)
  270. {
  271. sgx_ecc_state_handle_t ecc_handle;
  272. sgx_ecc256_open_context(&ecc_handle);
  273. commstates.clear();
  274. tot_nodes = 0;
  275. commstates.reserve(num_nodes);
  276. for (nodenum_t i=0; i<num_nodes; ++i) {
  277. // Check that the pubkey is valid
  278. int valid;
  279. if (sgx_ecc256_check_point(&apinodeconfigs[i].pubkey,
  280. ecc_handle, &valid) ||
  281. !valid) {
  282. printf("Pubkey for node %hu invalid\n", i);
  283. commstates.clear();
  284. sgx_ecc256_close_context(ecc_handle);
  285. return false;
  286. }
  287. commstates.emplace_back(&apinodeconfigs[i].pubkey, i);
  288. }
  289. sgx_ecc256_close_context(ecc_handle);
  290. // Check that no one other than us has our pubkey (deals with
  291. // reflection attacks)
  292. for (nodenum_t i=0; i<num_nodes; ++i) {
  293. if (i == my_node_num) continue;
  294. if (!memcmp(&commstates[i].pubkey,
  295. &commstates[my_node_num].pubkey,
  296. sizeof(commstates[i].pubkey))) {
  297. printf("Pubkey %hu matches our own; possible reflection attack?\n",
  298. i);
  299. commstates.clear();
  300. return false;
  301. }
  302. }
  303. tot_nodes = num_nodes;
  304. // There will be an enclave-to-enclave channel between us and each
  305. // other node's enclave. For the node numbers smaller than ours, we
  306. // will be the server for the handshake for that channel. Prepare
  307. // to receive the first handshake message from those nodes'
  308. // enclaves.
  309. for (nodenum_t i=0; i<my_node_num; ++i) {
  310. commstates[i].in_msg_get_buf = default_in_msg_get_buf;
  311. commstates[i].in_msg_received = handshake_1_msg_received;
  312. }
  313. return true;
  314. }
  315. bool ecall_message(nodenum_t node_num, uint32_t message_len)
  316. {
  317. if (node_num >= tot_nodes) {
  318. printf("Out-of-range node_num %hu received in ecall_message\n",
  319. node_num);
  320. return false;
  321. }
  322. NodeCommState &nodest = commstates[node_num];
  323. if (nodest.in_msg_size != nodest.in_msg_offset) {
  324. printf("Received ecall_message without completing previous message\n");
  325. return false;
  326. }
  327. if (!nodest.in_msg_get_buf) {
  328. printf("No message header handler registered\n");
  329. return false;
  330. }
  331. uint8_t *buf = nodest.in_msg_get_buf(nodest, message_len);
  332. if (!buf) {
  333. printf("Message header handler returned NULL\n");
  334. return false;
  335. }
  336. nodest.in_msg_size = message_len;
  337. nodest.in_msg_offset = 0;
  338. nodest.in_msg_plaintext_processed = 0;
  339. nodest.in_msg_buf = buf;
  340. return true;
  341. }
  342. bool ecall_chunk(nodenum_t node_num, const uint8_t *chunkdata,
  343. uint32_t chunklen)
  344. {
  345. if (node_num >= tot_nodes) {
  346. printf("Out-of-range node_num %hu received in ecall_chunk\n",
  347. node_num);
  348. return false;
  349. }
  350. NodeCommState &nodest = commstates[node_num];
  351. if (nodest.in_msg_size == nodest.in_msg_offset) {
  352. printf("Received ecall_chunk after completing message\n");
  353. return false;
  354. }
  355. if (!nodest.in_msg_buf) {
  356. printf("No incoming message buffer allocated\n");
  357. return false;
  358. }
  359. if (!nodest.in_msg_received) {
  360. printf("No message received handler registered\n");
  361. return false;
  362. }
  363. if (nodest.in_msg_offset + chunklen > nodest.in_msg_size) {
  364. printf("Chunk larger than remaining message size\n");
  365. return false;
  366. }
  367. if (nodest.handshake_step == HANDSHAKE_COMPLETE) {
  368. // Decrypt the incoming data
  369. *(size_t*)(nodest.in_aes_iv) += 1;
  370. if (sgx_rijndael128GCM_decrypt(&nodest.in_aes_key, chunkdata,
  371. chunklen - SGX_AESGCM_MAC_SIZE,
  372. nodest.in_msg_buf + nodest.in_msg_plaintext_processed,
  373. nodest.in_aes_iv, SGX_AESGCM_IV_SIZE, NULL, 0,
  374. (const sgx_aes_gcm_128bit_tag_t *)
  375. (chunkdata + chunklen - SGX_AESGCM_MAC_SIZE))) {
  376. printf("Decryption failed\n");
  377. return false;
  378. }
  379. nodest.in_msg_plaintext_processed +=
  380. chunklen - SGX_AESGCM_MAC_SIZE;
  381. } else {
  382. // Just copy the handshake data
  383. memmove(nodest.in_msg_buf + nodest.in_msg_plaintext_processed,
  384. chunkdata, chunklen);
  385. nodest.in_msg_plaintext_processed += chunklen;
  386. }
  387. nodest.in_msg_offset += chunklen;
  388. if (nodest.in_msg_offset == nodest.in_msg_size) {
  389. // This was the last chunk; handle the received message
  390. nodest.in_msg_received(nodest, nodest.in_msg_buf,
  391. nodest.in_msg_plaintext_processed, nodest.in_msg_size);
  392. }
  393. return true;
  394. }