libuutil: move under bmake
[unleashed.git] / usr / src / cmd / login / login.c
blobf33c7fc68439891e0192b06a65eb391a6c24f326
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
27 /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
28 /* All Rights Reserved */
31 * University Copyright- Copyright (c) 1982, 1986, 1988
32 * The Regents of the University of California
33 * All Rights Reserved
35 * University Acknowledgment- Portions of this document are derived from
36 * software developed by the University of California, Berkeley, and its
37 * contributors.
40 /* Copyright (c) 1987, 1988 Microsoft Corporation */
41 /* All Rights Reserved */
44 * For a complete reference to login(1), see the manual page. However,
45 * login has accreted some intentionally undocumented options, which are
46 * explained here:
48 * -a: This legacy flag appears to be unused.
50 * -f <username>: This flag was introduced by PSARC 1995/039 in support
51 * of Kerberos. But it's not used by Sun's Kerberos implementation.
52 * It is however employed by zlogin(1), since it allows one to tell
53 * login: "This user is authenticated." In the case of zlogin that's
54 * true because the zone always trusts the global zone.
56 * -z <zonename>: This flag is passed to login when zlogin(1) executes a
57 * zone login. This tells login(1) to skip it's normal CONSOLE check
58 * (i.e. that the root login must be on /dev/console) and tells us the
59 * name of the zone from which the login is occurring.
62 #include <sys/types.h>
63 #include <sys/param.h>
64 #include <unistd.h> /* For logfile locking */
65 #include <signal.h>
66 #include <stdio.h>
67 #include <sys/stat.h>
68 #include <string.h>
69 #include <deflt.h>
70 #include <grp.h>
71 #include <fcntl.h>
72 #include <termio.h>
73 #include <utmpx.h>
74 #include <stdlib.h>
75 #include <wait.h>
76 #include <errno.h>
77 #include <ctype.h>
78 #include <syslog.h>
79 #include <ulimit.h>
80 #include <libgen.h>
81 #include <pwd.h>
82 #include <security/pam_appl.h>
83 #include <strings.h>
84 #include <libdevinfo.h>
85 #include <zone.h>
86 #include "login_audit.h"
88 #include <krb5_repository.h>
91 * *** Defines, Macros, and String Constants ***
96 #define ISSUEFILE "/etc/issue" /* file to print before prompt */
97 #define NOLOGIN "/etc/nologin" /* file to lock users out during shutdown */
100 * These need to be defined for UTMPX management.
101 * If we add in the utility functions later, we
102 * can remove them.
104 #define __UPDATE_ENTRY 1
105 #define __LOGIN 2
108 * Intervals to sleep after failed login
110 #ifndef SLEEPTIME
111 #define SLEEPTIME 4 /* sleeptime before login incorrect msg */
112 #endif
113 static int Sleeptime = SLEEPTIME;
116 * seconds login disabled after allowable number of unsuccessful attempts
118 #ifndef DISABLETIME
119 #define DISABLETIME 20
120 #endif
121 static int Disabletime = DISABLETIME;
123 #define MAXTRYS 5
125 static int retry = MAXTRYS;
128 * Login logging support
130 #define LOGINLOG "/var/adm/loginlog" /* login log file */
131 #define LNAME_SIZE 20 /* size of logged logname */
132 #define TTYN_SIZE 15 /* size of logged tty name */
133 #define TIME_SIZE 30 /* size of logged time string */
134 #define ENT_SIZE (LNAME_SIZE + TTYN_SIZE + TIME_SIZE + 3)
135 #define L_WAITTIME 5 /* waittime for log file to unlock */
136 #define LOGTRYS 10 /* depth of 'try' logging */
139 * String manipulation macros: SCPYN, SCPYL, EQN and ENVSTRNCAT
140 * SCPYL is the safer version of SCPYN
142 #define SCPYL(a, b) (void) strlcpy(a, b, sizeof (a))
143 #define SCPYN(a, b) (void) strncpy(a, b, sizeof (a))
144 #define EQN(a, b) (strncmp(a, b, sizeof (a)-1) == 0)
145 #define ENVSTRNCAT(to, from) {int deflen; deflen = strlen(to); \
146 (void) strncpy((to)+ deflen, (from), sizeof (to) - (1 + deflen)); }
149 * Other macros
151 #define NMAX sizeof (((struct utmpx *)0)->ut_name)
152 #define HMAX sizeof (((struct utmpx *)0)->ut_host)
153 #define min(a, b) (((a) < (b)) ? (a) : (b))
156 * Various useful files and string constants
158 #define SHELL "/bin/sh"
159 #define SUBLOGIN "<!sublogin>"
160 #define PROG_NAME "login"
161 #define HUSHLOGIN ".hushlogin"
164 * Array and Buffer sizes
166 #define PBUFSIZE 8 /* max significant characters in a password */
167 #define MAXARGS 63 /* change value below if changing this */
168 #define MAXARGSWIDTH 2 /* log10(MAXARGS) */
169 #define MAXENV 1024
170 #define MAXLINE 2048
173 * Miscellaneous constants
175 #define ROOTUID 0
176 #define ERROR 1
177 #define OK 0
178 #define LOG_ERROR 1
179 #define DONT_LOG_ERROR 0
180 #define TRUE 1
181 #define FALSE 0
184 * Counters for counting the number of failed login attempts
186 static int trys = 0;
187 static int count = 1;
190 * error value for login_exit() audit output (0 == no audit record)
192 static int audit_error = 0;
195 * Externs a plenty
197 extern int getsecretkey();
200 * The current user name
202 static char user_name[NMAX];
203 static char minusnam[16] = "-";
206 * login_pid, used to find utmpx entry to update.
208 static pid_t login_pid;
211 * locale environments to be passed to shells.
213 static char *localeenv[] = {
214 "LANG",
215 "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE",
216 "LC_MONETARY", "LC_MESSAGES", "LC_ALL", 0};
217 static int locale_envmatch(char *, char *);
220 * Environment variable support
222 static char shell[256] = { "SHELL=" };
223 static char home[MAXPATHLEN] = { "HOME=" };
224 static char term[64] = { "TERM=" };
225 static char logname[30] = { "LOGNAME=" };
226 static char timez[100] = { "TZ=" };
227 static char hertz[10] = { "HZ=" };
228 static char path[MAXPATHLEN] = { "PATH=" };
229 static char *newenv[10+MAXARGS] =
230 {home, path, logname, hertz, term, 0, 0};
231 static char **envinit = newenv;
232 static int basicenv;
233 static char *zero = NULL;
234 static char **envp;
235 #ifndef NO_MAIL
236 static char mail[30] = { "MAIL=/var/mail/" };
237 #endif
238 extern char **environ;
239 static char inputline[MAXLINE];
241 #define MAX_ID_LEN 256
242 #define MAX_REPOSITORY_LEN 256
243 #define MAX_PAMSERVICE_LEN 256
245 static char identity[MAX_ID_LEN];
246 static char repository[MAX_REPOSITORY_LEN];
247 static char progname[MAX_PAMSERVICE_LEN];
251 * Strings used to prompt the user.
253 static char loginmsg[] = "login: ";
254 static char passwdmsg[] = "Password:";
255 static char incorrectmsg[] = "Login incorrect\n";
258 * Password file support
260 static struct passwd *pwd = NULL;
261 static char remote_host[HMAX];
262 static char zone_name[ZONENAME_MAX];
265 * Log file support
267 static char *log_entry[LOGTRYS];
268 static int writelog = 0;
269 static int dosyslog = 0;
270 static int flogin = MAXTRYS; /* flag for SYSLOG_FAILED_LOGINS */
273 * Default file toggles
275 static char *Pndefault = "/etc/default/login";
276 static char *Altshell = NULL;
277 static char *Console = NULL;
278 static int Passreqflag = 0;
280 #define DEFUMASK 022
281 static mode_t Umask = DEFUMASK;
282 static char *Def_tz = NULL;
283 static char *tmp_tz = NULL;
284 static char *Def_hertz = NULL;
285 #define SET_FSIZ 2 /* ulimit() command arg */
286 static long Def_ulimit = 0;
287 #define MAX_TIMEOUT (15 * 60)
288 #define DEF_TIMEOUT (5 * 60)
289 static unsigned Def_timeout = DEF_TIMEOUT;
290 static char *Def_path = NULL;
291 static char *Def_supath = NULL;
292 #define DEF_PATH "/usr/bin:" /* same as PATH */
293 #define DEF_SUPATH "/usr/sbin:/usr/bin" /* same as ROOTPATH */
296 * Defaults for updating expired passwords
298 #define DEF_ATTEMPTS 3
301 * ttyprompt will point to the environment variable TTYPROMPT.
302 * TTYPROMPT is set by ttymon if ttymon already wrote out the prompt.
304 static char *ttyprompt = NULL;
305 static char *ttyn = NULL;
308 * Pass inherited environment. Used by telnetd in support of the telnet
309 * ENVIRON option.
311 static boolean_t pflag = B_FALSE;
312 static boolean_t uflag = B_FALSE;
313 static boolean_t Rflag = B_FALSE;
314 static boolean_t sflag = B_FALSE;
315 static boolean_t tflag = B_FALSE;
316 static boolean_t hflag = B_FALSE;
317 static boolean_t zflag = B_FALSE;
320 * Remote login support
322 static char lusername[NMAX+1];
323 static char terminal[MAXPATHLEN];
326 * Pre-authentication flag support
328 static int fflag;
330 static char ** getargs(char *);
332 static int login_conv(int, struct pam_message **,
333 struct pam_response **, void *);
335 static struct pam_conv pam_conv = {login_conv, NULL};
336 static pam_handle_t *pamh; /* Authentication handle */
339 * Function declarations
341 static void turn_on_logging(void);
342 static void defaults(void);
343 static void usage(void);
344 static void login_authenticate();
345 static void setup_credentials(void);
346 static void adjust_nice(void);
347 static void update_utmpx_entry(int, boolean_t);
348 static void establish_user_environment(char **);
349 static void exec_the_shell(void);
350 static int process_chroot_logins(void);
351 static void chdir_to_dir_user(void);
352 static void validate_account(void);
353 static int get_options(int, char **);
354 static int legalenvvar(char *);
355 static void check_for_console(void);
356 static void check_for_dueling_unix(char *);
357 static void get_user_name(void);
358 static uint_t get_audit_id(void);
359 static void login_exit(int)__NORETURN;
360 static int logins_disabled(char *);
361 static void log_bad_attempts(void);
362 static int is_number(char *);
363 static void printmotd(void);
366 * *** main ***
368 * The primary flow of control is directed in this routine.
369 * Control moves in line from top to bottom calling subfunctions
370 * which perform the bulk of the work. Many of these calls exit
371 * when a fatal error is encountered and do not return to main.
377 main(int argc, char *argv[], char **renvp)
379 int sublogin;
380 int pam_rc;
381 boolean_t silent = B_FALSE;
383 login_pid = getpid();
386 * Set up Defaults and flags
388 defaults();
389 SCPYL(progname, PROG_NAME);
392 * Set up default umask
394 if (Umask > ((mode_t)0777))
395 Umask = DEFUMASK;
396 (void) umask(Umask);
399 * Set up default timeouts and delays
401 if (Def_timeout > MAX_TIMEOUT)
402 Def_timeout = MAX_TIMEOUT;
403 if (Sleeptime < 0 || Sleeptime > 5)
404 Sleeptime = SLEEPTIME;
406 (void) alarm(Def_timeout);
409 * Ignore SIGQUIT and SIGINT and set nice to 0
411 (void) signal(SIGQUIT, SIG_IGN);
412 (void) signal(SIGINT, SIG_IGN);
413 (void) nice(0);
416 * Set flag to disable the pid check if you find that you are
417 * a subsystem login.
419 sublogin = 0;
420 if (*renvp && strcmp(*renvp, SUBLOGIN) == 0)
421 sublogin = 1;
424 * Parse Arguments
426 if (get_options(argc, argv) == -1) {
427 usage();
428 audit_error = ADT_FAIL_VALUE_BAD_CMD;
429 login_exit(1);
433 * if devicename is not passed as argument, call ttyname(0)
435 if (ttyn == NULL) {
436 ttyn = ttyname(0);
437 if (ttyn == NULL)
438 ttyn = "/dev/???";
442 * Call pam_start to initiate a PAM authentication operation
445 if ((pam_rc = pam_start(progname, user_name, &pam_conv, &pamh))
446 != PAM_SUCCESS) {
447 audit_error = ADT_FAIL_PAM + pam_rc;
448 login_exit(1);
450 if ((pam_rc = pam_set_item(pamh, PAM_TTY, ttyn)) != PAM_SUCCESS) {
451 audit_error = ADT_FAIL_PAM + pam_rc;
452 login_exit(1);
454 if ((pam_rc = pam_set_item(pamh, PAM_RHOST, remote_host)) !=
455 PAM_SUCCESS) {
456 audit_error = ADT_FAIL_PAM + pam_rc;
457 login_exit(1);
461 * We currently only support special handling of the KRB5 PAM repository
463 if ((Rflag && strlen(repository)) &&
464 strcmp(repository, KRB5_REPOSITORY_NAME) == 0 &&
465 (uflag && strlen(identity))) {
466 krb5_repository_data_t krb5_data;
467 pam_repository_t pam_rep_data;
469 krb5_data.principal = identity;
470 krb5_data.flags = SUNW_PAM_KRB5_ALREADY_AUTHENTICATED;
472 pam_rep_data.type = repository;
473 pam_rep_data.scope = (void *)&krb5_data;
474 pam_rep_data.scope_len = sizeof (krb5_data);
476 (void) pam_set_item(pamh, PAM_REPOSITORY,
477 (void *)&pam_rep_data);
481 * Open the log file which contains a record of successful and failed
482 * login attempts
484 turn_on_logging();
487 * say "hi" to syslogd ..
489 openlog("login", 0, LOG_AUTH);
492 * validate user
494 /* we are already authenticated. fill in what we must, then continue */
495 if (fflag) {
496 if ((pwd = getpwnam(user_name)) == NULL) {
497 audit_error = ADT_FAIL_VALUE_USERNAME;
499 log_bad_attempts();
500 (void) printf("Login failed: unknown user '%s'.\n",
501 user_name);
502 login_exit(1);
504 } else {
506 * Perform the primary login authentication activity.
508 login_authenticate();
511 /* change root login, then we exec another login and try again */
512 if (process_chroot_logins() != OK)
513 login_exit(1);
516 * If root login and not on system console then call exit(2)
518 check_for_console();
521 * Check to see if a shutdown is in progress, if it is and
522 * we are not root then throw the user off the system
524 if (logins_disabled(user_name) == TRUE) {
525 audit_error = ADT_FAIL_VALUE_LOGIN_DISABLED;
526 login_exit(1);
529 if (pwd->pw_uid == 0) {
530 if (Def_supath != NULL)
531 Def_path = Def_supath;
532 else
533 Def_path = DEF_SUPATH;
537 * Check account expiration and passwd aging
539 validate_account();
542 * We only get here if we've been authenticated.
546 * Now we set up the environment for the new user, which includes
547 * the users ulimit, nice value, ownership of this tty, uid, gid,
548 * and environment variables.
550 if (Def_ulimit > 0L && ulimit(SET_FSIZ, Def_ulimit) < 0L)
551 (void) printf("Could not set ULIMIT to %ld\n", Def_ulimit);
553 /* di_devperm_login() sends detailed errors to syslog */
554 if (di_devperm_login((const char *)ttyn, pwd->pw_uid, pwd->pw_gid,
555 NULL) == -1) {
556 (void) fprintf(stderr, "error processing /etc/logindevperm,"
557 " see syslog for more details\n");
560 adjust_nice(); /* passwd file can specify nice value */
562 setup_credentials(); /* Set user credentials - exits on failure */
564 if (chdir(pwd->pw_dir) == 0)
565 silent = (access(HUSHLOGIN, F_OK) == 0);
567 * NOTE: telnetd relies upon this updating of utmpx
568 * to indicate that the authentication completed successfully,
569 * pam_open_session was called and therefore they are required to
570 * call pam_close_session.
572 update_utmpx_entry(sublogin, silent);
574 /* set the real (and effective) UID */
575 if (setuid(pwd->pw_uid) == -1) {
576 login_exit(1);
580 * Set up the basic environment for the exec. This includes
581 * HOME, PATH, LOGNAME, SHELL, TERM, TZ, HZ, and MAIL.
583 chdir_to_dir_user();
585 establish_user_environment(renvp);
587 (void) pam_end(pamh, PAM_SUCCESS); /* Done using PAM */
588 pamh = NULL;
590 if (pwd->pw_uid == 0) {
591 if (dosyslog) {
592 if (remote_host[0]) {
593 syslog(LOG_NOTICE, "ROOT LOGIN %s FROM %.*s",
594 ttyn, HMAX, remote_host);
595 } else
596 syslog(LOG_NOTICE, "ROOT LOGIN %s", ttyn);
599 closelog();
601 if (!silent)
602 printmotd();
604 (void) signal(SIGQUIT, SIG_DFL);
605 (void) signal(SIGINT, SIG_DFL);
608 * Set SIGXCPU and SIGXFSZ to default disposition.
609 * Shells inherit signal disposition from parent.
610 * And the shells should have default dispositions
611 * for the two below signals.
613 (void) signal(SIGXCPU, SIG_DFL);
614 (void) signal(SIGXFSZ, SIG_DFL);
617 * Now fire off the shell of choice
619 exec_the_shell();
622 * All done
624 login_exit(1);
625 return (0);
630 * *** Utility functions ***
636 * donothing & catch - Signal catching functions
639 /*ARGSUSED*/
640 static void
641 donothing(int sig)
643 if (pamh)
644 (void) pam_end(pamh, PAM_ABORT);
647 #ifdef notdef
648 static int intrupt;
650 /*ARGSUSED*/
651 static void
652 catch(int sig)
654 ++intrupt;
656 #endif
659 * *** Bad login logging support ***
663 * badlogin() - log to the log file 'trys'
664 * unsuccessful attempts
667 static void
668 badlogin(void)
670 int retval, count1, fildes;
673 * Tries to open the log file. If succeed, lock it and write
674 * in the failed attempts
676 if ((fildes = open(LOGINLOG, O_APPEND|O_WRONLY)) != -1) {
678 (void) sigset(SIGALRM, donothing);
679 (void) alarm(L_WAITTIME);
680 retval = lockf(fildes, F_LOCK, 0L);
681 (void) alarm(0);
682 (void) sigset(SIGALRM, SIG_DFL);
683 if (retval == 0) {
684 for (count1 = 0; count1 < trys; count1++)
685 (void) write(fildes, log_entry[count1],
686 (unsigned)strlen(log_entry[count1]));
687 (void) lockf(fildes, F_ULOCK, 0L);
689 (void) close(fildes);
695 * log_bad_attempts - log each bad login attempt - called from
696 * login_authenticate. Exits when the maximum attempt
697 * count is exceeded.
700 static void
701 log_bad_attempts(void)
703 time_t timenow;
705 if (trys >= LOGTRYS)
706 return;
707 if (writelog) {
708 (void) time(&timenow);
709 (void) strncat(log_entry[trys], user_name, LNAME_SIZE);
710 (void) strncat(log_entry[trys], ":", (size_t)1);
711 (void) strncat(log_entry[trys], ttyn, TTYN_SIZE);
712 (void) strncat(log_entry[trys], ":", (size_t)1);
713 (void) strncat(log_entry[trys], ctime(&timenow), TIME_SIZE);
714 trys++;
716 if (count > flogin) {
717 if ((pwd = getpwnam(user_name)) != NULL) {
718 if (remote_host[0]) {
719 syslog(LOG_NOTICE,
720 "Login failure on %s from %.*s, "
721 "%.*s", ttyn, HMAX, remote_host,
722 NMAX, user_name);
723 } else {
724 syslog(LOG_NOTICE,
725 "Login failure on %s, %.*s",
726 ttyn, NMAX, user_name);
728 } else {
729 if (remote_host[0]) {
730 syslog(LOG_NOTICE,
731 "Login failure on %s from %.*s",
732 ttyn, HMAX, remote_host);
733 } else {
734 syslog(LOG_NOTICE,
735 "Login failure on %s", ttyn);
743 * turn_on_logging - if the logfile exist, turn on attempt logging and
744 * initialize the string storage area
747 static void
748 turn_on_logging(void)
750 struct stat dbuf;
751 int i;
753 if (stat(LOGINLOG, &dbuf) == 0) {
754 writelog = 1;
755 for (i = 0; i < LOGTRYS; i++) {
756 if (!(log_entry[i] = malloc((size_t)ENT_SIZE))) {
757 writelog = 0;
758 break;
760 *log_entry[i] = '\0';
767 * login_conv():
768 * This is the conv (conversation) function called from
769 * a PAM authentication module to print error messages
770 * or garner information from the user.
772 /*ARGSUSED*/
773 static int
774 login_conv(int num_msg, struct pam_message **msg,
775 struct pam_response **response, void *appdata_ptr)
777 struct pam_message *m;
778 struct pam_response *r;
779 char *temp;
780 int k, i;
782 if (num_msg <= 0)
783 return (PAM_CONV_ERR);
785 *response = calloc(num_msg, sizeof (struct pam_response));
786 if (*response == NULL)
787 return (PAM_BUF_ERR);
789 k = num_msg;
790 m = *msg;
791 r = *response;
792 while (k--) {
794 switch (m->msg_style) {
796 case PAM_PROMPT_ECHO_OFF:
797 errno = 0;
798 temp = getpassphrase(m->msg);
799 if (temp != NULL) {
800 if (errno == EINTR)
801 return (PAM_CONV_ERR);
803 r->resp = strdup(temp);
804 if (r->resp == NULL) {
805 /* free responses */
806 r = *response;
807 for (i = 0; i < num_msg; i++, r++) {
808 free(r->resp);
810 free(*response);
811 *response = NULL;
812 return (PAM_BUF_ERR);
816 m++;
817 r++;
818 break;
820 case PAM_PROMPT_ECHO_ON:
821 if (m->msg != NULL)
822 (void) fputs(m->msg, stdout);
823 r->resp = calloc(1, PAM_MAX_RESP_SIZE);
824 if (r->resp == NULL) {
825 /* free responses */
826 r = *response;
827 for (i = 0; i < num_msg; i++, r++) {
828 free(r->resp);
830 free(*response);
831 *response = NULL;
832 return (PAM_BUF_ERR);
835 * The response might include environment variables
836 * information. We should store that information in
837 * envp if there is any; otherwise, envp is set to
838 * NULL.
840 bzero((void *)inputline, MAXLINE);
842 envp = getargs(inputline);
844 /* If we read in any input, process it. */
845 if (inputline[0] != '\0') {
846 int len;
848 if (envp != (char **)NULL)
850 * If getargs() did not return NULL,
851 * *envp is the first string in
852 * inputline. envp++ makes envp point
853 * to environment variables information
854 * or be NULL.
856 envp++;
858 (void) strncpy(r->resp, inputline,
859 PAM_MAX_RESP_SIZE-1);
860 r->resp[PAM_MAX_RESP_SIZE-1] = 0;
861 len = strlen(r->resp);
862 if (r->resp[len-1] == '\n')
863 r->resp[len-1] = '\0';
864 } else {
865 login_exit(1);
867 m++;
868 r++;
869 break;
871 case PAM_ERROR_MSG:
872 if (m->msg != NULL) {
873 (void) fputs(m->msg, stderr);
874 (void) fputs("\n", stderr);
876 m++;
877 r++;
878 break;
879 case PAM_TEXT_INFO:
880 if (m->msg != NULL) {
881 (void) fputs(m->msg, stdout);
882 (void) fputs("\n", stdout);
884 m++;
885 r++;
886 break;
888 default:
889 break;
892 return (PAM_SUCCESS);
896 * verify_passwd - Authenticates the user.
897 * Returns: PAM_SUCCESS if authentication successful,
898 * PAM error code if authentication fails.
901 static int
902 verify_passwd(void)
904 int error;
905 char *user;
906 int flag = (Passreqflag ? PAM_DISALLOW_NULL_AUTHTOK : 0);
909 * PAM authenticates the user for us.
911 error = pam_authenticate(pamh, flag);
913 /* get the user_name from the pam handle */
914 (void) pam_get_item(pamh, PAM_USER, (void**)&user);
916 if (user == NULL || *user == '\0')
917 return (PAM_SYSTEM_ERR);
919 SCPYL(user_name, user);
920 check_for_dueling_unix(user_name);
922 if (((pwd = getpwnam(user_name)) == NULL) &&
923 (error != PAM_USER_UNKNOWN)) {
924 return (PAM_SYSTEM_ERR);
927 return (error);
931 * quotec - Called by getargs
934 static int
935 quotec(void)
937 int c, i, num;
939 switch (c = getc(stdin)) {
941 case 'n':
942 c = '\n';
943 break;
945 case 'r':
946 c = '\r';
947 break;
949 case 'v':
950 c = '\013';
951 break;
953 case 'b':
954 c = '\b';
955 break;
957 case 't':
958 c = '\t';
959 break;
961 case 'f':
962 c = '\f';
963 break;
965 case '0':
966 case '1':
967 case '2':
968 case '3':
969 case '4':
970 case '5':
971 case '6':
972 case '7':
973 for (num = 0, i = 0; i < 3; i++) {
974 num = num * 8 + (c - '0');
975 if ((c = getc(stdin)) < '0' || c > '7')
976 break;
978 (void) ungetc(c, stdin);
979 c = num & 0377;
980 break;
982 default:
983 break;
985 return (c);
989 * getargs - returns an input line. Exits if EOF encountered.
991 #define WHITESPACE 0
992 #define ARGUMENT 1
994 static char **
995 getargs(char *input_line)
997 static char envbuf[MAXLINE];
998 static char *args[MAXARGS];
999 char *ptr, **answer;
1000 int c;
1001 int state;
1002 char *p = input_line;
1004 ptr = envbuf;
1005 answer = &args[0];
1006 state = WHITESPACE;
1008 while ((c = getc(stdin)) != EOF && answer < &args[MAXARGS-1]) {
1010 *(input_line++) = c;
1012 switch (c) {
1014 case '\n':
1015 if (ptr == &envbuf[0])
1016 return ((char **)NULL);
1017 *input_line = *ptr = '\0';
1018 *answer = NULL;
1019 return (&args[0]);
1021 case ' ':
1022 case '\t':
1023 if (state == ARGUMENT) {
1024 *ptr++ = '\0';
1025 state = WHITESPACE;
1027 break;
1029 case '\\':
1030 c = quotec();
1032 default:
1033 if (state == WHITESPACE) {
1034 *answer++ = ptr;
1035 state = ARGUMENT;
1037 *ptr++ = c;
1040 /* Attempt at overflow, exit */
1041 if (input_line - p >= MAXLINE - 1 ||
1042 ptr >= &envbuf[sizeof (envbuf) - 1]) {
1043 audit_error = ADT_FAIL_VALUE_INPUT_OVERFLOW;
1044 login_exit(1);
1049 * If we left loop because an EOF was received or we've overflown
1050 * args[], exit immediately.
1052 login_exit(0);
1053 /* NOTREACHED */
1057 * get_user_name - Gets the user name either passed in, or from the
1058 * login: prompt.
1061 static void
1062 get_user_name(void)
1064 FILE *fp;
1066 if ((fp = fopen(ISSUEFILE, "r")) != NULL) {
1067 char *ptr, buffer[BUFSIZ];
1068 while ((ptr = fgets(buffer, sizeof (buffer), fp)) != NULL) {
1069 (void) fputs(ptr, stdout);
1071 (void) fclose(fp);
1075 * if TTYPROMPT is not set, use our own prompt
1076 * otherwise, use ttyprompt. We just set PAM_USER_PROMPT
1077 * and let the module do the prompting.
1080 if ((ttyprompt == NULL) || (*ttyprompt == '\0'))
1081 (void) pam_set_item(pamh, PAM_USER_PROMPT, (void *)loginmsg);
1082 else
1083 (void) pam_set_item(pamh, PAM_USER_PROMPT, (void *)ttyprompt);
1085 envp = &zero; /* XXX: is this right? */
1090 * Check_for_dueling_unix - Check to see if the another login is talking
1091 * to the line we've got open as a login port
1092 * Exits if we're talking to another unix system
1095 static void
1096 check_for_dueling_unix(char *inputline)
1098 if (EQN(loginmsg, inputline) || EQN(passwdmsg, inputline) ||
1099 EQN(incorrectmsg, inputline)) {
1100 (void) printf("Looking at a login line.\n");
1101 login_exit(8);
1106 * logins_disabled - if the file /etc/nologin exists and the user is not
1107 * root then do not permit them to login
1109 static int
1110 logins_disabled(char *user_name)
1112 FILE *nlfd;
1113 int c;
1114 if (!EQN("root", user_name) &&
1115 ((nlfd = fopen(NOLOGIN, "r")) != NULL)) {
1116 while ((c = getc(nlfd)) != EOF)
1117 (void) putchar(c);
1118 (void) fflush(stdout);
1119 (void) sleep(5);
1120 return (TRUE);
1122 return (FALSE);
1125 #define DEFAULT_CONSOLE "/dev/console"
1128 * check_for_console - Checks if we're getting a root login on the
1129 * console, or a login from the global zone. Exits if not.
1131 * If CONSOLE is set to /dev/console in /etc/default/login, then root logins
1132 * on /dev/vt/# are permitted as well. /dev/vt/# does not exist in non-global
1133 * zones, but checking them does no harm.
1135 static void
1136 check_for_console(void)
1138 const char *consoles[] = { "/dev/console", "/dev/vt/", NULL };
1139 int i;
1141 if (pwd == NULL || pwd->pw_uid != 0 || zflag != B_FALSE ||
1142 Console == NULL)
1143 return;
1145 if (strcmp(Console, DEFAULT_CONSOLE) == 0) {
1146 for (i = 0; consoles[i] != NULL; i ++) {
1147 if (strncmp(ttyn, consoles[i],
1148 strlen(consoles[i])) == 0)
1149 return;
1151 } else {
1152 if (strcmp(ttyn, Console) == 0)
1153 return;
1156 (void) printf("Not on system console\n");
1158 audit_error = ADT_FAIL_VALUE_CONSOLE;
1159 login_exit(10);
1164 * List of environment variables or environment variable prefixes that should
1165 * not be propagated across logins, such as when the login -p option is used.
1167 static const char *const illegal[] = {
1168 "SHELL=",
1169 "HOME=",
1170 "LOGNAME=",
1171 #ifndef NO_MAIL
1172 "MAIL=",
1173 #endif
1174 "CDPATH=",
1175 "IFS=",
1176 "PATH=",
1177 "LD_",
1178 "SMF_",
1179 NULL
1183 * legalenvvar - Is it legal to insert this environmental variable?
1186 static int
1187 legalenvvar(char *s)
1189 const char *const *p;
1191 for (p = &illegal[0]; *p; p++) {
1192 if (strncmp(s, *p, strlen(*p)) == 0)
1193 return (0);
1196 return (1);
1200 * defaults - read defaults
1203 static void
1204 defaults(void)
1206 int flags;
1207 char *ptr;
1209 if (defopen(Pndefault) == 0) {
1211 * ignore case
1213 flags = defcntl(DC_GETFLAGS, 0);
1214 TURNOFF(flags, DC_CASE);
1215 (void) defcntl(DC_SETFLAGS, flags);
1217 if ((Console = defread("CONSOLE=")) != NULL)
1218 Console = strdup(Console);
1220 if ((Altshell = defread("ALTSHELL=")) != NULL)
1221 Altshell = strdup(Altshell);
1223 if ((ptr = defread("PASSREQ=")) != NULL &&
1224 strcasecmp("YES", ptr) == 0)
1225 Passreqflag = 1;
1227 if ((Def_tz = defread("TIMEZONE=")) != NULL)
1228 Def_tz = strdup(Def_tz);
1230 if ((Def_hertz = defread("HZ=")) != NULL)
1231 Def_hertz = strdup(Def_hertz);
1233 if ((Def_path = defread("PATH=")) != NULL)
1234 Def_path = strdup(Def_path);
1236 if ((Def_supath = defread("SUPATH=")) != NULL)
1237 Def_supath = strdup(Def_supath);
1239 if ((ptr = defread("ULIMIT=")) != NULL)
1240 Def_ulimit = atol(ptr);
1242 if ((ptr = defread("TIMEOUT=")) != NULL)
1243 Def_timeout = (unsigned)atoi(ptr);
1245 if ((ptr = defread("UMASK=")) != NULL)
1246 if (sscanf(ptr, "%lo", &Umask) != 1)
1247 Umask = DEFUMASK;
1249 if ((ptr = defread("SLEEPTIME=")) != NULL) {
1250 if (is_number(ptr))
1251 Sleeptime = atoi(ptr);
1254 if ((ptr = defread("DISABLETIME=")) != NULL) {
1255 if (is_number(ptr))
1256 Disabletime = atoi(ptr);
1259 if ((ptr = defread("SYSLOG=")) != NULL)
1260 dosyslog = strcmp(ptr, "YES") == 0;
1262 if ((ptr = defread("RETRIES=")) != NULL) {
1263 if (is_number(ptr))
1264 retry = atoi(ptr);
1267 if ((ptr = defread("SYSLOG_FAILED_LOGINS=")) != NULL) {
1268 if (is_number(ptr))
1269 flogin = atoi(ptr);
1270 else
1271 flogin = retry;
1272 } else
1273 flogin = retry;
1274 (void) defopen(NULL);
1280 * get_options(argc, argv)
1281 * - parse the cmd line.
1282 * - return 0 if successful, -1 if failed.
1283 * Calls login_exit() on misuse of -r, -h, and -z flags
1286 static int
1287 get_options(int argc, char *argv[])
1289 int c;
1290 int errflg = 0;
1291 char sflagname[NMAX+1];
1292 const char *flags_message = "Only one of -r, -h and -z allowed\n";
1294 while ((c = getopt(argc, argv, "u:s:R:f:h:r:pad:t:U:z:")) != -1) {
1295 switch (c) {
1296 case 'a':
1297 break;
1299 case 'd':
1301 * Must be root to pass in device name
1302 * otherwise we exit() as punishment for trying.
1304 if (getuid() != 0 || geteuid() != 0) {
1305 audit_error = ADT_FAIL_VALUE_DEVICE_PERM;
1306 login_exit(1); /* sigh */
1307 /*NOTREACHED*/
1309 ttyn = optarg;
1310 break;
1312 case 'h':
1313 if (hflag || zflag) {
1314 (void) fprintf(stderr, flags_message);
1315 login_exit(1);
1317 hflag = B_TRUE;
1318 SCPYL(remote_host, optarg);
1319 if (argv[optind]) {
1320 if (argv[optind][0] != '-') {
1321 SCPYL(terminal, argv[optind]);
1322 optind++;
1323 } else {
1325 * Allow "login -h hostname -" to
1326 * skip setting up an username as "-".
1328 if (argv[optind][1] == '\0')
1329 optind++;
1333 SCPYL(progname, "telnet");
1334 break;
1336 case 'p':
1337 pflag = B_TRUE;
1338 break;
1340 case 'f':
1342 * Must be root to bypass authentication
1343 * otherwise we exit() as punishment for trying.
1345 if (getuid() != 0 || geteuid() != 0) {
1346 audit_error = ADT_FAIL_VALUE_AUTH_BYPASS;
1348 login_exit(1); /* sigh */
1349 /*NOTREACHED*/
1351 /* save fflag user name for future use */
1352 SCPYL(user_name, optarg);
1353 fflag = B_TRUE;
1354 break;
1355 case 'u':
1356 if (!strlen(optarg)) {
1357 (void) fprintf(stderr,
1358 "Empty string supplied with -u\n");
1359 login_exit(1);
1361 SCPYL(identity, optarg);
1362 uflag = B_TRUE;
1363 break;
1364 case 's':
1365 if (!strlen(optarg)) {
1366 (void) fprintf(stderr,
1367 "Empty string supplied with -s\n");
1368 login_exit(1);
1370 SCPYL(sflagname, optarg);
1371 sflag = B_TRUE;
1372 break;
1373 case 'R':
1374 if (!strlen(optarg)) {
1375 (void) fprintf(stderr,
1376 "Empty string supplied with -R\n");
1377 login_exit(1);
1379 SCPYL(repository, optarg);
1380 Rflag = B_TRUE;
1381 break;
1382 case 't':
1383 if (!strlen(optarg)) {
1384 (void) fprintf(stderr,
1385 "Empty string supplied with -t\n");
1386 login_exit(1);
1388 SCPYL(terminal, optarg);
1389 tflag = B_TRUE;
1390 break;
1391 case 'z':
1392 if (hflag || zflag) {
1393 (void) fprintf(stderr, flags_message);
1394 login_exit(1);
1396 (void) snprintf(zone_name, sizeof (zone_name),
1397 "zone:%s", optarg);
1398 SCPYL(progname, "zlogin");
1399 zflag = B_TRUE;
1400 break;
1401 default:
1402 errflg++;
1403 break;
1404 } /* end switch */
1405 } /* end while */
1408 * If the 's svcname' flag was used, override the progname
1409 * value that is to be used in the pam_start call.
1411 if (sflag)
1412 SCPYL(progname, sflagname);
1415 * get the prompt set by ttymon
1417 ttyprompt = getenv("TTYPROMPT");
1419 if ((ttyprompt != NULL) && (*ttyprompt != '\0')) {
1421 * if ttyprompt is set, there should be data on
1422 * the stream already.
1424 if ((envp = getargs(inputline)) != (char **)NULL) {
1426 * don't get name if name passed as argument.
1428 SCPYL(user_name, *envp++);
1430 } else if (optind < argc) {
1431 SCPYL(user_name, argv[optind]);
1432 (void) SCPYL(inputline, user_name);
1433 (void) strlcat(inputline, " \n", sizeof (inputline));
1434 envp = &argv[optind+1];
1436 if (!fflag)
1437 SCPYL(lusername, user_name);
1440 if (errflg)
1441 return (-1);
1442 return (0);
1446 * usage - Print usage message
1449 static void
1450 usage(void)
1452 (void) fprintf(stderr,
1453 "usage:\n"
1454 " login [-p] [-d device] [-R repository] [-s service]\n"
1455 "\t[-t terminal] [-u identity]\n"
1456 "\t[-h hostname [terminal]] [name [environ]...]\n");
1462 * *** Account validation routines ***
1467 * validate_account - This is the PAM version of validate.
1470 static void
1471 validate_account(void)
1473 int error;
1474 int flag;
1475 int tries; /* new password retries */
1477 (void) alarm(0); /* give user time to come up with password */
1479 if (Passreqflag)
1480 flag = PAM_DISALLOW_NULL_AUTHTOK;
1481 else
1482 flag = 0;
1484 if ((error = pam_acct_mgmt(pamh, flag)) != PAM_SUCCESS) {
1485 if (error == PAM_NEW_AUTHTOK_REQD) {
1486 tries = 1;
1487 error = PAM_AUTHTOK_ERR;
1488 while (error == PAM_AUTHTOK_ERR &&
1489 tries <= DEF_ATTEMPTS) {
1490 if (tries > 1)
1491 (void) printf("Try again\n\n");
1493 (void) printf("Choose a new password.\n");
1495 error = pam_chauthtok(pamh,
1496 PAM_CHANGE_EXPIRED_AUTHTOK);
1497 if (error == PAM_TRY_AGAIN) {
1498 (void) sleep(1);
1499 error = pam_chauthtok(pamh,
1500 PAM_CHANGE_EXPIRED_AUTHTOK);
1502 tries++;
1505 if (error != PAM_SUCCESS) {
1506 if (dosyslog)
1507 syslog(LOG_CRIT,
1508 "change password failure: %s",
1509 pam_strerror(pamh, error));
1510 audit_error = ADT_FAIL_PAM + error;
1511 login_exit(1);
1512 } else {
1513 audit_success(ADT_passwd, pwd, zone_name);
1515 } else {
1516 (void) printf(incorrectmsg);
1518 if (dosyslog)
1519 syslog(LOG_CRIT,
1520 "login account failure: %s",
1521 pam_strerror(pamh, error));
1522 audit_error = ADT_FAIL_PAM + error;
1523 login_exit(1);
1529 * chdir_to_dir_user - Now chdir after setuid/setgid have happened to
1530 * place us in the user's home directory just in
1531 * case it was protected and the first chdir failed.
1532 * No chdir errors should happen at this point because
1533 * all failures should have happened on the first
1534 * time around.
1537 static void
1538 chdir_to_dir_user(void)
1540 if (chdir(pwd->pw_dir) < 0) {
1541 if (chdir("/") < 0) {
1542 (void) printf("No directory!\n");
1544 * This probably won't work since we can't get to /.
1546 if (dosyslog) {
1547 if (remote_host[0]) {
1548 syslog(LOG_CRIT,
1549 "LOGIN FAILURES ON %s FROM %.*s ",
1550 " %.*s", ttyn, HMAX,
1551 remote_host, NMAX, pwd->pw_name);
1552 } else {
1553 syslog(LOG_CRIT,
1554 "LOGIN FAILURES ON %s, %.*s",
1555 ttyn, NMAX, pwd->pw_name);
1558 closelog();
1559 (void) sleep(Disabletime);
1560 exit(1);
1561 } else {
1562 (void) printf("No directory! Logging in with home=/\n");
1563 pwd->pw_dir = "/";
1570 * login_authenticate - Performs the main authentication work
1571 * 1. Prints the login prompt
1572 * 2. Requests and verifys the password
1573 * 3. Checks the port password
1576 static void
1577 login_authenticate(void)
1579 char *user;
1580 int err;
1581 int login_successful = 0;
1583 do {
1584 /* if scheme broken, then nothing to do but quit */
1585 if (pam_get_item(pamh, PAM_USER, (void **)&user) != PAM_SUCCESS)
1586 exit(1);
1589 * only get name from utility if it is not already
1590 * supplied by pam_start or a pam_set_item.
1592 if (!user || !user[0]) {
1593 /* use call back to get user name */
1594 get_user_name();
1597 err = verify_passwd();
1600 * If root login and not on system console then call exit(2)
1602 check_for_console();
1604 switch (err) {
1605 case PAM_SUCCESS:
1606 case PAM_NEW_AUTHTOK_REQD:
1608 * Officially, pam_authenticate() shouldn't return this
1609 * but it's probably the right thing to return if
1610 * PAM_DISALLOW_NULL_AUTHTOK is set so the user will
1611 * be forced to change password later in this code.
1613 count = 0;
1614 login_successful = 1;
1615 break;
1616 case PAM_MAXTRIES:
1617 count = retry;
1618 /*FALLTHROUGH*/
1619 case PAM_AUTH_ERR:
1620 case PAM_AUTHINFO_UNAVAIL:
1621 case PAM_USER_UNKNOWN:
1622 audit_failure(get_audit_id(), ADT_FAIL_PAM + err, pwd,
1623 remote_host, ttyn, zone_name);
1624 log_bad_attempts();
1625 break;
1626 case PAM_ABORT:
1627 log_bad_attempts();
1628 (void) sleep(Disabletime);
1629 (void) printf(incorrectmsg);
1631 audit_error = ADT_FAIL_PAM + err;
1632 login_exit(1);
1633 /*NOTREACHED*/
1634 default: /* Some other PAM error */
1635 audit_error = ADT_FAIL_PAM + err;
1636 login_exit(1);
1637 /*NOTREACHED*/
1640 if (login_successful)
1641 break;
1643 /* sleep after bad passwd */
1644 if (count)
1645 (void) sleep(Sleeptime);
1646 (void) printf(incorrectmsg);
1647 /* force name to be null in this case */
1648 if (pam_set_item(pamh, PAM_USER, NULL) != PAM_SUCCESS)
1649 login_exit(1);
1650 if (pam_set_item(pamh, PAM_RUSER, NULL) != PAM_SUCCESS)
1651 login_exit(1);
1652 } while (count++ < retry);
1654 if (count >= retry) {
1655 audit_failure(get_audit_id(), ADT_FAIL_VALUE_MAX_TRIES, pwd,
1656 remote_host, ttyn, zone_name);
1658 * If logging is turned on, output the
1659 * string storage area to the log file,
1660 * and sleep for Disabletime
1661 * seconds before exiting.
1663 if (writelog)
1664 badlogin();
1665 if (dosyslog) {
1666 if ((pwd = getpwnam(user_name)) != NULL) {
1667 if (remote_host[0]) {
1668 syslog(LOG_CRIT,
1669 "REPEATED LOGIN FAILURES ON %s "
1670 "FROM %.*s, %.*s",
1671 ttyn, HMAX, remote_host, NMAX,
1672 user_name);
1673 } else {
1674 syslog(LOG_CRIT,
1675 "REPEATED LOGIN FAILURES ON "
1676 "%s, %.*s",
1677 ttyn, NMAX, user_name);
1679 } else {
1680 if (remote_host[0]) {
1681 syslog(LOG_CRIT,
1682 "REPEATED LOGIN FAILURES ON %s "
1683 "FROM %.*s",
1684 ttyn, HMAX, remote_host);
1685 } else {
1686 syslog(LOG_CRIT,
1687 "REPEATED LOGIN FAILURES ON %s",
1688 ttyn);
1692 (void) sleep(Disabletime);
1693 exit(1);
1699 * *** Credential Related routines ***
1704 * setup_credentials - sets the group ID, initializes the groups
1705 * and sets up the secretkey.
1706 * Exits if a failure occurrs.
1711 * setup_credentials - PAM does all the work for us on this one.
1714 static void
1715 setup_credentials(void)
1717 int error = 0;
1719 /* set the real (and effective) GID */
1720 if (setgid(pwd->pw_gid) == -1) {
1721 login_exit(1);
1725 * Initialize the supplementary group access list.
1727 if ((user_name[0] == '\0') ||
1728 (initgroups(user_name, pwd->pw_gid) == -1)) {
1729 audit_error = ADT_FAIL_VALUE_PROGRAM;
1730 login_exit(1);
1733 if ((error = pam_setcred(pamh, zflag ? PAM_REINITIALIZE_CRED :
1734 PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1735 audit_error = ADT_FAIL_PAM + error;
1736 login_exit(error);
1740 * Record successful login and fork process that records logout.
1741 * We have to do this after setting credentials because pam_setcred()
1742 * loads key audit info into the cred, but before setuid() so audit
1743 * system calls will work.
1745 audit_success(get_audit_id(), pwd, zone_name);
1748 static uint_t
1749 get_audit_id(void)
1751 if (hflag)
1752 return (ADT_telnet);
1753 else if (zflag)
1754 return (ADT_zlogin);
1756 return (ADT_login);
1761 * *** Routines to get a new user set up and running ***
1763 * Things to do when starting up a new user:
1764 * adjust_nice
1765 * update_utmpx_entry
1766 * establish_user_environment
1767 * exec_the_shell
1773 * adjust_nice - Set the nice (process priority) value if the
1774 * gecos value contains an appropriate value.
1777 static void
1778 adjust_nice(void)
1780 int pri, mflg, i;
1782 if (strncmp("pri=", pwd->pw_gecos, 4) == 0) {
1783 pri = 0;
1784 mflg = 0;
1785 i = 4;
1787 if (pwd->pw_gecos[i] == '-') {
1788 mflg++;
1789 i++;
1792 while (pwd->pw_gecos[i] >= '0' && pwd->pw_gecos[i] <= '9')
1793 pri = (pri * 10) + pwd->pw_gecos[i++] - '0';
1795 if (mflg)
1796 pri = -pri;
1798 (void) nice(pri);
1803 * update_utmpx_entry - Searchs for the correct utmpx entry, making an
1804 * entry there if it finds one, otherwise exits.
1807 static void
1808 update_utmpx_entry(int sublogin, boolean_t silent)
1810 int err;
1811 char *user;
1812 static char *errmsg = "No utmpx entry. "
1813 "You must exec \"login\" from the lowest level \"shell\".";
1814 int tmplen;
1815 struct utmpx *u = NULL;
1816 struct utmpx utmpx;
1817 char *ttyntail;
1818 int pamflags = 0;
1820 if (silent)
1821 pamflags |= PAM_SILENT;
1824 * If we're not a sublogin then
1825 * we'll get an error back if our PID doesn't match the PID of the
1826 * entry we are updating, otherwise if its a sublogin the flags
1827 * field is set to 0, which means we just write a matching entry
1828 * (without checking the pid), or a new entry if an entry doesn't
1829 * exist.
1832 if ((err = pam_open_session(pamh, pamflags)) != PAM_SUCCESS) {
1833 audit_error = ADT_FAIL_PAM + err;
1834 login_exit(1);
1837 if ((err = pam_get_item(pamh, PAM_USER, (void **) &user)) !=
1838 PAM_SUCCESS) {
1839 audit_error = ADT_FAIL_PAM + err;
1840 login_exit(1);
1843 (void) memset(&utmpx, 0, sizeof (utmpx));
1844 (void) time(&utmpx.ut_tv.tv_sec);
1845 utmpx.ut_pid = getpid();
1847 if (hflag) {
1848 SCPYN(utmpx.ut_host, remote_host);
1849 tmplen = strlen(remote_host) + 1;
1850 if (tmplen < sizeof (utmpx.ut_host))
1851 utmpx.ut_syslen = tmplen;
1852 else
1853 utmpx.ut_syslen = sizeof (utmpx.ut_host);
1854 } else if (zflag) {
1856 * If this is a login from another zone, put the
1857 * zone:<zonename> string in the utmpx entry.
1859 SCPYN(utmpx.ut_host, zone_name);
1860 tmplen = strlen(zone_name) + 1;
1861 if (tmplen < sizeof (utmpx.ut_host))
1862 utmpx.ut_syslen = tmplen;
1863 else
1864 utmpx.ut_syslen = sizeof (utmpx.ut_host);
1865 } else {
1866 utmpx.ut_syslen = 0;
1869 SCPYN(utmpx.ut_user, user);
1871 /* skip over "/dev/" */
1872 ttyntail = basename(ttyn);
1874 while ((u = getutxent()) != NULL) {
1875 if ((u->ut_type == INIT_PROCESS ||
1876 u->ut_type == LOGIN_PROCESS ||
1877 u->ut_type == USER_PROCESS) &&
1878 ((sublogin && strncmp(u->ut_line, ttyntail,
1879 sizeof (u->ut_line)) == 0) ||
1880 u->ut_pid == login_pid)) {
1881 SCPYN(utmpx.ut_line, (ttyn+sizeof ("/dev/")-1));
1882 (void) memcpy(utmpx.ut_id, u->ut_id,
1883 sizeof (utmpx.ut_id));
1884 utmpx.ut_exit.e_exit = u->ut_exit.e_exit;
1885 utmpx.ut_type = USER_PROCESS;
1886 (void) pututxline(&utmpx);
1887 break;
1890 endutxent();
1892 if (u == NULL) {
1893 if (!sublogin) {
1895 * no utmpx entry already setup
1896 * (init or telnetd)
1898 (void) puts(errmsg);
1900 audit_error = ADT_FAIL_VALUE_PROGRAM;
1901 login_exit(1);
1903 } else {
1904 /* Now attempt to write out this entry to the wtmp file if */
1905 /* we were successful in getting it from the utmpx file and */
1906 /* the wtmp file exists. */
1907 updwtmpx(WTMPX_FILE, &utmpx);
1914 * process_chroot_logins - Chroots to the specified subdirectory and
1915 * re executes login.
1918 static int
1919 process_chroot_logins(void)
1922 * If the shell field starts with a '*', do a chroot to the home
1923 * directory and perform a new login.
1926 if (*pwd->pw_shell == '*') {
1927 (void) pam_end(pamh, PAM_SUCCESS); /* Done using PAM */
1928 pamh = NULL; /* really done */
1929 if (chroot(pwd->pw_dir) < 0) {
1930 (void) printf("No Root Directory\n");
1932 audit_failure(get_audit_id(),
1933 ADT_FAIL_VALUE_CHDIR_FAILED,
1934 pwd, remote_host, ttyn, zone_name);
1936 return (ERROR);
1939 * Set the environment flag <!sublogin> so that the next login
1940 * knows that it is a sublogin.
1942 envinit[0] = SUBLOGIN;
1943 envinit[1] = NULL;
1944 (void) printf("Subsystem root: %s\n", pwd->pw_dir);
1945 (void) execle("/usr/bin/login", "login", (char *)0,
1946 &envinit[0]);
1947 (void) execle("/etc/login", "login", (char *)0, &envinit[0]);
1948 (void) printf("No /usr/bin/login or /etc/login on root\n");
1950 audit_error = ADT_FAIL_VALUE_PROGRAM;
1952 login_exit(1);
1954 return (OK);
1958 * establish_user_environment - Set up the new users enviornment
1961 static void
1962 establish_user_environment(char **renvp)
1964 int i, j, k, l_index, length, idx = 0;
1965 char *endptr;
1966 char **lenvp;
1967 char **pam_env;
1969 lenvp = environ;
1970 while (*lenvp++)
1973 /* count the number of PAM environment variables set by modules */
1974 if ((pam_env = pam_getenvlist(pamh)) != 0) {
1975 for (idx = 0; pam_env[idx] != 0; idx++)
1979 envinit = (char **)calloc(lenvp - environ + 10 + MAXARGS + idx,
1980 sizeof (char *));
1981 if (envinit == NULL) {
1982 (void) printf("Calloc failed - out of swap space.\n");
1983 login_exit(8);
1987 * add PAM environment variables first so they
1988 * can be overwritten at login's discretion.
1989 * check for illegal environment variables.
1991 idx = 0; basicenv = 0;
1992 if (pam_env != 0) {
1993 while (pam_env[idx] != 0) {
1994 if (legalenvvar(pam_env[idx])) {
1995 envinit[basicenv] = pam_env[idx];
1996 basicenv++;
1998 idx++;
2001 (void) memcpy(&envinit[basicenv], newenv, sizeof (newenv));
2003 /* Set up environment */
2004 if (hflag) {
2005 if (strlen(terminal)) {
2006 ENVSTRNCAT(term, terminal);
2008 } else {
2009 char *tp = getenv("TERM");
2011 if ((tp != NULL) && (*tp != '\0'))
2012 ENVSTRNCAT(term, tp);
2015 ENVSTRNCAT(logname, pwd->pw_name);
2018 * There are three places to get timezone info. init.c sets
2019 * TZ if the file /etc/default/init contains a value for TZ.
2020 * login.c looks in the file /etc/default/login for a
2021 * variable called TIMEZONE being set. If TIMEZONE has a
2022 * value, TZ is set to that value; no environment variable
2023 * TIMEZONE is set, only TZ. If neither of these methods
2024 * work to set TZ, then the library routines will default
2025 * to using the file /usr/lib/locale/TZ/localtime.
2027 * There is a priority set up here. If /etc/default/init has
2028 * a value for TZ, that value remains top priority. If the
2029 * file /etc/default/login has TIMEZONE set, that has second
2030 * highest priority not overriding the value of TZ in
2031 * /etc/default/init. The reason for this priority is that the
2032 * file /etc/default/init is supposed to be sourced by
2033 * /etc/profile. We are doing the "sourcing" prematurely in
2034 * init.c. Additionally, a login C shell doesn't source the
2035 * file /etc/profile thus not sourcing /etc/default/init thus not
2036 * allowing an adminstrator to globally set TZ for all users
2038 if (Def_tz != NULL) /* Is there a TZ from defaults/login? */
2039 tmp_tz = Def_tz;
2041 if ((Def_tz = getenv("TZ")) != NULL) {
2042 ENVSTRNCAT(timez, Def_tz);
2043 } else if (tmp_tz != NULL) {
2044 Def_tz = tmp_tz;
2045 ENVSTRNCAT(timez, Def_tz);
2048 if (Def_hertz == NULL)
2049 (void) sprintf(hertz + strlen(hertz), "%lu", HZ);
2050 else
2051 ENVSTRNCAT(hertz, Def_hertz);
2053 if (Def_path == NULL)
2054 (void) strlcat(path, DEF_PATH, sizeof (path));
2055 else
2056 ENVSTRNCAT(path, Def_path);
2058 ENVSTRNCAT(home, pwd->pw_dir);
2061 * Find the end of the basic environment
2063 for (basicenv = 0; envinit[basicenv] != NULL; basicenv++)
2067 * If TZ has a value, add it.
2069 if (strcmp(timez, "TZ=") != 0)
2070 envinit[basicenv++] = timez;
2072 if (*pwd->pw_shell == '\0') {
2073 pwd->pw_shell = SHELL;
2074 } else if (Altshell != NULL && strcmp(Altshell, "YES") == 0) {
2075 envinit[basicenv++] = shell;
2076 ENVSTRNCAT(shell, pwd->pw_shell);
2079 #ifndef NO_MAIL
2080 envinit[basicenv++] = mail;
2081 (void) strlcat(mail, pwd->pw_name, sizeof (mail));
2082 #endif
2085 * Pick up locale environment variables, if any.
2087 lenvp = renvp;
2088 while (*lenvp != NULL) {
2089 j = 0;
2090 while (localeenv[j] != 0) {
2092 * locale_envmatch() returns 1 if
2093 * *lenvp is localenev[j] and valid.
2095 if (locale_envmatch(localeenv[j], *lenvp) == 1) {
2096 envinit[basicenv++] = *lenvp;
2097 break;
2099 j++;
2101 lenvp++;
2105 * If '-p' flag, then try to pass on allowable environment
2106 * variables. Note that by processing this first, what is
2107 * passed on the final "login:" line may over-ride the invocation
2108 * values. XXX is this correct?
2110 if (pflag) {
2111 for (lenvp = renvp; *lenvp; lenvp++) {
2112 if (!legalenvvar(*lenvp)) {
2113 continue;
2116 * If this isn't 'xxx=yyy', skip it. XXX
2118 if ((endptr = strchr(*lenvp, '=')) == NULL) {
2119 continue;
2121 length = endptr + 1 - *lenvp;
2122 for (j = 0; j < basicenv; j++) {
2123 if (strncmp(envinit[j], *lenvp, length) == 0) {
2125 * Replace previously established value
2127 envinit[j] = *lenvp;
2128 break;
2131 if (j == basicenv) {
2133 * It's a new definition, so add it at the end.
2135 envinit[basicenv++] = *lenvp;
2141 * Add in all the environment variables picked up from the
2142 * argument list to "login" or from the user response to the
2143 * "login" request, if any.
2146 if (envp == NULL)
2147 goto switch_env; /* done */
2149 for (j = 0, k = 0, l_index = 0;
2150 *envp != NULL && j < (MAXARGS-1);
2151 j++, envp++) {
2154 * Scan each string provided. If it doesn't have the
2155 * format xxx=yyy, then add the string "Ln=" to the beginning.
2157 if ((endptr = strchr(*envp, '=')) == NULL) {
2159 * This much to be malloc'd:
2160 * strlen(*envp) + 1 char for 'L' +
2161 * MAXARGSWIDTH + 1 char for '=' + 1 for null char;
2163 * total = strlen(*envp) + MAXARGSWIDTH + 3
2165 int total = strlen(*envp) + MAXARGSWIDTH + 3;
2166 envinit[basicenv+k] = malloc(total);
2167 if (envinit[basicenv+k] == NULL) {
2168 (void) printf("%s: malloc failed\n", PROG_NAME);
2169 login_exit(1);
2171 (void) snprintf(envinit[basicenv+k], total, "L%d=%s",
2172 l_index, *envp);
2174 k++;
2175 l_index++;
2176 } else {
2177 if (!legalenvvar(*envp)) { /* this env var permited? */
2178 continue;
2179 } else {
2182 * Check to see whether this string replaces
2183 * any previously defined string
2185 for (i = 0, length = endptr + 1 - *envp;
2186 i < basicenv + k; i++) {
2187 if (strncmp(*envp, envinit[i], length)
2188 == 0) {
2189 envinit[i] = *envp;
2190 break;
2195 * If it doesn't, place it at the end of
2196 * environment array.
2198 if (i == basicenv+k) {
2199 envinit[basicenv+k] = *envp;
2200 k++;
2204 } /* for (j = 0 ... ) */
2206 switch_env:
2208 * Switch to the new environment.
2210 environ = envinit;
2214 * exec_the_shell - invoke the specified shell or start up program
2217 static void
2218 exec_the_shell(void)
2220 char *endptr;
2221 int i;
2223 (void) strlcat(minusnam, basename(pwd->pw_shell),
2224 sizeof (minusnam));
2227 * Exec the shell
2229 (void) execl(pwd->pw_shell, minusnam, (char *)0);
2232 * pwd->pw_shell was not an executable object file, maybe it
2233 * is a shell proceedure or a command line with arguments.
2234 * If so, turn off the SHELL= environment variable.
2236 for (i = 0; envinit[i] != NULL; ++i) {
2237 if ((envinit[i] == shell) &&
2238 ((endptr = strchr(shell, '=')) != NULL))
2239 (*++endptr) = '\0';
2242 if (access(pwd->pw_shell, R_OK|X_OK) == 0) {
2243 (void) execl(SHELL, "sh", pwd->pw_shell, (char *)0);
2246 (void) printf("No shell\n");
2250 * login_exit - Call exit() and terminate.
2251 * This function is here for PAM so cleanup can
2252 * be done before the process exits.
2254 static void
2255 login_exit(int exit_code)
2257 if (pamh)
2258 (void) pam_end(pamh, PAM_ABORT);
2260 if (audit_error)
2261 audit_failure(get_audit_id(), audit_error,
2262 pwd, remote_host, ttyn, zone_name);
2264 exit(exit_code);
2265 /*NOTREACHED*/
2269 * Check if lenv and penv matches or not.
2271 static int
2272 locale_envmatch(char *lenv, char *penv)
2274 while ((*lenv == *penv) && *lenv && *penv != '=') {
2275 lenv++;
2276 penv++;
2280 * '/' is eliminated for security reason.
2282 if (*lenv == '\0' && *penv == '=' && *(penv + 1) != '/')
2283 return (1);
2284 return (0);
2287 static int
2288 is_number(char *ptr)
2290 while (*ptr != '\0') {
2291 if (!isdigit(*ptr))
2292 return (0);
2293 ptr++;
2295 return (1);
2298 static void
2299 interrupt_syscall(int sig)
2301 return;
2304 static void
2305 printmotd(void)
2307 int fd;
2308 char buf[2048];
2309 ssize_t nr;
2311 if ((fd = open("/etc/motd", O_RDONLY)) < 0)
2312 return;
2314 (void) signal(SIGINT, interrupt_syscall);
2316 while ((nr = read(fd, buf, sizeof(buf))) > 0 &&
2317 write(STDOUT_FILENO, buf, nr) == nr)
2320 close(fd);