]> granicus.if.org Git - sudo/blob - src/selinux.c
Add SPDX-License-Identifier to files.
[sudo] / src / selinux.c
1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 2009-2016 Todd C. Miller <Todd.Miller@sudo.ws>
5  * Copyright (c) 2008 Dan Walsh <dwalsh@redhat.com>
6  *
7  * Borrowed heavily from newrole source code
8  * Authors:
9  *      Anthony Colatrella
10  *      Tim Fraser
11  *      Steve Grubb <sgrubb@redhat.com>
12  *      Darrel Goeddel <DGoeddel@trustedcs.com>
13  *      Michael Thompson <mcthomps@us.ibm.com>
14  *      Dan Walsh <dwalsh@redhat.com>
15  *
16  * Permission to use, copy, modify, and distribute this software for any
17  * purpose with or without fee is hereby granted, provided that the above
18  * copyright notice and this permission notice appear in all copies.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
21  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
22  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
23  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
25  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
26  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27  */
28
29 /*
30  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
31  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
32  */
33
34 #include <config.h>
35
36 #ifdef HAVE_SELINUX
37
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/wait.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <signal.h>
48
49 #include <selinux/selinux.h>           /* for is_selinux_enabled() */
50 #include <selinux/context.h>           /* for context-mangling functions */
51 #include <selinux/get_default_type.h>
52 #include <selinux/get_context_list.h>
53
54 #ifdef HAVE_LINUX_AUDIT
55 # include <libaudit.h>
56 #endif
57
58 #include "sudo.h"
59 #include "sudo_exec.h"
60
61 static struct selinux_state {
62     security_context_t old_context;
63     security_context_t new_context;
64     security_context_t tty_context;
65     security_context_t new_tty_context;
66     const char *ttyn;
67     int ttyfd;
68     int enforcing;
69 } se_state;
70
71 #ifdef HAVE_LINUX_AUDIT
72 static int
73 audit_role_change(const security_context_t old_context,
74     const security_context_t new_context, const char *ttyn, int result)
75 {
76     int au_fd, rc = -1;
77     char *message;
78     debug_decl(audit_role_change, SUDO_DEBUG_SELINUX)
79
80     au_fd = audit_open();
81     if (au_fd == -1) {
82         /* Kernel may not have audit support. */
83         if (errno != EINVAL && errno != EPROTONOSUPPORT && errno != EAFNOSUPPORT
84 )
85             sudo_fatal(U_("unable to open audit system"));
86     } else {
87         /* audit role change using the same format as newrole(1) */
88         rc = asprintf(&message, "newrole: old-context=%s new-context=%s",
89             old_context, new_context);
90         if (rc == -1)
91             sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
92         rc = audit_log_user_message(au_fd, AUDIT_USER_ROLE_CHANGE,
93             message, NULL, NULL, ttyn, result);
94         if (rc <= 0)
95             sudo_warn(U_("unable to send audit message"));
96         free(message);
97         close(au_fd);
98     }
99
100     debug_return_int(rc);
101 }
102 #endif
103
104 /*
105  * This function attempts to revert the relabeling done to the tty.
106  * fd              - referencing the opened ttyn
107  * ttyn            - name of tty to restore
108  *
109  * Returns zero on success, non-zero otherwise
110  */
111 int
112 selinux_restore_tty(void)
113 {
114     int retval = 0;
115     security_context_t chk_tty_context = NULL;
116     debug_decl(selinux_restore_tty, SUDO_DEBUG_SELINUX)
117
118     if (se_state.ttyfd == -1 || se_state.new_tty_context == NULL)
119         goto skip_relabel;
120
121     /* Verify that the tty still has the context set by sudo. */
122     if ((retval = fgetfilecon(se_state.ttyfd, &chk_tty_context)) < 0) {
123         sudo_warn(U_("unable to fgetfilecon %s"), se_state.ttyn);
124         goto skip_relabel;
125     }
126
127     if ((retval = strcmp(chk_tty_context, se_state.new_tty_context))) {
128         sudo_warnx(U_("%s changed labels"), se_state.ttyn);
129         goto skip_relabel;
130     }
131
132     if ((retval = fsetfilecon(se_state.ttyfd, se_state.tty_context)) < 0)
133         sudo_warn(U_("unable to restore context for %s"), se_state.ttyn);
134
135 skip_relabel:
136     if (se_state.ttyfd != -1) {
137         close(se_state.ttyfd);
138         se_state.ttyfd = -1;
139     }
140     if (chk_tty_context != NULL) {
141         freecon(chk_tty_context);
142         chk_tty_context = NULL;
143     }
144     debug_return_int(retval);
145 }
146
147 /*
148  * This function attempts to relabel the tty. If this function fails, then
149  * the contexts are free'd and -1 is returned. On success, 0 is returned
150  * and tty_context and new_tty_context are set.
151  *
152  * This function will not fail if it can not relabel the tty when selinux is
153  * in permissive mode.
154  */
155 static int
156 relabel_tty(const char *ttyn, int ptyfd)
157 {
158     security_context_t tty_con = NULL;
159     security_context_t new_tty_con = NULL;
160     struct stat sb;
161     int fd;
162     debug_decl(relabel_tty, SUDO_DEBUG_SELINUX)
163
164     se_state.ttyfd = ptyfd;
165
166     /* It is perfectly legal to have no tty. */
167     if (ptyfd == -1 && ttyn == NULL)
168         debug_return_int(0);
169
170     /* If sudo is not allocating a pty for the command, open current tty. */
171     if (ptyfd == -1) {
172         se_state.ttyfd = open(ttyn, O_RDWR|O_NOCTTY|O_NONBLOCK);
173         if (se_state.ttyfd == -1 || fstat(se_state.ttyfd, &sb) == -1) {
174             sudo_warn(U_("unable to open %s, not relabeling tty"), ttyn);
175             goto bad;
176         }
177         if (!S_ISCHR(sb.st_mode)) {
178             sudo_warn(U_("%s is not a character device, not relabeling tty"),
179                 ttyn);
180             goto bad;
181         }
182         (void)fcntl(se_state.ttyfd, F_SETFL,
183             fcntl(se_state.ttyfd, F_GETFL, 0) & ~O_NONBLOCK);
184     }
185
186     if (fgetfilecon(se_state.ttyfd, &tty_con) < 0) {
187         sudo_warn(U_("unable to get current tty context, not relabeling tty"));
188         goto bad;
189     }
190
191     if (tty_con) {
192         security_class_t tclass = string_to_security_class("chr_file");
193         if (tclass == 0) {
194             sudo_warn(U_("unknown security class \"chr_file\", not relabeling tty"));
195             goto bad;
196         }
197         if (security_compute_relabel(se_state.new_context, tty_con,
198             tclass, &new_tty_con) < 0) {
199             sudo_warn(U_("unable to get new tty context, not relabeling tty"));
200             goto bad;
201         }
202     }
203
204     if (new_tty_con != NULL) {
205         if (fsetfilecon(se_state.ttyfd, new_tty_con) < 0) {
206             sudo_warn(U_("unable to set new tty context"));
207             goto bad;
208         }
209     }
210
211     if (ptyfd != -1) {
212         /* Reopen pty that was relabeled, std{in,out,err} are reset later. */
213         se_state.ttyfd = open(ttyn, O_RDWR|O_NOCTTY, 0);
214         if (se_state.ttyfd == -1 || fstat(se_state.ttyfd, &sb) == -1) {
215             sudo_warn(U_("unable to open %s"), ttyn);
216             goto bad;
217         }
218         if (!S_ISCHR(sb.st_mode)) {
219             sudo_warn(U_("%s is not a character device, not relabeling tty"),
220                 ttyn);
221             goto bad;
222         }
223         if (dup2(se_state.ttyfd, ptyfd) == -1) {
224             sudo_warn("dup2");
225             goto bad;
226         }
227     } else {
228         /* Re-open tty to get new label and reset std{in,out,err} */
229         close(se_state.ttyfd);
230         se_state.ttyfd = open(ttyn, O_RDWR|O_NOCTTY|O_NONBLOCK);
231         if (se_state.ttyfd == -1 || fstat(se_state.ttyfd, &sb) == -1) {
232             sudo_warn(U_("unable to open %s"), ttyn);
233             goto bad;
234         }
235         if (!S_ISCHR(sb.st_mode)) {
236             sudo_warn(U_("%s is not a character device, not relabeling tty"),
237                 ttyn);
238             goto bad;
239         }
240         (void)fcntl(se_state.ttyfd, F_SETFL,
241             fcntl(se_state.ttyfd, F_GETFL, 0) & ~O_NONBLOCK);
242         for (fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
243             if (isatty(fd) && dup2(se_state.ttyfd, fd) == -1) {
244                 sudo_warn("dup2");
245                 goto bad;
246             }
247         }
248     }
249     /* Retain se_state.ttyfd so we can restore label when command finishes. */
250     (void)fcntl(se_state.ttyfd, F_SETFD, FD_CLOEXEC);
251
252     se_state.ttyn = ttyn;
253     se_state.tty_context = tty_con;
254     se_state.new_tty_context = new_tty_con;
255     debug_return_int(0);
256
257 bad:
258     if (se_state.ttyfd != -1 && se_state.ttyfd != ptyfd) {
259         close(se_state.ttyfd);
260         se_state.ttyfd = -1;
261     }
262     freecon(tty_con);
263     debug_return_int(se_state.enforcing ? -1 : 0);
264 }
265
266 /*
267  * Returns a new security context based on the old context and the
268  * specified role and type.
269  */
270 security_context_t
271 get_exec_context(security_context_t old_context, const char *role, const char *type)
272 {
273     security_context_t new_context = NULL;
274     context_t context = NULL;
275     char *typebuf = NULL;
276     debug_decl(get_exec_context, SUDO_DEBUG_SELINUX)
277     
278     /* We must have a role, the type is optional (we can use the default). */
279     if (!role) {
280         sudo_warnx(U_("you must specify a role for type %s"), type);
281         errno = EINVAL;
282         goto bad;
283     }
284     if (!type) {
285         if (get_default_type(role, &typebuf)) {
286             sudo_warnx(U_("unable to get default type for role %s"), role);
287             errno = EINVAL;
288             goto bad;
289         }
290         type = typebuf;
291     }
292     
293     /* 
294      * Expand old_context into a context_t so that we extract and modify 
295      * its components easily. 
296      */
297     context = context_new(old_context);
298     
299     /*
300      * Replace the role and type in "context" with the role and
301      * type we will be running the command as.
302      */
303     if (context_role_set(context, role)) {
304         sudo_warn(U_("failed to set new role %s"), role);
305         goto bad;
306     }
307     if (context_type_set(context, type)) {
308         sudo_warn(U_("failed to set new type %s"), type);
309         goto bad;
310     }
311       
312     /*
313      * Convert "context" back into a string and verify it.
314      */
315     if ((new_context = strdup(context_str(context))) == NULL) {
316         sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
317         goto bad;
318     }
319     if (security_check_context(new_context) < 0) {
320         sudo_warnx(U_("%s is not a valid context"), new_context);
321         errno = EINVAL;
322         goto bad;
323     }
324
325 #ifdef DEBUG
326     sudo_warnx("Your new context is %s", new_context);
327 #endif
328
329     context_free(context);
330     debug_return_ptr(new_context);
331
332 bad:
333     free(typebuf);
334     context_free(context);
335     freecon(new_context);
336     debug_return_ptr(NULL);
337 }
338
339 /* 
340  * Set the exec and tty contexts in preparation for fork/exec.
341  * Must run as root, before the uid change.
342  * If ptyfd is not -1, it indicates we are running
343  * in a pty and do not need to reset std{in,out,err}.
344  * Returns 0 on success and -1 on failure.
345  */
346 int
347 selinux_setup(const char *role, const char *type, const char *ttyn,
348     int ptyfd)
349 {
350     int ret = -1;
351     debug_decl(selinux_setup, SUDO_DEBUG_SELINUX)
352
353     /* Store the caller's SID in old_context. */
354     if (getprevcon(&se_state.old_context)) {
355         sudo_warn(U_("failed to get old_context"));
356         goto done;
357     }
358
359     se_state.enforcing = security_getenforce();
360     if (se_state.enforcing < 0) {
361         sudo_warn(U_("unable to determine enforcing mode."));
362         goto done;
363     }
364
365 #ifdef DEBUG
366     sudo_warnx("your old context was %s", se_state.old_context);
367 #endif
368     se_state.new_context = get_exec_context(se_state.old_context, role, type);
369     if (!se_state.new_context) {
370 #ifdef HAVE_LINUX_AUDIT
371         audit_role_change(se_state.old_context, "?",
372           se_state.ttyn, 0);
373 #endif
374         goto done;
375     }
376     
377     if (relabel_tty(ttyn, ptyfd) < 0) {
378         sudo_warn(U_("unable to set tty context to %s"), se_state.new_context);
379         goto done;
380     }
381
382 #ifdef DEBUG
383     if (se_state.ttyfd != -1) {
384         sudo_warnx("your old tty context is %s", se_state.tty_context);
385         sudo_warnx("your new tty context is %s", se_state.new_tty_context);
386     }
387 #endif
388
389 #ifdef HAVE_LINUX_AUDIT
390     audit_role_change(se_state.old_context, se_state.new_context,
391         se_state.ttyn, 1);
392 #endif
393
394     ret = 0;
395
396 done:
397     debug_return_int(ret);
398 }
399
400 void
401 selinux_execve(int fd, const char *path, char *const argv[], char *envp[],
402     bool noexec)
403 {
404     char **nargv;
405     const char *sesh;
406     int argc, nargc, serrno;
407     debug_decl(selinux_execve, SUDO_DEBUG_SELINUX)
408
409     sesh = sudo_conf_sesh_path();
410     if (sesh == NULL) {
411         sudo_warnx("internal error: sesh path not set");
412         errno = EINVAL;
413         debug_return;
414     }
415
416     if (setexeccon(se_state.new_context)) {
417         sudo_warn(U_("unable to set exec context to %s"), se_state.new_context);
418         if (se_state.enforcing)
419             debug_return;
420     }
421
422 #ifdef HAVE_SETKEYCREATECON
423     if (setkeycreatecon(se_state.new_context)) {
424         sudo_warn(U_("unable to set key creation context to %s"), se_state.new_context);
425         if (se_state.enforcing)
426             debug_return;
427     }
428 #endif /* HAVE_SETKEYCREATECON */
429
430     /*
431      * Build new argv with sesh as argv[0].
432      * If argv[0] ends in -noexec, sesh will disable execute
433      * for the command it runs.
434      */
435     for (argc = 0; argv[argc] != NULL; argc++)
436         continue;
437     nargv = reallocarray(NULL, argc + 3, sizeof(char *));
438     if (nargv == NULL) {
439         sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
440         debug_return;
441     }
442     if (noexec)
443         nargv[0] = *argv[0] == '-' ? "-sesh-noexec" : "sesh-noexec";
444     else
445         nargv[0] = *argv[0] == '-' ? "-sesh" : "sesh";
446     nargc = 1;
447     if (fd != -1 && asprintf(&nargv[nargc++], "--execfd=%d", fd) == -1) {
448         sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
449         debug_return;
450     }
451     nargv[nargc++] = (char *)path;
452     memcpy(&nargv[nargc], &argv[1], argc * sizeof(char *)); /* copies NULL */
453
454     /* sesh will handle noexec for us. */
455     sudo_execve(-1, sesh, nargv, envp, false);
456     serrno = errno;
457     free(nargv);
458     errno = serrno;
459     debug_return;
460 }
461
462 #endif /* HAVE_SELINUX */