| 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 <usterr-signal-safe.h> |
| 13 | #include <ust-helper.h> |
| 14 | #include "getenv.h" |
| 15 | |
| 16 | enum lttng_env_secure { |
| 17 | LTTNG_ENV_SECURE, |
| 18 | LTTNG_ENV_NOT_SECURE, |
| 19 | }; |
| 20 | |
| 21 | struct lttng_env { |
| 22 | const char *key; |
| 23 | enum lttng_env_secure secure; |
| 24 | char *value; |
| 25 | }; |
| 26 | |
| 27 | static struct lttng_env lttng_env[] = { |
| 28 | /* |
| 29 | * LTTNG_UST_DEBUG is used directly by snprintf, because it |
| 30 | * needs to be already set for ERR() used in |
| 31 | * lttng_ust_getenv_init(). |
| 32 | */ |
| 33 | { "LTTNG_UST_DEBUG", LTTNG_ENV_NOT_SECURE, NULL, }, |
| 34 | |
| 35 | /* Env. var. which can be used in setuid/setgid executables. */ |
| 36 | { "LTTNG_UST_WITHOUT_BADDR_STATEDUMP", LTTNG_ENV_NOT_SECURE, NULL, }, |
| 37 | { "LTTNG_UST_REGISTER_TIMEOUT", LTTNG_ENV_NOT_SECURE, NULL, }, |
| 38 | |
| 39 | /* Env. var. which are not fetched in setuid/setgid executables. */ |
| 40 | { "LTTNG_UST_CLOCK_PLUGIN", LTTNG_ENV_SECURE, NULL, }, |
| 41 | { "LTTNG_UST_GETCPU_PLUGIN", LTTNG_ENV_SECURE, NULL, }, |
| 42 | { "LTTNG_UST_ALLOW_BLOCKING", LTTNG_ENV_SECURE, NULL, }, |
| 43 | { "HOME", LTTNG_ENV_SECURE, NULL, }, |
| 44 | { "LTTNG_HOME", LTTNG_ENV_SECURE, NULL, }, |
| 45 | }; |
| 46 | |
| 47 | static |
| 48 | int lttng_is_setuid_setgid(void) |
| 49 | { |
| 50 | return geteuid() != getuid() || getegid() != getgid(); |
| 51 | } |
| 52 | |
| 53 | char *lttng_getenv(const char *name) |
| 54 | { |
| 55 | size_t i; |
| 56 | struct lttng_env *e; |
| 57 | bool found = false; |
| 58 | |
| 59 | for (i = 0; i < LTTNG_ARRAY_SIZE(lttng_env); i++) { |
| 60 | e = <tng_env[i]; |
| 61 | |
| 62 | if (strcmp(e->key, name) == 0) { |
| 63 | found = true; |
| 64 | break; |
| 65 | } |
| 66 | } |
| 67 | if (!found) { |
| 68 | return NULL; |
| 69 | } |
| 70 | return e->value; |
| 71 | } |
| 72 | |
| 73 | void lttng_ust_getenv_init(void) |
| 74 | { |
| 75 | size_t i; |
| 76 | |
| 77 | for (i = 0; i < LTTNG_ARRAY_SIZE(lttng_env); i++) { |
| 78 | struct lttng_env *e = <tng_env[i]; |
| 79 | |
| 80 | if (e->secure == LTTNG_ENV_SECURE && lttng_is_setuid_setgid()) { |
| 81 | ERR("Getting environment variable '%s' from setuid/setgid binary refused for security reasons.", |
| 82 | e->key); |
| 83 | continue; |
| 84 | } |
| 85 | e->value = getenv(e->key); |
| 86 | } |
| 87 | } |