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