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