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