4 * This program is derived from 4.3 BSD software and is subject to the
5 * copyright notice below.
7 * Copyright (C) 2011 Karel Zak <kzak@redhat.com>
8 * Rewritten to PAM-only version.
10 * Michael Glad (glad@daimi.dk)
11 * Computer Science Department, Aarhus University, Denmark
14 * Copyright (c) 1980, 1987, 1988 The Regents of the University of California.
15 * All rights reserved.
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.
29 #include <sys/param.h>
38 #include <sys/resource.h>
42 #include <sys/ioctl.h>
53 #include <sys/syslog.h>
54 #ifdef HAVE_LINUX_MAJOR_H
55 # include <linux/major.h>
58 #include <security/pam_appl.h>
59 #ifdef HAVE_SECURITY_PAM_MISC_H
60 # include <security/pam_misc.h>
61 #elif defined(HAVE_SECURITY_OPENPAM_H)
62 # include <security/openpam.h>
64 #include <sys/sendfile.h>
67 # include <libaudit.h>
71 #include "setproctitle.h"
72 #include "pathnames.h"
78 #include "fileutils.h"
82 #include "logindefs.h"
84 #define is_pam_failure(_rc) ((_rc) != PAM_SUCCESS)
86 #define LOGIN_MAX_TRIES 3
87 #define LOGIN_EXIT_TIMEOUT 5
88 #define LOGIN_TIMEOUT 60
91 # define TTY_MODE 0620
93 # define TTY_MODE 0600
96 #define TTYGRPNAME "tty" /* name of group to own ttys */
97 #define VCS_PATH_MAX 64
100 * Login control struct
102 struct login_context
{
103 const char *tty_path
; /* ttyname() return value */
104 const char *tty_name
; /* tty_path without /dev prefix */
105 const char *tty_number
; /* end of the tty_path */
106 mode_t tty_mode
; /* chmod() mode */
108 char *username
; /* from command line or PAM */
110 struct passwd
*pwd
; /* user info */
111 char *pwdbuf
; /* pwd strings */
113 pam_handle_t
*pamh
; /* PAM handler */
114 struct pam_conv conv
; /* PAM conversation */
116 #ifdef LOGIN_CHOWN_VCS
117 char vcsn
[VCS_PATH_MAX
]; /* virtual console name */
118 char vcsan
[VCS_PATH_MAX
];
121 char *thishost
; /* this machine */
122 char *thisdomain
; /* this machine's domain */
123 char *hostname
; /* remote machine */
124 char hostaddress
[16]; /* remote address */
127 int quiet
; /* 1 if hush file exists */
129 unsigned int remote
:1, /* login -h */
130 nohost
:1, /* login -H */
131 noauth
:1, /* login -f */
132 keep_env
:1; /* login -p */
136 * This bounds the time given to login. Not a define, so it can
137 * be patched on machines where it's too small.
139 static unsigned int timeout
= LOGIN_TIMEOUT
;
140 static int child_pid
= 0;
141 static volatile int got_sig
= 0;
143 #ifdef LOGIN_CHOWN_VCS
144 /* true if the filedescriptor fd is a console tty, very Linux specific */
145 static int is_consoletty(int fd
)
149 if ((fstat(fd
, &stb
) >= 0)
150 && (major(stb
.st_rdev
) == TTY_MAJOR
)
151 && (minor(stb
.st_rdev
) < 64)) {
160 * Robert Ambrose writes:
161 * A couple of my users have a problem with login processes hanging around
162 * soaking up pts's. What they seem to hung up on is trying to write out the
163 * message 'Login timed out after %d seconds' when the connection has already
165 * What I did was add a second timeout while trying to write the message, so
166 * the process just exits if the second timeout expires.
168 static void __attribute__ ((__noreturn__
))
169 timedout2(int sig
__attribute__ ((__unused__
)))
176 tcsetattr(0, TCSANOW
, &ti
);
177 exit(EXIT_SUCCESS
); /* %% */
180 static void timedout(int sig
__attribute__ ((__unused__
)))
182 signal(SIGALRM
, timedout2
);
184 /* TRANSLATORS: The standard value for %u is 60. */
185 warnx(_("timed out after %u seconds"), timeout
);
186 signal(SIGALRM
, SIG_IGN
);
192 * This handler allows to inform a shell about signals to login. If you have
193 * (root) permissions, you can kill all login children by one signal to the
196 * Also, a parent who is session leader is able (before setsid() in the child)
197 * to inform the child when the controlling tty goes away (e.g. modem hangup).
199 static void sig_handler(int signal
)
202 kill(-child_pid
, signal
);
205 if (signal
== SIGTERM
)
206 kill(-child_pid
, SIGHUP
); /* because the shell often ignores SIGTERM */
210 * Let us delay all exit() calls when the user is not authenticated
211 * or the session not fully initialized (loginpam_session()).
213 static void __attribute__ ((__noreturn__
)) sleepexit(int eval
)
215 sleep((unsigned int)getlogindefs_num("FAIL_DELAY", LOGIN_EXIT_TIMEOUT
));
219 static const char *get_thishost(struct login_context
*cxt
, const char **domain
)
221 if (!cxt
->thishost
) {
222 cxt
->thishost
= xgethostname();
223 if (!cxt
->thishost
) {
228 cxt
->thisdomain
= strchr(cxt
->thishost
, '.');
230 *cxt
->thisdomain
++ = '\0';
234 *domain
= cxt
->thisdomain
;
235 return cxt
->thishost
;
239 * Output the /etc/motd file.
241 * It determines the name of a login announcement file and outputs it to the
242 * user's terminal at login time. The MOTD_FILE configuration option is a
243 * colon-delimited list of filenames. An empty MOTD_FILE option disables
244 * message-of-the-day printing completely.
246 static void motd(void)
248 char *motdlist
, *motdfile
;
251 mb
= getlogindefs_str("MOTD_FILE", _PATH_MOTDFILE
);
255 motdlist
= xstrdup(mb
);
257 for (motdfile
= strtok(motdlist
, ":"); motdfile
;
258 motdfile
= strtok(NULL
, ":")) {
263 fd
= open(motdfile
, O_RDONLY
, 0);
266 if (!fstat(fd
, &st
) && st
.st_size
)
267 sendfile(fileno(stdout
), fd
, NULL
, st
.st_size
);
275 * Nice and simple code provided by Linus Torvalds 16-Feb-93.
276 * Non-blocking stuff by Maciej W. Rozycki, macro@ds2.pg.gda.pl, 1999.
278 * He writes: "Login performs open() on a tty in a blocking mode.
279 * In some cases it may make login wait in open() for carrier infinitely,
280 * for example if the line is a simplistic case of a three-wire serial
281 * connection. I believe login should open the line in non-blocking mode,
282 * leaving the decision to make a connection to getty (where it actually
285 static void open_tty(const char *tty
)
289 fd
= open(tty
, O_RDWR
| O_NONBLOCK
);
291 syslog(LOG_ERR
, _("FATAL: can't reopen tty: %m"));
292 sleepexit(EXIT_FAILURE
);
297 syslog(LOG_ERR
, _("FATAL: %s is not a terminal"), tty
);
298 sleepexit(EXIT_FAILURE
);
301 flags
= fcntl(fd
, F_GETFL
);
302 flags
&= ~O_NONBLOCK
;
303 fcntl(fd
, F_SETFL
, flags
);
305 for (i
= 0; i
< fd
; i
++)
307 for (i
= 0; i
< 3; i
++)
314 #define chown_err(_what, _uid, _gid) \
315 syslog(LOG_ERR, _("chown (%s, %lu, %lu) failed: %m"), \
316 (_what), (unsigned long) (_uid), (unsigned long) (_gid))
318 #define chmod_err(_what, _mode) \
319 syslog(LOG_ERR, _("chmod (%s, %u) failed: %m"), (_what), (_mode))
321 static void chown_tty(struct login_context
*cxt
)
324 uid_t uid
= cxt
->pwd
->pw_uid
;
325 gid_t gid
= cxt
->pwd
->pw_gid
;
327 grname
= getlogindefs_str("TTYGROUP", TTYGRPNAME
);
328 if (grname
&& *grname
) {
329 struct group
*gr
= getgrnam(grname
);
330 if (gr
) /* group by name */
332 else /* group by ID */
333 gid
= (gid_t
) getlogindefs_num("TTYGROUP", gid
);
335 if (fchown(0, uid
, gid
)) /* tty */
336 chown_err(cxt
->tty_name
, uid
, gid
);
337 if (fchmod(0, cxt
->tty_mode
))
338 chmod_err(cxt
->tty_name
, cxt
->tty_mode
);
340 #ifdef LOGIN_CHOWN_VCS
341 if (is_consoletty(0)) {
342 if (chown(cxt
->vcsn
, uid
, gid
)) /* vcs */
343 chown_err(cxt
->vcsn
, uid
, gid
);
344 if (chmod(cxt
->vcsn
, cxt
->tty_mode
))
345 chmod_err(cxt
->vcsn
, cxt
->tty_mode
);
347 if (chown(cxt
->vcsan
, uid
, gid
)) /* vcsa */
348 chown_err(cxt
->vcsan
, uid
, gid
);
349 if (chmod(cxt
->vcsan
, cxt
->tty_mode
))
350 chmod_err(cxt
->vcsan
, cxt
->tty_mode
);
356 * Reads the current terminal path and initializes cxt->tty_* variables.
358 static void init_tty(struct login_context
*cxt
)
361 struct termios tt
, ttt
;
363 cxt
->tty_mode
= (mode_t
) getlogindefs_num("TTYPERM", TTY_MODE
);
365 get_terminal_name(&cxt
->tty_path
, &cxt
->tty_name
, &cxt
->tty_number
);
368 * In case login is suid it was possible to use a hardlink as stdin
369 * and exploit races for a local root exploit. (Wojciech Purczynski).
371 * More precisely, the problem is ttyn := ttyname(0); ...; chown(ttyn);
372 * here ttyname() might return "/tmp/x", a hardlink to a pseudotty.
373 * All of this is a problem only when login is suid, which it isn't.
375 if (!cxt
->tty_path
|| !*cxt
->tty_path
||
376 lstat(cxt
->tty_path
, &st
) != 0 || !S_ISCHR(st
.st_mode
) ||
377 (st
.st_nlink
> 1 && strncmp(cxt
->tty_path
, "/dev/", 5)) ||
378 access(cxt
->tty_path
, R_OK
| W_OK
) != 0) {
380 syslog(LOG_ERR
, _("FATAL: bad tty"));
381 sleepexit(EXIT_FAILURE
);
384 #ifdef LOGIN_CHOWN_VCS
385 if (cxt
->tty_number
) {
386 /* find names of Virtual Console devices, for later mode change */
387 snprintf(cxt
->vcsn
, sizeof(cxt
->vcsn
), "/dev/vcs%s", cxt
->tty_number
);
388 snprintf(cxt
->vcsan
, sizeof(cxt
->vcsan
), "/dev/vcsa%s", cxt
->tty_number
);
394 ttt
.c_cflag
&= ~HUPCL
;
396 if ((fchown(0, 0, 0) || fchmod(0, cxt
->tty_mode
)) && errno
!= EROFS
) {
398 syslog(LOG_ERR
, _("FATAL: %s: change permissions failed: %m"),
400 sleepexit(EXIT_FAILURE
);
403 /* Kill processes left on this tty */
404 tcsetattr(0, TCSANOW
, &ttt
);
407 * Let's close file descriptors before vhangup
408 * https://lkml.org/lkml/2012/6/5/145
411 close(STDOUT_FILENO
);
412 close(STDERR_FILENO
);
414 signal(SIGHUP
, SIG_IGN
); /* so vhangup() won't kill us */
416 signal(SIGHUP
, SIG_DFL
);
418 /* open stdin,stdout,stderr to the tty */
419 open_tty(cxt
->tty_path
);
421 /* restore tty modes */
422 tcsetattr(0, TCSAFLUSH
, &tt
);
427 * Logs failed login attempts in _PATH_BTMP, if it exists.
428 * Must be called only with username the name of an actual user.
429 * The most common login failure is to give password instead of username.
431 static void log_btmp(struct login_context
*cxt
)
436 memset(&ut
, 0, sizeof(ut
));
439 cxt
->username
? cxt
->username
: "(unknown)",
443 strncpy(ut
.ut_id
, cxt
->tty_number
, sizeof(ut
.ut_id
));
445 xstrncpy(ut
.ut_line
, cxt
->tty_name
, sizeof(ut
.ut_line
));
447 gettimeofday(&tv
, NULL
);
448 ut
.ut_tv
.tv_sec
= tv
.tv_sec
;
449 ut
.ut_tv
.tv_usec
= tv
.tv_usec
;
451 ut
.ut_type
= LOGIN_PROCESS
; /* XXX doesn't matter */
452 ut
.ut_pid
= cxt
->pid
;
455 xstrncpy(ut
.ut_host
, cxt
->hostname
, sizeof(ut
.ut_host
));
456 if (*cxt
->hostaddress
)
457 memcpy(&ut
.ut_addr_v6
, cxt
->hostaddress
,
458 sizeof(ut
.ut_addr_v6
));
461 updwtmpx(_PATH_BTMP
, &ut
);
466 static void log_audit(struct login_context
*cxt
, int status
)
469 struct passwd
*pwd
= cxt
->pwd
;
471 audit_fd
= audit_open();
474 if (!pwd
&& cxt
->username
)
475 pwd
= getpwnam(cxt
->username
);
477 audit_log_acct_message(audit_fd
,
481 cxt
->username
? cxt
->username
: "(unknown)",
482 pwd
? pwd
->pw_uid
: (unsigned int) -1,
490 #else /* !HAVE_LIBAUDIT */
491 # define log_audit(cxt, status)
492 #endif /* HAVE_LIBAUDIT */
494 static void log_lastlog(struct login_context
*cxt
)
496 struct sigaction sa
, oldsa_xfsz
;
504 /* lastlog is huge on systems with large UIDs, ignore SIGXFSZ */
505 memset(&sa
, 0, sizeof(sa
));
506 sa
.sa_handler
= SIG_IGN
;
507 sigaction(SIGXFSZ
, &sa
, &oldsa_xfsz
);
509 fd
= open(_PATH_LASTLOG
, O_RDWR
, 0);
513 if (lseek(fd
, (off_t
) cxt
->pwd
->pw_uid
* sizeof(ll
), SEEK_SET
) == -1)
517 * Print last log message.
520 if (read(fd
, (char *)&ll
, sizeof(ll
)) == sizeof(ll
) &&
522 time_t ll_time
= (time_t) ll
.ll_time
;
524 printf(_("Last login: %.*s "), 24 - 5, ctime(&ll_time
));
525 if (*ll
.ll_host
!= '\0')
526 printf(_("from %.*s\n"),
527 (int)sizeof(ll
.ll_host
), ll
.ll_host
);
529 printf(_("on %.*s\n"),
530 (int)sizeof(ll
.ll_line
), ll
.ll_line
);
532 if (lseek(fd
, (off_t
) cxt
->pwd
->pw_uid
* sizeof(ll
), SEEK_SET
) == -1)
536 memset((char *)&ll
, 0, sizeof(ll
));
539 ll
.ll_time
= t
; /* ll_time is always 32bit */
542 xstrncpy(ll
.ll_line
, cxt
->tty_name
, sizeof(ll
.ll_line
));
544 xstrncpy(ll
.ll_host
, cxt
->hostname
, sizeof(ll
.ll_host
));
546 if (write_all(fd
, (char *)&ll
, sizeof(ll
)))
547 warn(_("write lastlog failed"));
552 sigaction(SIGXFSZ
, &oldsa_xfsz
, NULL
); /* restore original setting */
556 * Update wtmp and utmp logs.
558 static void log_utmp(struct login_context
*cxt
)
564 utmpxname(_PATH_UTMP
);
569 * login sometimes overwrites the runlevel entry in /var/run/utmp,
570 * confusing sysvinit. I added a test for the entry type, and the
571 * problem was gone. (In a runlevel entry, st_pid is not really a pid
572 * but some number calculated from the previous and current runlevel.)
573 * -- Michael Riepe <michael@stud.uni-hannover.de>
575 while ((utp
= getutxent()))
576 if (utp
->ut_pid
== cxt
->pid
577 && utp
->ut_type
>= INIT_PROCESS
578 && utp
->ut_type
<= DEAD_PROCESS
)
581 /* If we can't find a pre-existing entry by pid, try by line.
582 * BSD network daemons may rely on this. */
583 if (utp
== NULL
&& cxt
->tty_name
) {
585 ut
.ut_type
= LOGIN_PROCESS
;
586 strncpy(ut
.ut_line
, cxt
->tty_name
, sizeof(ut
.ut_line
));
587 utp
= getutxline(&ut
);
590 /* If we can't find a pre-existing entry by pid and line, try it by id.
591 * Very stupid telnetd daemons don't set up utmp at all. (kzak) */
592 if (utp
== NULL
&& cxt
->tty_number
) {
594 ut
.ut_type
= DEAD_PROCESS
;
595 strncpy(ut
.ut_id
, cxt
->tty_number
, sizeof(ut
.ut_id
));
600 memcpy(&ut
, utp
, sizeof(ut
));
602 /* some gettys/telnetds don't initialize utmp... */
603 memset(&ut
, 0, sizeof(ut
));
605 if (cxt
->tty_number
&& ut
.ut_id
[0] == 0)
606 strncpy(ut
.ut_id
, cxt
->tty_number
, sizeof(ut
.ut_id
));
608 strncpy(ut
.ut_user
, cxt
->username
, sizeof(ut
.ut_user
));
610 xstrncpy(ut
.ut_line
, cxt
->tty_name
, sizeof(ut
.ut_line
));
612 gettimeofday(&tv
, NULL
);
613 ut
.ut_tv
.tv_sec
= tv
.tv_sec
;
614 ut
.ut_tv
.tv_usec
= tv
.tv_usec
;
615 ut
.ut_type
= USER_PROCESS
;
616 ut
.ut_pid
= cxt
->pid
;
618 xstrncpy(ut
.ut_host
, cxt
->hostname
, sizeof(ut
.ut_host
));
619 if (*cxt
->hostaddress
)
620 memcpy(&ut
.ut_addr_v6
, cxt
->hostaddress
,
621 sizeof(ut
.ut_addr_v6
));
627 updwtmpx(_PATH_WTMP
, &ut
);
630 static void log_syslog(struct login_context
*cxt
)
632 struct passwd
*pwd
= cxt
->pwd
;
637 if (!strncmp(cxt
->tty_name
, "ttyS", 4))
638 syslog(LOG_INFO
, _("DIALUP AT %s BY %s"),
639 cxt
->tty_name
, pwd
->pw_name
);
643 syslog(LOG_NOTICE
, _("ROOT LOGIN ON %s FROM %s"),
644 cxt
->tty_name
, cxt
->hostname
);
646 syslog(LOG_NOTICE
, _("ROOT LOGIN ON %s"), cxt
->tty_name
);
649 syslog(LOG_INFO
, _("LOGIN ON %s BY %s FROM %s"),
650 cxt
->tty_name
, pwd
->pw_name
, cxt
->hostname
);
652 syslog(LOG_INFO
, _("LOGIN ON %s BY %s"), cxt
->tty_name
,
657 /* encapsulate stupid "void **" pam_get_item() API */
658 static int loginpam_get_username(pam_handle_t
*pamh
, char **name
)
660 const void *item
= (void *)*name
;
662 rc
= pam_get_item(pamh
, PAM_USER
, &item
);
663 *name
= (char *)item
;
667 static void loginpam_err(pam_handle_t
*pamh
, int retcode
)
669 const char *msg
= pam_strerror(pamh
, retcode
);
672 fprintf(stderr
, "\n%s\n", msg
);
673 syslog(LOG_ERR
, "%s", msg
);
675 pam_end(pamh
, retcode
);
676 sleepexit(EXIT_FAILURE
);
680 * Composes "<host> login: " string; or returns "login: " if -H is given.
682 static const char *loginpam_get_prompt(struct login_context
*cxt
)
685 char *prompt
, *dflt_prompt
= _("login: ");
688 if (cxt
->nohost
|| !(host
= get_thishost(cxt
, NULL
)))
691 sz
= strlen(host
) + 1 + strlen(dflt_prompt
) + 1;
693 prompt
= xmalloc(sz
);
694 snprintf(prompt
, sz
, "%s %s", host
, dflt_prompt
);
699 static pam_handle_t
*init_loginpam(struct login_context
*cxt
)
701 pam_handle_t
*pamh
= NULL
;
705 * username is initialized to NULL and if specified on the command line
706 * it is set. Therefore, we are safe not setting it to anything.
708 rc
= pam_start(cxt
->remote
? "remote" : "login",
709 cxt
->username
, &cxt
->conv
, &pamh
);
710 if (rc
!= PAM_SUCCESS
) {
711 warnx(_("PAM failure, aborting: %s"), pam_strerror(pamh
, rc
));
712 syslog(LOG_ERR
, _("Couldn't initialize PAM: %s"),
713 pam_strerror(pamh
, rc
));
714 sleepexit(EXIT_FAILURE
);
717 /* hostname & tty are either set to NULL or their correct values,
718 * depending on how much we know. */
719 rc
= pam_set_item(pamh
, PAM_RHOST
, cxt
->hostname
);
720 if (is_pam_failure(rc
))
721 loginpam_err(pamh
, rc
);
723 rc
= pam_set_item(pamh
, PAM_TTY
, cxt
->tty_name
);
724 if (is_pam_failure(rc
))
725 loginpam_err(pamh
, rc
);
728 * Andrew.Taylor@cal.montage.ca: Provide a user prompt to PAM so that
729 * the "login: " prompt gets localized. Unfortunately, PAM doesn't have
730 * an interface to specify the "Password: " string (yet).
732 rc
= pam_set_item(pamh
, PAM_USER_PROMPT
, loginpam_get_prompt(cxt
));
733 if (is_pam_failure(rc
))
734 loginpam_err(pamh
, rc
);
736 /* We don't need the original username. We have to follow PAM. */
738 cxt
->username
= NULL
;
744 static void loginpam_auth(struct login_context
*cxt
)
746 int rc
, show_unknown
;
747 unsigned int retries
, failcount
= 0;
748 const char *hostname
= cxt
->hostname
? cxt
->hostname
:
749 cxt
->tty_name
? cxt
->tty_name
: "<unknown>";
750 pam_handle_t
*pamh
= cxt
->pamh
;
752 /* if we didn't get a user on the command line, set it to NULL */
753 loginpam_get_username(pamh
, &cxt
->username
);
755 show_unknown
= getlogindefs_bool("LOG_UNKFAIL_ENAB", 0);
756 retries
= getlogindefs_num("LOGIN_RETRIES", LOGIN_MAX_TRIES
);
759 * There may be better ways to deal with some of these conditions, but
760 * at least this way I don't think we'll be giving away information...
762 * Perhaps someday we can trust that all PAM modules will pay attention
763 * to failure count and get rid of LOGIN_MAX_TRIES?
765 rc
= pam_authenticate(pamh
, 0);
767 while ((++failcount
< retries
) &&
768 ((rc
== PAM_AUTH_ERR
) ||
769 (rc
== PAM_USER_UNKNOWN
) ||
770 (rc
== PAM_CRED_INSUFFICIENT
) ||
771 (rc
== PAM_AUTHINFO_UNAVAIL
))) {
773 if (rc
== PAM_USER_UNKNOWN
&& !show_unknown
)
775 * Logging unknown usernames may be a security issue if
776 * a user enters her password instead of her login name.
778 cxt
->username
= NULL
;
780 loginpam_get_username(pamh
, &cxt
->username
);
783 _("FAILED LOGIN %u FROM %s FOR %s, %s"),
785 cxt
->username
? cxt
->username
: "(unknown)",
786 pam_strerror(pamh
, rc
));
791 fprintf(stderr
, _("Login incorrect\n\n"));
793 pam_set_item(pamh
, PAM_USER
, NULL
);
794 rc
= pam_authenticate(pamh
, 0);
797 if (is_pam_failure(rc
)) {
799 if (rc
== PAM_USER_UNKNOWN
&& !show_unknown
)
800 cxt
->username
= NULL
;
802 loginpam_get_username(pamh
, &cxt
->username
);
804 if (rc
== PAM_MAXTRIES
)
806 _("TOO MANY LOGIN TRIES (%u) FROM %s FOR %s, %s"),
808 cxt
->username
? cxt
->username
: "(unknown)",
809 pam_strerror(pamh
, rc
));
812 _("FAILED LOGIN SESSION FROM %s FOR %s, %s"),
814 cxt
->username
? cxt
->username
: "(unknown)",
815 pam_strerror(pamh
, rc
));
820 fprintf(stderr
, _("\nLogin incorrect\n"));
822 sleepexit(EXIT_SUCCESS
);
826 static void loginpam_acct(struct login_context
*cxt
)
829 pam_handle_t
*pamh
= cxt
->pamh
;
831 rc
= pam_acct_mgmt(pamh
, 0);
833 if (rc
== PAM_NEW_AUTHTOK_REQD
)
834 rc
= pam_chauthtok(pamh
, PAM_CHANGE_EXPIRED_AUTHTOK
);
836 if (is_pam_failure(rc
))
837 loginpam_err(pamh
, rc
);
840 * Grab the user information out of the password file for future use.
841 * First get the username that we are actually using, though.
843 rc
= loginpam_get_username(pamh
, &cxt
->username
);
844 if (is_pam_failure(rc
))
845 loginpam_err(pamh
, rc
);
847 if (!cxt
->username
|| !*cxt
->username
) {
848 warnx(_("\nSession setup problem, abort."));
849 syslog(LOG_ERR
, _("NULL user name in %s:%d. Abort."),
850 __FUNCTION__
, __LINE__
);
851 pam_end(pamh
, PAM_SYSTEM_ERR
);
852 sleepexit(EXIT_FAILURE
);
857 * Note that the position of the pam_setcred() call is discussable:
859 * - the PAM docs recommend pam_setcred() before pam_open_session()
860 * - but the original RFC http://www.opengroup.org/rfc/mirror-rfc/rfc86.0.txt
861 * uses pam_setcred() after pam_open_session()
863 * The old login versions (before year 2011) followed the RFC. This is probably
864 * not optimal, because there could be a dependence between some session modules
865 * and the user's credentials.
867 * The best is probably to follow openssh and call pam_setcred() before and
868 * after pam_open_session(). -- kzak@redhat.com (18-Nov-2011)
871 static void loginpam_session(struct login_context
*cxt
)
874 pam_handle_t
*pamh
= cxt
->pamh
;
876 rc
= pam_setcred(pamh
, PAM_ESTABLISH_CRED
);
877 if (is_pam_failure(rc
))
878 loginpam_err(pamh
, rc
);
880 rc
= pam_open_session(pamh
, 0);
881 if (is_pam_failure(rc
)) {
882 pam_setcred(cxt
->pamh
, PAM_DELETE_CRED
);
883 loginpam_err(pamh
, rc
);
886 rc
= pam_setcred(pamh
, PAM_REINITIALIZE_CRED
);
887 if (is_pam_failure(rc
)) {
888 pam_close_session(pamh
, 0);
889 loginpam_err(pamh
, rc
);
894 * Detach the controlling terminal, fork, restore syslog stuff, and create
897 static void fork_session(struct login_context
*cxt
)
899 struct sigaction sa
, oldsa_hup
, oldsa_term
;
901 signal(SIGALRM
, SIG_DFL
);
902 signal(SIGQUIT
, SIG_DFL
);
903 signal(SIGTSTP
, SIG_IGN
);
905 memset(&sa
, 0, sizeof(sa
));
906 sa
.sa_handler
= SIG_IGN
;
907 sigaction(SIGINT
, &sa
, NULL
);
909 sigaction(SIGHUP
, &sa
, &oldsa_hup
); /* ignore when TIOCNOTTY */
912 * Detach the controlling tty.
913 * We don't need the tty in a parent who only waits for a child.
914 * The child calls setsid() that detaches from the tty as well.
916 ioctl(0, TIOCNOTTY
, NULL
);
919 * We have to beware of SIGTERM, because leaving a PAM session
920 * without pam_close_session() is a pretty bad thing.
922 sa
.sa_handler
= sig_handler
;
923 sigaction(SIGHUP
, &sa
, NULL
);
924 sigaction(SIGTERM
, &sa
, &oldsa_term
);
929 * We must fork before setuid(), because we need to call
930 * pam_close_session() as root.
934 warn(_("fork failed"));
936 pam_setcred(cxt
->pamh
, PAM_DELETE_CRED
);
937 pam_end(cxt
->pamh
, pam_close_session(cxt
->pamh
, 0));
938 sleepexit(EXIT_FAILURE
);
943 * parent - wait for child to finish, then clean up session
948 sa
.sa_handler
= SIG_IGN
;
949 sigaction(SIGQUIT
, &sa
, NULL
);
950 sigaction(SIGINT
, &sa
, NULL
);
952 /* wait as long as any child is there */
953 while (wait(NULL
) == -1 && errno
== EINTR
) ;
954 openlog("login", LOG_ODELAY
, LOG_AUTHPRIV
);
956 pam_setcred(cxt
->pamh
, PAM_DELETE_CRED
);
957 pam_end(cxt
->pamh
, pam_close_session(cxt
->pamh
, 0));
964 sigaction(SIGHUP
, &oldsa_hup
, NULL
); /* restore old state */
965 sigaction(SIGTERM
, &oldsa_term
, NULL
);
970 * Problem: if the user's shell is a shell like ash that doesn't do
971 * setsid() or setpgrp(), then a ctrl-\, sending SIGQUIT to every
972 * process in the pgrp, will kill us.
975 /* start new session */
978 /* make sure we have a controlling tty */
979 open_tty(cxt
->tty_path
);
980 openlog("login", LOG_ODELAY
, LOG_AUTHPRIV
); /* reopen */
983 * TIOCSCTTY: steal tty from other process group.
985 if (ioctl(0, TIOCSCTTY
, 1))
986 syslog(LOG_ERR
, _("TIOCSCTTY failed: %m"));
987 signal(SIGINT
, SIG_DFL
);
991 * Initialize $TERM, $HOME, ...
993 static void init_environ(struct login_context
*cxt
)
995 struct passwd
*pwd
= cxt
->pwd
;
996 char *termenv
, **env
;
1000 termenv
= getenv("TERM");
1002 termenv
= xstrdup(termenv
);
1004 /* destroy environment unless user has requested preservation (-p) */
1005 if (!cxt
->keep_env
) {
1006 environ
= xmalloc(sizeof(char *));
1007 memset(environ
, 0, sizeof(char *));
1010 xsetenv("HOME", pwd
->pw_dir
, 0); /* legal to override */
1011 xsetenv("USER", pwd
->pw_name
, 1);
1012 xsetenv("SHELL", pwd
->pw_shell
, 1);
1013 xsetenv("TERM", termenv
? termenv
: "dumb", 1);
1017 if (logindefs_setenv("PATH", "ENV_PATH", _PATH_DEFPATH
) != 0)
1018 err(EXIT_FAILURE
, _("failed to set the %s environment variable"), "PATH");
1020 } else if (logindefs_setenv("PATH", "ENV_ROOTPATH", NULL
) != 0 &&
1021 logindefs_setenv("PATH", "ENV_SUPATH", _PATH_DEFPATH_ROOT
) != 0) {
1022 err(EXIT_FAILURE
, _("failed to set the %s environment variable"), "PATH");
1025 /* mailx will give a funny error msg if you forget this one */
1026 len
= snprintf(tmp
, sizeof(tmp
), "%s/%s", _PATH_MAILDIR
, pwd
->pw_name
);
1027 if (len
> 0 && (size_t) len
< sizeof(tmp
))
1028 xsetenv("MAIL", tmp
, 0);
1030 /* LOGNAME is not documented in login(1) but HP-UX 6.5 does it. We'll
1031 * not allow modifying it.
1033 xsetenv("LOGNAME", pwd
->pw_name
, 1);
1035 env
= pam_getenvlist(cxt
->pamh
);
1036 for (i
= 0; env
&& env
[i
]; i
++)
1041 * This is called for the -h option, initializes cxt->{hostname,hostaddress}.
1043 static void init_remote_info(struct login_context
*cxt
, char *remotehost
)
1047 struct addrinfo hints
, *info
= NULL
;
1051 get_thishost(cxt
, &domain
);
1053 if (domain
&& (p
= strchr(remotehost
, '.')) &&
1054 strcasecmp(p
+ 1, domain
) == 0)
1057 cxt
->hostname
= xstrdup(remotehost
);
1059 memset(&hints
, 0, sizeof(hints
));
1060 hints
.ai_flags
= AI_ADDRCONFIG
;
1061 cxt
->hostaddress
[0] = 0;
1063 if (getaddrinfo(cxt
->hostname
, NULL
, &hints
, &info
) == 0 && info
) {
1064 if (info
->ai_family
== AF_INET
) {
1065 struct sockaddr_in
*sa
=
1066 (struct sockaddr_in
*) info
->ai_addr
;
1068 memcpy(cxt
->hostaddress
, &(sa
->sin_addr
), sizeof(sa
->sin_addr
));
1070 } else if (info
->ai_family
== AF_INET6
) {
1071 struct sockaddr_in6
*sa
=
1072 (struct sockaddr_in6
*) info
->ai_addr
;
1073 #ifdef IN6_IS_ADDR_V4MAPPED
1074 if (IN6_IS_ADDR_V4MAPPED(&sa
->sin6_addr
)) {
1075 const uint8_t *bytes
= sa
->sin6_addr
.s6_addr
;
1076 struct in_addr addr
= { *(const in_addr_t
*) (bytes
+ 12) };
1078 memcpy(cxt
->hostaddress
, &addr
, sizeof(struct in_addr
));
1081 memcpy(cxt
->hostaddress
, &(sa
->sin6_addr
), sizeof(sa
->sin6_addr
));
1087 static void __attribute__((__noreturn__
)) usage(void)
1089 fputs(USAGE_HEADER
, stdout
);
1090 printf(_(" %s [-p] [-h <host>] [-H] [[-f] <username>]\n"), program_invocation_short_name
);
1091 fputs(USAGE_SEPARATOR
, stdout
);
1092 fputs(_("Begin a session on the system.\n"), stdout
);
1094 fputs(USAGE_OPTIONS
, stdout
);
1095 puts(_(" -p do not destroy the environment"));
1096 puts(_(" -f skip a second login authentication"));
1097 puts(_(" -h <host> hostname to be used for utmp logging"));
1098 puts(_(" -H suppress hostname in the login prompt"));
1099 printf(" --help %s\n", USAGE_OPTSTR_HELP
);
1100 printf(" -V, --version %s\n", USAGE_OPTSTR_VERSION
);
1101 printf(USAGE_MAN_TAIL("login(1)"));
1105 int main(int argc
, char **argv
)
1109 char *childArgv
[10];
1113 struct sigaction act
;
1116 struct login_context cxt
= {
1117 .tty_mode
= TTY_MODE
, /* tty chmod() */
1118 .pid
= getpid(), /* PID */
1119 #ifdef HAVE_SECURITY_PAM_MISC_H
1120 .conv
= { misc_conv
, NULL
} /* Linux-PAM conversation function */
1121 #elif defined(HAVE_SECURITY_OPENPAM_H)
1122 .conv
= { openpam_ttyconv
, NULL
} /* OpenPAM conversation function */
1127 /* the only two longopts to satisfy UL standards */
1128 enum { HELP_OPTION
= CHAR_MAX
+ 1 };
1129 static const struct option longopts
[] = {
1130 {"help", no_argument
, NULL
, HELP_OPTION
},
1131 {"version", no_argument
, NULL
, 'V'},
1135 timeout
= (unsigned int)getlogindefs_num("LOGIN_TIMEOUT", LOGIN_TIMEOUT
);
1137 signal(SIGALRM
, timedout
);
1138 (void) sigaction(SIGALRM
, NULL
, &act
);
1139 act
.sa_flags
&= ~SA_RESTART
;
1140 sigaction(SIGALRM
, &act
, NULL
);
1142 signal(SIGQUIT
, SIG_IGN
);
1143 signal(SIGINT
, SIG_IGN
);
1145 setlocale(LC_ALL
, "");
1146 bindtextdomain(PACKAGE
, LOCALEDIR
);
1147 textdomain(PACKAGE
);
1149 setpriority(PRIO_PROCESS
, 0, 0);
1150 initproctitle(argc
, argv
);
1153 * -p is used by getty to tell login not to destroy the environment
1154 * -f is used to skip a second login authentication
1155 * -h is used by other servers to pass the name of the remote
1156 * host to login so that it may be placed in utmp and wtmp
1158 while ((c
= getopt_long(argc
, argv
, "fHh:pV", longopts
, NULL
)) != -1)
1171 _("login: -h is for superuser only\n"));
1174 init_remote_info(&cxt
, optarg
);
1182 printf(UTIL_LINUX_VERSION
);
1183 return EXIT_SUCCESS
;
1187 errtryhelp(EXIT_FAILURE
);
1194 cxt
.username
= xstrdup(p
);
1196 /* Wipe the name - some people mistype their password here. */
1197 /* (Of course we are too late, but perhaps this helps a little...) */
1202 for (cnt
= get_fd_tabsize() - 1; cnt
> 2; cnt
--)
1205 setpgrp(); /* set pgid to pid this means that setsid() will fail */
1208 openlog("login", LOG_ODELAY
, LOG_AUTHPRIV
);
1210 init_loginpam(&cxt
);
1212 /* login -f, then the user has already been authenticated */
1213 cxt
.noauth
= cxt
.noauth
&& getuid() == 0 ? 1 : 0;
1216 loginpam_auth(&cxt
);
1219 * Authentication may be skipped (for example, during krlogin, rlogin,
1220 * etc...), but it doesn't mean that we can skip other account checks.
1221 * The account could be disabled or the password has expired (although
1222 * the kerberos ticket is valid). -- kzak@redhat.com (22-Feb-2006)
1224 loginpam_acct(&cxt
);
1226 cxt
.pwd
= xgetpwnam(cxt
.username
, &cxt
.pwdbuf
);
1228 warnx(_("\nSession setup problem, abort."));
1229 syslog(LOG_ERR
, _("Invalid user name \"%s\" in %s:%d. Abort."),
1230 cxt
.username
, __FUNCTION__
, __LINE__
);
1231 pam_end(cxt
.pamh
, PAM_SYSTEM_ERR
);
1232 sleepexit(EXIT_FAILURE
);
1236 cxt
.username
= pwd
->pw_name
;
1239 * Initialize the supplementary group list. This should be done before
1240 * pam_setcred, because PAM modules might add groups during that call.
1242 * For root we don't call initgroups, instead we call setgroups with
1243 * group 0. This avoids the need to step through the whole group file,
1244 * which can cause problems if NIS, NIS+, LDAP or something similar
1245 * is used and the machine has network problems.
1247 retcode
= pwd
->pw_uid
? initgroups(cxt
.username
, pwd
->pw_gid
) : /* user */
1248 setgroups(0, NULL
); /* root */
1250 syslog(LOG_ERR
, _("groups initialization failed: %m"));
1251 warnx(_("\nSession setup problem, abort."));
1252 pam_end(cxt
.pamh
, PAM_SYSTEM_ERR
);
1253 sleepexit(EXIT_FAILURE
);
1257 * Open PAM session (after successful authentication and account check).
1259 loginpam_session(&cxt
);
1261 /* committed to login -- turn off timeout */
1262 alarm((unsigned int)0);
1266 cxt
.quiet
= get_hushlogin_status(pwd
, 1);
1274 if (setgid(pwd
->pw_gid
) < 0 && pwd
->pw_gid
) {
1275 syslog(LOG_ALERT
, _("setgid() failed"));
1279 if (pwd
->pw_shell
== NULL
|| *pwd
->pw_shell
== '\0')
1280 pwd
->pw_shell
= _PATH_BSHELL
;
1282 init_environ(&cxt
); /* init $HOME, $TERM ... */
1284 setproctitle("login", cxt
.username
);
1291 #ifdef LOGIN_STAT_MAIL
1293 * This turns out to be a bad idea: when the mail spool
1294 * is NFS mounted, and the NFS connection hangs, the
1295 * login hangs, even root cannot login.
1296 * Checking for mail should be done from the shell.
1302 mail
= getenv("MAIL");
1303 if (mail
&& stat(mail
, &st
) == 0 && st
.st_size
!= 0) {
1304 if (st
.st_mtime
> st
.st_atime
)
1305 printf(_("You have new mail.\n"));
1307 printf(_("You have mail.\n"));
1314 * Detach the controlling terminal, fork, and create a new session
1315 * and reinitialize syslog stuff.
1319 /* discard permissions last so we can't get killed and drop core */
1320 if (setuid(pwd
->pw_uid
) < 0 && pwd
->pw_uid
) {
1321 syslog(LOG_ALERT
, _("setuid() failed"));
1325 /* wait until here to change directory! */
1326 if (chdir(pwd
->pw_dir
) < 0) {
1327 warn(_("%s: change directory failed"), pwd
->pw_dir
);
1329 if (!getlogindefs_bool("DEFAULT_HOME", 1))
1334 printf(_("Logging in with home = \"/\".\n"));
1337 /* if the shell field has a space: treat it like a shell script */
1338 if (strchr(pwd
->pw_shell
, ' ')) {
1339 buff
= xmalloc(strlen(pwd
->pw_shell
) + 6);
1341 strcpy(buff
, "exec ");
1342 strcat(buff
, pwd
->pw_shell
);
1343 childArgv
[childArgc
++] = "/bin/sh";
1344 childArgv
[childArgc
++] = "-sh";
1345 childArgv
[childArgc
++] = "-c";
1346 childArgv
[childArgc
++] = buff
;
1348 char tbuf
[PATH_MAX
+ 2], *p
;
1351 xstrncpy(tbuf
+ 1, ((p
= strrchr(pwd
->pw_shell
, '/')) ?
1352 p
+ 1 : pwd
->pw_shell
), sizeof(tbuf
) - 1);
1354 childArgv
[childArgc
++] = pwd
->pw_shell
;
1355 childArgv
[childArgc
++] = xstrdup(tbuf
);
1358 childArgv
[childArgc
++] = NULL
;
1360 execvp(childArgv
[0], childArgv
+ 1);
1362 if (!strcmp(childArgv
[0], "/bin/sh"))
1363 warn(_("couldn't exec shell script"));
1365 warn(_("no shell"));