1 /*-
2 * SPDX-License-Identifier: BSD-4-Clause
3 *
4 * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 * Copyright (c) 2002 Networks Associates Technologies, Inc.
7 * All rights reserved.
8 *
9 * Portions of this software were developed for the FreeBSD Project by
10 * ThinkSec AS and NAI Labs, the Security Research Division of Network
11 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
12 * ("CBOSS"), as part of the DARPA CHATS research program.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the University of
25 * California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * SUCH DAMAGE.
41 */
42
43 #if 0
44 #ifndef lint
45 static char sccsid[] = "@(#)login.c 8.4 (Berkeley) 4/2/94";
46 #endif
47 #endif
48
49 #include <sys/cdefs.h>
50 /*
51 * login [ name ]
52 * login -h hostname (for telnetd, etc.)
53 * login -f name (for pre-authenticated login: datakit, xterm, etc.)
54 */
55
56 #include <sys/param.h>
57 #include <sys/file.h>
58 #include <sys/stat.h>
59 #include <sys/time.h>
60 #include <sys/resource.h>
61 #include <sys/wait.h>
62
63 #include <err.h>
64 #include <errno.h>
65 #include <grp.h>
66 #include <login_cap.h>
67 #include <pwd.h>
68 #include <setjmp.h>
69 #include <signal.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <syslog.h>
74 #include <ttyent.h>
75 #include <unistd.h>
76
77 #include <security/pam_appl.h>
78 #include <security/openpam.h>
79
80 #include "login.h"
81 #include "pathnames.h"
82
83 static int auth_pam(void);
84 static void bail(int, int);
85 static void bail_internal(int, int, int);
86 static int export(const char *);
87 static void export_pam_environment(void);
88 static int motd(const char *);
89 static void badlogin(char *);
90 static char *getloginname(void);
91 static void pam_syslog(const char *);
92 static void pam_cleanup(void);
93 static void refused(const char *, const char *, int);
94 static const char *stypeof(char *);
95 static void sigint(int);
96 static void timedout(int);
97 static void bail_sig(int);
98 static void usage(void);
99
100 #define TTYGRPNAME "tty" /* group to own ttys */
101 #define DEFAULT_BACKOFF 3
102 #define DEFAULT_RETRIES 10
103 #define DEFAULT_PROMPT "login: "
104 #define DEFAULT_PASSWD_PROMPT "Password:"
105 #define TERM_UNKNOWN "su"
106 #define DEFAULT_WARN (2L * 7L * 86400L) /* Two weeks */
107 #define NO_SLEEP_EXIT 0
108 #define SLEEP_EXIT 5
109
110 /*
111 * This bounds the time given to login. Not a define so it can
112 * be patched on machines where it's too small.
113 */
114 static u_int timeout = 300;
115
116 /* Buffer for signal handling of timeout */
117 static jmp_buf timeout_buf;
118
119 char pwbuf[1024];
120 struct passwd pwres;
121 struct passwd *pwd;
122 static int failures;
123
124 static char *envinit[1]; /* empty environment list */
125
126 /*
127 * Command line flags and arguments
128 */
129 static int fflag; /* -f: do not perform authentication */
130 static int hflag; /* -h: login from remote host */
131 static char *hostname; /* hostname from command line */
132 static int pflag; /* -p: preserve environment */
133
134 /*
135 * User name
136 */
137 static char *username; /* user name */
138 static char *olduser; /* previous user name */
139
140 /*
141 * Prompts
142 */
143 static char default_prompt[] = DEFAULT_PROMPT;
144 static const char *prompt;
145 static char default_passwd_prompt[] = DEFAULT_PASSWD_PROMPT;
146 static const char *passwd_prompt;
147
148 static char *tty;
149
150 /*
151 * PAM data
152 */
153 static pam_handle_t *pamh = NULL;
154 static struct pam_conv pamc = { openpam_ttyconv, NULL };
155 static int pam_err;
156 static int pam_silent = PAM_SILENT;
157 static int pam_cred_established;
158 static int pam_session_established;
159
160 int
main(int argc,char * argv[])161 main(int argc, char *argv[])
162 {
163 struct group *gr;
164 struct stat st;
165 int retries, backoff;
166 int ask, ch, cnt, quietlog, rootlogin, rval;
167 uid_t uid, euid;
168 gid_t egid;
169 char *term;
170 char *p, *ttyn;
171 char tname[sizeof(_PATH_TTY) + 10];
172 char *arg0;
173 const char *tp;
174 const char *shell = NULL;
175 login_cap_t *lc = NULL;
176 login_cap_t *lc_user = NULL;
177 pid_t pid;
178 sigset_t mask, omask;
179 struct sigaction sa;
180 #ifdef USE_BSM_AUDIT
181 char auditsuccess = 1;
182 #endif
183
184 sa.sa_flags = SA_RESTART;
185 (void)sigfillset(&sa.sa_mask);
186 sa.sa_handler = SIG_IGN;
187 (void)sigaction(SIGQUIT, &sa, NULL);
188 (void)sigaction(SIGINT, &sa, NULL);
189 (void)sigaction(SIGHUP, &sa, NULL);
190 if (setjmp(timeout_buf)) {
191 if (failures)
192 badlogin(username);
193 (void)fprintf(stderr, "Login timed out after %d seconds\n",
194 timeout);
195 bail(NO_SLEEP_EXIT, 0);
196 }
197 sa.sa_handler = timedout;
198 (void)sigaction(SIGALRM, &sa, NULL);
199 (void)alarm(timeout);
200 (void)setpriority(PRIO_PROCESS, 0, 0);
201
202 openlog("login", LOG_CONS, LOG_AUTH);
203
204 uid = getuid();
205 euid = geteuid();
206 egid = getegid();
207
208 while ((ch = getopt(argc, argv, "fh:p")) != -1)
209 switch (ch) {
210 case 'f':
211 fflag = 1;
212 break;
213 case 'h':
214 if (uid != 0)
215 errx(1, "-h option: %s", strerror(EPERM));
216 if (strlen(optarg) >= MAXHOSTNAMELEN)
217 errx(1, "-h option: %s: exceeds maximum "
218 "hostname size", optarg);
219 hflag = 1;
220 hostname = optarg;
221 break;
222 case 'p':
223 pflag = 1;
224 break;
225 case '?':
226 default:
227 if (uid == 0)
228 syslog(LOG_ERR, "invalid flag %c", ch);
229 usage();
230 }
231 argc -= optind;
232 argv += optind;
233
234 if (argc > 0) {
235 username = strdup(*argv);
236 if (username == NULL)
237 err(1, "strdup()");
238 ask = 0;
239 } else {
240 ask = 1;
241 }
242
243 setproctitle("-%s", getprogname());
244
245 closefrom(3);
246
247 /*
248 * Get current TTY
249 */
250 ttyn = ttyname(STDIN_FILENO);
251 if (ttyn == NULL || *ttyn == '\0') {
252 (void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
253 ttyn = tname;
254 }
255 if (strncmp(ttyn, _PATH_DEV, sizeof _PATH_DEV - 1) == 0)
256 tty = ttyn + sizeof _PATH_DEV - 1;
257 else
258 tty = ttyn;
259
260 /*
261 * Get "login-retries" & "login-backoff" from default class
262 */
263 lc = login_getclass(NULL);
264 prompt = login_getcapstr(lc, "login_prompt",
265 default_prompt, default_prompt);
266 passwd_prompt = login_getcapstr(lc, "passwd_prompt",
267 default_passwd_prompt, default_passwd_prompt);
268 retries = login_getcapnum(lc, "login-retries",
269 DEFAULT_RETRIES, DEFAULT_RETRIES);
270 backoff = login_getcapnum(lc, "login-backoff",
271 DEFAULT_BACKOFF, DEFAULT_BACKOFF);
272 login_close(lc);
273 lc = NULL;
274
275 /*
276 * Try to authenticate the user until we succeed or time out.
277 */
278 for (cnt = 0;; ask = 1) {
279 if (ask) {
280 fflag = 0;
281 if (olduser != NULL)
282 free(olduser);
283 olduser = username;
284 username = getloginname();
285 }
286 rootlogin = 0;
287
288 /*
289 * Note if trying multiple user names; log failures for
290 * previous user name, but don't bother logging one failure
291 * for nonexistent name (mistyped username).
292 */
293 if (failures && strcmp(olduser, username) != 0) {
294 if (failures > (pwd ? 0 : 1))
295 badlogin(olduser);
296 }
297
298 /*
299 * Load the PAM policy and set some variables
300 */
301 pam_err = pam_start("login", username, &pamc, &pamh);
302 if (pam_err != PAM_SUCCESS) {
303 pam_syslog("pam_start()");
304 #ifdef USE_BSM_AUDIT
305 au_login_fail("PAM Error", 1);
306 #endif
307 bail(NO_SLEEP_EXIT, 1);
308 }
309 pam_err = pam_set_item(pamh, PAM_TTY, tty);
310 if (pam_err != PAM_SUCCESS) {
311 pam_syslog("pam_set_item(PAM_TTY)");
312 #ifdef USE_BSM_AUDIT
313 au_login_fail("PAM Error", 1);
314 #endif
315 bail(NO_SLEEP_EXIT, 1);
316 }
317 pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
318 if (pam_err != PAM_SUCCESS) {
319 pam_syslog("pam_set_item(PAM_RHOST)");
320 #ifdef USE_BSM_AUDIT
321 au_login_fail("PAM Error", 1);
322 #endif
323 bail(NO_SLEEP_EXIT, 1);
324 }
325
326 (void)getpwnam_r(username, &pwres, pwbuf, sizeof(pwbuf), &pwd);
327 if (pwd != NULL && pwd->pw_uid == 0)
328 rootlogin = 1;
329
330 /*
331 * If the -f option was specified and the caller is
332 * root or the caller isn't changing their uid, don't
333 * authenticate.
334 */
335 if (pwd != NULL && fflag &&
336 (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
337 /* already authenticated */
338 rval = 0;
339 #ifdef USE_BSM_AUDIT
340 auditsuccess = 0; /* opened a terminal window only */
341 #endif
342 } else {
343 fflag = 0;
344 (void)setpriority(PRIO_PROCESS, 0, -4);
345 rval = auth_pam();
346 (void)setpriority(PRIO_PROCESS, 0, 0);
347 }
348
349 if (pwd != NULL && rval == 0)
350 break;
351
352 pam_cleanup();
353
354 /*
355 * We are not exiting here, but this corresponds to a failed
356 * login event, so set exitstatus to 1.
357 */
358 #ifdef USE_BSM_AUDIT
359 au_login_fail("Login incorrect", 1);
360 #endif
361
362 (void)printf("Login incorrect\n");
363 failures++;
364
365 pwd = NULL;
366
367 /*
368 * Allow up to 'retry' (10) attempts, but start
369 * backing off after 'backoff' (3) attempts.
370 */
371 if (++cnt > backoff) {
372 if (cnt >= retries) {
373 badlogin(username);
374 bail(SLEEP_EXIT, 1);
375 }
376 sleep((u_int)((cnt - backoff) * 5));
377 }
378 }
379
380 /* committed to login -- turn off timeout */
381 (void)alarm((u_int)0);
382
383 (void)sigemptyset(&mask);
384 (void)sigaddset(&mask, SIGHUP);
385 (void)sigaddset(&mask, SIGTERM);
386 (void)sigprocmask(SIG_BLOCK, &mask, &omask);
387 sa.sa_handler = bail_sig;
388 (void)sigaction(SIGHUP, &sa, NULL);
389 (void)sigaction(SIGTERM, &sa, NULL);
390
391 endpwent();
392
393 #ifdef USE_BSM_AUDIT
394 /* Audit successful login. */
395 if (auditsuccess)
396 au_login_success();
397 #endif
398
399 /*
400 * This needs to happen before login_getpwclass to support
401 * home directories on GSS-API authenticated NFS where the
402 * kerberos credentials need to be saved so that the kernel
403 * can authenticate to the NFS server.
404 */
405 pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
406 if (pam_err != PAM_SUCCESS) {
407 pam_syslog("pam_setcred()");
408 bail(NO_SLEEP_EXIT, 1);
409 }
410 pam_cred_established = 1;
411
412 /*
413 * Establish the login class.
414 */
415 lc = login_getpwclass(pwd);
416 lc_user = login_getuserclass(pwd);
417
418 if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
419 quietlog = login_getcapbool(lc, "hushlogin", 0);
420
421 /*
422 * Switching needed for NFS with root access disabled.
423 *
424 * XXX: This change fails to modify the additional groups for the
425 * process, and as such, may restrict rights normally granted
426 * through those groups.
427 */
428 (void)setegid(pwd->pw_gid);
429 (void)seteuid(rootlogin ? 0 : pwd->pw_uid);
430 if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
431 if (login_getcapbool(lc, "requirehome", 0))
432 refused("Home directory not available", "HOMEDIR", 1);
433 if (chdir("/") < 0)
434 refused("Cannot find root directory", "ROOTDIR", 1);
435 if (!quietlog || *pwd->pw_dir)
436 printf("No home directory.\nLogging in with home = \"/\".\n");
437 pwd->pw_dir = strdup("/");
438 if (pwd->pw_dir == NULL) {
439 syslog(LOG_NOTICE, "strdup(): %m");
440 bail(SLEEP_EXIT, 1);
441 }
442 }
443 (void)seteuid(euid);
444 (void)setegid(egid);
445 if (!quietlog) {
446 quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
447 if (!quietlog)
448 pam_silent = 0;
449 }
450
451 shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
452 if (*pwd->pw_shell == '\0')
453 pwd->pw_shell = strdup(_PATH_BSHELL);
454 if (pwd->pw_shell == NULL) {
455 syslog(LOG_NOTICE, "strdup(): %m");
456 bail(SLEEP_EXIT, 1);
457 }
458 if (*shell == '\0') /* Not overridden */
459 shell = pwd->pw_shell;
460 if ((shell = strdup(shell)) == NULL) {
461 syslog(LOG_NOTICE, "strdup(): %m");
462 bail(SLEEP_EXIT, 1);
463 }
464
465 /*
466 * Set device protections, depending on what terminal the
467 * user is logged in. This feature is used on Suns to give
468 * console users better privacy.
469 */
470 login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
471
472 /*
473 * Clear flags of the tty. None should be set, and when the
474 * user sets them otherwise, this can cause the chown to fail.
475 * Since it isn't clear that flags are useful on character
476 * devices, we just clear them.
477 *
478 * We don't log in the case of EOPNOTSUPP because dev might be
479 * on NFS, which doesn't support chflags.
480 *
481 * We don't log in the EROFS because that means that /dev is on
482 * a read only file system and we assume that the permissions there
483 * are sane.
484 */
485 if (ttyn != tname && chflags(ttyn, 0))
486 if (errno != EOPNOTSUPP && errno != EROFS)
487 syslog(LOG_ERR, "chflags(%s): %m", ttyn);
488 if (ttyn != tname && chown(ttyn, pwd->pw_uid,
489 (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
490 if (errno != EROFS)
491 syslog(LOG_ERR, "chown(%s): %m", ttyn);
492
493 #ifdef LOGALL
494 /*
495 * Syslog each successful login, so we don't have to watch
496 * hundreds of wtmp or lastlogin files.
497 */
498 if (hflag)
499 syslog(LOG_INFO, "login from %s on %s as %s",
500 hostname, tty, pwd->pw_name);
501 else
502 syslog(LOG_INFO, "login on %s as %s",
503 tty, pwd->pw_name);
504 #endif
505
506 /*
507 * If fflag is on, assume caller/authenticator has logged root
508 * login.
509 */
510 if (rootlogin && fflag == 0) {
511 if (hflag)
512 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
513 username, tty, hostname);
514 else
515 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
516 username, tty);
517 }
518
519 /*
520 * Destroy environment unless user has requested its
521 * preservation - but preserve TERM in all cases
522 */
523 term = getenv("TERM");
524 if (!pflag)
525 environ = envinit;
526 if (term != NULL)
527 setenv("TERM", term, 0);
528
529 /*
530 * PAM modules might add supplementary groups during pam_setcred().
531 */
532 if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
533 syslog(LOG_ERR, "setusercontext() failed - exiting");
534 bail(NO_SLEEP_EXIT, 1);
535 }
536
537 pam_err = pam_setcred(pamh, pam_silent|PAM_REINITIALIZE_CRED);
538 if (pam_err != PAM_SUCCESS) {
539 pam_syslog("pam_setcred()");
540 bail(NO_SLEEP_EXIT, 1);
541 }
542
543 pam_err = pam_open_session(pamh, pam_silent);
544 if (pam_err != PAM_SUCCESS) {
545 pam_syslog("pam_open_session()");
546 bail(NO_SLEEP_EXIT, 1);
547 }
548 pam_session_established = 1;
549
550 /*
551 * We must fork() before setuid() because we need to call
552 * pam_close_session() as root.
553 */
554 pid = fork();
555 if (pid < 0) {
556 err(1, "fork");
557 } else if (pid != 0) {
558 /*
559 * Parent: wait for child to finish, then clean up
560 * session.
561 *
562 * If we get SIGHUP or SIGTERM, clean up the session
563 * and exit right away. This will make the terminal
564 * inaccessible and send SIGHUP to the foreground
565 * process group.
566 */
567 int status;
568 setproctitle("-%s [pam]", getprogname());
569 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
570 waitpid(pid, &status, 0);
571 (void)sigprocmask(SIG_BLOCK, &mask, NULL);
572 bail(NO_SLEEP_EXIT, 0);
573 }
574
575 /*
576 * NOTICE: We are now in the child process!
577 */
578
579 /*
580 * Add any environment variables the PAM modules may have set.
581 */
582 export_pam_environment();
583
584 /*
585 * We're done with PAM now; our parent will deal with the rest.
586 */
587 pam_end(pamh, 0);
588 pamh = NULL;
589
590 /*
591 * We don't need to be root anymore, so set the login name and
592 * the UID.
593 */
594 if (setlogin(username) != 0) {
595 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
596 bail(NO_SLEEP_EXIT, 1);
597 }
598 if (setusercontext(lc, pwd, pwd->pw_uid,
599 LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
600 syslog(LOG_ERR, "setusercontext() failed - exiting");
601 exit(1);
602 }
603
604 (void)setenv("SHELL", pwd->pw_shell, 1);
605 (void)setenv("HOME", pwd->pw_dir, 1);
606 /* Overwrite "term" from login.conf(5) for any known TERM */
607 if (term == NULL && (tp = stypeof(tty)) != NULL)
608 (void)setenv("TERM", tp, 1);
609 else
610 (void)setenv("TERM", TERM_UNKNOWN, 0);
611 (void)setenv("LOGNAME", username, 1);
612 (void)setenv("USER", username, 1);
613 (void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
614
615 if (!quietlog) {
616 const char *cw;
617
618 cw = login_getcapstr(lc, "welcome", NULL, NULL);
619 if (cw != NULL && access(cw, F_OK) == 0)
620 motd(cw);
621 else
622 motd(_PATH_MOTDFILE);
623
624 if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
625 login_getcapbool(lc, "nocheckmail", 0) == 0) {
626 char *cx;
627
628 /* $MAIL may have been set by class. */
629 cx = getenv("MAIL");
630 if (cx == NULL) {
631 asprintf(&cx, "%s/%s",
632 _PATH_MAILDIR, pwd->pw_name);
633 }
634 if (cx && stat(cx, &st) == 0 && st.st_size != 0)
635 (void)printf("You have %smail.\n",
636 (st.st_mtime > st.st_atime) ? "new " : "");
637 if (getenv("MAIL") == NULL)
638 free(cx);
639 }
640 }
641
642 login_close(lc_user);
643 login_close(lc);
644
645 sa.sa_handler = SIG_DFL;
646 (void)sigaction(SIGALRM, &sa, NULL);
647 (void)sigaction(SIGQUIT, &sa, NULL);
648 (void)sigaction(SIGINT, &sa, NULL);
649 (void)sigaction(SIGTERM, &sa, NULL);
650 (void)sigaction(SIGHUP, &sa, NULL);
651 sa.sa_handler = SIG_IGN;
652 (void)sigaction(SIGTSTP, &sa, NULL);
653 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
654
655 /*
656 * Login shells have a leading '-' in front of argv[0]
657 */
658 p = strrchr(pwd->pw_shell, '/');
659 if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
660 syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
661 username);
662 errx(1, "shell exceeds maximum pathname size");
663 } else if (arg0 == NULL) {
664 err(1, "asprintf()");
665 }
666
667 execlp(shell, arg0, (char *)0);
668 err(1, "%s", shell);
669
670 /*
671 * That's it, folks!
672 */
673 }
674
675 /*
676 * Attempt to authenticate the user using PAM. Returns 0 if the user is
677 * authenticated, or 1 if not authenticated. If some sort of PAM system
678 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
679 * function returns -1. This can be used as an indication that we should
680 * fall back to a different authentication mechanism.
681 */
682 static int
auth_pam(void)683 auth_pam(void)
684 {
685 const char *tmpl_user;
686 const void *item;
687 int rval;
688
689 pam_err = pam_authenticate(pamh, pam_silent);
690 switch (pam_err) {
691
692 case PAM_SUCCESS:
693 /*
694 * With PAM we support the concept of a "template"
695 * user. The user enters a login name which is
696 * authenticated by PAM, usually via a remote service
697 * such as RADIUS or TACACS+. If authentication
698 * succeeds, a different but related "template" name
699 * is used for setting the credentials, shell, and
700 * home directory. The name the user enters need only
701 * exist on the remote authentication server, but the
702 * template name must be present in the local password
703 * database.
704 *
705 * This is supported by two various mechanisms in the
706 * individual modules. However, from the application's
707 * point of view, the template user is always passed
708 * back as a changed value of the PAM_USER item.
709 */
710 pam_err = pam_get_item(pamh, PAM_USER, &item);
711 if (pam_err == PAM_SUCCESS) {
712 tmpl_user = (const char *)item;
713 if (strcmp(username, tmpl_user) != 0) {
714 (void)getpwnam_r(tmpl_user, &pwres, pwbuf,
715 sizeof(pwbuf), &pwd);
716 }
717 } else {
718 pam_syslog("pam_get_item(PAM_USER)");
719 }
720 rval = 0;
721 break;
722
723 case PAM_AUTH_ERR:
724 case PAM_USER_UNKNOWN:
725 case PAM_MAXTRIES:
726 rval = 1;
727 break;
728
729 default:
730 pam_syslog("pam_authenticate()");
731 rval = -1;
732 break;
733 }
734
735 if (rval == 0) {
736 pam_err = pam_acct_mgmt(pamh, pam_silent);
737 switch (pam_err) {
738 case PAM_SUCCESS:
739 break;
740 case PAM_NEW_AUTHTOK_REQD:
741 pam_err = pam_chauthtok(pamh,
742 pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
743 if (pam_err != PAM_SUCCESS) {
744 pam_syslog("pam_chauthtok()");
745 rval = 1;
746 }
747 break;
748 default:
749 pam_syslog("pam_acct_mgmt()");
750 rval = 1;
751 break;
752 }
753 }
754
755 if (rval != 0) {
756 pam_end(pamh, pam_err);
757 pamh = NULL;
758 }
759 return (rval);
760 }
761
762 /*
763 * Export any environment variables PAM modules may have set
764 */
765 static void
export_pam_environment(void)766 export_pam_environment(void)
767 {
768 char **pam_env;
769 char **pp;
770
771 pam_env = pam_getenvlist(pamh);
772 if (pam_env != NULL) {
773 for (pp = pam_env; *pp != NULL; pp++) {
774 (void)export(*pp);
775 free(*pp);
776 }
777 }
778 }
779
780 /*
781 * Perform sanity checks on an environment variable:
782 * - Make sure there is an '=' in the string.
783 * - Make sure the string doesn't run on too long.
784 * - Do not export certain variables. This list was taken from the
785 * Solaris pam_putenv(3) man page.
786 * Then export it.
787 */
788 static int
export(const char * s)789 export(const char *s)
790 {
791 static const char *noexport[] = {
792 "SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
793 "IFS", "PATH", NULL
794 };
795 char *p;
796 const char **pp;
797 size_t n;
798 int rv;
799
800 if (strlen(s) > 1024 || (p = strchr(s, '=')) == NULL)
801 return (0);
802 if (strncmp(s, "LD_", 3) == 0)
803 return (0);
804 for (pp = noexport; *pp != NULL; pp++) {
805 n = strlen(*pp);
806 if (s[n] == '=' && strncmp(s, *pp, n) == 0)
807 return (0);
808 }
809 *p = '\0';
810 rv = setenv(s, p + 1, 1);
811 *p = '=';
812 if (rv == -1)
813 return (0);
814 return (1);
815 }
816
817 static void
usage(void)818 usage(void)
819 {
820
821 (void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
822 exit(1);
823 }
824
825 /*
826 * Prompt user and read login name from stdin.
827 */
828 static char *
getloginname(void)829 getloginname(void)
830 {
831 char *nbuf, *p;
832 int ch;
833
834 nbuf = malloc(MAXLOGNAME);
835 if (nbuf == NULL)
836 err(1, "malloc()");
837 do {
838 (void)printf("%s", prompt);
839 for (p = nbuf; (ch = getchar()) != '\n'; ) {
840 if (ch == EOF) {
841 badlogin(username);
842 bail(NO_SLEEP_EXIT, 0);
843 }
844 if (p < nbuf + MAXLOGNAME - 1)
845 *p++ = ch;
846 }
847 } while (p == nbuf);
848
849 *p = '\0';
850 if (nbuf[0] == '-') {
851 pam_silent = 0;
852 memmove(nbuf, nbuf + 1, strlen(nbuf));
853 } else {
854 pam_silent = PAM_SILENT;
855 }
856 return nbuf;
857 }
858
859 /*
860 * SIGINT handler for motd().
861 */
862 static volatile int motdinterrupt;
863 static void
sigint(int signo __unused)864 sigint(int signo __unused)
865 {
866 motdinterrupt = 1;
867 }
868
869 /*
870 * Display the contents of a file (such as /etc/motd).
871 */
872 static int
motd(const char * motdfile)873 motd(const char *motdfile)
874 {
875 struct sigaction newint, oldint;
876 FILE *f;
877 int ch;
878
879 if ((f = fopen(motdfile, "r")) == NULL)
880 return (-1);
881 motdinterrupt = 0;
882 newint.sa_handler = sigint;
883 newint.sa_flags = 0;
884 sigfillset(&newint.sa_mask);
885 sigaction(SIGINT, &newint, &oldint);
886 while ((ch = fgetc(f)) != EOF && !motdinterrupt)
887 putchar(ch);
888 sigaction(SIGINT, &oldint, NULL);
889 if (ch != EOF || ferror(f)) {
890 fclose(f);
891 return (-1);
892 }
893 fclose(f);
894 return (0);
895 }
896
897 /*
898 * SIGALRM handler, to enforce login prompt timeout.
899 *
900 * XXX This can potentially confuse the hell out of PAM. We should
901 * XXX instead implement a conversation function that returns
902 * XXX PAM_CONV_ERR when interrupted by a signal, and have the signal
903 * XXX handler just set a flag.
904 */
905 static void
timedout(int signo __unused)906 timedout(int signo __unused)
907 {
908
909 longjmp(timeout_buf, signo);
910 }
911
912 static void
badlogin(char * name)913 badlogin(char *name)
914 {
915
916 if (failures == 0)
917 return;
918 if (hflag) {
919 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
920 failures, failures > 1 ? "S" : "", hostname);
921 syslog(LOG_AUTHPRIV|LOG_NOTICE,
922 "%d LOGIN FAILURE%s FROM %s, %s",
923 failures, failures > 1 ? "S" : "", hostname, name);
924 } else {
925 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
926 failures, failures > 1 ? "S" : "", tty);
927 syslog(LOG_AUTHPRIV|LOG_NOTICE,
928 "%d LOGIN FAILURE%s ON %s, %s",
929 failures, failures > 1 ? "S" : "", tty, name);
930 }
931 failures = 0;
932 }
933
934 const char *
stypeof(char * ttyid)935 stypeof(char *ttyid)
936 {
937 struct ttyent *t;
938
939 if (ttyid != NULL && *ttyid != '\0') {
940 t = getttynam(ttyid);
941 if (t != NULL && t->ty_type != NULL)
942 return (t->ty_type);
943 }
944 return (NULL);
945 }
946
947 static void
refused(const char * msg,const char * rtype,int lout)948 refused(const char *msg, const char *rtype, int lout)
949 {
950
951 if (msg != NULL)
952 printf("%s.\n", msg);
953 if (hflag)
954 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
955 pwd->pw_name, rtype, hostname, tty);
956 else
957 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
958 pwd->pw_name, rtype, tty);
959 if (lout)
960 bail(SLEEP_EXIT, 1);
961 }
962
963 /*
964 * Log a PAM error
965 */
966 static void
pam_syslog(const char * msg)967 pam_syslog(const char *msg)
968 {
969 syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err));
970 }
971
972 /*
973 * Shut down PAM
974 */
975 static void
pam_cleanup(void)976 pam_cleanup(void)
977 {
978
979 if (pamh != NULL) {
980 if (pam_session_established) {
981 pam_err = pam_close_session(pamh, 0);
982 if (pam_err != PAM_SUCCESS)
983 pam_syslog("pam_close_session()");
984 }
985 pam_session_established = 0;
986 if (pam_cred_established) {
987 pam_err = pam_setcred(pamh, pam_silent|PAM_DELETE_CRED);
988 if (pam_err != PAM_SUCCESS)
989 pam_syslog("pam_setcred()");
990 }
991 pam_cred_established = 0;
992 pam_end(pamh, pam_err);
993 pamh = NULL;
994 }
995 }
996
997 static void
bail_internal(int sec,int eval,int signo)998 bail_internal(int sec, int eval, int signo)
999 {
1000 struct sigaction sa;
1001
1002 pam_cleanup();
1003 #ifdef USE_BSM_AUDIT
1004 if (pwd != NULL)
1005 audit_logout();
1006 #endif
1007 (void)sleep(sec);
1008 if (signo == 0)
1009 exit(eval);
1010 else {
1011 sa.sa_handler = SIG_DFL;
1012 sa.sa_flags = 0;
1013 (void)sigemptyset(&sa.sa_mask);
1014 (void)sigaction(signo, &sa, NULL);
1015 (void)sigaddset(&sa.sa_mask, signo);
1016 (void)sigprocmask(SIG_UNBLOCK, &sa.sa_mask, NULL);
1017 raise(signo);
1018 exit(128 + signo);
1019 }
1020 }
1021
1022 /*
1023 * Exit, optionally after sleeping a few seconds
1024 */
1025 static void
bail(int sec,int eval)1026 bail(int sec, int eval)
1027 {
1028 bail_internal(sec, eval, 0);
1029 }
1030
1031 /*
1032 * Exit because of a signal.
1033 * This is not async-signal safe, so only call async-signal safe functions
1034 * while the signal is unmasked.
1035 */
1036 static void
bail_sig(int signo)1037 bail_sig(int signo)
1038 {
1039 bail_internal(NO_SLEEP_EXIT, 0, signo);
1040 }
1041