1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include <sys/types.h>
15 #include <selinux/avc.h>
16 #include <selinux/context.h>
17 #include <selinux/label.h>
18 #include <selinux/selinux.h>
21 #include "alloc-util.h"
22 #include "errno-util.h"
26 #include "path-util.h"
27 #include "selinux-util.h"
28 #include "stdio-util.h"
29 #include "time-util.h"
32 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(context_t
, context_free
, NULL
);
33 #define _cleanup_context_free_ _cleanup_(context_freep)
35 static int mac_selinux_reload(int seqno
);
37 static int cached_use
= -1;
38 static bool initialized
= false;
39 static int last_policyload
= 0;
40 static struct selabel_handle
*label_hnd
= NULL
;
41 static bool have_status_page
= false;
43 #define log_enforcing(...) \
44 log_full(mac_selinux_enforcing() ? LOG_ERR : LOG_WARNING, __VA_ARGS__)
46 #define log_enforcing_errno(error, ...) \
48 bool _enforcing = mac_selinux_enforcing(); \
49 int _level = _enforcing ? LOG_ERR : LOG_WARNING; \
52 int _r = (log_get_max_level() >= LOG_PRI(_level)) \
53 ? log_internal(_level, _e, PROJECT_FILE, __LINE__, __func__, __VA_ARGS__) \
55 _enforcing ? _r : 0; \
59 bool mac_selinux_use(void) {
61 if (_unlikely_(cached_use
< 0)) {
62 cached_use
= is_selinux_enabled() > 0;
63 log_debug("SELinux enabled state cached to: %s", cached_use
? "enabled" : "disabled");
72 bool mac_selinux_enforcing(void) {
76 /* If the SELinux status page has been successfully opened, retrieve the enforcing
77 * status over it to avoid system calls in security_getenforce(). */
80 r
= selinux_status_getenforce();
82 r
= security_getenforce();
88 void mac_selinux_retest(void) {
96 # define HAVE_GENERIC_MALLINFO 1
97 typedef struct mallinfo2 generic_mallinfo
;
98 static generic_mallinfo
generic_mallinfo_get(void) {
102 # define HAVE_GENERIC_MALLINFO 1
103 typedef struct mallinfo generic_mallinfo
;
104 static generic_mallinfo
generic_mallinfo_get(void) {
105 /* glibc has deprecated mallinfo(), let's suppress the deprecation warning if mallinfo2() doesn't
107 DISABLE_WARNING_DEPRECATED_DECLARATIONS
112 # define HAVE_GENERIC_MALLINFO 0
115 static int open_label_db(void) {
116 struct selabel_handle
*hnd
;
117 usec_t before_timestamp
, after_timestamp
;
119 # if HAVE_GENERIC_MALLINFO
120 generic_mallinfo before_mallinfo
= generic_mallinfo_get();
122 before_timestamp
= now(CLOCK_MONOTONIC
);
124 hnd
= selabel_open(SELABEL_CTX_FILE
, NULL
, 0);
126 return log_enforcing_errno(errno
, "Failed to initialize SELinux labeling handle: %m");
128 after_timestamp
= now(CLOCK_MONOTONIC
);
129 # if HAVE_GENERIC_MALLINFO
130 generic_mallinfo after_mallinfo
= generic_mallinfo_get();
131 size_t l
= LESS_BY((size_t) after_mallinfo
.uordblks
, (size_t) before_mallinfo
.uordblks
);
132 log_debug("Successfully loaded SELinux database in %s, size on heap is %zuK.",
133 FORMAT_TIMESPAN(after_timestamp
- before_timestamp
, 0),
134 DIV_ROUND_UP(l
, 1024));
136 log_debug("Successfully loaded SELinux database in %s.",
137 FORMAT_TIMESPAN(after_timestamp
- before_timestamp
, 0));
140 /* release memory after measurement */
142 selabel_close(label_hnd
);
143 label_hnd
= TAKE_PTR(hnd
);
149 int mac_selinux_init(void) {
156 if (!mac_selinux_use())
159 r
= selinux_status_open(/* netlink fallback */ 1);
161 if (!ERRNO_IS_PRIVILEGE(errno
))
162 return log_enforcing_errno(errno
, "Failed to open SELinux status page: %m");
163 log_warning_errno(errno
, "selinux_status_open() with netlink fallback failed, not checking for policy reloads: %m");
165 log_warning("selinux_status_open() failed to open the status page, using the netlink fallback.");
167 have_status_page
= true;
171 selinux_status_close();
175 /* Save the current policyload sequence number, so mac_selinux_maybe_reload() does not trigger on
176 * first call without any actual change. */
177 last_policyload
= selinux_status_policyload();
184 void mac_selinux_maybe_reload(void) {
191 /* Do not use selinux_status_updated(3), cause since libselinux 3.2 selinux_check_access(3),
192 * called in core and user instances, does also use it under the hood.
193 * That can cause changes to be consumed by selinux_check_access(3) and not being visible here.
194 * Also do not use selinux callbacks, selinux_set_callback(3), cause they are only automatically
195 * invoked since libselinux 3.2 by selinux_status_updated(3).
196 * Relevant libselinux commit: https://github.com/SELinuxProject/selinux/commit/05bdc03130d741e53e1fb45a958d0a2c184be503
197 * Debian Bullseye is going to ship libselinux 3.1, so stay compatible for backports. */
198 policyload
= selinux_status_policyload();
199 if (policyload
< 0) {
200 log_debug_errno(errno
, "Failed to get SELinux policyload from status page: %m");
204 if (policyload
!= last_policyload
) {
205 mac_selinux_reload(policyload
);
206 last_policyload
= policyload
;
211 void mac_selinux_finish(void) {
215 selabel_close(label_hnd
);
219 selinux_status_close();
220 have_status_page
= false;
227 static int mac_selinux_reload(int seqno
) {
228 log_debug("SELinux reload %d", seqno
);
230 (void) open_label_db();
236 int mac_selinux_fix_container(const char *path
, const char *inside_path
, LabelFixFlags flags
) {
242 _cleanup_close_
int fd
= -1;
244 /* if mac_selinux_init() wasn't called before we are a NOOP */
248 /* Open the file as O_PATH, to pin it while we determine and adjust the label */
249 fd
= open(path
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
251 if ((flags
& LABEL_IGNORE_ENOENT
) && errno
== ENOENT
)
257 return mac_selinux_fix_container_fd(fd
, path
, inside_path
, flags
);
263 int mac_selinux_fix_container_fd(int fd
, const char *path
, const char *inside_path
, LabelFixFlags flags
) {
269 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
270 _cleanup_freecon_
char* fcon
= NULL
;
274 /* if mac_selinux_init() wasn't called before we are a NOOP */
278 if (fstat(fd
, &st
) < 0)
281 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
282 mac_selinux_maybe_reload();
286 if (selabel_lookup_raw(label_hnd
, &fcon
, inside_path
, st
.st_mode
) < 0) {
287 /* If there's no label to set, then exit without warning */
295 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
296 if (setfilecon_raw(procfs_path
, fcon
) < 0) {
297 _cleanup_freecon_
char *oldcon
= NULL
;
299 /* If the FS doesn't support labels, then exit without warning */
300 if (ERRNO_IS_NOT_SUPPORTED(errno
))
303 /* It the FS is read-only and we were told to ignore failures caused by that, suppress error */
304 if (errno
== EROFS
&& (flags
& LABEL_IGNORE_EROFS
))
309 /* If the old label is identical to the new one, suppress any kind of error */
310 if (getfilecon_raw(procfs_path
, &oldcon
) >= 0 && streq(fcon
, oldcon
))
319 return log_enforcing_errno(r
, "Unable to fix SELinux security context of %s (%s): %m", strna(path
), strna(inside_path
));
325 int mac_selinux_apply(const char *path
, const char *label
) {
330 if (!mac_selinux_use())
335 if (setfilecon(path
, label
) < 0)
336 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s on path %s: %m", label
, path
);
341 int mac_selinux_apply_fd(int fd
, const char *path
, const char *label
) {
346 if (!mac_selinux_use())
351 if (fsetfilecon(fd
, label
) < 0)
352 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s on path %s: %m", label
, strna(path
));
357 int mac_selinux_get_create_label_from_exe(const char *exe
, char **label
) {
359 _cleanup_freecon_
char *mycon
= NULL
, *fcon
= NULL
;
360 security_class_t sclass
;
366 if (!mac_selinux_use())
369 r
= getcon_raw(&mycon
);
373 r
= getfilecon_raw(exe
, &fcon
);
377 sclass
= string_to_security_class("process");
381 r
= security_compute_create_raw(mycon
, fcon
, sclass
, label
);
391 int mac_selinux_get_our_label(char **label
) {
397 if (!mac_selinux_use())
400 r
= getcon_raw(label
);
410 int mac_selinux_get_child_mls_label(int socket_fd
, const char *exe
, const char *exec_label
, char **label
) {
412 _cleanup_freecon_
char *mycon
= NULL
, *peercon
= NULL
, *fcon
= NULL
;
413 _cleanup_context_free_ context_t pcon
= NULL
, bcon
= NULL
;
414 security_class_t sclass
;
415 const char *range
= NULL
;
418 assert(socket_fd
>= 0);
422 if (!mac_selinux_use())
425 r
= getcon_raw(&mycon
);
429 r
= getpeercon_raw(socket_fd
, &peercon
);
434 /* If there is no context set for next exec let's use context
435 of target executable */
436 r
= getfilecon_raw(exe
, &fcon
);
441 bcon
= context_new(mycon
);
445 pcon
= context_new(peercon
);
449 range
= context_range_get(pcon
);
453 r
= context_range_set(bcon
, range
);
458 mycon
= strdup(context_str(bcon
));
462 sclass
= string_to_security_class("process");
466 r
= security_compute_create_raw(mycon
, fcon
, sclass
, label
);
476 char* mac_selinux_free(char *label
) {
488 static int selinux_create_file_prepare_abspath(const char *abspath
, mode_t mode
) {
489 _cleanup_freecon_
char *filecon
= NULL
;
493 assert(path_is_absolute(abspath
));
495 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
496 mac_selinux_maybe_reload();
500 r
= selabel_lookup_raw(label_hnd
, &filecon
, abspath
, mode
);
502 /* No context specified by the policy? Proceed without setting it. */
506 return log_enforcing_errno(errno
, "Failed to determine SELinux security context for %s: %m", abspath
);
509 if (setfscreatecon_raw(filecon
) < 0)
510 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s for %s: %m", filecon
, abspath
);
516 int mac_selinux_create_file_prepare_at(int dirfd
, const char *path
, mode_t mode
) {
518 _cleanup_free_
char *abspath
= NULL
;
526 if (!path_is_absolute(path
)) {
527 if (dirfd
== AT_FDCWD
)
528 r
= safe_getcwd(&abspath
);
530 r
= fd_get_path(dirfd
, &abspath
);
534 if (!path_extend(&abspath
, path
))
540 return selinux_create_file_prepare_abspath(path
, mode
);
546 int mac_selinux_create_file_prepare(const char *path
, mode_t mode
) {
550 _cleanup_free_
char *abspath
= NULL
;
557 r
= path_make_absolute_cwd(path
, &abspath
);
561 return selinux_create_file_prepare_abspath(abspath
, mode
);
567 void mac_selinux_create_file_clear(void) {
572 if (!mac_selinux_use())
575 setfscreatecon_raw(NULL
);
579 int mac_selinux_create_socket_prepare(const char *label
) {
584 if (!mac_selinux_use())
587 if (setsockcreatecon(label
) < 0)
588 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s for sockets: %m", label
);
594 void mac_selinux_create_socket_clear(void) {
599 if (!mac_selinux_use())
602 setsockcreatecon_raw(NULL
);
606 int mac_selinux_bind(int fd
, const struct sockaddr
*addr
, socklen_t addrlen
) {
608 /* Binds a socket and label its file system object according to the SELinux policy */
611 _cleanup_freecon_
char *fcon
= NULL
;
612 const struct sockaddr_un
*un
;
613 bool context_changed
= false;
619 assert(addrlen
>= sizeof(sa_family_t
));
624 /* Filter out non-local sockets */
625 if (addr
->sa_family
!= AF_UNIX
)
628 /* Filter out anonymous sockets */
629 if (addrlen
< offsetof(struct sockaddr_un
, sun_path
) + 1)
632 /* Filter out abstract namespace sockets */
633 un
= (const struct sockaddr_un
*) addr
;
634 if (un
->sun_path
[0] == 0)
637 path
= strndupa(un
->sun_path
, addrlen
- offsetof(struct sockaddr_un
, sun_path
));
639 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
640 mac_selinux_maybe_reload();
644 if (path_is_absolute(path
))
645 r
= selabel_lookup_raw(label_hnd
, &fcon
, path
, S_IFSOCK
);
647 _cleanup_free_
char *newpath
= NULL
;
649 r
= path_make_absolute_cwd(path
, &newpath
);
653 r
= selabel_lookup_raw(label_hnd
, &fcon
, newpath
, S_IFSOCK
);
657 /* No context specified by the policy? Proceed without setting it */
661 r
= log_enforcing_errno(errno
, "Failed to determine SELinux security context for %s: %m", path
);
665 if (setfscreatecon_raw(fcon
) < 0) {
666 r
= log_enforcing_errno(errno
, "Failed to set SELinux security context %s for %s: %m", fcon
, path
);
670 context_changed
= true;
673 r
= bind(fd
, addr
, addrlen
) < 0 ? -errno
: 0;
676 (void) setfscreatecon_raw(NULL
);
682 if (bind(fd
, addr
, addrlen
) < 0)