• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "heap_tagging.h"
31 
32 #include <elf.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <stddef.h>
36 #include <stdint.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <sys/auxv.h>
41 #include <sys/personality.h>
42 #include <sys/time.h>
43 #include <unistd.h>
44 
45 #include <async_safe/log.h>
46 
47 #include "private/WriteProtected.h"
48 #include "private/bionic_defs.h"
49 #include "private/bionic_globals.h"
50 #include "private/bionic_tls.h"
51 #include "private/thread_private.h"
52 #include "pthread_internal.h"
53 
54 extern "C" int __system_properties_init(void);
55 
56 __LIBC_HIDDEN__ WriteProtected<libc_globals> __libc_globals;
57 
58 // Not public, but well-known in the BSDs.
59 const char* __progname;
60 
__libc_init_globals()61 void __libc_init_globals() {
62   // Initialize libc globals that are needed in both the linker and in libc.
63   // In dynamic binaries, this is run at least twice for different copies of the
64   // globals, once for the linker's copy and once for the one in libc.so.
65   __libc_globals.initialize();
66   __libc_globals.mutate([](libc_globals* globals) {
67     __libc_init_vdso(globals);
68     __libc_init_setjmp_cookie(globals);
69   });
70 }
71 
72 #if !defined(__LP64__)
__check_max_thread_id()73 static void __check_max_thread_id() {
74   if (gettid() > 65535) {
75     async_safe_fatal("Limited by the size of pthread_mutex_t, 32 bit bionic libc only accepts "
76                      "pid <= 65535, but current pid is %d", gettid());
77   }
78 }
79 #endif
80 
arc4random_fork_handler()81 static void arc4random_fork_handler() {
82   _rs_forked = 1;
83   _thread_arc4_lock();
84 }
85 
86 __BIONIC_WEAK_FOR_NATIVE_BRIDGE
__libc_add_main_thread()87 void __libc_add_main_thread() {
88   // Get the main thread from TLS and add it to the thread list.
89   pthread_internal_t* main_thread = __get_thread();
90   __pthread_internal_add(main_thread);
91 }
92 
__libc_init_common()93 void __libc_init_common() {
94   // Initialize various globals.
95   environ = __libc_shared_globals()->init_environ;
96   errno = 0;
97   setprogname(__libc_shared_globals()->init_progname ?: "<unknown>");
98 
99 #if !defined(__LP64__)
100   __check_max_thread_id();
101 #endif
102 
103   __libc_add_main_thread();
104 
105   __system_properties_init(); // Requires 'environ'.
106   __libc_init_fdsan(); // Requires system properties (for debug.fdsan).
107   __libc_init_fdtrack();
108 
109   SetDefaultHeapTaggingLevel();
110 }
111 
__libc_init_fork_handler()112 void __libc_init_fork_handler() {
113   // Register atfork handlers to take and release the arc4random lock.
114   pthread_atfork(arc4random_fork_handler, _thread_arc4_unlock, _thread_arc4_unlock);
115 }
116 
__early_abort(int line)117 __noreturn static void __early_abort(int line) {
118   // We can't write to stdout or stderr because we're aborting before we've checked that
119   // it's safe for us to use those file descriptors. We probably can't strace either, so
120   // we rely on the fact that if we dereference a low address, either debuggerd or the
121   // kernel's crash dump will show the fault address.
122   *reinterpret_cast<int*>(line) = 0;
123   _exit(EXIT_FAILURE);
124 }
125 
126 // Force any of the closed stdin, stdout and stderr to be associated with /dev/null.
__nullify_closed_stdio()127 static void __nullify_closed_stdio() {
128   int dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
129   if (dev_null == -1) {
130     // init won't have /dev/null available, but SELinux provides an equivalent.
131     dev_null = TEMP_FAILURE_RETRY(open("/sys/fs/selinux/null", O_RDWR));
132   }
133   if (dev_null == -1) {
134     __early_abort(__LINE__);
135   }
136 
137   // If any of the stdio file descriptors is valid and not associated
138   // with /dev/null, dup /dev/null to it.
139   for (int i = 0; i < 3; i++) {
140     // If it is /dev/null already, we are done.
141     if (i == dev_null) {
142       continue;
143     }
144 
145     // Is this fd already open?
146     int status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL));
147     if (status != -1) {
148       continue;
149     }
150 
151     // The only error we allow is that the file descriptor does not
152     // exist, in which case we dup /dev/null to it.
153     if (errno == EBADF) {
154       // Try dupping /dev/null to this stdio file descriptor and
155       // repeat if there is a signal. Note that any errors in closing
156       // the stdio descriptor are lost.
157       status = TEMP_FAILURE_RETRY(dup2(dev_null, i));
158       if (status == -1) {
159         __early_abort(__LINE__);
160       }
161     } else {
162       __early_abort(__LINE__);
163     }
164   }
165 
166   // If /dev/null is not one of the stdio file descriptors, close it.
167   if (dev_null > 2) {
168     if (close(dev_null) == -1) {
169       __early_abort(__LINE__);
170     }
171   }
172 }
173 
174 // Check if the environment variable definition at 'envstr'
175 // starts with '<name>=', and if so return the address of the
176 // first character after the equal sign. Otherwise return null.
env_match(const char * envstr,const char * name)177 static const char* env_match(const char* envstr, const char* name) {
178   size_t i = 0;
179 
180   while (envstr[i] == name[i] && name[i] != '\0') {
181     ++i;
182   }
183 
184   if (name[i] == '\0' && envstr[i] == '=') {
185     return envstr + i + 1;
186   }
187 
188   return nullptr;
189 }
190 
__is_valid_environment_variable(const char * name)191 static bool __is_valid_environment_variable(const char* name) {
192   // According to the kernel source, by default the kernel uses 32*PAGE_SIZE
193   // as the maximum size for an environment variable definition.
194   const int MAX_ENV_LEN = 32*4096;
195 
196   if (name == nullptr) {
197     return false;
198   }
199 
200   // Parse the string, looking for the first '=' there, and its size.
201   int pos = 0;
202   int first_equal_pos = -1;
203   while (pos < MAX_ENV_LEN) {
204     if (name[pos] == '\0') {
205       break;
206     }
207     if (name[pos] == '=' && first_equal_pos < 0) {
208       first_equal_pos = pos;
209     }
210     pos++;
211   }
212 
213   // Check that it's smaller than MAX_ENV_LEN (to detect non-zero terminated strings).
214   if (pos >= MAX_ENV_LEN) {
215     return false;
216   }
217 
218   // Check that it contains at least one equal sign that is not the first character
219   if (first_equal_pos < 1) {
220     return false;
221   }
222 
223   return true;
224 }
225 
__is_unsafe_environment_variable(const char * name)226 static bool __is_unsafe_environment_variable(const char* name) {
227   // None of these should be allowed when the AT_SECURE auxv
228   // flag is set. This flag is set to inform userspace that a
229   // security transition has occurred, for example, as a result
230   // of executing a setuid program or the result of an SELinux
231   // security transition.
232   static constexpr const char* UNSAFE_VARIABLE_NAMES[] = {
233       "ANDROID_DNS_MODE",
234       "GCONV_PATH",
235       "GETCONF_DIR",
236       "HOSTALIASES",
237       "JE_MALLOC_CONF",
238       "LD_AOUT_LIBRARY_PATH",
239       "LD_AOUT_PRELOAD",
240       "LD_AUDIT",
241       "LD_CONFIG_FILE",
242       "LD_DEBUG",
243       "LD_DEBUG_OUTPUT",
244       "LD_DYNAMIC_WEAK",
245       "LD_LIBRARY_PATH",
246       "LD_ORIGIN_PATH",
247       "LD_PRELOAD",
248       "LD_PROFILE",
249       "LD_SHOW_AUXV",
250       "LD_USE_LOAD_BIAS",
251       "LIBC_DEBUG_MALLOC_OPTIONS",
252       "LIBC_HOOKS_ENABLE",
253       "LOCALDOMAIN",
254       "LOCPATH",
255       "MALLOC_CHECK_",
256       "MALLOC_CONF",
257       "MALLOC_TRACE",
258       "NIS_PATH",
259       "NLSPATH",
260       "RESOLV_HOST_CONF",
261       "RES_OPTIONS",
262       "SCUDO_OPTIONS",
263       "TMPDIR",
264       "TZDIR",
265   };
266   for (const auto& unsafe_variable_name : UNSAFE_VARIABLE_NAMES) {
267     if (env_match(name, unsafe_variable_name) != nullptr) {
268       return true;
269     }
270   }
271   return false;
272 }
273 
__sanitize_environment_variables(char ** env)274 static void __sanitize_environment_variables(char** env) {
275   char** src = env;
276   char** dst = env;
277   for (; src[0] != nullptr; ++src) {
278     if (!__is_valid_environment_variable(src[0])) {
279       continue;
280     }
281     // Remove various unsafe environment variables if we're loading a setuid program.
282     if (__is_unsafe_environment_variable(src[0])) {
283       continue;
284     }
285     dst[0] = src[0];
286     ++dst;
287   }
288   dst[0] = nullptr;
289 }
290 
__initialize_personality()291 static void __initialize_personality() {
292 #if !defined(__LP64__)
293   int old_value = personality(0xffffffff);
294   if (old_value == -1) {
295     async_safe_fatal("error getting old personality value: %s", strerror(errno));
296   }
297 
298   if (personality((static_cast<unsigned int>(old_value) & ~PER_MASK) | PER_LINUX32) == -1) {
299     async_safe_fatal("error setting PER_LINUX32 personality: %s", strerror(errno));
300   }
301 #endif
302 }
303 
__libc_init_AT_SECURE(char ** env)304 void __libc_init_AT_SECURE(char** env) {
305   // Check that the kernel provided a value for AT_SECURE.
306   errno = 0;
307   unsigned long is_AT_SECURE = getauxval(AT_SECURE);
308   if (errno != 0) __early_abort(__LINE__);
309 
310   // Always ensure that STDIN/STDOUT/STDERR exist. This prevents file
311   // descriptor confusion bugs where a parent process closes
312   // STD*, the exec()d process calls open() for an unrelated reason,
313   // the newly created file descriptor is assigned
314   // 0<=FD<=2, and unrelated code attempts to read / write to the STD*
315   // FDs.
316   // In particular, this can be a security bug for setuid/setgid programs.
317   // For example:
318   // https://www.freebsd.org/security/advisories/FreeBSD-SA-02:23.stdio.asc
319   // However, for robustness reasons, we don't limit these protections to
320   // just security critical executables.
321   //
322   // Init is excluded from these protections unless AT_SECURE is set, as
323   // /dev/null and/or /sys/fs/selinux/null will not be available at
324   // early boot.
325   if ((getpid() != 1) || is_AT_SECURE) {
326     __nullify_closed_stdio();
327   }
328 
329   if (is_AT_SECURE) {
330     __sanitize_environment_variables(env);
331   }
332 
333   // Now the environment has been sanitized, make it available.
334   environ = __libc_shared_globals()->init_environ = env;
335 
336   __initialize_personality();
337 }
338 
339 /* This function will be called during normal program termination
340  * to run the destructors that are listed in the .fini_array section
341  * of the executable, if any.
342  *
343  * 'fini_array' points to a list of function addresses. The first
344  * entry in the list has value -1, the last one has value 0.
345  */
__libc_fini(void * array)346 void __libc_fini(void* array) {
347   typedef void (*Dtor)();
348   Dtor* fini_array = reinterpret_cast<Dtor*>(array);
349   const Dtor minus1 = reinterpret_cast<Dtor>(static_cast<uintptr_t>(-1));
350 
351   // Sanity check - first entry must be -1.
352   if (array == nullptr || fini_array[0] != minus1) {
353     return;
354   }
355 
356   // Skip over it.
357   fini_array += 1;
358 
359   // Count the number of destructors.
360   int count = 0;
361   while (fini_array[count] != nullptr) {
362     ++count;
363   }
364 
365   // Now call each destructor in reverse order.
366   while (count > 0) {
367     Dtor dtor = fini_array[--count];
368 
369     // Sanity check, any -1 in the list is ignored.
370     if (dtor == minus1) {
371       continue;
372     }
373 
374     dtor();
375   }
376 }
377