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