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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
/*
* Copyright (C) 2020-2023 Firejail and systemd authors
*
* This file is part of firejail project, from systemd selinux-util.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#if HAVE_SELINUX
#include "firejail.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#ifndef O_PATH
#define O_PATH 010000000
#endif
#include <selinux/context.h>
#include <selinux/label.h>
#include <selinux/selinux.h>
static struct selabel_handle *label_hnd = NULL;
static int selinux_enabled = -1;
#endif
void selinux_relabel_path(const char *path, const char *inside_path)
{
#if HAVE_SELINUX
char procfs_path[64];
char *fcon = NULL;
int fd;
struct stat st;
if (selinux_enabled == -1)
selinux_enabled = is_selinux_enabled();
if (!selinux_enabled)
return;
if (!label_hnd)
label_hnd = selabel_open(SELABEL_CTX_FILE, NULL, 0);
if (!label_hnd)
errExit("selabel_open");
/* Open the file as O_PATH, to pin it while we determine and adjust the label
* Defeat symlink races by not allowing symbolic links */
int called_as_root = 0;
if (geteuid() == 0)
called_as_root = 1;
if (called_as_root)
EUID_USER();
fd = safer_openat(-1, path, O_NOFOLLOW|O_CLOEXEC|O_PATH);
if (called_as_root)
EUID_ROOT();
if (fd < 0)
return;
if (fstat(fd, &st) < 0)
goto close;
if (selabel_lookup_raw(label_hnd, &fcon, inside_path, st.st_mode) == 0) {
sprintf(procfs_path, "/proc/self/fd/%i", fd);
if (arg_debug)
printf("Relabeling %s as %s (%s)\n", path, inside_path, fcon);
if (!called_as_root)
EUID_ROOT();
if (setfilecon_raw(procfs_path, fcon) != 0 && arg_debug)
printf("Cannot relabel %s: %s\n", path, strerror(errno));
if (!called_as_root)
EUID_USER();
}
freecon(fcon);
close:
close(fd);
#else
(void) path;
(void) inside_path;
#endif
}
|