summaryrefslogtreecommitdiff
path: root/loginutils/login.c (plain)
blob: 03ddadb6bcfa165e4d16b7088d70f54fdfcd5f0c
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"
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 for 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 for /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 for /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.
50
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))
53
54//kbuild:lib-$(CONFIG_LOGIN) += login.o
55
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
64#include "libbb.h"
65#include "common_bufsiz.h"
66#include <syslog.h>
67#include <sys/resource.h>
68
69#if ENABLE_SELINUX
70# include <selinux/selinux.h> /* for is_selinux_enabled() */
71#ifndef __BIONIC__
72# include <selinux/get_context_list.h> /* for get_default_context() */
73# /* from deprecated <selinux/flask.h>: */
74# undef SECCLASS_CHR_FILE
75# define SECCLASS_CHR_FILE 10
76#endif
77#endif
78
79#if ENABLE_PAM
80/* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
81# undef setlocale
82/* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
83 * Apparently they like to confuse people. */
84# include <security/pam_appl.h>
85# include <security/pam_misc.h>
86
87# if 0
88/* This supposedly can be used to avoid double password prompt,
89 * if used instead of standard misc_conv():
90 *
91 * "When we want to authenticate first with local method and then with tacacs for example,
92 * the password is asked for local method and if not good is asked a second time for tacacs.
93 * So if we want to authenticate a user with tacacs, and the user exists localy, the password is
94 * asked two times before authentication is accepted."
95 *
96 * However, code looks shaky. For example, why misc_conv() return value is ignored?
97 * Are msg[i] and resp[i] indexes handled correctly?
98 */
99static char *passwd = NULL;
100static int my_conv(int num_msg, const struct pam_message **msg,
101 struct pam_response **resp, void *data)
102{
103 int i;
104 for (i = 0; i < num_msg; i++) {
105 switch (msg[i]->msg_style) {
106 case PAM_PROMPT_ECHO_OFF:
107 if (passwd == NULL) {
108 misc_conv(num_msg, msg, resp, data);
109 passwd = xstrdup(resp[i]->resp);
110 return PAM_SUCCESS;
111 }
112
113 resp[0] = xzalloc(sizeof(struct pam_response));
114 resp[0]->resp = passwd;
115 passwd = NULL;
116 resp[0]->resp_retcode = PAM_SUCCESS;
117 resp[1] = NULL;
118 return PAM_SUCCESS;
119
120 default:
121 break;
122 }
123 }
124
125 return PAM_SUCCESS;
126}
127# endif
128
129static const struct pam_conv conv = {
130 misc_conv,
131 NULL
132};
133#endif
134
135enum {
136 TIMEOUT = 60,
137 EMPTY_USERNAME_COUNT = 10,
138 /* Some users found 32 chars limit to be too low: */
139 USERNAME_SIZE = 64,
140 TTYNAME_SIZE = 32,
141};
142
143struct globals {
144 struct termios tty_attrs;
145} FIX_ALIASING;
146#define G (*(struct globals*)bb_common_bufsiz1)
147#define INIT_G() do { setup_common_bufsiz(); } while (0)
148
149
150#if ENABLE_FEATURE_NOLOGIN
151static void die_if_nologin(void)
152{
153 FILE *fp;
154 int c;
155 int empty = 1;
156
157 fp = fopen_for_read("/etc/nologin");
158 if (!fp) /* assuming it does not exist */
159 return;
160
161 while ((c = getc(fp)) != EOF) {
162 if (c == '\n')
163 bb_putchar('\r');
164 bb_putchar(c);
165 empty = 0;
166 }
167 if (empty)
168 puts("\r\nSystem closed for routine maintenance\r");
169
170 fclose(fp);
171 fflush_all();
172 /* Users say that they do need this prior to exit: */
173 tcdrain(STDOUT_FILENO);
174 exit(EXIT_FAILURE);
175}
176#else
177# define die_if_nologin() ((void)0)
178#endif
179
180#if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
181static int check_securetty(const char *short_tty)
182{
183 char *buf = (char*)"/etc/securetty"; /* any non-NULL is ok */
184 parser_t *parser = config_open2("/etc/securetty", fopen_for_read);
185 while (config_read(parser, &buf, 1, 1, "# \t", PARSE_NORMAL)) {
186 if (strcmp(buf, short_tty) == 0)
187 break;
188 buf = NULL;
189 }
190 config_close(parser);
191 /* buf != NULL here if config file was not found, empty
192 * or line was found which equals short_tty */
193 return buf != NULL;
194}
195#else
196static ALWAYS_INLINE int check_securetty(const char *short_tty UNUSED_PARAM) { return 1; }
197#endif
198
199#if ENABLE_SELINUX
200static void initselinux(char *username, char *full_tty,
201 security_context_t *user_sid)
202{
203 security_context_t old_tty_sid, new_tty_sid;
204
205 if (!is_selinux_enabled())
206 return;
207
208 if (get_default_context(username, NULL, user_sid)) {
209 bb_error_msg_and_die("can't get SID for %s", username);
210 }
211 if (getfilecon(full_tty, &old_tty_sid) < 0) {
212 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
213 }
214 if (security_compute_relabel(*user_sid, old_tty_sid,
215 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
216 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
217 }
218 if (setfilecon(full_tty, new_tty_sid) != 0) {
219 if (strcmp(old_tty_sid, new_tty_sid))
220 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
221 }
222}
223#endif
224
225#if ENABLE_LOGIN_SCRIPTS
226static void run_login_script(struct passwd *pw, char *full_tty)
227{
228 char *t_argv[2];
229
230 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
231 if (t_argv[0]) {
232 t_argv[1] = NULL;
233 xsetenv("LOGIN_TTY", full_tty);
234 xsetenv("LOGIN_USER", pw->pw_name);
235 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
236 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
237 xsetenv("LOGIN_SHELL", pw->pw_shell);
238 spawn_and_wait(t_argv); /* NOMMU-friendly */
239 unsetenv("LOGIN_TTY");
240 unsetenv("LOGIN_USER");
241 unsetenv("LOGIN_UID");
242 unsetenv("LOGIN_GID");
243 unsetenv("LOGIN_SHELL");
244 }
245}
246#else
247void run_login_script(struct passwd *pw, char *full_tty);
248#endif
249
250#if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
251static void login_pam_end(pam_handle_t *pamh)
252{
253 int pamret;
254
255 pamret = pam_setcred(pamh, PAM_DELETE_CRED);
256 if (pamret != PAM_SUCCESS) {
257 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
258 pam_strerror(pamh, pamret), pamret);
259 }
260 pamret = pam_close_session(pamh, 0);
261 if (pamret != PAM_SUCCESS) {
262 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
263 pam_strerror(pamh, pamret), pamret);
264 }
265 pamret = pam_end(pamh, pamret);
266 if (pamret != PAM_SUCCESS) {
267 bb_error_msg("pam_%s failed: %s (%d)", "end",
268 pam_strerror(pamh, pamret), pamret);
269 }
270}
271#endif /* ENABLE_PAM */
272
273static void get_username_or_die(char *buf, int size_buf)
274{
275 int c, cntdown;
276
277 cntdown = EMPTY_USERNAME_COUNT;
278 prompt:
279 print_login_prompt();
280 /* skip whitespace */
281 do {
282 c = getchar();
283 if (c == EOF)
284 exit(EXIT_FAILURE);
285 if (c == '\n') {
286 if (!--cntdown)
287 exit(EXIT_FAILURE);
288 goto prompt;
289 }
290 } while (isspace(c)); /* maybe isblank? */
291
292 *buf++ = c;
293 if (!fgets(buf, size_buf-2, stdin))
294 exit(EXIT_FAILURE);
295 if (!strchr(buf, '\n'))
296 exit(EXIT_FAILURE);
297 while ((unsigned char)*buf > ' ')
298 buf++;
299 *buf = '\0';
300}
301
302static void motd(void)
303{
304 int fd;
305
306 fd = open(bb_path_motd_file, O_RDONLY);
307 if (fd >= 0) {
308 fflush_all();
309 bb_copyfd_eof(fd, STDOUT_FILENO);
310 close(fd);
311 }
312}
313
314static void alarm_handler(int sig UNUSED_PARAM)
315{
316 /* This is the escape hatch! Poor serial line users and the like
317 * arrive here when their connection is broken.
318 * We don't want to block here */
319 ndelay_on(STDOUT_FILENO);
320 /* Test for correct attr restoring:
321 * run "getty 0 -" from a shell, enter bogus username, stop at
322 * password prompt, let it time out. Without the tcsetattr below,
323 * when you are back at shell prompt, echo will be still off.
324 */
325 tcsetattr_stdin_TCSANOW(&G.tty_attrs);
326 printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
327 fflush_all();
328 /* unix API is brain damaged regarding O_NONBLOCK,
329 * we should undo it, or else we can affect other processes */
330 ndelay_off(STDOUT_FILENO);
331 _exit(EXIT_SUCCESS);
332}
333
334int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
335int login_main(int argc UNUSED_PARAM, char **argv)
336{
337 enum {
338 LOGIN_OPT_f = (1<<0),
339 LOGIN_OPT_h = (1<<1),
340 LOGIN_OPT_p = (1<<2),
341 };
342 char *fromhost;
343 char username[USERNAME_SIZE];
344 int run_by_root;
345 unsigned opt;
346 int count = 0;
347 struct passwd *pw;
348 char *opt_host = NULL;
349 char *opt_user = opt_user; /* for compiler */
350 char *full_tty;
351 char *short_tty;
352 IF_SELINUX(security_context_t user_sid = NULL;)
353#if ENABLE_PAM
354 int pamret;
355 pam_handle_t *pamh;
356 const char *pamuser;
357 const char *failed_msg;
358 struct passwd pwdstruct;
359 char pwdbuf[256];
360 char **pamenv;
361#endif
362#if ENABLE_LOGIN_SESSION_AS_CHILD
363 pid_t child_pid;
364#endif
365
366 INIT_G();
367
368 /* More of suid paranoia if called by non-root: */
369 /* Clear dangerous stuff, set PATH */
370 run_by_root = !sanitize_env_if_suid();
371
372 /* Mandatory paranoia for suid applet:
373 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
374 * and any extra open fd's are closed.
375 * (The name of the function is misleading. Not daemonizing here.) */
376 bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
377
378 username[0] = '\0';
379 opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
380 if (opt & LOGIN_OPT_f) {
381 if (!run_by_root)
382 bb_error_msg_and_die("-f is for root only");
383 safe_strncpy(username, opt_user, sizeof(username));
384 }
385 argv += optind;
386 if (argv[0]) /* user from command line (getty) */
387 safe_strncpy(username, argv[0], sizeof(username));
388
389 /* Save tty attributes - and by doing it, check that it's indeed a tty */
390 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
391 || !isatty(STDOUT_FILENO)
392 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
393 ) {
394 return EXIT_FAILURE; /* Must be a terminal */
395 }
396
397 /* We install timeout handler only _after_ we saved G.tty_attrs */
398 signal(SIGALRM, alarm_handler);
399 alarm(TIMEOUT);
400
401 /* Find out and memorize our tty name */
402 full_tty = xmalloc_ttyname(STDIN_FILENO);
403 if (!full_tty)
404 full_tty = xstrdup("UNKNOWN");
405 short_tty = skip_dev_pfx(full_tty);
406
407 if (opt_host) {
408 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
409 } else {
410 fromhost = xasprintf(" on '%s'", short_tty);
411 }
412
413 /* Was breaking "login <username>" from shell command line: */
414 /*bb_setpgrp();*/
415
416 openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
417
418 while (1) {
419 /* flush away any type-ahead (as getty does) */
420 tcflush(0, TCIFLUSH);
421
422 if (!username[0])
423 get_username_or_die(username, sizeof(username));
424
425#if ENABLE_PAM
426 pamret = pam_start("login", username, &conv, &pamh);
427 if (pamret != PAM_SUCCESS) {
428 failed_msg = "start";
429 goto pam_auth_failed;
430 }
431 /* set TTY (so things like securetty work) */
432 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
433 if (pamret != PAM_SUCCESS) {
434 failed_msg = "set_item(TTY)";
435 goto pam_auth_failed;
436 }
437 /* set RHOST */
438 if (opt_host) {
439 pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
440 if (pamret != PAM_SUCCESS) {
441 failed_msg = "set_item(RHOST)";
442 goto pam_auth_failed;
443 }
444 }
445 if (!(opt & LOGIN_OPT_f)) {
446 pamret = pam_authenticate(pamh, 0);
447 if (pamret != PAM_SUCCESS) {
448 failed_msg = "authenticate";
449 goto pam_auth_failed;
450 /* TODO: or just "goto auth_failed"
451 * since user seems to enter wrong password
452 * (in this case pamret == 7)
453 */
454 }
455 }
456 /* check that the account is healthy */
457 pamret = pam_acct_mgmt(pamh, 0);
458 if (pamret != PAM_SUCCESS) {
459 failed_msg = "acct_mgmt";
460 goto pam_auth_failed;
461 }
462 /* read user back */
463 pamuser = NULL;
464 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
465 * thus we cast to (void*) */
466 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
467 failed_msg = "get_item(USER)";
468 goto pam_auth_failed;
469 }
470 if (!pamuser || !pamuser[0])
471 goto auth_failed;
472 safe_strncpy(username, pamuser, sizeof(username));
473 /* Don't use "pw = getpwnam(username);",
474 * PAM is said to be capable of destroying static storage
475 * used by getpwnam(). We are using safe(r) function */
476 pw = NULL;
477 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
478 if (!pw)
479 goto auth_failed;
480 pamret = pam_open_session(pamh, 0);
481 if (pamret != PAM_SUCCESS) {
482 failed_msg = "open_session";
483 goto pam_auth_failed;
484 }
485 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
486 if (pamret != PAM_SUCCESS) {
487 failed_msg = "setcred";
488 goto pam_auth_failed;
489 }
490 break; /* success, continue login process */
491
492 pam_auth_failed:
493 /* syslog, because we don't want potential attacker
494 * to know _why_ login failed */
495 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
496 pam_strerror(pamh, pamret), pamret);
497 safe_strncpy(username, "UNKNOWN", sizeof(username));
498#else /* not PAM */
499 pw = safegetpwnam(username);
500 if (!pw) {
501 strcpy(username, "UNKNOWN");
502 goto fake_it;
503 }
504
505 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
506 goto auth_failed;
507
508 if (opt & LOGIN_OPT_f)
509 break; /* -f USER: success without asking passwd */
510
511 if (pw->pw_uid == 0 && !check_securetty(short_tty))
512 goto auth_failed;
513
514 /* Don't check the password if password entry is empty (!) */
515 if (!pw->pw_passwd[0])
516 break;
517 fake_it:
518 /* Password reading and authorization takes place here.
519 * Note that reads (in no-echo mode) trash tty attributes.
520 * If we get interrupted by SIGALRM, we need to restore attrs.
521 */
522 if (ask_and_check_password(pw) > 0)
523 break;
524#endif /* ENABLE_PAM */
525 auth_failed:
526 opt &= ~LOGIN_OPT_f;
527 bb_do_delay(LOGIN_FAIL_DELAY);
528 /* TODO: doesn't sound like correct English phrase to me */
529 puts("Login incorrect");
530 if (++count == 3) {
531 syslog(LOG_WARNING, "invalid password for '%s'%s",
532 username, fromhost);
533
534 if (ENABLE_FEATURE_CLEAN_UP)
535 free(fromhost);
536
537 return EXIT_FAILURE;
538 }
539 username[0] = '\0';
540 } /* while (1) */
541
542 alarm(0);
543 /* We can ignore /etc/nologin if we are logging in as root,
544 * it doesn't matter whether we are run by root or not */
545 if (pw->pw_uid != 0)
546 die_if_nologin();
547
548#if ENABLE_LOGIN_SESSION_AS_CHILD
549 child_pid = vfork();
550 if (child_pid != 0) {
551 if (child_pid < 0)
552 bb_perror_msg("vfork");
553 else {
554 if (safe_waitpid(child_pid, NULL, 0) == -1)
555 bb_perror_msg("waitpid");
556 update_utmp_DEAD_PROCESS(child_pid);
557 }
558 IF_PAM(login_pam_end(pamh);)
559 return 0;
560 }
561#endif
562
563 IF_SELINUX(initselinux(username, full_tty, &user_sid);)
564
565 /* Try these, but don't complain if they fail.
566 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
567 fchown(0, pw->pw_uid, pw->pw_gid);
568 fchmod(0, 0600);
569
570 update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
571
572 /* We trust environment only if we run by root */
573 if (ENABLE_LOGIN_SCRIPTS && run_by_root)
574 run_login_script(pw, full_tty);
575
576 change_identity(pw);
577 setup_environment(pw->pw_shell,
578 (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
579 pw);
580
581#if ENABLE_PAM
582 /* Modules such as pam_env will setup the PAM environment,
583 * which should be copied into the new environment. */
584 pamenv = pam_getenvlist(pamh);
585 if (pamenv) while (*pamenv) {
586 putenv(*pamenv);
587 pamenv++;
588 }
589#endif
590
591 if (access(".hushlogin", F_OK) != 0)
592 motd();
593
594 if (pw->pw_uid == 0)
595 syslog(LOG_INFO, "root login%s", fromhost);
596
597 if (ENABLE_FEATURE_CLEAN_UP)
598 free(fromhost);
599
600 /* well, a simple setexeccon() here would do the job as well,
601 * but let's play the game for now */
602 IF_SELINUX(set_current_security_context(user_sid);)
603
604 // util-linux login also does:
605 // /* start new session */
606 // setsid();
607 // /* TIOCSCTTY: steal tty from other process group */
608 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
609 // BBox login used to do this (see above):
610 // bb_setpgrp();
611 // If this stuff is really needed, add it and explain why!
612
613 /* Set signals to defaults */
614 /* Non-ignored signals revert to SIG_DFL on exec anyway */
615 /*signal(SIGALRM, SIG_DFL);*/
616
617 /* Is this correct? This way user can ctrl-c out of /etc/profile,
618 * potentially creating security breach (tested with bash 3.0).
619 * But without this, bash 3.0 will not enable ctrl-c either.
620 * Maybe bash is buggy?
621 * Need to find out what standards say about /bin/login -
622 * should we leave SIGINT etc enabled or disabled? */
623 signal(SIGINT, SIG_DFL);
624
625 /* Exec login shell with no additional parameters */
626 run_shell(pw->pw_shell, 1, NULL);
627
628 /* return EXIT_FAILURE; - not reached */
629}
630