ps: revert wrong "optimization": (i & 1) -> i
[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 #if ENABLE_FEATURE_NOLOGIN
104 static void die_if_nologin_and_non_root(int amroot)
105 {
106         FILE *fp;
107         int c;
108
109         if (access("/etc/nologin", F_OK))
110                 return;
111
112         fp = fopen("/etc/nologin", "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 #else
125 static ALWAYS_INLINE void die_if_nologin_and_non_root(int amroot) {}
126 #endif
127
128 #if ENABLE_FEATURE_SECURETTY
129 static int check_securetty(void)
130 {
131         FILE *fp;
132         int i;
133         char buf[256];
134
135         fp = fopen("/etc/securetty", "r");
136         if (!fp) {
137                 /* A missing securetty file is not an error. */
138                 return 1;
139         }
140         while (fgets(buf, sizeof(buf)-1, fp)) {
141                 for (i = strlen(buf)-1; i >= 0; --i) {
142                         if (!isspace(buf[i]))
143                                 break;
144                 }
145                 buf[++i] = '\0';
146                 if (!buf[0] || (buf[0] == '#'))
147                         continue;
148                 if (strcmp(buf, short_tty) == 0) {
149                         fclose(fp);
150                         return 1;
151                 }
152         }
153         fclose(fp);
154         return 0;
155 }
156 #else
157 static ALWAYS_INLINE int check_securetty(void) { return 1; }
158 #endif
159
160 static void get_username_or_die(char *buf, int size_buf)
161 {
162         int c, cntdown;
163
164         cntdown = EMPTY_USERNAME_COUNT;
165  prompt:
166         print_login_prompt();
167         /* skip whitespace */
168         do {
169                 c = getchar();
170                 if (c == EOF) exit(1);
171                 if (c == '\n') {
172                         if (!--cntdown) exit(1);
173                         goto prompt;
174                 }
175         } while (isspace(c));
176
177         *buf++ = c;
178         if (!fgets(buf, size_buf-2, stdin))
179                 exit(1);
180         if (!strchr(buf, '\n'))
181                 exit(1);
182         while (isgraph(*buf)) buf++;
183         *buf = '\0';
184 }
185
186 static void motd(void)
187 {
188         int fd;
189
190         fd = open(bb_path_motd_file, O_RDONLY);
191         if (fd) {
192                 fflush(stdout);
193                 bb_copyfd_eof(fd, STDOUT_FILENO);
194                 close(fd);
195         }
196 }
197
198 static void alarm_handler(int sig ATTRIBUTE_UNUSED)
199 {
200         /* This is the escape hatch!  Poor serial line users and the like
201          * arrive here when their connection is broken.
202          * We don't want to block here */
203         ndelay_on(1);
204         ndelay_on(2);
205         printf("\r\nLogin timed out after %d seconds\r\n", TIMEOUT);
206         exit(EXIT_SUCCESS);
207 }
208
209 int login_main(int argc, char **argv);
210 int login_main(int argc, char **argv)
211 {
212         enum {
213                 LOGIN_OPT_f = (1<<0),
214                 LOGIN_OPT_h = (1<<1),
215                 LOGIN_OPT_p = (1<<2),
216         };
217         char fromhost[512];
218         char username[USERNAME_SIZE];
219         const char *tmp;
220         int amroot;
221         unsigned opt;
222         int count = 0;
223         struct passwd *pw;
224         char *opt_host = NULL;
225         char *opt_user = NULL;
226         char full_tty[TTYNAME_SIZE];
227         USE_SELINUX(security_context_t user_sid = NULL;)
228         USE_FEATURE_UTMP(struct utmp utent;)
229
230         short_tty = full_tty;
231         username[0] = '\0';
232         amroot = (getuid() == 0);
233         signal(SIGALRM, alarm_handler);
234         alarm(TIMEOUT);
235
236         /* Mandatory paranoia for suid applet:
237          * ensure that fd# 0,1,2 are opened (at least to /dev/null)
238          * and any extra open fd's are closed.
239          * (The name of the function is misleading. Not daemonizing here.) */
240         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
241
242         opt = getopt32(argc, argv, "f:h:p", &opt_user, &opt_host);
243         if (opt & LOGIN_OPT_f) {
244                 if (!amroot)
245                         bb_error_msg_and_die("-f is for root only");
246                 safe_strncpy(username, opt_user, sizeof(username));
247         }
248         if (optind < argc) /* user from command line (getty) */
249                 safe_strncpy(username, argv[optind], sizeof(username));
250
251         /* Let's find out and memorize our tty */
252         if (!isatty(0) || !isatty(1) || !isatty(2))
253                 return EXIT_FAILURE;            /* Must be a terminal */
254         safe_strncpy(full_tty, "UNKNOWN", sizeof(full_tty));
255         tmp = ttyname(0);
256         if (tmp) {
257                 safe_strncpy(full_tty, tmp, sizeof(full_tty));
258                 if (strncmp(full_tty, "/dev/", 5) == 0)
259                         short_tty = full_tty + 5;
260         }
261
262         read_or_build_utent(&utent, !amroot);
263
264         if (opt_host) {
265                 USE_FEATURE_UTMP(
266                         safe_strncpy(utent.ut_host, opt_host, sizeof(utent.ut_host));
267                 )
268                 snprintf(fromhost, sizeof(fromhost)-1, " on '%.100s' from "
269                                         "'%.200s'", short_tty, opt_host);
270         } else
271                 snprintf(fromhost, sizeof(fromhost)-1, " on '%.100s'", short_tty);
272
273         // Was breaking "login <username>" from shell command line:
274         // bb_setpgrp();
275
276         openlog(applet_name, LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH);
277
278         while (1) {
279                 if (!username[0])
280                         get_username_or_die(username, sizeof(username));
281
282                 pw = getpwnam(username);
283                 if (!pw) {
284                         strcpy(username, "UNKNOWN");
285                         goto fake_it;
286                 }
287
288                 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
289                         goto auth_failed;
290
291                 if (opt & LOGIN_OPT_f)
292                         break; /* -f USER: success without asking passwd */
293
294                 if (pw->pw_uid == 0 && !check_securetty())
295                         goto auth_failed;
296
297                 /* Don't check the password if password entry is empty (!) */
298                 if (!pw->pw_passwd[0])
299                         break;
300  fake_it:
301                 /* authorization takes place here */
302                 if (correct_password(pw))
303                         break;
304  auth_failed:
305                 opt &= ~LOGIN_OPT_f;
306                 bb_do_delay(FAIL_DELAY);
307                 puts("Login incorrect");
308                 if (++count == 3) {
309                         syslog(LOG_WARNING, "invalid password for '%s'%s",
310                                                 username, fromhost);
311                         return EXIT_FAILURE;
312                 }
313                 username[0] = '\0';
314         }
315
316         alarm(0);
317         die_if_nologin_and_non_root(pw->pw_uid == 0);
318
319         write_utent(&utent, username);
320
321 #if ENABLE_SELINUX
322         if (is_selinux_enabled()) {
323                 security_context_t old_tty_sid, new_tty_sid;
324
325                 if (get_default_context(username, NULL, &user_sid)) {
326                         bb_error_msg_and_die("cannot get SID for %s",
327                                         username);
328                 }
329                 if (getfilecon(full_tty, &old_tty_sid) < 0) {
330                         bb_perror_msg_and_die("getfilecon(%s) failed",
331                                         full_tty);
332                 }
333                 if (security_compute_relabel(user_sid, old_tty_sid,
334                                         SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
335                         bb_perror_msg_and_die("security_change_sid(%s) failed",
336                                         full_tty);
337                 }
338                 if (setfilecon(full_tty, new_tty_sid) != 0) {
339                         bb_perror_msg_and_die("chsid(%s, %s) failed",
340                                         full_tty, new_tty_sid);
341                 }
342         }
343 #endif
344         /* Try these, but don't complain if they fail.
345          * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
346         fchown(0, pw->pw_uid, pw->pw_gid);
347         fchmod(0, 0600);
348
349         if (ENABLE_LOGIN_SCRIPTS) {
350                 char *t_argv[2];
351
352                 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
353                 if (t_argv[0]) {
354                         t_argv[1] = NULL;
355                         xsetenv("LOGIN_TTY", full_tty);
356                         xsetenv("LOGIN_USER", pw->pw_name);
357                         xsetenv("LOGIN_UID", utoa(pw->pw_uid));
358                         xsetenv("LOGIN_GID", utoa(pw->pw_gid));
359                         xsetenv("LOGIN_SHELL", pw->pw_shell);
360                         xspawn(t_argv); /* NOMMU-friendly */
361                         /* All variables are unset by setup_environment */
362                         wait(NULL);
363                 }
364         }
365
366         change_identity(pw);
367         tmp = pw->pw_shell;
368         if (!tmp || !*tmp)
369                 tmp = DEFAULT_SHELL;
370         setup_environment(tmp, 1, !(opt & LOGIN_OPT_p), pw);
371
372         motd();
373
374         if (pw->pw_uid == 0)
375                 syslog(LOG_INFO, "root login%s", fromhost);
376 #if ENABLE_SELINUX
377         /* well, a simple setexeccon() here would do the job as well,
378          * but let's play the game for now */
379         set_current_security_context(user_sid);
380 #endif
381
382         // util-linux login also does:
383         // /* start new session */
384         // setsid();
385         // /* TIOCSCTTY: steal tty from other process group */
386         // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
387         // BBox login used to do this (see above):
388         // bb_setpgrp();
389         // If this stuff is really needed, add it and explain why!
390
391         /* set signals to defaults */
392         signal(SIGALRM, SIG_DFL);
393         /* Is this correct? This way user can ctrl-c out of /etc/profile,
394          * potentially creating security breach (tested with bash 3.0).
395          * But without this, bash 3.0 will not enable ctrl-c either.
396          * Maybe bash is buggy?
397          * Need to find out what standards say about /bin/login -
398          * should it leave SIGINT etc enabled or disabled? */
399         signal(SIGINT, SIG_DFL);
400
401         run_shell(tmp, 1, 0, 0);        /* exec the shell finally */
402
403         return EXIT_FAILURE;
404 }