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