861382f12159f8877ba7a7c1b1b827f33ae778d6
[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         int empty = 1;
122
123         fp = fopen_for_read("/etc/nologin");
124         if (!fp) /* assuming it does not exist */
125                 return;
126
127         while ((c = getc(fp)) != EOF) {
128                 if (c == '\n')
129                         bb_putchar('\r');
130                 bb_putchar(c);
131                 empty = 0;
132         }
133         if (empty)
134                 puts("\r\nSystem closed for routine maintenance\r");
135
136         fclose(fp);
137         fflush(NULL);
138         /* Users say that they do need this prior to exit: */
139         tcdrain(STDOUT_FILENO);
140         exit(EXIT_FAILURE);
141 }
142 #else
143 static ALWAYS_INLINE void die_if_nologin(void) {}
144 #endif
145
146 #if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
147 static int check_securetty(void)
148 {
149         char *buf = (char*)"/etc/securetty"; /* any non-NULL is ok */
150         parser_t *parser = config_open2("/etc/securetty", fopen_for_read);
151         while (config_read(parser, &buf, 1, 1, "# \t", PARSE_NORMAL)) {
152                 if (strcmp(buf, short_tty) == 0)
153                         break;
154                 buf = NULL;
155         }
156         config_close(parser);
157         /* buf != NULL here if config file was not found, empty
158          * or line was found which equals short_tty */
159         return buf != NULL;
160 }
161 #else
162 static ALWAYS_INLINE int check_securetty(void) { return 1; }
163 #endif
164
165 static void get_username_or_die(char *buf, int size_buf)
166 {
167         int c, cntdown;
168
169         cntdown = EMPTY_USERNAME_COUNT;
170  prompt:
171         print_login_prompt();
172         /* skip whitespace */
173         do {
174                 c = getchar();
175                 if (c == EOF) exit(EXIT_FAILURE);
176                 if (c == '\n') {
177                         if (!--cntdown) exit(EXIT_FAILURE);
178                         goto prompt;
179                 }
180         } while (isspace(c));
181
182         *buf++ = c;
183         if (!fgets(buf, size_buf-2, stdin))
184                 exit(EXIT_FAILURE);
185         if (!strchr(buf, '\n'))
186                 exit(EXIT_FAILURE);
187         while (isgraph(*buf)) buf++;
188         *buf = '\0';
189 }
190
191 static void motd(void)
192 {
193         int fd;
194
195         fd = open(bb_path_motd_file, O_RDONLY);
196         if (fd >= 0) {
197                 fflush(stdout);
198                 bb_copyfd_eof(fd, STDOUT_FILENO);
199                 close(fd);
200         }
201 }
202
203 static void alarm_handler(int sig UNUSED_PARAM)
204 {
205         /* This is the escape hatch!  Poor serial line users and the like
206          * arrive here when their connection is broken.
207          * We don't want to block here */
208         ndelay_on(1);
209         printf("\r\nLogin timed out after %d seconds\r\n", TIMEOUT);
210         fflush(stdout);
211         /* unix API is brain damaged regarding O_NONBLOCK,
212          * we should undo it, or else we can affect other processes */
213         ndelay_off(1);
214         _exit(EXIT_SUCCESS);
215 }
216
217 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
218 int login_main(int argc UNUSED_PARAM, char **argv)
219 {
220         enum {
221                 LOGIN_OPT_f = (1<<0),
222                 LOGIN_OPT_h = (1<<1),
223                 LOGIN_OPT_p = (1<<2),
224         };
225         char *fromhost;
226         char username[USERNAME_SIZE];
227         const char *tmp;
228         int amroot;
229         unsigned opt;
230         int count = 0;
231         struct passwd *pw;
232         char *opt_host = opt_host; /* for compiler */
233         char *opt_user = opt_user; /* for compiler */
234         char full_tty[TTYNAME_SIZE];
235         USE_SELINUX(security_context_t user_sid = NULL;)
236         USE_FEATURE_UTMP(struct utmp utent;)
237 #if ENABLE_PAM
238         int pamret;
239         pam_handle_t *pamh;
240         const char *pamuser;
241         const char *failed_msg;
242         struct passwd pwdstruct;
243         char pwdbuf[256];
244 #endif
245
246         short_tty = full_tty;
247         username[0] = '\0';
248         signal(SIGALRM, alarm_handler);
249         alarm(TIMEOUT);
250
251         /* More of suid paranoia if called by non-root */
252         amroot = !sanitize_env_if_suid(); /* Clear dangerous stuff, set PATH */
253
254         /* Mandatory paranoia for suid applet:
255          * ensure that fd# 0,1,2 are opened (at least to /dev/null)
256          * and any extra open fd's are closed.
257          * (The name of the function is misleading. Not daemonizing here.) */
258         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
259
260         opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
261         if (opt & LOGIN_OPT_f) {
262                 if (!amroot)
263                         bb_error_msg_and_die("-f is for root only");
264                 safe_strncpy(username, opt_user, sizeof(username));
265         }
266         argv += optind;
267         if (argv[0]) /* user from command line (getty) */
268                 safe_strncpy(username, argv[0], sizeof(username));
269
270         /* Let's find out and memorize our tty */
271         if (!isatty(0) || !isatty(1) || !isatty(2))
272                 return EXIT_FAILURE;            /* Must be a terminal */
273         safe_strncpy(full_tty, "UNKNOWN", sizeof(full_tty));
274         tmp = ttyname(0);
275         if (tmp) {
276                 safe_strncpy(full_tty, tmp, sizeof(full_tty));
277                 if (strncmp(full_tty, "/dev/", 5) == 0)
278                         short_tty = full_tty + 5;
279         }
280
281         read_or_build_utent(&utent, !amroot);
282
283         if (opt & LOGIN_OPT_h) {
284                 USE_FEATURE_UTMP(
285                         safe_strncpy(utent.ut_host, opt_host, sizeof(utent.ut_host));
286                 )
287                 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
288         } else
289                 fromhost = xasprintf(" on '%s'", short_tty);
290
291         /* Was breaking "login <username>" from shell command line: */
292         /*bb_setpgrp();*/
293
294         openlog(applet_name, LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH);
295
296         while (1) {
297                 /* flush away any type-ahead (as getty does) */
298                 ioctl(0, TCFLSH, TCIFLUSH);
299
300                 if (!username[0])
301                         get_username_or_die(username, sizeof(username));
302
303 #if ENABLE_PAM
304                 pamret = pam_start("login", username, &conv, &pamh);
305                 if (pamret != PAM_SUCCESS) {
306                         failed_msg = "start";
307                         goto pam_auth_failed;
308                 }
309                 /* set TTY (so things like securetty work) */
310                 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
311                 if (pamret != PAM_SUCCESS) {
312                         failed_msg = "set_item(TTY)";
313                         goto pam_auth_failed;
314                 }
315                 pamret = pam_authenticate(pamh, 0);
316                 if (pamret != PAM_SUCCESS) {
317                         failed_msg = "authenticate";
318                         goto pam_auth_failed;
319                         /* TODO: or just "goto auth_failed"
320                          * since user seems to enter wrong password
321                          * (in this case pamret == 7)
322                          */
323                 }
324                 /* check that the account is healthy */
325                 pamret = pam_acct_mgmt(pamh, 0);
326                 if (pamret != PAM_SUCCESS) {
327                         failed_msg = "acct_mgmt";
328                         goto pam_auth_failed;
329                 }
330                 /* read user back */
331                 pamuser = NULL;
332                 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
333                  * thus we cast to (void*) */
334                 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
335                         failed_msg = "get_item(USER)";
336                         goto pam_auth_failed;
337                 }
338                 if (!pamuser || !pamuser[0])
339                         goto auth_failed;
340                 safe_strncpy(username, pamuser, sizeof(username));
341                 /* Don't use "pw = getpwnam(username);",
342                  * PAM is said to be capable of destroying static storage
343                  * used by getpwnam(). We are using safe(r) function */
344                 pw = NULL;
345                 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
346                 if (!pw)
347                         goto auth_failed;
348                 pamret = pam_open_session(pamh, 0);
349                 if (pamret != PAM_SUCCESS) {
350                         failed_msg = "open_session";
351                         goto pam_auth_failed;
352                 }
353                 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
354                 if (pamret != PAM_SUCCESS) {
355                         failed_msg = "setcred";
356                         goto pam_auth_failed;
357                 }
358                 break; /* success, continue login process */
359
360  pam_auth_failed:
361                 bb_error_msg("pam_%s call failed: %s (%d)", failed_msg,
362                                         pam_strerror(pamh, pamret), pamret);
363                 safe_strncpy(username, "UNKNOWN", sizeof(username));
364 #else /* not PAM */
365                 pw = getpwnam(username);
366                 if (!pw) {
367                         strcpy(username, "UNKNOWN");
368                         goto fake_it;
369                 }
370
371                 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
372                         goto auth_failed;
373
374                 if (opt & LOGIN_OPT_f)
375                         break; /* -f USER: success without asking passwd */
376
377                 if (pw->pw_uid == 0 && !check_securetty())
378                         goto auth_failed;
379
380                 /* Don't check the password if password entry is empty (!) */
381                 if (!pw->pw_passwd[0])
382                         break;
383  fake_it:
384                 /* authorization takes place here */
385                 if (correct_password(pw))
386                         break;
387 #endif /* ENABLE_PAM */
388  auth_failed:
389                 opt &= ~LOGIN_OPT_f;
390                 bb_do_delay(FAIL_DELAY);
391                 /* TODO: doesn't sound like correct English phrase to me */
392                 puts("Login incorrect");
393                 if (++count == 3) {
394                         syslog(LOG_WARNING, "invalid password for '%s'%s",
395                                                 username, fromhost);
396                         return EXIT_FAILURE;
397                 }
398                 username[0] = '\0';
399         }
400
401         alarm(0);
402         if (!amroot)
403                 die_if_nologin();
404
405         write_utent(&utent, username);
406
407 #if ENABLE_SELINUX
408         if (is_selinux_enabled()) {
409                 security_context_t old_tty_sid, new_tty_sid;
410
411                 if (get_default_context(username, NULL, &user_sid)) {
412                         bb_error_msg_and_die("cannot get SID for %s",
413                                         username);
414                 }
415                 if (getfilecon(full_tty, &old_tty_sid) < 0) {
416                         bb_perror_msg_and_die("getfilecon(%s) failed",
417                                         full_tty);
418                 }
419                 if (security_compute_relabel(user_sid, old_tty_sid,
420                                         SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
421                         bb_perror_msg_and_die("security_change_sid(%s) failed",
422                                         full_tty);
423                 }
424                 if (setfilecon(full_tty, new_tty_sid) != 0) {
425                         bb_perror_msg_and_die("chsid(%s, %s) failed",
426                                         full_tty, new_tty_sid);
427                 }
428         }
429 #endif
430         /* Try these, but don't complain if they fail.
431          * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
432         fchown(0, pw->pw_uid, pw->pw_gid);
433         fchmod(0, 0600);
434
435         /* We trust environment only if we run by root */
436         if (ENABLE_LOGIN_SCRIPTS && amroot) {
437                 char *t_argv[2];
438
439                 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
440                 if (t_argv[0]) {
441                         t_argv[1] = NULL;
442                         xsetenv("LOGIN_TTY", full_tty);
443                         xsetenv("LOGIN_USER", pw->pw_name);
444                         xsetenv("LOGIN_UID", utoa(pw->pw_uid));
445                         xsetenv("LOGIN_GID", utoa(pw->pw_gid));
446                         xsetenv("LOGIN_SHELL", pw->pw_shell);
447                         spawn_and_wait(t_argv); /* NOMMU-friendly */
448                         unsetenv("LOGIN_TTY"  );
449                         unsetenv("LOGIN_USER" );
450                         unsetenv("LOGIN_UID"  );
451                         unsetenv("LOGIN_GID"  );
452                         unsetenv("LOGIN_SHELL");
453                 }
454         }
455
456         change_identity(pw);
457         tmp = pw->pw_shell;
458         if (!tmp || !*tmp)
459                 tmp = DEFAULT_SHELL;
460         /* setup_environment params: shell, clear_env, change_env, pw */
461         setup_environment(tmp, !(opt & LOGIN_OPT_p), 1, pw);
462
463         motd();
464
465         if (pw->pw_uid == 0)
466                 syslog(LOG_INFO, "root login%s", fromhost);
467 #if ENABLE_SELINUX
468         /* well, a simple setexeccon() here would do the job as well,
469          * but let's play the game for now */
470         set_current_security_context(user_sid);
471 #endif
472
473         // util-linux login also does:
474         // /* start new session */
475         // setsid();
476         // /* TIOCSCTTY: steal tty from other process group */
477         // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
478         // BBox login used to do this (see above):
479         // bb_setpgrp();
480         // If this stuff is really needed, add it and explain why!
481
482         /* set signals to defaults */
483         signal(SIGALRM, SIG_DFL);
484         /* Is this correct? This way user can ctrl-c out of /etc/profile,
485          * potentially creating security breach (tested with bash 3.0).
486          * But without this, bash 3.0 will not enable ctrl-c either.
487          * Maybe bash is buggy?
488          * Need to find out what standards say about /bin/login -
489          * should it leave SIGINT etc enabled or disabled? */
490         signal(SIGINT, SIG_DFL);
491
492         /* Exec login shell with no additional parameters */
493         run_shell(tmp, 1, NULL, NULL);
494
495         /* return EXIT_FAILURE; - not reached */
496 }