]> git.ipfire.org Git - thirdparty/util-linux.git/blob - login-utils/login.c
login: extract get_hushlogin_status
[thirdparty/util-linux.git] / login-utils / login.c
1 /*
2 * login(1)
3 *
4 * This program is derived from 4.3 BSD software and is subject to the
5 * copyright notice below.
6 *
7 * Copyright (C) 2011 Karel Zak <kzak@redhat.com>
8 * Rewritten to PAM-only version.
9 *
10 * Michael Glad (glad@daimi.dk)
11 * Computer Science Department, Aarhus University, Denmark
12 * 1990-07-04
13 *
14 * Copyright (c) 1980, 1987, 1988 The Regents of the University of California.
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms are permitted
18 * provided that the above copyright notice and this paragraph are
19 * duplicated in all such forms and that any documentation,
20 * advertising materials, and other materials related to such
21 * distribution and use acknowledge that the software was developed
22 * by the University of California, Berkeley. The name of the
23 * University may not be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
27 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
28 */
29 #include <sys/param.h>
30 #include <stdio.h>
31 #include <ctype.h>
32 #include <unistd.h>
33 #include <getopt.h>
34 #include <memory.h>
35 #include <time.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/resource.h>
39 #include <sys/file.h>
40 #include <termios.h>
41 #include <string.h>
42 #include <sys/ioctl.h>
43 #include <sys/wait.h>
44 #include <signal.h>
45 #include <errno.h>
46 #include <grp.h>
47 #include <pwd.h>
48 #include <utmp.h>
49 #include <stdlib.h>
50 #include <sys/syslog.h>
51 #include <sys/sysmacros.h>
52 #ifdef HAVE_LINUX_MAJOR_H
53 # include <linux/major.h>
54 #endif
55 #include <netdb.h>
56 #include <lastlog.h>
57 #include <security/pam_appl.h>
58 #include <security/pam_misc.h>
59 #include <sys/sendfile.h>
60
61 #ifdef HAVE_LIBAUDIT
62 # include <libaudit.h>
63 #endif
64
65 #include "c.h"
66 #include "setproctitle.h"
67 #include "pathnames.h"
68 #include "strutils.h"
69 #include "nls.h"
70 #include "xalloc.h"
71 #include "all-io.h"
72 #include "fileutils.h"
73 #include "ttyutils.h"
74
75 #include "logindefs.h"
76
77 #define is_pam_failure(_rc) ((_rc) != PAM_SUCCESS)
78
79 #define LOGIN_MAX_TRIES 3
80 #define LOGIN_EXIT_TIMEOUT 5
81 #define LOGIN_TIMEOUT 60
82
83 #ifdef USE_TTY_GROUP
84 # define TTY_MODE 0620
85 #else
86 # define TTY_MODE 0600
87 #endif
88
89 #define TTYGRPNAME "tty" /* name of group to own ttys */
90 #define VCS_PATH_MAX 64
91
92 /*
93 * Login control struct
94 */
95 struct login_context {
96 const char *tty_path; /* ttyname() return value */
97 const char *tty_name; /* tty_path without /dev prefix */
98 const char *tty_number; /* end of the tty_path */
99 mode_t tty_mode; /* chmod() mode */
100
101 char *username; /* from command line or PAM */
102
103 struct passwd *pwd; /* user info */
104
105 pam_handle_t *pamh; /* PAM handler */
106 struct pam_conv conv; /* PAM conversation */
107
108 #ifdef LOGIN_CHOWN_VCS
109 char vcsn[VCS_PATH_MAX]; /* virtual console name */
110 char vcsan[VCS_PATH_MAX];
111 #endif
112
113 char *thishost; /* this machine */
114 char *thisdomain; /* this machine's domain */
115 char *hostname; /* remote machine */
116 char hostaddress[16]; /* remote address */
117
118 pid_t pid;
119 int quiet; /* 1 if hush file exists */
120
121 unsigned int remote:1, /* login -h */
122 nohost:1, /* login -H */
123 noauth:1, /* login -f */
124 keep_env:1; /* login -p */
125 };
126
127 /*
128 * This bounds the time given to login. Not a define, so it can
129 * be patched on machines where it's too small.
130 */
131 static unsigned int timeout = LOGIN_TIMEOUT;
132 static int child_pid = 0;
133 static volatile int got_sig = 0;
134
135 #ifdef LOGIN_CHOWN_VCS
136 /* true if the filedescriptor fd is a console tty, very Linux specific */
137 static int is_consoletty(int fd)
138 {
139 struct stat stb;
140
141 if ((fstat(fd, &stb) >= 0)
142 && (major(stb.st_rdev) == TTY_MAJOR)
143 && (minor(stb.st_rdev) < 64)) {
144 return 1;
145 }
146 return 0;
147 }
148 #endif
149
150
151 /*
152 * Robert Ambrose writes:
153 * A couple of my users have a problem with login processes hanging around
154 * soaking up pts's. What they seem to hung up on is trying to write out the
155 * message 'Login timed out after %d seconds' when the connection has already
156 * been dropped.
157 * What I did was add a second timeout while trying to write the message, so
158 * the process just exits if the second timeout expires.
159 */
160 static void __attribute__ ((__noreturn__))
161 timedout2(int sig __attribute__ ((__unused__)))
162 {
163 struct termios ti;
164
165 /* reset echo */
166 tcgetattr(0, &ti);
167 ti.c_lflag |= ECHO;
168 tcsetattr(0, TCSANOW, &ti);
169 exit(EXIT_SUCCESS); /* %% */
170 }
171
172 static void timedout(int sig __attribute__ ((__unused__)))
173 {
174 signal(SIGALRM, timedout2);
175 alarm(10);
176 /* TRANSLATORS: The standard value for %u is 60. */
177 warnx(_("timed out after %u seconds"), timeout);
178 signal(SIGALRM, SIG_IGN);
179 alarm(0);
180 timedout2(0);
181 }
182
183 /*
184 * This handler allows to inform a shell about signals to login. If you have
185 * (root) permissions, you can kill all login children by one signal to the
186 * login process.
187 *
188 * Also, a parent who is session leader is able (before setsid() in the child)
189 * to inform the child when the controlling tty goes away (e.g. modem hangup).
190 */
191 static void sig_handler(int signal)
192 {
193 if (child_pid)
194 kill(-child_pid, signal);
195 else
196 got_sig = 1;
197 if (signal == SIGTERM)
198 kill(-child_pid, SIGHUP); /* because the shell often ignores SIGTERM */
199 }
200
201 /*
202 * Let us delay all exit() calls when the user is not authenticated
203 * or the session not fully initialized (loginpam_session()).
204 */
205 static void __attribute__ ((__noreturn__)) sleepexit(int eval)
206 {
207 sleep((unsigned int)getlogindefs_num("FAIL_DELAY", LOGIN_EXIT_TIMEOUT));
208 exit(eval);
209 }
210
211 static const char *get_thishost(struct login_context *cxt, const char **domain)
212 {
213 if (!cxt->thishost) {
214 cxt->thishost = xgethostname();
215 if (!cxt->thishost) {
216 if (domain)
217 *domain = NULL;
218 return NULL;
219 }
220 cxt->thisdomain = strchr(cxt->thishost, '.');
221 if (cxt->thisdomain)
222 *cxt->thisdomain++ = '\0';
223 }
224
225 if (domain)
226 *domain = cxt->thisdomain;
227 return cxt->thishost;
228 }
229
230 /*
231 * Output the /etc/motd file.
232 *
233 * It determines the name of a login announcement file and outputs it to the
234 * user's terminal at login time. The MOTD_FILE configuration option is a
235 * colon-delimited list of filenames. An empty MOTD_FILE option disables
236 * message-of-the-day printing completely.
237 */
238 static void motd(void)
239 {
240 char *motdlist, *motdfile;
241 const char *mb;
242
243 mb = getlogindefs_str("MOTD_FILE", _PATH_MOTDFILE);
244 if (!mb || !*mb)
245 return;
246
247 motdlist = xstrdup(mb);
248
249 for (motdfile = strtok(motdlist, ":"); motdfile;
250 motdfile = strtok(NULL, ":")) {
251
252 struct stat st;
253 int fd;
254
255 if (stat(motdfile, &st) || !st.st_size)
256 continue;
257 fd = open(motdfile, O_RDONLY, 0);
258 if (fd < 0)
259 continue;
260
261 sendfile(fileno(stdout), fd, NULL, st.st_size);
262 close(fd);
263 }
264
265 free(motdlist);
266 }
267
268 /*
269 * Nice and simple code provided by Linus Torvalds 16-Feb-93.
270 * Non-blocking stuff by Maciej W. Rozycki, macro@ds2.pg.gda.pl, 1999.
271 *
272 * He writes: "Login performs open() on a tty in a blocking mode.
273 * In some cases it may make login wait in open() for carrier infinitely,
274 * for example if the line is a simplistic case of a three-wire serial
275 * connection. I believe login should open the line in non-blocking mode,
276 * leaving the decision to make a connection to getty (where it actually
277 * belongs)."
278 */
279 static void open_tty(const char *tty)
280 {
281 int i, fd, flags;
282
283 fd = open(tty, O_RDWR | O_NONBLOCK);
284 if (fd == -1) {
285 syslog(LOG_ERR, _("FATAL: can't reopen tty: %m"));
286 sleepexit(EXIT_FAILURE);
287 }
288
289 if (!isatty(fd)) {
290 close(fd);
291 syslog(LOG_ERR, _("FATAL: %s is not a terminal"), tty);
292 sleepexit(EXIT_FAILURE);
293 }
294
295 flags = fcntl(fd, F_GETFL);
296 flags &= ~O_NONBLOCK;
297 fcntl(fd, F_SETFL, flags);
298
299 for (i = 0; i < fd; i++)
300 close(i);
301 for (i = 0; i < 3; i++)
302 if (fd != i)
303 dup2(fd, i);
304 if (fd >= 3)
305 close(fd);
306 }
307
308 #define chown_err(_what, _uid, _gid) \
309 syslog(LOG_ERR, _("chown (%s, %lu, %lu) failed: %m"), \
310 (_what), (unsigned long) (_uid), (unsigned long) (_gid))
311
312 #define chmod_err(_what, _mode) \
313 syslog(LOG_ERR, _("chmod (%s, %u) failed: %m"), (_what), (_mode))
314
315 static void chown_tty(struct login_context *cxt)
316 {
317 const char *grname;
318 uid_t uid = cxt->pwd->pw_uid;
319 gid_t gid = cxt->pwd->pw_gid;
320
321 grname = getlogindefs_str("TTYGROUP", TTYGRPNAME);
322 if (grname && *grname) {
323 struct group *gr = getgrnam(grname);
324 if (gr) /* group by name */
325 gid = gr->gr_gid;
326 else /* group by ID */
327 gid = (gid_t) getlogindefs_num("TTYGROUP", gid);
328 }
329 if (fchown(0, uid, gid)) /* tty */
330 chown_err(cxt->tty_name, uid, gid);
331 if (fchmod(0, cxt->tty_mode))
332 chmod_err(cxt->tty_name, cxt->tty_mode);
333
334 #ifdef LOGIN_CHOWN_VCS
335 if (is_consoletty(0)) {
336 if (chown(cxt->vcsn, uid, gid)) /* vcs */
337 chown_err(cxt->vcsn, uid, gid);
338 if (chmod(cxt->vcsn, cxt->tty_mode))
339 chmod_err(cxt->vcsn, cxt->tty_mode);
340
341 if (chown(cxt->vcsan, uid, gid)) /* vcsa */
342 chown_err(cxt->vcsan, uid, gid);
343 if (chmod(cxt->vcsan, cxt->tty_mode))
344 chmod_err(cxt->vcsan, cxt->tty_mode);
345 }
346 #endif
347 }
348
349 /*
350 * Reads the currect terminal path and initializes cxt->tty_* variables.
351 */
352 static void init_tty(struct login_context *cxt)
353 {
354 struct stat st;
355 struct termios tt, ttt;
356
357 cxt->tty_mode = (mode_t) getlogindefs_num("TTYPERM", TTY_MODE);
358
359 get_terminal_name(0, &cxt->tty_path, &cxt->tty_name, &cxt->tty_number);
360
361 /*
362 * In case login is suid it was possible to use a hardlink as stdin
363 * and exploit races for a local root exploit. (Wojciech Purczynski).
364 *
365 * More precisely, the problem is ttyn := ttyname(0); ...; chown(ttyn);
366 * here ttyname() might return "/tmp/x", a hardlink to a pseudotty.
367 * All of this is a problem only when login is suid, which it isn't.
368 */
369 if (!cxt->tty_path || !*cxt->tty_path ||
370 lstat(cxt->tty_path, &st) != 0 || !S_ISCHR(st.st_mode) ||
371 (st.st_nlink > 1 && strncmp(cxt->tty_path, "/dev/", 5)) ||
372 access(cxt->tty_path, R_OK | W_OK) != 0) {
373
374 syslog(LOG_ERR, _("FATAL: bad tty"));
375 sleepexit(EXIT_FAILURE);
376 }
377
378 #ifdef LOGIN_CHOWN_VCS
379 if (cxt->tty_number) {
380 /* find names of Virtual Console devices, for later mode change */
381 snprintf(cxt->vcsn, sizeof(cxt->vcsn), "/dev/vcs%s", cxt->tty_number);
382 snprintf(cxt->vcsan, sizeof(cxt->vcsan), "/dev/vcsa%s", cxt->tty_number);
383 }
384 #endif
385
386 tcgetattr(0, &tt);
387 ttt = tt;
388 ttt.c_cflag &= ~HUPCL;
389
390 if ((fchown(0, 0, 0) || fchmod(0, cxt->tty_mode)) && errno != EROFS) {
391
392 syslog(LOG_ERR, _("FATAL: %s: change permissions failed: %m"),
393 cxt->tty_path);
394 sleepexit(EXIT_FAILURE);
395 }
396
397 /* Kill processes left on this tty */
398 tcsetattr(0, TCSANOW, &ttt);
399
400 /*
401 * Let's close file decriptors before vhangup
402 * https://lkml.org/lkml/2012/6/5/145
403 */
404 close(STDIN_FILENO);
405 close(STDOUT_FILENO);
406 close(STDERR_FILENO);
407
408 signal(SIGHUP, SIG_IGN); /* so vhangup() wont kill us */
409 vhangup();
410 signal(SIGHUP, SIG_DFL);
411
412 /* open stdin,stdout,stderr to the tty */
413 open_tty(cxt->tty_path);
414
415 /* restore tty modes */
416 tcsetattr(0, TCSAFLUSH, &tt);
417 }
418
419
420 /*
421 * Logs failed login attempts in _PATH_BTMP, if it exists.
422 * Must be called only with username the name of an actual user.
423 * The most common login failure is to give password instead of username.
424 */
425 static void log_btmp(struct login_context *cxt)
426 {
427 struct utmp ut;
428 struct timeval tv;
429
430 memset(&ut, 0, sizeof(ut));
431
432 strncpy(ut.ut_user,
433 cxt->username ? cxt->username : "(unknown)",
434 sizeof(ut.ut_user));
435
436 if (cxt->tty_number)
437 strncpy(ut.ut_id, cxt->tty_number, sizeof(ut.ut_id));
438 if (cxt->tty_name)
439 xstrncpy(ut.ut_line, cxt->tty_name, sizeof(ut.ut_line));
440
441 #if defined(_HAVE_UT_TV) /* in <utmpbits.h> included by <utmp.h> */
442 gettimeofday(&tv, NULL);
443 ut.ut_tv.tv_sec = tv.tv_sec;
444 ut.ut_tv.tv_usec = tv.tv_usec;
445 #else
446 {
447 time_t t;
448 time(&t);
449 ut.ut_time = t; /* ut_time is not always a time_t */
450 }
451 #endif
452
453 ut.ut_type = LOGIN_PROCESS; /* XXX doesn't matter */
454 ut.ut_pid = cxt->pid;
455
456 if (cxt->hostname) {
457 xstrncpy(ut.ut_host, cxt->hostname, sizeof(ut.ut_host));
458 if (*cxt->hostaddress)
459 memcpy(&ut.ut_addr_v6, cxt->hostaddress,
460 sizeof(ut.ut_addr_v6));
461 }
462
463 updwtmp(_PATH_BTMP, &ut);
464 }
465
466
467 #ifdef HAVE_LIBAUDIT
468 static void log_audit(struct login_context *cxt, int status)
469 {
470 int audit_fd;
471 struct passwd *pwd = cxt->pwd;
472
473 audit_fd = audit_open();
474 if (audit_fd == -1)
475 return;
476 if (!pwd && cxt->username)
477 pwd = getpwnam(cxt->username);
478
479 audit_log_acct_message(audit_fd,
480 AUDIT_USER_LOGIN,
481 NULL,
482 "login",
483 cxt->username ? cxt->username : "(unknown)",
484 pwd ? pwd->pw_uid : (unsigned int) -1,
485 cxt->hostname,
486 NULL,
487 cxt->tty_name,
488 status);
489
490 close(audit_fd);
491 }
492 #else /* !HAVE_LIBAUDIT */
493 # define log_audit(cxt, status)
494 #endif /* HAVE_LIBAUDIT */
495
496 static void log_lastlog(struct login_context *cxt)
497 {
498 struct lastlog ll;
499 time_t t;
500 int fd;
501
502 if (!cxt->pwd)
503 return;
504
505 fd = open(_PATH_LASTLOG, O_RDWR, 0);
506 if (fd < 0)
507 return;
508
509 if (lseek(fd, (off_t) cxt->pwd->pw_uid * sizeof(ll), SEEK_SET) == -1)
510 goto done;
511
512 /*
513 * Print last log message.
514 */
515 if (!cxt->quiet) {
516 if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
517 ll.ll_time != 0) {
518 time_t ll_time = (time_t) ll.ll_time;
519
520 printf(_("Last login: %.*s "), 24 - 5, ctime(&ll_time));
521 if (*ll.ll_host != '\0')
522 printf(_("from %.*s\n"),
523 (int)sizeof(ll.ll_host), ll.ll_host);
524 else
525 printf(_("on %.*s\n"),
526 (int)sizeof(ll.ll_line), ll.ll_line);
527 }
528 if (lseek(fd, (off_t) cxt->pwd->pw_uid * sizeof(ll), SEEK_SET) == -1)
529 goto done;
530 }
531
532 memset((char *)&ll, 0, sizeof(ll));
533
534 time(&t);
535 ll.ll_time = t; /* ll_time is always 32bit */
536
537 if (cxt->tty_name)
538 xstrncpy(ll.ll_line, cxt->tty_name, sizeof(ll.ll_line));
539 if (cxt->hostname)
540 xstrncpy(ll.ll_host, cxt->hostname, sizeof(ll.ll_host));
541
542 if (write_all(fd, (char *)&ll, sizeof(ll)))
543 warn(_("write lastlog failed"));
544 done:
545 close(fd);
546 }
547
548 /*
549 * Update wtmp and utmp logs.
550 */
551 static void log_utmp(struct login_context *cxt)
552 {
553 struct utmp ut;
554 struct utmp *utp;
555 struct timeval tv;
556
557 utmpname(_PATH_UTMP);
558 setutent();
559
560 /* Find pid in utmp.
561 *
562 * login sometimes overwrites the runlevel entry in /var/run/utmp,
563 * confusing sysvinit. I added a test for the entry type, and the
564 * problem was gone. (In a runlevel entry, st_pid is not really a pid
565 * but some number calculated from the previous and current runlevel.)
566 * -- Michael Riepe <michael@stud.uni-hannover.de>
567 */
568 while ((utp = getutent()))
569 if (utp->ut_pid == cxt->pid
570 && utp->ut_type >= INIT_PROCESS
571 && utp->ut_type <= DEAD_PROCESS)
572 break;
573
574 /* If we can't find a pre-existing entry by pid, try by line.
575 * BSD network daemons may rely on this. */
576 if (utp == NULL && cxt->tty_name) {
577 setutent();
578 ut.ut_type = LOGIN_PROCESS;
579 strncpy(ut.ut_line, cxt->tty_name, sizeof(ut.ut_line));
580 utp = getutline(&ut);
581 }
582
583 /* If we can't find a pre-existing entry by pid and line, try it by id.
584 * Very stupid telnetd daemons don't set up utmp at all. (kzak) */
585 if (utp == NULL && cxt->tty_number) {
586 setutent();
587 ut.ut_type = DEAD_PROCESS;
588 strncpy(ut.ut_id, cxt->tty_number, sizeof(ut.ut_id));
589 utp = getutid(&ut);
590 }
591
592 if (utp)
593 memcpy(&ut, utp, sizeof(ut));
594 else
595 /* some gettys/telnetds don't initialize utmp... */
596 memset(&ut, 0, sizeof(ut));
597
598 if (cxt->tty_number && ut.ut_id[0] == 0)
599 strncpy(ut.ut_id, cxt->tty_number, sizeof(ut.ut_id));
600 if (cxt->username)
601 strncpy(ut.ut_user, cxt->username, sizeof(ut.ut_user));
602 if (cxt->tty_name)
603 xstrncpy(ut.ut_line, cxt->tty_name, sizeof(ut.ut_line));
604
605 #ifdef _HAVE_UT_TV /* in <utmpbits.h> included by <utmp.h> */
606 gettimeofday(&tv, NULL);
607 ut.ut_tv.tv_sec = tv.tv_sec;
608 ut.ut_tv.tv_usec = tv.tv_usec;
609 #else
610 {
611 time_t t;
612 time(&t);
613 ut.ut_time = t; /* ut_time is not always a time_t */
614 /* glibc2 #defines it as ut_tv.tv_sec */
615 }
616 #endif
617 ut.ut_type = USER_PROCESS;
618 ut.ut_pid = cxt->pid;
619 if (cxt->hostname) {
620 xstrncpy(ut.ut_host, cxt->hostname, sizeof(ut.ut_host));
621 if (*cxt->hostaddress)
622 memcpy(&ut.ut_addr_v6, cxt->hostaddress,
623 sizeof(ut.ut_addr_v6));
624 }
625
626 pututline(&ut);
627 endutent();
628
629 updwtmp(_PATH_WTMP, &ut);
630 }
631
632 static void log_syslog(struct login_context *cxt)
633 {
634 struct passwd *pwd = cxt->pwd;
635
636 if (!cxt->tty_name)
637 return;
638
639 if (!strncmp(cxt->tty_name, "ttyS", 4))
640 syslog(LOG_INFO, _("DIALUP AT %s BY %s"),
641 cxt->tty_name, pwd->pw_name);
642
643 if (!pwd->pw_uid) {
644 if (cxt->hostname)
645 syslog(LOG_NOTICE, _("ROOT LOGIN ON %s FROM %s"),
646 cxt->tty_name, cxt->hostname);
647 else
648 syslog(LOG_NOTICE, _("ROOT LOGIN ON %s"), cxt->tty_name);
649 } else {
650 if (cxt->hostname)
651 syslog(LOG_INFO, _("LOGIN ON %s BY %s FROM %s"),
652 cxt->tty_name, pwd->pw_name, cxt->hostname);
653 else
654 syslog(LOG_INFO, _("LOGIN ON %s BY %s"), cxt->tty_name,
655 pwd->pw_name);
656 }
657 }
658
659 static struct passwd *get_passwd_entry(const char *username,
660 char **pwdbuf,
661 struct passwd *pwd)
662 {
663 struct passwd *res = NULL;
664 size_t sz = 16384;
665 int x;
666
667 if (!pwdbuf || !username)
668 return NULL;
669
670 #ifdef _SC_GETPW_R_SIZE_MAX
671 {
672 long xsz = sysconf(_SC_GETPW_R_SIZE_MAX);
673 if (xsz > 0)
674 sz = (size_t) xsz;
675 }
676 #endif
677 *pwdbuf = xrealloc(*pwdbuf, sz);
678
679 x = getpwnam_r(username, pwd, *pwdbuf, sz, &res);
680 if (!res) {
681 errno = x;
682 return NULL;
683 }
684 return res;
685 }
686
687 /* encapsulate stupid "void **" pam_get_item() API */
688 static int loginpam_get_username(pam_handle_t *pamh, char **name)
689 {
690 const void *item = (void *)*name;
691 int rc;
692 rc = pam_get_item(pamh, PAM_USER, &item);
693 *name = (char *)item;
694 return rc;
695 }
696
697 static void loginpam_err(pam_handle_t *pamh, int retcode)
698 {
699 const char *msg = pam_strerror(pamh, retcode);
700
701 if (msg) {
702 fprintf(stderr, "\n%s\n", msg);
703 syslog(LOG_ERR, "%s", msg);
704 }
705 pam_end(pamh, retcode);
706 sleepexit(EXIT_FAILURE);
707 }
708
709 /*
710 * Composes "<host> login: " string; or returns "login: " if -H is given.
711 */
712 static const char *loginpam_get_prompt(struct login_context *cxt)
713 {
714 const char *host;
715 char *prompt, *dflt_prompt = _("login: ");
716 size_t sz;
717
718 if (cxt->nohost || !(host = get_thishost(cxt, NULL)))
719 return dflt_prompt;
720
721 sz = strlen(host) + 1 + strlen(dflt_prompt) + 1;
722
723 prompt = xmalloc(sz);
724 snprintf(prompt, sz, "%s %s", host, dflt_prompt);
725
726 return prompt;
727 }
728
729 static pam_handle_t *init_loginpam(struct login_context *cxt)
730 {
731 pam_handle_t *pamh = NULL;
732 int rc;
733
734 /*
735 * username is initialized to NULL and if specified on the command line
736 * it is set. Therefore, we are safe not setting it to anything.
737 */
738 rc = pam_start(cxt->remote ? "remote" : "login",
739 cxt->username, &cxt->conv, &pamh);
740 if (rc != PAM_SUCCESS) {
741 warnx(_("PAM failure, aborting: %s"), pam_strerror(pamh, rc));
742 syslog(LOG_ERR, _("Couldn't initialize PAM: %s"),
743 pam_strerror(pamh, rc));
744 sleepexit(EXIT_FAILURE);
745 }
746
747 /* hostname & tty are either set to NULL or their correct values,
748 * depending on how much we know. */
749 rc = pam_set_item(pamh, PAM_RHOST, cxt->hostname);
750 if (is_pam_failure(rc))
751 loginpam_err(pamh, rc);
752
753 rc = pam_set_item(pamh, PAM_TTY, cxt->tty_name);
754 if (is_pam_failure(rc))
755 loginpam_err(pamh, rc);
756
757 /*
758 * Andrew.Taylor@cal.montage.ca: Provide a user prompt to PAM so that
759 * the "login: " prompt gets localized. Unfortunately, PAM doesn't have
760 * an interface to specify the "Password: " string (yet).
761 */
762 rc = pam_set_item(pamh, PAM_USER_PROMPT, loginpam_get_prompt(cxt));
763 if (is_pam_failure(rc))
764 loginpam_err(pamh, rc);
765
766 /* We don't need the original username. We have to follow PAM. */
767 free(cxt->username);
768 cxt->username = NULL;
769 cxt->pamh = pamh;
770
771 return pamh;
772 }
773
774 static void loginpam_auth(struct login_context *cxt)
775 {
776 int rc, show_unknown;
777 unsigned int retries, failcount = 0;
778 const char *hostname = cxt->hostname ? cxt->hostname :
779 cxt->tty_name ? cxt->tty_name : "<unknown>";
780 pam_handle_t *pamh = cxt->pamh;
781
782 /* if we didn't get a user on the command line, set it to NULL */
783 loginpam_get_username(pamh, &cxt->username);
784
785 show_unknown = getlogindefs_bool("LOG_UNKFAIL_ENAB", 0);
786 retries = getlogindefs_num("LOGIN_RETRIES", LOGIN_MAX_TRIES);
787
788 /*
789 * There may be better ways to deal with some of these conditions, but
790 * at least this way I don't think we'll be giving away information...
791 *
792 * Perhaps someday we can trust that all PAM modules will pay attention
793 * to failure count and get rid of LOGIN_MAX_TRIES?
794 */
795 rc = pam_authenticate(pamh, 0);
796
797 while ((++failcount < retries) &&
798 ((rc == PAM_AUTH_ERR) ||
799 (rc == PAM_USER_UNKNOWN) ||
800 (rc == PAM_CRED_INSUFFICIENT) ||
801 (rc == PAM_AUTHINFO_UNAVAIL))) {
802
803 if (rc == PAM_USER_UNKNOWN && !show_unknown)
804 /*
805 * Logging unknown usernames may be a security issue if
806 * a user enters her password instead of her login name.
807 */
808 cxt->username = NULL;
809 else
810 loginpam_get_username(pamh, &cxt->username);
811
812 syslog(LOG_NOTICE,
813 _("FAILED LOGIN %u FROM %s FOR %s, %s"),
814 failcount, hostname,
815 cxt->username ? cxt->username : "(unknown)",
816 pam_strerror(pamh, rc));
817
818 log_btmp(cxt);
819 log_audit(cxt, 0);
820
821 fprintf(stderr, _("Login incorrect\n\n"));
822
823 pam_set_item(pamh, PAM_USER, NULL);
824 rc = pam_authenticate(pamh, 0);
825 }
826
827 if (is_pam_failure(rc)) {
828
829 if (rc == PAM_USER_UNKNOWN && !show_unknown)
830 cxt->username = NULL;
831 else
832 loginpam_get_username(pamh, &cxt->username);
833
834 if (rc == PAM_MAXTRIES)
835 syslog(LOG_NOTICE,
836 _("TOO MANY LOGIN TRIES (%u) FROM %s FOR %s, %s"),
837 failcount, hostname,
838 cxt->username ? cxt->username : "(unknown)",
839 pam_strerror(pamh, rc));
840 else
841 syslog(LOG_NOTICE,
842 _("FAILED LOGIN SESSION FROM %s FOR %s, %s"),
843 hostname,
844 cxt->username ? cxt->username : "(unknown)",
845 pam_strerror(pamh, rc));
846
847 log_btmp(cxt);
848 log_audit(cxt, 0);
849
850 fprintf(stderr, _("\nLogin incorrect\n"));
851 pam_end(pamh, rc);
852 sleepexit(EXIT_SUCCESS);
853 }
854 }
855
856 static void loginpam_acct(struct login_context *cxt)
857 {
858 int rc;
859 pam_handle_t *pamh = cxt->pamh;
860
861 rc = pam_acct_mgmt(pamh, 0);
862
863 if (rc == PAM_NEW_AUTHTOK_REQD)
864 rc = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
865
866 if (is_pam_failure(rc))
867 loginpam_err(pamh, rc);
868
869 /*
870 * Grab the user information out of the password file for future use.
871 * First get the username that we are actually using, though.
872 */
873 rc = loginpam_get_username(pamh, &cxt->username);
874 if (is_pam_failure(rc))
875 loginpam_err(pamh, rc);
876
877 if (!cxt->username || !*cxt->username) {
878 warnx(_("\nSession setup problem, abort."));
879 syslog(LOG_ERR, _("NULL user name in %s:%d. Abort."),
880 __FUNCTION__, __LINE__);
881 pam_end(pamh, PAM_SYSTEM_ERR);
882 sleepexit(EXIT_FAILURE);
883 }
884 }
885
886 /*
887 * Note that the position of the pam_setcred() call is discussable:
888 *
889 * - the PAM docs recommend pam_setcred() before pam_open_session()
890 * - but the original RFC http://www.opengroup.org/rfc/mirror-rfc/rfc86.0.txt
891 * uses pam_setcred() after pam_open_session()
892 *
893 * The old login versions (before year 2011) followed the RFC. This is probably
894 * not optimal, because there could be a dependence between some session modules
895 * and the user's credentials.
896 *
897 * The best is probably to follow openssh and call pam_setcred() before and
898 * after pam_open_session(). -- kzak@redhat.com (18-Nov-2011)
899 *
900 */
901 static void loginpam_session(struct login_context *cxt)
902 {
903 int rc;
904 pam_handle_t *pamh = cxt->pamh;
905
906 rc = pam_setcred(pamh, PAM_ESTABLISH_CRED);
907 if (is_pam_failure(rc))
908 loginpam_err(pamh, rc);
909
910 rc = pam_open_session(pamh, 0);
911 if (is_pam_failure(rc)) {
912 pam_setcred(cxt->pamh, PAM_DELETE_CRED);
913 loginpam_err(pamh, rc);
914 }
915
916 rc = pam_setcred(pamh, PAM_REINITIALIZE_CRED);
917 if (is_pam_failure(rc)) {
918 pam_close_session(pamh, 0);
919 loginpam_err(pamh, rc);
920 }
921 }
922
923 /*
924 * Detach the controlling terminal, fork, restore syslog stuff, and create
925 * a new session.
926 */
927 static void fork_session(struct login_context *cxt)
928 {
929 struct sigaction sa, oldsa_hup, oldsa_term;
930
931 signal(SIGALRM, SIG_DFL);
932 signal(SIGQUIT, SIG_DFL);
933 signal(SIGTSTP, SIG_IGN);
934
935 memset(&sa, 0, sizeof(sa));
936 sa.sa_handler = SIG_IGN;
937 sigaction(SIGINT, &sa, NULL);
938
939 sigaction(SIGHUP, &sa, &oldsa_hup); /* ignore when TIOCNOTTY */
940
941 /*
942 * Detach the controlling tty.
943 * We don't need the tty in a parent who only waits for a child.
944 * The child calls setsid() that detaches from the tty as well.
945 */
946 ioctl(0, TIOCNOTTY, NULL);
947
948 /*
949 * We have to beware of SIGTERM, because leaving a PAM session
950 * without pam_close_session() is a pretty bad thing.
951 */
952 sa.sa_handler = sig_handler;
953 sigaction(SIGHUP, &sa, NULL);
954 sigaction(SIGTERM, &sa, &oldsa_term);
955
956 closelog();
957
958 /*
959 * We must fork before setuid(), because we need to call
960 * pam_close_session() as root.
961 */
962 child_pid = fork();
963 if (child_pid < 0) {
964 warn(_("fork failed"));
965
966 pam_setcred(cxt->pamh, PAM_DELETE_CRED);
967 pam_end(cxt->pamh, pam_close_session(cxt->pamh, 0));
968 sleepexit(EXIT_FAILURE);
969 }
970
971 if (child_pid) {
972 /*
973 * parent - wait for child to finish, then clean up session
974 */
975 close(0);
976 close(1);
977 close(2);
978 sa.sa_handler = SIG_IGN;
979 sigaction(SIGQUIT, &sa, NULL);
980 sigaction(SIGINT, &sa, NULL);
981
982 /* wait as long as any child is there */
983 while (wait(NULL) == -1 && errno == EINTR) ;
984 openlog("login", LOG_ODELAY, LOG_AUTHPRIV);
985
986 pam_setcred(cxt->pamh, PAM_DELETE_CRED);
987 pam_end(cxt->pamh, pam_close_session(cxt->pamh, 0));
988 exit(EXIT_SUCCESS);
989 }
990
991 /*
992 * child
993 */
994 sigaction(SIGHUP, &oldsa_hup, NULL); /* restore old state */
995 sigaction(SIGTERM, &oldsa_term, NULL);
996 if (got_sig)
997 exit(EXIT_FAILURE);
998
999 /*
1000 * Problem: if the user's shell is a shell like ash that doesn't do
1001 * setsid() or setpgrp(), then a ctrl-\, sending SIGQUIT to every
1002 * process in the pgrp, will kill us.
1003 */
1004
1005 /* start new session */
1006 setsid();
1007
1008 /* make sure we have a controlling tty */
1009 open_tty(cxt->tty_path);
1010 openlog("login", LOG_ODELAY, LOG_AUTHPRIV); /* reopen */
1011
1012 /*
1013 * TIOCSCTTY: steal tty from other process group.
1014 */
1015 if (ioctl(0, TIOCSCTTY, 1))
1016 syslog(LOG_ERR, _("TIOCSCTTY failed: %m"));
1017 signal(SIGINT, SIG_DFL);
1018 }
1019
1020 /*
1021 * Initialize $TERM, $HOME, ...
1022 */
1023 static void init_environ(struct login_context *cxt)
1024 {
1025 struct passwd *pwd = cxt->pwd;
1026 char *termenv = NULL, **env;
1027 char tmp[PATH_MAX];
1028 int len, i;
1029
1030 termenv = getenv("TERM");
1031 termenv = termenv ? xstrdup(termenv) : "dumb";
1032
1033 /* destroy environment unless user has requested preservation (-p) */
1034 if (!cxt->keep_env) {
1035 environ = (char **) xmalloc(sizeof(char *));
1036 memset(environ, 0, sizeof(char *));
1037 }
1038
1039 setenv("HOME", pwd->pw_dir, 0); /* legal to override */
1040 setenv("USER", pwd->pw_name, 1);
1041 setenv("SHELL", pwd->pw_shell, 1);
1042 setenv("TERM", termenv, 1);
1043
1044 if (pwd->pw_uid)
1045 logindefs_setenv("PATH", "ENV_PATH", _PATH_DEFPATH);
1046
1047 else if (logindefs_setenv("PATH", "ENV_ROOTPATH", NULL) != 0)
1048 logindefs_setenv("PATH", "ENV_SUPATH", _PATH_DEFPATH_ROOT);
1049
1050 /* mailx will give a funny error msg if you forget this one */
1051 len = snprintf(tmp, sizeof(tmp), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
1052 if (len > 0 && (size_t) len + 1 <= sizeof(tmp))
1053 setenv("MAIL", tmp, 0);
1054
1055 /* LOGNAME is not documented in login(1) but HP-UX 6.5 does it. We'll
1056 * not allow modifying it.
1057 */
1058 setenv("LOGNAME", pwd->pw_name, 1);
1059
1060 env = pam_getenvlist(cxt->pamh);
1061 for (i = 0; env && env[i]; i++)
1062 putenv(env[i]);
1063 }
1064
1065 /*
1066 * This is called for the -h option, initializes cxt->{hostname,hostaddress}.
1067 */
1068 static void init_remote_info(struct login_context *cxt, char *remotehost)
1069 {
1070 const char *domain;
1071 char *p;
1072 struct addrinfo hints, *info = NULL;
1073
1074 cxt->remote = 1;
1075
1076 get_thishost(cxt, &domain);
1077
1078 if (domain && (p = strchr(remotehost, '.')) &&
1079 strcasecmp(p + 1, domain) == 0)
1080 *p = '\0';
1081
1082 cxt->hostname = xstrdup(remotehost);
1083
1084 memset(&hints, 0, sizeof(hints));
1085 hints.ai_flags = AI_ADDRCONFIG;
1086 cxt->hostaddress[0] = 0;
1087
1088 if (getaddrinfo(cxt->hostname, NULL, &hints, &info) == 0 && info) {
1089 if (info->ai_family == AF_INET) {
1090 struct sockaddr_in *sa =
1091 (struct sockaddr_in *) info->ai_addr;
1092
1093 memcpy(cxt->hostaddress, &(sa->sin_addr), sizeof(sa->sin_addr));
1094
1095 } else if (info->ai_family == AF_INET6) {
1096 struct sockaddr_in6 *sa =
1097 (struct sockaddr_in6 *) info->ai_addr;
1098
1099 memcpy(cxt->hostaddress, &(sa->sin6_addr), sizeof(sa->sin6_addr));
1100 }
1101 freeaddrinfo(info);
1102 }
1103 }
1104
1105 int main(int argc, char **argv)
1106 {
1107 int c;
1108 int cnt;
1109 char *childArgv[10];
1110 char *buff;
1111 int childArgc = 0;
1112 int retcode;
1113
1114 char *pwdbuf = NULL;
1115 struct passwd *pwd = NULL, _pwd;
1116
1117 struct login_context cxt = {
1118 .tty_mode = TTY_MODE, /* tty chmod() */
1119 .pid = getpid(), /* PID */
1120 .conv = { misc_conv, NULL } /* PAM conversation function */
1121 };
1122
1123 timeout = (unsigned int)getlogindefs_num("LOGIN_TIMEOUT", LOGIN_TIMEOUT);
1124
1125 signal(SIGALRM, timedout);
1126 siginterrupt(SIGALRM, 1); /* we have to interrupt syscalls like ioclt() */
1127 alarm(timeout);
1128 signal(SIGQUIT, SIG_IGN);
1129 signal(SIGINT, SIG_IGN);
1130
1131 setlocale(LC_ALL, "");
1132 bindtextdomain(PACKAGE, LOCALEDIR);
1133 textdomain(PACKAGE);
1134
1135 setpriority(PRIO_PROCESS, 0, 0);
1136 initproctitle(argc, argv);
1137
1138 /*
1139 * -p is used by getty to tell login not to destroy the environment
1140 * -f is used to skip a second login authentication
1141 * -h is used by other servers to pass the name of the remote
1142 * host to login so that it may be placed in utmp and wtmp
1143 */
1144 while ((c = getopt(argc, argv, "fHh:pV")) != -1)
1145 switch (c) {
1146 case 'f':
1147 cxt.noauth = 1;
1148 break;
1149
1150 case 'H':
1151 cxt.nohost = 1;
1152 break;
1153
1154 case 'h':
1155 if (getuid()) {
1156 fprintf(stderr,
1157 _("login: -h is for superuser only\n"));
1158 exit(EXIT_FAILURE);
1159 }
1160 init_remote_info(&cxt, optarg);
1161 break;
1162
1163 case 'p':
1164 cxt.keep_env = 1;
1165 break;
1166
1167 case 'V':
1168 printf(UTIL_LINUX_VERSION);
1169 return EXIT_SUCCESS;
1170 case '?':
1171 default:
1172 fprintf(stderr, _("Usage: login [-p] [-h <host>] [-H] [[-f] <username>]\n"));
1173 exit(EXIT_FAILURE);
1174 }
1175 argc -= optind;
1176 argv += optind;
1177
1178 if (*argv) {
1179 char *p = *argv;
1180 cxt.username = xstrdup(p);
1181
1182 /* Wipe the name - some people mistype their password here. */
1183 /* (Of course we are too late, but perhaps this helps a little...) */
1184 while (*p)
1185 *p++ = ' ';
1186 }
1187
1188 for (cnt = get_fd_tabsize() - 1; cnt > 2; cnt--)
1189 close(cnt);
1190
1191 setpgrp(); /* set pgid to pid this means that setsid() will fail */
1192 init_tty(&cxt);
1193
1194 openlog("login", LOG_ODELAY, LOG_AUTHPRIV);
1195
1196 init_loginpam(&cxt);
1197
1198 /* login -f, then the user has already been authenticated */
1199 cxt.noauth = cxt.noauth && getuid() == 0 ? 1 : 0;
1200
1201 if (!cxt.noauth)
1202 loginpam_auth(&cxt);
1203
1204 /*
1205 * Authentication may be skipped (for example, during krlogin, rlogin,
1206 * etc...), but it doesn't mean that we can skip other account checks.
1207 * The account could be disabled or the password has expired (although
1208 * the kerberos ticket is valid). -- kzak@redhat.com (22-Feb-2006)
1209 */
1210 loginpam_acct(&cxt);
1211
1212 if (!(cxt.pwd = get_passwd_entry(cxt.username, &pwdbuf, &_pwd))) {
1213 warnx(_("\nSession setup problem, abort."));
1214 syslog(LOG_ERR, _("Invalid user name \"%s\" in %s:%d. Abort."),
1215 cxt.username, __FUNCTION__, __LINE__);
1216 pam_end(cxt.pamh, PAM_SYSTEM_ERR);
1217 sleepexit(EXIT_FAILURE);
1218 }
1219
1220 pwd = cxt.pwd;
1221 cxt.username = pwd->pw_name;
1222
1223 /*
1224 * Initialize the supplementary group list. This should be done before
1225 * pam_setcred, because PAM modules might add groups during that call.
1226 *
1227 * For root we don't call initgroups, instead we call setgroups with
1228 * group 0. This avoids the need to step through the whole group file,
1229 * which can cause problems if NIS, NIS+, LDAP or something similar
1230 * is used and the machine has network problems.
1231 */
1232 retcode = pwd->pw_uid ? initgroups(cxt.username, pwd->pw_gid) : /* user */
1233 setgroups(0, NULL); /* root */
1234 if (retcode < 0) {
1235 syslog(LOG_ERR, _("groups initialization failed: %m"));
1236 warnx(_("\nSession setup problem, abort."));
1237 pam_end(cxt.pamh, PAM_SYSTEM_ERR);
1238 sleepexit(EXIT_FAILURE);
1239 }
1240
1241 /*
1242 * Open PAM session (after successful authentication and account check).
1243 */
1244 loginpam_session(&cxt);
1245
1246 /* committed to login -- turn off timeout */
1247 alarm((unsigned int)0);
1248
1249 endpwent();
1250
1251 cxt.quiet = get_hushlogin_status(pwd);
1252
1253 log_utmp(&cxt);
1254 log_audit(&cxt, 1);
1255 log_lastlog(&cxt);
1256
1257 chown_tty(&cxt);
1258
1259 if (setgid(pwd->pw_gid) < 0 && pwd->pw_gid) {
1260 syslog(LOG_ALERT, _("setgid() failed"));
1261 exit(EXIT_FAILURE);
1262 }
1263
1264 if (pwd->pw_shell == NULL || *pwd->pw_shell == '\0')
1265 pwd->pw_shell = _PATH_BSHELL;
1266
1267 init_environ(&cxt); /* init $HOME, $TERM ... */
1268
1269 setproctitle("login", cxt.username);
1270
1271 log_syslog(&cxt);
1272
1273 if (!cxt.quiet) {
1274 motd();
1275
1276 #ifdef LOGIN_STAT_MAIL
1277 /*
1278 * This turns out to be a bad idea: when the mail spool
1279 * is NFS mounted, and the NFS connection hangs, the
1280 * login hangs, even root cannot login.
1281 * Checking for mail should be done from the shell.
1282 */
1283 {
1284 struct stat st;
1285 char *mail;
1286
1287 mail = getenv("MAIL");
1288 if (mail && stat(mail, &st) == 0 && st.st_size != 0) {
1289 if (st.st_mtime > st.st_atime)
1290 printf(_("You have new mail.\n"));
1291 else
1292 printf(_("You have mail.\n"));
1293 }
1294 }
1295 #endif
1296 }
1297
1298 /*
1299 * Detach the controlling terminal, fork, and create a new session
1300 * and reinitialize syslog stuff.
1301 */
1302 fork_session(&cxt);
1303
1304 /* discard permissions last so we can't get killed and drop core */
1305 if (setuid(pwd->pw_uid) < 0 && pwd->pw_uid) {
1306 syslog(LOG_ALERT, _("setuid() failed"));
1307 exit(EXIT_FAILURE);
1308 }
1309
1310 /* wait until here to change directory! */
1311 if (chdir(pwd->pw_dir) < 0) {
1312 warn(_("%s: change directory failed"), pwd->pw_dir);
1313
1314 if (!getlogindefs_bool("DEFAULT_HOME", 1))
1315 exit(0);
1316 if (chdir("/"))
1317 exit(EXIT_FAILURE);
1318 pwd->pw_dir = "/";
1319 printf(_("Logging in with home = \"/\".\n"));
1320 }
1321
1322 /* if the shell field has a space: treat it like a shell script */
1323 if (strchr(pwd->pw_shell, ' ')) {
1324 buff = xmalloc(strlen(pwd->pw_shell) + 6);
1325
1326 strcpy(buff, "exec ");
1327 strcat(buff, pwd->pw_shell);
1328 childArgv[childArgc++] = "/bin/sh";
1329 childArgv[childArgc++] = "-sh";
1330 childArgv[childArgc++] = "-c";
1331 childArgv[childArgc++] = buff;
1332 } else {
1333 char tbuf[PATH_MAX + 2], *p;
1334
1335 tbuf[0] = '-';
1336 xstrncpy(tbuf + 1, ((p = strrchr(pwd->pw_shell, '/')) ?
1337 p + 1 : pwd->pw_shell), sizeof(tbuf) - 1);
1338
1339 childArgv[childArgc++] = pwd->pw_shell;
1340 childArgv[childArgc++] = xstrdup(tbuf);
1341 }
1342
1343 childArgv[childArgc++] = NULL;
1344
1345 execvp(childArgv[0], childArgv + 1);
1346
1347 if (!strcmp(childArgv[0], "/bin/sh"))
1348 warn(_("couldn't exec shell script"));
1349 else
1350 warn(_("no shell"));
1351
1352 exit(EXIT_SUCCESS);
1353 }