login.c 16 KB

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