blob: 673f5fd30c5fb21baad35aee92f86adabfe1a9cb [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 Tsyrklevich05ee22e2018-08-14 20:28:58 +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 Tsyrklevich05ee22e2018-08-14 20:28:58 +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 Tsyrklevich05ee22e2018-08-14 20:28:58 +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;
Vlad Tsyrklevichf6c70102018-08-21 17:29:01 +0000155 size_t size;
Vlad Tsyrklevich05ee22e2018-08-14 20:28:58 +0000156 pid_t pid;
157 tid_t tid;
158};
159
160/// Linked list of unsafe stacks for threads that are exiting. We delay
161/// unmapping them until the thread exits.
162static thread_stack_ll *thread_stacks = nullptr;
163static pthread_mutex_t thread_stacks_mutex = PTHREAD_MUTEX_INITIALIZER;
164
165/// Thread-specific data destructor. We want to free the unsafe stack only after
166/// this thread is terminated. libc can call functions in safestack-instrumented
167/// code (like free) after thread-specific data destructors have run.
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000168static void thread_cleanup_handler(void *_iter) {
Vlad Tsyrklevich05ee22e2018-08-14 20:28:58 +0000169 CHECK_NE(unsafe_stack_start, nullptr);
170 pthread_setspecific(thread_cleanup_key, NULL);
171
172 pthread_mutex_lock(&thread_stacks_mutex);
173 // Temporary list to hold the previous threads stacks so we don't hold the
174 // thread_stacks_mutex for long.
175 thread_stack_ll *temp_stacks = thread_stacks;
176 thread_stacks = nullptr;
177 pthread_mutex_unlock(&thread_stacks_mutex);
178
179 pid_t pid = getpid();
180 tid_t tid = GetTid();
181
182 // Free stacks for dead threads
183 thread_stack_ll **stackp = &temp_stacks;
184 while (*stackp) {
185 thread_stack_ll *stack = *stackp;
186 if (stack->pid != pid || TgKill(stack->pid, stack->tid, 0) == -ESRCH) {
Vlad Tsyrklevichf6c70102018-08-21 17:29:01 +0000187 UnmapOrDie(stack->stack_base, stack->size);
Vlad Tsyrklevich05ee22e2018-08-14 20:28:58 +0000188 *stackp = stack->next;
189 free(stack);
190 } else
191 stackp = &stack->next;
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000192 }
Vlad Tsyrklevich05ee22e2018-08-14 20:28:58 +0000193
194 thread_stack_ll *cur_stack =
195 (thread_stack_ll *)malloc(sizeof(thread_stack_ll));
196 cur_stack->stack_base = (char *)unsafe_stack_start - unsafe_stack_guard;
Vlad Tsyrklevichf6c70102018-08-21 17:29:01 +0000197 cur_stack->size = unsafe_stack_size + unsafe_stack_guard;
Vlad Tsyrklevich05ee22e2018-08-14 20:28:58 +0000198 cur_stack->pid = pid;
199 cur_stack->tid = tid;
200
201 pthread_mutex_lock(&thread_stacks_mutex);
202 // Merge thread_stacks with the current thread's stack and any remaining
203 // temp_stacks
204 *stackp = thread_stacks;
205 cur_stack->next = temp_stacks;
206 thread_stacks = cur_stack;
207 pthread_mutex_unlock(&thread_stacks_mutex);
208
209 unsafe_stack_start = nullptr;
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000210}
211
Vitaly Buka4add8a12018-05-26 01:18:32 +0000212static void EnsureInterceptorsInitialized();
213
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000214/// Intercept thread creation operation to allocate and setup the unsafe stack
215INTERCEPTOR(int, pthread_create, pthread_t *thread,
216 const pthread_attr_t *attr,
217 void *(*start_routine)(void*), void *arg) {
Vitaly Buka4add8a12018-05-26 01:18:32 +0000218 EnsureInterceptorsInitialized();
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000219 size_t size = 0;
220 size_t guard = 0;
221
Vedant Kumar59ba7b82015-10-01 00:22:21 +0000222 if (attr) {
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000223 pthread_attr_getstacksize(attr, &size);
224 pthread_attr_getguardsize(attr, &guard);
225 } else {
226 // get pthread default stack size
227 pthread_attr_t tmpattr;
228 pthread_attr_init(&tmpattr);
229 pthread_attr_getstacksize(&tmpattr, &size);
230 pthread_attr_getguardsize(&tmpattr, &guard);
231 pthread_attr_destroy(&tmpattr);
232 }
233
234 CHECK_NE(size, 0);
235 CHECK_EQ((size & (kStackAlign - 1)), 0);
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +0000236 CHECK_EQ((guard & (pageSize - 1)), 0);
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000237
238 void *addr = unsafe_stack_alloc(size, guard);
239 struct tinfo *tinfo =
240 (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
241 tinfo->start_routine = start_routine;
242 tinfo->start_routine_arg = arg;
243 tinfo->unsafe_stack_start = addr;
244 tinfo->unsafe_stack_size = size;
245 tinfo->unsafe_stack_guard = guard;
246
247 return REAL(pthread_create)(thread, attr, thread_start, tinfo);
248}
249
Vitaly Buka4add8a12018-05-26 01:18:32 +0000250static BlockingMutex interceptor_init_lock(LINKER_INITIALIZED);
251static bool interceptors_inited = false;
252
253static void EnsureInterceptorsInitialized() {
254 BlockingMutexLock lock(&interceptor_init_lock);
255 if (interceptors_inited) return;
256
257 // Initialize pthread interceptors for thread allocation
258 INTERCEPT_FUNCTION(pthread_create);
259
260 interceptors_inited = true;
261}
262
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000263extern "C" __attribute__((visibility("default")))
264#if !SANITIZER_CAN_USE_PREINIT_ARRAY
265// On ELF platforms, the constructor is invoked using .preinit_array (see below)
266__attribute__((constructor(0)))
267#endif
268void __safestack_init() {
269 // Determine the stack size for the main thread.
270 size_t size = kDefaultUnsafeStackSize;
271 size_t guard = 4096;
272
273 struct rlimit limit;
274 if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
275 size = limit.rlim_cur;
276
277 // Allocate unsafe stack for main thread
278 void *addr = unsafe_stack_alloc(size, guard);
279
280 unsafe_stack_setup(addr, size, guard);
Adhemerval Zanellaeaf11622015-12-11 17:38:38 +0000281 pageSize = sysconf(_SC_PAGESIZE);
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000282
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000283 // Setup the cleanup handler
284 pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
285}
286
287#if SANITIZER_CAN_USE_PREINIT_ARRAY
288// On ELF platforms, run safestack initialization before any other constructors.
289// On other platforms we use the constructor attribute to arrange to run our
290// initialization early.
291extern "C" {
292__attribute__((section(".preinit_array"),
293 used)) void (*__safestack_preinit)(void) = __safestack_init;
294}
295#endif
296
297extern "C"
Vlad Tsyrklevichbe9a9fd2018-07-13 19:48:35 +0000298 __attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000299 return unsafe_stack_start;
300}
301
302extern "C"
Vlad Tsyrklevichbe9a9fd2018-07-13 19:48:35 +0000303 __attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
304 return (char*)unsafe_stack_start + unsafe_stack_size;
305}
306
307extern "C"
Vlad Tsyrklevichddf998b2018-07-13 20:56:48 +0000308 __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
309 return unsafe_stack_start;
310}
Vlad Tsyrklevichbe9a9fd2018-07-13 19:48:35 +0000311
312extern "C"
Peter Collingbourneb64d0b12015-06-15 21:08:47 +0000313 __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
314 return __safestack_unsafe_stack_ptr;
315}