summaryrefslogtreecommitdiff
path: root/loginutils/login.c (plain)
blob: 862104c9fac8dad703eec9b3a93a7019f7e2f7ad
1/* vi: set sw=4 ts=4: */
2/*
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4 */
5
6//usage:#define login_trivial_usage
7//usage: "[-p] [-h HOST] [[-f] USER]"
8//usage:#define login_full_usage "\n\n"
9//usage: "Begin a new session on the system\n"
10//usage: "\n -f Don't authenticate (user already authenticated)"
11//usage: "\n -h Name of the remote host"
12//usage: "\n -p Preserve environment"
13
14#include "libbb.h"
15#include <syslog.h>
16#include <sys/resource.h>
17
18#if ENABLE_SELINUX
19# include <selinux/selinux.h> /* for is_selinux_enabled() */
20#ifndef __BIONIC__
21# include <selinux/get_context_list.h> /* for get_default_context() */
22# include <selinux/flask.h> /* for security class definitions */
23#endif
24#endif
25
26#if ENABLE_PAM
27/* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
28# undef setlocale
29/* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
30 * Apparently they like to confuse people. */
31# include <security/pam_appl.h>
32# include <security/pam_misc.h>
33static const struct pam_conv conv = {
34 misc_conv,
35 NULL
36};
37#endif
38
39enum {
40 TIMEOUT = 60,
41 EMPTY_USERNAME_COUNT = 10,
42 /* Some users found 32 chars limit to be too low: */
43 USERNAME_SIZE = 64,
44 TTYNAME_SIZE = 32,
45};
46
47struct globals {
48 struct termios tty_attrs;
49} FIX_ALIASING;
50#define G (*(struct globals*)&bb_common_bufsiz1)
51#define INIT_G() do { } while (0)
52
53
54#if ENABLE_FEATURE_NOLOGIN
55static void die_if_nologin(void)
56{
57 FILE *fp;
58 int c;
59 int empty = 1;
60
61 fp = fopen_for_read("/etc/nologin");
62 if (!fp) /* assuming it does not exist */
63 return;
64
65 while ((c = getc(fp)) != EOF) {
66 if (c == '\n')
67 bb_putchar('\r');
68 bb_putchar(c);
69 empty = 0;
70 }
71 if (empty)
72 puts("\r\nSystem closed for routine maintenance\r");
73
74 fclose(fp);
75 fflush_all();
76 /* Users say that they do need this prior to exit: */
77 tcdrain(STDOUT_FILENO);
78 exit(EXIT_FAILURE);
79}
80#else
81# define die_if_nologin() ((void)0)
82#endif
83
84#if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
85static int check_securetty(const char *short_tty)
86{
87 char *buf = (char*)"/etc/securetty"; /* any non-NULL is ok */
88 parser_t *parser = config_open2("/etc/securetty", fopen_for_read);
89 while (config_read(parser, &buf, 1, 1, "# \t", PARSE_NORMAL)) {
90 if (strcmp(buf, short_tty) == 0)
91 break;
92 buf = NULL;
93 }
94 config_close(parser);
95 /* buf != NULL here if config file was not found, empty
96 * or line was found which equals short_tty */
97 return buf != NULL;
98}
99#else
100static ALWAYS_INLINE int check_securetty(const char *short_tty UNUSED_PARAM) { return 1; }
101#endif
102
103#if ENABLE_SELINUX
104static void initselinux(char *username, char *full_tty,
105 security_context_t *user_sid)
106{
107 security_context_t old_tty_sid, new_tty_sid;
108
109 if (!is_selinux_enabled())
110 return;
111
112 if (get_default_context(username, NULL, user_sid)) {
113 bb_error_msg_and_die("can't get SID for %s", username);
114 }
115 if (getfilecon(full_tty, &old_tty_sid) < 0) {
116 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
117 }
118 if (security_compute_relabel(*user_sid, old_tty_sid,
119 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
120 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
121 }
122 if (setfilecon(full_tty, new_tty_sid) != 0) {
123 if (strcmp(old_tty_sid, new_tty_sid))
124 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
125 }
126}
127#endif
128
129#if ENABLE_LOGIN_SCRIPTS
130static void run_login_script(struct passwd *pw, char *full_tty)
131{
132 char *t_argv[2];
133
134 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
135 if (t_argv[0]) {
136 t_argv[1] = NULL;
137 xsetenv("LOGIN_TTY", full_tty);
138 xsetenv("LOGIN_USER", pw->pw_name);
139 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
140 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
141 xsetenv("LOGIN_SHELL", pw->pw_shell);
142 spawn_and_wait(t_argv); /* NOMMU-friendly */
143 unsetenv("LOGIN_TTY");
144 unsetenv("LOGIN_USER");
145 unsetenv("LOGIN_UID");
146 unsetenv("LOGIN_GID");
147 unsetenv("LOGIN_SHELL");
148 }
149}
150#else
151void run_login_script(struct passwd *pw, char *full_tty);
152#endif
153
154#if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
155static void login_pam_end(pam_handle_t *pamh)
156{
157 int pamret;
158
159 pamret = pam_setcred(pamh, PAM_DELETE_CRED);
160 if (pamret != PAM_SUCCESS) {
161 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
162 pam_strerror(pamh, pamret), pamret);
163 }
164 pamret = pam_close_session(pamh, 0);
165 if (pamret != PAM_SUCCESS) {
166 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
167 pam_strerror(pamh, pamret), pamret);
168 }
169 pamret = pam_end(pamh, pamret);
170 if (pamret != PAM_SUCCESS) {
171 bb_error_msg("pam_%s failed: %s (%d)", "end",
172 pam_strerror(pamh, pamret), pamret);
173 }
174}
175#endif /* ENABLE_PAM */
176
177static void get_username_or_die(char *buf, int size_buf)
178{
179 int c, cntdown;
180
181 cntdown = EMPTY_USERNAME_COUNT;
182 prompt:
183 print_login_prompt();
184 /* skip whitespace */
185 do {
186 c = getchar();
187 if (c == EOF)
188 exit(EXIT_FAILURE);
189 if (c == '\n') {
190 if (!--cntdown)
191 exit(EXIT_FAILURE);
192 goto prompt;
193 }
194 } while (isspace(c)); /* maybe isblank? */
195
196 *buf++ = c;
197 if (!fgets(buf, size_buf-2, stdin))
198 exit(EXIT_FAILURE);
199 if (!strchr(buf, '\n'))
200 exit(EXIT_FAILURE);
201 while ((unsigned char)*buf > ' ')
202 buf++;
203 *buf = '\0';
204}
205
206static void motd(void)
207{
208 int fd;
209
210 fd = open(bb_path_motd_file, O_RDONLY);
211 if (fd >= 0) {
212 fflush_all();
213 bb_copyfd_eof(fd, STDOUT_FILENO);
214 close(fd);
215 }
216}
217
218static void alarm_handler(int sig UNUSED_PARAM)
219{
220 /* This is the escape hatch! Poor serial line users and the like
221 * arrive here when their connection is broken.
222 * We don't want to block here */
223 ndelay_on(STDOUT_FILENO);
224 /* Test for correct attr restoring:
225 * run "getty 0 -" from a shell, enter bogus username, stop at
226 * password prompt, let it time out. Without the tcsetattr below,
227 * when you are back at shell prompt, echo will be still off.
228 */
229 tcsetattr_stdin_TCSANOW(&G.tty_attrs);
230 printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
231 fflush_all();
232 /* unix API is brain damaged regarding O_NONBLOCK,
233 * we should undo it, or else we can affect other processes */
234 ndelay_off(STDOUT_FILENO);
235 _exit(EXIT_SUCCESS);
236}
237
238int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
239int login_main(int argc UNUSED_PARAM, char **argv)
240{
241 enum {
242 LOGIN_OPT_f = (1<<0),
243 LOGIN_OPT_h = (1<<1),
244 LOGIN_OPT_p = (1<<2),
245 };
246 char *fromhost;
247 char username[USERNAME_SIZE];
248 int run_by_root;
249 unsigned opt;
250 int count = 0;
251 struct passwd *pw;
252 char *opt_host = NULL;
253 char *opt_user = opt_user; /* for compiler */
254 char *full_tty;
255 char *short_tty;
256 IF_SELINUX(security_context_t user_sid = NULL;)
257#if ENABLE_PAM
258 int pamret;
259 pam_handle_t *pamh;
260 const char *pamuser;
261 const char *failed_msg;
262 struct passwd pwdstruct;
263 char pwdbuf[256];
264 char **pamenv;
265#endif
266#if ENABLE_LOGIN_SESSION_AS_CHILD
267 pid_t child_pid;
268#endif
269
270 INIT_G();
271
272 /* More of suid paranoia if called by non-root: */
273 /* Clear dangerous stuff, set PATH */
274 run_by_root = !sanitize_env_if_suid();
275
276 /* Mandatory paranoia for suid applet:
277 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
278 * and any extra open fd's are closed.
279 * (The name of the function is misleading. Not daemonizing here.) */
280 bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
281
282 username[0] = '\0';
283 opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
284 if (opt & LOGIN_OPT_f) {
285 if (!run_by_root)
286 bb_error_msg_and_die("-f is for root only");
287 safe_strncpy(username, opt_user, sizeof(username));
288 }
289 argv += optind;
290 if (argv[0]) /* user from command line (getty) */
291 safe_strncpy(username, argv[0], sizeof(username));
292
293 /* Save tty attributes - and by doing it, check that it's indeed a tty */
294 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
295 || !isatty(STDOUT_FILENO)
296 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
297 ) {
298 return EXIT_FAILURE; /* Must be a terminal */
299 }
300
301 /* We install timeout handler only _after_ we saved G.tty_attrs */
302 signal(SIGALRM, alarm_handler);
303 alarm(TIMEOUT);
304
305 /* Find out and memorize our tty name */
306 full_tty = xmalloc_ttyname(STDIN_FILENO);
307 if (!full_tty)
308 full_tty = xstrdup("UNKNOWN");
309 short_tty = skip_dev_pfx(full_tty);
310
311 if (opt_host) {
312 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
313 } else {
314 fromhost = xasprintf(" on '%s'", short_tty);
315 }
316
317 /* Was breaking "login <username>" from shell command line: */
318 /*bb_setpgrp();*/
319
320 openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
321
322 while (1) {
323 /* flush away any type-ahead (as getty does) */
324 tcflush(0, TCIFLUSH);
325
326 if (!username[0])
327 get_username_or_die(username, sizeof(username));
328
329#if ENABLE_PAM
330 pamret = pam_start("login", username, &conv, &pamh);
331 if (pamret != PAM_SUCCESS) {
332 failed_msg = "start";
333 goto pam_auth_failed;
334 }
335 /* set TTY (so things like securetty work) */
336 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
337 if (pamret != PAM_SUCCESS) {
338 failed_msg = "set_item(TTY)";
339 goto pam_auth_failed;
340 }
341 /* set RHOST */
342 if (opt_host) {
343 pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
344 if (pamret != PAM_SUCCESS) {
345 failed_msg = "set_item(RHOST)";
346 goto pam_auth_failed;
347 }
348 }
349 if (!(opt & LOGIN_OPT_f)) {
350 pamret = pam_authenticate(pamh, 0);
351 if (pamret != PAM_SUCCESS) {
352 failed_msg = "authenticate";
353 goto pam_auth_failed;
354 /* TODO: or just "goto auth_failed"
355 * since user seems to enter wrong password
356 * (in this case pamret == 7)
357 */
358 }
359 }
360 /* check that the account is healthy */
361 pamret = pam_acct_mgmt(pamh, 0);
362 if (pamret != PAM_SUCCESS) {
363 failed_msg = "acct_mgmt";
364 goto pam_auth_failed;
365 }
366 /* read user back */
367 pamuser = NULL;
368 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
369 * thus we cast to (void*) */
370 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
371 failed_msg = "get_item(USER)";
372 goto pam_auth_failed;
373 }
374 if (!pamuser || !pamuser[0])
375 goto auth_failed;
376 safe_strncpy(username, pamuser, sizeof(username));
377 /* Don't use "pw = getpwnam(username);",
378 * PAM is said to be capable of destroying static storage
379 * used by getpwnam(). We are using safe(r) function */
380 pw = NULL;
381 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
382 if (!pw)
383 goto auth_failed;
384 pamret = pam_open_session(pamh, 0);
385 if (pamret != PAM_SUCCESS) {
386 failed_msg = "open_session";
387 goto pam_auth_failed;
388 }
389 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
390 if (pamret != PAM_SUCCESS) {
391 failed_msg = "setcred";
392 goto pam_auth_failed;
393 }
394 break; /* success, continue login process */
395
396 pam_auth_failed:
397 /* syslog, because we don't want potential attacker
398 * to know _why_ login failed */
399 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
400 pam_strerror(pamh, pamret), pamret);
401 safe_strncpy(username, "UNKNOWN", sizeof(username));
402#else /* not PAM */
403 pw = safegetpwnam(username);
404 if (!pw) {
405 strcpy(username, "UNKNOWN");
406 goto fake_it;
407 }
408
409 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
410 goto auth_failed;
411
412 if (opt & LOGIN_OPT_f)
413 break; /* -f USER: success without asking passwd */
414
415 if (pw->pw_uid == 0 && !check_securetty(short_tty))
416 goto auth_failed;
417
418 /* Don't check the password if password entry is empty (!) */
419 if (!pw->pw_passwd[0])
420 break;
421 fake_it:
422 /* Password reading and authorization takes place here.
423 * Note that reads (in no-echo mode) trash tty attributes.
424 * If we get interrupted by SIGALRM, we need to restore attrs.
425 */
426 if (ask_and_check_password(pw) > 0)
427 break;
428#endif /* ENABLE_PAM */
429 auth_failed:
430 opt &= ~LOGIN_OPT_f;
431 bb_do_delay(LOGIN_FAIL_DELAY);
432 /* TODO: doesn't sound like correct English phrase to me */
433 puts("Login incorrect");
434 if (++count == 3) {
435 syslog(LOG_WARNING, "invalid password for '%s'%s",
436 username, fromhost);
437
438 if (ENABLE_FEATURE_CLEAN_UP)
439 free(fromhost);
440
441 return EXIT_FAILURE;
442 }
443 username[0] = '\0';
444 } /* while (1) */
445
446 alarm(0);
447 /* We can ignore /etc/nologin if we are logging in as root,
448 * it doesn't matter whether we are run by root or not */
449 if (pw->pw_uid != 0)
450 die_if_nologin();
451
452#if ENABLE_LOGIN_SESSION_AS_CHILD
453 child_pid = vfork();
454 if (child_pid != 0) {
455 if (child_pid < 0)
456 bb_perror_msg("vfork");
457 else {
458 if (safe_waitpid(child_pid, NULL, 0) == -1)
459 bb_perror_msg("waitpid");
460 update_utmp(child_pid, DEAD_PROCESS, NULL, NULL, NULL);
461 }
462 IF_PAM(login_pam_end(pamh);)
463 return 0;
464 }
465#endif
466
467 IF_SELINUX(initselinux(username, full_tty, &user_sid);)
468
469 /* Try these, but don't complain if they fail.
470 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
471 fchown(0, pw->pw_uid, pw->pw_gid);
472 fchmod(0, 0600);
473
474 update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
475
476 /* We trust environment only if we run by root */
477 if (ENABLE_LOGIN_SCRIPTS && run_by_root)
478 run_login_script(pw, full_tty);
479
480 change_identity(pw);
481 setup_environment(pw->pw_shell,
482 (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
483 pw);
484
485#if ENABLE_PAM
486 /* Modules such as pam_env will setup the PAM environment,
487 * which should be copied into the new environment. */
488 pamenv = pam_getenvlist(pamh);
489 if (pamenv) while (*pamenv) {
490 putenv(*pamenv);
491 pamenv++;
492 }
493#endif
494
495 motd();
496
497 if (pw->pw_uid == 0)
498 syslog(LOG_INFO, "root login%s", fromhost);
499
500 if (ENABLE_FEATURE_CLEAN_UP)
501 free(fromhost);
502
503 /* well, a simple setexeccon() here would do the job as well,
504 * but let's play the game for now */
505 IF_SELINUX(set_current_security_context(user_sid);)
506
507 // util-linux login also does:
508 // /* start new session */
509 // setsid();
510 // /* TIOCSCTTY: steal tty from other process group */
511 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
512 // BBox login used to do this (see above):
513 // bb_setpgrp();
514 // If this stuff is really needed, add it and explain why!
515
516 /* Set signals to defaults */
517 /* Non-ignored signals revert to SIG_DFL on exec anyway */
518 /*signal(SIGALRM, SIG_DFL);*/
519
520 /* Is this correct? This way user can ctrl-c out of /etc/profile,
521 * potentially creating security breach (tested with bash 3.0).
522 * But without this, bash 3.0 will not enable ctrl-c either.
523 * Maybe bash is buggy?
524 * Need to find out what standards say about /bin/login -
525 * should we leave SIGINT etc enabled or disabled? */
526 signal(SIGINT, SIG_DFL);
527
528 /* Exec login shell with no additional parameters */
529 run_shell(pw->pw_shell, 1, NULL, NULL);
530
531 /* return EXIT_FAILURE; - not reached */
532}
533