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