-
Notifications
You must be signed in to change notification settings - Fork 61
/
rtld_c18n.c
2251 lines (1903 loc) · 55 KB
/
rtld_c18n.c
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
/*-
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2021-2023 Dapeng Gao
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*
* Design overview of compartmentalisation (c18n)
*
* When RTLD is relocating function symbols (during startup for GOT entries and
* during program execution for lazily-bound symbols), tramp_intern is called to
* create a trampoline that wraps the resolved function.
*
* Exactly one trampoline is constructed for each resolved function, where
* uniqueness is guaranteed by a hash-table. When a cross-compartment function
* call takes place, the trampoline intercepts the control-flow and performs a
* domain transition from the caller's compartment to the callee's. A domain
* transition consists of switching the execution stack and clearing non-
* argument registers so that no capability leaks to the callee that is not
* passed as an argument.
*
* During a domain transition, the trampoline uses a stack lookup table of type
* 'struct stk_table' to record and retrieve the current stack top of each
* compartment. In addition, the trampoline pushes a trusted frame of type
* 'struct trusted_frame' to a trusted stack that records the path of domain
* transitions. When the callee returns, control-flow is passed again to the
* trampoline, which reverses the domain transition and pops the topmost trusted
* frame from the trusted stack.
*
* Stack unwinding due to either setjmp/longjmp or C++ exceptions is supported.
* The relevant parts of libc and libunwind have been modified so that when
* attempting to save/restore the program state, RTLD hooks are called to update
* state related to compartmentalisation such as the contents of the trusted
* stack and the stack lookup table.
*
* Compartmentalisation integrates well with the POSIX signal mechanism. When
* the user registers a signal handler, RTLD (or libthr, if multi-threading is
* enabled) instead registers _rtld_sighandler on their behalf. When a signal
* arrives, _rtld_sighandler dispatches the signal to the registered handler to
* be run in its own compartment.
*/
#include <sys/param.h>
#include <sys/ktrace.h>
#include <sys/mman.h>
#include <sys/signalvar.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <machine/sigframe.h>
#include <cheri/c18n.h>
#include <errno.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdlib.h>
#include "debug.h"
#include "rtld.h"
#include "rtld_c18n.h"
#include "rtld_libc.h"
#include "rtld_utrace.h"
_Static_assert(
TRUSTED_FRAME_SIZE * sizeof(uintptr_t) == sizeof(struct trusted_frame),
"Unexpected struct trusted_frame size");
_Static_assert(
TRUSTED_FRAME_SP_OSP == offsetof(struct trusted_frame, state.sp),
"Unexpected struct trusted_frame member offset");
_Static_assert(
TRUSTED_FRAME_PREV == offsetof(struct trusted_frame, previous),
"Unexpected struct trusted_frame member offset");
_Static_assert(
TRUSTED_FRAME_CALLER == offsetof(struct trusted_frame, caller),
"Unexpected struct trusted_frame member offset");
_Static_assert(
TRUSTED_FRAME_CALLEE == offsetof(struct trusted_frame, callee),
"Unexpected struct trusted_frame member offset");
_Static_assert(
TRUSTED_FRAME_LANDING == offsetof(struct trusted_frame, landing),
"Unexpected struct trusted_frame member offset");
_Static_assert(
STACK_TABLE_RTLD == cid_to_index_raw(RTLD_COMPART_ID),
"Unexpected struct stk_table member offset");
_Static_assert(sizeof(struct func_sig) == sizeof(func_sig_int),
"Unexpected func_sig size");
_Static_assert(
SIG_FRAME_SIZE == sizeof(struct sigframe),
"Unexpected struct sigframe size");
/*
* Sealers for RTLD privileged information
*/
static uintptr_t sealer_tcb;
static uintptr_t sealer_trusted_stk;
uintptr_t sealer_pltgot, sealer_tramp;
/* Enable compartmentalisation */
bool ld_compartment_enable;
/* Permission bit to be cleared for user code */
uint64_t c18n_code_perm_clear;
/* Use utrace() to log compartmentalisation-related events */
const char *ld_compartment_utrace;
/* Path of the compartmentalisation policy */
const char *ld_compartment_policy;
/* Simulate overhead during compartment transitions */
const char *ld_compartment_overhead;
/* Read the .c18n.signature ELF section */
const char *ld_compartment_sig;
/* Expose tagged frame pointers to trusted frames */
const char *ld_compartment_unwind;
/* Export compartmentalisation statistics to a file */
const char *ld_compartment_stats;
/* Export count of compartment switches to statistics */
const char *ld_compartment_switch_count;
struct rtld_c18n_stats *c18n_stats;
#define INC_NUM_COMPART (c18n_stats->rcs_compart++, comparts.size++)
#define INC_NUM_BYTES(n) \
atomic_fetch_add_explicit(&c18n_stats->rcs_bytes_total, (n), \
memory_order_relaxed)
static void *
c18n_malloc(size_t n)
{
void *buf = xmalloc(n);
INC_NUM_BYTES(cheri_getlen(buf));
return (buf);
}
static void *
c18n_realloc(void *buf, size_t new)
{
size_t old = buf == NULL ? 0 : cheri_getlen(buf);
buf = realloc(buf, new);
if (buf == NULL)
rtld_fatal("realloc failed");
new = cheri_getlen(buf);
INC_NUM_BYTES(new - old);
return (buf);
}
static void
c18n_free(void *buf)
{
size_t old = buf == NULL ? 0 : cheri_getlen(buf);
free(buf);
INC_NUM_BYTES(-old);
}
/*
* Policies
*/
typedef ssize_t string_handle;
struct string_base {
char *buf;
string_handle size;
string_handle capacity;
};
#define C18N_STRING_BASE_INIT 32
static void
string_base_expand(struct string_base *sb, size_t capacity)
{
sb->buf = c18n_realloc(sb->buf, capacity);
sb->capacity = capacity;
}
static string_handle
string_base_push(struct string_base *sb, const char *str)
{
string_handle i = sb->size;
do {
if (sb->size == sb->capacity)
string_base_expand(sb,
MAX(C18N_STRING_BASE_INIT, sb->capacity * 2));
sb->buf[sb->size++] = *str;
} while (*str++ != '\0');
return (i);
}
static string_handle
string_base_search(const struct string_base *sb, const char *str)
{
const char *cur;
string_handle i = 0, s;
while (i < sb->size) {
s = i;
cur = str;
while (sb->buf[i++] == *cur)
if (*cur++ == '\0')
return (s);
while (sb->buf[i] != '\0') ++i;
++i;
}
return (-1);
}
struct compart {
/*
* Name of the compartment
*/
const char *name;
/*
* Names of libraries that belong to the compartment
*/
struct string_base libs;
/*
* Symbols that the library is allowed to import, if restrict_imports is
* true.
*/
struct string_base imports;
/*
* Symbols trusted by the library.
*/
struct string_base trusts;
bool restrict_imports;
};
extern int _compart_size;
int _compart_size = sizeof(struct compart);
extern struct r_debug r_debug;
void
r_debug_comparts_state(struct r_debug *, struct compart *);
void
r_debug_comparts_state(struct r_debug *rd __unused, struct compart *m __unused)
{
/*
* See r_debug_state().
*/
__compiler_membar();
}
#define GDB_COMPARTS_STATE(s,m) \
r_debug.r_comparts_state = s; r_debug_comparts_state(&r_debug, m);
/*
* A pseudo-compartment that encompasses all compartments.
*/
static struct compart uni_compart;
static struct {
struct compart *data;
compart_id_t size;
compart_id_t capacity;
} comparts;
static void
expand_comparts_data(compart_id_t capacity)
{
struct compart *data;
data = c18n_realloc(comparts.data, sizeof(*data) * capacity);
comparts.data = r_debug.r_comparts = data;
comparts.capacity = capacity;
}
static struct compart *
add_comparts_data(const char *name)
{
struct compart *com;
rtld_require(comparts.size <= COMPART_ID_MAX,
"c18n: Compartment ID overflow for %s", name);
if (comparts.size == comparts.capacity)
expand_comparts_data(comparts.capacity * 2);
GDB_COMPARTS_STATE(RCT_ADD, NULL);
com = &comparts.data[INC_NUM_COMPART];
*com = (struct compart) {
.name = name
};
r_debug.r_comparts_size = comparts.size;
GDB_COMPARTS_STATE(RCT_CONSISTENT, com);
return (com);
}
compart_id_t
compart_id_allocate(const char *lib)
{
compart_id_t i;
struct compart *com;
/*
* Start searching from the first compartment
*/
for (i = RTLD_COMPART_ID; i < comparts.size; ++i)
if (string_base_search(&comparts.data[i].libs, lib) != -1)
return (i);
com = add_comparts_data(lib);
string_base_push(&com->libs, lib);
return (i);
}
static compart_id_t
compart_name_to_id(const char *name)
{
compart_id_t i;
/*
* Start searching from the first compartment
*/
for (i = RTLD_COMPART_ID; i < comparts.size; ++i)
if (strcmp(comparts.data[i].name, name) == 0)
return (i);
rtld_fatal("c18n: Cannot find compartment ID for %s", name);
}
struct rule_action {
compart_id_t caller;
SLIST_ENTRY(rule_action) link;
};
struct rule {
compart_id_t callee;
struct string_base symbols;
SLIST_HEAD(, rule_action) action;
SLIST_ENTRY(rule) link;
};
static SLIST_HEAD(, rule) rules = SLIST_HEAD_INITIALIZER(rules);
struct cursor {
const char *buf;
const size_t size;
size_t pos;
};
static bool
eat(struct cursor *cur, const char *token)
{
size_t pos = cur->pos;
while (*token != '\0')
if (pos >= cur->size || cur->buf[pos++] != *token++)
return (false);
cur->pos = pos;
return (true);
}
static bool
eat_token(struct cursor *cur, char delim, char *buf, size_t size)
{
char c;
size_t pos = cur->pos;
while (size > 0 && pos < cur->size) {
c = cur->buf[pos++];
if (c == delim) {
*buf = '\0';
cur->pos = pos;
return (true);
}
*buf++ = c;
--size;
}
return (false);
}
static void
policy_error(const struct cursor *cur)
{
size_t li = 1;
size_t ch = 1;
size_t pos = 0;
while (pos < cur->pos) {
if (cur->buf[pos++] == '\n') {
++li;
ch = 1;
} else
++ch;
}
rtld_fatal("c18n: Policy error at line %lu, character %lu", li, ch);
}
#define C18N_POLICY_TOKEN_MAX 128
static void
parse_policy(const char *pol, size_t size)
{
compart_id_t id;
struct cursor cur = {
.buf = pol,
.size = size
};
struct rule_action *act;
struct rule *rule;
struct compart *com;
struct string_base *symbols;
char buf[C18N_POLICY_TOKEN_MAX];
if (!eat(&cur, "Version 1\n"))
policy_error(&cur);
while (cur.pos < cur.size) {
while (eat(&cur, "\n"))
;
if (eat(&cur, "compartment ")) {
if (eat_token(&cur, '\n', buf, sizeof(buf)))
com = add_comparts_data(strdup(buf));
else
policy_error(&cur);
while (eat(&cur, "\t"))
if (eat_token(&cur, '\n', buf, sizeof(buf)))
string_base_push(&com->libs, buf);
else
policy_error(&cur);
} else if (eat(&cur, "caller ")) {
if (eat(&cur, "*\n"))
com = &uni_compart;
else if (eat_token(&cur, '\n', buf, sizeof(buf))) {
id = compart_name_to_id(buf);
com = &comparts.data[id];
} else
policy_error(&cur);
if (eat(&cur, "trust\n"))
symbols = &com->trusts;
else if (eat(&cur, "import\n"))
symbols = &com->imports;
else
policy_error(&cur);
while (eat(&cur, "\t"))
if (eat_token(&cur, '\n', buf, sizeof(buf)))
string_base_push(symbols, buf);
else
policy_error(&cur);
} else if (eat(&cur, "callee ")) {
if (eat_token(&cur, '\n', buf, sizeof(buf))) {
id = compart_name_to_id(buf);
rule = c18n_malloc(sizeof(*rule));
*rule = (struct rule) {
.callee = id,
.action = SLIST_HEAD_INITIALIZER()
};
} else
policy_error(&cur);
while (eat(&cur, "export to "))
if (eat_token(&cur, '\n', buf, sizeof(buf))) {
id = compart_name_to_id(buf);
act = c18n_malloc(sizeof(*act));
*act = (struct rule_action) {
.caller = id,
};
SLIST_INSERT_HEAD(&rule->action, act,
link);
} else
policy_error(&cur);
while (eat(&cur, "\t"))
if (eat_token(&cur, '\n', buf, sizeof(buf)))
string_base_push(&rule->symbols, buf);
else
policy_error(&cur);
SLIST_INSERT_HEAD(&rules, rule, link);
} else
policy_error(&cur);
}
}
static bool
evaluate_rules(compart_id_t caller, compart_id_t callee, const char *sym)
{
struct rule *cur;
struct rule_action *act;
if (comparts.data[caller].restrict_imports &&
string_base_search(&comparts.data[caller].imports, sym) == -1)
return (false);
SLIST_FOREACH(cur, &rules, link) {
if (cur->callee != callee ||
string_base_search(&cur->symbols, sym) == -1)
continue;
SLIST_FOREACH(act, &cur->action, link) {
if (act->caller == caller)
return (true);
}
return (false);
}
return (true);
}
static bool
tramp_should_include(const Obj_Entry *reqobj, const struct tramp_data *data)
{
const char *sym;
if (data->def == NULL)
return (true);
if (data->def == &sym_zero)
return (false);
sym = strtab_value(data->defobj, data->def->st_name);
if (string_base_search(&uni_compart.trusts, sym) != -1)
return (false);
if (reqobj == NULL)
return (true);
if (reqobj->compart_id == data->defobj->compart_id)
return (false);
if (string_base_search(&comparts.data[reqobj->compart_id].trusts, sym)
!= -1)
return (false);
if (evaluate_rules(reqobj->compart_id, data->defobj->compart_id, sym))
return (true);
rtld_fatal("c18n: Policy violation: %s is not allowed to access symbol "
"%s defined by %s",
comparts.data[reqobj->compart_id].name, sym,
comparts.data[data->defobj->compart_id].name);
}
/*
* Stack switching
*/
/*
* Assembly function with non-standard ABI.
*/
void create_untrusted_stk(void);
static _Atomic(struct stk_table *) dead_stk_tables;
/*
* A fake tcb that is passed to libthr during thread creation and destruction.
*/
struct tcb_wrapper {
struct tcb header __attribute__((cheri_no_subobject_bounds));
struct tcb *tcb;
struct stk_table *table;
};
static void
push_stk_table(_Atomic(struct stk_table *) *head, struct stk_table *table)
{
struct stk_table **link = &SLIST_NEXT(table, next);
*link = atomic_load_explicit(head, memory_order_relaxed);
while (!atomic_compare_exchange_weak_explicit(head, link, table,
/*
* Use release ordering to ensure that table construction happens
* before the push.
*/
memory_order_release, memory_order_release));
}
static struct stk_table *
pop_stk_table(_Atomic(struct stk_table *) *head)
{
struct stk_table *table, *next;
table = atomic_load_explicit(head, memory_order_relaxed);
do {
next = SLIST_NEXT(table, next);
} while (!atomic_compare_exchange_weak_explicit(head, &table, next,
/*
* Use acquire ordering to ensure that the pop happens after table
* construction.
*/
memory_order_acquire, memory_order_acquire));
return (table);
}
static struct stk_table *
expand_stk_table(struct stk_table *table, size_t capacity)
{
size_t o_capacity;
bool create = table == NULL;
table = c18n_realloc(table,
sizeof(*table) + sizeof(*table->entries) * capacity);
if (create)
table->meta = NULL;
table->meta = c18n_realloc(table->meta,
sizeof(*table->meta) +
sizeof(*table->meta->compart_stk) * capacity);
if (table->meta == NULL)
rtld_fatal("realloc failed");
if (create) {
table->resolver = create_untrusted_stk;
table->meta->wrap = NULL;
table->meta->trusted_stk = (struct stk_table_stk_info) {};
o_capacity = 0;
} else
o_capacity = table->meta->capacity;
table->meta->capacity =
(cheri_getlen(table) - offsetof(typeof(*table), entries)) /
sizeof(*table->entries);
for (size_t i = o_capacity; i < table->meta->capacity; ++i) {
table->meta->compart_stk[i] = (struct stk_table_stk_info) {};
table->entries[i] = (struct stk_table_entry) {
.stack = create_untrusted_stk,
};
}
return (table);
}
struct tcb *
c18n_allocate_tcb(struct tcb *tcb)
{
struct stk_table *table;
struct tcb_wrapper *wrap;
table = expand_stk_table(NULL, comparts.size);
wrap = c18n_malloc(sizeof(*wrap));
*wrap = (struct tcb_wrapper) {
.header = *tcb,
.tcb = cheri_seal(tcb, sealer_tcb),
.table = cheri_seal(table, sealer_tcb)
};
return (&wrap->header);
}
void
c18n_free_tcb(void)
{
struct stk_table *table;
table = pop_stk_table(&dead_stk_tables);
c18n_free(table->meta->wrap);
c18n_free(table->meta);
c18n_free(table);
}
static void *
create_stk(size_t size)
{
char *stk;
stk = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_STACK, -1, 0);
if (stk == MAP_FAILED)
rtld_fatal("mmap failed");
return (stk + size);
}
#define C18N_TRUSTED_STACK_SIZE (128 * 1024)
static void
init_stk_table(struct stk_table *table, struct tcb_wrapper *wrap)
{
char *sp;
size_t size;
struct trusted_frame *tf;
/*
* Save the fake tcb in the stack lookup table.
*/
table->meta->wrap = wrap;
/*
* Create a trusted stack.
*/
size = C18N_TRUSTED_STACK_SIZE;
tf = create_stk(size);
/*
* Record the trusted stack in the stack lookup table.
*/
table->meta->trusted_stk = (struct stk_table_stk_info) {
.size = size,
.begin = (char *)tf - size
};
/*
* Record RTLD's stack in the stack lookup table.
*/
#ifdef __ARM_MORELLO_PURECAP_BENCHMARK_ABI
sp = cheri_setoffset(cheri_getstack(), 0);
#else
/*
* RTLD's actual stack is the Executive stack which does not need to be
* stored in the stack lookup table. Instead, fill the table entry with
* a one-byte dummy stack.
*
* Note that NULL cannot be used here because a compartment can then
* pretend to be RTLD when a signal is delivered. Nor can a zero-length
* stack be used because the signal handler uses the recorded size of
* the stack to determine whether it has been allocated.
*/
static char dummy_stk;
sp = &dummy_stk;
set_untrusted_stk(sp);
#endif
size = cheri_getlen(sp);
assert(size > 0);
table->meta->compart_stk[RTLD_COMPART_ID] = (struct stk_table_stk_info)
{
.size = size,
.begin = sp
};
table->entries[RTLD_COMPART_ID].stack = sp + size;
/*
* Push a dummy trusted frame indicating that the 'root' compartment is
* RTLD.
*/
tf = push_dummy_rtld_trusted_frame(tf);
/*
* Install the stack lookup table.
*/
set_stk_table(table);
}
#define C18N_STACK_SIZE (4 * 1024 * 1024)
static void *
get_or_create_untrusted_stk(compart_id_t cid, struct stk_table **tablep)
{
char *stk;
size_t size;
RtldLockState lockstate;
struct stk_table *table = *tablep;
if (table->meta->capacity <= cid) {
/*
* If the compartment ID exceeds the capacity of the stack
* lookup table, then new libraries must have been loaded.
*
* Acquire a lock first to ensure that the compartment size does
* not change and then expand the stack lookup table.
*/
wlock_acquire(rtld_bind_lock, &lockstate);
*tablep = table = expand_stk_table(table, comparts.size);
lock_release(rtld_bind_lock, &lockstate);
set_stk_table(table);
} else if (table->meta->compart_stk[cid].size > 0)
return (table->entries[cid].stack);
size = C18N_STACK_SIZE;
stk = create_stk(size);
table->meta->compart_stk[cid] = (struct stk_table_stk_info) {
.size = size,
.begin = stk - size
};
table->entries[cid].stack = cheri_clearperm(stk, CHERI_PERM_SW_VMEM);
atomic_fetch_add_explicit(&c18n_stats->rcs_ustack, 1,
memory_order_relaxed);
return (stk);
}
void *resolve_untrusted_stk_impl(stk_table_index);
void *
resolve_untrusted_stk_impl(stk_table_index index)
{
void *stk;
sigset_t nset, oset;
struct stk_table *table;
struct trusted_frame *tf;
/*
* Push a dummy trusted frame indicating that the current compartment is
* RTLD.
*/
tf = push_dummy_rtld_trusted_frame(get_trusted_stk());
/*
* Make the function re-entrant by blocking all signals and re-check
* whether the stack needs to be allocated.
*/
SIGFILLSET(nset);
sigprocmask(SIG_SETMASK, &nset, &oset);
table = get_stk_table();
stk = get_or_create_untrusted_stk(index_to_cid(index), &table);
sigprocmask(SIG_SETMASK, &oset, NULL);
tf = pop_dummy_rtld_trusted_frame(tf);
return (stk);
}
/*
* Stack unwinding
*
* APIs exposed to stack unwinders (e.g., libc setjmp/longjmp and libunwind)
*/
/*
* Assembly functions that are tail-called when compartmentalisation is
* disabled.
*/
uintptr_t _rtld_unw_getcontext_epilogue(uintptr_t, void **);
struct jmp_args _rtld_unw_setcontext_epilogue(struct jmp_args, void *, void **);
int
c18n_is_tramp(uintptr_t pc, const struct trusted_frame *tf)
{
if (!cheri_gettag(pc))
return (0);
return (pc == tf->landing);
}
void *
dl_c18n_get_trusted_stack(uintptr_t pc)
{
/*
* Return a sealed capability to the caller's trusted frame. But if the
* caller is entered via a trampoline and a return capability to said
* trampoline is passed as the argument, return a sealed capability to
* the trusted frame of the caller's own caller.
*/
struct trusted_frame *tf;
if (!C18N_ENABLED)
return (NULL);
tf = get_trusted_stk()->previous;
if (c18n_is_tramp(pc, tf))
tf = tf->previous;
return (cheri_seal(tf, sealer_trusted_stk));
}
/*
* XXX Dapeng: These functions are kept here for compatibility with old libc and
* libunwind.
*/
uintptr_t _rtld_setjmp(uintptr_t, void **);
uintptr_t _rtld_unw_getcontext(uintptr_t, void **);
uintptr_t
_rtld_setjmp(uintptr_t ret, void **buf)
{
*buf = dl_c18n_get_trusted_stack(0);
return (ret);
}
uintptr_t
_rtld_unw_getcontext(uintptr_t ret, void **buf)
{
if (!C18N_ENABLED) {
__attribute__((musttail))
return (_rtld_unw_getcontext_epilogue(ret, buf));
}
*buf = dl_c18n_get_trusted_stack(0);
return (ret);
}
/*
* Returning this struct allows us to control the content of unused return value
* registers.
*/
struct jmp_args { uintptr_t ret1; uintptr_t ret2; };
void
dl_c18n_unwind_trusted_stack(void *rcsp, void *target)
{
/*
* Traverse the trusted stack and unwind the untrusted stack of each
* compartment until reaching the target compartment. Then return to the
* target compartment while installing the untrusted stack passed by the
* argument.
*/
void **ospp;
compart_id_t cid;
stk_table_index index;
struct stk_table *table;
struct trusted_frame *cur, *tf;
sigset_t nset, oset;
if (!C18N_ENABLED)
return;
/*
* Make the function re-entrant by blocking all signals.
*/
SIGFILLSET(nset);
sigprocmask(SIG_SETMASK, &nset, &oset);
tf = get_trusted_stk();
target = cheri_unseal(target, sealer_trusted_stk);
if (!cheri_is_subset(tf, target) ||
(ptraddr_t)tf->previous >= (ptraddr_t)target) {
rtld_fdprintf(STDERR_FILENO,
"c18n: Illegal unwind from %#p to %#p\n", tf, target);
abort();
}
/*
* Unwind each frame before the target frame.
*/
cur = tf;
table = get_stk_table();
do {
index = cur->caller;
cid = index_to_cid(index);
ospp = &table->entries[cid].stack;
if ((ptraddr_t)*ospp > (ptraddr_t)cur->osp) {
rtld_fdprintf(STDERR_FILENO,
"c18n: Cannot unwind %s from %#p to %#p\n",
comparts.data[cid].name, *ospp, cur->osp);
abort();
}
*ospp = cur->osp;
cur = cur->previous;
} while ((ptraddr_t)cur < (ptraddr_t)target);
if ((ptraddr_t)cur != (ptraddr_t)target) {
rtld_fdprintf(STDERR_FILENO,
"c18n: Illegal unwind from %#p to %#p\n", cur, target);
abort();
}
/*
* Link the topmost trusted frame to the target frame. Modify the
* topmost trusted frame to restore the untrusted stack when it is
* popped.
*/