utils.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. #include <pthread.h>
  2. #include "utils.hpp"
  3. #ifdef COUNT_OSWAPS
  4. thread_local uint64_t OSWAP_COUNTER=0;
  5. #endif
  6. thread_local PRB_buffer PRB_buf;
  7. thread_local uint64_t PRB_rand_bits = 0;
  8. thread_local uint32_t PRB_rand_bits_remaining = 0;
  9. bool bulk_initialized = false;
  10. sgx_aes_ctr_128bit_key_t bulk_random_seed[SGX_AESCTR_KEY_SIZE];
  11. unsigned char bulk_counter[SGX_AESCTR_KEY_SIZE];
  12. int compare(const void *buf1, const void *buf2) {
  13. uint64_t label1, label2;
  14. memcpy(&label1, (const unsigned char*) buf1, 8);
  15. memcpy(&label2, (const unsigned char*) buf2, 8);
  16. return((int)(label1 - label2));
  17. }
  18. int compare_32(const void *buf1, const void *buf2) {
  19. uint32_t label1, label2;
  20. memcpy(&label1, (const unsigned char*) buf1, 4);
  21. memcpy(&label2, (const unsigned char*) buf2, 4);
  22. return((int)(label1 - label2));
  23. }
  24. #if 0
  25. void generateSortPermutation_DJB(size_t N, unsigned char *buffer, size_t block_size, size_t *permutation) {
  26. size_t *keys;
  27. try {
  28. keys = new size_t[N];
  29. } catch (std::bad_alloc&) {
  30. printf("Allocating memory failed in generateSortPermutation_DJB\n");
  31. }
  32. unsigned char *buffer_ptr = buffer;
  33. for(size_t i=0; i<N; i++){
  34. keys[i] = *((size_t*)(buffer_ptr));
  35. permutation[i] = i;
  36. buffer_ptr+=block_size;
  37. }
  38. BitonicSort((unsigned char*) keys, N, (unsigned char*) permutation, NULL, 8, true);
  39. /*
  40. printf("\nSort Permutation:\n");
  41. for(size_t i=0; i<N; i++)
  42. printf("%ld, ", permutation[i]);
  43. printf("\n");
  44. */
  45. delete[] keys;
  46. }
  47. void generateSortPermutation_OA(uint32_t N, unsigned char *buffer, size_t block_size, uint32_t *permutation) {
  48. // Extract key list from buffer
  49. uint32_t *keys = new uint32_t[N];
  50. unsigned char *buffer_ptr = buffer;
  51. for(size_t i=0; i<N; i++){
  52. keys[i] = *((uint32_t*)(buffer_ptr));
  53. permutation[i] = i;
  54. buffer_ptr+=block_size;
  55. }
  56. BitonicSort<OSWAP_4, uint32_t> ((unsigned char*) keys, N, (unsigned char*) permutation, NULL, 4, true);
  57. /*
  58. printf("\nSort Permutation:\n");
  59. for(size_t i=0; i<N; i++)
  60. printf("%ld, ", permutation[i]);
  61. printf("\n");
  62. */
  63. delete []keys;
  64. }
  65. #endif
  66. /* Debug function to see keys in a buffer*/
  67. void displayKeysInBuffer(unsigned char *buffer, size_t N, size_t block_size){
  68. unsigned char *ptr = buffer;
  69. printf("Keys in displayKeysInBuffer:\n");
  70. for(size_t i=0; i<N; i++){
  71. size_t key = *((size_t*) ptr);
  72. ptr+=block_size;
  73. printf("%ld\n",key);
  74. }
  75. printf("\n\n");
  76. }
  77. #if 0
  78. #ifndef BEFTS_MODE
  79. /*
  80. Decrypts buffers passed to the enclave that are encrypted with keys from Enclave_LoadTestKeys
  81. with AES_GCM. In addition it, gives each decrypted block an 8 byte random tag at the start.
  82. Intended for using SN as a shuffler, by sorting the blocks based on the attached random tags.
  83. The function assumes the provided encrypted buffer is initalized to the correct length.
  84. It returns a buffer of correct size (N * block_size_with_tag ) back to the function that
  85. invoked decryptBuffer, where block_size_with_tag = decrypted_block_size + 8
  86. The function returns the block_size_with_tag.
  87. */
  88. size_t decryptBuffer_attachRTags_addDummies(unsigned char *encrypted_buffer, uint64_t N,
  89. uint64_t N_prime, uint64_t B, uint64_t Z, size_t encrypted_block_size,
  90. unsigned char *random_bytes, unsigned char **decrypted_buffer) {
  91. size_t decrypted_block_size = encrypted_block_size - SGX_AESGCM_IV_SIZE - SGX_AESGCM_MAC_SIZE;
  92. size_t block_size_with_tag = decrypted_block_size + 8;
  93. // If decrypted_buffer hasn't been allocated yet, allocate required memory to hold the decrypted
  94. // buffer
  95. if((*decrypted_buffer)==NULL){
  96. size_t mem_to_malloc = 2 * N_prime * block_size_with_tag;
  97. (*decrypted_buffer) = (unsigned char *) malloc(mem_to_malloc);
  98. if(*decrypted_buffer==NULL) {
  99. printf("Malloc failed in decryptBuffer_withAttachedRandomTags_interleaveDummies\n");
  100. }
  101. }
  102. unsigned char *dec_buf_ptr = *decrypted_buffer;
  103. unsigned char *enc_buf_ptr = encrypted_buffer;
  104. unsigned char *tag_ptr = enc_buf_ptr + SGX_AESGCM_IV_SIZE + decrypted_block_size;
  105. uint64_t reals_per_bucket = N / B;
  106. uint32_t num_buckets_with_extra_reals = N % B;
  107. uint64_t packets_to_extract = reals_per_bucket;
  108. for(size_t B_curr = 0; B_curr < B; B_curr++) {
  109. packets_to_extract = (B_curr < num_buckets_with_extra_reals)? reals_per_bucket+1 : reals_per_bucket;
  110. size_t num_dummies = Z - packets_to_extract;
  111. for(size_t i=0; i<packets_to_extract; i++) {
  112. uint64_t destination_bucket = (*((uint64_t*) random_bytes)) % B;
  113. memcpy(dec_buf_ptr, (unsigned char*) &destination_bucket, 8);
  114. random_bytes+=8;
  115. dec_buf_ptr+=8;
  116. sgx_status_t aesret = sgx_rijndael128GCM_decrypt(
  117. &enclave_decryption_key, enc_buf_ptr + SGX_AESGCM_IV_SIZE, decrypted_block_size,
  118. dec_buf_ptr, enc_buf_ptr, SGX_AESGCM_IV_SIZE, NULL, 0,
  119. (const sgx_aes_gcm_128bit_tag_t*)(tag_ptr));
  120. if (aesret != SGX_SUCCESS) {
  121. printf("sgx_rijndael128GCM_decrypt failure (%x)\n", aesret);
  122. return -1;
  123. }
  124. dec_buf_ptr+=decrypted_block_size;
  125. enc_buf_ptr+=encrypted_block_size;
  126. tag_ptr+=encrypted_block_size;
  127. }
  128. for(size_t i=0; i<num_dummies; i++) {
  129. // Set the destination label to UINT64_MAX to indicate it's a dummy.
  130. // We don't care about the contents of the dummy, so whatever came from malloc is fine.
  131. *((uint64_t*) dec_buf_ptr) = UINT64_MAX;
  132. dec_buf_ptr+=block_size_with_tag;
  133. }
  134. }
  135. return(block_size_with_tag);
  136. }
  137. /*
  138. Decrypts buffers passed to the enclave that are encrypted with keys from Enclave_LoadTestKeys
  139. with AES_GCM. In addition it, gives each decrypted block an 8 byte random tag at the start.
  140. Intended for using SN as a shuffler, by sorting the blocks based on the attached randome tags.
  141. The function assumes the provided encrypted buffer is initalized to the correct length.
  142. It returns a buffer of correct size (N * block_size_with_tag ) back to the function that
  143. invoked decryptBuffer, where block_size_with_tag = decrypted_block_size + 8
  144. The function returns the block_size_with_tag.
  145. */
  146. size_t decryptBuffer_attachRTags(unsigned char *encrypted_buffer, uint64_t N, size_t encrypted_block_size, unsigned char *random_bytes, unsigned char **decrypted_buffer) {
  147. size_t decrypted_block_size = encrypted_block_size - SGX_AESGCM_IV_SIZE - SGX_AESGCM_MAC_SIZE;
  148. size_t block_size_with_tag = decrypted_block_size + 8;
  149. // If decrypted_buffer hasn't been allocated yet, allocate required memory to hold the decrypted
  150. // buffer
  151. if((*decrypted_buffer)==NULL){
  152. (*decrypted_buffer) = (unsigned char *) malloc(N * block_size_with_tag);
  153. if(*decrypted_buffer==NULL) {
  154. printf("Malloc failed in decryptBuffer_withAttachedRandomTags\n");
  155. }
  156. }
  157. unsigned char *dec_buf_ptr = *decrypted_buffer;
  158. unsigned char *enc_buf_ptr = encrypted_buffer;
  159. unsigned char *tag_ptr = enc_buf_ptr + SGX_AESGCM_IV_SIZE + decrypted_block_size;
  160. for(size_t i =0; i<N; i++){
  161. memcpy(dec_buf_ptr, random_bytes, 8);
  162. random_bytes+=8;
  163. dec_buf_ptr+=8;
  164. sgx_status_t aesret = sgx_rijndael128GCM_decrypt(
  165. &enclave_decryption_key, enc_buf_ptr + SGX_AESGCM_IV_SIZE, decrypted_block_size,
  166. dec_buf_ptr, enc_buf_ptr, SGX_AESGCM_IV_SIZE, NULL, 0,
  167. (const sgx_aes_gcm_128bit_tag_t*)(tag_ptr));
  168. if (aesret != SGX_SUCCESS) {
  169. printf("sgx_rijndael128GCM_decrypt failure (%x)\n", aesret);
  170. return -1;
  171. }
  172. dec_buf_ptr+=decrypted_block_size;
  173. enc_buf_ptr+=encrypted_block_size;
  174. tag_ptr+=encrypted_block_size;
  175. }
  176. return(block_size_with_tag);
  177. }
  178. /*
  179. Decrypts buffers passed to the enclave that are encrypted with keys from Enclave_LoadTestKeys
  180. with AES_GCM.
  181. The function assumes the provided encrypted buffer is initalized to the correct length.
  182. It returns a buffer of correct size (N * decrypted_block_size) back to the function that
  183. invoked decryptBuffer.
  184. The function returns the decrypted_block_size.
  185. */
  186. size_t decryptBuffer(unsigned char *encrypted_buffer, uint64_t N, size_t encrypted_block_size,
  187. unsigned char **decrypted_buffer) {
  188. size_t decrypted_block_size = encrypted_block_size - SGX_AESGCM_IV_SIZE - SGX_AESGCM_MAC_SIZE;
  189. // If decrypted_buffer hasn't been allocated yet, allocate required memory to hold the decrypted
  190. // buffer
  191. if((*decrypted_buffer)==NULL){
  192. (*decrypted_buffer) = (unsigned char *) malloc(N * decrypted_block_size);
  193. if(*decrypted_buffer==NULL) {
  194. printf("Malloc failed in decryptBuffer for %ld bytes\n", (N*decrypted_block_size));
  195. }
  196. }
  197. unsigned char *dec_buf_ptr = *decrypted_buffer;
  198. unsigned char *enc_buf_ptr = encrypted_buffer;
  199. unsigned char *tag_ptr = enc_buf_ptr + SGX_AESGCM_IV_SIZE + decrypted_block_size;
  200. for(size_t i =0; i<N; i++){
  201. sgx_status_t aesret = sgx_rijndael128GCM_decrypt(
  202. &enclave_decryption_key, enc_buf_ptr + SGX_AESGCM_IV_SIZE, decrypted_block_size,
  203. dec_buf_ptr, enc_buf_ptr, SGX_AESGCM_IV_SIZE, NULL, 0,
  204. (const sgx_aes_gcm_128bit_tag_t*)(tag_ptr));
  205. if (aesret != SGX_SUCCESS) {
  206. printf("sgx_rijndael128GCM_decrypt failure (%x)\n", aesret);
  207. return -1;
  208. }
  209. dec_buf_ptr+=decrypted_block_size;
  210. enc_buf_ptr+=encrypted_block_size;
  211. tag_ptr+=encrypted_block_size;
  212. }
  213. return(decrypted_block_size);
  214. }
  215. /*
  216. Encrypts buffers going out of the Enclave using AESGCM with keys from Enclave_LoadTestKeys.
  217. The function assumes the buffers are initalized with the correct length.
  218. Unlike decryptBuffers, encryptBuffer expects the encrypted_buffer of correct size to be passed to it
  219. and it populates it with encryptions of blocks from decrypted_buffer.
  220. (This is done to avoid unnecessary additional copying of the encrypted buffer to a result buffer
  221. passed by the outside application to the enclave)
  222. */
  223. size_t encryptBuffer(unsigned char *decrypted_buffer, uint64_t N, size_t decrypted_block_size,
  224. unsigned char *encrypted_buffer) {
  225. size_t encrypted_block_size = decrypted_block_size + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE;
  226. unsigned char *dec_buf_ptr = decrypted_buffer;
  227. unsigned char *enc_buf_ptr = encrypted_buffer;
  228. unsigned char *tag_ptr = enc_buf_ptr + SGX_AESGCM_IV_SIZE + decrypted_block_size;
  229. for(size_t i =0; i<N; i++){
  230. getRandomBytes(enc_buf_ptr, SGX_AESGCM_IV_SIZE);
  231. sgx_status_t aesret = sgx_rijndael128GCM_encrypt(
  232. &enclave_encryption_key, dec_buf_ptr, decrypted_block_size,
  233. enc_buf_ptr + SGX_AESGCM_IV_SIZE, enc_buf_ptr, SGX_AESGCM_IV_SIZE, NULL, 0,
  234. (sgx_aes_gcm_128bit_tag_t*)(tag_ptr));
  235. if (aesret != SGX_SUCCESS) {
  236. printf("sgx_rijndael128GCM_encrypt failure (%x)\n", aesret);
  237. return -1;
  238. }
  239. dec_buf_ptr+=decrypted_block_size;
  240. enc_buf_ptr+=encrypted_block_size;
  241. tag_ptr+=encrypted_block_size;
  242. }
  243. return(encrypted_block_size);
  244. }
  245. /*
  246. Removes the random tags attached by decryptBuffer_attachRTags before encrypting the buffer.
  247. */
  248. size_t encryptBuffer_removeRTags(unsigned char *decrypted_buffer, uint64_t N,
  249. size_t decrypted_block_size, unsigned char *encrypted_buffer) {
  250. size_t real_block_size = decrypted_block_size - 8;
  251. size_t encrypted_block_size = real_block_size + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE;
  252. unsigned char *dec_buf_ptr = decrypted_buffer;
  253. unsigned char *enc_buf_ptr = encrypted_buffer;
  254. unsigned char *tag_ptr = enc_buf_ptr + SGX_AESGCM_IV_SIZE + real_block_size;
  255. for(size_t i =0; i<N; i++){
  256. //Skip the attached random tag
  257. dec_buf_ptr+=8;
  258. getRandomBytes(enc_buf_ptr, SGX_AESGCM_IV_SIZE);
  259. sgx_status_t aesret = sgx_rijndael128GCM_encrypt(
  260. &enclave_encryption_key, dec_buf_ptr, real_block_size,
  261. enc_buf_ptr + SGX_AESGCM_IV_SIZE, enc_buf_ptr, SGX_AESGCM_IV_SIZE, NULL, 0,
  262. (sgx_aes_gcm_128bit_tag_t*)(tag_ptr));
  263. if (aesret != SGX_SUCCESS) {
  264. printf("i = %d\n", i);
  265. printf("sgx_rijndael128GCM_encrypt failure (%x)\n", aesret);
  266. return -1;
  267. }
  268. dec_buf_ptr+=real_block_size;
  269. enc_buf_ptr+=encrypted_block_size;
  270. tag_ptr+=encrypted_block_size;
  271. }
  272. return(encrypted_block_size);
  273. }
  274. #endif
  275. #endif
  276. // Returns log2 rounded up.
  277. int calculatelog2(uint64_t value){
  278. int log2v = 0;
  279. uint64_t temp = 1;
  280. while(temp<value){
  281. temp=temp<<1;
  282. log2v+=1;
  283. }
  284. return log2v;
  285. }
  286. int calculatelog2_floor(uint64_t value){
  287. int log2v = 0;
  288. uint64_t temp = 1;
  289. while(temp<value){
  290. temp=temp<<1;
  291. log2v+=1;
  292. }
  293. if(temp==value)
  294. return log2v;
  295. else
  296. return log2v-1;
  297. }
  298. // Returns largest power of two less than N
  299. uint64_t pow2_lt(uint64_t N) {
  300. uint64_t N1 = 1;
  301. while (N1 < N) {
  302. N1 <<= 1;
  303. }
  304. N1 >>= 1;
  305. return N1;
  306. }
  307. #ifndef BEFTS_MODE
  308. /*
  309. * printf:
  310. * Invokes OCALL to display the enclave buffer to the terminal.
  311. */
  312. void printf(const char *fmt, ...)
  313. {
  314. char buf[BUFSIZ] = {'\0'};
  315. va_list ap;
  316. va_start(ap, fmt);
  317. vsnprintf(buf, BUFSIZ, fmt, ap);
  318. va_end(ap);
  319. ocall_print_string(buf);
  320. }
  321. /*
  322. * printf_with_rtclock:
  323. * Invokes OCALL to display the enclave buffer to the terminal with a
  324. * timestamp and returns the timestamp.
  325. */
  326. unsigned long printf_with_rtclock(const char *fmt, ...)
  327. {
  328. unsigned long ret;
  329. char buf[BUFSIZ] = {'\0'};
  330. va_list ap;
  331. va_start(ap, fmt);
  332. vsnprintf(buf, BUFSIZ, fmt, ap);
  333. va_end(ap);
  334. ocall_print_string_with_rtclock(&ret, buf);
  335. return ret;
  336. }
  337. /*
  338. * printf_with_rtclock_diff:
  339. * Invokes OCALL to display the enclave buffer to the terminal with a
  340. * timestamp and returns the timestamp. Also prints the difference from
  341. * the before timestamp.
  342. */
  343. unsigned long printf_with_rtclock_diff(unsigned long before, const char *fmt, ...)
  344. {
  345. unsigned long ret;
  346. char buf[BUFSIZ] = {'\0'};
  347. va_list ap;
  348. va_start(ap, fmt);
  349. vsnprintf(buf, BUFSIZ, fmt, ap);
  350. va_end(ap);
  351. ocall_print_string_with_rtclock_diff(&ret, buf, before);
  352. return ret;
  353. }
  354. #endif
  355. #if 0
  356. void displayORPPacket(unsigned char* packet_in, size_t block_size) {
  357. unsigned char *packet_ptr = packet_in;
  358. uint64_t evict_stream, ORP_label, key;
  359. unsigned char data[block_size];
  360. memcpy(&evict_stream, packet_ptr, sizeof(uint64_t));
  361. packet_ptr+=sizeof(uint64_t);
  362. memcpy(&ORP_label, packet_ptr, sizeof(uint64_t));
  363. packet_ptr+=sizeof(uint64_t);
  364. memcpy(&key, packet_ptr, sizeof(uint64_t));
  365. packet_ptr+=sizeof(uint64_t);
  366. memcpy(data, packet_ptr, block_size);
  367. data[block_size]='\0';
  368. printf("(evict_stream = %ld, ORP_label = %ld, Key = %ld)\n",
  369. evict_stream, ORP_label, key);
  370. //printf("Hex of data is :");
  371. //for(int i=0;i<DATA_SIZE;++i) printf("%02x", data[i]); printf("\n");
  372. }
  373. // isDummy and setDummy works on real packets : <Key, Data>
  374. bool isDummy(unsigned char *ptr_to_serialized_packet){
  375. return(((uint64_t*) ptr_to_serialized_packet)[0] == UINT64_MAX);
  376. }
  377. void setDummy(unsigned char *ptr_to_serialized_packet){
  378. ((uint64_t*) ptr_to_serialized_packet)[0] = UINT64_MAX;
  379. }
  380. // isORPDummy and setORPDummy works on ORP packets : <Eviction_stream, ORP_label, Key, Data>
  381. bool isORPDummy(unsigned char *ptr_to_serialized_packet){
  382. return(((uint64_t*) ptr_to_serialized_packet)[1] == UINT64_MAX);
  383. }
  384. void setORPDummy(unsigned char *ptr_to_packet){
  385. ((uint64_t*) ptr_to_packet)[0] = UINT64_MAX;
  386. ((uint64_t*) ptr_to_packet)[1] = UINT64_MAX;
  387. ((uint64_t*) ptr_to_packet)[2] = UINT64_MAX;
  388. }
  389. size_t packetsConsumedUptoMSN(signed long msn_no, size_t msns_with_extra_packets, size_t packets_per_entry_msn) {
  390. if(msn_no<0)
  391. return 0;
  392. if(msn_no<=msns_with_extra_packets){
  393. return (msn_no * (packets_per_entry_msn+1));
  394. }
  395. else{
  396. size_t reg_msn = msn_no - msns_with_extra_packets;
  397. return ((reg_msn * packets_per_entry_msn) + (msns_with_extra_packets * packets_per_entry_msn));
  398. }
  399. }
  400. #endif
  401. #ifdef USE_PRB
  402. void PRB_pool_init(int nthreads) {
  403. // Nothing needs to be done any more
  404. }
  405. void PRB_pool_shutdown() {
  406. // Nothing needs to be done any more
  407. }
  408. PRB_buffer::PRB_buffer() {
  409. }
  410. sgx_status_t PRB_buffer::init_PRB_buffer(uint32_t buffer_size = PRB_BUFFER_SIZE) {
  411. sgx_status_t rt = SGX_SUCCESS;
  412. if(initialized==false) {
  413. rt = sgx_read_rand((unsigned char*) random_seed, SGX_AESCTR_KEY_SIZE);
  414. if(rt!=SGX_SUCCESS){
  415. printf("Failed sgx_read_rand (%x)", rt);
  416. return rt;
  417. }
  418. rt = sgx_read_rand((unsigned char*) counter, SGX_AESCTR_KEY_SIZE);
  419. if(rt!=SGX_SUCCESS){
  420. printf("Failed sgx_read_rand (%x)", rt);
  421. return rt;
  422. }
  423. initialized=true;
  424. }
  425. char zeroes[buffer_size];
  426. // We don't bother initializing to zeroes since AES_CTR just adds the PRB_stream to the buffer
  427. // Use AES CTR to populate random_bytes
  428. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) zeroes, buffer_size,
  429. (uint8_t*) counter, CTR_INC_BITS, random_bytes);
  430. *(uint64_t*)counter += 1;
  431. if(rt!=SGX_SUCCESS){
  432. printf("Failed sgx_aes_ctr_encrypt (%x) in init_getRandomBytes\n", rt);
  433. return rt;
  434. }
  435. random_bytes_left = PRB_BUFFER_SIZE;
  436. random_bytes_ptr = random_bytes;
  437. return rt;
  438. }
  439. sgx_status_t PRB_buffer::getRandomBytes(unsigned char *buffer, size_t size) {
  440. sgx_status_t rt = SGX_SUCCESS;
  441. if(initialized==false)
  442. init_PRB_buffer();
  443. if(size < random_bytes_left) {
  444. // Supply buffer with random bytes from random_bytes
  445. memcpy(buffer, random_bytes_ptr, size);
  446. random_bytes_ptr+=size;
  447. random_bytes_left-= size;
  448. return rt;
  449. } else {
  450. // Consume all the random bytes we have left
  451. unsigned char *ptr = buffer;
  452. size_t size_left_for_req = size - random_bytes_left;
  453. memcpy(ptr, random_bytes_ptr, random_bytes_left);
  454. ptr+= random_bytes_left;
  455. // Use AES CTR to populate random_bytes
  456. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) random_bytes, PRB_BUFFER_SIZE,
  457. (uint8_t*) counter, CTR_INC_BITS, random_bytes);
  458. *(uint64_t*)counter += 1;
  459. if(rt!=SGX_SUCCESS){
  460. printf("Failed sgx_aes_ctr_encrypt (%x)", rt);
  461. return rt;
  462. }
  463. random_bytes_left = PRB_BUFFER_SIZE;
  464. random_bytes_ptr = random_bytes;
  465. // Add size_left_for_req random bytes to the buffer
  466. memcpy(ptr, random_bytes_ptr, size_left_for_req);
  467. random_bytes_ptr+=size_left_for_req;
  468. random_bytes_left-=size_left_for_req;
  469. return rt;
  470. }
  471. }
  472. /*
  473. sgx_status_t PRB_buffer::getBulkRandomBytes(unsigned char *buffer, size_t size) {
  474. sgx_status_t rt = SGX_SUCCESS;
  475. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) buffer, size,
  476. (uint8_t*) counter, CTR_INC_BITS, buffer);
  477. *(uint64_t*)counter += 1;
  478. if(rt!=SGX_SUCCESS){
  479. printf("Failed sgx_aes_ctr_encrypt (%x) in getBulkRandomBytes [%p %p %lu %p %d %p]\n", rt, random_seed, (const uint8_t*) buffer, size, (uint8_t*) counter, CTR_INC_BITS, buffer);
  480. return rt;
  481. }
  482. return rt;
  483. }
  484. sgx_status_t initialize_BRB() {
  485. sgx_status_t rt = SGX_SUCCESS;
  486. rt = sgx_read_rand((unsigned char*) bulk_random_seed, SGX_AESCTR_KEY_SIZE);
  487. if(rt!=SGX_SUCCESS){
  488. printf("initialize_BRB(): Failed sgx_read_rand (%x)", rt);
  489. return rt;
  490. }
  491. rt = sgx_read_rand((unsigned char*) bulk_counter, SGX_AESCTR_KEY_SIZE);
  492. if(rt!=SGX_SUCCESS){
  493. printf("initialize_BRB(): Failed sgx_read_rand (%x)", rt);
  494. return rt;
  495. }
  496. bulk_initialized = true;
  497. return rt;
  498. }
  499. sgx_status_t getBulkRandomBytes(unsigned char *buffer, size_t size) {
  500. if(bulk_initialized == false){
  501. initialize_BRB();
  502. }
  503. sgx_status_t rt = SGX_SUCCESS;
  504. rt = sgx_aes_ctr_encrypt(bulk_random_seed, (const uint8_t*) buffer, size,
  505. (uint8_t*) bulk_counter, CTR_INC_BITS, buffer);
  506. if(rt!=SGX_SUCCESS){
  507. printf("getBulkRandomBytes: Failed sgx_aes_ctr_encrypt (%x) in getBulkRandomBytes [%p %p %lu %p %d %p]\n", rt, bulk_random_seed, (const uint8_t*) buffer, size, (uint8_t*) bulk_counter, CTR_INC_BITS, buffer);
  508. return rt;
  509. }
  510. return rt;
  511. }
  512. */
  513. #else
  514. sgx_status_t getRandomBytes(unsigned char *random_bytes, size_t size) {
  515. sgx_status_t rt = SGX_SUCCESS;
  516. rt = sgx_read_rand((unsigned char*) random_bytes, size);
  517. return rt;
  518. }
  519. #endif
  520. unsigned char* compare_keys(unsigned char *packet_1, unsigned char *packet_2){
  521. if( *((uint64_t*)(packet_1)) < *((uint64_t*)(packet_2))){
  522. return packet_1;
  523. }
  524. else {
  525. return packet_2;
  526. }
  527. }
  528. void merge(unsigned char *data, size_t data_size, size_t l, size_t m, size_t r, unsigned char* (*comparator)(unsigned char*, unsigned char*)){
  529. uint64_t i=0, j=0, k=0;
  530. size_t s1, s2;
  531. s1 = l+(m-l+1);
  532. s2 = (m+1)+(r-m);
  533. //unsigned char merged_array[(r-l+1)*data_size];
  534. unsigned char *merged_array = (unsigned char*) malloc((r-l+1)*data_size);
  535. i = l;
  536. j = m+1;
  537. k = 0;
  538. while (i < s1 && j < s2) {
  539. unsigned char *smaller_pkt = comparator(data+(i*data_size), data+(j*data_size));
  540. if(smaller_pkt == data+(i*data_size)){
  541. memcpy(merged_array+(k*data_size), smaller_pkt, data_size);
  542. i++;
  543. }
  544. else{
  545. memcpy(merged_array+(k*data_size), smaller_pkt, data_size);
  546. j++;
  547. }
  548. k++;
  549. }
  550. while (i < s1) {
  551. memcpy(merged_array + (k*data_size), data+(i*data_size), data_size);
  552. i++;
  553. k++;
  554. }
  555. while (j < s2) {
  556. memcpy(merged_array + (k*data_size), data+(j*data_size), data_size);
  557. j++;
  558. k++;
  559. }
  560. memcpy(data+(l*data_size), merged_array, data_size * ((r-l)+1));
  561. free(merged_array);
  562. }
  563. void mergeSort(unsigned char *data, size_t data_size, size_t start_index, size_t end_index, unsigned char* (*comparator)(unsigned char*, unsigned char*)){
  564. if(start_index < end_index){
  565. size_t m = start_index + (end_index-start_index)/2;
  566. mergeSort(data, data_size, start_index, m, comparator);
  567. mergeSort(data, data_size, m+1, end_index, comparator);
  568. merge(data, data_size, start_index, m , end_index, comparator);
  569. }
  570. }
  571. void mergeSort_OPRM(unsigned char *data, size_t data_size, size_t start_index, size_t end_index, unsigned char* (*comparator)(unsigned char*, unsigned char*)){
  572. if(start_index < end_index){
  573. size_t m = start_index + (end_index-start_index)/2;
  574. mergeSort(data, data_size, start_index, m, comparator);
  575. mergeSort(data, data_size, m+1, end_index, comparator);
  576. merge(data, data_size, start_index, m , end_index, comparator);
  577. }
  578. }
  579. #if 0
  580. //Tight Compaction and Expansion utility functions for testing if a Block is real/dummy
  581. uint8_t isBlockReal_16(unsigned char *block_ptr) {
  582. uint16_t label = *((uint16_t *)(block_ptr));
  583. return (label==UINT16_MAX);
  584. }
  585. uint8_t isBlockReal_32(unsigned char *block_ptr) {
  586. uint32_t label = *((uint32_t *)(block_ptr));
  587. return (label==UINT32_MAX);
  588. }
  589. uint8_t isBlockReal_64(unsigned char *block_ptr) {
  590. uint64_t label = *((uint64_t *)(block_ptr));
  591. return (label==UINT64_MAX);
  592. }
  593. void oswap_buffer(unsigned char *dest, unsigned char *source, uint32_t buffer_size, uint8_t flag){
  594. #ifdef COUNT_OSWAPS
  595. uint64_t *ltvp = &OSWAP_COUNTER;
  596. FOAV_SAFE2_CNTXT(oswap_buffer, buffer_size, *ltvp)
  597. OSWAP_COUNTER++;
  598. #endif
  599. if(buffer_size%16==0){
  600. oswap_buffer_16x(dest, source, buffer_size, flag);
  601. } else if(buffer_size==8){
  602. oswap_buffer_byte(dest, source, buffer_size, flag);
  603. }
  604. else{
  605. oswap_buffer_byte(dest, source, 8, flag);
  606. oswap_buffer_16x(dest+8, source+8, buffer_size-8, flag);
  607. }
  608. }
  609. uint8_t isCorrect16x(uint32_t block_size){
  610. printf("Entered Correctness Tester!!!\n");
  611. bool is_correct = true;
  612. unsigned char *b1 = new unsigned char[block_size];
  613. unsigned char *b2 = new unsigned char[block_size];
  614. unsigned char *b3 = new unsigned char[block_size];
  615. unsigned char *b4 = new unsigned char[block_size];
  616. getBulkRandomBytes(b1, block_size);
  617. getBulkRandomBytes(b2, block_size);
  618. memcpy(b3, b1, block_size);
  619. memcpy(b4, b2, block_size);
  620. bool swap_flag = false;
  621. oswap_buffer<OSWAP_16X>(b1, b2, block_size, swap_flag);
  622. if(memcmp(b1, b3, block_size)){
  623. is_correct=false;
  624. printf("Failed Test 1\n");
  625. }
  626. if(memcmp(b2, b4, block_size)){
  627. is_correct=false;
  628. printf("Failed Test 2\n");
  629. }
  630. memcpy(b1, b3, block_size);
  631. memcpy(b2, b4, block_size);
  632. swap_flag = true;
  633. oswap_buffer<OSWAP_16X>(b1, b2, block_size, swap_flag);
  634. if(memcmp(b1, b4, block_size)){
  635. is_correct=false;
  636. printf("Failed Test 3\n");
  637. }
  638. if(memcmp(b2, b3, block_size)){
  639. is_correct=false;
  640. printf("Failed Test 4\n");
  641. }
  642. delete []b1;
  643. delete []b2;
  644. delete []b3;
  645. delete []b4;
  646. if(is_correct){
  647. printf("Correctness test SUCCESS! \n");
  648. return true;
  649. }
  650. return false;
  651. }
  652. uint8_t isCorrect8_16x(uint32_t block_size){
  653. printf("Entered Correctness Tester!!!\n");
  654. bool is_correct = true;
  655. unsigned char *b1 = new unsigned char[block_size];
  656. unsigned char *b2 = new unsigned char[block_size];
  657. unsigned char *b3 = new unsigned char[block_size];
  658. unsigned char *b4 = new unsigned char[block_size];
  659. getBulkRandomBytes(b1, block_size);
  660. getBulkRandomBytes(b2, block_size);
  661. memcpy(b3, b1, block_size);
  662. memcpy(b4, b2, block_size);
  663. bool swap_flag = false;
  664. oswap_buffer<OSWAP_8_16X>(b1, b2, block_size, swap_flag);
  665. if(memcmp(b1, b3, block_size)){
  666. is_correct=false;
  667. printf("Failed Test 1\n");
  668. }
  669. if(memcmp(b2, b4, block_size)){
  670. is_correct=false;
  671. printf("Failed Test 2\n");
  672. }
  673. memcpy(b1, b3, block_size);
  674. memcpy(b2, b4, block_size);
  675. swap_flag = true;
  676. oswap_buffer<OSWAP_8_16X>(b1, b2, block_size, swap_flag);
  677. if(memcmp(b1, b4, block_size)){
  678. is_correct=false;
  679. printf("Failed Test 3\n");
  680. }
  681. if(memcmp(b2, b3, block_size)){
  682. is_correct=false;
  683. printf("Failed Test 4\n");
  684. }
  685. delete []b1;
  686. delete []b2;
  687. delete []b3;
  688. delete []b4;
  689. if(is_correct){
  690. printf("Correctness test SUCCESS! \n");
  691. return true;
  692. }
  693. return false;
  694. }
  695. void swapBuckets(unsigned char *bkt1, unsigned char *bkt2, unsigned char *temp_bucket, size_t bucket_size) {
  696. memcpy(temp_bucket, bkt2, bucket_size);
  697. memcpy(bkt2, bkt1, bucket_size);
  698. memcpy(bkt1, temp_bucket, bucket_size);
  699. }
  700. #endif
  701. /*** Thread pool implementation ***/
  702. /* Implements a restricted-model thread pool. The restriction is that
  703. * every thread is the "parent" of a number of other threads (and no
  704. * thread has more than one parent). Each thread can be dispatched and
  705. * joined only by its parent, so there's no contention on the dispatch
  706. * and join inter-thread communication. A parent thread has to specify
  707. * the exact thread id of the child thread it dispatches work to. */
  708. thread_local threadid_t g_thread_id = 0;
  709. enum threadstate_t {
  710. THREADSTATE_NONE,
  711. THREADSTATE_WAITING,
  712. THREADSTATE_DISPATCHING,
  713. THREADSTATE_WORKING,
  714. THREADSTATE_TERMINATE
  715. };
  716. struct threadblock_t {
  717. threadid_t threadid;
  718. threadstate_t state;
  719. pthread_t thread_handle;
  720. pthread_mutex_t mutex;
  721. pthread_cond_t dispatch_cond;
  722. void *(*dispatch_func)(void *data);
  723. void *dispatch_data;
  724. pthread_cond_t join_cond;
  725. void *ret_data;
  726. #ifdef COUNT_OSWAPS
  727. size_t num_oswaps;
  728. #endif
  729. };
  730. static threadblock_t *threadpool_control_blocks = NULL;
  731. static threadid_t threadpool_numthreads = 0;
  732. /* The main thread loop */
  733. static void* threadloop(void *vdata) {
  734. threadblock_t *block = (threadblock_t *)vdata;
  735. /* Initialize any per-thread state */
  736. g_thread_id = block->threadid;
  737. PRB_rand_bits = 0;
  738. PRB_rand_bits_remaining = 0;
  739. pthread_mutex_lock(&block->mutex);
  740. while(1) {
  741. /* Wait for work */
  742. block->state = THREADSTATE_WAITING;
  743. pthread_cond_wait(&block->dispatch_cond, &block->mutex);
  744. if (block->state == THREADSTATE_TERMINATE) {
  745. break;
  746. }
  747. /* Do the work */
  748. block->state = THREADSTATE_WORKING;
  749. pthread_mutex_unlock(&block->mutex);
  750. block->ret_data = (block->dispatch_func)(block->dispatch_data);
  751. #ifdef COUNT_OSWAPS
  752. /* Account for the oswaps done in this thread */
  753. block->num_oswaps = OSWAP_COUNTER;
  754. OSWAP_COUNTER = 0;
  755. #endif
  756. /* Signal the parent thread that we're done, and loop back to
  757. * wait for more work. */
  758. pthread_mutex_lock(&block->mutex);
  759. pthread_cond_signal(&block->join_cond);
  760. }
  761. block->state = THREADSTATE_NONE;
  762. pthread_mutex_unlock(&block->mutex);
  763. return NULL;
  764. }
  765. /* Create the threadpool, with numthreads-1 additional threads (numbered
  766. * 1 through numthreads-1) in addition to the current "main" thread
  767. * (numbered 0). Returns 0 on success, -1 on failure. It is allowed, but
  768. * not very useful, to pass 1 here. */
  769. int threadpool_init(threadid_t numthreads) {
  770. g_thread_id = 0;
  771. PRB_rand_bits = 0;
  772. PRB_rand_bits_remaining = 0;
  773. if (numthreads < 1) {
  774. return -1;
  775. } else if (numthreads == 1) {
  776. threadpool_numthreads = 1;
  777. return 0;
  778. }
  779. /* We don't actually create a thread control block for the main
  780. * thread 0, so the internal indexing into this array will be that
  781. * thread i's control block lives at index i-1 in this array. */
  782. threadpool_control_blocks = new threadblock_t[numthreads-1];
  783. if (threadpool_control_blocks == NULL) {
  784. return -1;
  785. }
  786. threadpool_numthreads = numthreads;
  787. /* Init each thread control block */
  788. bool thread_create_failure = false;
  789. for (threadid_t i = 0; i < numthreads-1; ++i) {
  790. threadblock_t *block = threadpool_control_blocks + i;
  791. block->threadid = i+1;
  792. block->state = THREADSTATE_NONE;
  793. pthread_mutex_init(&block->mutex, NULL);
  794. pthread_cond_init(&block->dispatch_cond, NULL);
  795. pthread_cond_init(&block->join_cond, NULL);
  796. block->thread_handle = NULL;
  797. int create_ret =
  798. pthread_create(&block->thread_handle, NULL, threadloop, block);
  799. if (create_ret) {
  800. thread_create_failure = true;
  801. printf("Failed to launch thread %lu; ret=%d\n", i+1, create_ret);
  802. }
  803. }
  804. if (thread_create_failure) {
  805. threadpool_shutdown();
  806. return -1;
  807. }
  808. return 0;
  809. }
  810. /* Ask all the threads to terminate, wait for that to happen, and clean
  811. * up. */
  812. void threadpool_shutdown() {
  813. /* Note that this function may be called when some threads failed to
  814. * launch at all in threadpool_init. In that case, the thread field
  815. * in the thread's control block will be NULL. The mutex/cond
  816. * variables will still have been initialized, however, and need
  817. * cleaning. */
  818. if (threadpool_numthreads == 0) {
  819. /* Nothing to do */
  820. return;
  821. }
  822. if (threadpool_numthreads == 1) {
  823. /* Almost nothing to do */
  824. threadpool_numthreads = 0;
  825. return;
  826. }
  827. for (threadid_t i=0;i<threadpool_numthreads-1; ++i) {
  828. threadblock_t *block = threadpool_control_blocks + i;
  829. pthread_mutex_lock(&block->mutex);
  830. if (block->state == THREADSTATE_WORKING) {
  831. /* There's a thread actively running? Wait for it to
  832. * finish. */
  833. pthread_mutex_unlock(&block->mutex);
  834. threadpool_join(i+1, NULL);
  835. pthread_mutex_lock(&block->mutex);
  836. }
  837. if (block->state == THREADSTATE_WAITING) {
  838. /* Tell the thread to exit */
  839. block->state = THREADSTATE_TERMINATE;
  840. pthread_mutex_unlock(&block->mutex);
  841. pthread_cond_signal(&block->dispatch_cond);
  842. pthread_join(block->thread_handle, NULL);
  843. block->thread_handle = NULL;
  844. }
  845. if (block->state != THREADSTATE_NONE) {
  846. printf("Unexpected state on thread %lu during shutdown: %u\n", i+1, block->state);
  847. pthread_cond_destroy(&block->dispatch_cond);
  848. pthread_cond_destroy(&block->join_cond);
  849. pthread_mutex_destroy(&block->mutex);
  850. }
  851. }
  852. delete[] threadpool_control_blocks;
  853. threadpool_control_blocks = NULL;
  854. threadpool_numthreads = 0;
  855. }
  856. /* Dispatch some work to a particular thread in the thread pool. */
  857. void threadpool_dispatch(threadid_t threadid, void *(*func)(void*),
  858. void *data) {
  859. threadblock_t *block = threadpool_control_blocks + (threadid-1);
  860. pthread_mutex_lock(&block->mutex);
  861. if (block->state != THREADSTATE_WAITING) {
  862. printf("Thread %lu not in expected WAITING state: %u\n",
  863. threadid, block->state);
  864. pthread_mutex_unlock(&block->mutex);
  865. return;
  866. }
  867. block->dispatch_func = func;
  868. block->dispatch_data = data;
  869. block->state = THREADSTATE_DISPATCHING;
  870. pthread_mutex_unlock(&block->mutex);
  871. /* Tell the thread there's work to do */
  872. pthread_cond_signal(&block->dispatch_cond);
  873. }
  874. /* Join a thread */
  875. void threadpool_join(threadid_t threadid, void **resp) {
  876. threadblock_t *block = threadpool_control_blocks + (threadid-1);
  877. pthread_mutex_lock(&block->mutex);
  878. /* Did the thread finish already? */
  879. if (block->state == THREADSTATE_DISPATCHING ||
  880. block->state == THREADSTATE_WORKING) {
  881. /* Wait until the thread completes */
  882. pthread_cond_wait(&block->join_cond, &block->mutex);
  883. } else if (block->state != THREADSTATE_WAITING) {
  884. printf("Thread %lu in unexpected state (not WORKING or WAITING) on join: %u\n",
  885. threadid, block->state);
  886. }
  887. if (resp) {
  888. *resp = block->ret_data;
  889. }
  890. #ifdef COUNT_OSWAPS
  891. uint64_t *ltvp = &OSWAP_COUNTER;
  892. FOAV_SAFE_CNTXT(oswap_buffer, *ltvp)
  893. OSWAP_COUNTER += block->num_oswaps;
  894. block->num_oswaps = 0;
  895. #endif
  896. pthread_mutex_unlock(&block->mutex);
  897. }