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
;
118 char timespan
[FORMAT_TIMESPAN_MAX
];
120 # if HAVE_GENERIC_MALLINFO
121 generic_mallinfo before_mallinfo
= generic_mallinfo_get();
123 before_timestamp
= now(CLOCK_MONOTONIC
);
125 hnd
= selabel_open(SELABEL_CTX_FILE
, NULL
, 0);
127 return log_enforcing_errno(errno
, "Failed to initialize SELinux labeling handle: %m");
129 after_timestamp
= now(CLOCK_MONOTONIC
);
130 # if HAVE_GENERIC_MALLINFO
131 generic_mallinfo after_mallinfo
= generic_mallinfo_get();
132 size_t l
= LESS_BY((size_t) after_mallinfo
.uordblks
, (size_t) before_mallinfo
.uordblks
);
133 log_debug("Successfully loaded SELinux database in %s, size on heap is %zuK.",
134 format_timespan(timespan
, sizeof(timespan
), after_timestamp
- before_timestamp
, 0),
135 DIV_ROUND_UP(l
, 1024));
137 log_debug("Successfully loaded SELinux database in %s.",
138 format_timespan(timespan
, sizeof(timespan
), after_timestamp
- before_timestamp
, 0));
141 /* release memory after measurement */
143 selabel_close(label_hnd
);
144 label_hnd
= TAKE_PTR(hnd
);
150 int mac_selinux_init(void) {
157 if (!mac_selinux_use())
160 r
= selinux_status_open(/* netlink fallback */ 1);
162 if (!ERRNO_IS_PRIVILEGE(errno
))
163 return log_enforcing_errno(errno
, "Failed to open SELinux status page: %m");
164 log_warning_errno(errno
, "selinux_status_open() with netlink fallback failed, not checking for policy reloads: %m");
166 log_warning("selinux_status_open() failed to open the status page, using the netlink fallback.");
168 have_status_page
= true;
172 selinux_status_close();
176 /* Save the current policyload sequence number, so mac_selinux_maybe_reload() does not trigger on
177 * first call without any actual change. */
178 last_policyload
= selinux_status_policyload();
185 void mac_selinux_maybe_reload(void) {
192 /* Do not use selinux_status_updated(3), cause since libselinux 3.2 selinux_check_access(3),
193 * called in core and user instances, does also use it under the hood.
194 * That can cause changes to be consumed by selinux_check_access(3) and not being visible here.
195 * Also do not use selinux callbacks, selinux_set_callback(3), cause they are only automatically
196 * invoked since libselinux 3.2 by selinux_status_updated(3).
197 * Relevant libselinux commit: https://github.com/SELinuxProject/selinux/commit/05bdc03130d741e53e1fb45a958d0a2c184be503
198 * Debian Bullseye is going to ship libselinux 3.1, so stay compatible for backports. */
199 policyload
= selinux_status_policyload();
200 if (policyload
< 0) {
201 log_debug_errno(errno
, "Failed to get SELinux policyload from status page: %m");
205 if (policyload
!= last_policyload
) {
206 mac_selinux_reload(policyload
);
207 last_policyload
= policyload
;
212 void mac_selinux_finish(void) {
216 selabel_close(label_hnd
);
220 selinux_status_close();
221 have_status_page
= false;
228 static int mac_selinux_reload(int seqno
) {
229 log_debug("SELinux reload %d", seqno
);
231 (void) open_label_db();
237 int mac_selinux_fix_container(const char *path
, const char *inside_path
, LabelFixFlags flags
) {
243 _cleanup_close_
int fd
= -1;
245 /* if mac_selinux_init() wasn't called before we are a NOOP */
249 /* Open the file as O_PATH, to pin it while we determine and adjust the label */
250 fd
= open(path
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
252 if ((flags
& LABEL_IGNORE_ENOENT
) && errno
== ENOENT
)
258 return mac_selinux_fix_container_fd(fd
, path
, inside_path
, flags
);
264 int mac_selinux_fix_container_fd(int fd
, const char *path
, const char *inside_path
, LabelFixFlags flags
) {
270 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
271 _cleanup_freecon_
char* fcon
= NULL
;
275 /* if mac_selinux_init() wasn't called before we are a NOOP */
279 if (fstat(fd
, &st
) < 0)
282 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
283 mac_selinux_maybe_reload();
287 if (selabel_lookup_raw(label_hnd
, &fcon
, inside_path
, st
.st_mode
) < 0) {
288 /* If there's no label to set, then exit without warning */
296 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
297 if (setfilecon_raw(procfs_path
, fcon
) < 0) {
298 _cleanup_freecon_
char *oldcon
= NULL
;
300 /* If the FS doesn't support labels, then exit without warning */
301 if (ERRNO_IS_NOT_SUPPORTED(errno
))
304 /* It the FS is read-only and we were told to ignore failures caused by that, suppress error */
305 if (errno
== EROFS
&& (flags
& LABEL_IGNORE_EROFS
))
310 /* If the old label is identical to the new one, suppress any kind of error */
311 if (getfilecon_raw(procfs_path
, &oldcon
) >= 0 && streq(fcon
, oldcon
))
320 return log_enforcing_errno(r
, "Unable to fix SELinux security context of %s (%s): %m", strna(path
), strna(inside_path
));
326 int mac_selinux_apply(const char *path
, const char *label
) {
331 if (!mac_selinux_use())
336 if (setfilecon(path
, label
) < 0)
337 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s on path %s: %m", label
, path
);
342 int mac_selinux_apply_fd(int fd
, const char *path
, const char *label
) {
347 if (!mac_selinux_use())
352 if (fsetfilecon(fd
, label
) < 0)
353 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s on path %s: %m", label
, strna(path
));
358 int mac_selinux_get_create_label_from_exe(const char *exe
, char **label
) {
360 _cleanup_freecon_
char *mycon
= NULL
, *fcon
= NULL
;
361 security_class_t sclass
;
367 if (!mac_selinux_use())
370 r
= getcon_raw(&mycon
);
374 r
= getfilecon_raw(exe
, &fcon
);
378 sclass
= string_to_security_class("process");
382 r
= security_compute_create_raw(mycon
, fcon
, sclass
, label
);
392 int mac_selinux_get_our_label(char **label
) {
398 if (!mac_selinux_use())
401 r
= getcon_raw(label
);
411 int mac_selinux_get_child_mls_label(int socket_fd
, const char *exe
, const char *exec_label
, char **label
) {
413 _cleanup_freecon_
char *mycon
= NULL
, *peercon
= NULL
, *fcon
= NULL
;
414 _cleanup_context_free_ context_t pcon
= NULL
, bcon
= NULL
;
415 security_class_t sclass
;
416 const char *range
= NULL
;
419 assert(socket_fd
>= 0);
423 if (!mac_selinux_use())
426 r
= getcon_raw(&mycon
);
430 r
= getpeercon_raw(socket_fd
, &peercon
);
435 /* If there is no context set for next exec let's use context
436 of target executable */
437 r
= getfilecon_raw(exe
, &fcon
);
442 bcon
= context_new(mycon
);
446 pcon
= context_new(peercon
);
450 range
= context_range_get(pcon
);
454 r
= context_range_set(bcon
, range
);
459 mycon
= strdup(context_str(bcon
));
463 sclass
= string_to_security_class("process");
467 r
= security_compute_create_raw(mycon
, fcon
, sclass
, label
);
477 char* mac_selinux_free(char *label
) {
489 static int selinux_create_file_prepare_abspath(const char *abspath
, mode_t mode
) {
490 _cleanup_freecon_
char *filecon
= NULL
;
494 assert(path_is_absolute(abspath
));
496 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
497 mac_selinux_maybe_reload();
501 r
= selabel_lookup_raw(label_hnd
, &filecon
, abspath
, mode
);
503 /* No context specified by the policy? Proceed without setting it. */
507 return log_enforcing_errno(errno
, "Failed to determine SELinux security context for %s: %m", abspath
);
510 if (setfscreatecon_raw(filecon
) < 0)
511 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s for %s: %m", filecon
, abspath
);
517 int mac_selinux_create_file_prepare_at(int dirfd
, const char *path
, mode_t mode
) {
519 _cleanup_free_
char *abspath
= NULL
;
527 if (!path_is_absolute(path
)) {
528 if (dirfd
== AT_FDCWD
)
529 r
= safe_getcwd(&abspath
);
531 r
= fd_get_path(dirfd
, &abspath
);
535 if (!path_extend(&abspath
, path
))
541 return selinux_create_file_prepare_abspath(path
, mode
);
547 int mac_selinux_create_file_prepare(const char *path
, mode_t mode
) {
551 _cleanup_free_
char *abspath
= NULL
;
558 r
= path_make_absolute_cwd(path
, &abspath
);
562 return selinux_create_file_prepare_abspath(abspath
, mode
);
568 void mac_selinux_create_file_clear(void) {
573 if (!mac_selinux_use())
576 setfscreatecon_raw(NULL
);
580 int mac_selinux_create_socket_prepare(const char *label
) {
585 if (!mac_selinux_use())
588 if (setsockcreatecon(label
) < 0)
589 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s for sockets: %m", label
);
595 void mac_selinux_create_socket_clear(void) {
600 if (!mac_selinux_use())
603 setsockcreatecon_raw(NULL
);
607 int mac_selinux_bind(int fd
, const struct sockaddr
*addr
, socklen_t addrlen
) {
609 /* Binds a socket and label its file system object according to the SELinux policy */
612 _cleanup_freecon_
char *fcon
= NULL
;
613 const struct sockaddr_un
*un
;
614 bool context_changed
= false;
620 assert(addrlen
>= sizeof(sa_family_t
));
625 /* Filter out non-local sockets */
626 if (addr
->sa_family
!= AF_UNIX
)
629 /* Filter out anonymous sockets */
630 if (addrlen
< offsetof(struct sockaddr_un
, sun_path
) + 1)
633 /* Filter out abstract namespace sockets */
634 un
= (const struct sockaddr_un
*) addr
;
635 if (un
->sun_path
[0] == 0)
638 path
= strndupa(un
->sun_path
, addrlen
- offsetof(struct sockaddr_un
, sun_path
));
640 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
641 mac_selinux_maybe_reload();
645 if (path_is_absolute(path
))
646 r
= selabel_lookup_raw(label_hnd
, &fcon
, path
, S_IFSOCK
);
648 _cleanup_free_
char *newpath
= NULL
;
650 r
= path_make_absolute_cwd(path
, &newpath
);
654 r
= selabel_lookup_raw(label_hnd
, &fcon
, newpath
, S_IFSOCK
);
658 /* No context specified by the policy? Proceed without setting it */
662 r
= log_enforcing_errno(errno
, "Failed to determine SELinux security context for %s: %m", path
);
666 if (setfscreatecon_raw(fcon
) < 0) {
667 r
= log_enforcing_errno(errno
, "Failed to set SELinux security context %s for %s: %m", fcon
, path
);
671 context_changed
= true;
674 r
= bind(fd
, addr
, addrlen
) < 0 ? -errno
: 0;
677 (void) setfscreatecon_raw(NULL
);
683 if (bind(fd
, addr
, addrlen
) < 0)