File: selinux-utils.c

package info (click to toggle)
util-linux 2.41-5
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 95,208 kB
  • sloc: ansic: 179,016; sh: 22,689; yacc: 1,284; makefile: 528; xml: 422; python: 316; lex: 89; ruby: 75; csh: 37; exp: 19; sed: 16; perl: 15; sql: 9
file content (85 lines) | stat: -rw-r--r-- 1,774 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 * No copyright is claimed.  This code is in the public domain; do with
 * it what you wish.
 *
 * Written by Karel Zak <kzak@redhat.com> [January 2021]
 */
#include <selinux/context.h>
#include <selinux/selinux.h>
#include <selinux/label.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>

#include "selinux-utils.h"

/* set the SELinux security context used for _creating_ a new file system object
 *
 * returns 0 on success,
 *     or <0 on error
 */
int ul_setfscreatecon_from_file(char *orig_file)
{
	if (is_selinux_enabled() > 0) {
		char *scontext = NULL;

		if (getfilecon(orig_file, &scontext) < 0)
			return -1;
		if (setfscreatecon(scontext) < 0) {
			freecon(scontext);
			return -1;
		}
		freecon(scontext);
	}
	return 0;
}

/* returns 1 if user has access to @class and @perm ("passwd", "chfn")
 *	or 0 on error,
 *	or 0 if has no access -- in this case sets @user_cxt to user-context
 */
int ul_selinux_has_access(const char *classstr, const char *perm, char **user_cxt)
{
	char *user;
	int rc;

	if (user_cxt)
		*user_cxt = NULL;

	if (getprevcon(&user) != 0)
		return 0;

	rc = selinux_check_access(user, user, classstr, perm, NULL);
	if (rc != 0 && user_cxt)
		*user_cxt = user;
	else
		freecon(user);

	return rc == 0 ? 1 : 0;
}

/* Gets the default context for @path and @st_mode.
 *
 * returns 0 on success,
 *     or <0 on error
 */
int ul_selinux_get_default_context(const char *path, int st_mode, char **cxt)
{
	struct selabel_handle *hnd;
	struct selinux_opt options[SELABEL_NOPT] = {};
	int rc = 0;

	*cxt = NULL;

	hnd = selabel_open(SELABEL_CTX_FILE, options, SELABEL_NOPT);
	if (!hnd)
		return -errno;

	if (selabel_lookup(hnd, cxt, path, st_mode) != 0)
		rc = -errno
			;
	selabel_close(hnd);

	return rc;
}