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