1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include <selinux/selinux.h>
11 #include "sd-messages.h"
13 #include "initrd-util.h"
16 #include "selinux-setup.h"
17 #include "selinux-util.h"
18 #include "string-util.h"
19 #include "time-util.h"
23 static int null_log(int type
, const char *fmt
, ...) {
28 int mac_selinux_setup(bool *loaded_policy
) {
32 usec_t before_load
, after_load
;
37 assert(loaded_policy
);
39 /* Turn off all of SELinux' own logging, we want to do that */
40 selinux_set_callback(SELINUX_CB_LOG
, (const union selinux_callback
) { .func_log
= null_log
});
42 /* Don't load policy in the initrd if we don't appear to have it. For the real root, we check below
43 * if we've already loaded policy, and return gracefully. */
44 if (in_initrd() && access(selinux_path(), F_OK
) < 0)
47 /* Already initialized by somebody else? */
49 /* getcon_raw can return 0, and still give us a NULL pointer if /proc/self/attr/current is
50 * empty. SELinux guarantees this won't happen, but that file isn't specific to SELinux, and may be
51 * provided by some other arbitrary LSM with different semantics. */
53 initialized
= !streq(con
, "kernel");
58 /* Make sure we have no fds open while loading the policy and
62 /* Now load the policy */
63 before_load
= now(CLOCK_MONOTONIC
);
64 r
= selinux_init_load_policy(&enforce
);
66 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
70 /* Transition to the new context */
71 r
= mac_selinux_get_create_label_from_exe(SYSTEMD_BINARY_PATH
, &label
);
72 if (r
< 0 || !label
) {
74 log_error("Failed to compute init label, ignoring.");
76 r
= setcon_raw(label
);
80 log_error("Failed to transition into init label '%s', ignoring.", label
);
83 after_load
= now(CLOCK_MONOTONIC
);
85 log_info("Successfully loaded SELinux policy in %s.",
86 FORMAT_TIMESPAN(after_load
- before_load
, 0));
88 *loaded_policy
= true;
95 return log_struct_errno(LOG_EMERG
, SYNTHETIC_ERRNO(EIO
),
96 LOG_MESSAGE("Failed to load SELinux policy :%m"),
97 "MESSAGE_ID=" SD_MESSAGE_SELINUX_FAILED_STR
);
99 log_warning("Failed to load new SELinux policy. Continuing with old policy.");
101 log_debug("Unable to load SELinux policy. Ignoring.");