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 (*enforcing_status_func
)(void) = security_getenforce
;
40 static int last_policyload
= 0;
41 static struct selabel_handle
*label_hnd
= NULL
;
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) {
74 return enforcing_status_func() != 0;
80 void mac_selinux_retest(void) {
88 static struct mallinfo
mallinfo_nowarn(void) {
89 /* glibc has deprecated mallinfo(), but the replacement malloc_info() returns an XML blob ;=[ */
90 DISABLE_WARNING_DEPRECATED_DECLARATIONS
95 # warning "mallinfo() is missing, add mallinfo2() supported instead."
98 static int open_label_db(void) {
99 struct selabel_handle
*hnd
;
100 usec_t before_timestamp
, after_timestamp
;
101 char timespan
[FORMAT_TIMESPAN_MAX
];
104 struct mallinfo before_mallinfo
= mallinfo_nowarn();
106 before_timestamp
= now(CLOCK_MONOTONIC
);
108 hnd
= selabel_open(SELABEL_CTX_FILE
, NULL
, 0);
110 return log_enforcing_errno(errno
, "Failed to initialize SELinux labeling handle: %m");
112 after_timestamp
= now(CLOCK_MONOTONIC
);
114 struct mallinfo after_mallinfo
= mallinfo_nowarn();
115 int l
= after_mallinfo
.uordblks
> before_mallinfo
.uordblks
? after_mallinfo
.uordblks
- before_mallinfo
.uordblks
: 0;
116 log_debug("Successfully loaded SELinux database in %s, size on heap is %iK.",
117 format_timespan(timespan
, sizeof(timespan
), after_timestamp
- before_timestamp
, 0),
118 DIV_ROUND_UP(l
, 1024));
120 log_debug("Successfully loaded SELinux database in %s.",
121 format_timespan(timespan
, sizeof(timespan
), after_timestamp
- before_timestamp
, 0));
124 /* release memory after measurement */
126 selabel_close(label_hnd
);
127 label_hnd
= TAKE_PTR(hnd
);
133 int mac_selinux_init(void) {
136 bool have_status_page
= false;
141 if (!mac_selinux_use())
144 r
= selinux_status_open(/* netlink fallback */ 1);
146 if (!ERRNO_IS_PRIVILEGE(errno
))
147 return log_enforcing_errno(errno
, "Failed to open SELinux status page: %m");
148 log_warning_errno(errno
, "selinux_status_open() with netlink fallback failed, not checking for policy reloads: %m");
150 log_warning("selinux_status_open() failed to open the status page, using the netlink fallback.");
152 have_status_page
= true;
156 selinux_status_close();
160 /* Save the current policyload sequence number, so mac_selinux_maybe_reload() does not trigger on
161 * first call without any actual change. */
162 last_policyload
= selinux_status_policyload();
164 if (have_status_page
)
165 /* Now that the SELinux status page has been successfully opened, retrieve the enforcing
166 * status over it (to avoid system calls in security_getenforce()). */
167 enforcing_status_func
= selinux_status_getenforce
;
174 void mac_selinux_maybe_reload(void) {
181 r
= selinux_status_updated();
183 log_debug_errno(errno
, "Failed to update SELinux from status page: %m");
187 log_debug("SELinux status page update");
189 /* from libselinux > 3.1 callbacks gets automatically called, see
190 https://github.com/SELinuxProject/selinux/commit/05bdc03130d741e53e1fb45a958d0a2c184be503 */
192 /* only reload on policy changes, not enforcing status changes */
193 policyload
= selinux_status_policyload();
194 if (policyload
!= last_policyload
) {
195 mac_selinux_reload(policyload
);
196 last_policyload
= policyload
;
202 void mac_selinux_finish(void) {
206 selabel_close(label_hnd
);
210 enforcing_status_func
= security_getenforce
;
212 selinux_status_close();
219 static int mac_selinux_reload(int seqno
) {
220 log_debug("SELinux reload %d", seqno
);
222 (void) open_label_db();
228 int mac_selinux_fix_container(const char *path
, const char *inside_path
, LabelFixFlags flags
) {
234 _cleanup_close_
int fd
= -1;
236 /* if mac_selinux_init() wasn't called before we are a NOOP */
240 /* Open the file as O_PATH, to pin it while we determine and adjust the label */
241 fd
= open(path
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
243 if ((flags
& LABEL_IGNORE_ENOENT
) && errno
== ENOENT
)
249 return mac_selinux_fix_container_fd(fd
, path
, inside_path
, flags
);
255 int mac_selinux_fix_container_fd(int fd
, const char *path
, const char *inside_path
, LabelFixFlags flags
) {
261 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
262 _cleanup_freecon_
char* fcon
= NULL
;
266 /* if mac_selinux_init() wasn't called before we are a NOOP */
270 if (fstat(fd
, &st
) < 0)
273 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
274 mac_selinux_maybe_reload();
278 if (selabel_lookup_raw(label_hnd
, &fcon
, inside_path
, st
.st_mode
) < 0) {
279 /* If there's no label to set, then exit without warning */
287 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
288 if (setfilecon_raw(procfs_path
, fcon
) < 0) {
289 _cleanup_freecon_
char *oldcon
= NULL
;
291 /* If the FS doesn't support labels, then exit without warning */
292 if (ERRNO_IS_NOT_SUPPORTED(errno
))
295 /* It the FS is read-only and we were told to ignore failures caused by that, suppress error */
296 if (errno
== EROFS
&& (flags
& LABEL_IGNORE_EROFS
))
301 /* If the old label is identical to the new one, suppress any kind of error */
302 if (getfilecon_raw(procfs_path
, &oldcon
) >= 0 && streq(fcon
, oldcon
))
311 return log_enforcing_errno(r
, "Unable to fix SELinux security context of %s (%s): %m", strna(path
), strna(inside_path
));
317 int mac_selinux_apply(const char *path
, const char *label
) {
322 if (!mac_selinux_use())
327 if (setfilecon(path
, label
) < 0)
328 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s on path %s: %m", label
, path
);
333 int mac_selinux_apply_fd(int fd
, const char *path
, const char *label
) {
338 if (!mac_selinux_use())
343 if (fsetfilecon(fd
, label
) < 0)
344 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s on path %s: %m", label
, strna(path
));
349 int mac_selinux_get_create_label_from_exe(const char *exe
, char **label
) {
351 _cleanup_freecon_
char *mycon
= NULL
, *fcon
= NULL
;
352 security_class_t sclass
;
358 if (!mac_selinux_use())
361 r
= getcon_raw(&mycon
);
365 r
= getfilecon_raw(exe
, &fcon
);
369 sclass
= string_to_security_class("process");
373 r
= security_compute_create_raw(mycon
, fcon
, sclass
, label
);
383 int mac_selinux_get_our_label(char **label
) {
389 if (!mac_selinux_use())
392 r
= getcon_raw(label
);
402 int mac_selinux_get_child_mls_label(int socket_fd
, const char *exe
, const char *exec_label
, char **label
) {
404 _cleanup_freecon_
char *mycon
= NULL
, *peercon
= NULL
, *fcon
= NULL
;
405 _cleanup_context_free_ context_t pcon
= NULL
, bcon
= NULL
;
406 security_class_t sclass
;
407 const char *range
= NULL
;
410 assert(socket_fd
>= 0);
414 if (!mac_selinux_use())
417 r
= getcon_raw(&mycon
);
421 r
= getpeercon_raw(socket_fd
, &peercon
);
426 /* If there is no context set for next exec let's use context
427 of target executable */
428 r
= getfilecon_raw(exe
, &fcon
);
433 bcon
= context_new(mycon
);
437 pcon
= context_new(peercon
);
441 range
= context_range_get(pcon
);
445 r
= context_range_set(bcon
, range
);
450 mycon
= strdup(context_str(bcon
));
454 sclass
= string_to_security_class("process");
458 r
= security_compute_create_raw(mycon
, fcon
, sclass
, label
);
468 char* mac_selinux_free(char *label
) {
480 static int selinux_create_file_prepare_abspath(const char *abspath
, mode_t mode
) {
481 _cleanup_freecon_
char *filecon
= NULL
;
485 assert(path_is_absolute(abspath
));
487 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
488 mac_selinux_maybe_reload();
492 r
= selabel_lookup_raw(label_hnd
, &filecon
, abspath
, mode
);
494 /* No context specified by the policy? Proceed without setting it. */
498 return log_enforcing_errno(errno
, "Failed to determine SELinux security context for %s: %m", abspath
);
501 if (setfscreatecon_raw(filecon
) < 0)
502 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s for %s: %m", filecon
, abspath
);
508 int mac_selinux_create_file_prepare_at(int dirfd
, const char *path
, mode_t mode
) {
510 _cleanup_free_
char *abspath
= NULL
;
518 if (!path_is_absolute(path
)) {
519 _cleanup_free_
char *p
= NULL
;
521 if (dirfd
== AT_FDCWD
)
524 r
= fd_get_path(dirfd
, &p
);
528 path
= abspath
= path_join(p
, path
);
533 return selinux_create_file_prepare_abspath(path
, mode
);
539 int mac_selinux_create_file_prepare(const char *path
, mode_t mode
) {
543 _cleanup_free_
char *abspath
= NULL
;
550 r
= path_make_absolute_cwd(path
, &abspath
);
554 return selinux_create_file_prepare_abspath(abspath
, mode
);
560 void mac_selinux_create_file_clear(void) {
565 if (!mac_selinux_use())
568 setfscreatecon_raw(NULL
);
572 int mac_selinux_create_socket_prepare(const char *label
) {
577 if (!mac_selinux_use())
580 if (setsockcreatecon(label
) < 0)
581 return log_enforcing_errno(errno
, "Failed to set SELinux security context %s for sockets: %m", label
);
587 void mac_selinux_create_socket_clear(void) {
592 if (!mac_selinux_use())
595 setsockcreatecon_raw(NULL
);
599 int mac_selinux_bind(int fd
, const struct sockaddr
*addr
, socklen_t addrlen
) {
601 /* Binds a socket and label its file system object according to the SELinux policy */
604 _cleanup_freecon_
char *fcon
= NULL
;
605 const struct sockaddr_un
*un
;
606 bool context_changed
= false;
612 assert(addrlen
>= sizeof(sa_family_t
));
617 /* Filter out non-local sockets */
618 if (addr
->sa_family
!= AF_UNIX
)
621 /* Filter out anonymous sockets */
622 if (addrlen
< offsetof(struct sockaddr_un
, sun_path
) + 1)
625 /* Filter out abstract namespace sockets */
626 un
= (const struct sockaddr_un
*) addr
;
627 if (un
->sun_path
[0] == 0)
630 path
= strndupa(un
->sun_path
, addrlen
- offsetof(struct sockaddr_un
, sun_path
));
632 /* Check for policy reload so 'label_hnd' is kept up-to-date by callbacks */
633 mac_selinux_maybe_reload();
637 if (path_is_absolute(path
))
638 r
= selabel_lookup_raw(label_hnd
, &fcon
, path
, S_IFSOCK
);
640 _cleanup_free_
char *newpath
= NULL
;
642 r
= path_make_absolute_cwd(path
, &newpath
);
646 r
= selabel_lookup_raw(label_hnd
, &fcon
, newpath
, S_IFSOCK
);
650 /* No context specified by the policy? Proceed without setting it */
654 r
= log_enforcing_errno(errno
, "Failed to determine SELinux security context for %s: %m", path
);
658 if (setfscreatecon_raw(fcon
) < 0) {
659 r
= log_enforcing_errno(errno
, "Failed to set SELinux security context %s for %s: %m", fcon
, path
);
663 context_changed
= true;
666 r
= bind(fd
, addr
, addrlen
) < 0 ? -errno
: 0;
669 (void) setfscreatecon_raw(NULL
);
675 if (bind(fd
, addr
, addrlen
) < 0)