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/stat.h>
39 #include <sys/wait.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 
48 #include <selinux/selinux.h>           /* for is_selinux_enabled() */
49 #include <selinux/context.h>           /* for context-mangling functions */
50 #include <selinux/get_default_type.h>
51 #include <selinux/get_context_list.h>
52 
53 #ifdef HAVE_LINUX_AUDIT
54 # include <libaudit.h>
55 #endif
56 
57 #include "sudo.h"
58 #include "sudo_exec.h"
59 
60 static struct selinux_state {
61     char * old_context;
62     char * new_context;
63     char * tty_con_raw;
64     char * new_tty_con_raw;
65     const char *ttyn;
66     int ttyfd;
67     int enforcing;
68 } se_state;
69 
70 #ifdef HAVE_LINUX_AUDIT
71 static int
audit_role_change(const char * old_context,const char * new_context,const char * ttyn,int result)72 audit_role_change(const char * old_context,
73     const char * new_context, const char *ttyn, int result)
74 {
75     int au_fd, rc = -1;
76     char *message;
77     debug_decl(audit_role_change, SUDO_DEBUG_SELINUX);
78 
79     au_fd = audit_open();
80     if (au_fd == -1) {
81         /* Kernel may not have audit support. */
82         if (errno != EINVAL && errno != EPROTONOSUPPORT && errno != EAFNOSUPPORT
83 )
84             sudo_fatal("%s", U_("unable to open audit system"));
85     } else {
86 	/* audit role change using the same format as newrole(1) */
87 	rc = asprintf(&message, "newrole: old-context=%s new-context=%s",
88 	    old_context, new_context);
89 	if (rc == -1)
90 	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
91 	rc = audit_log_user_message(au_fd, AUDIT_USER_ROLE_CHANGE,
92 	    message, NULL, NULL, ttyn, result);
93 	if (rc <= 0)
94 	    sudo_warn("%s", U_("unable to send audit message"));
95 	free(message);
96 	close(au_fd);
97     }
98 
99     debug_return_int(rc);
100 }
101 #endif
102 
103 /*
104  * This function attempts to revert the relabeling done to the tty.
105  * fd		   - referencing the opened ttyn
106  * ttyn		   - name of tty to restore
107  *
108  * Returns 0 on success and -1 on failure.
109  */
110 int
selinux_restore_tty(void)111 selinux_restore_tty(void)
112 {
113     int ret = -1;
114     char * chk_tty_con_raw = NULL;
115     debug_decl(selinux_restore_tty, SUDO_DEBUG_SELINUX);
116 
117     if (se_state.ttyfd == -1 || se_state.new_tty_con_raw == NULL) {
118 	sudo_debug_printf(SUDO_DEBUG_INFO, "%s: no tty, skip relabel",
119 	    __func__);
120 	debug_return_int(0);
121     }
122 
123     sudo_debug_printf(SUDO_DEBUG_INFO, "%s: %s -> %s",
124 	__func__, se_state.new_tty_con_raw, se_state.tty_con_raw);
125 
126     /* Verify that the tty still has the context set by sudo. */
127     if (fgetfilecon_raw(se_state.ttyfd, &chk_tty_con_raw) == -1) {
128 	sudo_warn(U_("unable to fgetfilecon %s"), se_state.ttyn);
129 	goto skip_relabel;
130     }
131 
132     if (strcmp(chk_tty_con_raw, se_state.new_tty_con_raw) != 0) {
133 	sudo_warnx(U_("%s changed labels"), se_state.ttyn);
134 	sudo_debug_printf(SUDO_DEBUG_INFO,
135 	    "%s: not restoring tty label, expected %s, have %s",
136 	    __func__, se_state.new_tty_con_raw, chk_tty_con_raw);
137 	goto skip_relabel;
138     }
139 
140     if (fsetfilecon_raw(se_state.ttyfd, se_state.tty_con_raw) == -1) {
141 	sudo_warn(U_("unable to restore context for %s"), se_state.ttyn);
142 	goto skip_relabel;
143     }
144 
145     sudo_debug_printf(SUDO_DEBUG_INFO, "%s: successfully set tty label to %s",
146 	__func__, se_state.tty_con_raw);
147     ret = 0;
148 
149 skip_relabel:
150     if (se_state.ttyfd != -1) {
151 	close(se_state.ttyfd);
152 	se_state.ttyfd = -1;
153     }
154     freecon(chk_tty_con_raw);
155     debug_return_int(ret);
156 }
157 
158 /*
159  * This function attempts to relabel the tty. If this function fails, then
160  * the contexts are free'd and -1 is returned. On success, 0 is returned
161  * and tty_con_raw and new_tty_con_raw are set.
162  *
163  * This function will not fail if it can not relabel the tty when selinux is
164  * in permissive mode.
165  */
166 static int
relabel_tty(const char * ttyn,int ptyfd)167 relabel_tty(const char *ttyn, int ptyfd)
168 {
169     char * tty_con = NULL;
170     char * new_tty_con = NULL;
171     struct stat sb;
172     int fd;
173     debug_decl(relabel_tty, SUDO_DEBUG_SELINUX);
174 
175     se_state.ttyfd = ptyfd;
176 
177     /* It is perfectly legal to have no tty. */
178     if (ptyfd == -1 && ttyn == NULL) {
179 	sudo_debug_printf(SUDO_DEBUG_INFO, "%s: no tty, skip relabel",
180 	    __func__);
181 	debug_return_int(0);
182     }
183     sudo_debug_printf(SUDO_DEBUG_INFO, "%s: relabeling tty %s", __func__, ttyn);
184 
185     /* If sudo is not allocating a pty for the command, open current tty. */
186     if (ptyfd == -1) {
187 	se_state.ttyfd = open(ttyn, O_RDWR|O_NOCTTY|O_NONBLOCK);
188 	if (se_state.ttyfd == -1 || fstat(se_state.ttyfd, &sb) == -1) {
189 	    sudo_warn(U_("unable to open %s, not relabeling tty"), ttyn);
190 	    goto bad;
191 	}
192 	if (!S_ISCHR(sb.st_mode)) {
193 	    sudo_warn(U_("%s is not a character device, not relabeling tty"),
194 		ttyn);
195 	    goto bad;
196 	}
197 	(void)fcntl(se_state.ttyfd, F_SETFL,
198 	    fcntl(se_state.ttyfd, F_GETFL, 0) & ~O_NONBLOCK);
199     }
200 
201     if (fgetfilecon(se_state.ttyfd, &tty_con) == -1) {
202 	sudo_warn("%s", U_("unable to get current tty context, not relabeling tty"));
203 	goto bad;
204     }
205 
206     if (tty_con != NULL) {
207 	security_class_t tclass = string_to_security_class("chr_file");
208 	if (tclass == 0) {
209 	    sudo_warn("%s", U_("unknown security class \"chr_file\", not relabeling tty"));
210 	    goto bad;
211 	}
212 	if (security_compute_relabel(se_state.new_context, tty_con,
213 	    tclass, &new_tty_con) == -1) {
214 	    sudo_warn("%s", U_("unable to get new tty context, not relabeling tty"));
215 	    goto bad;
216 	}
217     }
218 
219     if (new_tty_con != NULL) {
220 	sudo_debug_printf(SUDO_DEBUG_INFO, "%s: tty context %s -> %s",
221 	    __func__, tty_con, new_tty_con);
222 	if (fsetfilecon(se_state.ttyfd, new_tty_con) == -1) {
223 	    sudo_warn("%s", U_("unable to set new tty context"));
224 	    goto bad;
225 	}
226     }
227 
228     if (ptyfd != -1) {
229 	int oflags, flags = 0;
230 
231 	/* Reopen pty that was relabeled, std{in,out,err} are reset later. */
232 	se_state.ttyfd = open(ttyn, O_RDWR|O_NOCTTY, 0);
233 	if (se_state.ttyfd == -1 || fstat(se_state.ttyfd, &sb) == -1) {
234 	    sudo_warn(U_("unable to open %s"), ttyn);
235 	    goto bad;
236 	}
237 	if (!S_ISCHR(sb.st_mode)) {
238 	    sudo_warn(U_("%s is not a character device, not relabeling tty"),
239 		ttyn);
240 	    goto bad;
241 	}
242 	/* Preserve O_NONBLOCK and the close-on-exec flags. */
243 	if ((oflags = fcntl(ptyfd, F_GETFL)) == -1) {
244 	    sudo_warn("F_GETFL");
245 	    goto bad;
246 	}
247 	if (ISSET(oflags, O_NONBLOCK))
248 	    flags |= O_NONBLOCK;
249 	if ((oflags = fcntl(ptyfd, F_GETFD)) == -1) {
250 	    sudo_warn("F_GETFD");
251 	    goto bad;
252 	}
253 	if (ISSET(oflags, FD_CLOEXEC))
254 	    flags |= O_CLOEXEC;
255 	if (dup3(se_state.ttyfd, ptyfd, flags) == -1) {
256 	    sudo_warn("dup3");
257 	    goto bad;
258 	}
259     } else {
260 	/* Re-open tty to get new label and reset std{in,out,err} */
261 	close(se_state.ttyfd);
262 	se_state.ttyfd = open(ttyn, O_RDWR|O_NOCTTY|O_NONBLOCK);
263 	if (se_state.ttyfd == -1 || fstat(se_state.ttyfd, &sb) == -1) {
264 	    sudo_warn(U_("unable to open %s"), ttyn);
265 	    goto bad;
266 	}
267 	if (!S_ISCHR(sb.st_mode)) {
268 	    sudo_warn(U_("%s is not a character device, not relabeling tty"),
269 		ttyn);
270 	    goto bad;
271 	}
272 	(void)fcntl(se_state.ttyfd, F_SETFL,
273 	    fcntl(se_state.ttyfd, F_GETFL, 0) & ~O_NONBLOCK);
274 	for (fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
275 	    if (isatty(fd) && dup2(se_state.ttyfd, fd) == -1) {
276 		sudo_warn("dup2");
277 		goto bad;
278 	    }
279 	}
280     }
281     /* Retain se_state.ttyfd so we can restore label when command finishes. */
282     (void)fcntl(se_state.ttyfd, F_SETFD, FD_CLOEXEC);
283 
284     se_state.ttyn = ttyn;
285     if (selinux_trans_to_raw_context(tty_con, &se_state.tty_con_raw) == -1)
286 	goto bad;
287     if (selinux_trans_to_raw_context(new_tty_con, &se_state.new_tty_con_raw) == -1)
288 	goto bad;
289     freecon(tty_con);
290     freecon(new_tty_con);
291     debug_return_int(0);
292 
293 bad:
294     if (se_state.ttyfd != -1 && se_state.ttyfd != ptyfd) {
295 	close(se_state.ttyfd);
296 	se_state.ttyfd = -1;
297     }
298     freecon(se_state.tty_con_raw);
299     se_state.tty_con_raw = NULL;
300     freecon(se_state.new_tty_con_raw);
301     se_state.new_tty_con_raw = NULL;
302     freecon(tty_con);
303     freecon(new_tty_con);
304     debug_return_int(se_state.enforcing ? -1 : 0);
305 }
306 
307 /*
308  * Returns a new security context based on the old context and the
309  * specified role and type.
310  */
311 char *
get_exec_context(char * old_context,const char * role,const char * type)312 get_exec_context(char * old_context, const char *role, const char *type)
313 {
314     char * new_context = NULL;
315     context_t context = NULL;
316     char *typebuf = NULL;
317     debug_decl(get_exec_context, SUDO_DEBUG_SELINUX);
318 
319     /* We must have a role, the type is optional (we can use the default). */
320     if (role == NULL) {
321 	sudo_warnx(U_("you must specify a role for type %s"), type);
322 	errno = EINVAL;
323 	goto bad;
324     }
325     if (type == NULL) {
326 	if (get_default_type(role, &typebuf)) {
327 	    sudo_warnx(U_("unable to get default type for role %s"), role);
328 	    errno = EINVAL;
329 	    goto bad;
330 	}
331 	type = typebuf;
332     }
333 
334     /*
335      * Expand old_context into a context_t so that we can extract and modify
336      * its components easily.
337      */
338     if ((context = context_new(old_context)) == NULL) {
339 	sudo_warn("%s", U_("failed to get new context"));
340 	goto bad;
341     }
342 
343     /*
344      * Replace the role and type in "context" with the role and
345      * type we will be running the command as.
346      */
347     if (context_role_set(context, role)) {
348 	sudo_warn(U_("failed to set new role %s"), role);
349 	goto bad;
350     }
351     if (context_type_set(context, type)) {
352 	sudo_warn(U_("failed to set new type %s"), type);
353 	goto bad;
354     }
355 
356     /*
357      * Convert "context" back into a string and verify it.
358      */
359     if ((new_context = strdup(context_str(context))) == NULL) {
360 	sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
361 	goto bad;
362     }
363     if (security_check_context(new_context) == -1) {
364 	sudo_warnx(U_("%s is not a valid context"), new_context);
365 	errno = EINVAL;
366 	goto bad;
367     }
368 
369     context_free(context);
370     debug_return_str(new_context);
371 
372 bad:
373     free(typebuf);
374     context_free(context);
375     freecon(new_context);
376     debug_return_str(NULL);
377 }
378 
379 /*
380  * Determine the exec and tty contexts in preparation for fork/exec.
381  * Must run as root, before forking the child process.
382  * Sets the tty context but not the exec context (which happens later).
383  * If ptyfd is not -1, it indicates we are running
384  * in a pty and do not need to reset std{in,out,err}.
385  * Returns 0 on success and -1 on failure.
386  */
387 int
selinux_setup(const char * role,const char * type,const char * ttyn,int ptyfd,bool label_tty)388 selinux_setup(const char *role, const char *type, const char *ttyn,
389     int ptyfd, bool label_tty)
390 {
391     int ret = -1;
392     debug_decl(selinux_setup, SUDO_DEBUG_SELINUX);
393 
394     /* Store the caller's SID in old_context. */
395     if (getprevcon(&se_state.old_context)) {
396 	sudo_warn("%s", U_("failed to get old context"));
397 	goto done;
398     }
399 
400     se_state.enforcing = security_getenforce();
401     if (se_state.enforcing == -1) {
402 	sudo_warn("%s", U_("unable to determine enforcing mode."));
403 	goto done;
404     }
405 
406     sudo_debug_printf(SUDO_DEBUG_INFO, "%s: old context %s", __func__,
407 	se_state.old_context);
408     se_state.new_context = get_exec_context(se_state.old_context, role, type);
409     if (se_state.new_context == NULL) {
410 #ifdef HAVE_LINUX_AUDIT
411 	audit_role_change(se_state.old_context, "?", se_state.ttyn, 0);
412 #endif
413 	goto done;
414     }
415     sudo_debug_printf(SUDO_DEBUG_INFO, "%s: new context %s", __func__,
416 	se_state.new_context);
417 
418     if (label_tty && relabel_tty(ttyn, ptyfd) == -1) {
419 	sudo_warn(U_("unable to set tty context to %s"), se_state.new_context);
420 	goto done;
421     }
422 
423 #ifdef HAVE_LINUX_AUDIT
424     audit_role_change(se_state.old_context, se_state.new_context,
425 	se_state.ttyn, 1);
426 #endif
427 
428     ret = 0;
429 
430 done:
431     debug_return_int(ret);
432 }
433 
434 int
selinux_setcon(void)435 selinux_setcon(void)
436 {
437     debug_decl(selinux_setcon, SUDO_DEBUG_SELINUX);
438 
439     if (setexeccon(se_state.new_context)) {
440 	sudo_warn(U_("unable to set exec context to %s"), se_state.new_context);
441 	if (se_state.enforcing)
442 	    debug_return_int(-1);
443     }
444 
445 #ifdef HAVE_SETKEYCREATECON
446     if (setkeycreatecon(se_state.new_context)) {
447 	sudo_warn(U_("unable to set key creation context to %s"), se_state.new_context);
448 	if (se_state.enforcing)
449 	    debug_return_int(-1);
450     }
451 #endif /* HAVE_SETKEYCREATECON */
452 
453     debug_return_int(0);
454 }
455 
456 void
selinux_execve(int fd,const char * path,char * const argv[],char * envp[],bool noexec)457 selinux_execve(int fd, const char *path, char *const argv[], char *envp[],
458     bool noexec)
459 {
460     char **nargv;
461     const char *sesh;
462     int argc, nargc, serrno;
463     debug_decl(selinux_execve, SUDO_DEBUG_SELINUX);
464 
465     sesh = sudo_conf_sesh_path();
466     if (sesh == NULL) {
467 	sudo_warnx("internal error: sesh path not set");
468 	errno = EINVAL;
469 	debug_return;
470     }
471 
472     /* Set SELinux exec and keycreate contexts. */
473     if (selinux_setcon() == -1)
474 	debug_return;
475 
476     /*
477      * Build new argv with sesh as argv[0].
478      * If argv[0] ends in -noexec, sesh will disable execute
479      * for the command it runs.
480      */
481     for (argc = 0; argv[argc] != NULL; argc++)
482 	continue;
483     if (argc == 0) {
484 	errno = EINVAL;
485 	debug_return;
486     }
487     nargv = reallocarray(NULL, argc + 3, sizeof(char *));
488     if (nargv == NULL) {
489 	sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
490 	debug_return;
491     }
492     if (noexec)
493 	nargv[0] = *argv[0] == '-' ? "-sesh-noexec" : "sesh-noexec";
494     else
495 	nargv[0] = *argv[0] == '-' ? "-sesh" : "sesh";
496     nargc = 1;
497     if (fd != -1 && asprintf(&nargv[nargc++], "--execfd=%d", fd) == -1) {
498 	sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
499 	debug_return;
500     }
501     nargv[nargc++] = (char *)path;
502     memcpy(&nargv[nargc], &argv[1], argc * sizeof(char *)); /* copies NULL */
503 
504     /* sesh will handle noexec for us. */
505     sudo_execve(-1, sesh, nargv, envp, -1, 0);
506     serrno = errno;
507     free(nargv);
508     errno = serrno;
509     debug_return;
510 }
511 
512 #endif /* HAVE_SELINUX */
513