lineedit: print prompt and editing operations to stderr
[busybox-git.git] / loginutils / login.c
blob301be4a348467b37bc02915f54fdc646c312bfe0
1 /* vi: set sw=4 ts=4: */
2 /*
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 */
5 //config:config LOGIN
6 //config: bool "login (25 kb)"
7 //config: default y
8 //config: select FEATURE_SYSLOG
9 //config: help
10 //config: login is used when signing onto a system.
11 //config:
12 //config: Note that busybox binary must be setuid root for this applet to
13 //config: work properly.
14 //config:
15 //config:config LOGIN_SESSION_AS_CHILD
16 //config: bool "Run logged in session in a child process"
17 //config: default y if PAM
18 //config: depends on LOGIN
19 //config: help
20 //config: Run the logged in session in a child process. This allows
21 //config: login to clean up things such as utmp entries or PAM sessions
22 //config: when the login session is complete. If you use PAM, you
23 //config: almost always would want this to be set to Y, else PAM session
24 //config: will not be cleaned up.
25 //config:
26 //config:config LOGIN_SCRIPTS
27 //config: bool "Support login scripts"
28 //config: depends on LOGIN
29 //config: default y
30 //config: help
31 //config: Enable this if you want login to execute $LOGIN_PRE_SUID_SCRIPT
32 //config: just prior to switching from root to logged-in user.
33 //config:
34 //config:config FEATURE_NOLOGIN
35 //config: bool "Support /etc/nologin"
36 //config: default y
37 //config: depends on LOGIN
38 //config: help
39 //config: The file /etc/nologin is used by (some versions of) login(1).
40 //config: If it exists, non-root logins are prohibited.
41 //config:
42 //config:config FEATURE_SECURETTY
43 //config: bool "Support /etc/securetty"
44 //config: default y
45 //config: depends on LOGIN
46 //config: help
47 //config: The file /etc/securetty is used by (some versions of) login(1).
48 //config: The file contains the device names of tty lines (one per line,
49 //config: without leading /dev/) on which root is allowed to login.
51 //applet:/* Needs to be run by root or be suid root - needs to change uid and gid: */
52 //applet:IF_LOGIN(APPLET(login, BB_DIR_BIN, BB_SUID_REQUIRE))
54 //kbuild:lib-$(CONFIG_LOGIN) += login.o
56 //usage:#define login_trivial_usage
57 //usage: "[-p] [-h HOST] [[-f] USER]"
58 //usage:#define login_full_usage "\n\n"
59 //usage: "Begin a new session on the system\n"
60 //usage: "\n -f Don't authenticate (user already authenticated)"
61 //usage: "\n -h HOST Host user came from (for network logins)"
62 //usage: "\n -p Preserve environment"
63 //usage: "\n"
64 //usage: "\n$LOGIN_TIMEOUT Seconds (default 60, 0 - disable)"
65 //usage: IF_LOGIN_SCRIPTS(
66 //usage: "\n$LOGIN_PRE_SUID_SCRIPT Execute before user ID change"
67 //usage: )
69 #include "libbb.h"
70 #include "common_bufsiz.h"
71 #include <syslog.h>
73 #if ENABLE_SELINUX
74 # include <selinux/selinux.h> /* for is_selinux_enabled() */
75 # include <selinux/get_context_list.h> /* for get_default_context() */
76 # /* from deprecated <selinux/flask.h>: */
77 # undef SECCLASS_CHR_FILE
78 # define SECCLASS_CHR_FILE 10
79 #endif
81 #if ENABLE_PAM
82 /* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
83 # undef setlocale
84 /* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
85 * Apparently they like to confuse people. */
86 # include <security/pam_appl.h>
87 # include <security/pam_misc.h>
89 # if 0
90 /* This supposedly can be used to avoid double password prompt,
91 * if used instead of standard misc_conv():
93 * "When we want to authenticate first with local method and then with tacacs for example,
94 * the password is asked for local method and if not good is asked a second time for tacacs.
95 * So if we want to authenticate a user with tacacs, and the user exists localy, the password is
96 * asked two times before authentication is accepted."
98 * However, code looks shaky. For example, why misc_conv() return value is ignored?
99 * Are msg[i] and resp[i] indexes handled correctly?
101 static char *passwd = NULL;
102 static int my_conv(int num_msg, const struct pam_message **msg,
103 struct pam_response **resp, void *data)
105 int i;
106 for (i = 0; i < num_msg; i++) {
107 switch (msg[i]->msg_style) {
108 case PAM_PROMPT_ECHO_OFF:
109 if (passwd == NULL) {
110 misc_conv(num_msg, msg, resp, data);
111 passwd = xstrdup(resp[i]->resp);
112 return PAM_SUCCESS;
115 resp[0] = xzalloc(sizeof(struct pam_response));
116 resp[0]->resp = passwd;
117 passwd = NULL;
118 resp[0]->resp_retcode = PAM_SUCCESS;
119 resp[1] = NULL;
120 return PAM_SUCCESS;
122 default:
123 break;
127 return PAM_SUCCESS;
129 # endif
131 static const struct pam_conv conv = {
132 misc_conv,
133 NULL
135 #endif
137 enum {
138 EMPTY_USERNAME_COUNT = 10,
139 /* Some users found 32 chars limit to be too low: */
140 USERNAME_SIZE = 64,
141 TTYNAME_SIZE = 32,
144 struct globals {
145 struct termios tty_attrs;
146 int timeout;
147 } FIX_ALIASING;
148 #define G (*(struct globals*)bb_common_bufsiz1)
149 #define INIT_G() do { setup_common_bufsiz(); } while (0)
152 #if ENABLE_FEATURE_NOLOGIN
153 static void die_if_nologin(void)
155 FILE *fp;
156 int c;
157 int empty = 1;
159 fp = fopen_for_read("/etc/nologin");
160 if (!fp) /* assuming it does not exist */
161 return;
163 while ((c = getc(fp)) != EOF) {
164 if (c == '\n')
165 bb_putchar('\r');
166 bb_putchar(c);
167 empty = 0;
169 if (empty)
170 puts("\r\nSystem closed for routine maintenance\r");
172 fclose(fp);
173 fflush_all();
174 /* Users say that they do need this prior to exit: */
175 tcdrain(STDOUT_FILENO);
176 exit_FAILURE();
178 #else
179 # define die_if_nologin() ((void)0)
180 #endif
182 #if ENABLE_SELINUX
183 static void initselinux(char *username, char *full_tty,
184 security_context_t *user_sid)
186 security_context_t old_tty_sid, new_tty_sid;
188 if (!is_selinux_enabled())
189 return;
191 if (get_default_context(username, NULL, user_sid)) {
192 bb_error_msg_and_die("can't get SID for %s", username);
194 if (getfilecon(full_tty, &old_tty_sid) < 0) {
195 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
197 if (security_compute_relabel(*user_sid, old_tty_sid,
198 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
199 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
201 if (setfilecon(full_tty, new_tty_sid) != 0) {
202 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
205 #endif
207 #if ENABLE_LOGIN_SCRIPTS
208 static void run_login_script(struct passwd *pw, char *full_tty)
210 char *t_argv[2];
212 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
213 if (t_argv[0]) {
214 t_argv[1] = NULL;
215 xsetenv("LOGIN_TTY", full_tty);
216 xsetenv("LOGIN_USER", pw->pw_name);
217 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
218 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
219 xsetenv("LOGIN_SHELL", pw->pw_shell);
220 spawn_and_wait(t_argv); /* NOMMU-friendly */
221 unsetenv("LOGIN_TTY");
222 unsetenv("LOGIN_USER");
223 unsetenv("LOGIN_UID");
224 unsetenv("LOGIN_GID");
225 unsetenv("LOGIN_SHELL");
228 #else
229 void run_login_script(struct passwd *pw, char *full_tty);
230 #endif
232 #if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
233 static void login_pam_end(pam_handle_t *pamh)
235 int pamret;
237 pamret = pam_setcred(pamh, PAM_DELETE_CRED);
238 if (pamret != PAM_SUCCESS) {
239 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
240 pam_strerror(pamh, pamret), pamret);
242 pamret = pam_close_session(pamh, 0);
243 if (pamret != PAM_SUCCESS) {
244 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
245 pam_strerror(pamh, pamret), pamret);
247 pamret = pam_end(pamh, pamret);
248 if (pamret != PAM_SUCCESS) {
249 bb_error_msg("pam_%s failed: %s (%d)", "end",
250 pam_strerror(pamh, pamret), pamret);
253 #else
254 # define login_pam_end(pamh) ((void)0)
255 #endif
257 static void get_username_or_die(char *buf, int size_buf)
259 int c, cntdown;
261 cntdown = EMPTY_USERNAME_COUNT;
262 prompt:
263 print_login_prompt();
264 /* skip whitespace */
265 do {
266 c = getchar();
267 if (c == EOF)
268 exit_FAILURE();
269 if (c == '\n') {
270 if (!--cntdown)
271 exit_FAILURE();
272 goto prompt;
274 } while (isspace(c)); /* maybe isblank? */
276 *buf++ = c;
277 if (!fgets(buf, size_buf-2, stdin))
278 exit_FAILURE();
279 if (!strchr(buf, '\n'))
280 exit_FAILURE();
281 while ((unsigned char)*buf > ' ')
282 buf++;
283 *buf = '\0';
286 static void motd(void)
288 int fd;
290 fd = open(bb_path_motd_file, O_RDONLY);
291 if (fd >= 0) {
292 fflush_all();
293 bb_copyfd_eof(fd, STDOUT_FILENO);
294 close(fd);
298 static void alarm_handler(int sig UNUSED_PARAM)
300 /* This is the escape hatch! Poor serial line users and the like
301 * arrive here when their connection is broken.
302 * We don't want to block here */
303 ndelay_on(STDOUT_FILENO);
304 /* Test for correct attr restoring:
305 * run "getty 0 -" from a shell, enter bogus username, stop at
306 * password prompt, let it time out. Without the tcsetattr below,
307 * when you are back at shell prompt, echo will be still off.
309 tcsetattr_stdin_TCSANOW(&G.tty_attrs);
310 printf("\r\nLogin timed out after %u seconds\r\n", G.timeout);
311 fflush_all();
312 /* unix API is brain damaged regarding O_NONBLOCK,
313 * we should undo it, or else we can affect other processes */
314 ndelay_off(STDOUT_FILENO);
315 _exit_SUCCESS();
318 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
319 int login_main(int argc UNUSED_PARAM, char **argv)
321 enum {
322 LOGIN_OPT_f = (1<<0),
323 LOGIN_OPT_h = (1<<1),
324 LOGIN_OPT_p = (1<<2),
326 char *fromhost;
327 char username[USERNAME_SIZE];
328 int run_by_root;
329 unsigned opt;
330 int count = 0;
331 struct passwd *pw;
332 char *opt_host = NULL;
333 char *opt_user = opt_user; /* for compiler */
334 char *full_tty;
335 char *short_tty;
336 IF_SELINUX(security_context_t user_sid = NULL;)
337 #if ENABLE_PAM
338 int pamret;
339 pam_handle_t *pamh;
340 const char *pamuser;
341 const char *failed_msg;
342 struct passwd pwdstruct;
343 char pwdbuf[256];
344 char **pamenv;
345 #endif
346 #if ENABLE_LOGIN_SESSION_AS_CHILD
347 pid_t child_pid;
348 #endif
349 IF_FEATURE_UTMP(pid_t my_pid;)
351 INIT_G();
353 G.timeout = xatoi_positive(getenv("LOGIN_TIMEOUT") ? : "60");
355 /* More of suid paranoia if called by non-root: */
356 /* Clear dangerous stuff, set PATH */
357 run_by_root = !sanitize_env_if_suid();
359 /* Mandatory paranoia for suid applet:
360 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
361 * and any extra open fd's are closed.
363 bb_daemon_helper(DAEMON_CLOSE_EXTRA_FDS);
365 username[0] = '\0';
366 opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
367 if (opt & LOGIN_OPT_f) {
368 if (!run_by_root)
369 bb_simple_error_msg_and_die("-f is for root only");
370 safe_strncpy(username, opt_user, sizeof(username));
372 argv += optind;
373 if (argv[0]) /* user from command line (getty) */
374 safe_strncpy(username, argv[0], sizeof(username));
376 /* Save tty attributes - and by doing it, check that it's indeed a tty */
377 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
378 || !isatty(STDOUT_FILENO)
379 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
381 return EXIT_FAILURE; /* Must be a terminal */
384 /* We install timeout handler only _after_ we saved G.tty_attrs */
385 signal(SIGALRM, alarm_handler);
386 alarm(G.timeout);
388 /* Find out and memorize our tty name */
389 full_tty = xmalloc_ttyname(STDIN_FILENO);
390 if (!full_tty)
391 full_tty = xstrdup("UNKNOWN");
392 short_tty = skip_dev_pfx(full_tty);
394 if (opt_host) {
395 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
396 } else {
397 fromhost = xasprintf(" on '%s'", short_tty);
400 /* Was breaking "login <username>" from shell command line: */
401 /*bb_setpgrp();*/
403 openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
405 while (1) {
406 /* flush away any type-ahead (as getty does) */
407 tcflush(0, TCIFLUSH);
409 if (!username[0])
410 get_username_or_die(username, sizeof(username));
412 #if ENABLE_PAM
413 pamret = pam_start("login", username, &conv, &pamh);
414 if (pamret != PAM_SUCCESS) {
415 failed_msg = "start";
416 goto pam_auth_failed;
418 /* set TTY (so things like securetty work) */
419 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
420 if (pamret != PAM_SUCCESS) {
421 failed_msg = "set_item(TTY)";
422 goto pam_auth_failed;
424 /* set RHOST */
425 if (opt_host) {
426 pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
427 if (pamret != PAM_SUCCESS) {
428 failed_msg = "set_item(RHOST)";
429 goto pam_auth_failed;
432 if (!(opt & LOGIN_OPT_f)) {
433 pamret = pam_authenticate(pamh, 0);
434 if (pamret != PAM_SUCCESS) {
435 failed_msg = "authenticate";
436 goto pam_auth_failed;
437 /* TODO: or just "goto auth_failed"
438 * since user seems to enter wrong password
439 * (in this case pamret == 7)
443 /* check that the account is healthy */
444 pamret = pam_acct_mgmt(pamh, 0);
445 if (pamret == PAM_NEW_AUTHTOK_REQD) {
446 pamret = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
448 if (pamret != PAM_SUCCESS) {
449 failed_msg = "acct_mgmt";
450 goto pam_auth_failed;
452 /* read user back */
453 pamuser = NULL;
454 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
455 * thus we cast to (void*) */
456 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
457 failed_msg = "get_item(USER)";
458 goto pam_auth_failed;
460 if (!pamuser || !pamuser[0])
461 goto auth_failed;
462 safe_strncpy(username, pamuser, sizeof(username));
463 /* Don't use "pw = getpwnam(username);",
464 * PAM is said to be capable of destroying static storage
465 * used by getpwnam(). We are using safe(r) function */
466 pw = NULL;
467 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
468 if (!pw)
469 goto auth_failed;
470 pamret = pam_open_session(pamh, 0);
471 if (pamret != PAM_SUCCESS) {
472 failed_msg = "open_session";
473 goto pam_auth_failed;
475 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
476 if (pamret != PAM_SUCCESS) {
477 failed_msg = "setcred";
478 goto pam_auth_failed;
480 break; /* success, continue login process */
482 pam_auth_failed:
483 /* syslog, because we don't want potential attacker
484 * to know _why_ login failed */
485 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
486 pam_strerror(pamh, pamret), pamret);
487 login_pam_end(pamh);
488 safe_strncpy(username, "UNKNOWN", sizeof(username));
489 #else /* not PAM */
490 pw = getpwnam(username);
491 if (!pw) {
492 strcpy(username, "UNKNOWN");
493 goto fake_it;
496 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
497 goto auth_failed;
499 if (opt & LOGIN_OPT_f)
500 break; /* -f USER: success without asking passwd */
502 if (pw->pw_uid == 0 && !is_tty_secure(short_tty))
503 goto auth_failed;
505 /* Don't check the password if password entry is empty (!) */
506 if (!pw->pw_passwd[0])
507 break;
508 fake_it:
509 /* Password reading and authorization takes place here.
510 * Note that reads (in no-echo mode) trash tty attributes.
511 * If we get interrupted by SIGALRM, we need to restore attrs.
513 if (ask_and_check_password(pw) > 0)
514 break;
515 #endif /* ENABLE_PAM */
516 auth_failed:
517 opt &= ~LOGIN_OPT_f;
518 pause_after_failed_login();
519 /* TODO: doesn't sound like correct English phrase to me */
520 puts("Login incorrect");
521 syslog(LOG_WARNING, "invalid password for '%s'%s",
522 username, fromhost);
523 if (++count == 3) {
524 if (ENABLE_FEATURE_CLEAN_UP)
525 free(fromhost);
526 return EXIT_FAILURE;
528 username[0] = '\0';
529 } /* while (1) */
531 alarm(0);
532 /* We can ignore /etc/nologin if we are logging in as root,
533 * it doesn't matter whether we are run by root or not */
534 if (pw->pw_uid != 0)
535 die_if_nologin();
537 IF_FEATURE_UTMP(my_pid = getpid();)
538 update_utmp(my_pid, USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
540 #if ENABLE_LOGIN_SESSION_AS_CHILD
541 child_pid = vfork();
542 if (child_pid != 0) {
543 if (child_pid < 0)
544 bb_simple_perror_msg("vfork");
545 else {
546 wait_for_exitstatus(child_pid);
548 update_utmp_DEAD_PROCESS(my_pid);
549 login_pam_end(pamh);
550 return 0;
552 #endif
554 IF_SELINUX(initselinux(username, full_tty, &user_sid);)
556 /* Try these, but don't complain if they fail.
557 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
558 fchown(0, pw->pw_uid, pw->pw_gid);
559 fchmod(0, 0600);
561 /* We trust environment only if we run by root */
562 if (ENABLE_LOGIN_SCRIPTS && run_by_root)
563 run_login_script(pw, full_tty);
565 change_identity(pw);
566 setup_environment(pw->pw_shell,
567 (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV)
568 + SETUP_ENV_CHANGEENV
569 + SETUP_ENV_CHDIR,
570 pw);
572 #if ENABLE_PAM
573 /* Modules such as pam_env will setup the PAM environment,
574 * which should be copied into the new environment. */
575 pamenv = pam_getenvlist(pamh);
576 if (pamenv) while (*pamenv) {
577 putenv(*pamenv);
578 pamenv++;
580 #endif
582 if (access(".hushlogin", F_OK) != 0)
583 motd();
585 if (pw->pw_uid == 0)
586 syslog(LOG_INFO, "root login%s", fromhost);
588 if (ENABLE_FEATURE_CLEAN_UP)
589 free(fromhost);
591 /* well, a simple setexeccon() here would do the job as well,
592 * but let's play the game for now */
593 IF_SELINUX(set_current_security_context(user_sid);)
595 // util-linux login also does:
596 // /* start new session */
597 // setsid();
598 // /* TIOCSCTTY: steal tty from other process group */
599 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
600 // BBox login used to do this (see above):
601 // bb_setpgrp();
602 // If this stuff is really needed, add it and explain why!
604 /* Set signals to defaults */
605 /* Non-ignored signals revert to SIG_DFL on exec anyway */
606 /*signal(SIGALRM, SIG_DFL);*/
608 /* Is this correct? This way user can ctrl-c out of /etc/profile,
609 * potentially creating security breach (tested with bash 3.0).
610 * But without this, bash 3.0 will not enable ctrl-c either.
611 * Maybe bash is buggy?
612 * Need to find out what standards say about /bin/login -
613 * should we leave SIGINT etc enabled or disabled?
614 * Also note: sulogin does not do it! Why?
616 signal(SIGINT, SIG_DFL);
618 /* Exec login shell with no additional parameters */
619 exec_login_shell(pw->pw_shell);
621 /* return EXIT_FAILURE; - not reached */