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