Tomato 1.28
[tomato.git] / release / src / router / busybox / loginutils / login.c
blobd57d529c03b7c02a3c3f36523b1b051f7b298b5a
1 /* vi: set sw=4 ts=4: */
2 /*
3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
4 */
6 #include "libbb.h"
7 #include <syslog.h>
8 #include <utmp.h>
9 #include <sys/resource.h>
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
17 #if ENABLE_PAM
18 /* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
19 #undef setlocale
20 /* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
21 * Apparently they like to confuse people. */
22 #include <security/pam_appl.h>
23 #include <security/pam_misc.h>
24 static const struct pam_conv conv = {
25 misc_conv,
26 NULL
28 #endif
30 enum {
31 TIMEOUT = 60,
32 EMPTY_USERNAME_COUNT = 10,
33 USERNAME_SIZE = 32,
34 TTYNAME_SIZE = 32,
37 static char* short_tty;
39 #if ENABLE_FEATURE_UTMP
40 /* vv Taken from tinylogin utmp.c vv */
42 * read_or_build_utent - see if utmp file is correct for this process
44 * System V is very picky about the contents of the utmp file
45 * and requires that a slot for the current process exist.
46 * The utmp file is scanned for an entry with the same process
47 * ID. If no entry exists the process exits with a message.
49 * The "picky" flag is for network and other logins that may
50 * use special flags. It allows the pid checks to be overridden.
51 * This means that getty should never invoke login with any
52 * command line flags.
55 static void read_or_build_utent(struct utmp *utptr, int run_by_root)
57 struct utmp *ut;
58 pid_t pid = getpid();
60 setutent();
62 /* First, try to find a valid utmp entry for this process. */
63 /* If there is one, just use it. */
64 while ((ut = getutent()) != NULL)
65 if (ut->ut_pid == pid && ut->ut_line[0] && ut->ut_id[0]
66 && (ut->ut_type == LOGIN_PROCESS || ut->ut_type == USER_PROCESS)
67 ) {
68 *utptr = *ut; /* struct copy */
69 if (run_by_root) /* why only for root? */
70 memset(utptr->ut_host, 0, sizeof(utptr->ut_host));
71 return;
74 // Why? Do we require non-root to exec login from another
75 // former login process (e.g. login shell)? Some login's have
76 // login shells as children, so it won't work...
77 // if (!run_by_root)
78 // bb_error_msg_and_die("no utmp entry found");
80 /* Otherwise create a new one. */
81 memset(utptr, 0, sizeof(*utptr));
82 utptr->ut_type = LOGIN_PROCESS;
83 utptr->ut_pid = pid;
84 strncpy(utptr->ut_line, short_tty, sizeof(utptr->ut_line));
85 /* This one is only 4 chars wide. Try to fit something
86 * remotely meaningful by skipping "tty"... */
87 strncpy(utptr->ut_id, short_tty + 3, sizeof(utptr->ut_id));
88 strncpy(utptr->ut_user, "LOGIN", sizeof(utptr->ut_user));
89 utptr->ut_tv.tv_sec = time(NULL);
93 * write_utent - put a USER_PROCESS entry in the utmp file
95 * write_utent changes the type of the current utmp entry to
96 * USER_PROCESS. the wtmp file will be updated as well.
98 static void write_utent(struct utmp *utptr, const char *username)
100 utptr->ut_type = USER_PROCESS;
101 strncpy(utptr->ut_user, username, sizeof(utptr->ut_user));
102 utptr->ut_tv.tv_sec = time(NULL);
103 /* other fields already filled in by read_or_build_utent above */
104 setutent();
105 pututline(utptr);
106 endutent();
107 #if ENABLE_FEATURE_WTMP
108 if (access(bb_path_wtmp_file, R_OK|W_OK) == -1) {
109 close(creat(bb_path_wtmp_file, 0664));
111 updwtmp(bb_path_wtmp_file, utptr);
112 #endif
114 #else /* !ENABLE_FEATURE_UTMP */
115 #define read_or_build_utent(utptr, run_by_root) ((void)0)
116 #define write_utent(utptr, username) ((void)0)
117 #endif /* !ENABLE_FEATURE_UTMP */
119 #if ENABLE_FEATURE_NOLOGIN
120 static void die_if_nologin(void)
122 FILE *fp;
123 int c;
124 int empty = 1;
126 fp = fopen_for_read("/etc/nologin");
127 if (!fp) /* assuming it does not exist */
128 return;
130 while ((c = getc(fp)) != EOF) {
131 if (c == '\n')
132 bb_putchar('\r');
133 bb_putchar(c);
134 empty = 0;
136 if (empty)
137 puts("\r\nSystem closed for routine maintenance\r");
139 fclose(fp);
140 fflush(NULL);
141 /* Users say that they do need this prior to exit: */
142 tcdrain(STDOUT_FILENO);
143 exit(EXIT_FAILURE);
145 #else
146 static ALWAYS_INLINE void die_if_nologin(void) {}
147 #endif
149 #if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
150 static int check_securetty(void)
152 char *buf = (char*)"/etc/securetty"; /* any non-NULL is ok */
153 parser_t *parser = config_open2("/etc/securetty", fopen_for_read);
154 while (config_read(parser, &buf, 1, 1, "# \t", PARSE_NORMAL)) {
155 if (strcmp(buf, short_tty) == 0)
156 break;
157 buf = NULL;
159 config_close(parser);
160 /* buf != NULL here if config file was not found, empty
161 * or line was found which equals short_tty */
162 return buf != NULL;
164 #else
165 static ALWAYS_INLINE int check_securetty(void) { return 1; }
166 #endif
168 #if ENABLE_SELINUX
169 static void initselinux(char *username, char *full_tty,
170 security_context_t *user_sid)
172 security_context_t old_tty_sid, new_tty_sid;
174 if (!is_selinux_enabled())
175 return;
177 if (get_default_context(username, NULL, user_sid)) {
178 bb_error_msg_and_die("cannot get SID for %s", username);
180 if (getfilecon(full_tty, &old_tty_sid) < 0) {
181 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
183 if (security_compute_relabel(*user_sid, old_tty_sid,
184 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
185 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
187 if (setfilecon(full_tty, new_tty_sid) != 0) {
188 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
191 #endif
193 #if ENABLE_LOGIN_SCRIPTS
194 static void run_login_script(struct passwd *pw, char *full_tty)
196 char *t_argv[2];
198 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
199 if (t_argv[0]) {
200 t_argv[1] = NULL;
201 xsetenv("LOGIN_TTY", full_tty);
202 xsetenv("LOGIN_USER", pw->pw_name);
203 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
204 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
205 xsetenv("LOGIN_SHELL", pw->pw_shell);
206 spawn_and_wait(t_argv); /* NOMMU-friendly */
207 unsetenv("LOGIN_TTY");
208 unsetenv("LOGIN_USER");
209 unsetenv("LOGIN_UID");
210 unsetenv("LOGIN_GID");
211 unsetenv("LOGIN_SHELL");
214 #else
215 void run_login_script(struct passwd *pw, char *full_tty);
216 #endif
218 static void get_username_or_die(char *buf, int size_buf)
220 int c, cntdown;
222 cntdown = EMPTY_USERNAME_COUNT;
223 prompt:
224 print_login_prompt();
225 /* skip whitespace */
226 do {
227 c = getchar();
228 if (c == EOF) exit(EXIT_FAILURE);
229 if (c == '\n') {
230 if (!--cntdown) exit(EXIT_FAILURE);
231 goto prompt;
233 } while (isspace(c));
235 *buf++ = c;
236 if (!fgets(buf, size_buf-2, stdin))
237 exit(EXIT_FAILURE);
238 if (!strchr(buf, '\n'))
239 exit(EXIT_FAILURE);
240 while (isgraph(*buf)) buf++;
241 *buf = '\0';
244 static void motd(void)
246 int fd;
248 fd = open(bb_path_motd_file, O_RDONLY);
249 if (fd >= 0) {
250 fflush(stdout);
251 bb_copyfd_eof(fd, STDOUT_FILENO);
252 close(fd);
256 static void alarm_handler(int sig UNUSED_PARAM)
258 /* This is the escape hatch! Poor serial line users and the like
259 * arrive here when their connection is broken.
260 * We don't want to block here */
261 ndelay_on(1);
262 printf("\r\nLogin timed out after %d seconds\r\n", TIMEOUT);
263 fflush(stdout);
264 /* unix API is brain damaged regarding O_NONBLOCK,
265 * we should undo it, or else we can affect other processes */
266 ndelay_off(1);
267 _exit(EXIT_SUCCESS);
270 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
271 int login_main(int argc UNUSED_PARAM, char **argv)
273 enum {
274 LOGIN_OPT_f = (1<<0),
275 LOGIN_OPT_h = (1<<1),
276 LOGIN_OPT_p = (1<<2),
278 char *fromhost;
279 char username[USERNAME_SIZE];
280 const char *tmp;
281 int run_by_root;
282 unsigned opt;
283 int count = 0;
284 struct passwd *pw;
285 char *opt_host = opt_host; /* for compiler */
286 char *opt_user = opt_user; /* for compiler */
287 char *full_tty;
288 USE_SELINUX(security_context_t user_sid = NULL;)
289 USE_FEATURE_UTMP(struct utmp utent;)
290 #if ENABLE_PAM
291 int pamret;
292 pam_handle_t *pamh;
293 const char *pamuser;
294 const char *failed_msg;
295 struct passwd pwdstruct;
296 char pwdbuf[256];
297 #endif
299 username[0] = '\0';
300 signal(SIGALRM, alarm_handler);
301 alarm(TIMEOUT);
303 /* More of suid paranoia if called by non-root: */
304 /* Clear dangerous stuff, set PATH */
305 run_by_root = !sanitize_env_if_suid();
307 /* Mandatory paranoia for suid applet:
308 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
309 * and any extra open fd's are closed.
310 * (The name of the function is misleading. Not daemonizing here.) */
311 bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
313 opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
314 if (opt & LOGIN_OPT_f) {
315 if (!run_by_root)
316 bb_error_msg_and_die("-f is for root only");
317 safe_strncpy(username, opt_user, sizeof(username));
319 argv += optind;
320 if (argv[0]) /* user from command line (getty) */
321 safe_strncpy(username, argv[0], sizeof(username));
323 /* Let's find out and memorize our tty */
324 if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO) || !isatty(STDERR_FILENO))
325 return EXIT_FAILURE; /* Must be a terminal */
326 full_tty = xmalloc_ttyname(STDIN_FILENO);
327 if (!full_tty)
328 full_tty = xstrdup("UNKNOWN");
329 short_tty = full_tty;
330 if (strncmp(full_tty, "/dev/", 5) == 0)
331 short_tty += 5;
333 read_or_build_utent(&utent, run_by_root);
335 if (opt & LOGIN_OPT_h) {
336 USE_FEATURE_UTMP(safe_strncpy(utent.ut_host, opt_host, sizeof(utent.ut_host));)
337 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
338 } else {
339 fromhost = xasprintf(" on '%s'", short_tty);
342 /* Was breaking "login <username>" from shell command line: */
343 /*bb_setpgrp();*/
345 openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
347 while (1) {
348 /* flush away any type-ahead (as getty does) */
349 ioctl(0, TCFLSH, TCIFLUSH);
351 if (!username[0])
352 get_username_or_die(username, sizeof(username));
354 #if ENABLE_PAM
355 pamret = pam_start("login", username, &conv, &pamh);
356 if (pamret != PAM_SUCCESS) {
357 failed_msg = "start";
358 goto pam_auth_failed;
360 /* set TTY (so things like securetty work) */
361 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
362 if (pamret != PAM_SUCCESS) {
363 failed_msg = "set_item(TTY)";
364 goto pam_auth_failed;
366 pamret = pam_authenticate(pamh, 0);
367 if (pamret != PAM_SUCCESS) {
368 failed_msg = "authenticate";
369 goto pam_auth_failed;
370 /* TODO: or just "goto auth_failed"
371 * since user seems to enter wrong password
372 * (in this case pamret == 7)
375 /* check that the account is healthy */
376 pamret = pam_acct_mgmt(pamh, 0);
377 if (pamret != PAM_SUCCESS) {
378 failed_msg = "acct_mgmt";
379 goto pam_auth_failed;
381 /* read user back */
382 pamuser = NULL;
383 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
384 * thus we cast to (void*) */
385 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
386 failed_msg = "get_item(USER)";
387 goto pam_auth_failed;
389 if (!pamuser || !pamuser[0])
390 goto auth_failed;
391 safe_strncpy(username, pamuser, sizeof(username));
392 /* Don't use "pw = getpwnam(username);",
393 * PAM is said to be capable of destroying static storage
394 * used by getpwnam(). We are using safe(r) function */
395 pw = NULL;
396 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
397 if (!pw)
398 goto auth_failed;
399 pamret = pam_open_session(pamh, 0);
400 if (pamret != PAM_SUCCESS) {
401 failed_msg = "open_session";
402 goto pam_auth_failed;
404 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
405 if (pamret != PAM_SUCCESS) {
406 failed_msg = "setcred";
407 goto pam_auth_failed;
409 break; /* success, continue login process */
411 pam_auth_failed:
412 bb_error_msg("pam_%s call failed: %s (%d)", failed_msg,
413 pam_strerror(pamh, pamret), pamret);
414 safe_strncpy(username, "UNKNOWN", sizeof(username));
415 #else /* not PAM */
416 pw = getpwnam(username);
417 if (!pw) {
418 strcpy(username, "UNKNOWN");
419 goto fake_it;
422 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
423 goto auth_failed;
425 if (opt & LOGIN_OPT_f)
426 break; /* -f USER: success without asking passwd */
428 if (pw->pw_uid == 0 && !check_securetty())
429 goto auth_failed;
431 /* Don't check the password if password entry is empty (!) */
432 if (!pw->pw_passwd[0])
433 break;
434 fake_it:
435 /* authorization takes place here */
436 if (correct_password(pw))
437 break;
438 #endif /* ENABLE_PAM */
439 auth_failed:
440 opt &= ~LOGIN_OPT_f;
441 bb_do_delay(FAIL_DELAY);
442 /* TODO: doesn't sound like correct English phrase to me */
443 puts("Login incorrect");
444 if (++count == 3) {
445 syslog(LOG_WARNING, "invalid password for '%s'%s",
446 username, fromhost);
447 return EXIT_FAILURE;
449 username[0] = '\0';
450 } /* while (1) */
452 alarm(0);
453 /* We can ignore /etc/nologin if we are logging in as root,
454 * it doesn't matter whether we are run by root or not */
455 if (pw->pw_uid != 0)
456 die_if_nologin();
458 write_utent(&utent, username);
460 USE_SELINUX(initselinux(username, full_tty, &user_sid));
462 /* Try these, but don't complain if they fail.
463 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
464 fchown(0, pw->pw_uid, pw->pw_gid);
465 fchmod(0, 0600);
467 /* We trust environment only if we run by root */
468 if (ENABLE_LOGIN_SCRIPTS && run_by_root)
469 run_login_script(pw, full_tty);
471 change_identity(pw);
472 tmp = pw->pw_shell;
473 if (!tmp || !*tmp)
474 tmp = DEFAULT_SHELL;
475 /* setup_environment params: shell, clear_env, change_env, pw */
476 setup_environment(tmp, !(opt & LOGIN_OPT_p), 1, pw);
478 motd();
480 if (pw->pw_uid == 0)
481 syslog(LOG_INFO, "root login%s", fromhost);
483 /* well, a simple setexeccon() here would do the job as well,
484 * but let's play the game for now */
485 USE_SELINUX(set_current_security_context(user_sid);)
487 // util-linux login also does:
488 // /* start new session */
489 // setsid();
490 // /* TIOCSCTTY: steal tty from other process group */
491 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
492 // BBox login used to do this (see above):
493 // bb_setpgrp();
494 // If this stuff is really needed, add it and explain why!
496 /* Set signals to defaults */
497 /* Non-ignored signals revert to SIG_DFL on exec anyway */
498 /*signal(SIGALRM, SIG_DFL);*/
500 /* Is this correct? This way user can ctrl-c out of /etc/profile,
501 * potentially creating security breach (tested with bash 3.0).
502 * But without this, bash 3.0 will not enable ctrl-c either.
503 * Maybe bash is buggy?
504 * Need to find out what standards say about /bin/login -
505 * should we leave SIGINT etc enabled or disabled? */
506 signal(SIGINT, SIG_DFL);
508 /* Exec login shell with no additional parameters */
509 run_shell(tmp, 1, NULL, NULL);
511 /* return EXIT_FAILURE; - not reached */