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