utils.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. // Returns largest power of two greater than N
  308. uint64_t pow2_gt(uint64_t N) {
  309. uint64_t N1 = 1;
  310. while (N1 < N) {
  311. N1 <<= 1;
  312. }
  313. return N1;
  314. }
  315. #ifndef BEFTS_MODE
  316. /*
  317. * printf:
  318. * Invokes OCALL to display the enclave buffer to the terminal.
  319. */
  320. void printf(const char *fmt, ...)
  321. {
  322. char buf[BUFSIZ] = {'\0'};
  323. va_list ap;
  324. va_start(ap, fmt);
  325. vsnprintf(buf, BUFSIZ, fmt, ap);
  326. va_end(ap);
  327. ocall_print_string(buf);
  328. }
  329. /*
  330. * printf_with_rtclock:
  331. * Invokes OCALL to display the enclave buffer to the terminal with a
  332. * timestamp and returns the timestamp.
  333. */
  334. unsigned long printf_with_rtclock(const char *fmt, ...)
  335. {
  336. unsigned long ret;
  337. char buf[BUFSIZ] = {'\0'};
  338. va_list ap;
  339. va_start(ap, fmt);
  340. vsnprintf(buf, BUFSIZ, fmt, ap);
  341. va_end(ap);
  342. ocall_print_string_with_rtclock(&ret, buf);
  343. return ret;
  344. }
  345. /*
  346. * printf_with_rtclock_diff:
  347. * Invokes OCALL to display the enclave buffer to the terminal with a
  348. * timestamp and returns the timestamp. Also prints the difference from
  349. * the before timestamp.
  350. */
  351. unsigned long printf_with_rtclock_diff(unsigned long before, const char *fmt, ...)
  352. {
  353. unsigned long ret;
  354. char buf[BUFSIZ] = {'\0'};
  355. va_list ap;
  356. va_start(ap, fmt);
  357. vsnprintf(buf, BUFSIZ, fmt, ap);
  358. va_end(ap);
  359. ocall_print_string_with_rtclock_diff(&ret, buf, before);
  360. return ret;
  361. }
  362. #endif
  363. #if 0
  364. void displayORPPacket(unsigned char* packet_in, size_t block_size) {
  365. unsigned char *packet_ptr = packet_in;
  366. uint64_t evict_stream, ORP_label, key;
  367. unsigned char data[block_size];
  368. memcpy(&evict_stream, packet_ptr, sizeof(uint64_t));
  369. packet_ptr+=sizeof(uint64_t);
  370. memcpy(&ORP_label, packet_ptr, sizeof(uint64_t));
  371. packet_ptr+=sizeof(uint64_t);
  372. memcpy(&key, packet_ptr, sizeof(uint64_t));
  373. packet_ptr+=sizeof(uint64_t);
  374. memcpy(data, packet_ptr, block_size);
  375. data[block_size]='\0';
  376. printf("(evict_stream = %ld, ORP_label = %ld, Key = %ld)\n",
  377. evict_stream, ORP_label, key);
  378. //printf("Hex of data is :");
  379. //for(int i=0;i<DATA_SIZE;++i) printf("%02x", data[i]); printf("\n");
  380. }
  381. // isDummy and setDummy works on real packets : <Key, Data>
  382. bool isDummy(unsigned char *ptr_to_serialized_packet){
  383. return(((uint64_t*) ptr_to_serialized_packet)[0] == UINT64_MAX);
  384. }
  385. void setDummy(unsigned char *ptr_to_serialized_packet){
  386. ((uint64_t*) ptr_to_serialized_packet)[0] = UINT64_MAX;
  387. }
  388. // isORPDummy and setORPDummy works on ORP packets : <Eviction_stream, ORP_label, Key, Data>
  389. bool isORPDummy(unsigned char *ptr_to_serialized_packet){
  390. return(((uint64_t*) ptr_to_serialized_packet)[1] == UINT64_MAX);
  391. }
  392. void setORPDummy(unsigned char *ptr_to_packet){
  393. ((uint64_t*) ptr_to_packet)[0] = UINT64_MAX;
  394. ((uint64_t*) ptr_to_packet)[1] = UINT64_MAX;
  395. ((uint64_t*) ptr_to_packet)[2] = UINT64_MAX;
  396. }
  397. size_t packetsConsumedUptoMSN(signed long msn_no, size_t msns_with_extra_packets, size_t packets_per_entry_msn) {
  398. if(msn_no<0)
  399. return 0;
  400. if(msn_no<=msns_with_extra_packets){
  401. return (msn_no * (packets_per_entry_msn+1));
  402. }
  403. else{
  404. size_t reg_msn = msn_no - msns_with_extra_packets;
  405. return ((reg_msn * packets_per_entry_msn) + (msns_with_extra_packets * packets_per_entry_msn));
  406. }
  407. }
  408. #endif
  409. #ifdef USE_PRB
  410. void PRB_pool_init(int nthreads) {
  411. // Nothing needs to be done any more
  412. }
  413. void PRB_pool_shutdown() {
  414. // Nothing needs to be done any more
  415. }
  416. PRB_buffer::PRB_buffer() {
  417. }
  418. sgx_status_t PRB_buffer::init_PRB_buffer(uint32_t buffer_size = PRB_BUFFER_SIZE) {
  419. sgx_status_t rt = SGX_SUCCESS;
  420. if(initialized==false) {
  421. rt = sgx_read_rand((unsigned char*) random_seed, SGX_AESCTR_KEY_SIZE);
  422. if(rt!=SGX_SUCCESS){
  423. printf("Failed sgx_read_rand (%x)", rt);
  424. return rt;
  425. }
  426. rt = sgx_read_rand((unsigned char*) counter, SGX_AESCTR_KEY_SIZE);
  427. if(rt!=SGX_SUCCESS){
  428. printf("Failed sgx_read_rand (%x)", rt);
  429. return rt;
  430. }
  431. initialized=true;
  432. }
  433. char zeroes[buffer_size];
  434. // We don't bother initializing to zeroes since AES_CTR just adds the PRB_stream to the buffer
  435. // Use AES CTR to populate random_bytes
  436. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) zeroes, buffer_size,
  437. (uint8_t*) counter, CTR_INC_BITS, random_bytes);
  438. *(uint64_t*)counter += 1;
  439. if(rt!=SGX_SUCCESS){
  440. printf("Failed sgx_aes_ctr_encrypt (%x) in init_getRandomBytes\n", rt);
  441. return rt;
  442. }
  443. random_bytes_left = PRB_BUFFER_SIZE;
  444. random_bytes_ptr = random_bytes;
  445. return rt;
  446. }
  447. sgx_status_t PRB_buffer::getRandomBytes(unsigned char *buffer, size_t size) {
  448. sgx_status_t rt = SGX_SUCCESS;
  449. if(initialized==false)
  450. init_PRB_buffer();
  451. if(size < random_bytes_left) {
  452. // Supply buffer with random bytes from random_bytes
  453. memcpy(buffer, random_bytes_ptr, size);
  454. random_bytes_ptr+=size;
  455. random_bytes_left-= size;
  456. return rt;
  457. } else {
  458. // Consume all the random bytes we have left
  459. unsigned char *ptr = buffer;
  460. size_t size_left_for_req = size - random_bytes_left;
  461. memcpy(ptr, random_bytes_ptr, random_bytes_left);
  462. ptr+= random_bytes_left;
  463. // Use AES CTR to populate random_bytes
  464. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) random_bytes, PRB_BUFFER_SIZE,
  465. (uint8_t*) counter, CTR_INC_BITS, random_bytes);
  466. *(uint64_t*)counter += 1;
  467. if(rt!=SGX_SUCCESS){
  468. printf("Failed sgx_aes_ctr_encrypt (%x)", rt);
  469. return rt;
  470. }
  471. random_bytes_left = PRB_BUFFER_SIZE;
  472. random_bytes_ptr = random_bytes;
  473. // Add size_left_for_req random bytes to the buffer
  474. memcpy(ptr, random_bytes_ptr, size_left_for_req);
  475. random_bytes_ptr+=size_left_for_req;
  476. random_bytes_left-=size_left_for_req;
  477. return rt;
  478. }
  479. }
  480. /*
  481. sgx_status_t PRB_buffer::getBulkRandomBytes(unsigned char *buffer, size_t size) {
  482. sgx_status_t rt = SGX_SUCCESS;
  483. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) buffer, size,
  484. (uint8_t*) counter, CTR_INC_BITS, buffer);
  485. *(uint64_t*)counter += 1;
  486. if(rt!=SGX_SUCCESS){
  487. 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);
  488. return rt;
  489. }
  490. return rt;
  491. }
  492. sgx_status_t initialize_BRB() {
  493. sgx_status_t rt = SGX_SUCCESS;
  494. rt = sgx_read_rand((unsigned char*) bulk_random_seed, SGX_AESCTR_KEY_SIZE);
  495. if(rt!=SGX_SUCCESS){
  496. printf("initialize_BRB(): Failed sgx_read_rand (%x)", rt);
  497. return rt;
  498. }
  499. rt = sgx_read_rand((unsigned char*) bulk_counter, SGX_AESCTR_KEY_SIZE);
  500. if(rt!=SGX_SUCCESS){
  501. printf("initialize_BRB(): Failed sgx_read_rand (%x)", rt);
  502. return rt;
  503. }
  504. bulk_initialized = true;
  505. return rt;
  506. }
  507. sgx_status_t getBulkRandomBytes(unsigned char *buffer, size_t size) {
  508. if(bulk_initialized == false){
  509. initialize_BRB();
  510. }
  511. sgx_status_t rt = SGX_SUCCESS;
  512. rt = sgx_aes_ctr_encrypt(bulk_random_seed, (const uint8_t*) buffer, size,
  513. (uint8_t*) bulk_counter, CTR_INC_BITS, buffer);
  514. if(rt!=SGX_SUCCESS){
  515. 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);
  516. return rt;
  517. }
  518. return rt;
  519. }
  520. */
  521. #else
  522. sgx_status_t getRandomBytes(unsigned char *random_bytes, size_t size) {
  523. sgx_status_t rt = SGX_SUCCESS;
  524. rt = sgx_read_rand((unsigned char*) random_bytes, size);
  525. return rt;
  526. }
  527. #endif
  528. unsigned char* compare_keys(unsigned char *packet_1, unsigned char *packet_2){
  529. if( *((uint64_t*)(packet_1)) < *((uint64_t*)(packet_2))){
  530. return packet_1;
  531. }
  532. else {
  533. return packet_2;
  534. }
  535. }
  536. 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*)){
  537. uint64_t i=0, j=0, k=0;
  538. size_t s1, s2;
  539. s1 = l+(m-l+1);
  540. s2 = (m+1)+(r-m);
  541. //unsigned char merged_array[(r-l+1)*data_size];
  542. unsigned char *merged_array = (unsigned char*) malloc((r-l+1)*data_size);
  543. i = l;
  544. j = m+1;
  545. k = 0;
  546. while (i < s1 && j < s2) {
  547. unsigned char *smaller_pkt = comparator(data+(i*data_size), data+(j*data_size));
  548. if(smaller_pkt == data+(i*data_size)){
  549. memcpy(merged_array+(k*data_size), smaller_pkt, data_size);
  550. i++;
  551. }
  552. else{
  553. memcpy(merged_array+(k*data_size), smaller_pkt, data_size);
  554. j++;
  555. }
  556. k++;
  557. }
  558. while (i < s1) {
  559. memcpy(merged_array + (k*data_size), data+(i*data_size), data_size);
  560. i++;
  561. k++;
  562. }
  563. while (j < s2) {
  564. memcpy(merged_array + (k*data_size), data+(j*data_size), data_size);
  565. j++;
  566. k++;
  567. }
  568. memcpy(data+(l*data_size), merged_array, data_size * ((r-l)+1));
  569. free(merged_array);
  570. }
  571. void mergeSort(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. 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*)){
  580. if(start_index < end_index){
  581. size_t m = start_index + (end_index-start_index)/2;
  582. mergeSort(data, data_size, start_index, m, comparator);
  583. mergeSort(data, data_size, m+1, end_index, comparator);
  584. merge(data, data_size, start_index, m , end_index, comparator);
  585. }
  586. }
  587. #if 0
  588. //Tight Compaction and Expansion utility functions for testing if a Block is real/dummy
  589. uint8_t isBlockReal_16(unsigned char *block_ptr) {
  590. uint16_t label = *((uint16_t *)(block_ptr));
  591. return (label==UINT16_MAX);
  592. }
  593. uint8_t isBlockReal_32(unsigned char *block_ptr) {
  594. uint32_t label = *((uint32_t *)(block_ptr));
  595. return (label==UINT32_MAX);
  596. }
  597. uint8_t isBlockReal_64(unsigned char *block_ptr) {
  598. uint64_t label = *((uint64_t *)(block_ptr));
  599. return (label==UINT64_MAX);
  600. }
  601. void oswap_buffer(unsigned char *dest, unsigned char *source, uint32_t buffer_size, uint8_t flag){
  602. #ifdef COUNT_OSWAPS
  603. uint64_t *ltvp = &OSWAP_COUNTER;
  604. FOAV_SAFE2_CNTXT(oswap_buffer, buffer_size, *ltvp)
  605. OSWAP_COUNTER++;
  606. #endif
  607. if(buffer_size%16==0){
  608. oswap_buffer_16x(dest, source, buffer_size, flag);
  609. } else if(buffer_size==8){
  610. oswap_buffer_byte(dest, source, buffer_size, flag);
  611. }
  612. else{
  613. oswap_buffer_byte(dest, source, 8, flag);
  614. oswap_buffer_16x(dest+8, source+8, buffer_size-8, flag);
  615. }
  616. }
  617. uint8_t isCorrect16x(uint32_t block_size){
  618. printf("Entered Correctness Tester!!!\n");
  619. bool is_correct = true;
  620. unsigned char *b1 = new unsigned char[block_size];
  621. unsigned char *b2 = new unsigned char[block_size];
  622. unsigned char *b3 = new unsigned char[block_size];
  623. unsigned char *b4 = new unsigned char[block_size];
  624. getBulkRandomBytes(b1, block_size);
  625. getBulkRandomBytes(b2, block_size);
  626. memcpy(b3, b1, block_size);
  627. memcpy(b4, b2, block_size);
  628. bool swap_flag = false;
  629. oswap_buffer<OSWAP_16X>(b1, b2, block_size, swap_flag);
  630. if(memcmp(b1, b3, block_size)){
  631. is_correct=false;
  632. printf("Failed Test 1\n");
  633. }
  634. if(memcmp(b2, b4, block_size)){
  635. is_correct=false;
  636. printf("Failed Test 2\n");
  637. }
  638. memcpy(b1, b3, block_size);
  639. memcpy(b2, b4, block_size);
  640. swap_flag = true;
  641. oswap_buffer<OSWAP_16X>(b1, b2, block_size, swap_flag);
  642. if(memcmp(b1, b4, block_size)){
  643. is_correct=false;
  644. printf("Failed Test 3\n");
  645. }
  646. if(memcmp(b2, b3, block_size)){
  647. is_correct=false;
  648. printf("Failed Test 4\n");
  649. }
  650. delete []b1;
  651. delete []b2;
  652. delete []b3;
  653. delete []b4;
  654. if(is_correct){
  655. printf("Correctness test SUCCESS! \n");
  656. return true;
  657. }
  658. return false;
  659. }
  660. uint8_t isCorrect8_16x(uint32_t block_size){
  661. printf("Entered Correctness Tester!!!\n");
  662. bool is_correct = true;
  663. unsigned char *b1 = new unsigned char[block_size];
  664. unsigned char *b2 = new unsigned char[block_size];
  665. unsigned char *b3 = new unsigned char[block_size];
  666. unsigned char *b4 = new unsigned char[block_size];
  667. getBulkRandomBytes(b1, block_size);
  668. getBulkRandomBytes(b2, block_size);
  669. memcpy(b3, b1, block_size);
  670. memcpy(b4, b2, block_size);
  671. bool swap_flag = false;
  672. oswap_buffer<OSWAP_8_16X>(b1, b2, block_size, swap_flag);
  673. if(memcmp(b1, b3, block_size)){
  674. is_correct=false;
  675. printf("Failed Test 1\n");
  676. }
  677. if(memcmp(b2, b4, block_size)){
  678. is_correct=false;
  679. printf("Failed Test 2\n");
  680. }
  681. memcpy(b1, b3, block_size);
  682. memcpy(b2, b4, block_size);
  683. swap_flag = true;
  684. oswap_buffer<OSWAP_8_16X>(b1, b2, block_size, swap_flag);
  685. if(memcmp(b1, b4, block_size)){
  686. is_correct=false;
  687. printf("Failed Test 3\n");
  688. }
  689. if(memcmp(b2, b3, block_size)){
  690. is_correct=false;
  691. printf("Failed Test 4\n");
  692. }
  693. delete []b1;
  694. delete []b2;
  695. delete []b3;
  696. delete []b4;
  697. if(is_correct){
  698. printf("Correctness test SUCCESS! \n");
  699. return true;
  700. }
  701. return false;
  702. }
  703. void swapBuckets(unsigned char *bkt1, unsigned char *bkt2, unsigned char *temp_bucket, size_t bucket_size) {
  704. memcpy(temp_bucket, bkt2, bucket_size);
  705. memcpy(bkt2, bkt1, bucket_size);
  706. memcpy(bkt1, temp_bucket, bucket_size);
  707. }
  708. #endif
  709. /*** Thread pool implementation ***/
  710. /* Implements a restricted-model thread pool. The restriction is that
  711. * every thread is the "parent" of a number of other threads (and no
  712. * thread has more than one parent). Each thread can be dispatched and
  713. * joined only by its parent, so there's no contention on the dispatch
  714. * and join inter-thread communication. A parent thread has to specify
  715. * the exact thread id of the child thread it dispatches work to. */
  716. thread_local threadid_t g_thread_id = 0;
  717. enum threadstate_t {
  718. THREADSTATE_NONE,
  719. THREADSTATE_WAITING,
  720. THREADSTATE_DISPATCHING,
  721. THREADSTATE_WORKING,
  722. THREADSTATE_TERMINATE
  723. };
  724. struct threadblock_t {
  725. threadid_t threadid;
  726. threadstate_t state;
  727. pthread_t thread_handle;
  728. pthread_mutex_t mutex;
  729. pthread_cond_t dispatch_cond;
  730. void *(*dispatch_func)(void *data);
  731. void *dispatch_data;
  732. pthread_cond_t join_cond;
  733. void *ret_data;
  734. #ifdef COUNT_OSWAPS
  735. size_t num_oswaps;
  736. #endif
  737. };
  738. static threadblock_t *threadpool_control_blocks = NULL;
  739. static threadid_t threadpool_numthreads = 0;
  740. /* The main thread loop */
  741. static void* threadloop(void *vdata) {
  742. threadblock_t *block = (threadblock_t *)vdata;
  743. /* Initialize any per-thread state */
  744. g_thread_id = block->threadid;
  745. PRB_rand_bits = 0;
  746. PRB_rand_bits_remaining = 0;
  747. pthread_mutex_lock(&block->mutex);
  748. while(1) {
  749. /* Wait for work */
  750. block->state = THREADSTATE_WAITING;
  751. pthread_cond_wait(&block->dispatch_cond, &block->mutex);
  752. if (block->state == THREADSTATE_TERMINATE) {
  753. break;
  754. }
  755. /* Do the work */
  756. block->state = THREADSTATE_WORKING;
  757. pthread_mutex_unlock(&block->mutex);
  758. block->ret_data = (block->dispatch_func)(block->dispatch_data);
  759. #ifdef COUNT_OSWAPS
  760. /* Account for the oswaps done in this thread */
  761. block->num_oswaps = OSWAP_COUNTER;
  762. OSWAP_COUNTER = 0;
  763. #endif
  764. /* Signal the parent thread that we're done, and loop back to
  765. * wait for more work. */
  766. pthread_mutex_lock(&block->mutex);
  767. pthread_cond_signal(&block->join_cond);
  768. }
  769. block->state = THREADSTATE_NONE;
  770. pthread_mutex_unlock(&block->mutex);
  771. return NULL;
  772. }
  773. /* Create the threadpool, with numthreads-1 additional threads (numbered
  774. * 1 through numthreads-1) in addition to the current "main" thread
  775. * (numbered 0). Returns 0 on success, -1 on failure. It is allowed, but
  776. * not very useful, to pass 1 here. */
  777. int threadpool_init(threadid_t numthreads) {
  778. g_thread_id = 0;
  779. PRB_rand_bits = 0;
  780. PRB_rand_bits_remaining = 0;
  781. if (numthreads < 1) {
  782. return -1;
  783. } else if (numthreads == 1) {
  784. threadpool_numthreads = 1;
  785. return 0;
  786. }
  787. /* We don't actually create a thread control block for the main
  788. * thread 0, so the internal indexing into this array will be that
  789. * thread i's control block lives at index i-1 in this array. */
  790. threadpool_control_blocks = new threadblock_t[numthreads-1];
  791. if (threadpool_control_blocks == NULL) {
  792. return -1;
  793. }
  794. threadpool_numthreads = numthreads;
  795. /* Init each thread control block */
  796. bool thread_create_failure = false;
  797. for (threadid_t i = 0; i < numthreads-1; ++i) {
  798. threadblock_t *block = threadpool_control_blocks + i;
  799. block->threadid = i+1;
  800. block->state = THREADSTATE_NONE;
  801. pthread_mutex_init(&block->mutex, NULL);
  802. pthread_cond_init(&block->dispatch_cond, NULL);
  803. pthread_cond_init(&block->join_cond, NULL);
  804. block->thread_handle = NULL;
  805. int create_ret =
  806. pthread_create(&block->thread_handle, NULL, threadloop, block);
  807. if (create_ret) {
  808. thread_create_failure = true;
  809. printf("Failed to launch thread %lu; ret=%d\n", i+1, create_ret);
  810. }
  811. }
  812. if (thread_create_failure) {
  813. threadpool_shutdown();
  814. return -1;
  815. }
  816. return 0;
  817. }
  818. /* Ask all the threads to terminate, wait for that to happen, and clean
  819. * up. */
  820. void threadpool_shutdown() {
  821. /* Note that this function may be called when some threads failed to
  822. * launch at all in threadpool_init. In that case, the thread field
  823. * in the thread's control block will be NULL. The mutex/cond
  824. * variables will still have been initialized, however, and need
  825. * cleaning. */
  826. if (threadpool_numthreads == 0) {
  827. /* Nothing to do */
  828. return;
  829. }
  830. if (threadpool_numthreads == 1) {
  831. /* Almost nothing to do */
  832. threadpool_numthreads = 0;
  833. return;
  834. }
  835. for (threadid_t i=0;i<threadpool_numthreads-1; ++i) {
  836. threadblock_t *block = threadpool_control_blocks + i;
  837. pthread_mutex_lock(&block->mutex);
  838. if (block->state == THREADSTATE_WORKING) {
  839. /* There's a thread actively running? Wait for it to
  840. * finish. */
  841. pthread_mutex_unlock(&block->mutex);
  842. threadpool_join(i+1, NULL);
  843. pthread_mutex_lock(&block->mutex);
  844. }
  845. if (block->state == THREADSTATE_WAITING) {
  846. /* Tell the thread to exit */
  847. block->state = THREADSTATE_TERMINATE;
  848. pthread_mutex_unlock(&block->mutex);
  849. pthread_cond_signal(&block->dispatch_cond);
  850. pthread_join(block->thread_handle, NULL);
  851. block->thread_handle = NULL;
  852. }
  853. if (block->state != THREADSTATE_NONE) {
  854. printf("Unexpected state on thread %lu during shutdown: %u\n", i+1, block->state);
  855. pthread_cond_destroy(&block->dispatch_cond);
  856. pthread_cond_destroy(&block->join_cond);
  857. pthread_mutex_destroy(&block->mutex);
  858. }
  859. }
  860. delete[] threadpool_control_blocks;
  861. threadpool_control_blocks = NULL;
  862. threadpool_numthreads = 0;
  863. }
  864. /* Dispatch some work to a particular thread in the thread pool. */
  865. void threadpool_dispatch(threadid_t threadid, void *(*func)(void*),
  866. void *data) {
  867. threadblock_t *block = threadpool_control_blocks + (threadid-1);
  868. pthread_mutex_lock(&block->mutex);
  869. if (block->state != THREADSTATE_WAITING) {
  870. printf("Thread %lu not in expected WAITING state: %u\n",
  871. threadid, block->state);
  872. pthread_mutex_unlock(&block->mutex);
  873. return;
  874. }
  875. block->dispatch_func = func;
  876. block->dispatch_data = data;
  877. block->state = THREADSTATE_DISPATCHING;
  878. pthread_mutex_unlock(&block->mutex);
  879. /* Tell the thread there's work to do */
  880. pthread_cond_signal(&block->dispatch_cond);
  881. }
  882. /* Join a thread */
  883. void threadpool_join(threadid_t threadid, void **resp) {
  884. threadblock_t *block = threadpool_control_blocks + (threadid-1);
  885. pthread_mutex_lock(&block->mutex);
  886. /* Did the thread finish already? */
  887. if (block->state == THREADSTATE_DISPATCHING ||
  888. block->state == THREADSTATE_WORKING) {
  889. /* Wait until the thread completes */
  890. pthread_cond_wait(&block->join_cond, &block->mutex);
  891. } else if (block->state != THREADSTATE_WAITING) {
  892. printf("Thread %lu in unexpected state (not WORKING or WAITING) on join: %u\n",
  893. threadid, block->state);
  894. }
  895. if (resp) {
  896. *resp = block->ret_data;
  897. }
  898. #ifdef COUNT_OSWAPS
  899. uint64_t *ltvp = &OSWAP_COUNTER;
  900. FOAV_SAFE_CNTXT(oswap_buffer, *ltvp)
  901. OSWAP_COUNTER += block->num_oswaps;
  902. block->num_oswaps = 0;
  903. #endif
  904. pthread_mutex_unlock(&block->mutex);
  905. }