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