blob: 920b89b5e7cca62c4848236032015b3cfc0d9b94 [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
Vlad Tsyrklevicha24ecc32018-08-09 22:56:41 +000017#include <errno.h>
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000018#include <limits.h>
19#include <pthread.h>
20#include <stddef.h>
Peter Collingbourne84540442015-06-24 17:23:13 +000021#include <stdint.h>
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +000022#include <unistd.h>
Vlad Tsyrklevicha24ecc32018-08-09 22:56:41 +000023#include <stdlib.h>
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000024#include <sys/resource.h>
Peter Collingbourne19e86192015-06-24 18:16:05 +000025#include <sys/types.h>
Kamil Rytarowskifbd51b92017-08-10 18:40:09 +000026#if !defined(__NetBSD__)
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000027#include <sys/user.h>
Kamil Rytarowskifbd51b92017-08-10 18:40:09 +000028#endif
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000029
30#include "interception/interception.h"
31#include "sanitizer_common/sanitizer_common.h"
32
Peter Collingbourneadbde272015-06-23 22:26:48 +000033// TODO: The runtime library does not currently protect the safe stack beyond
34// relying on the system-enforced ASLR. The protection of the (safe) stack can
35// be provided by three alternative features:
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000036//
Peter Collingbourneadbde272015-06-23 22:26:48 +000037// 1) Protection via hardware segmentation on x86-32 and some x86-64
38// architectures: the (safe) stack segment (implicitly accessed via the %ss
39// segment register) can be separated from the data segment (implicitly
40// accessed via the %ds segment register). Dereferencing a pointer to the safe
41// segment would result in a segmentation fault.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000042//
Peter Collingbourneadbde272015-06-23 22:26:48 +000043// 2) Protection via software fault isolation: memory writes that are not meant
44// to access the safe stack can be prevented from doing so through runtime
45// instrumentation. One way to do it is to allocate the safe stack(s) in the
46// upper half of the userspace and bitmask the corresponding upper bit of the
47// memory addresses of memory writes that are not meant to access the safe
48// stack.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000049//
Peter Collingbourneadbde272015-06-23 22:26:48 +000050// 3) Protection via information hiding on 64 bit architectures: the location
51// of the safe stack(s) can be randomized through secure mechanisms, and the
52// leakage of the stack pointer can be prevented. Currently, libc can leak the
53// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
54// context switching related functions, etc.). These can be fixed in libc and
55// in other low-level libraries, by either eliminating the escaping/dumping of
56// the stack pointer (i.e., %rsp) when that's possible, or by using
57// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
58// we control and protect better, as is already done for setjmp in glibc.)
59// Furthermore, a static machine code level verifier can be ran after code
60// generation to make sure that the stack pointer is never written to memory,
61// or if it is, its written on the safe stack.
62//
63// Finally, while the Unsafe Stack pointer is currently stored in a thread
64// local variable, with libc support it could be stored in the TCB (thread
65// control block) as well, eliminating another level of indirection and making
66// such accesses faster. Alternatively, dedicating a separate register for
67// storing it would also be possible.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000068
69/// Minimum stack alignment for the unsafe stack.
70const unsigned kStackAlign = 16;
71
72/// Default size of the unsafe stack. This value is only used if the stack
73/// size rlimit is set to infinity.
74const unsigned kDefaultUnsafeStackSize = 0x2800000;
75
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +000076/// Runtime page size obtained through sysconf
77static unsigned pageSize;
78
Peter Collingbourneb64d0b12015-06-15 21:08:47 +000079// TODO: To make accessing the unsafe stack pointer faster, we plan to
80// eventually store it directly in the thread control block data structure on
81// platforms where this structure is pointed to by %fs or %gs. This is exactly
82// the same mechanism as currently being used by the traditional stack
83// protector pass to store the stack guard (see getStackCookieLocation()
84// function above). Doing so requires changing the tcbhead_t struct in glibc
85// on Linux and tcb struct in libc on FreeBSD.
86//
87// For now, store it in a thread-local variable.
88extern "C" {
89__attribute__((visibility(
90 "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
91}
92
93// Per-thread unsafe stack information. It's not frequently accessed, so there
94// it can be kept out of the tcb in normal thread-local variables.
95static __thread void *unsafe_stack_start = nullptr;
96static __thread size_t unsafe_stack_size = 0;
97static __thread size_t unsafe_stack_guard = 0;
98
Anna Zaks691644f2016-09-15 21:02:18 +000099using namespace __sanitizer;
100
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000101static inline void *unsafe_stack_alloc(size_t size, size_t guard) {
102 CHECK_GE(size + guard, size);
103 void *addr = MmapOrDie(size + guard, "unsafe_stack_alloc");
104 MprotectNoAccess((uptr)addr, (uptr)guard);
105 return (char *)addr + guard;
106}
107
108static inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
109 CHECK_GE((char *)start + size, (char *)start);
110 CHECK_GE((char *)start + guard, (char *)start);
111 void *stack_ptr = (char *)start + size;
112 CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);
113
114 __safestack_unsafe_stack_ptr = stack_ptr;
115 unsafe_stack_start = start;
116 unsafe_stack_size = size;
117 unsafe_stack_guard = guard;
118}
119
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000120/// Thread data for the cleanup handler
121static pthread_key_t thread_cleanup_key;
122
123/// Safe stack per-thread information passed to the thread_start function
124struct tinfo {
125 void *(*start_routine)(void *);
126 void *start_routine_arg;
127
128 void *unsafe_stack_start;
129 size_t unsafe_stack_size;
130 size_t unsafe_stack_guard;
131};
132
133/// Wrap the thread function in order to deallocate the unsafe stack when the
134/// thread terminates by returning from its main function.
135static void *thread_start(void *arg) {
136 struct tinfo *tinfo = (struct tinfo *)arg;
137
138 void *(*start_routine)(void *) = tinfo->start_routine;
139 void *start_routine_arg = tinfo->start_routine_arg;
140
141 // Setup the unsafe stack; this will destroy tinfo content
142 unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
143 tinfo->unsafe_stack_guard);
144
145 // Make sure out thread-specific destructor will be called
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000146 pthread_setspecific(thread_cleanup_key, (void *)1);
147
148 return start_routine(start_routine_arg);
149}
150
Vlad Tsyrklevicha24ecc32018-08-09 22:56:41 +0000151/// Linked list used to store exiting threads stack/thread information.
152struct thread_stack_ll {
153 struct thread_stack_ll *next;
154 void *stack_base;
155 pid_t pid;
156 tid_t tid;
157};
158
159/// Linked list of unsafe stacks for threads that are exiting. We delay
160/// unmapping them until the thread exits.
161static thread_stack_ll *thread_stacks = nullptr;
162static pthread_mutex_t thread_stacks_mutex = PTHREAD_MUTEX_INITIALIZER;
163
164/// Thread-specific data destructor. We want to free the unsafe stack only after
165/// this thread is terminated. libc can call functions in safestack-instrumented
166/// code (like free) after thread-specific data destructors have run.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000167static void thread_cleanup_handler(void *_iter) {
Vlad Tsyrklevicha24ecc32018-08-09 22:56:41 +0000168 CHECK_NE(unsafe_stack_start, nullptr);
169 pthread_setspecific(thread_cleanup_key, NULL);
170
171 pthread_mutex_lock(&thread_stacks_mutex);
172 // Temporary list to hold the previous threads stacks so we don't hold the
173 // thread_stacks_mutex for long.
174 thread_stack_ll *temp_stacks = thread_stacks;
175 thread_stacks = nullptr;
176 pthread_mutex_unlock(&thread_stacks_mutex);
177
178 pid_t pid = getpid();
179 tid_t tid = GetTid();
180
181 // Free stacks for dead threads
182 thread_stack_ll **stackp = &temp_stacks;
183 while (*stackp) {
184 thread_stack_ll *stack = *stackp;
185 if (stack->pid != pid || TgKill(stack->pid, stack->tid, 0) == -ESRCH) {
186 UnmapOrDie(stack->stack_base, unsafe_stack_size + unsafe_stack_guard);
187 *stackp = stack->next;
188 free(stack);
189 } else
190 stackp = &stack->next;
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000191 }
Vlad Tsyrklevicha24ecc32018-08-09 22:56:41 +0000192
193 thread_stack_ll *cur_stack =
194 (thread_stack_ll *)malloc(sizeof(thread_stack_ll));
195 cur_stack->stack_base = (char *)unsafe_stack_start - unsafe_stack_guard;
196 cur_stack->pid = pid;
197 cur_stack->tid = tid;
198
199 pthread_mutex_lock(&thread_stacks_mutex);
200 // Merge thread_stacks with the current thread's stack and any remaining
201 // temp_stacks
202 *stackp = thread_stacks;
203 cur_stack->next = temp_stacks;
204 thread_stacks = cur_stack;
205 pthread_mutex_unlock(&thread_stacks_mutex);
206
207 unsafe_stack_start = nullptr;
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000208}
209
Vitaly Buka4add8a12018-05-26 01:18:32 +0000210static void EnsureInterceptorsInitialized();
211
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000212/// Intercept thread creation operation to allocate and setup the unsafe stack
213INTERCEPTOR(int, pthread_create, pthread_t *thread,
214 const pthread_attr_t *attr,
215 void *(*start_routine)(void*), void *arg) {
Vitaly Buka4add8a12018-05-26 01:18:32 +0000216 EnsureInterceptorsInitialized();
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000217 size_t size = 0;
218 size_t guard = 0;
219
Vedant Kumar59ba7b82015-10-01 00:22:21 +0000220 if (attr) {
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000221 pthread_attr_getstacksize(attr, &size);
222 pthread_attr_getguardsize(attr, &guard);
223 } else {
224 // get pthread default stack size
225 pthread_attr_t tmpattr;
226 pthread_attr_init(&tmpattr);
227 pthread_attr_getstacksize(&tmpattr, &size);
228 pthread_attr_getguardsize(&tmpattr, &guard);
229 pthread_attr_destroy(&tmpattr);
230 }
231
232 CHECK_NE(size, 0);
233 CHECK_EQ((size & (kStackAlign - 1)), 0);
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +0000234 CHECK_EQ((guard & (pageSize - 1)), 0);
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000235
236 void *addr = unsafe_stack_alloc(size, guard);
237 struct tinfo *tinfo =
238 (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
239 tinfo->start_routine = start_routine;
240 tinfo->start_routine_arg = arg;
241 tinfo->unsafe_stack_start = addr;
242 tinfo->unsafe_stack_size = size;
243 tinfo->unsafe_stack_guard = guard;
244
245 return REAL(pthread_create)(thread, attr, thread_start, tinfo);
246}
247
Vitaly Buka4add8a12018-05-26 01:18:32 +0000248static BlockingMutex interceptor_init_lock(LINKER_INITIALIZED);
249static bool interceptors_inited = false;
250
251static void EnsureInterceptorsInitialized() {
252 BlockingMutexLock lock(&interceptor_init_lock);
253 if (interceptors_inited) return;
254
255 // Initialize pthread interceptors for thread allocation
256 INTERCEPT_FUNCTION(pthread_create);
257
258 interceptors_inited = true;
259}
260
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000261extern "C" __attribute__((visibility("default")))
262#if !SANITIZER_CAN_USE_PREINIT_ARRAY
263// On ELF platforms, the constructor is invoked using .preinit_array (see below)
264__attribute__((constructor(0)))
265#endif
266void __safestack_init() {
267 // Determine the stack size for the main thread.
268 size_t size = kDefaultUnsafeStackSize;
269 size_t guard = 4096;
270
271 struct rlimit limit;
272 if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
273 size = limit.rlim_cur;
274
275 // Allocate unsafe stack for main thread
276 void *addr = unsafe_stack_alloc(size, guard);
277
278 unsafe_stack_setup(addr, size, guard);
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +0000279 pageSize = sysconf(_SC_PAGESIZE);
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000280
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000281 // Setup the cleanup handler
282 pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
283}
284
285#if SANITIZER_CAN_USE_PREINIT_ARRAY
286// On ELF platforms, run safestack initialization before any other constructors.
287// On other platforms we use the constructor attribute to arrange to run our
288// initialization early.
289extern "C" {
290__attribute__((section(".preinit_array"),
291 used)) void (*__safestack_preinit)(void) = __safestack_init;
292}
293#endif
294
295extern "C"
Vlad Tsyrklevichbe9a9fd2018-07-13 19:48:35 +0000296 __attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000297 return unsafe_stack_start;
298}
299
300extern "C"
Vlad Tsyrklevichbe9a9fd2018-07-13 19:48:35 +0000301 __attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
302 return (char*)unsafe_stack_start + unsafe_stack_size;
303}
304
305extern "C"
Vlad Tsyrklevichddf998b2018-07-13 20:56:48 +0000306 __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
307 return unsafe_stack_start;
308}
Vlad Tsyrklevichbe9a9fd2018-07-13 19:48:35 +0000309
310extern "C"
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000311 __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
312 return __safestack_unsafe_stack_ptr;
313}