]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/selinux-setup.c
Merge pull request #11714 from poettering/final-news-241
[thirdparty/systemd.git] / src / core / selinux-setup.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <unistd.h>
6
7 #if HAVE_SELINUX
8 #include <selinux/selinux.h>
9 #endif
10
11 #include "log.h"
12 #include "macro.h"
13 #include "selinux-setup.h"
14 #include "selinux-util.h"
15 #include "string-util.h"
16 #include "util.h"
17
18 #if HAVE_SELINUX
19 _printf_(2,3)
20 static int null_log(int type, const char *fmt, ...) {
21 return 0;
22 }
23 #endif
24
25 int mac_selinux_setup(bool *loaded_policy) {
26
27 #if HAVE_SELINUX
28 int enforce = 0;
29 usec_t before_load, after_load;
30 char *con;
31 int r;
32 static const union selinux_callback cb = {
33 .func_log = null_log,
34 };
35
36 bool initialized = false;
37
38 assert(loaded_policy);
39
40 /* Turn off all of SELinux' own logging, we want to do that */
41 selinux_set_callback(SELINUX_CB_LOG, cb);
42
43 /* Don't load policy in the initrd if we don't appear to have
44 * it. For the real root, we check below if we've already
45 * loaded policy, and return gracefully.
46 */
47 if (in_initrd() && access(selinux_path(), F_OK) < 0)
48 return 0;
49
50 /* Already initialized by somebody else? */
51 r = getcon_raw(&con);
52 if (r == 0) {
53 initialized = !streq(con, "kernel");
54 freecon(con);
55 }
56
57 /* Make sure we have no fds open while loading the policy and
58 * transitioning */
59 log_close();
60
61 /* Now load the policy */
62 before_load = now(CLOCK_MONOTONIC);
63 r = selinux_init_load_policy(&enforce);
64 if (r == 0) {
65 _cleanup_(mac_selinux_freep) char *label = NULL;
66 char timespan[FORMAT_TIMESPAN_MAX];
67
68 mac_selinux_retest();
69
70 /* Transition to the new context */
71 r = mac_selinux_get_create_label_from_exe(SYSTEMD_BINARY_PATH, &label);
72 if (r < 0 || !label) {
73 log_open();
74 log_error("Failed to compute init label, ignoring.");
75 } else {
76 r = setcon_raw(label);
77
78 log_open();
79 if (r < 0)
80 log_error("Failed to transition into init label '%s', ignoring.", label);
81 }
82
83 after_load = now(CLOCK_MONOTONIC);
84
85 log_info("Successfully loaded SELinux policy in %s.",
86 format_timespan(timespan, sizeof(timespan), after_load - before_load, 0));
87
88 *loaded_policy = true;
89
90 } else {
91 log_open();
92
93 if (enforce > 0) {
94 if (!initialized) {
95 log_emergency("Failed to load SELinux policy.");
96 return -EIO;
97 }
98
99 log_warning("Failed to load new SELinux policy. Continuing with old policy.");
100 } else
101 log_debug("Unable to load SELinux policy. Ignoring.");
102 }
103 #endif
104
105 return 0;
106 }