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