2 * SPDX-License-Identifier: LGPL-2.1-only
4 * Copyright (C) 2017 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
11 #include <sys/types.h>
13 #include <urcu/system.h>
14 #include "common/logging.h"
15 #include "common/macros.h"
16 #include "common/getenv.h"
18 enum lttng_env_secure
{
25 enum lttng_env_secure secure
;
29 /* lttng_ust_getenv_init_mutex provides mutual exclusion for initialization. */
30 static pthread_mutex_t lttng_ust_getenv_init_mutex
= PTHREAD_MUTEX_INITIALIZER
;
31 static int lttng_ust_getenv_is_init
= 0;
33 static struct lttng_env lttng_env
[] = {
35 * LTTNG_UST_DEBUG is used directly by snprintf, because it
36 * needs to be already set for ERR() used in
37 * lttng_ust_getenv_init().
39 { "LTTNG_UST_DEBUG", LTTNG_ENV_NOT_SECURE
, NULL
, },
41 /* Env. var. which can be used in setuid/setgid executables. */
42 { "LTTNG_UST_WITHOUT_BADDR_STATEDUMP", LTTNG_ENV_NOT_SECURE
, NULL
, },
43 { "LTTNG_UST_REGISTER_TIMEOUT", LTTNG_ENV_NOT_SECURE
, NULL
, },
45 /* Env. var. which are not fetched in setuid/setgid executables. */
46 { "LTTNG_UST_CLOCK_PLUGIN", LTTNG_ENV_SECURE
, NULL
, },
47 { "LTTNG_UST_GETCPU_PLUGIN", LTTNG_ENV_SECURE
, NULL
, },
48 { "LTTNG_UST_ALLOW_BLOCKING", LTTNG_ENV_SECURE
, NULL
, },
49 { "HOME", LTTNG_ENV_SECURE
, NULL
, },
50 { "LTTNG_HOME", LTTNG_ENV_SECURE
, NULL
, },
54 int lttng_is_setuid_setgid(void)
56 return geteuid() != getuid() || getegid() != getgid();
60 * Wrapper over getenv that will only return the values of whitelisted
61 * environment variables when the current process is setuid and/or setgid.
63 char *lttng_ust_getenv(const char *name
)
70 * Perform lazy initialization of lttng_ust_getenv for early use
71 * by library constructors.
73 lttng_ust_getenv_init();
75 for (i
= 0; i
< LTTNG_ARRAY_SIZE(lttng_env
); i
++) {
78 if (strcmp(e
->key
, name
) == 0) {
89 void lttng_ust_getenv_init(void)
94 * Return early if the init has already completed.
96 if (CMM_LOAD_SHARED(lttng_ust_getenv_is_init
)) {
98 * Load lttng_ust_getenv_is_init before reading environment cache.
104 pthread_mutex_lock(<tng_ust_getenv_init_mutex
);
107 * Check again if the init has completed in another thread now that we
108 * have acquired the mutex.
110 if (lttng_ust_getenv_is_init
)
113 for (i
= 0; i
< LTTNG_ARRAY_SIZE(lttng_env
); i
++) {
114 struct lttng_env
*e
= <tng_env
[i
];
116 if (e
->secure
== LTTNG_ENV_SECURE
&& lttng_is_setuid_setgid()) {
117 ERR("Getting environment variable '%s' from setuid/setgid binary refused for security reasons.",
121 e
->value
= getenv(e
->key
);
125 * Store environment cache before setting lttng_ust_getenv_is_init to 1.
128 CMM_STORE_SHARED(lttng_ust_getenv_is_init
, 1);
130 pthread_mutex_unlock(<tng_ust_getenv_init_mutex
);