forked from donnod/linux-sgx-mage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.cpp
More file actions
1008 lines (895 loc) · 35.3 KB
/
loader.cpp
File metadata and controls
1008 lines (895 loc) · 35.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011-2019 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "se_wrapper.h"
#include "se_error_internal.h"
#include "arch.h"
#include "util.h"
#include "loader.h"
#include "se_page_attr.h"
#include "enclave.h"
#include "enclave_creator.h"
#include "routine.h"
#include "sgx_attributes.h"
#include "se_vendor.h"
#include "se_detect.h"
#include "binparser.h"
#include "metadata.h"
#include <assert.h>
#include <vector>
#include <tuple>
#include <algorithm>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <sys/mman.h>
const char * layout_id_str[] = {
"Undefined",
"HEAP_MIN",
"HEAP_INIT",
"HEAP_MAX",
"TCS",
"TD",
"SSA",
"STACK_MAX",
"STACK_MIN",
"THREAD_GROUP",
"GUARD",
"HEAP_DYN_MIN",
"HEAP_DYN_INIT",
"HEAP_DYN_MAX",
"TCS_DYN",
"TD_DYN",
"SSA_DYN",
"STACK_DYN_MAX",
"STACK_DYN_MIN",
"THREAD_GROUP_DYN",
"RSRV_MIN",
"RSRV_INIT",
"RSRV_MAX"
};
// enclave creator instance
extern EnclaveCreator* g_enclave_creator;
EnclaveCreator* get_enclave_creator(void)
{
return g_enclave_creator;
}
CLoader::CLoader(uint8_t *mapped_file_base, BinParser &parser)
: m_mapped_file_base(mapped_file_base)
, m_enclave_id(0)
, m_start_addr(NULL)
, m_metadata(NULL)
, m_parser(parser)
{
memset(&m_secs, 0, sizeof(m_secs));
}
CLoader::~CLoader()
{
}
sgx_enclave_id_t CLoader::get_enclave_id() const
{
return m_enclave_id;
}
const void* CLoader::get_start_addr() const
{
return m_start_addr;
}
const std::vector<std::pair<tcs_t *, bool>>& CLoader::get_tcs_list() const
{
return m_tcs_list;
}
const secs_t& CLoader::get_secs() const
{
return m_secs;
}
void* CLoader::get_symbol_address(const char * const symbol)
{
uint64_t rva = m_parser.get_symbol_rva(symbol);
if(0 == rva)
return NULL;
return GET_PTR(void, m_start_addr, rva);
}
// is_relocation_page returns true if the specified RVA is a writable relocation page based on the bitmap.
bool CLoader::is_relocation_page(const uint64_t rva, std::vector<uint8_t> *bitmap)
{
uint64_t page_frame = rva >> SE_PAGE_SHIFT;
//NOTE:
// Current enclave size is not beyond 128G, so the type-casting from (uint64>>15) to (size_t) is OK.
// In the future, if the max enclave size is extended to beyond (1<<49), this type-casting will not work.
// It only impacts the enclave signing process. (32bit signing tool to sign 64 bit enclaves)
size_t index = (size_t)(page_frame / 8);
if(bitmap && (index < bitmap->size()))
{
return ((*bitmap)[index] & (1 << (page_frame % 8)));
}
return false;
}
int CLoader::build_mem_region(const section_info_t &sec_info)
{
int ret = SGX_SUCCESS;
uint64_t offset = 0;
sec_info_t sinfo;
memset(&sinfo, 0, sizeof(sinfo));
// Build pages of the section that are contain initialized data. Each page
// needs to be added individually as the page may hold relocation data, in
// which case the page needs to be marked writable.
while(offset < sec_info.raw_data_size)
{
uint64_t rva = sec_info.rva + offset;
uint64_t size = MIN((SE_PAGE_SIZE - PAGE_OFFSET(rva)), (sec_info.raw_data_size - offset));
sinfo.flags = sec_info.flag;
if(is_relocation_page(rva, sec_info.bitmap) && !(sec_info.flag & SI_FLAG_W))
{
sinfo.flags = sec_info.flag | SI_FLAG_W;
assert(g_enclave_creator != NULL);
if(g_enclave_creator->use_se_hw() == true)
{
ret = mprotect((void*)(TRIM_TO_PAGE(rva) + (uint64_t)m_start_addr), SE_PAGE_SIZE,
(int)(sinfo.flags & SI_MASK_MEM_ATTRIBUTE));
if(ret != 0)
{
SE_TRACE(SE_TRACE_WARNING, "mprotect(rva=0x%llx, len=%d, flags=%d) failed\n",
rva, SE_PAGE_SIZE, int(sinfo.flags & SI_MASK_MEM_ATTRIBUTE));
return SGX_ERROR_UNEXPECTED;
}
}
}
if (size == SE_PAGE_SIZE)
ret = build_pages(rva, size, sec_info.raw_data + offset, sinfo, ADD_EXTEND_PAGE);
else
ret = build_partial_page(rva, size, sec_info.raw_data + offset, sinfo, ADD_EXTEND_PAGE);
if(SGX_SUCCESS != ret)
return ret;
// only the first time that rva may be not page aligned
offset += SE_PAGE_SIZE - PAGE_OFFSET(rva);
}
// Add any remaining uninitialized data. We can call build_pages directly
// even if there are partial pages since the source is null, i.e. everything
// is filled with '0'. Uninitialied data cannot be a relocation table, ergo
// there is no need to check the relocation bitmap.
if(sec_info.virtual_size > offset)
{
uint64_t rva = sec_info.rva + offset;
size_t size = (size_t)(ROUND_TO_PAGE(sec_info.virtual_size - offset + PAGE_OFFSET(rva)));
rva = TRIM_TO_PAGE(rva);
sinfo.flags = sec_info.flag;
if(SGX_SUCCESS != (ret = build_pages(rva, size, 0, sinfo, ADD_EXTEND_PAGE)))
return ret;
}
return SGX_SUCCESS;
}
int CLoader::build_sections(std::vector<uint8_t> *bitmap)
{
int ret = SGX_SUCCESS;
std::vector<Section*> sections = m_parser.get_sections();
uint64_t max_rva =0;
Section* last_section = NULL;
for(unsigned int i = 0; i < sections.size() ; i++)
{
if((META_DATA_MAKE_VERSION(SGX_1_5_MAJOR_VERSION,SGX_1_5_MINOR_VERSION ) == m_metadata->version) &&
(last_section != NULL) &&
(ROUND_TO_PAGE(last_section->virtual_size() + last_section->get_rva()) < ROUND_TO_PAGE(ROUND_TO_PAGE(last_section->virtual_size()) + last_section->get_rva())) &&
(ROUND_TO_PAGE(last_section->get_rva() + last_section->virtual_size()) < (sections[i]->get_rva() & (~(SE_PAGE_SIZE - 1)))))
{
size_t size = SE_PAGE_SIZE;
sec_info_t sinfo;
memset(&sinfo, 0, sizeof(sinfo));
sinfo.flags = last_section->get_si_flags();
uint64_t rva = ROUND_TO_PAGE(last_section->get_rva() + last_section->virtual_size());
if(SGX_SUCCESS != (ret = build_pages(rva, size, 0, sinfo, ADD_EXTEND_PAGE)))
return ret;
}
if(sections[i]->get_rva() > max_rva)
{
max_rva = sections[i]->get_rva();
last_section = sections[i];
}
section_info_t sec_info = { sections[i]->raw_data(), sections[i]->raw_data_size(), sections[i]->get_rva(), sections[i]->virtual_size(), sections[i]->get_si_flags(), bitmap };
if(SGX_SUCCESS != (ret = build_mem_region(sec_info)))
return ret;
}
if((META_DATA_MAKE_VERSION(SGX_1_5_MAJOR_VERSION,SGX_1_5_MINOR_VERSION ) == m_metadata->version) &&
(last_section != NULL) &&
(ROUND_TO_PAGE(last_section->virtual_size() + last_section->get_rva()) < ROUND_TO_PAGE(ROUND_TO_PAGE(last_section->virtual_size()) + last_section->get_rva())))
{
size_t size = SE_PAGE_SIZE;
sec_info_t sinfo;
memset(&sinfo, 0, sizeof(sinfo));
sinfo.flags = last_section->get_si_flags();
uint64_t rva = ROUND_TO_PAGE(last_section->get_rva() + last_section->virtual_size());
if(SGX_SUCCESS != (ret = build_pages(rva, size, 0, sinfo, ADD_EXTEND_PAGE)))
return ret;
}
return SGX_SUCCESS;
}
int CLoader::build_partial_page(const uint64_t rva, const uint64_t size, const void *source, const sec_info_t &sinfo, const uint32_t attr)
{
// RVA may or may not be aligned.
uint64_t offset = PAGE_OFFSET(rva);
// Initialize the page with '0', this serves as both the padding at the start
// of the page (if it's not aligned) as well as the fill for any unitilized
// bytes at the end of the page, e.g. .bss data.
uint8_t page_data[SE_PAGE_SIZE];
memset(page_data, 0, SE_PAGE_SIZE);
// The amount of raw data may be less than the number of bytes on the page,
// but that portion of page_data has already been filled (see above).
memcpy_s(&page_data[offset], (size_t)(SE_PAGE_SIZE - offset), source, (size_t)size);
// Add the page, trimming the start address to make it page aligned.
return build_pages(TRIM_TO_PAGE(rva), SE_PAGE_SIZE, page_data, sinfo, attr);
}
int CLoader::build_pages(const uint64_t start_rva, const uint64_t size, const void *source, const sec_info_t &sinfo, const uint32_t attr)
{
int ret = SGX_SUCCESS;
uint64_t offset = 0;
uint64_t rva = start_rva;
assert(IS_PAGE_ALIGNED(start_rva) && IS_PAGE_ALIGNED(size));
uint64_t skip_rva = 0;
uint64_t skip_size = 0;
const Section* mage_section = m_parser.get_mage_section();
if (mage_section != NULL)
{
skip_rva = mage_section->get_rva();
skip_size = mage_section->virtual_size();
}
while(offset < size)
{
//call driver to add page;
if (rva >= skip_rva + skip_size || rva + SE_PAGE_SIZE <= skip_rva) {
if(SGX_SUCCESS != (ret = get_enclave_creator()->add_enclave_page(ENCLAVE_ID_IOCTL, GET_PTR(void, source, 0), rva, sinfo, attr)))
{
//if add page failed , we should remove enclave somewhere;
return ret;
}
}
offset += SE_PAGE_SIZE;
rva += SE_PAGE_SIZE;
}
return SGX_SUCCESS;
}
int CLoader::build_mage_pages()
{
int ret = SGX_SUCCESS;
const Section* mage_section = m_parser.get_mage_section_ex();
if (mage_section == NULL) return ret;
uint64_t offset = 0;
uint64_t rva = mage_section->get_rva();
uint64_t size = mage_section->virtual_size();
const void *source = mage_section->raw_data();
sec_info_t sinfo;
for(unsigned int i = 0; i< sizeof(sinfo.reserved)/sizeof(sinfo.reserved[0]); i++)
{
sinfo.reserved[i] = 0;
}
sinfo.flags = 0x201;
uint32_t attr = 3;
assert(IS_PAGE_ALIGNED(rva) && IS_PAGE_ALIGNED(size));
se_trace(SE_TRACE_DEBUG, "\n\nbuild_mage_pages: %lx %lx\n", rva, rva + size);
for(unsigned int i = 0; i< size; i++)
{
se_trace(SE_TRACE_DEBUG, "%02x", reinterpret_cast<const uint8_t*>(source)[i]);
}
se_trace(SE_TRACE_DEBUG, "\n\nmage content %lx\n", size);
while(offset < size)
{
//call driver to add page;
if(SGX_SUCCESS != (ret = get_enclave_creator()->add_enclave_page(
ENCLAVE_ID_IOCTL, GET_PTR(void, source, 0), rva, sinfo, attr
)))
{
//if add page failed , we should remove enclave somewhere;
return ret;
} else {
se_trace(SE_TRACE_DEBUG, "\n\nadd_page: %lx\n", offset);
}
offset += SE_PAGE_SIZE;
rva += SE_PAGE_SIZE;
}
return SGX_SUCCESS;
}
int CLoader::post_init_action(layout_t *layout_start, layout_t *layout_end, uint64_t delta)
{
int ret = SGX_SUCCESS;
for(layout_t *layout = layout_start; layout < layout_end; layout++)
{
if (!IS_GROUP_ID(layout->group.id) && (layout->entry.attributes & PAGE_ATTR_POST_REMOVE))
{
uint64_t start_addr = layout->entry.rva + delta + (uint64_t)get_start_addr();
uint64_t page_count = (uint64_t)layout->entry.page_count;
if (SGX_SUCCESS != (ret = get_enclave_creator()->trim_range(start_addr, start_addr + (page_count << SE_PAGE_SHIFT))))
return ret;
}
else if (IS_GROUP_ID(layout->group.id))
{
uint64_t step = 0;
for(uint32_t j = 0; j < layout->group.load_times; j++)
{
step += layout->group.load_step;
if(SGX_SUCCESS != (ret = post_init_action(&layout[-layout->group.entry_count], layout, step)))
return ret;
}
}
}
return SGX_SUCCESS;
}
int CLoader::post_init_action_commit(layout_t *layout_start, layout_t *layout_end, uint64_t delta)
{
int ret = SGX_SUCCESS;
for(layout_t *layout = layout_start; layout < layout_end; layout++)
{
if (!IS_GROUP_ID(layout->group.id) && (layout->entry.attributes & PAGE_ATTR_POST_REMOVE))
{
uint64_t start_addr = layout->entry.rva + delta + (uint64_t)get_start_addr();
uint64_t page_count = (uint64_t)layout->entry.page_count;
for (uint64_t i = 0; i < page_count; i++)
{
if (SGX_SUCCESS != (ret = get_enclave_creator()->trim_accept(start_addr + (i << SE_PAGE_SHIFT))))
return ret;
}
}
else if (IS_GROUP_ID(layout->group.id))
{
uint64_t step = 0;
for(uint32_t j = 0; j < layout->group.load_times; j++)
{
step += layout->group.load_step;
if(SGX_SUCCESS != (ret = post_init_action_commit(&layout[-layout->group.entry_count], layout, step)))
return ret;
}
}
}
return SGX_SUCCESS;
}
int CLoader::build_context(const uint64_t start_rva, layout_entry_t *layout)
{
int ret = SGX_ERROR_UNEXPECTED;
uint8_t added_page[SE_PAGE_SIZE];
sec_info_t sinfo;
memset(added_page, 0, SE_PAGE_SIZE);
memset(&sinfo, 0, sizeof(sinfo));
uint64_t rva = start_rva + layout->rva;
assert(IS_PAGE_ALIGNED(rva));
se_trace(SE_TRACE_DEBUG, "\t%s\n", __FUNCTION__);
se_trace(SE_TRACE_DEBUG, "\tEntry Id = %4u, %-16s, ", layout->id, layout_id_str[layout->id & ~(GROUP_FLAG)]);
se_trace(SE_TRACE_DEBUG, "Page Count = %5u, ", layout->page_count);
se_trace(SE_TRACE_DEBUG, "Attributes = 0x%02X, ", layout->attributes);
se_trace(SE_TRACE_DEBUG, "Flags = 0x%016llX, ", layout->si_flags);
se_trace(SE_TRACE_DEBUG, "RVA = 0x%016llX -> ", layout->rva);
se_trace(SE_TRACE_DEBUG, "RVA = 0x%016llX\n", rva);
if (layout->attributes & PAGE_ATTR_EADD)
{
uint16_t attributes = layout->attributes;
#ifdef SE_SIM
attributes = attributes & (uint16_t)(~PAGE_ATTR_EREMOVE);
#endif
if (layout->content_offset)
{
if(layout->si_flags == SI_FLAGS_TCS)
{
memset(added_page, 0, SE_PAGE_SIZE);
memcpy_s(added_page, SE_PAGE_SIZE, GET_PTR(uint8_t, m_metadata, layout->content_offset), layout->content_size);
tcs_t *ptcs = reinterpret_cast<tcs_t*>(added_page);
ptcs->ossa += rva;
ptcs->ofs_base += rva;
ptcs->ogs_base += rva;
if(!(attributes & PAGE_ATTR_EREMOVE))
{
m_tcs_list.push_back(std::make_pair(GET_PTR(tcs_t, m_start_addr, rva), false));
}
sinfo.flags = layout->si_flags;
if(SGX_SUCCESS != (ret = build_pages(rva, ((uint64_t)layout->page_count) << SE_PAGE_SHIFT, added_page, sinfo, attributes)))
{
return ret;
}
}
else // guard page should not have content_offset != 0
{
section_info_t sec_info = {GET_PTR(uint8_t, m_metadata, layout->content_offset), layout->content_size, rva, ((uint64_t)layout->page_count) << SE_PAGE_SHIFT, layout->si_flags, NULL};
if(SGX_SUCCESS != (ret = build_mem_region(sec_info)))
{
return ret;
}
}
}
else if (layout->si_flags != SI_FLAG_NONE)
{
sinfo.flags = layout->si_flags;
void *source = NULL;
if(layout->content_size)
{
for(uint32_t *p = (uint32_t *)added_page; p < GET_PTR(uint32_t, added_page, SE_PAGE_SIZE); p++)
{
*p = layout->content_size;
}
source = added_page;
}
if(SGX_SUCCESS != (ret = build_pages(rva, ((uint64_t)layout->page_count) << SE_PAGE_SHIFT, source, sinfo, layout->attributes)))
{
return ret;
}
}
}
if(layout->attributes & PAGE_ATTR_POST_ADD)
{
#ifndef SE_SIM
if(layout->id == LAYOUT_ID_TCS_DYN)
{
m_tcs_list.push_back(std::make_pair(GET_PTR(tcs_t, m_start_addr, rva), true));
}
#endif
}
return SGX_SUCCESS;
}
int CLoader::build_contexts(layout_t *layout_start, layout_t *layout_end, uint64_t delta)
{
int ret = SGX_ERROR_UNEXPECTED;
for(layout_t *layout = layout_start; layout < layout_end; layout++)
{
se_trace(SE_TRACE_DEBUG, "%s, step = 0x%016llX\n", __FUNCTION__, delta);
if (!IS_GROUP_ID(layout->entry.id)) {
se_trace(SE_TRACE_DEBUG, "\tEntry Id(%2u) = %4u, %-16s, ", 0, layout->entry.id, layout_id_str[layout->entry.id]);
se_trace(SE_TRACE_DEBUG, "Page Count = %5u, ", layout->entry.page_count);
se_trace(SE_TRACE_DEBUG, "Attributes = 0x%02X, ", layout->entry.attributes);
se_trace(SE_TRACE_DEBUG, "Flags = 0x%016llX, ", layout->entry.si_flags);
se_trace(SE_TRACE_DEBUG, "RVA = 0x%016llX + 0x%016llX\n", layout->entry.rva, delta);
}
else {
se_trace(SE_TRACE_DEBUG, "\tEntry Id(%2u) = %4u, %-16s, ", 0, layout->entry.id, layout_id_str[layout->entry.id & ~(GROUP_FLAG)]);
se_trace(SE_TRACE_DEBUG, "Entry Count = %4u, ", layout->group.entry_count);
se_trace(SE_TRACE_DEBUG, "Load Times = %u, ", layout->group.load_times);
se_trace(SE_TRACE_DEBUG, "LStep = 0x%016llX\n", layout->group.load_step);
}
if (!IS_GROUP_ID(layout->group.id))
{
if(SGX_SUCCESS != (ret = build_context(delta, &layout->entry)))
{
return ret;
}
}
else
{
uint64_t step = 0;
for(uint32_t j = 0; j < layout->group.load_times; j++)
{
step += layout->group.load_step;
if(SGX_SUCCESS != (ret = build_contexts(&layout[-layout->group.entry_count], layout, step)))
{
return ret;
}
}
}
}
return SGX_SUCCESS;
}
int CLoader::build_secs(sgx_attributes_t * const secs_attr, sgx_config_id_t *config_id, sgx_config_svn_t config_svn, sgx_misc_attribute_t * const misc_attr)
{
memset(&m_secs, 0, sizeof(secs_t)); //should set resvered field of secs as 0.
//create secs structure.
m_secs.base = 0; //base is allocated by driver. set it as 0
m_secs.size = m_metadata->enclave_size;
m_secs.misc_select = misc_attr->misc_select;
if(memcpy_s(&m_secs.attributes, sizeof(m_secs.attributes), secs_attr, sizeof(m_secs.attributes)))
return SGX_ERROR_UNEXPECTED;
m_secs.ssa_frame_size = m_metadata->ssa_frame_size;
if (config_id)
{
if (memcpy_s(m_secs.config_id, SGX_CONFIGID_SIZE, config_id, SGX_CONFIGID_SIZE))
return SGX_ERROR_UNEXPECTED;
}
m_secs.config_svn = config_svn;
EnclaveCreator *enclave_creator = get_enclave_creator();
if(NULL == enclave_creator)
return SGX_ERROR_UNEXPECTED;
int ret = enclave_creator->create_enclave(&m_secs, &m_enclave_id, &m_start_addr, is_ae(&m_metadata->enclave_css));
if(SGX_SUCCESS == ret)
{
SE_TRACE(SE_TRACE_NOTICE, "Enclave start addr. = %p, Size = 0x%llx, %llu KB\n",
m_start_addr, m_metadata->enclave_size, m_metadata->enclave_size/1024);
}
// m_secs.mr_enclave value is not set previously
if(memcpy_s(&m_secs.mr_enclave, sizeof(sgx_measurement_t), &m_metadata->enclave_css.body.enclave_hash, sizeof(sgx_measurement_t)))
return SGX_ERROR_UNEXPECTED;
return ret;
}
int CLoader::build_image(SGXLaunchToken * const lc, sgx_attributes_t * const secs_attr, sgx_config_id_t *config_id, sgx_config_svn_t config_svn, le_prd_css_file_t *prd_css_file, sgx_misc_attribute_t * const misc_attr)
{
int ret = SGX_SUCCESS;
if(SGX_SUCCESS != (ret = build_secs(secs_attr, config_id, config_svn, misc_attr)))
{
SE_TRACE(SE_TRACE_WARNING, "build secs failed\n");
return ret;
};
// read reloc bitmap before patch the enclave file
// If load_enclave_ex try to load the enclave for the 2nd time,
// the enclave image is already patched, and parser cannot read the information.
// For linux, there's no map conflict. We assume load_enclave_ex will not do the retry.
std::vector<uint8_t> bitmap;
if(!m_parser.get_reloc_bitmap(bitmap))
return SGX_ERROR_INVALID_ENCLAVE;
// patch enclave file
patch_entry_t *patch_start = GET_PTR(patch_entry_t, m_metadata, m_metadata->dirs[DIR_PATCH].offset);
patch_entry_t *patch_end = GET_PTR(patch_entry_t, m_metadata, m_metadata->dirs[DIR_PATCH].offset + m_metadata->dirs[DIR_PATCH].size);
for(patch_entry_t *patch = patch_start; patch < patch_end; patch++)
{
memcpy_s(GET_PTR(void, m_parser.get_start_addr(), patch->dst), patch->size, GET_PTR(void, m_metadata, patch->src), patch->size);
}
//build sections, copy export function table as well;
if(SGX_SUCCESS != (ret = build_sections(&bitmap)))
{
SE_TRACE(SE_TRACE_WARNING, "build sections failed\n");
goto fail;
}
// build heap/thread context
SE_TRACE_DEBUG("\n");
se_trace(SE_TRACE_DEBUG, "\tMetadata Version = 0x%016llX\n", m_metadata->version);
if (SGX_SUCCESS != (ret = build_contexts(GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset),
GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset + m_metadata->dirs[DIR_LAYOUT].size),
0)))
{
SE_TRACE(SE_TRACE_WARNING, "build heap/thread context failed\n");
goto fail;
}
// build mage section
if(SGX_SUCCESS != (ret = build_mage_pages()))
{
SE_TRACE(SE_TRACE_WARNING, "build mage sections failed\n");
goto fail;
}
//initialize Enclave
ret = get_enclave_creator()->init_enclave(ENCLAVE_ID_IOCTL, const_cast<enclave_css_t *>(&m_metadata->enclave_css), lc, prd_css_file);
if(SGX_SUCCESS != ret)
{
SE_TRACE(SE_TRACE_WARNING, "init_enclave failed\n");
goto fail;
}
if(get_enclave_creator()->use_se_hw() == true)
{
set_memory_protection(false);
}
return SGX_SUCCESS;
fail:
get_enclave_creator()->destroy_enclave(ENCLAVE_ID_IOCTL, m_secs.size);
return ret;
}
bool CLoader::is_metadata_buffer(uint32_t offset, uint32_t size)
{
if((offsetof(metadata_t, data) > offset) || (offset >= m_metadata->size))
{
return false;
}
uint32_t end = offset + size;
if ((end < offset) || (end < size) || (end > m_metadata->size))
{
return false;
}
return true;
}
bool CLoader::is_enclave_buffer(uint64_t offset, uint64_t size)
{
if(offset >= m_metadata->enclave_size)
{
return false;
}
uint64_t end = offset + size;
if ((end < offset) || (end < size) || (end > m_metadata->enclave_size))
{
return false;
}
return true;
}
int CLoader::validate_layout_table()
{
layout_t *layout_start = GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset);
layout_t *layout_end = GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset + m_metadata->dirs[DIR_LAYOUT].size);
std::vector<std::pair<uint64_t, uint64_t>> rva_vector;
for (layout_t *layout = layout_start; layout < layout_end; layout++)
{
if(!IS_GROUP_ID(layout->entry.id)) // layout entry
{
rva_vector.push_back(std::make_pair(layout->entry.rva, ((uint64_t)layout->entry.page_count) << SE_PAGE_SHIFT));
if(layout->entry.content_offset)
{
if(false == is_metadata_buffer(layout->entry.content_offset, layout->entry.content_size))
{
return SGX_ERROR_INVALID_METADATA;
}
}
}
else // layout group
{
if (layout->group.entry_count > (uint32_t)(PTR_DIFF(layout, layout_start)/sizeof(layout_t)))
{
return SGX_ERROR_INVALID_METADATA;
}
uint64_t load_step = 0;
for(uint32_t i = 0; i < layout->group.load_times; i++)
{
load_step += layout->group.load_step;
if(load_step > m_metadata->enclave_size)
{
return SGX_ERROR_INVALID_METADATA;
}
for(layout_entry_t *entry = &layout[-layout->group.entry_count].entry; entry < &layout->entry; entry++)
{
if(IS_GROUP_ID(entry->id))
{
return SGX_ERROR_INVALID_METADATA;
}
rva_vector.push_back(std::make_pair(entry->rva + load_step, ((uint64_t)entry->page_count) << SE_PAGE_SHIFT));
// no need to check integer overflow for entry->rva + load_step, because
// entry->rva and load_step are less than enclave_size, whose size is no more than 37 bit
}
}
}
}
sort(rva_vector.begin(), rva_vector.end());
for (std::vector<std::pair<uint64_t, uint64_t>>::iterator it = rva_vector.begin(); it != rva_vector.end(); it++)
{
if(!IS_PAGE_ALIGNED(it->first))
{
return SGX_ERROR_INVALID_METADATA;
}
if(false == is_enclave_buffer(it->first, it->second))
{
return SGX_ERROR_INVALID_METADATA;
}
if((it+1) != rva_vector.end())
{
if((it->first+it->second) > (it+1)->first)
{
return SGX_ERROR_INVALID_METADATA;
}
}
}
return SGX_SUCCESS;
}
int CLoader::validate_patch_table()
{
patch_entry_t *patch_start = GET_PTR(patch_entry_t, m_metadata, m_metadata->dirs[DIR_PATCH].offset);
patch_entry_t *patch_end = GET_PTR(patch_entry_t, m_metadata, m_metadata->dirs[DIR_PATCH].offset + m_metadata->dirs[DIR_PATCH].size);
for(patch_entry_t *patch = patch_start; patch < patch_end; patch++)
{
if(false == is_metadata_buffer(patch->src, patch->size))
{
return SGX_ERROR_INVALID_METADATA;
}
if(false == is_enclave_buffer(patch->dst, patch->size))
{
return SGX_ERROR_INVALID_METADATA;
}
}
return SGX_SUCCESS;
}
int CLoader::validate_metadata()
{
if(!m_metadata)
return SGX_ERROR_INVALID_METADATA;
uint64_t urts_version = META_DATA_MAKE_VERSION(MAJOR_VERSION,MINOR_VERSION);
//if the version of metadata does NOT match the version of metadata in urts, we should NOT launch enclave.
if(MAJOR_VERSION_OF_METADATA(urts_version) < MAJOR_VERSION_OF_METADATA(m_metadata->version))
{
SE_TRACE(SE_TRACE_WARNING, "Mismatch between the metadata urts required and the metadata in use.\n");
return SGX_ERROR_INVALID_VERSION;
}
if(m_metadata->tcs_policy > TCS_POLICY_UNBIND)
return SGX_ERROR_INVALID_METADATA;
if(m_metadata->ssa_frame_size < SSA_FRAME_SIZE_MIN || m_metadata->ssa_frame_size > SSA_FRAME_SIZE_MAX)
return SGX_ERROR_INVALID_METADATA;
uint64_t size = m_metadata->enclave_size;
if(size > m_parser.get_enclave_max_size())
{
return SGX_ERROR_INVALID_METADATA;
}
while ((size != 0) && ((size & 1) != 1))
{
size = size >> 1;
}
if(size != 1)
{
return SGX_ERROR_INVALID_METADATA;
}
// check dirs
for(uint32_t i = 0; i < DIR_NUM; i++)
{
if(false == is_metadata_buffer(m_metadata->dirs[i].offset, m_metadata->dirs[i].size))
{
return SGX_ERROR_INVALID_METADATA;
}
}
// check layout table
int status = validate_layout_table();
if(SGX_SUCCESS != status)
{
return status;
}
// check patch table
status = validate_patch_table();
if(SGX_SUCCESS != status)
{
return status;
}
return SGX_SUCCESS;
}
bool CLoader::is_ae(const enclave_css_t *enclave_css)
{
assert(NULL != enclave_css);
if(INTEL_VENDOR_ID == enclave_css->header.module_vendor
&& AE_PRODUCT_ID == enclave_css->body.isv_prod_id)
return true;
return false;
}
int CLoader::load_enclave(SGXLaunchToken *lc, int debug, const metadata_t *metadata, sgx_config_id_t *config_id, sgx_config_svn_t config_svn, le_prd_css_file_t *prd_css_file, sgx_misc_attribute_t *misc_attr)
{
int ret = SGX_SUCCESS;
sgx_misc_attribute_t sgx_misc_attr;
memset(&sgx_misc_attr, 0, sizeof(sgx_misc_attribute_t));
m_metadata = metadata;
ret = validate_metadata();
if(SGX_SUCCESS != ret)
{
SE_TRACE(SE_TRACE_ERROR, "The metadata setting is not correct\n");
return ret;
}
ret = get_enclave_creator()->get_misc_attr(&sgx_misc_attr, const_cast<metadata_t *>(m_metadata), lc, debug);
if(SGX_SUCCESS != ret)
{
return ret;
}
ret = build_image(lc, &sgx_misc_attr.secs_attr, config_id, config_svn, prd_css_file, &sgx_misc_attr);
// Update misc_attr with secs.attr upon success.
if(SGX_SUCCESS == ret)
{
//When run here EINIT success, so SGX_FLAGS_INITTED should be set by ucode. uRTS align it with EINIT instruction.
sgx_misc_attr.secs_attr.flags |= SGX_FLAGS_INITTED;
m_secs.attributes = sgx_misc_attr.secs_attr;
if(misc_attr)
{
memcpy_s(misc_attr, sizeof(sgx_misc_attribute_t), &sgx_misc_attr, sizeof(sgx_misc_attribute_t));
}
}
return ret;
}
int CLoader::load_enclave_ex(SGXLaunchToken *lc, bool debug, const metadata_t *metadata, sgx_config_id_t *config_id, sgx_config_svn_t config_svn, le_prd_css_file_t *prd_css_file, sgx_misc_attribute_t *misc_attr)
{
unsigned int ret = SGX_SUCCESS, map_conflict_count = 3;
bool retry = true;
while (retry)
{
ret = this->load_enclave(lc, debug, metadata, config_id, config_svn, prd_css_file, misc_attr);
switch(ret)
{
//If CreateEnclave failed due to power transition, we retry it.
case SGX_ERROR_ENCLAVE_LOST: //caused by loading enclave while power transition occurs
break;
//If memroy map conflict occurs, we only retry 3 times.
case SGX_ERROR_MEMORY_MAP_CONFLICT:
if(0 == map_conflict_count)
retry = false;
else
map_conflict_count--;
break;
//We don't re-load enclave due to other error code.
default:
retry = false;
break;
}
}
return ret;
}
int CLoader::destroy_enclave()
{
return get_enclave_creator()->destroy_enclave(ENCLAVE_ID_IOCTL, m_secs.size);
}
int CLoader::set_memory_protection(bool is_after_initialization)
{
int ret = 0;
//set memory protection for segments
if(m_parser.set_memory_protection((uint64_t)m_start_addr, is_after_initialization) != true)
{
return SGX_ERROR_UNEXPECTED;
}
if (is_after_initialization &&
(META_DATA_MAKE_VERSION(MAJOR_VERSION,MINOR_VERSION) <= m_metadata->version) &&
get_enclave_creator()->is_EDMM_supported(get_enclave_id()))
{
std::vector<std::tuple<uint64_t, uint64_t, uint32_t>> pages_to_protect;
m_parser.get_pages_to_protect((uint64_t)m_start_addr, pages_to_protect);
for (auto page : pages_to_protect)
{ uint64_t start = 0, len = 0;
uint32_t perm = 0;
std::tie(start, len, perm) = page;
ret = get_enclave_creator()->emodpr(start, len, (uint64_t)perm);
if (ret != SGX_SUCCESS)
return SGX_ERROR_UNEXPECTED;
}
}
//set memory protection for context
ret = set_context_protection(GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset),
GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset + m_metadata->dirs[DIR_LAYOUT].size),
0);
if (SGX_SUCCESS != ret)
{
return ret;
}
return SGX_SUCCESS;
}
int CLoader::set_context_protection(layout_t *layout_start, layout_t *layout_end, uint64_t delta)
{
int ret = SGX_ERROR_UNEXPECTED;
for(layout_t *layout = layout_start; layout < layout_end; layout++)
{
if (!IS_GROUP_ID(layout->group.id))
{
int prot = 0 ;
if(layout->entry.si_flags == SI_FLAG_NONE)
{
prot = SI_FLAG_NONE & SI_MASK_MEM_ATTRIBUTE;
}
else
{
prot = SI_FLAGS_RW & SI_MASK_MEM_ATTRIBUTE;
#ifndef SE_SIM
//when a page is eremoved when loading, we should set this page to none access.
//if this page is accessed, a sigbus exception will be raised.
uint16_t attributes = layout->entry.attributes;
if(attributes & PAGE_ATTR_EADD && attributes & PAGE_ATTR_EREMOVE)
{
if(attributes & PAGE_ATTR_EREMOVE)
{
prot = SI_FLAG_NONE & SI_MASK_MEM_ATTRIBUTE;
}
}
#endif
}
ret = mprotect(GET_PTR(void, m_start_addr, layout->entry.rva + delta),
(size_t)layout->entry.page_count << SE_PAGE_SHIFT,
prot);
if(ret != 0)
{
SE_TRACE(SE_TRACE_WARNING, "mprotect(rva=%" PRIu64 ", len=%" PRIu64 ", flags=%d) failed\n",
(uint64_t)m_start_addr + layout->entry.rva + delta,
(uint64_t)layout->entry.page_count << SE_PAGE_SHIFT,
prot);
return SGX_ERROR_UNEXPECTED;
}
}
else
{
uint64_t step = 0;
for(uint32_t j = 0; j < layout->group.load_times; j++)
{
step += layout->group.load_step;
if(SGX_SUCCESS != (ret = set_context_protection(&layout[-layout->group.entry_count], layout, step)))