1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include "libc_init_common.h"
30
31 #include <async_safe/log.h>
32 #include <elf.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <inttypes.h>
36 #include <stddef.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/auxv.h>
42 #include <sys/personality.h>
43 #include <sys/time.h>
44 #include <unistd.h>
45
46 #include "heap_tagging.h"
47 #include "private/ScopedPthreadMutexLocker.h"
48 #include "private/WriteProtected.h"
49 #include "private/bionic_defs.h"
50 #include "private/bionic_globals.h"
51 #include "private/bionic_tls.h"
52 #include "private/thread_private.h"
53 #include "pthread_internal.h"
54
55 extern "C" int __system_properties_init(void);
56 extern "C" void scudo_malloc_set_zero_contents(int);
57 extern "C" void scudo_malloc_set_pattern_fill_contents(int);
58
59 __LIBC_HIDDEN__ constinit WriteProtected<libc_globals> __libc_globals;
60 __LIBC_HIDDEN__ constinit _Atomic(bool) __libc_memtag_stack;
61
62 // Not public, but well-known in the BSDs.
63 __BIONIC_WEAK_VARIABLE_FOR_NATIVE_BRIDGE
64 const char* __progname;
65
__libc_init_globals()66 void __libc_init_globals() {
67 // Initialize libc globals that are needed in both the linker and in libc.
68 // In dynamic binaries, this is run at least twice for different copies of the
69 // globals, once for the linker's copy and once for the one in libc.so.
70 __libc_globals.initialize();
71 __libc_globals.mutate([](libc_globals* globals) {
72 __libc_init_vdso(globals);
73 __libc_init_setjmp_cookie(globals);
74 });
75 }
76
77 #if !defined(__LP64__)
__check_max_thread_id()78 static void __check_max_thread_id() {
79 if (gettid() > 65535) {
80 async_safe_fatal("Limited by the size of pthread_mutex_t, 32 bit bionic libc only accepts "
81 "pid <= 65535, but current pid is %d", gettid());
82 }
83 }
84 #endif
85
arc4random_fork_handler()86 static void arc4random_fork_handler() {
87 _rs_forked = 1;
88 _thread_arc4_lock();
89 }
90
91 __BIONIC_WEAK_FOR_NATIVE_BRIDGE
__libc_init_scudo()92 void __libc_init_scudo() {
93 // Heap tagging level *must* be set before interacting with Scudo, otherwise
94 // the primary will be mapped with PROT_MTE even if MTE is is not enabled in
95 // this process.
96 SetDefaultHeapTaggingLevel();
97
98 // TODO(b/158870657) make this unconditional when all devices support SCUDO.
99 #if defined(USE_SCUDO) && !__has_feature(hwaddress_sanitizer)
100 #if defined(SCUDO_PATTERN_FILL_CONTENTS)
101 scudo_malloc_set_pattern_fill_contents(1);
102 #elif defined(SCUDO_ZERO_CONTENTS)
103 scudo_malloc_set_zero_contents(1);
104 #endif
105 #endif
106 }
107
108 __BIONIC_WEAK_FOR_NATIVE_BRIDGE
109 __attribute__((no_sanitize("hwaddress", "memtag"))) void
__libc_init_mte_late()110 __libc_init_mte_late() {
111 #if defined(__aarch64__)
112 if (!__libc_shared_globals()->heap_tagging_upgrade_timer_sec) {
113 return;
114 }
115 struct sigevent event = {};
116 static timer_t timer;
117 event.sigev_notify = SIGEV_THREAD;
118 event.sigev_notify_function = [](union sigval) {
119 async_safe_format_log(ANDROID_LOG_INFO, "libc",
120 "Downgrading MTE to async.");
121 ScopedPthreadMutexLocker l(&g_heap_tagging_lock);
122 SetHeapTaggingLevel(M_HEAP_TAGGING_LEVEL_ASYNC);
123 timer_delete(timer);
124 };
125
126 if (timer_create(CLOCK_REALTIME, &event, &timer) == -1) {
127 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
128 "Failed to create MTE downgrade timer: %m");
129 // Revert back to ASYNC. If we fail to create or arm the timer, otherwise
130 // the process would be indefinitely stuck in SYNC.
131 SetHeapTaggingLevel(M_HEAP_TAGGING_LEVEL_ASYNC);
132 return;
133 }
134
135 struct itimerspec timerspec = {};
136 timerspec.it_value.tv_sec =
137 __libc_shared_globals()->heap_tagging_upgrade_timer_sec;
138 if (timer_settime(timer, /* flags= */ 0, &timerspec, nullptr) == -1) {
139 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
140 "Failed to arm MTE downgrade timer: %m");
141 // Revert back to ASYNC. If we fail to create or arm the timer, otherwise
142 // the process would be indefinitely stuck in SYNC.
143 SetHeapTaggingLevel(M_HEAP_TAGGING_LEVEL_ASYNC);
144 timer_delete(timer);
145 return;
146 }
147 async_safe_format_log(
148 ANDROID_LOG_INFO, "libc", "Armed MTE downgrade timer for %" PRId64 " s",
149 __libc_shared_globals()->heap_tagging_upgrade_timer_sec);
150 #endif
151 }
152
153 __BIONIC_WEAK_FOR_NATIVE_BRIDGE
__libc_add_main_thread()154 void __libc_add_main_thread() {
155 // Get the main thread from TLS and add it to the thread list.
156 pthread_internal_t* main_thread = __get_thread();
157 __pthread_internal_add(main_thread);
158 }
159
__libc_init_common()160 void __libc_init_common() {
161 // Initialize various globals.
162 environ = __libc_shared_globals()->init_environ;
163 errno = 0;
164 setprogname(__libc_shared_globals()->init_progname ?: "<unknown>");
165
166 #if !defined(__LP64__)
167 __check_max_thread_id();
168 #endif
169
170 __libc_add_main_thread();
171
172 __system_properties_init(); // Requires 'environ'.
173 __libc_init_fdsan(); // Requires system properties (for debug.fdsan).
174 __libc_init_fdtrack();
175 }
176
__libc_init_fork_handler()177 void __libc_init_fork_handler() {
178 // Register atfork handlers to take and release the arc4random lock.
179 pthread_atfork(arc4random_fork_handler, _thread_arc4_unlock, _thread_arc4_unlock);
180 }
181
182 extern "C" void scudo_malloc_set_add_large_allocation_slack(int add_slack);
183
__libc_set_target_sdk_version(int target __unused)184 __BIONIC_WEAK_FOR_NATIVE_BRIDGE void __libc_set_target_sdk_version(int target __unused) {
185 #if defined(USE_SCUDO) && !__has_feature(hwaddress_sanitizer)
186 scudo_malloc_set_add_large_allocation_slack(target < __ANDROID_API_S__);
187 #endif
188 }
189
__early_abort(size_t line)190 __noreturn static void __early_abort(size_t line) {
191 // We can't write to stdout or stderr because we're aborting before we've checked that
192 // it's safe for us to use those file descriptors. We probably can't strace either, so
193 // we rely on the fact that if we dereference a low address, either debuggerd or the
194 // kernel's crash dump will show the fault address.
195 *reinterpret_cast<int*>(line) = 0;
196 _exit(EXIT_FAILURE);
197 }
198
199 // Force any of the stdin/stdout/stderr file descriptors that aren't
200 // open to be associated with /dev/null.
__nullify_closed_stdio()201 static void __nullify_closed_stdio() {
202 for (int i = 0; i < 3; i++) {
203 if (TEMP_FAILURE_RETRY(fcntl(i, F_GETFL)) == -1) {
204 // The only error we allow is that the file descriptor does not exist.
205 if (errno != EBADF) __early_abort(__LINE__);
206
207 // This file descriptor wasn't open, so open /dev/null.
208 // init won't have /dev/null available, but SELinux provides an equivalent.
209 // This takes advantage of the fact that open() will take the lowest free
210 // file descriptor, and we're iterating in order from 0, but we'll
211 // double-check we got the right fd anyway...
212 int fd;
213 if (((fd = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR))) == -1 &&
214 (fd = TEMP_FAILURE_RETRY(open("/sys/fs/selinux/null", O_RDWR))) == -1) ||
215 fd != i) {
216 __early_abort(__LINE__);
217 }
218 }
219 }
220 }
221
222 // Check if the environment variable definition at 'envstr'
223 // starts with '<name>=', and if so return the address of the
224 // first character after the equal sign. Otherwise return null.
env_match(const char * envstr,const char * name)225 static const char* env_match(const char* envstr, const char* name) {
226 size_t i = 0;
227
228 while (envstr[i] == name[i] && name[i] != '\0') {
229 ++i;
230 }
231
232 if (name[i] == '\0' && envstr[i] == '=') {
233 return envstr + i + 1;
234 }
235
236 return nullptr;
237 }
238
__is_valid_environment_variable(const char * name)239 static bool __is_valid_environment_variable(const char* name) {
240 // According to the kernel source, by default the kernel uses 32*PAGE_SIZE
241 // as the maximum size for an environment variable definition.
242 const int MAX_ENV_LEN = 32*4096;
243
244 if (name == nullptr) {
245 return false;
246 }
247
248 // Parse the string, looking for the first '=' there, and its size.
249 int pos = 0;
250 int first_equal_pos = -1;
251 while (pos < MAX_ENV_LEN) {
252 if (name[pos] == '\0') {
253 break;
254 }
255 if (name[pos] == '=' && first_equal_pos < 0) {
256 first_equal_pos = pos;
257 }
258 pos++;
259 }
260
261 // Check that it's smaller than MAX_ENV_LEN (to detect non-zero terminated strings).
262 if (pos >= MAX_ENV_LEN) {
263 return false;
264 }
265
266 // Check that it contains at least one equal sign that is not the first character
267 if (first_equal_pos < 1) {
268 return false;
269 }
270
271 return true;
272 }
273
__is_unsafe_environment_variable(const char * name)274 static bool __is_unsafe_environment_variable(const char* name) {
275 // None of these should be allowed when the AT_SECURE auxv
276 // flag is set. This flag is set to inform userspace that a
277 // security transition has occurred, for example, as a result
278 // of executing a setuid program or the result of an SELinux
279 // security transition.
280 static constexpr const char* UNSAFE_VARIABLE_NAMES[] = {
281 "ANDROID_DNS_MODE",
282 "GCONV_PATH",
283 "GETCONF_DIR",
284 "HOSTALIASES",
285 "JE_MALLOC_CONF",
286 "LD_AOUT_LIBRARY_PATH",
287 "LD_AOUT_PRELOAD",
288 "LD_AUDIT",
289 "LD_CONFIG_FILE",
290 "LD_DEBUG",
291 "LD_DEBUG_OUTPUT",
292 "LD_DYNAMIC_WEAK",
293 "LD_HWASAN",
294 "LD_LIBRARY_PATH",
295 "LD_ORIGIN_PATH",
296 "LD_PRELOAD",
297 "LD_PROFILE",
298 "LD_SHOW_AUXV",
299 "LD_USE_LOAD_BIAS",
300 "LIBC_DEBUG_MALLOC_OPTIONS",
301 "LIBC_HOOKS_ENABLE",
302 "LOCALDOMAIN",
303 "LOCPATH",
304 "MALLOC_CHECK_",
305 "MALLOC_CONF",
306 "MALLOC_TRACE",
307 "NIS_PATH",
308 "NLSPATH",
309 "RESOLV_HOST_CONF",
310 "RES_OPTIONS",
311 "SCUDO_OPTIONS",
312 "TMPDIR",
313 "TZDIR",
314 };
315 for (const auto& unsafe_variable_name : UNSAFE_VARIABLE_NAMES) {
316 if (env_match(name, unsafe_variable_name) != nullptr) {
317 return true;
318 }
319 }
320 return false;
321 }
322
__sanitize_environment_variables(char ** env)323 static void __sanitize_environment_variables(char** env) {
324 char** src = env;
325 char** dst = env;
326 for (; src[0] != nullptr; ++src) {
327 if (!__is_valid_environment_variable(src[0])) {
328 continue;
329 }
330 // Remove various unsafe environment variables if we're loading a setuid program.
331 if (__is_unsafe_environment_variable(src[0])) {
332 continue;
333 }
334 dst[0] = src[0];
335 ++dst;
336 }
337 dst[0] = nullptr;
338 }
339
__initialize_personality()340 static void __initialize_personality() {
341 #if !defined(__LP64__)
342 int old_value = personality(0xffffffff);
343 if (old_value == -1) {
344 async_safe_fatal("error getting old personality value: %m");
345 }
346
347 if (personality((static_cast<unsigned int>(old_value) & ~PER_MASK) | PER_LINUX32) == -1) {
348 async_safe_fatal("error setting PER_LINUX32 personality: %m");
349 }
350 #endif
351 }
352
__libc_init_AT_SECURE(char ** env)353 void __libc_init_AT_SECURE(char** env) {
354 // Check that the kernel provided a value for AT_SECURE.
355 errno = 0;
356 unsigned long is_AT_SECURE = getauxval(AT_SECURE);
357 if (errno != 0) __early_abort(__LINE__);
358
359 // Always ensure that STDIN/STDOUT/STDERR exist. This prevents file
360 // descriptor confusion bugs where a parent process closes
361 // STD*, the exec()d process calls open() for an unrelated reason,
362 // the newly created file descriptor is assigned
363 // 0<=FD<=2, and unrelated code attempts to read / write to the STD*
364 // FDs.
365 // In particular, this can be a security bug for setuid/setgid programs.
366 // For example:
367 // https://www.freebsd.org/security/advisories/FreeBSD-SA-02:23.stdio.asc
368 // However, for robustness reasons, we don't limit these protections to
369 // just security critical executables.
370 //
371 // Init is excluded from these protections unless AT_SECURE is set, as
372 // /dev/null and/or /sys/fs/selinux/null will not be available at
373 // early boot.
374 if ((getpid() != 1) || is_AT_SECURE) {
375 __nullify_closed_stdio();
376 }
377
378 if (is_AT_SECURE) {
379 __sanitize_environment_variables(env);
380 }
381
382 // Now the environment has been sanitized, make it available.
383 environ = __libc_shared_globals()->init_environ = env;
384
385 __initialize_personality();
386 }
387
388 /* This function will be called during normal program termination
389 * to run the destructors that are listed in the .fini_array section
390 * of the executable, if any.
391 *
392 * 'fini_array' points to a list of function addresses. The first
393 * entry in the list has value -1, the last one has value 0.
394 */
__libc_fini(void * array)395 void __libc_fini(void* array) {
396 typedef void (*Dtor)();
397 Dtor* fini_array = reinterpret_cast<Dtor*>(array);
398 const Dtor minus1 = reinterpret_cast<Dtor>(static_cast<uintptr_t>(-1));
399
400 // Validity check: the first entry must be -1.
401 if (array == nullptr || fini_array[0] != minus1) return;
402
403 // Skip over it.
404 fini_array += 1;
405
406 // Count the number of destructors.
407 int count = 0;
408 while (fini_array[count] != nullptr) {
409 ++count;
410 }
411
412 // Now call each destructor in reverse order, ignoring any -1s.
413 while (count > 0) {
414 Dtor dtor = fini_array[--count];
415 if (dtor != minus1) dtor();
416 }
417 }
418