xref: /openbsd-src/gnu/llvm/compiler-rt/lib/safestack/safestack.cpp (revision 3cab2bb3f667058bece8e38b12449a63a9d73c4b)
1*3cab2bb3Spatrick //===-- safestack.cpp -----------------------------------------------------===//
2*3cab2bb3Spatrick //
3*3cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*3cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
5*3cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*3cab2bb3Spatrick //
7*3cab2bb3Spatrick //===----------------------------------------------------------------------===//
8*3cab2bb3Spatrick //
9*3cab2bb3Spatrick // This file implements the runtime support for the safe stack protection
10*3cab2bb3Spatrick // mechanism. The runtime manages allocation/deallocation of the unsafe stack
11*3cab2bb3Spatrick // for the main thread, as well as all pthreads that are created/destroyed
12*3cab2bb3Spatrick // during program execution.
13*3cab2bb3Spatrick //
14*3cab2bb3Spatrick //===----------------------------------------------------------------------===//
15*3cab2bb3Spatrick 
16*3cab2bb3Spatrick #include "safestack_platform.h"
17*3cab2bb3Spatrick #include "safestack_util.h"
18*3cab2bb3Spatrick 
19*3cab2bb3Spatrick #include <errno.h>
20*3cab2bb3Spatrick #include <sys/resource.h>
21*3cab2bb3Spatrick 
22*3cab2bb3Spatrick #include "interception/interception.h"
23*3cab2bb3Spatrick 
24*3cab2bb3Spatrick using namespace safestack;
25*3cab2bb3Spatrick 
26*3cab2bb3Spatrick // TODO: To make accessing the unsafe stack pointer faster, we plan to
27*3cab2bb3Spatrick // eventually store it directly in the thread control block data structure on
28*3cab2bb3Spatrick // platforms where this structure is pointed to by %fs or %gs. This is exactly
29*3cab2bb3Spatrick // the same mechanism as currently being used by the traditional stack
30*3cab2bb3Spatrick // protector pass to store the stack guard (see getStackCookieLocation()
31*3cab2bb3Spatrick // function above). Doing so requires changing the tcbhead_t struct in glibc
32*3cab2bb3Spatrick // on Linux and tcb struct in libc on FreeBSD.
33*3cab2bb3Spatrick //
34*3cab2bb3Spatrick // For now, store it in a thread-local variable.
35*3cab2bb3Spatrick extern "C" {
36*3cab2bb3Spatrick __attribute__((visibility(
37*3cab2bb3Spatrick     "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
38*3cab2bb3Spatrick }
39*3cab2bb3Spatrick 
40*3cab2bb3Spatrick namespace {
41*3cab2bb3Spatrick 
42*3cab2bb3Spatrick // TODO: The runtime library does not currently protect the safe stack beyond
43*3cab2bb3Spatrick // relying on the system-enforced ASLR. The protection of the (safe) stack can
44*3cab2bb3Spatrick // be provided by three alternative features:
45*3cab2bb3Spatrick //
46*3cab2bb3Spatrick // 1) Protection via hardware segmentation on x86-32 and some x86-64
47*3cab2bb3Spatrick // architectures: the (safe) stack segment (implicitly accessed via the %ss
48*3cab2bb3Spatrick // segment register) can be separated from the data segment (implicitly
49*3cab2bb3Spatrick // accessed via the %ds segment register). Dereferencing a pointer to the safe
50*3cab2bb3Spatrick // segment would result in a segmentation fault.
51*3cab2bb3Spatrick //
52*3cab2bb3Spatrick // 2) Protection via software fault isolation: memory writes that are not meant
53*3cab2bb3Spatrick // to access the safe stack can be prevented from doing so through runtime
54*3cab2bb3Spatrick // instrumentation. One way to do it is to allocate the safe stack(s) in the
55*3cab2bb3Spatrick // upper half of the userspace and bitmask the corresponding upper bit of the
56*3cab2bb3Spatrick // memory addresses of memory writes that are not meant to access the safe
57*3cab2bb3Spatrick // stack.
58*3cab2bb3Spatrick //
59*3cab2bb3Spatrick // 3) Protection via information hiding on 64 bit architectures: the location
60*3cab2bb3Spatrick // of the safe stack(s) can be randomized through secure mechanisms, and the
61*3cab2bb3Spatrick // leakage of the stack pointer can be prevented. Currently, libc can leak the
62*3cab2bb3Spatrick // stack pointer in several ways (e.g. in longjmp, signal handling, user-level
63*3cab2bb3Spatrick // context switching related functions, etc.). These can be fixed in libc and
64*3cab2bb3Spatrick // in other low-level libraries, by either eliminating the escaping/dumping of
65*3cab2bb3Spatrick // the stack pointer (i.e., %rsp) when that's possible, or by using
66*3cab2bb3Spatrick // encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
67*3cab2bb3Spatrick // we control and protect better, as is already done for setjmp in glibc.)
68*3cab2bb3Spatrick // Furthermore, a static machine code level verifier can be ran after code
69*3cab2bb3Spatrick // generation to make sure that the stack pointer is never written to memory,
70*3cab2bb3Spatrick // or if it is, its written on the safe stack.
71*3cab2bb3Spatrick //
72*3cab2bb3Spatrick // Finally, while the Unsafe Stack pointer is currently stored in a thread
73*3cab2bb3Spatrick // local variable, with libc support it could be stored in the TCB (thread
74*3cab2bb3Spatrick // control block) as well, eliminating another level of indirection and making
75*3cab2bb3Spatrick // such accesses faster. Alternatively, dedicating a separate register for
76*3cab2bb3Spatrick // storing it would also be possible.
77*3cab2bb3Spatrick 
78*3cab2bb3Spatrick /// Minimum stack alignment for the unsafe stack.
79*3cab2bb3Spatrick const unsigned kStackAlign = 16;
80*3cab2bb3Spatrick 
81*3cab2bb3Spatrick /// Default size of the unsafe stack. This value is only used if the stack
82*3cab2bb3Spatrick /// size rlimit is set to infinity.
83*3cab2bb3Spatrick const unsigned kDefaultUnsafeStackSize = 0x2800000;
84*3cab2bb3Spatrick 
85*3cab2bb3Spatrick // Per-thread unsafe stack information. It's not frequently accessed, so there
86*3cab2bb3Spatrick // it can be kept out of the tcb in normal thread-local variables.
87*3cab2bb3Spatrick __thread void *unsafe_stack_start = nullptr;
88*3cab2bb3Spatrick __thread size_t unsafe_stack_size = 0;
89*3cab2bb3Spatrick __thread size_t unsafe_stack_guard = 0;
90*3cab2bb3Spatrick 
unsafe_stack_alloc(size_t size,size_t guard)91*3cab2bb3Spatrick inline void *unsafe_stack_alloc(size_t size, size_t guard) {
92*3cab2bb3Spatrick   SFS_CHECK(size + guard >= size);
93*3cab2bb3Spatrick   void *addr = Mmap(nullptr, size + guard, PROT_READ | PROT_WRITE,
94*3cab2bb3Spatrick                     MAP_PRIVATE | MAP_ANON, -1, 0);
95*3cab2bb3Spatrick   SFS_CHECK(MAP_FAILED != addr);
96*3cab2bb3Spatrick   Mprotect(addr, guard, PROT_NONE);
97*3cab2bb3Spatrick   return (char *)addr + guard;
98*3cab2bb3Spatrick }
99*3cab2bb3Spatrick 
unsafe_stack_setup(void * start,size_t size,size_t guard)100*3cab2bb3Spatrick inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
101*3cab2bb3Spatrick   SFS_CHECK((char *)start + size >= (char *)start);
102*3cab2bb3Spatrick   SFS_CHECK((char *)start + guard >= (char *)start);
103*3cab2bb3Spatrick   void *stack_ptr = (char *)start + size;
104*3cab2bb3Spatrick   SFS_CHECK((((size_t)stack_ptr) & (kStackAlign - 1)) == 0);
105*3cab2bb3Spatrick 
106*3cab2bb3Spatrick   __safestack_unsafe_stack_ptr = stack_ptr;
107*3cab2bb3Spatrick   unsafe_stack_start = start;
108*3cab2bb3Spatrick   unsafe_stack_size = size;
109*3cab2bb3Spatrick   unsafe_stack_guard = guard;
110*3cab2bb3Spatrick }
111*3cab2bb3Spatrick 
112*3cab2bb3Spatrick /// Thread data for the cleanup handler
113*3cab2bb3Spatrick pthread_key_t thread_cleanup_key;
114*3cab2bb3Spatrick 
115*3cab2bb3Spatrick /// Safe stack per-thread information passed to the thread_start function
116*3cab2bb3Spatrick struct tinfo {
117*3cab2bb3Spatrick   void *(*start_routine)(void *);
118*3cab2bb3Spatrick   void *start_routine_arg;
119*3cab2bb3Spatrick 
120*3cab2bb3Spatrick   void *unsafe_stack_start;
121*3cab2bb3Spatrick   size_t unsafe_stack_size;
122*3cab2bb3Spatrick   size_t unsafe_stack_guard;
123*3cab2bb3Spatrick };
124*3cab2bb3Spatrick 
125*3cab2bb3Spatrick /// Wrap the thread function in order to deallocate the unsafe stack when the
126*3cab2bb3Spatrick /// thread terminates by returning from its main function.
thread_start(void * arg)127*3cab2bb3Spatrick void *thread_start(void *arg) {
128*3cab2bb3Spatrick   struct tinfo *tinfo = (struct tinfo *)arg;
129*3cab2bb3Spatrick 
130*3cab2bb3Spatrick   void *(*start_routine)(void *) = tinfo->start_routine;
131*3cab2bb3Spatrick   void *start_routine_arg = tinfo->start_routine_arg;
132*3cab2bb3Spatrick 
133*3cab2bb3Spatrick   // Setup the unsafe stack; this will destroy tinfo content
134*3cab2bb3Spatrick   unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
135*3cab2bb3Spatrick                      tinfo->unsafe_stack_guard);
136*3cab2bb3Spatrick 
137*3cab2bb3Spatrick   // Make sure out thread-specific destructor will be called
138*3cab2bb3Spatrick   pthread_setspecific(thread_cleanup_key, (void *)1);
139*3cab2bb3Spatrick 
140*3cab2bb3Spatrick   return start_routine(start_routine_arg);
141*3cab2bb3Spatrick }
142*3cab2bb3Spatrick 
143*3cab2bb3Spatrick /// Linked list used to store exiting threads stack/thread information.
144*3cab2bb3Spatrick struct thread_stack_ll {
145*3cab2bb3Spatrick   struct thread_stack_ll *next;
146*3cab2bb3Spatrick   void *stack_base;
147*3cab2bb3Spatrick   size_t size;
148*3cab2bb3Spatrick   pid_t pid;
149*3cab2bb3Spatrick   ThreadId tid;
150*3cab2bb3Spatrick };
151*3cab2bb3Spatrick 
152*3cab2bb3Spatrick /// Linked list of unsafe stacks for threads that are exiting. We delay
153*3cab2bb3Spatrick /// unmapping them until the thread exits.
154*3cab2bb3Spatrick thread_stack_ll *thread_stacks = nullptr;
155*3cab2bb3Spatrick pthread_mutex_t thread_stacks_mutex = PTHREAD_MUTEX_INITIALIZER;
156*3cab2bb3Spatrick 
157*3cab2bb3Spatrick /// Thread-specific data destructor. We want to free the unsafe stack only after
158*3cab2bb3Spatrick /// this thread is terminated. libc can call functions in safestack-instrumented
159*3cab2bb3Spatrick /// code (like free) after thread-specific data destructors have run.
thread_cleanup_handler(void * _iter)160*3cab2bb3Spatrick void thread_cleanup_handler(void *_iter) {
161*3cab2bb3Spatrick   SFS_CHECK(unsafe_stack_start != nullptr);
162*3cab2bb3Spatrick   pthread_setspecific(thread_cleanup_key, NULL);
163*3cab2bb3Spatrick 
164*3cab2bb3Spatrick   pthread_mutex_lock(&thread_stacks_mutex);
165*3cab2bb3Spatrick   // Temporary list to hold the previous threads stacks so we don't hold the
166*3cab2bb3Spatrick   // thread_stacks_mutex for long.
167*3cab2bb3Spatrick   thread_stack_ll *temp_stacks = thread_stacks;
168*3cab2bb3Spatrick   thread_stacks = nullptr;
169*3cab2bb3Spatrick   pthread_mutex_unlock(&thread_stacks_mutex);
170*3cab2bb3Spatrick 
171*3cab2bb3Spatrick   pid_t pid = getpid();
172*3cab2bb3Spatrick   ThreadId tid = GetTid();
173*3cab2bb3Spatrick 
174*3cab2bb3Spatrick   // Free stacks for dead threads
175*3cab2bb3Spatrick   thread_stack_ll **stackp = &temp_stacks;
176*3cab2bb3Spatrick   while (*stackp) {
177*3cab2bb3Spatrick     thread_stack_ll *stack = *stackp;
178*3cab2bb3Spatrick     if (stack->pid != pid ||
179*3cab2bb3Spatrick         (-1 == TgKill(stack->pid, stack->tid, 0) && errno == ESRCH)) {
180*3cab2bb3Spatrick       Munmap(stack->stack_base, stack->size);
181*3cab2bb3Spatrick       *stackp = stack->next;
182*3cab2bb3Spatrick       free(stack);
183*3cab2bb3Spatrick     } else
184*3cab2bb3Spatrick       stackp = &stack->next;
185*3cab2bb3Spatrick   }
186*3cab2bb3Spatrick 
187*3cab2bb3Spatrick   thread_stack_ll *cur_stack =
188*3cab2bb3Spatrick       (thread_stack_ll *)malloc(sizeof(thread_stack_ll));
189*3cab2bb3Spatrick   cur_stack->stack_base = (char *)unsafe_stack_start - unsafe_stack_guard;
190*3cab2bb3Spatrick   cur_stack->size = unsafe_stack_size + unsafe_stack_guard;
191*3cab2bb3Spatrick   cur_stack->pid = pid;
192*3cab2bb3Spatrick   cur_stack->tid = tid;
193*3cab2bb3Spatrick 
194*3cab2bb3Spatrick   pthread_mutex_lock(&thread_stacks_mutex);
195*3cab2bb3Spatrick   // Merge thread_stacks with the current thread's stack and any remaining
196*3cab2bb3Spatrick   // temp_stacks
197*3cab2bb3Spatrick   *stackp = thread_stacks;
198*3cab2bb3Spatrick   cur_stack->next = temp_stacks;
199*3cab2bb3Spatrick   thread_stacks = cur_stack;
200*3cab2bb3Spatrick   pthread_mutex_unlock(&thread_stacks_mutex);
201*3cab2bb3Spatrick 
202*3cab2bb3Spatrick   unsafe_stack_start = nullptr;
203*3cab2bb3Spatrick }
204*3cab2bb3Spatrick 
205*3cab2bb3Spatrick void EnsureInterceptorsInitialized();
206*3cab2bb3Spatrick 
207*3cab2bb3Spatrick /// Intercept thread creation operation to allocate and setup the unsafe stack
INTERCEPTOR(int,pthread_create,pthread_t * thread,const pthread_attr_t * attr,void * (* start_routine)(void *),void * arg)208*3cab2bb3Spatrick INTERCEPTOR(int, pthread_create, pthread_t *thread,
209*3cab2bb3Spatrick             const pthread_attr_t *attr,
210*3cab2bb3Spatrick             void *(*start_routine)(void*), void *arg) {
211*3cab2bb3Spatrick   EnsureInterceptorsInitialized();
212*3cab2bb3Spatrick   size_t size = 0;
213*3cab2bb3Spatrick   size_t guard = 0;
214*3cab2bb3Spatrick 
215*3cab2bb3Spatrick   if (attr) {
216*3cab2bb3Spatrick     pthread_attr_getstacksize(attr, &size);
217*3cab2bb3Spatrick     pthread_attr_getguardsize(attr, &guard);
218*3cab2bb3Spatrick   } else {
219*3cab2bb3Spatrick     // get pthread default stack size
220*3cab2bb3Spatrick     pthread_attr_t tmpattr;
221*3cab2bb3Spatrick     pthread_attr_init(&tmpattr);
222*3cab2bb3Spatrick     pthread_attr_getstacksize(&tmpattr, &size);
223*3cab2bb3Spatrick     pthread_attr_getguardsize(&tmpattr, &guard);
224*3cab2bb3Spatrick     pthread_attr_destroy(&tmpattr);
225*3cab2bb3Spatrick   }
226*3cab2bb3Spatrick 
227*3cab2bb3Spatrick   SFS_CHECK(size);
228*3cab2bb3Spatrick   size = RoundUpTo(size, kStackAlign);
229*3cab2bb3Spatrick 
230*3cab2bb3Spatrick   void *addr = unsafe_stack_alloc(size, guard);
231*3cab2bb3Spatrick   // Put tinfo at the end of the buffer. guard may be not page aligned.
232*3cab2bb3Spatrick   // If that is so then some bytes after addr can be mprotected.
233*3cab2bb3Spatrick   struct tinfo *tinfo =
234*3cab2bb3Spatrick       (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
235*3cab2bb3Spatrick   tinfo->start_routine = start_routine;
236*3cab2bb3Spatrick   tinfo->start_routine_arg = arg;
237*3cab2bb3Spatrick   tinfo->unsafe_stack_start = addr;
238*3cab2bb3Spatrick   tinfo->unsafe_stack_size = size;
239*3cab2bb3Spatrick   tinfo->unsafe_stack_guard = guard;
240*3cab2bb3Spatrick 
241*3cab2bb3Spatrick   return REAL(pthread_create)(thread, attr, thread_start, tinfo);
242*3cab2bb3Spatrick }
243*3cab2bb3Spatrick 
244*3cab2bb3Spatrick pthread_mutex_t interceptor_init_mutex = PTHREAD_MUTEX_INITIALIZER;
245*3cab2bb3Spatrick bool interceptors_inited = false;
246*3cab2bb3Spatrick 
EnsureInterceptorsInitialized()247*3cab2bb3Spatrick void EnsureInterceptorsInitialized() {
248*3cab2bb3Spatrick   MutexLock lock(interceptor_init_mutex);
249*3cab2bb3Spatrick   if (interceptors_inited)
250*3cab2bb3Spatrick     return;
251*3cab2bb3Spatrick 
252*3cab2bb3Spatrick   // Initialize pthread interceptors for thread allocation
253*3cab2bb3Spatrick   INTERCEPT_FUNCTION(pthread_create);
254*3cab2bb3Spatrick 
255*3cab2bb3Spatrick   interceptors_inited = true;
256*3cab2bb3Spatrick }
257*3cab2bb3Spatrick 
258*3cab2bb3Spatrick }  // namespace
259*3cab2bb3Spatrick 
260*3cab2bb3Spatrick extern "C" __attribute__((visibility("default")))
261*3cab2bb3Spatrick #if !SANITIZER_CAN_USE_PREINIT_ARRAY
262*3cab2bb3Spatrick // On ELF platforms, the constructor is invoked using .preinit_array (see below)
263*3cab2bb3Spatrick __attribute__((constructor(0)))
264*3cab2bb3Spatrick #endif
__safestack_init()265*3cab2bb3Spatrick void __safestack_init() {
266*3cab2bb3Spatrick   // Determine the stack size for the main thread.
267*3cab2bb3Spatrick   size_t size = kDefaultUnsafeStackSize;
268*3cab2bb3Spatrick   size_t guard = 4096;
269*3cab2bb3Spatrick 
270*3cab2bb3Spatrick   struct rlimit limit;
271*3cab2bb3Spatrick   if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
272*3cab2bb3Spatrick     size = limit.rlim_cur;
273*3cab2bb3Spatrick 
274*3cab2bb3Spatrick   // Allocate unsafe stack for main thread
275*3cab2bb3Spatrick   void *addr = unsafe_stack_alloc(size, guard);
276*3cab2bb3Spatrick   unsafe_stack_setup(addr, size, guard);
277*3cab2bb3Spatrick 
278*3cab2bb3Spatrick   // Setup the cleanup handler
279*3cab2bb3Spatrick   pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
280*3cab2bb3Spatrick }
281*3cab2bb3Spatrick 
282*3cab2bb3Spatrick #if SANITIZER_CAN_USE_PREINIT_ARRAY
283*3cab2bb3Spatrick // On ELF platforms, run safestack initialization before any other constructors.
284*3cab2bb3Spatrick // On other platforms we use the constructor attribute to arrange to run our
285*3cab2bb3Spatrick // initialization early.
286*3cab2bb3Spatrick extern "C" {
287*3cab2bb3Spatrick __attribute__((section(".preinit_array"),
288*3cab2bb3Spatrick                used)) void (*__safestack_preinit)(void) = __safestack_init;
289*3cab2bb3Spatrick }
290*3cab2bb3Spatrick #endif
291*3cab2bb3Spatrick 
292*3cab2bb3Spatrick extern "C"
__get_unsafe_stack_bottom()293*3cab2bb3Spatrick     __attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
294*3cab2bb3Spatrick   return unsafe_stack_start;
295*3cab2bb3Spatrick }
296*3cab2bb3Spatrick 
297*3cab2bb3Spatrick extern "C"
__get_unsafe_stack_top()298*3cab2bb3Spatrick     __attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
299*3cab2bb3Spatrick   return (char*)unsafe_stack_start + unsafe_stack_size;
300*3cab2bb3Spatrick }
301*3cab2bb3Spatrick 
302*3cab2bb3Spatrick extern "C"
__get_unsafe_stack_start()303*3cab2bb3Spatrick     __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
304*3cab2bb3Spatrick   return unsafe_stack_start;
305*3cab2bb3Spatrick }
306*3cab2bb3Spatrick 
307*3cab2bb3Spatrick extern "C"
__get_unsafe_stack_ptr()308*3cab2bb3Spatrick     __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
309*3cab2bb3Spatrick   return __safestack_unsafe_stack_ptr;
310*3cab2bb3Spatrick }
311