xref: /aosp_15_r20/external/selinux/libselinux/src/setexecfilecon.c (revision 2d543d20722ada2425b5bdab9d0d1d29470e7bba)
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <string.h>
4 #include "selinux_internal.h"
5 #include "context_internal.h"
6 
setexecfilecon(const char * filename,const char * fallback_type)7 int setexecfilecon(const char *filename, const char *fallback_type)
8 {
9 	char * mycon = NULL, *fcon = NULL, *newcon = NULL;
10 	context_t con = NULL;
11 	int rc = 0;
12 
13 	if (is_selinux_enabled() < 1)
14 		return 0;
15 
16 	rc = getcon(&mycon);
17 	if (rc < 0)
18 		goto out;
19 
20 	rc = getfilecon(filename, &fcon);
21 	if (rc < 0)
22 		goto out;
23 
24 	rc = security_compute_create(mycon, fcon, string_to_security_class("process"), &newcon);
25 	if (rc < 0)
26 		goto out;
27 
28 	if (!strcmp(mycon, newcon)) {
29 		/* No default transition, use fallback_type for now. */
30 		rc = -1;
31 		con = context_new(mycon);
32 		if (!con)
33 			goto out;
34 		if (context_type_set(con, fallback_type))
35 			goto out;
36 		freecon(newcon);
37 		newcon = strdup(context_str(con));
38 		if (!newcon)
39 			goto out;
40 	}
41 
42 	rc = setexeccon(newcon);
43       out:
44 
45 	if (rc < 0 && security_getenforce() == 0)
46 		rc = 0;
47 
48 	context_free(con);
49 	freecon(newcon);
50 	freecon(fcon);
51 	freecon(mycon);
52 	return rc < 0 ? rc : 0;
53 }
54 
55 #ifndef DISABLE_RPM
rpm_execcon(unsigned int verified,const char * filename,char * const argv[],char * const envp[])56 int rpm_execcon(unsigned int verified __attribute__ ((unused)),
57 		const char *filename, char *const argv[], char *const envp[])
58 {
59 	int rc;
60 
61 	rc = setexecfilecon(filename, "rpm_script_t");
62 	if (rc < 0)
63 		return rc;
64 
65 	return execve(filename, argv, envp);
66 }
67 #endif
68