Update menuconfig items with approximate applet sizes
[oweals/busybox.git] / loginutils / login.c
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 (24 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.
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
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_SELINUX
179 static void initselinux(char *username, char *full_tty,
180                                                 security_context_t *user_sid)
181 {
182         security_context_t old_tty_sid, new_tty_sid;
183
184         if (!is_selinux_enabled())
185                 return;
186
187         if (get_default_context(username, NULL, user_sid)) {
188                 bb_error_msg_and_die("can't get SID for %s", username);
189         }
190         if (getfilecon(full_tty, &old_tty_sid) < 0) {
191                 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
192         }
193         if (security_compute_relabel(*user_sid, old_tty_sid,
194                                 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
195                 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
196         }
197         if (setfilecon(full_tty, new_tty_sid) != 0) {
198                 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
199         }
200 }
201 #endif
202
203 #if ENABLE_LOGIN_SCRIPTS
204 static void run_login_script(struct passwd *pw, char *full_tty)
205 {
206         char *t_argv[2];
207
208         t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
209         if (t_argv[0]) {
210                 t_argv[1] = NULL;
211                 xsetenv("LOGIN_TTY", full_tty);
212                 xsetenv("LOGIN_USER", pw->pw_name);
213                 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
214                 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
215                 xsetenv("LOGIN_SHELL", pw->pw_shell);
216                 spawn_and_wait(t_argv); /* NOMMU-friendly */
217                 unsetenv("LOGIN_TTY");
218                 unsetenv("LOGIN_USER");
219                 unsetenv("LOGIN_UID");
220                 unsetenv("LOGIN_GID");
221                 unsetenv("LOGIN_SHELL");
222         }
223 }
224 #else
225 void run_login_script(struct passwd *pw, char *full_tty);
226 #endif
227
228 #if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
229 static void login_pam_end(pam_handle_t *pamh)
230 {
231         int pamret;
232
233         pamret = pam_setcred(pamh, PAM_DELETE_CRED);
234         if (pamret != PAM_SUCCESS) {
235                 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
236                         pam_strerror(pamh, pamret), pamret);
237         }
238         pamret = pam_close_session(pamh, 0);
239         if (pamret != PAM_SUCCESS) {
240                 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
241                         pam_strerror(pamh, pamret), pamret);
242         }
243         pamret = pam_end(pamh, pamret);
244         if (pamret != PAM_SUCCESS) {
245                 bb_error_msg("pam_%s failed: %s (%d)", "end",
246                         pam_strerror(pamh, pamret), pamret);
247         }
248 }
249 #endif /* ENABLE_PAM */
250
251 static void get_username_or_die(char *buf, int size_buf)
252 {
253         int c, cntdown;
254
255         cntdown = EMPTY_USERNAME_COUNT;
256  prompt:
257         print_login_prompt();
258         /* skip whitespace */
259         do {
260                 c = getchar();
261                 if (c == EOF)
262                         exit(EXIT_FAILURE);
263                 if (c == '\n') {
264                         if (!--cntdown)
265                                 exit(EXIT_FAILURE);
266                         goto prompt;
267                 }
268         } while (isspace(c)); /* maybe isblank? */
269
270         *buf++ = c;
271         if (!fgets(buf, size_buf-2, stdin))
272                 exit(EXIT_FAILURE);
273         if (!strchr(buf, '\n'))
274                 exit(EXIT_FAILURE);
275         while ((unsigned char)*buf > ' ')
276                 buf++;
277         *buf = '\0';
278 }
279
280 static void motd(void)
281 {
282         int fd;
283
284         fd = open(bb_path_motd_file, O_RDONLY);
285         if (fd >= 0) {
286                 fflush_all();
287                 bb_copyfd_eof(fd, STDOUT_FILENO);
288                 close(fd);
289         }
290 }
291
292 static void alarm_handler(int sig UNUSED_PARAM)
293 {
294         /* This is the escape hatch! Poor serial line users and the like
295          * arrive here when their connection is broken.
296          * We don't want to block here */
297         ndelay_on(STDOUT_FILENO);
298         /* Test for correct attr restoring:
299          * run "getty 0 -" from a shell, enter bogus username, stop at
300          * password prompt, let it time out. Without the tcsetattr below,
301          * when you are back at shell prompt, echo will be still off.
302          */
303         tcsetattr_stdin_TCSANOW(&G.tty_attrs);
304         printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
305         fflush_all();
306         /* unix API is brain damaged regarding O_NONBLOCK,
307          * we should undo it, or else we can affect other processes */
308         ndelay_off(STDOUT_FILENO);
309         _exit(EXIT_SUCCESS);
310 }
311
312 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
313 int login_main(int argc UNUSED_PARAM, char **argv)
314 {
315         enum {
316                 LOGIN_OPT_f = (1<<0),
317                 LOGIN_OPT_h = (1<<1),
318                 LOGIN_OPT_p = (1<<2),
319         };
320         char *fromhost;
321         char username[USERNAME_SIZE];
322         int run_by_root;
323         unsigned opt;
324         int count = 0;
325         struct passwd *pw;
326         char *opt_host = NULL;
327         char *opt_user = opt_user; /* for compiler */
328         char *full_tty;
329         char *short_tty;
330         IF_SELINUX(security_context_t user_sid = NULL;)
331 #if ENABLE_PAM
332         int pamret;
333         pam_handle_t *pamh;
334         const char *pamuser;
335         const char *failed_msg;
336         struct passwd pwdstruct;
337         char pwdbuf[256];
338         char **pamenv;
339 #endif
340 #if ENABLE_LOGIN_SESSION_AS_CHILD
341         pid_t child_pid;
342 #endif
343
344         INIT_G();
345
346         /* More of suid paranoia if called by non-root: */
347         /* Clear dangerous stuff, set PATH */
348         run_by_root = !sanitize_env_if_suid();
349
350         /* Mandatory paranoia for suid applet:
351          * ensure that fd# 0,1,2 are opened (at least to /dev/null)
352          * and any extra open fd's are closed.
353          * (The name of the function is misleading. Not daemonizing here.) */
354         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
355
356         username[0] = '\0';
357         opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
358         if (opt & LOGIN_OPT_f) {
359                 if (!run_by_root)
360                         bb_error_msg_and_die("-f is for root only");
361                 safe_strncpy(username, opt_user, sizeof(username));
362         }
363         argv += optind;
364         if (argv[0]) /* user from command line (getty) */
365                 safe_strncpy(username, argv[0], sizeof(username));
366
367         /* Save tty attributes - and by doing it, check that it's indeed a tty */
368         if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
369          || !isatty(STDOUT_FILENO)
370          /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
371         ) {
372                 return EXIT_FAILURE;  /* Must be a terminal */
373         }
374
375         /* We install timeout handler only _after_ we saved G.tty_attrs */
376         signal(SIGALRM, alarm_handler);
377         alarm(TIMEOUT);
378
379         /* Find out and memorize our tty name */
380         full_tty = xmalloc_ttyname(STDIN_FILENO);
381         if (!full_tty)
382                 full_tty = xstrdup("UNKNOWN");
383         short_tty = skip_dev_pfx(full_tty);
384
385         if (opt_host) {
386                 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
387         } else {
388                 fromhost = xasprintf(" on '%s'", short_tty);
389         }
390
391         /* Was breaking "login <username>" from shell command line: */
392         /*bb_setpgrp();*/
393
394         openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
395
396         while (1) {
397                 /* flush away any type-ahead (as getty does) */
398                 tcflush(0, TCIFLUSH);
399
400                 if (!username[0])
401                         get_username_or_die(username, sizeof(username));
402
403 #if ENABLE_PAM
404                 pamret = pam_start("login", username, &conv, &pamh);
405                 if (pamret != PAM_SUCCESS) {
406                         failed_msg = "start";
407                         goto pam_auth_failed;
408                 }
409                 /* set TTY (so things like securetty work) */
410                 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
411                 if (pamret != PAM_SUCCESS) {
412                         failed_msg = "set_item(TTY)";
413                         goto pam_auth_failed;
414                 }
415                 /* set RHOST */
416                 if (opt_host) {
417                         pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
418                         if (pamret != PAM_SUCCESS) {
419                                 failed_msg = "set_item(RHOST)";
420                                 goto pam_auth_failed;
421                         }
422                 }
423                 if (!(opt & LOGIN_OPT_f)) {
424                         pamret = pam_authenticate(pamh, 0);
425                         if (pamret != PAM_SUCCESS) {
426                                 failed_msg = "authenticate";
427                                 goto pam_auth_failed;
428                                 /* TODO: or just "goto auth_failed"
429                                  * since user seems to enter wrong password
430                                  * (in this case pamret == 7)
431                                  */
432                         }
433                 }
434                 /* check that the account is healthy */
435                 pamret = pam_acct_mgmt(pamh, 0);
436                 if (pamret != PAM_SUCCESS) {
437                         failed_msg = "acct_mgmt";
438                         goto pam_auth_failed;
439                 }
440                 /* read user back */
441                 pamuser = NULL;
442                 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
443                  * thus we cast to (void*) */
444                 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
445                         failed_msg = "get_item(USER)";
446                         goto pam_auth_failed;
447                 }
448                 if (!pamuser || !pamuser[0])
449                         goto auth_failed;
450                 safe_strncpy(username, pamuser, sizeof(username));
451                 /* Don't use "pw = getpwnam(username);",
452                  * PAM is said to be capable of destroying static storage
453                  * used by getpwnam(). We are using safe(r) function */
454                 pw = NULL;
455                 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
456                 if (!pw)
457                         goto auth_failed;
458                 pamret = pam_open_session(pamh, 0);
459                 if (pamret != PAM_SUCCESS) {
460                         failed_msg = "open_session";
461                         goto pam_auth_failed;
462                 }
463                 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
464                 if (pamret != PAM_SUCCESS) {
465                         failed_msg = "setcred";
466                         goto pam_auth_failed;
467                 }
468                 break; /* success, continue login process */
469
470  pam_auth_failed:
471                 /* syslog, because we don't want potential attacker
472                  * to know _why_ login failed */
473                 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
474                                         pam_strerror(pamh, pamret), pamret);
475                 safe_strncpy(username, "UNKNOWN", sizeof(username));
476 #else /* not PAM */
477                 pw = getpwnam(username);
478                 if (!pw) {
479                         strcpy(username, "UNKNOWN");
480                         goto fake_it;
481                 }
482
483                 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
484                         goto auth_failed;
485
486                 if (opt & LOGIN_OPT_f)
487                         break; /* -f USER: success without asking passwd */
488
489                 if (pw->pw_uid == 0 && !is_tty_secure(short_tty))
490                         goto auth_failed;
491
492                 /* Don't check the password if password entry is empty (!) */
493                 if (!pw->pw_passwd[0])
494                         break;
495  fake_it:
496                 /* Password reading and authorization takes place here.
497                  * Note that reads (in no-echo mode) trash tty attributes.
498                  * If we get interrupted by SIGALRM, we need to restore attrs.
499                  */
500                 if (ask_and_check_password(pw) > 0)
501                         break;
502 #endif /* ENABLE_PAM */
503  auth_failed:
504                 opt &= ~LOGIN_OPT_f;
505                 bb_do_delay(LOGIN_FAIL_DELAY);
506                 /* TODO: doesn't sound like correct English phrase to me */
507                 puts("Login incorrect");
508                 if (++count == 3) {
509                         syslog(LOG_WARNING, "invalid password for '%s'%s",
510                                                 username, fromhost);
511
512                         if (ENABLE_FEATURE_CLEAN_UP)
513                                 free(fromhost);
514
515                         return EXIT_FAILURE;
516                 }
517                 username[0] = '\0';
518         } /* while (1) */
519
520         alarm(0);
521         /* We can ignore /etc/nologin if we are logging in as root,
522          * it doesn't matter whether we are run by root or not */
523         if (pw->pw_uid != 0)
524                 die_if_nologin();
525
526 #if ENABLE_LOGIN_SESSION_AS_CHILD
527         child_pid = vfork();
528         if (child_pid != 0) {
529                 if (child_pid < 0)
530                         bb_perror_msg("vfork");
531                 else {
532                         if (safe_waitpid(child_pid, NULL, 0) == -1)
533                                 bb_perror_msg("waitpid");
534                         update_utmp_DEAD_PROCESS(child_pid);
535                 }
536                 IF_PAM(login_pam_end(pamh);)
537                 return 0;
538         }
539 #endif
540
541         IF_SELINUX(initselinux(username, full_tty, &user_sid);)
542
543         /* Try these, but don't complain if they fail.
544          * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
545         fchown(0, pw->pw_uid, pw->pw_gid);
546         fchmod(0, 0600);
547
548         update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
549
550         /* We trust environment only if we run by root */
551         if (ENABLE_LOGIN_SCRIPTS && run_by_root)
552                 run_login_script(pw, full_tty);
553
554         change_identity(pw);
555         setup_environment(pw->pw_shell,
556                         (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
557                         pw);
558
559 #if ENABLE_PAM
560         /* Modules such as pam_env will setup the PAM environment,
561          * which should be copied into the new environment. */
562         pamenv = pam_getenvlist(pamh);
563         if (pamenv) while (*pamenv) {
564                 putenv(*pamenv);
565                 pamenv++;
566         }
567 #endif
568
569         if (access(".hushlogin", F_OK) != 0)
570                 motd();
571
572         if (pw->pw_uid == 0)
573                 syslog(LOG_INFO, "root login%s", fromhost);
574
575         if (ENABLE_FEATURE_CLEAN_UP)
576                 free(fromhost);
577
578         /* well, a simple setexeccon() here would do the job as well,
579          * but let's play the game for now */
580         IF_SELINUX(set_current_security_context(user_sid);)
581
582         // util-linux login also does:
583         // /* start new session */
584         // setsid();
585         // /* TIOCSCTTY: steal tty from other process group */
586         // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
587         // BBox login used to do this (see above):
588         // bb_setpgrp();
589         // If this stuff is really needed, add it and explain why!
590
591         /* Set signals to defaults */
592         /* Non-ignored signals revert to SIG_DFL on exec anyway */
593         /*signal(SIGALRM, SIG_DFL);*/
594
595         /* Is this correct? This way user can ctrl-c out of /etc/profile,
596          * potentially creating security breach (tested with bash 3.0).
597          * But without this, bash 3.0 will not enable ctrl-c either.
598          * Maybe bash is buggy?
599          * Need to find out what standards say about /bin/login -
600          * should we leave SIGINT etc enabled or disabled? */
601         signal(SIGINT, SIG_DFL);
602
603         /* Exec login shell with no additional parameters */
604         run_shell(pw->pw_shell, 1, NULL);
605
606         /* return EXIT_FAILURE; - not reached */
607 }