1/*	$NetBSD: su_pam.c,v 1.15 2008/07/21 14:19:26 lukem 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
40static char sccsid[] = "@(#)su.c	8.3 (Berkeley) 4/2/94";*/
41#else
42__RCSID("$NetBSD: su_pam.c,v 1.15 2008/07/21 14:19:26 lukem 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
74static 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
84static void logit(const char *, ...);
85
86int
87main(int argc, char **argv)
88{
89	extern char **environ;
90	struct passwd *pwd, pwres;
91	char *p;
92	uid_t ruid;
93	int asme, ch, asthem, fastlogin, prio, gohome;
94	u_int setwhat;
95	enum { UNSET, YES, NO } iscsh = UNSET;
96	const char *user, *shell, *avshell;
97	char *username, *class;
98	char **np;
99	char shellbuf[MAXPATHLEN], avshellbuf[MAXPATHLEN];
100	int pam_err;
101	char hostname[MAXHOSTNAMELEN];
102	char *tty;
103	const char *func;
104	const void *newuser;
105	login_cap_t *lc;
106	pam_handle_t *pamh = NULL;
107	char pwbuf[1024];
108#ifdef PAM_DEBUG
109	extern int _openpam_debug;
110
111	_openpam_debug = 1;
112#endif
113#ifdef ALLOW_GROUP_CHANGE
114	char *gname;
115#endif
116
117	(void)setprogname(argv[0]);
118	asme = asthem = fastlogin = 0;
119	gohome = 1;
120	shell = class = NULL;
121	while ((ch = getopt(argc, argv, ARGSTR)) != -1)
122		switch((char)ch) {
123		case 'c':
124			class = optarg;
125			break;
126		case 'd':
127			asme = 0;
128			asthem = 1;
129			gohome = 0;
130			break;
131		case 'f':
132			fastlogin = 1;
133			break;
134		case '-':
135		case 'l':
136			asme = 0;
137			asthem = 1;
138			break;
139		case 'm':
140			asme = 1;
141			asthem = 0;
142			break;
143		case '?':
144		default:
145			(void)fprintf(stderr,
146#ifdef ALLOW_GROUP_CHANGE
147			    "Usage: %s [%s] [login[:group] [shell arguments]]\n",
148#else
149			    "Usage: %s [%s] [login [shell arguments]]\n",
150#endif
151			    getprogname(), ARGSTR);
152			exit(EXIT_FAILURE);
153		}
154	argv += optind;
155
156	/* Lower the priority so su runs faster */
157	errno = 0;
158	prio = getpriority(PRIO_PROCESS, 0);
159	if (errno)
160		prio = 0;
161	if (prio > -2)
162		(void)setpriority(PRIO_PROCESS, 0, -2);
163	openlog("su", 0, LOG_AUTH);
164
165	/* get current login name and shell */
166	ruid = getuid();
167	username = getlogin();
168	if (username == NULL ||
169	    getpwnam_r(username, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
170	    pwd == NULL || pwd->pw_uid != ruid) {
171		if (getpwuid_r(ruid, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0)
172			pwd = NULL;
173	}
174	if (pwd == NULL)
175		errx(EXIT_FAILURE, "who are you?");
176	username = estrdup(pwd->pw_name);
177
178	if (asme) {
179		if (pwd->pw_shell && *pwd->pw_shell) {
180			(void)estrlcpy(shellbuf, pwd->pw_shell, sizeof(shellbuf));
181			shell = shellbuf;
182		} else {
183			shell = _PATH_BSHELL;
184			iscsh = NO;
185		}
186	}
187	/* get target login information, default to root */
188	user = *argv ? *argv : "root";
189	np = *argv ? argv : argv - 1;
190
191#ifdef ALLOW_GROUP_CHANGE
192	if ((p = strchr(user, ':')) != NULL) {
193		*p = '\0';
194		gname = ++p;
195	}
196	else
197		gname = NULL;
198
199#ifdef ALLOW_EMPTY_USER
200	if (user[0] == '\0')
201		user = username;
202#endif
203#endif
204	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
205	    pwd == NULL)
206		errx(EXIT_FAILURE, "unknown login %s", user);
207
208	/*
209	 * PAM initialization
210	 */
211#define PAM_END(msg) do { func = msg; goto done;} /* NOTREACHED */ while (/*CONSTCOND*/0)
212
213	if ((pam_err = pam_start("su", user, &pamc, &pamh)) != PAM_SUCCESS) {
214		if (pamh != NULL)
215			PAM_END("pam_start");
216		/* Things went really bad... */
217		syslog(LOG_ERR, "pam_start failed: %s",
218		    pam_strerror(pamh, pam_err));
219		errx(EXIT_FAILURE, "pam_start failed");
220	}
221
222#define PAM_END_ITEM(item)	PAM_END("pam_set_item(" # item ")")
223#define PAM_SET_ITEM(item, var) 					    \
224	if ((pam_err = pam_set_item(pamh, (item), (var))) != PAM_SUCCESS)   \
225		PAM_END_ITEM(item)
226
227	/*
228	 * Fill hostname, username and tty
229	 */
230	PAM_SET_ITEM(PAM_RUSER, username);
231	if (gethostname(hostname, sizeof(hostname)) != -1)
232		PAM_SET_ITEM(PAM_RHOST, hostname);
233
234	if ((tty = ttyname(STDERR_FILENO)) != NULL)
235		PAM_SET_ITEM(PAM_TTY, tty);
236
237	/*
238	 * Authentication
239	 */
240	if ((pam_err = pam_authenticate(pamh, 0)) != PAM_SUCCESS) {
241		syslog(LOG_WARNING, "BAD SU %s to %s%s: %s",
242		    username, user, ontty(), pam_strerror(pamh, pam_err));
243		(void)pam_end(pamh, pam_err);
244		errx(EXIT_FAILURE, "Sorry: %s", pam_strerror(pamh, pam_err));
245	}
246
247	/*
248	 * Authorization
249	 */
250	switch(pam_err = pam_acct_mgmt(pamh, 0)) {
251	case PAM_NEW_AUTHTOK_REQD:
252		pam_err = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
253		if (pam_err != PAM_SUCCESS)
254			PAM_END("pam_chauthok");
255		break;
256	case PAM_SUCCESS:
257		break;
258	default:
259		PAM_END("pam_acct_mgmt");
260		break;
261	}
262
263	/*
264	 * pam_authenticate might have changed the target user.
265	 * refresh pwd and user
266	 */
267	pam_err = pam_get_item(pamh, PAM_USER, &newuser);
268	if (pam_err != PAM_SUCCESS) {
269		syslog(LOG_WARNING,
270		    "pam_get_item(PAM_USER): %s", pam_strerror(pamh, pam_err));
271	} else {
272		user = (char *)__UNCONST(newuser);
273		if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
274		    pwd == NULL) {
275			(void)pam_end(pamh, pam_err);
276			syslog(LOG_ERR, "unknown login: %s", username);
277			errx(EXIT_FAILURE, "unknown login: %s", username);
278		}
279	}
280
281#define ERRX_PAM_END(args) do {			\
282	(void)pam_end(pamh, pam_err);		\
283	errx args;				\
284} while (/* CONSTCOND */0)
285
286#define ERR_PAM_END(args) do {			\
287	(void)pam_end(pamh, pam_err);		\
288	err args;				\
289} while (/* CONSTCOND */0)
290
291	/* force the usage of specified class */
292	if (class) {
293		if (ruid)
294			ERRX_PAM_END((EXIT_FAILURE, "Only root may use -c"));
295
296		pwd->pw_class = class;
297	}
298
299	if ((lc = login_getclass(pwd->pw_class)) == NULL)
300		ERRX_PAM_END((EXIT_FAILURE,
301		    "Unknown class %s\n", pwd->pw_class));
302
303	if (asme) {
304		/* if asme and non-standard target shell, must be root */
305		if (chshell(pwd->pw_shell) == 0 && ruid)
306			ERRX_PAM_END((EXIT_FAILURE,
307			    "permission denied (shell)."));
308	} else if (pwd->pw_shell && *pwd->pw_shell) {
309		shell = pwd->pw_shell;
310		iscsh = UNSET;
311	} else {
312		shell = _PATH_BSHELL;
313		iscsh = NO;
314	}
315
316	if ((p = strrchr(shell, '/')) != NULL)
317		avshell = p + 1;
318	else
319		avshell = shell;
320
321	/* if we're forking a csh, we want to slightly muck the args */
322	if (iscsh == UNSET)
323		iscsh = strstr(avshell, "csh") ? YES : NO;
324
325	/*
326	 * Initialize the supplemental groups before pam gets to them,
327	 * so that other pam modules get a chance to add more when
328	 * we do setcred. Note, we don't relinguish our set-userid yet
329	 */
330	/* if we aren't changing users, keep the current group members */
331	if (ruid != pwd->pw_uid &&
332	    setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) == -1)
333		ERR_PAM_END((EXIT_FAILURE, "setting user context"));
334
335#ifdef ALLOW_GROUP_CHANGE
336	addgroup(lc, gname, pwd, ruid, "Group Password:");
337#endif
338	if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS)
339		PAM_END("pam_setcred");
340
341	/*
342	 * Manage session.
343	 */
344	if (asthem) {
345		pid_t pid, xpid;
346		int status = 1;
347		struct sigaction sa, sa_int, sa_pipe, sa_quit;
348		int fds[2];
349
350 		if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS)
351			PAM_END("pam_open_session");
352
353		/*
354		 * In order to call pam_close_session after the
355		 * command terminates, we need to fork.
356		 */
357		sa.sa_flags = SA_RESTART;
358		sa.sa_handler = SIG_IGN;
359		(void)sigemptyset(&sa.sa_mask);
360		(void)sigaction(SIGINT, &sa, &sa_int);
361		(void)sigaction(SIGQUIT, &sa, &sa_quit);
362		(void)sigaction(SIGPIPE, &sa, &sa_pipe);
363		sa.sa_handler = SIG_DFL;
364		(void)sigaction(SIGTSTP, &sa, NULL);
365		/*
366		 * Use a pipe to guarantee the order of execution of
367		 * the parent and the child.
368		 */
369		if (pipe(fds) == -1) {
370			warn("pipe failed");
371			goto out;
372		}
373
374		switch (pid = fork()) {
375		case -1:
376			logit("fork failed (%s)", strerror(errno));
377			goto out;
378
379		case 0:	/* Child */
380			(void)close(fds[1]);
381			(void)read(fds[0], &status, 1);
382			(void)close(fds[0]);
383			(void)sigaction(SIGINT, &sa_int, NULL);
384			(void)sigaction(SIGQUIT, &sa_quit, NULL);
385			(void)sigaction(SIGPIPE, &sa_pipe, NULL);
386			break;
387
388		default:
389			sa.sa_handler = SIG_IGN;
390			(void)sigaction(SIGTTOU, &sa, NULL);
391			(void)close(fds[0]);
392			(void)setpgid(pid, pid);
393			(void)tcsetpgrp(STDERR_FILENO, pid);
394			(void)close(fds[1]);
395			(void)sigaction(SIGPIPE, &sa_pipe, NULL);
396			/*
397			 * Parent: wait for the child to terminate
398			 * and call pam_close_session.
399			 */
400			while ((xpid = waitpid(pid, &status, WUNTRACED))
401			    == pid) {
402				if (WIFSTOPPED(status)) {
403					(void)kill(getpid(), SIGSTOP);
404					(void)tcsetpgrp(STDERR_FILENO,
405					    getpgid(pid));
406					(void)kill(pid, SIGCONT);
407					status = 1;
408					continue;
409				}
410				break;
411			}
412
413			(void)tcsetpgrp(STDERR_FILENO, getpgid(0));
414
415			if (xpid == -1) {
416			    logit("Error waiting for pid %d (%s)", pid,
417				strerror(errno));
418			} else if (xpid != pid) {
419			    /* Can't happen. */
420			    logit("Wrong PID: %d != %d", pid, xpid);
421			}
422out:
423			pam_err = pam_setcred(pamh, PAM_DELETE_CRED);
424			if (pam_err != PAM_SUCCESS)
425				logit("pam_setcred: %s",
426				    pam_strerror(pamh, pam_err));
427			pam_err = pam_close_session(pamh, 0);
428			if (pam_err != PAM_SUCCESS)
429				logit("pam_close_session: %s",
430				    pam_strerror(pamh, pam_err));
431			(void)pam_end(pamh, pam_err);
432			exit(WEXITSTATUS(status));
433			break;
434		}
435	}
436
437	/*
438	 * The child: starting here, we don't have to care about
439	 * handling PAM issues if we exit, the parent will do the
440	 * job when we exit.
441	 */
442#undef PAM_END
443#undef ERR_PAM_END
444#undef ERRX_PAM_END
445
446	if (!asme) {
447		if (asthem) {
448			char **pamenv;
449
450			p = getenv("TERM");
451			/*
452			 * Create an empty environment
453			 */
454			environ = emalloc(sizeof(char *));
455			environ[0] = NULL;
456
457			/*
458			 * Add PAM environement, before the LOGIN_CAP stuff:
459			 * if the login class is unspecified, we'll get the
460			 * same data from PAM, if -c was used, the specified
461			 * class must override PAM.
462	 		 */
463			if ((pamenv = pam_getenvlist(pamh)) != NULL) {
464				char **envitem;
465
466				/*
467				 * XXX Here FreeBSD filters out
468				 * SHELL, LOGNAME, MAIL, CDPATH, IFS, PATH
469				 * how could we get untrusted data here?
470				 */
471				for (envitem = pamenv; *envitem; envitem++) {
472					if (putenv(*envitem) == -1)
473						free(*envitem);
474				}
475
476				free(pamenv);
477			}
478
479			if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETPATH |
480				LOGIN_SETENV | LOGIN_SETUMASK) == -1)
481				err(EXIT_FAILURE, "setting user context");
482			if (p)
483				(void)setenv("TERM", p, 1);
484			if (gohome && chdir(pwd->pw_dir) == -1)
485				errx(EXIT_FAILURE, "no directory");
486		}
487
488		if (asthem || pwd->pw_uid) {
489			(void)setenv("LOGNAME", pwd->pw_name, 1);
490			(void)setenv("USER", pwd->pw_name, 1);
491		}
492		(void)setenv("HOME", pwd->pw_dir, 1);
493		(void)setenv("SHELL", shell, 1);
494	}
495	(void)setenv("SU_FROM", username, 1);
496
497	if (iscsh == YES) {
498		if (fastlogin)
499			*np-- = __UNCONST("-f");
500		if (asme)
501			*np-- = __UNCONST("-m");
502	} else {
503		if (fastlogin)
504			(void)unsetenv("ENV");
505	}
506
507	if (asthem) {
508		avshellbuf[0] = '-';
509		(void)estrlcpy(avshellbuf + 1, avshell, sizeof(avshellbuf) - 1);
510		avshell = avshellbuf;
511	} else if (iscsh == YES) {
512		/* csh strips the first character... */
513		avshellbuf[0] = '_';
514		(void)estrlcpy(avshellbuf + 1, avshell, sizeof(avshellbuf) - 1);
515		avshell = avshellbuf;
516	}
517	*np = __UNCONST(avshell);
518
519	if (ruid != 0)
520		syslog(LOG_NOTICE, "%s to %s%s",
521		    username, pwd->pw_name, ontty());
522
523	/* Raise our priority back to what we had before */
524	(void)setpriority(PRIO_PROCESS, 0, prio);
525
526	/*
527	 * Set user context, except for umask, and the stuff
528	 * we have done before.
529	 */
530	setwhat = LOGIN_SETALL & ~(LOGIN_SETENV | LOGIN_SETUMASK |
531	    LOGIN_SETLOGIN | LOGIN_SETPATH | LOGIN_SETGROUP);
532
533	/*
534	 * Don't touch resource/priority settings if -m has been used
535	 * or -l and -c hasn't, and we're not su'ing to root.
536	 */
537	if ((asme || (!asthem && class == NULL)) && pwd->pw_uid)
538		setwhat &= ~(LOGIN_SETPRIORITY | LOGIN_SETRESOURCES);
539
540	if (setusercontext(lc, pwd, pwd->pw_uid, setwhat) == -1)
541		err(EXIT_FAILURE, "setusercontext");
542
543	(void)execv(shell, np);
544	err(EXIT_FAILURE, "%s", shell);
545done:
546	logit("%s: %s", func, pam_strerror(pamh, pam_err));
547	(void)pam_end(pamh, pam_err);
548	return EXIT_FAILURE;
549}
550
551static void
552logit(const char *fmt, ...)
553{
554	va_list ap;
555
556	va_start(ap, fmt);
557	vwarnx(fmt, ap);
558	vsyslog(LOG_ERR, fmt, ap);
559	va_end(ap);
560}
561