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