utils.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. #include <pthread.h>
  2. #include "utils.hpp"
  3. #ifdef COUNT_OSWAPS
  4. thread_local uint64_t OSWAP_COUNTER=0;
  5. #endif
  6. PRB_buffer* PRB_pool;
  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. PRB_pool = new PRB_buffer[nthreads];
  412. }
  413. void PRB_pool_shutdown() {
  414. delete [] PRB_pool;
  415. }
  416. PRB_buffer::PRB_buffer() {
  417. }
  418. PRB_buffer::~PRB_buffer() {
  419. }
  420. sgx_status_t PRB_buffer::init_PRB_buffer(uint32_t buffer_size = PRB_BUFFER_SIZE) {
  421. sgx_status_t rt = SGX_SUCCESS;
  422. if(initialized==false) {
  423. rt = sgx_read_rand((unsigned char*) random_seed, SGX_AESCTR_KEY_SIZE);
  424. if(rt!=SGX_SUCCESS){
  425. printf("Failed sgx_read_rand (%x)", rt);
  426. return rt;
  427. }
  428. rt = sgx_read_rand((unsigned char*) counter, SGX_AESCTR_KEY_SIZE);
  429. if(rt!=SGX_SUCCESS){
  430. printf("Failed sgx_read_rand (%x)", rt);
  431. return rt;
  432. }
  433. initialized=true;
  434. }
  435. char zeroes[buffer_size];
  436. // We don't bother initializing to zeroes since AES_CTR just adds the PRB_stream to the buffer
  437. // Use AES CTR to populate random_bytes
  438. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) zeroes, buffer_size,
  439. (uint8_t*) counter, CTR_INC_BITS, random_bytes);
  440. *(uint64_t*)counter += 1;
  441. if(rt!=SGX_SUCCESS){
  442. printf("Failed sgx_aes_ctr_encrypt (%x) in init_getRandomBytes\n", rt);
  443. return rt;
  444. }
  445. random_bytes_left = PRB_BUFFER_SIZE;
  446. random_bytes_ptr = random_bytes;
  447. return rt;
  448. }
  449. sgx_status_t PRB_buffer::getRandomBytes(unsigned char *buffer, size_t size) {
  450. sgx_status_t rt = SGX_SUCCESS;
  451. if(initialized==false)
  452. init_PRB_buffer();
  453. if(size < random_bytes_left) {
  454. // Supply buffer with random bytes from random_bytes
  455. memcpy(buffer, random_bytes_ptr, size);
  456. random_bytes_ptr+=size;
  457. random_bytes_left-= size;
  458. return rt;
  459. } else {
  460. // Consume all the random bytes we have left
  461. unsigned char *ptr = buffer;
  462. size_t size_left_for_req = size - random_bytes_left;
  463. memcpy(ptr, random_bytes_ptr, random_bytes_left);
  464. ptr+= random_bytes_left;
  465. // Use AES CTR to populate random_bytes
  466. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) random_bytes, PRB_BUFFER_SIZE,
  467. (uint8_t*) counter, CTR_INC_BITS, random_bytes);
  468. *(uint64_t*)counter += 1;
  469. if(rt!=SGX_SUCCESS){
  470. printf("Failed sgx_aes_ctr_encrypt (%x)", rt);
  471. return rt;
  472. }
  473. random_bytes_left = PRB_BUFFER_SIZE;
  474. random_bytes_ptr = random_bytes;
  475. // Add size_left_for_req random bytes to the buffer
  476. memcpy(ptr, random_bytes_ptr, size_left_for_req);
  477. random_bytes_ptr+=size_left_for_req;
  478. random_bytes_left-=size_left_for_req;
  479. return rt;
  480. }
  481. }
  482. sgx_status_t PRB_buffer::getBulkRandomBytes(unsigned char *buffer, size_t size) {
  483. sgx_status_t rt = SGX_SUCCESS;
  484. rt = sgx_aes_ctr_encrypt(random_seed, (const uint8_t*) buffer, size,
  485. (uint8_t*) counter, CTR_INC_BITS, buffer);
  486. *(uint64_t*)counter += 1;
  487. if(rt!=SGX_SUCCESS){
  488. 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);
  489. return rt;
  490. }
  491. return rt;
  492. }
  493. sgx_status_t initialize_BRB() {
  494. sgx_status_t rt = SGX_SUCCESS;
  495. rt = sgx_read_rand((unsigned char*) bulk_random_seed, SGX_AESCTR_KEY_SIZE);
  496. if(rt!=SGX_SUCCESS){
  497. printf("initialize_BRB(): Failed sgx_read_rand (%x)", rt);
  498. return rt;
  499. }
  500. rt = sgx_read_rand((unsigned char*) bulk_counter, SGX_AESCTR_KEY_SIZE);
  501. if(rt!=SGX_SUCCESS){
  502. printf("initialize_BRB(): Failed sgx_read_rand (%x)", rt);
  503. return rt;
  504. }
  505. bulk_initialized = true;
  506. return rt;
  507. }
  508. sgx_status_t getBulkRandomBytes(unsigned char *buffer, size_t size) {
  509. if(bulk_initialized == false){
  510. initialize_BRB();
  511. }
  512. sgx_status_t rt = SGX_SUCCESS;
  513. rt = sgx_aes_ctr_encrypt(bulk_random_seed, (const uint8_t*) buffer, size,
  514. (uint8_t*) bulk_counter, CTR_INC_BITS, buffer);
  515. if(rt!=SGX_SUCCESS){
  516. 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);
  517. return rt;
  518. }
  519. return rt;
  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. }