c0f4b72bbd1809dc859a7b1b1783331be727a883
[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 <fcntl.h>
7 #include <signal.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <syslog.h>
12 #include <termios.h>
13 #include <unistd.h>
14 #include <utmp.h>
15 #include <sys/resource.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <ctype.h>
20 #include <time.h>
21
22 #include "busybox.h"
23 #ifdef CONFIG_SELINUX
24 #include <selinux/selinux.h>  /* for is_selinux_enabled()  */
25 #include <selinux/get_context_list.h> /* for get_default_context() */
26 #include <selinux/flask.h> /* for security class definitions  */
27 #include <errno.h>
28 #endif
29
30 #ifdef CONFIG_FEATURE_UTMP
31 // import from utmp.c
32 static struct utmp utent;
33 static void read_or_build_utent(int picky);
34 static void write_utent(const char *username);
35 #endif
36
37 enum {
38         TIMEOUT = 60,
39         EMPTY_USERNAME_COUNT = 10,
40         USERNAME_SIZE = 32,
41         TTYNAME_SIZE = 32,
42 };
43
44 static void die_if_nologin_and_non_root(int amroot);
45
46 #if defined CONFIG_FEATURE_SECURETTY
47 static int check_securetty(void);
48
49 #else
50 static inline int check_securetty(void) { return 1; }
51
52 #endif
53
54 static void get_username_or_die(char *buf, int size_buf);
55 static void motd(void);
56
57 static void nonblock(int fd)
58 {
59         fcntl(fd, F_SETFL, O_NONBLOCK | fcntl(fd, F_GETFL));
60 }
61
62 static void alarm_handler(int sig ATTRIBUTE_UNUSED)
63 {
64         /* This is the escape hatch!  Poor serial line users and the like
65          * arrive here when their connection is broken.
66          * We don't want to block here */
67         nonblock(1);
68         nonblock(2);
69         bb_info_msg("\r\nLogin timed out after %d seconds\r", TIMEOUT);
70         exit(EXIT_SUCCESS);
71 }
72
73
74 static char full_tty[TTYNAME_SIZE];
75 static char* short_tty = full_tty;
76
77
78 int login_main(int argc, char **argv)
79 {
80         char fromhost[512];
81         char username[USERNAME_SIZE];
82         const char *tmp;
83         int amroot;
84         int flag;
85         int count = 0;
86         struct passwd *pw;
87 #ifdef CONFIG_WHEEL_GROUP
88         struct group *grp;
89 #endif
90         int opt_preserve = 0;
91         int opt_fflag = 0;
92         char *opt_host = 0;
93 #ifdef CONFIG_SELINUX
94         security_context_t user_sid = NULL;
95 #endif
96
97         username[0] = '\0';
98         amroot = (getuid() == 0);
99         signal(SIGALRM, alarm_handler);
100         alarm(TIMEOUT);
101
102         while ((flag = getopt(argc, argv, "f:h:p")) != EOF) {
103                 switch (flag) {
104                 case 'p':
105                         opt_preserve = 1;
106                         break;
107                 case 'f':
108                         /*
109                          * username must be a separate token
110                          * (-f root, *NOT* -froot). --marekm
111                          */
112                         if (optarg != argv[optind-1])
113                                 bb_show_usage();
114
115                         if (!amroot)    /* Auth bypass only if real UID is zero */
116                                 bb_error_msg_and_die("-f is for root only");
117
118                         safe_strncpy(username, optarg, sizeof(username));
119                         opt_fflag = 1;
120                         break;
121                 case 'h':
122                         opt_host = optarg;
123                         break;
124                 default:
125                         bb_show_usage();
126                 }
127         }
128         if (optind < argc)             /* user from command line (getty) */
129                 safe_strncpy(username, argv[optind], sizeof(username));
130
131         /* Let's find out and memorize our tty */
132         if (!isatty(0) || !isatty(1) || !isatty(2))
133                 return EXIT_FAILURE;            /* Must be a terminal */
134         safe_strncpy(full_tty, "UNKNOWN", sizeof(full_tty));
135         tmp = ttyname(0);
136         if (tmp) {
137                 safe_strncpy(full_tty, tmp, sizeof(full_tty));
138                 if (strncmp(full_tty, "/dev/", 5) == 0)
139                         short_tty = full_tty + 5;
140         }
141
142         if (ENABLE_FEATURE_UTMP) {
143                 read_or_build_utent(!amroot);
144                 if (amroot)
145                         memset(utent.ut_host, 0, sizeof(utent.ut_host));
146         }
147
148         if (opt_host) {
149                 if (ENABLE_FEATURE_UTMP)
150                         safe_strncpy(utent.ut_host, opt_host, sizeof(utent.ut_host));
151                 snprintf(fromhost, sizeof(fromhost)-1, " on `%.100s' from "
152                                         "`%.200s'", short_tty, opt_host);
153         }
154         else
155                 snprintf(fromhost, sizeof(fromhost)-1, " on `%.100s'", short_tty);
156
157         bb_setpgrp;
158
159         openlog(bb_applet_name, LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH);
160
161         while (1) {
162                 if (!username[0])
163                         get_username_or_die(username, sizeof(username));
164
165                 pw = getpwnam(username);
166                 if (!pw) {
167                         safe_strncpy(username, "UNKNOWN", sizeof(username));
168                         goto auth_failed;
169                 }
170
171                 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
172                         goto auth_failed;
173
174                 if (opt_fflag)
175                         break; /* -f USER: success without asking passwd */
176
177                 if (pw->pw_uid == 0 && !check_securetty())
178                         goto auth_failed;
179
180                 /* Don't check the password if password entry is empty (!) */
181                 if (!pw->pw_passwd[0])
182                         break; 
183
184                 /* authorization takes place here */
185                 if (correct_password(pw))
186                         break; 
187
188 auth_failed:
189                 opt_fflag = 0;
190                 bb_do_delay(FAIL_DELAY);
191                 puts("Login incorrect");
192                 if (++count == 3) {
193                         syslog(LOG_WARNING, "invalid password for `%s'%s",
194                                                 username, fromhost);
195                         return EXIT_FAILURE;
196                 }
197                 username[0] = '\0';
198         }
199
200         alarm(0);
201         die_if_nologin_and_non_root(pw->pw_uid == 0);
202
203         if (ENABLE_FEATURE_UTMP)
204                 write_utent(username);
205
206 #ifdef CONFIG_SELINUX
207         if (is_selinux_enabled()) {
208                 security_context_t old_tty_sid, new_tty_sid;
209
210                 if (get_default_context(username, NULL, &user_sid)) {
211                         bb_error_msg_and_die("unable to get SID for %s",
212                                         username);
213                 }
214                 if (getfilecon(full_tty, &old_tty_sid) < 0) {
215                         bb_perror_msg_and_die("getfilecon(%.100s) failed",
216                                         full_tty);
217                 }
218                 if (security_compute_relabel(user_sid, old_tty_sid,
219                                         SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
220                         bb_perror_msg_and_die("security_change_sid(%.100s) failed",
221                                         full_tty);
222                 }
223                 if (setfilecon(full_tty, new_tty_sid) != 0) {
224                         bb_perror_msg_and_die("chsid(%.100s, %s) failed",
225                                         full_tty, new_tty_sid);
226                 }
227         }
228 #endif
229         /* Try these, but don't complain if they fail.
230          * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
231         fchown(0, pw->pw_uid, pw->pw_gid);
232         fchmod(0, 0600);
233
234         if (ENABLE_LOGIN_SCRIPTS) {
235                 char *script = getenv("LOGIN_PRE_SUID_SCRIPT");
236                 if (script) {
237                         char *t_argv[2] = { script, NULL };
238                         switch (fork()) {
239                         case -1: break;
240                         case 0: /* child */
241                                 xchdir("/");
242                                 setenv("LOGIN_TTY", full_tty, 1);
243                                 setenv("LOGIN_USER", pw->pw_name, 1);
244                                 setenv("LOGIN_UID", utoa(pw->pw_uid), 1);
245                                 setenv("LOGIN_GID", utoa(pw->pw_gid), 1);
246                                 setenv("LOGIN_SHELL", pw->pw_shell, 1);
247                                 execvp(script, t_argv);
248                                 exit(1);
249                         default: /* parent */
250                                 wait(NULL);
251                         }
252                 }
253         }
254
255         change_identity(pw);
256         tmp = pw->pw_shell;
257         if (!tmp || !*tmp)
258                 tmp = DEFAULT_SHELL;
259         setup_environment(tmp, 1, !opt_preserve, pw);
260
261         motd();
262         signal(SIGALRM, SIG_DFL);       /* default alarm signal */
263
264         if (pw->pw_uid == 0)
265                 syslog(LOG_INFO, "root login%s", fromhost);
266 #ifdef CONFIG_SELINUX
267         /* well, a simple setexeccon() here would do the job as well,
268          * but let's play the game for now */
269         set_current_security_context(user_sid);
270 #endif
271         run_shell(tmp, 1, 0, 0);        /* exec the shell finally. */
272
273         return EXIT_FAILURE;
274 }
275
276
277 static void get_username_or_die(char *buf, int size_buf)
278 {
279         int c, cntdown;
280         cntdown = EMPTY_USERNAME_COUNT;
281 prompt:
282         /* skip whitespace */
283         print_login_prompt();
284         do {
285                 c = getchar();
286                 if (c == EOF) exit(1);
287                 if (c == '\n') {
288                         if (!--cntdown) exit(1);
289                         goto prompt;
290                 }
291         } while (isspace(c));
292
293         *buf++ = c;
294         if (!fgets(buf, size_buf-2, stdin))
295                 exit(1);
296         if (!strchr(buf, '\n'))
297                 exit(1);
298         while (isgraph(*buf)) buf++;
299         *buf = '\0';
300 }
301
302
303 static void die_if_nologin_and_non_root(int amroot)
304 {
305         FILE *fp;
306         int c;
307
308         if (access(bb_path_nologin_file, F_OK))
309                 return;
310
311         fp = fopen(bb_path_nologin_file, "r");
312         if (fp) {
313                 while ((c = getc(fp)) != EOF)
314                         putchar((c=='\n') ? '\r' : c);
315                 fflush(stdout);
316                 fclose(fp);
317         } else
318                 puts("\r\nSystem closed for routine maintenance\r");
319         if (!amroot)
320                 exit(1);
321         puts("\r\n[Disconnect bypassed -- root login allowed.]\r");
322 }
323
324 #ifdef CONFIG_FEATURE_SECURETTY
325
326 static int check_securetty(void)
327 {
328         FILE *fp;
329         int i;
330         char buf[BUFSIZ];
331
332         fp = fopen(bb_path_securetty_file, "r");
333         if (!fp) {
334                 /* A missing securetty file is not an error. */
335                 return 1;
336         }
337         while (fgets(buf, sizeof(buf)-1, fp)) {
338                 for(i = strlen(buf)-1; i>=0; --i) {
339                         if (!isspace(buf[i]))
340                                 break;
341                 }
342                 buf[++i] = '\0';
343                 if ((buf[0]=='\0') || (buf[0]=='#'))
344                         continue;
345                 if (strcmp(buf, short_tty) == 0) {
346                         fclose(fp);
347                         return 1;
348                 }
349         }
350         fclose(fp);
351         return 0;
352 }
353
354 #endif
355
356 static void motd(void)
357 {
358         FILE *fp;
359         int c;
360
361         fp = fopen(bb_path_motd_file, "r");
362         if (fp) {
363                 while ((c = getc(fp)) != EOF)
364                         putchar(c);
365                 fclose(fp);
366         }
367 }
368
369
370 #ifdef CONFIG_FEATURE_UTMP
371 /* vv  Taken from tinylogin utmp.c  vv */
372
373 /*
374  * read_or_build_utent - see if utmp file is correct for this process
375  *
376  *      System V is very picky about the contents of the utmp file
377  *      and requires that a slot for the current process exist.
378  *      The utmp file is scanned for an entry with the same process
379  *      ID.  If no entry exists the process exits with a message.
380  *
381  *      The "picky" flag is for network and other logins that may
382  *      use special flags.  It allows the pid checks to be overridden.
383  *      This means that getty should never invoke login with any
384  *      command line flags.
385  */
386
387 static void read_or_build_utent(int picky)
388 {
389         struct utmp *ut;
390         pid_t pid = getpid();
391
392         setutent();
393
394         /* First, try to find a valid utmp entry for this process.  */
395         while ((ut = getutent()))
396                 if (ut->ut_pid == pid && ut->ut_line[0] && ut->ut_id[0] &&
397                 (ut->ut_type == LOGIN_PROCESS || ut->ut_type == USER_PROCESS))
398                         break;
399
400         /* If there is one, just use it, otherwise create a new one.  */
401         if (ut) {
402                 utent = *ut;
403         } else {
404                 if (picky)
405                         bb_error_msg_and_die("no utmp entry found");
406
407                 memset(&utent, 0, sizeof(utent));
408                 utent.ut_type = LOGIN_PROCESS;
409                 utent.ut_pid = pid;
410                 strncpy(utent.ut_line, short_tty, sizeof(utent.ut_line));
411                 /* This one is only 4 chars wide. Try to fit something
412                  * remotely meaningful by skipping "tty"... */
413                 strncpy(utent.ut_id, short_tty + 3, sizeof(utent.ut_id));
414                 strncpy(utent.ut_user, "LOGIN", sizeof(utent.ut_user));
415                 utent.ut_time = time(NULL);
416         }
417 }
418
419 /*
420  * write_utent - put a USER_PROCESS entry in the utmp file
421  *
422  *      write_utent changes the type of the current utmp entry to
423  *      USER_PROCESS.  the wtmp file will be updated as well.
424  */
425
426 static void write_utent(const char *username)
427 {
428         utent.ut_type = USER_PROCESS;
429         strncpy(utent.ut_user, username, sizeof(utent.ut_user));
430         utent.ut_time = time(NULL);
431         /* other fields already filled in by read_or_build_utent above */
432         setutent();
433         pututline(&utent);
434         endutent();
435 #ifdef CONFIG_FEATURE_WTMP
436         if (access(bb_path_wtmp_file, R_OK|W_OK) == -1) {
437                 close(creat(bb_path_wtmp_file, 0664));
438         }
439         updwtmp(bb_path_wtmp_file, &utent);
440 #endif
441 }
442 #endif /* CONFIG_FEATURE_UTMP */