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