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