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