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