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