Fix: perform lazy initialization of getenv common lib
[lttng-ust.git] / src / common / getenv.c
1 /*
2 * SPDX-License-Identifier: LGPL-2.1-only
3 *
4 * Copyright (C) 2017 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 */
6
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <sys/types.h>
12 #include <urcu/system.h>
13 #include "common/logging.h"
14 #include "common/macros.h"
15 #include "common/getenv.h"
16
17 enum lttng_env_secure {
18 LTTNG_ENV_SECURE,
19 LTTNG_ENV_NOT_SECURE,
20 };
21
22 struct lttng_env {
23 const char *key;
24 enum lttng_env_secure secure;
25 char *value;
26 };
27
28 static
29 int lttng_ust_getenv_is_init = 0;
30
31 static struct lttng_env lttng_env[] = {
32 /*
33 * LTTNG_UST_DEBUG is used directly by snprintf, because it
34 * needs to be already set for ERR() used in
35 * lttng_ust_getenv_init().
36 */
37 { "LTTNG_UST_DEBUG", LTTNG_ENV_NOT_SECURE, NULL, },
38
39 /* Env. var. which can be used in setuid/setgid executables. */
40 { "LTTNG_UST_WITHOUT_BADDR_STATEDUMP", LTTNG_ENV_NOT_SECURE, NULL, },
41 { "LTTNG_UST_REGISTER_TIMEOUT", LTTNG_ENV_NOT_SECURE, NULL, },
42
43 /* Env. var. which are not fetched in setuid/setgid executables. */
44 { "LTTNG_UST_CLOCK_PLUGIN", LTTNG_ENV_SECURE, NULL, },
45 { "LTTNG_UST_GETCPU_PLUGIN", LTTNG_ENV_SECURE, NULL, },
46 { "LTTNG_UST_ALLOW_BLOCKING", LTTNG_ENV_SECURE, NULL, },
47 { "HOME", LTTNG_ENV_SECURE, NULL, },
48 { "LTTNG_HOME", LTTNG_ENV_SECURE, NULL, },
49 };
50
51 static
52 int lttng_is_setuid_setgid(void)
53 {
54 return geteuid() != getuid() || getegid() != getgid();
55 }
56
57 /*
58 * Wrapper over getenv that will only return the values of whitelisted
59 * environment variables when the current process is setuid and/or setgid.
60 */
61 char *lttng_ust_getenv(const char *name)
62 {
63 size_t i;
64 struct lttng_env *e;
65 bool found = false;
66
67 /*
68 * Perform lazy initialization of lttng_ust_getenv for early use
69 * by library constructors.
70 */
71 lttng_ust_getenv_init();
72
73 for (i = 0; i < LTTNG_ARRAY_SIZE(lttng_env); i++) {
74 e = &lttng_env[i];
75
76 if (strcmp(e->key, name) == 0) {
77 found = true;
78 break;
79 }
80 }
81 if (!found) {
82 return NULL;
83 }
84 return e->value;
85 }
86
87 void lttng_ust_getenv_init(void)
88 {
89 size_t i;
90
91 if (CMM_LOAD_SHARED(lttng_ust_getenv_is_init))
92 return;
93
94 for (i = 0; i < LTTNG_ARRAY_SIZE(lttng_env); i++) {
95 struct lttng_env *e = &lttng_env[i];
96
97 if (e->secure == LTTNG_ENV_SECURE && lttng_is_setuid_setgid()) {
98 ERR("Getting environment variable '%s' from setuid/setgid binary refused for security reasons.",
99 e->key);
100 continue;
101 }
102 e->value = getenv(e->key);
103 }
104 CMM_STORE_SHARED(lttng_ust_getenv_is_init, 1);
105 }
This page took 0.03197 seconds and 5 git commands to generate.