Home | History | Annotate | Line # | Download | only in su
su_pam.c revision 1.18
      1 /*	$NetBSD: su_pam.c,v 1.18 2013/06/20 20:54:02 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1988\
     35  The Regents of the University of California.  All rights reserved.");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)su.c	8.3 (Berkeley) 4/2/94";*/
     41 #else
     42 __RCSID("$NetBSD: su_pam.c,v 1.18 2013/06/20 20:54:02 christos Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/time.h>
     48 #include <sys/resource.h>
     49 #include <sys/wait.h>
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <grp.h>
     53 #include <paths.h>
     54 #include <pwd.h>
     55 #include <signal.h>
     56 #include <stdio.h>
     57 #include <stdlib.h>
     58 #include <string.h>
     59 #include <syslog.h>
     60 #include <time.h>
     61 #include <tzfile.h>
     62 #include <unistd.h>
     63 #include <util.h>
     64 #include <login_cap.h>
     65 
     66 #include <security/pam_appl.h>
     67 #include <security/openpam.h>   /* for openpam_ttyconv() */
     68 
     69 #ifdef ALLOW_GROUP_CHANGE
     70 #include "grutil.h"
     71 #endif
     72 #include "suutil.h"
     73 
     74 static const struct pam_conv pamc = { &openpam_ttyconv, NULL };
     75 
     76 #define	ARGSTRX	"-dflm"
     77 
     78 #ifdef LOGIN_CAP
     79 #define ARGSTR	ARGSTRX "c:"
     80 #else
     81 #define ARGSTR ARGSTRX
     82 #endif
     83 
     84 static void logit(const char *, ...) __printflike(1, 2);
     85 
     86 static const char *
     87 safe_pam_strerror(pam_handle_t *pamh, int pam_err) {
     88 	const char *msg;
     89 
     90 	if ((msg = pam_strerror(pamh, pam_err)) != NULL)
     91 		return msg;
     92 
     93 	static char buf[1024];
     94 	snprintf(buf, sizeof(buf), "Unknown pam error %d", pam_err);
     95 	return buf;
     96 }
     97 
     98 int
     99 main(int argc, char **argv)
    100 {
    101 	extern char **environ;
    102 	struct passwd *pwd, pwres;
    103 	char *p;
    104 	uid_t ruid;
    105 	int asme, ch, asthem, fastlogin, prio, gohome;
    106 	u_int setwhat;
    107 	enum { UNSET, YES, NO } iscsh = UNSET;
    108 	const char *user, *shell, *avshell;
    109 	char *username, *class;
    110 	char **np;
    111 	char shellbuf[MAXPATHLEN], avshellbuf[MAXPATHLEN];
    112 	int pam_err;
    113 	char hostname[MAXHOSTNAMELEN];
    114 	char *tty;
    115 	const char *func;
    116 	const void *newuser;
    117 	login_cap_t *lc;
    118 	pam_handle_t *pamh = NULL;
    119 	char pwbuf[1024];
    120 #ifdef PAM_DEBUG
    121 	extern int _openpam_debug;
    122 
    123 	_openpam_debug = 1;
    124 #endif
    125 #ifdef ALLOW_GROUP_CHANGE
    126 	char *gname;
    127 #endif
    128 
    129 	(void)setprogname(argv[0]);
    130 	asme = asthem = fastlogin = 0;
    131 	gohome = 1;
    132 	shell = class = NULL;
    133 	while ((ch = getopt(argc, argv, ARGSTR)) != -1)
    134 		switch((char)ch) {
    135 		case 'c':
    136 			class = optarg;
    137 			break;
    138 		case 'd':
    139 			asme = 0;
    140 			asthem = 1;
    141 			gohome = 0;
    142 			break;
    143 		case 'f':
    144 			fastlogin = 1;
    145 			break;
    146 		case '-':
    147 		case 'l':
    148 			asme = 0;
    149 			asthem = 1;
    150 			break;
    151 		case 'm':
    152 			asme = 1;
    153 			asthem = 0;
    154 			break;
    155 		case '?':
    156 		default:
    157 			(void)fprintf(stderr,
    158 #ifdef ALLOW_GROUP_CHANGE
    159 			    "Usage: %s [%s] [login[:group] [shell arguments]]\n",
    160 #else
    161 			    "Usage: %s [%s] [login [shell arguments]]\n",
    162 #endif
    163 			    getprogname(), ARGSTR);
    164 			exit(EXIT_FAILURE);
    165 		}
    166 	argv += optind;
    167 
    168 	/* Lower the priority so su runs faster */
    169 	errno = 0;
    170 	prio = getpriority(PRIO_PROCESS, 0);
    171 	if (errno)
    172 		prio = 0;
    173 	if (prio > -2)
    174 		(void)setpriority(PRIO_PROCESS, 0, -2);
    175 	openlog("su", 0, LOG_AUTH);
    176 
    177 	/* get current login name and shell */
    178 	ruid = getuid();
    179 	username = getlogin();
    180 	if (username == NULL ||
    181 	    getpwnam_r(username, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    182 	    pwd == NULL || pwd->pw_uid != ruid) {
    183 		if (getpwuid_r(ruid, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0)
    184 			pwd = NULL;
    185 	}
    186 	if (pwd == NULL)
    187 		errx(EXIT_FAILURE, "who are you?");
    188 	username = estrdup(pwd->pw_name);
    189 
    190 	if (asme) {
    191 		if (pwd->pw_shell && *pwd->pw_shell) {
    192 			(void)estrlcpy(shellbuf, pwd->pw_shell, sizeof(shellbuf));
    193 			shell = shellbuf;
    194 		} else {
    195 			shell = _PATH_BSHELL;
    196 			iscsh = NO;
    197 		}
    198 	}
    199 	/* get target login information, default to root */
    200 	user = *argv ? *argv : "root";
    201 	np = *argv ? argv : argv - 1;
    202 
    203 #ifdef ALLOW_GROUP_CHANGE
    204 	if ((p = strchr(user, ':')) != NULL) {
    205 		*p = '\0';
    206 		gname = ++p;
    207 	}
    208 	else
    209 		gname = NULL;
    210 
    211 #ifdef ALLOW_EMPTY_USER
    212 	if (user[0] == '\0')
    213 		user = username;
    214 #endif
    215 #endif
    216 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    217 	    pwd == NULL)
    218 		errx(EXIT_FAILURE, "unknown login %s", user);
    219 
    220 	/*
    221 	 * PAM initialization
    222 	 */
    223 #define PAM_END(msg) do { func = msg; goto done;} /* NOTREACHED */ while (/*CONSTCOND*/0)
    224 
    225 	if ((pam_err = pam_start("su", user, &pamc, &pamh)) != PAM_SUCCESS) {
    226 		if (pamh != NULL)
    227 			PAM_END("pam_start");
    228 		/* Things went really bad... */
    229 		syslog(LOG_ERR, "pam_start failed: %s",
    230 		    safe_pam_strerror(pamh, pam_err));
    231 		errx(EXIT_FAILURE, "pam_start failed");
    232 	}
    233 
    234 #define PAM_END_ITEM(item)	PAM_END("pam_set_item(" # item ")")
    235 #define PAM_SET_ITEM(item, var) 					    \
    236 	if ((pam_err = pam_set_item(pamh, (item), (var))) != PAM_SUCCESS)   \
    237 		PAM_END_ITEM(item)
    238 
    239 	/*
    240 	 * Fill hostname, username and tty
    241 	 */
    242 	PAM_SET_ITEM(PAM_RUSER, username);
    243 	if (gethostname(hostname, sizeof(hostname)) != -1)
    244 		PAM_SET_ITEM(PAM_RHOST, hostname);
    245 
    246 	if ((tty = ttyname(STDERR_FILENO)) != NULL)
    247 		PAM_SET_ITEM(PAM_TTY, tty);
    248 
    249 	/*
    250 	 * Authentication
    251 	 */
    252 	if ((pam_err = pam_authenticate(pamh, 0)) != PAM_SUCCESS) {
    253 		syslog(LOG_WARNING, "BAD SU %s to %s%s: %s",
    254 		    username, user, ontty(), safe_pam_strerror(pamh, pam_err));
    255 		(void)pam_end(pamh, pam_err);
    256 		errx(EXIT_FAILURE, "Sorry: %s", safe_pam_strerror(pamh, pam_err));
    257 	}
    258 
    259 	/*
    260 	 * Authorization
    261 	 */
    262 	switch(pam_err = pam_acct_mgmt(pamh, 0)) {
    263 	case PAM_NEW_AUTHTOK_REQD:
    264 		pam_err = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
    265 		if (pam_err != PAM_SUCCESS)
    266 			PAM_END("pam_chauthok");
    267 		break;
    268 	case PAM_SUCCESS:
    269 		break;
    270 	default:
    271 		PAM_END("pam_acct_mgmt");
    272 		break;
    273 	}
    274 
    275 	/*
    276 	 * pam_authenticate might have changed the target user.
    277 	 * refresh pwd and user
    278 	 */
    279 	pam_err = pam_get_item(pamh, PAM_USER, &newuser);
    280 	if (pam_err != PAM_SUCCESS) {
    281 		syslog(LOG_WARNING,
    282 		    "pam_get_item(PAM_USER): %s", safe_pam_strerror(pamh, pam_err));
    283 	} else {
    284 		user = (char *)__UNCONST(newuser);
    285 		if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    286 		    pwd == NULL) {
    287 			(void)pam_end(pamh, pam_err);
    288 			syslog(LOG_ERR, "unknown login: %s", username);
    289 			errx(EXIT_FAILURE, "unknown login: %s", username);
    290 		}
    291 	}
    292 
    293 #define ERRX_PAM_END(args) do {			\
    294 	(void)pam_end(pamh, pam_err);		\
    295 	errx args;				\
    296 } while (/* CONSTCOND */0)
    297 
    298 #define ERR_PAM_END(args) do {			\
    299 	(void)pam_end(pamh, pam_err);		\
    300 	err args;				\
    301 } while (/* CONSTCOND */0)
    302 
    303 	/* force the usage of specified class */
    304 	if (class) {
    305 		if (ruid)
    306 			ERRX_PAM_END((EXIT_FAILURE, "Only root may use -c"));
    307 
    308 		pwd->pw_class = class;
    309 	}
    310 
    311 	if ((lc = login_getclass(pwd->pw_class)) == NULL)
    312 		ERRX_PAM_END((EXIT_FAILURE,
    313 		    "Unknown class %s\n", pwd->pw_class));
    314 
    315 	if (asme) {
    316 		/* if asme and non-standard target shell, must be root */
    317 		if (chshell(pwd->pw_shell) == 0 && ruid)
    318 			ERRX_PAM_END((EXIT_FAILURE,
    319 			    "permission denied (shell)."));
    320 	} else if (pwd->pw_shell && *pwd->pw_shell) {
    321 		shell = pwd->pw_shell;
    322 		iscsh = UNSET;
    323 	} else {
    324 		shell = _PATH_BSHELL;
    325 		iscsh = NO;
    326 	}
    327 
    328 	if ((p = strrchr(shell, '/')) != NULL)
    329 		avshell = p + 1;
    330 	else
    331 		avshell = shell;
    332 
    333 	/* if we're forking a csh, we want to slightly muck the args */
    334 	if (iscsh == UNSET)
    335 		iscsh = strstr(avshell, "csh") ? YES : NO;
    336 
    337 	/*
    338 	 * Initialize the supplemental groups before pam gets to them,
    339 	 * so that other pam modules get a chance to add more when
    340 	 * we do setcred. Note, we don't relinguish our set-userid yet
    341 	 */
    342 	/* if we aren't changing users, keep the current group members */
    343 	if (ruid != pwd->pw_uid &&
    344 	    setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) == -1)
    345 		ERR_PAM_END((EXIT_FAILURE, "setting user context"));
    346 
    347 #ifdef ALLOW_GROUP_CHANGE
    348 	addgroup(lc, gname, pwd, ruid, "Group Password:");
    349 #endif
    350 	if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS)
    351 		PAM_END("pam_setcred");
    352 
    353 	/*
    354 	 * Manage session.
    355 	 */
    356 	if (asthem) {
    357 		pid_t pid, xpid;
    358 		int status = 1;
    359 		struct sigaction sa, sa_int, sa_pipe, sa_quit;
    360 		int fds[2];
    361 
    362  		if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS)
    363 			PAM_END("pam_open_session");
    364 
    365 		/*
    366 		 * In order to call pam_close_session after the
    367 		 * command terminates, we need to fork.
    368 		 */
    369 		sa.sa_flags = SA_RESTART;
    370 		sa.sa_handler = SIG_IGN;
    371 		(void)sigemptyset(&sa.sa_mask);
    372 		(void)sigaction(SIGINT, &sa, &sa_int);
    373 		(void)sigaction(SIGQUIT, &sa, &sa_quit);
    374 		(void)sigaction(SIGPIPE, &sa, &sa_pipe);
    375 		sa.sa_handler = SIG_DFL;
    376 		(void)sigaction(SIGTSTP, &sa, NULL);
    377 		/*
    378 		 * Use a pipe to guarantee the order of execution of
    379 		 * the parent and the child.
    380 		 */
    381 		if (pipe(fds) == -1) {
    382 			warn("pipe failed");
    383 			goto out;
    384 		}
    385 
    386 		switch (pid = fork()) {
    387 		case -1:
    388 			logit("fork failed (%s)", strerror(errno));
    389 			goto out;
    390 
    391 		case 0:	/* Child */
    392 			(void)close(fds[1]);
    393 			(void)read(fds[0], &status, 1);
    394 			(void)close(fds[0]);
    395 			(void)sigaction(SIGINT, &sa_int, NULL);
    396 			(void)sigaction(SIGQUIT, &sa_quit, NULL);
    397 			(void)sigaction(SIGPIPE, &sa_pipe, NULL);
    398 			break;
    399 
    400 		default:
    401 			sa.sa_handler = SIG_IGN;
    402 			(void)sigaction(SIGTTOU, &sa, NULL);
    403 			(void)close(fds[0]);
    404 			(void)setpgid(pid, pid);
    405 			(void)tcsetpgrp(STDERR_FILENO, pid);
    406 			(void)close(fds[1]);
    407 			(void)sigaction(SIGPIPE, &sa_pipe, NULL);
    408 			/*
    409 			 * Parent: wait for the child to terminate
    410 			 * and call pam_close_session.
    411 			 */
    412 			while ((xpid = waitpid(pid, &status, WUNTRACED))
    413 			    == pid) {
    414 				if (WIFSTOPPED(status)) {
    415 					(void)kill(getpid(), SIGSTOP);
    416 					(void)tcsetpgrp(STDERR_FILENO,
    417 					    getpgid(pid));
    418 					(void)kill(pid, SIGCONT);
    419 					status = 1;
    420 					continue;
    421 				}
    422 				break;
    423 			}
    424 
    425 			(void)tcsetpgrp(STDERR_FILENO, getpgid(0));
    426 
    427 			if (xpid == -1) {
    428 			    logit("Error waiting for pid %d (%s)", pid,
    429 				strerror(errno));
    430 			} else if (xpid != pid) {
    431 			    /* Can't happen. */
    432 			    logit("Wrong PID: %d != %d", pid, xpid);
    433 			}
    434 out:
    435 			pam_err = pam_setcred(pamh, PAM_DELETE_CRED);
    436 			if (pam_err != PAM_SUCCESS)
    437 				logit("pam_setcred: %s",
    438 				    safe_pam_strerror(pamh, pam_err));
    439 			pam_err = pam_close_session(pamh, 0);
    440 			if (pam_err != PAM_SUCCESS)
    441 				logit("pam_close_session: %s",
    442 				    safe_pam_strerror(pamh, pam_err));
    443 			(void)pam_end(pamh, pam_err);
    444 			exit(WEXITSTATUS(status));
    445 			break;
    446 		}
    447 	}
    448 
    449 	/*
    450 	 * The child: starting here, we don't have to care about
    451 	 * handling PAM issues if we exit, the parent will do the
    452 	 * job when we exit.
    453 	 */
    454 #undef PAM_END
    455 #undef ERR_PAM_END
    456 #undef ERRX_PAM_END
    457 
    458 	if (!asme) {
    459 		if (asthem) {
    460 			char **pamenv;
    461 
    462 			p = getenv("TERM");
    463 			/*
    464 			 * Create an empty environment
    465 			 */
    466 			environ = emalloc(sizeof(char *));
    467 			environ[0] = NULL;
    468 
    469 			/*
    470 			 * Add PAM environement, before the LOGIN_CAP stuff:
    471 			 * if the login class is unspecified, we'll get the
    472 			 * same data from PAM, if -c was used, the specified
    473 			 * class must override PAM.
    474 	 		 */
    475 			if ((pamenv = pam_getenvlist(pamh)) != NULL) {
    476 				char **envitem;
    477 
    478 				/*
    479 				 * XXX Here FreeBSD filters out
    480 				 * SHELL, LOGNAME, MAIL, CDPATH, IFS, PATH
    481 				 * how could we get untrusted data here?
    482 				 */
    483 				for (envitem = pamenv; *envitem; envitem++) {
    484 					if (putenv(*envitem) == -1)
    485 						free(*envitem);
    486 				}
    487 
    488 				free(pamenv);
    489 			}
    490 
    491 			if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETPATH |
    492 				LOGIN_SETENV | LOGIN_SETUMASK) == -1)
    493 				err(EXIT_FAILURE, "setting user context");
    494 			if (p)
    495 				(void)setenv("TERM", p, 1);
    496 			if (gohome && chdir(pwd->pw_dir) == -1)
    497 				errx(EXIT_FAILURE, "no directory");
    498 		}
    499 
    500 		if (asthem || pwd->pw_uid) {
    501 			(void)setenv("LOGNAME", pwd->pw_name, 1);
    502 			(void)setenv("USER", pwd->pw_name, 1);
    503 		}
    504 		(void)setenv("HOME", pwd->pw_dir, 1);
    505 		(void)setenv("SHELL", shell, 1);
    506 	}
    507 	(void)setenv("SU_FROM", username, 1);
    508 
    509 	if (iscsh == YES) {
    510 		if (fastlogin)
    511 			*np-- = __UNCONST("-f");
    512 		if (asme)
    513 			*np-- = __UNCONST("-m");
    514 	} else {
    515 		if (fastlogin)
    516 			(void)unsetenv("ENV");
    517 	}
    518 
    519 	if (asthem) {
    520 		avshellbuf[0] = '-';
    521 		(void)estrlcpy(avshellbuf + 1, avshell, sizeof(avshellbuf) - 1);
    522 		avshell = avshellbuf;
    523 	} else if (iscsh == YES) {
    524 		/* csh strips the first character... */
    525 		avshellbuf[0] = '_';
    526 		(void)estrlcpy(avshellbuf + 1, avshell, sizeof(avshellbuf) - 1);
    527 		avshell = avshellbuf;
    528 	}
    529 	*np = __UNCONST(avshell);
    530 
    531 	if (ruid != 0)
    532 		syslog(LOG_NOTICE, "%s to %s%s",
    533 		    username, pwd->pw_name, ontty());
    534 
    535 	/* Raise our priority back to what we had before */
    536 	(void)setpriority(PRIO_PROCESS, 0, prio);
    537 
    538 	/*
    539 	 * Set user context, except for umask, and the stuff
    540 	 * we have done before.
    541 	 */
    542 	setwhat = LOGIN_SETALL & ~(LOGIN_SETENV | LOGIN_SETUMASK |
    543 	    LOGIN_SETLOGIN | LOGIN_SETPATH | LOGIN_SETGROUP);
    544 
    545 	/*
    546 	 * Don't touch resource/priority settings if -m has been used
    547 	 * or -l and -c hasn't, and we're not su'ing to root.
    548 	 */
    549 	if ((asme || (!asthem && class == NULL)) && pwd->pw_uid)
    550 		setwhat &= ~(LOGIN_SETPRIORITY | LOGIN_SETRESOURCES);
    551 
    552 	if (setusercontext(lc, pwd, pwd->pw_uid, setwhat) == -1)
    553 		err(EXIT_FAILURE, "setusercontext");
    554 
    555 	(void)execv(shell, np);
    556 	err(EXIT_FAILURE, "%s", shell);
    557 done:
    558 	logit("%s: %s", func, safe_pam_strerror(pamh, pam_err));
    559 	(void)pam_end(pamh, pam_err);
    560 	return EXIT_FAILURE;
    561 }
    562 
    563 static void
    564 logit(const char *fmt, ...)
    565 {
    566 	va_list ap;
    567 
    568 	va_start(ap, fmt);
    569 	vwarnx(fmt, ap);
    570 	va_end(ap);
    571 	va_start(ap, fmt);
    572 	vsyslog(LOG_ERR, fmt, ap);
    573 	va_end(ap);
    574 }
    575