1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6 //usage:#define login_trivial_usage
7 //usage: "[-p] [-h HOST] [[-f] USER]"
8 //usage:#define login_full_usage "\n\n"
9 //usage: "Begin a new session on the system\n"
10 //usage: "\n -f Don't authenticate (user already authenticated)"
11 //usage: "\n -h Name of the remote host"
12 //usage: "\n -p Preserve environment"
16 #include <sys/resource.h>
19 # include <selinux/selinux.h> /* for is_selinux_enabled() */
20 # include <selinux/get_context_list.h> /* for get_default_context() */
21 # include <selinux/flask.h> /* for security class definitions */
25 /* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
27 /* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
28 * Apparently they like to confuse people. */
29 # include <security/pam_appl.h>
30 # include <security/pam_misc.h>
31 static const struct pam_conv conv
= {
39 EMPTY_USERNAME_COUNT
= 10,
40 /* Some users found 32 chars limit to be too low: */
46 struct termios tty_attrs
;
48 #define G (*(struct globals*)&bb_common_bufsiz1)
49 #define INIT_G() do { } while (0)
52 #if ENABLE_FEATURE_NOLOGIN
53 static void die_if_nologin(void)
59 fp
= fopen_for_read("/etc/nologin");
60 if (!fp
) /* assuming it does not exist */
63 while ((c
= getc(fp
)) != EOF
) {
70 puts("\r\nSystem closed for routine maintenance\r");
74 /* Users say that they do need this prior to exit: */
75 tcdrain(STDOUT_FILENO
);
79 # define die_if_nologin() ((void)0)
82 #if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
83 static int check_securetty(const char *short_tty
)
85 char *buf
= (char*)"/etc/securetty"; /* any non-NULL is ok */
86 parser_t
*parser
= config_open2("/etc/securetty", fopen_for_read
);
87 while (config_read(parser
, &buf
, 1, 1, "# \t", PARSE_NORMAL
)) {
88 if (strcmp(buf
, short_tty
) == 0)
93 /* buf != NULL here if config file was not found, empty
94 * or line was found which equals short_tty */
98 static ALWAYS_INLINE
int check_securetty(const char *short_tty UNUSED_PARAM
) { return 1; }
102 static void initselinux(char *username
, char *full_tty
,
103 security_context_t
*user_sid
)
105 security_context_t old_tty_sid
, new_tty_sid
;
107 if (!is_selinux_enabled())
110 if (get_default_context(username
, NULL
, user_sid
)) {
111 bb_error_msg_and_die("can't get SID for %s", username
);
113 if (getfilecon(full_tty
, &old_tty_sid
) < 0) {
114 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty
);
116 if (security_compute_relabel(*user_sid
, old_tty_sid
,
117 SECCLASS_CHR_FILE
, &new_tty_sid
) != 0) {
118 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty
);
120 if (setfilecon(full_tty
, new_tty_sid
) != 0) {
121 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty
, new_tty_sid
);
126 #if ENABLE_LOGIN_SCRIPTS
127 static void run_login_script(struct passwd
*pw
, char *full_tty
)
131 t_argv
[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
134 xsetenv("LOGIN_TTY", full_tty
);
135 xsetenv("LOGIN_USER", pw
->pw_name
);
136 xsetenv("LOGIN_UID", utoa(pw
->pw_uid
));
137 xsetenv("LOGIN_GID", utoa(pw
->pw_gid
));
138 xsetenv("LOGIN_SHELL", pw
->pw_shell
);
139 spawn_and_wait(t_argv
); /* NOMMU-friendly */
140 unsetenv("LOGIN_TTY");
141 unsetenv("LOGIN_USER");
142 unsetenv("LOGIN_UID");
143 unsetenv("LOGIN_GID");
144 unsetenv("LOGIN_SHELL");
148 void run_login_script(struct passwd
*pw
, char *full_tty
);
151 #if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
152 static void login_pam_end(pam_handle_t
*pamh
)
156 pamret
= pam_setcred(pamh
, PAM_DELETE_CRED
);
157 if (pamret
!= PAM_SUCCESS
) {
158 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
159 pam_strerror(pamh
, pamret
), pamret
);
161 pamret
= pam_close_session(pamh
, 0);
162 if (pamret
!= PAM_SUCCESS
) {
163 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
164 pam_strerror(pamh
, pamret
), pamret
);
166 pamret
= pam_end(pamh
, pamret
);
167 if (pamret
!= PAM_SUCCESS
) {
168 bb_error_msg("pam_%s failed: %s (%d)", "end",
169 pam_strerror(pamh
, pamret
), pamret
);
172 #endif /* ENABLE_PAM */
174 static void get_username_or_die(char *buf
, int size_buf
)
178 cntdown
= EMPTY_USERNAME_COUNT
;
180 print_login_prompt();
181 /* skip whitespace */
191 } while (isspace(c
)); /* maybe isblank? */
194 if (!fgets(buf
, size_buf
-2, stdin
))
196 if (!strchr(buf
, '\n'))
198 while ((unsigned char)*buf
> ' ')
203 static void motd(void)
207 fd
= open(bb_path_motd_file
, O_RDONLY
);
210 bb_copyfd_eof(fd
, STDOUT_FILENO
);
215 static void alarm_handler(int sig UNUSED_PARAM
)
217 /* This is the escape hatch! Poor serial line users and the like
218 * arrive here when their connection is broken.
219 * We don't want to block here */
220 ndelay_on(STDOUT_FILENO
);
221 /* Test for correct attr restoring:
222 * run "getty 0 -" from a shell, enter bogus username, stop at
223 * password prompt, let it time out. Without the tcsetattr below,
224 * when you are back at shell prompt, echo will be still off.
226 tcsetattr_stdin_TCSANOW(&G
.tty_attrs
);
227 printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT
);
229 /* unix API is brain damaged regarding O_NONBLOCK,
230 * we should undo it, or else we can affect other processes */
231 ndelay_off(STDOUT_FILENO
);
235 int login_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
236 int login_main(int argc UNUSED_PARAM
, char **argv
)
239 LOGIN_OPT_f
= (1<<0),
240 LOGIN_OPT_h
= (1<<1),
241 LOGIN_OPT_p
= (1<<2),
244 char username
[USERNAME_SIZE
];
249 char *opt_host
= NULL
;
250 char *opt_user
= opt_user
; /* for compiler */
253 IF_SELINUX(security_context_t user_sid
= NULL
;)
258 const char *failed_msg
;
259 struct passwd pwdstruct
;
263 #if ENABLE_LOGIN_SESSION_AS_CHILD
269 /* More of suid paranoia if called by non-root: */
270 /* Clear dangerous stuff, set PATH */
271 run_by_root
= !sanitize_env_if_suid();
273 /* Mandatory paranoia for suid applet:
274 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
275 * and any extra open fd's are closed.
276 * (The name of the function is misleading. Not daemonizing here.) */
277 bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE
| DAEMON_CLOSE_EXTRA_FDS
, NULL
);
280 opt
= getopt32(argv
, "f:h:p", &opt_user
, &opt_host
);
281 if (opt
& LOGIN_OPT_f
) {
283 bb_error_msg_and_die("-f is for root only");
284 safe_strncpy(username
, opt_user
, sizeof(username
));
287 if (argv
[0]) /* user from command line (getty) */
288 safe_strncpy(username
, argv
[0], sizeof(username
));
290 /* Save tty attributes - and by doing it, check that it's indeed a tty */
291 if (tcgetattr(STDIN_FILENO
, &G
.tty_attrs
) < 0
292 || !isatty(STDOUT_FILENO
)
293 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
295 return EXIT_FAILURE
; /* Must be a terminal */
298 /* We install timeout handler only _after_ we saved G.tty_attrs */
299 signal(SIGALRM
, alarm_handler
);
302 /* Find out and memorize our tty name */
303 full_tty
= xmalloc_ttyname(STDIN_FILENO
);
305 full_tty
= xstrdup("UNKNOWN");
306 short_tty
= skip_dev_pfx(full_tty
);
309 fromhost
= xasprintf(" on '%s' from '%s'", short_tty
, opt_host
);
311 fromhost
= xasprintf(" on '%s'", short_tty
);
314 /* Was breaking "login <username>" from shell command line: */
317 openlog(applet_name
, LOG_PID
| LOG_CONS
, LOG_AUTH
);
320 /* flush away any type-ahead (as getty does) */
321 tcflush(0, TCIFLUSH
);
324 get_username_or_die(username
, sizeof(username
));
327 pamret
= pam_start("login", username
, &conv
, &pamh
);
328 if (pamret
!= PAM_SUCCESS
) {
329 failed_msg
= "start";
330 goto pam_auth_failed
;
332 /* set TTY (so things like securetty work) */
333 pamret
= pam_set_item(pamh
, PAM_TTY
, short_tty
);
334 if (pamret
!= PAM_SUCCESS
) {
335 failed_msg
= "set_item(TTY)";
336 goto pam_auth_failed
;
340 pamret
= pam_set_item(pamh
, PAM_RHOST
, opt_host
);
341 if (pamret
!= PAM_SUCCESS
) {
342 failed_msg
= "set_item(RHOST)";
343 goto pam_auth_failed
;
346 if (!(opt
& LOGIN_OPT_f
)) {
347 pamret
= pam_authenticate(pamh
, 0);
348 if (pamret
!= PAM_SUCCESS
) {
349 failed_msg
= "authenticate";
350 goto pam_auth_failed
;
351 /* TODO: or just "goto auth_failed"
352 * since user seems to enter wrong password
353 * (in this case pamret == 7)
357 /* check that the account is healthy */
358 pamret
= pam_acct_mgmt(pamh
, 0);
359 if (pamret
!= PAM_SUCCESS
) {
360 failed_msg
= "acct_mgmt";
361 goto pam_auth_failed
;
365 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
366 * thus we cast to (void*) */
367 if (pam_get_item(pamh
, PAM_USER
, (void*)&pamuser
) != PAM_SUCCESS
) {
368 failed_msg
= "get_item(USER)";
369 goto pam_auth_failed
;
371 if (!pamuser
|| !pamuser
[0])
373 safe_strncpy(username
, pamuser
, sizeof(username
));
374 /* Don't use "pw = getpwnam(username);",
375 * PAM is said to be capable of destroying static storage
376 * used by getpwnam(). We are using safe(r) function */
378 getpwnam_r(username
, &pwdstruct
, pwdbuf
, sizeof(pwdbuf
), &pw
);
381 pamret
= pam_open_session(pamh
, 0);
382 if (pamret
!= PAM_SUCCESS
) {
383 failed_msg
= "open_session";
384 goto pam_auth_failed
;
386 pamret
= pam_setcred(pamh
, PAM_ESTABLISH_CRED
);
387 if (pamret
!= PAM_SUCCESS
) {
388 failed_msg
= "setcred";
389 goto pam_auth_failed
;
391 break; /* success, continue login process */
394 /* syslog, because we don't want potential attacker
395 * to know _why_ login failed */
396 syslog(LOG_WARNING
, "pam_%s call failed: %s (%d)", failed_msg
,
397 pam_strerror(pamh
, pamret
), pamret
);
398 safe_strncpy(username
, "UNKNOWN", sizeof(username
));
400 pw
= getpwnam(username
);
402 strcpy(username
, "UNKNOWN");
406 if (pw
->pw_passwd
[0] == '!' || pw
->pw_passwd
[0] == '*')
409 if (opt
& LOGIN_OPT_f
)
410 break; /* -f USER: success without asking passwd */
412 if (pw
->pw_uid
== 0 && !check_securetty(short_tty
))
415 /* Don't check the password if password entry is empty (!) */
416 if (!pw
->pw_passwd
[0])
419 /* Password reading and authorization takes place here.
420 * Note that reads (in no-echo mode) trash tty attributes.
421 * If we get interrupted by SIGALRM, we need to restore attrs.
423 if (correct_password(pw
))
425 #endif /* ENABLE_PAM */
428 bb_do_delay(LOGIN_FAIL_DELAY
);
429 /* TODO: doesn't sound like correct English phrase to me */
430 puts("Login incorrect");
432 syslog(LOG_WARNING
, "invalid password for '%s'%s",
435 if (ENABLE_FEATURE_CLEAN_UP
)
444 /* We can ignore /etc/nologin if we are logging in as root,
445 * it doesn't matter whether we are run by root or not */
449 #if ENABLE_LOGIN_SESSION_AS_CHILD
451 if (child_pid
!= 0) {
453 bb_perror_msg("vfork");
455 if (safe_waitpid(child_pid
, NULL
, 0) == -1)
456 bb_perror_msg("waitpid");
457 update_utmp(child_pid
, DEAD_PROCESS
, NULL
, NULL
, NULL
);
459 IF_PAM(login_pam_end(pamh
);)
464 IF_SELINUX(initselinux(username
, full_tty
, &user_sid
);)
466 /* Try these, but don't complain if they fail.
467 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
468 fchown(0, pw
->pw_uid
, pw
->pw_gid
);
471 update_utmp(getpid(), USER_PROCESS
, short_tty
, username
, run_by_root
? opt_host
: NULL
);
473 /* We trust environment only if we run by root */
474 if (ENABLE_LOGIN_SCRIPTS
&& run_by_root
)
475 run_login_script(pw
, full_tty
);
478 setup_environment(pw
->pw_shell
,
479 (!(opt
& LOGIN_OPT_p
) * SETUP_ENV_CLEARENV
) + SETUP_ENV_CHANGEENV
,
483 /* Modules such as pam_env will setup the PAM environment,
484 * which should be copied into the new environment. */
485 pamenv
= pam_getenvlist(pamh
);
486 if (pamenv
) while (*pamenv
) {
495 syslog(LOG_INFO
, "root login%s", fromhost
);
497 if (ENABLE_FEATURE_CLEAN_UP
)
500 /* well, a simple setexeccon() here would do the job as well,
501 * but let's play the game for now */
502 IF_SELINUX(set_current_security_context(user_sid
);)
504 // util-linux login also does:
505 // /* start new session */
507 // /* TIOCSCTTY: steal tty from other process group */
508 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
509 // BBox login used to do this (see above):
511 // If this stuff is really needed, add it and explain why!
513 /* Set signals to defaults */
514 /* Non-ignored signals revert to SIG_DFL on exec anyway */
515 /*signal(SIGALRM, SIG_DFL);*/
517 /* Is this correct? This way user can ctrl-c out of /etc/profile,
518 * potentially creating security breach (tested with bash 3.0).
519 * But without this, bash 3.0 will not enable ctrl-c either.
520 * Maybe bash is buggy?
521 * Need to find out what standards say about /bin/login -
522 * should we leave SIGINT etc enabled or disabled? */
523 signal(SIGINT
, SIG_DFL
);
525 /* Exec login shell with no additional parameters */
526 run_shell(pw
->pw_shell
, 1, NULL
, NULL
);
528 /* return EXIT_FAILURE; - not reached */