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,
45 struct termios tty_attrs;
47 #define G (*(struct globals*)&bb_common_bufsiz1)
48 #define INIT_G() do { } while (0)
51 #if ENABLE_FEATURE_NOLOGIN
52 static void die_if_nologin(void)
58 fp = fopen_for_read("/etc/nologin");
59 if (!fp) /* assuming it does not exist */
62 while ((c = getc(fp)) != EOF) {
69 puts("\r\nSystem closed for routine maintenance\r");
73 /* Users say that they do need this prior to exit: */
74 tcdrain(STDOUT_FILENO);
78 # define die_if_nologin() ((void)0)
81 #if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
82 static int check_securetty(const char *short_tty)
84 char *buf = (char*)"/etc/securetty"; /* any non-NULL is ok */
85 parser_t *parser = config_open2("/etc/securetty", fopen_for_read);
86 while (config_read(parser, &buf, 1, 1, "# \t", PARSE_NORMAL)) {
87 if (strcmp(buf, short_tty) == 0)
92 /* buf != NULL here if config file was not found, empty
93 * or line was found which equals short_tty */
97 static ALWAYS_INLINE int check_securetty(const char *short_tty UNUSED_PARAM) { return 1; }
101 static void initselinux(char *username, char *full_tty,
102 security_context_t *user_sid)
104 security_context_t old_tty_sid, new_tty_sid;
106 if (!is_selinux_enabled())
109 if (get_default_context(username, NULL, user_sid)) {
110 bb_error_msg_and_die("can't get SID for %s", username);
112 if (getfilecon(full_tty, &old_tty_sid) < 0) {
113 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
115 if (security_compute_relabel(*user_sid, old_tty_sid,
116 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
117 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
119 if (setfilecon(full_tty, new_tty_sid) != 0) {
120 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
125 #if ENABLE_LOGIN_SCRIPTS
126 static void run_login_script(struct passwd *pw, char *full_tty)
130 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
133 xsetenv("LOGIN_TTY", full_tty);
134 xsetenv("LOGIN_USER", pw->pw_name);
135 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
136 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
137 xsetenv("LOGIN_SHELL", pw->pw_shell);
138 spawn_and_wait(t_argv); /* NOMMU-friendly */
139 unsetenv("LOGIN_TTY");
140 unsetenv("LOGIN_USER");
141 unsetenv("LOGIN_UID");
142 unsetenv("LOGIN_GID");
143 unsetenv("LOGIN_SHELL");
147 void run_login_script(struct passwd *pw, char *full_tty);
150 #if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
151 static void login_pam_end(pam_handle_t *pamh)
155 pamret = pam_setcred(pamh, PAM_DELETE_CRED);
156 if (pamret != PAM_SUCCESS) {
157 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
158 pam_strerror(pamh, pamret), pamret);
160 pamret = pam_close_session(pamh, 0);
161 if (pamret != PAM_SUCCESS) {
162 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
163 pam_strerror(pamh, pamret), pamret);
165 pamret = pam_end(pamh, pamret);
166 if (pamret != PAM_SUCCESS) {
167 bb_error_msg("pam_%s failed: %s (%d)", "end",
168 pam_strerror(pamh, pamret), pamret);
171 #endif /* ENABLE_PAM */
173 static void get_username_or_die(char *buf, int size_buf)
177 cntdown = EMPTY_USERNAME_COUNT;
179 print_login_prompt();
180 /* skip whitespace */
190 } while (isspace(c)); /* maybe isblank? */
193 if (!fgets(buf, size_buf-2, stdin))
195 if (!strchr(buf, '\n'))
197 while ((unsigned char)*buf > ' ')
202 static void motd(void)
206 fd = open(bb_path_motd_file, O_RDONLY);
209 bb_copyfd_eof(fd, STDOUT_FILENO);
214 static void alarm_handler(int sig UNUSED_PARAM)
216 /* This is the escape hatch! Poor serial line users and the like
217 * arrive here when their connection is broken.
218 * We don't want to block here */
219 ndelay_on(STDOUT_FILENO);
220 /* Test for correct attr restoring:
221 * run "getty 0 -" from a shell, enter bogus username, stop at
222 * password prompt, let it time out. Without the tcsetattr below,
223 * when you are back at shell prompt, echo will be still off.
225 tcsetattr_stdin_TCSANOW(&G.tty_attrs);
226 printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
228 /* unix API is brain damaged regarding O_NONBLOCK,
229 * we should undo it, or else we can affect other processes */
230 ndelay_off(STDOUT_FILENO);
234 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
235 int login_main(int argc UNUSED_PARAM, char **argv)
238 LOGIN_OPT_f = (1<<0),
239 LOGIN_OPT_h = (1<<1),
240 LOGIN_OPT_p = (1<<2),
243 char username[USERNAME_SIZE];
248 char *opt_host = NULL;
249 char *opt_user = opt_user; /* for compiler */
252 IF_SELINUX(security_context_t user_sid = NULL;)
257 const char *failed_msg;
258 struct passwd pwdstruct;
262 #if ENABLE_LOGIN_SESSION_AS_CHILD
268 /* More of suid paranoia if called by non-root: */
269 /* Clear dangerous stuff, set PATH */
270 run_by_root = !sanitize_env_if_suid();
272 /* Mandatory paranoia for suid applet:
273 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
274 * and any extra open fd's are closed.
275 * (The name of the function is misleading. Not daemonizing here.) */
276 bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
279 opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
280 if (opt & LOGIN_OPT_f) {
282 bb_error_msg_and_die("-f is for root only");
283 safe_strncpy(username, opt_user, sizeof(username));
286 if (argv[0]) /* user from command line (getty) */
287 safe_strncpy(username, argv[0], sizeof(username));
289 /* Save tty attributes - and by doing it, check that it's indeed a tty */
290 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
291 || !isatty(STDOUT_FILENO)
292 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
294 return EXIT_FAILURE; /* Must be a terminal */
297 /* We install timeout handler only _after_ we saved G.tty_attrs */
298 signal(SIGALRM, alarm_handler);
301 /* Find out and memorize our tty name */
302 full_tty = xmalloc_ttyname(STDIN_FILENO);
304 full_tty = xstrdup("UNKNOWN");
305 short_tty = skip_dev_pfx(full_tty);
308 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
310 fromhost = xasprintf(" on '%s'", short_tty);
313 /* Was breaking "login <username>" from shell command line: */
316 openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
319 /* flush away any type-ahead (as getty does) */
320 tcflush(0, TCIFLUSH);
323 get_username_or_die(username, sizeof(username));
326 pamret = pam_start("login", username, &conv, &pamh);
327 if (pamret != PAM_SUCCESS) {
328 failed_msg = "start";
329 goto pam_auth_failed;
331 /* set TTY (so things like securetty work) */
332 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
333 if (pamret != PAM_SUCCESS) {
334 failed_msg = "set_item(TTY)";
335 goto pam_auth_failed;
339 pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
340 if (pamret != PAM_SUCCESS) {
341 failed_msg = "set_item(RHOST)";
342 goto pam_auth_failed;
345 pamret = pam_authenticate(pamh, 0);
346 if (pamret != PAM_SUCCESS) {
347 failed_msg = "authenticate";
348 goto pam_auth_failed;
349 /* TODO: or just "goto auth_failed"
350 * since user seems to enter wrong password
351 * (in this case pamret == 7)
354 /* check that the account is healthy */
355 pamret = pam_acct_mgmt(pamh, 0);
356 if (pamret != PAM_SUCCESS) {
357 failed_msg = "acct_mgmt";
358 goto pam_auth_failed;
362 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
363 * thus we cast to (void*) */
364 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
365 failed_msg = "get_item(USER)";
366 goto pam_auth_failed;
368 if (!pamuser || !pamuser[0])
370 safe_strncpy(username, pamuser, sizeof(username));
371 /* Don't use "pw = getpwnam(username);",
372 * PAM is said to be capable of destroying static storage
373 * used by getpwnam(). We are using safe(r) function */
375 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
378 pamret = pam_open_session(pamh, 0);
379 if (pamret != PAM_SUCCESS) {
380 failed_msg = "open_session";
381 goto pam_auth_failed;
383 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
384 if (pamret != PAM_SUCCESS) {
385 failed_msg = "setcred";
386 goto pam_auth_failed;
388 break; /* success, continue login process */
391 /* syslog, because we don't want potential attacker
392 * to know _why_ login failed */
393 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
394 pam_strerror(pamh, pamret), pamret);
395 safe_strncpy(username, "UNKNOWN", sizeof(username));
397 pw = getpwnam(username);
399 strcpy(username, "UNKNOWN");
403 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
406 if (opt & LOGIN_OPT_f)
407 break; /* -f USER: success without asking passwd */
409 if (pw->pw_uid == 0 && !check_securetty(short_tty))
412 /* Don't check the password if password entry is empty (!) */
413 if (!pw->pw_passwd[0])
416 /* Password reading and authorization takes place here.
417 * Note that reads (in no-echo mode) trash tty attributes.
418 * If we get interrupted by SIGALRM, we need to restore attrs.
420 if (correct_password(pw))
422 #endif /* ENABLE_PAM */
425 bb_do_delay(LOGIN_FAIL_DELAY);
426 /* TODO: doesn't sound like correct English phrase to me */
427 puts("Login incorrect");
429 syslog(LOG_WARNING, "invalid password for '%s'%s",
432 if (ENABLE_FEATURE_CLEAN_UP)
441 /* We can ignore /etc/nologin if we are logging in as root,
442 * it doesn't matter whether we are run by root or not */
446 #if ENABLE_LOGIN_SESSION_AS_CHILD
448 if (child_pid != 0) {
450 bb_perror_msg("vfork");
452 if (safe_waitpid(child_pid, NULL, 0) == -1)
453 bb_perror_msg("waitpid");
454 update_utmp(child_pid, DEAD_PROCESS, NULL, NULL, NULL);
456 IF_PAM(login_pam_end(pamh);)
461 IF_SELINUX(initselinux(username, full_tty, &user_sid);)
463 /* Try these, but don't complain if they fail.
464 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
465 fchown(0, pw->pw_uid, pw->pw_gid);
468 update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
470 /* We trust environment only if we run by root */
471 if (ENABLE_LOGIN_SCRIPTS && run_by_root)
472 run_login_script(pw, full_tty);
475 setup_environment(pw->pw_shell,
476 (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
480 /* Modules such as pam_env will setup the PAM environment,
481 * which should be copied into the new environment. */
482 pamenv = pam_getenvlist(pamh);
483 if (pamenv) while (*pamenv) {
492 syslog(LOG_INFO, "root login%s", fromhost);
494 if (ENABLE_FEATURE_CLEAN_UP)
497 /* well, a simple setexeccon() here would do the job as well,
498 * but let's play the game for now */
499 IF_SELINUX(set_current_security_context(user_sid);)
501 // util-linux login also does:
502 // /* start new session */
504 // /* TIOCSCTTY: steal tty from other process group */
505 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
506 // BBox login used to do this (see above):
508 // If this stuff is really needed, add it and explain why!
510 /* Set signals to defaults */
511 /* Non-ignored signals revert to SIG_DFL on exec anyway */
512 /*signal(SIGALRM, SIG_DFL);*/
514 /* Is this correct? This way user can ctrl-c out of /etc/profile,
515 * potentially creating security breach (tested with bash 3.0).
516 * But without this, bash 3.0 will not enable ctrl-c either.
517 * Maybe bash is buggy?
518 * Need to find out what standards say about /bin/login -
519 * should we leave SIGINT etc enabled or disabled? */
520 signal(SIGINT, SIG_DFL);
522 /* Exec login shell with no additional parameters */
523 run_shell(pw->pw_shell, 1, NULL, NULL);
525 /* return EXIT_FAILURE; - not reached */