blob: b194b6cfa8f9c35e480b391e0767fafdbb7f6f0e [file] [log] [blame]
Peter Collingbourneb64d0b12015-06-15 21:08:47 +00001//===-- safestack.cc ------------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the runtime support for the safe stack protection
11// mechanism. The runtime manages allocation/deallocation of the unsafe stack
12// for the main thread, as well as all pthreads that are created/destroyed
13// during program execution.
14//
15//===----------------------------------------------------------------------===//
16
17#include <limits.h>
18#include <pthread.h>
19#include <stddef.h>
Peter Collingbourne84540442015-06-24 17:23:13 +000020#include <stdint.h>
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +000021#include <unistd.h>
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000022#include <sys/resource.h>
Peter Collingbourne19e86192015-06-24 18:16:05 +000023#include <sys/types.h>
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000024#include <sys/user.h>
25
26#include "interception/interception.h"
27#include "sanitizer_common/sanitizer_common.h"
28
Peter Collingbourneadbde272015-06-23 22:26:48 +000029// TODO: The runtime library does not currently protect the safe stack beyond
30// relying on the system-enforced ASLR. The protection of the (safe) stack can
31// be provided by three alternative features:
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000032//
Peter Collingbourneadbde272015-06-23 22:26:48 +000033// 1) Protection via hardware segmentation on x86-32 and some x86-64
34// architectures: the (safe) stack segment (implicitly accessed via the %ss
35// segment register) can be separated from the data segment (implicitly
36// accessed via the %ds segment register). Dereferencing a pointer to the safe
37// segment would result in a segmentation fault.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000038//
Peter Collingbourneadbde272015-06-23 22:26:48 +000039// 2) Protection via software fault isolation: memory writes that are not meant
40// to access the safe stack can be prevented from doing so through runtime
41// instrumentation. One way to do it is to allocate the safe stack(s) in the
42// upper half of the userspace and bitmask the corresponding upper bit of the
43// memory addresses of memory writes that are not meant to access the safe
44// stack.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000045//
Peter Collingbourneadbde272015-06-23 22:26:48 +000046// 3) Protection via information hiding on 64 bit architectures: the location
47// of the safe stack(s) can be randomized through secure mechanisms, and the
48// leakage of the stack pointer can be prevented. Currently, libc can leak the
49// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
50// context switching related functions, etc.). These can be fixed in libc and
51// in other low-level libraries, by either eliminating the escaping/dumping of
52// the stack pointer (i.e., %rsp) when that's possible, or by using
53// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
54// we control and protect better, as is already done for setjmp in glibc.)
55// Furthermore, a static machine code level verifier can be ran after code
56// generation to make sure that the stack pointer is never written to memory,
57// or if it is, its written on the safe stack.
58//
59// Finally, while the Unsafe Stack pointer is currently stored in a thread
60// local variable, with libc support it could be stored in the TCB (thread
61// control block) as well, eliminating another level of indirection and making
62// such accesses faster. Alternatively, dedicating a separate register for
63// storing it would also be possible.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000064
65/// Minimum stack alignment for the unsafe stack.
66const unsigned kStackAlign = 16;
67
68/// Default size of the unsafe stack. This value is only used if the stack
69/// size rlimit is set to infinity.
70const unsigned kDefaultUnsafeStackSize = 0x2800000;
71
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +000072/// Runtime page size obtained through sysconf
73static unsigned pageSize;
74
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000075// TODO: To make accessing the unsafe stack pointer faster, we plan to
76// eventually store it directly in the thread control block data structure on
77// platforms where this structure is pointed to by %fs or %gs. This is exactly
78// the same mechanism as currently being used by the traditional stack
79// protector pass to store the stack guard (see getStackCookieLocation()
80// function above). Doing so requires changing the tcbhead_t struct in glibc
81// on Linux and tcb struct in libc on FreeBSD.
82//
83// For now, store it in a thread-local variable.
84extern "C" {
85__attribute__((visibility(
86 "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
87}
88
89// Per-thread unsafe stack information. It's not frequently accessed, so there
90// it can be kept out of the tcb in normal thread-local variables.
91static __thread void *unsafe_stack_start = nullptr;
92static __thread size_t unsafe_stack_size = 0;
93static __thread size_t unsafe_stack_guard = 0;
94
Anna Zaks691644f2016-09-15 21:02:18 +000095using namespace __sanitizer;
96
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000097static inline void *unsafe_stack_alloc(size_t size, size_t guard) {
98 CHECK_GE(size + guard, size);
99 void *addr = MmapOrDie(size + guard, "unsafe_stack_alloc");
100 MprotectNoAccess((uptr)addr, (uptr)guard);
101 return (char *)addr + guard;
102}
103
104static inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
105 CHECK_GE((char *)start + size, (char *)start);
106 CHECK_GE((char *)start + guard, (char *)start);
107 void *stack_ptr = (char *)start + size;
108 CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);
109
110 __safestack_unsafe_stack_ptr = stack_ptr;
111 unsafe_stack_start = start;
112 unsafe_stack_size = size;
113 unsafe_stack_guard = guard;
114}
115
116static void unsafe_stack_free() {
117 if (unsafe_stack_start) {
118 UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,
119 unsafe_stack_size + unsafe_stack_guard);
120 }
121 unsafe_stack_start = nullptr;
122}
123
124/// Thread data for the cleanup handler
125static pthread_key_t thread_cleanup_key;
126
127/// Safe stack per-thread information passed to the thread_start function
128struct tinfo {
129 void *(*start_routine)(void *);
130 void *start_routine_arg;
131
132 void *unsafe_stack_start;
133 size_t unsafe_stack_size;
134 size_t unsafe_stack_guard;
135};
136
137/// Wrap the thread function in order to deallocate the unsafe stack when the
138/// thread terminates by returning from its main function.
139static void *thread_start(void *arg) {
140 struct tinfo *tinfo = (struct tinfo *)arg;
141
142 void *(*start_routine)(void *) = tinfo->start_routine;
143 void *start_routine_arg = tinfo->start_routine_arg;
144
145 // Setup the unsafe stack; this will destroy tinfo content
146 unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
147 tinfo->unsafe_stack_guard);
148
149 // Make sure out thread-specific destructor will be called
150 // FIXME: we can do this only any other specific key is set by
151 // intercepting the pthread_setspecific function itself
152 pthread_setspecific(thread_cleanup_key, (void *)1);
153
154 return start_routine(start_routine_arg);
155}
156
157/// Thread-specific data destructor
158static void thread_cleanup_handler(void *_iter) {
159 // We want to free the unsafe stack only after all other destructors
160 // have already run. We force this function to be called multiple times.
161 // User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1
162 // times might still end up executing after the unsafe stack is deallocated.
163 size_t iter = (size_t)_iter;
164 if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {
165 pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));
166 } else {
167 // This is the last iteration
168 unsafe_stack_free();
169 }
170}
171
172/// Intercept thread creation operation to allocate and setup the unsafe stack
173INTERCEPTOR(int, pthread_create, pthread_t *thread,
174 const pthread_attr_t *attr,
175 void *(*start_routine)(void*), void *arg) {
176
177 size_t size = 0;
178 size_t guard = 0;
179
Vedant Kumar59ba7b82015-10-01 00:22:21 +0000180 if (attr) {
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000181 pthread_attr_getstacksize(attr, &size);
182 pthread_attr_getguardsize(attr, &guard);
183 } else {
184 // get pthread default stack size
185 pthread_attr_t tmpattr;
186 pthread_attr_init(&tmpattr);
187 pthread_attr_getstacksize(&tmpattr, &size);
188 pthread_attr_getguardsize(&tmpattr, &guard);
189 pthread_attr_destroy(&tmpattr);
190 }
191
192 CHECK_NE(size, 0);
193 CHECK_EQ((size & (kStackAlign - 1)), 0);
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +0000194 CHECK_EQ((guard & (pageSize - 1)), 0);
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000195
196 void *addr = unsafe_stack_alloc(size, guard);
197 struct tinfo *tinfo =
198 (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
199 tinfo->start_routine = start_routine;
200 tinfo->start_routine_arg = arg;
201 tinfo->unsafe_stack_start = addr;
202 tinfo->unsafe_stack_size = size;
203 tinfo->unsafe_stack_guard = guard;
204
205 return REAL(pthread_create)(thread, attr, thread_start, tinfo);
206}
207
208extern "C" __attribute__((visibility("default")))
209#if !SANITIZER_CAN_USE_PREINIT_ARRAY
210// On ELF platforms, the constructor is invoked using .preinit_array (see below)
211__attribute__((constructor(0)))
212#endif
213void __safestack_init() {
214 // Determine the stack size for the main thread.
215 size_t size = kDefaultUnsafeStackSize;
216 size_t guard = 4096;
217
218 struct rlimit limit;
219 if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
220 size = limit.rlim_cur;
221
222 // Allocate unsafe stack for main thread
223 void *addr = unsafe_stack_alloc(size, guard);
224
225 unsafe_stack_setup(addr, size, guard);
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +0000226 pageSize = sysconf(_SC_PAGESIZE);
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000227
228 // Initialize pthread interceptors for thread allocation
229 INTERCEPT_FUNCTION(pthread_create);
230
231 // Setup the cleanup handler
232 pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
233}
234
235#if SANITIZER_CAN_USE_PREINIT_ARRAY
236// On ELF platforms, run safestack initialization before any other constructors.
237// On other platforms we use the constructor attribute to arrange to run our
238// initialization early.
239extern "C" {
240__attribute__((section(".preinit_array"),
241 used)) void (*__safestack_preinit)(void) = __safestack_init;
242}
243#endif
244
245extern "C"
246 __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
247 return unsafe_stack_start;
248}
249
250extern "C"
251 __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
252 return __safestack_unsafe_stack_ptr;
253}