]> git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/selinux-utils.c
mkswap: remove deprecated SELinux matchpathcon()
[thirdparty/util-linux.git] / lib / selinux-utils.c
1 /*
2 * No copyright is claimed. This code is in the public domain; do with
3 * it what you wish.
4 *
5 * Written by Karel Zak <kzak@redhat.com> [January 2021]
6 */
7 #include <selinux/context.h>
8 #include <selinux/selinux.h>
9 #include <selinux/label.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <errno.h>
14
15 #include "selinux-utils.h"
16
17 int ul_setfscreatecon_from_file(char *orig_file)
18 {
19 if (is_selinux_enabled() > 0) {
20 char *scontext = NULL;
21
22 if (getfilecon(orig_file, &scontext) < 0)
23 return 1;
24 if (setfscreatecon(scontext) < 0) {
25 freecon(scontext);
26 return 1;
27 }
28 freecon(scontext);
29 }
30 return 0;
31 }
32
33 /* returns 1 if user has access to @class and @perm ("passwd", "chfn")
34 * or 0 on error,
35 * or 0 if has no access -- in this case sets @user_cxt to user-context
36 */
37 int ul_selinux_has_access(const char *classstr, const char *perm, char **user_cxt)
38 {
39 char *user;
40 int rc;
41
42 if (user_cxt)
43 *user_cxt = NULL;
44
45 if (getprevcon(&user) != 0)
46 return 0;
47
48 rc = selinux_check_access(user, user, classstr, perm, NULL);
49 if (rc != 0 && user_cxt)
50 *user_cxt = user;
51 else
52 freecon(user);
53
54 return rc == 0 ? 1 : 0;
55 }
56
57 /* return 0 on success, 0 on error; @cxt returns the default context for @path
58 * and @st_mode (stat())
59 */
60 int ul_selinux_get_default_context(const char *path, int st_mode, char **cxt)
61 {
62 struct selabel_handle *hnd;
63 struct selinux_opt options[SELABEL_NOPT] = {};
64 int rc = 0;
65
66 *cxt = NULL;
67
68 hnd = selabel_open(SELABEL_CTX_FILE, options, SELABEL_NOPT);
69 if (!hnd)
70 return -errno;
71
72 if (selabel_lookup(hnd, cxt, path, st_mode) != 0)
73 rc = -errno
74 ;
75 selabel_close(hnd);
76
77 return rc;
78 }