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