login.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. #else
  224. # define login_pam_end(pamh) ((void)0)
  225. #endif
  226. static void get_username_or_die(char *buf, int size_buf)
  227. {
  228. int c, cntdown;
  229. cntdown = EMPTY_USERNAME_COUNT;
  230. prompt:
  231. print_login_prompt();
  232. /* skip whitespace */
  233. do {
  234. c = getchar();
  235. if (c == EOF)
  236. exit(EXIT_FAILURE);
  237. if (c == '\n') {
  238. if (!--cntdown)
  239. exit(EXIT_FAILURE);
  240. goto prompt;
  241. }
  242. } while (isspace(c)); /* maybe isblank? */
  243. *buf++ = c;
  244. if (!fgets(buf, size_buf-2, stdin))
  245. exit(EXIT_FAILURE);
  246. if (!strchr(buf, '\n'))
  247. exit(EXIT_FAILURE);
  248. while ((unsigned char)*buf > ' ')
  249. buf++;
  250. *buf = '\0';
  251. }
  252. static void motd(void)
  253. {
  254. int fd;
  255. fd = open(bb_path_motd_file, O_RDONLY);
  256. if (fd >= 0) {
  257. fflush_all();
  258. bb_copyfd_eof(fd, STDOUT_FILENO);
  259. close(fd);
  260. }
  261. }
  262. static void alarm_handler(int sig UNUSED_PARAM)
  263. {
  264. /* This is the escape hatch! Poor serial line users and the like
  265. * arrive here when their connection is broken.
  266. * We don't want to block here */
  267. ndelay_on(STDOUT_FILENO);
  268. /* Test for correct attr restoring:
  269. * run "getty 0 -" from a shell, enter bogus username, stop at
  270. * password prompt, let it time out. Without the tcsetattr below,
  271. * when you are back at shell prompt, echo will be still off.
  272. */
  273. tcsetattr_stdin_TCSANOW(&G.tty_attrs);
  274. printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
  275. fflush_all();
  276. /* unix API is brain damaged regarding O_NONBLOCK,
  277. * we should undo it, or else we can affect other processes */
  278. ndelay_off(STDOUT_FILENO);
  279. _exit(EXIT_SUCCESS);
  280. }
  281. int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  282. int login_main(int argc UNUSED_PARAM, char **argv)
  283. {
  284. enum {
  285. LOGIN_OPT_f = (1<<0),
  286. LOGIN_OPT_h = (1<<1),
  287. LOGIN_OPT_p = (1<<2),
  288. };
  289. char *fromhost;
  290. char username[USERNAME_SIZE];
  291. int run_by_root;
  292. unsigned opt;
  293. int count = 0;
  294. struct passwd *pw;
  295. char *opt_host = NULL;
  296. char *opt_user = opt_user; /* for compiler */
  297. char *full_tty;
  298. char *short_tty;
  299. IF_SELINUX(security_context_t user_sid = NULL;)
  300. #if ENABLE_PAM
  301. int pamret;
  302. pam_handle_t *pamh;
  303. const char *pamuser;
  304. const char *failed_msg;
  305. struct passwd pwdstruct;
  306. char pwdbuf[256];
  307. char **pamenv;
  308. #endif
  309. #if ENABLE_LOGIN_SESSION_AS_CHILD
  310. pid_t child_pid;
  311. #endif
  312. INIT_G();
  313. /* More of suid paranoia if called by non-root: */
  314. /* Clear dangerous stuff, set PATH */
  315. run_by_root = !sanitize_env_if_suid();
  316. /* Mandatory paranoia for suid applet:
  317. * ensure that fd# 0,1,2 are opened (at least to /dev/null)
  318. * and any extra open fd's are closed.
  319. */
  320. bb_daemon_helper(DAEMON_CLOSE_EXTRA_FDS);
  321. username[0] = '\0';
  322. opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
  323. if (opt & LOGIN_OPT_f) {
  324. if (!run_by_root)
  325. bb_error_msg_and_die("-f is for root only");
  326. safe_strncpy(username, opt_user, sizeof(username));
  327. }
  328. argv += optind;
  329. if (argv[0]) /* user from command line (getty) */
  330. safe_strncpy(username, argv[0], sizeof(username));
  331. /* Save tty attributes - and by doing it, check that it's indeed a tty */
  332. if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
  333. || !isatty(STDOUT_FILENO)
  334. /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
  335. ) {
  336. return EXIT_FAILURE; /* Must be a terminal */
  337. }
  338. /* We install timeout handler only _after_ we saved G.tty_attrs */
  339. signal(SIGALRM, alarm_handler);
  340. alarm(TIMEOUT);
  341. /* Find out and memorize our tty name */
  342. full_tty = xmalloc_ttyname(STDIN_FILENO);
  343. if (!full_tty)
  344. full_tty = xstrdup("UNKNOWN");
  345. short_tty = skip_dev_pfx(full_tty);
  346. if (opt_host) {
  347. fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
  348. } else {
  349. fromhost = xasprintf(" on '%s'", short_tty);
  350. }
  351. /* Was breaking "login <username>" from shell command line: */
  352. /*bb_setpgrp();*/
  353. openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
  354. while (1) {
  355. /* flush away any type-ahead (as getty does) */
  356. tcflush(0, TCIFLUSH);
  357. if (!username[0])
  358. get_username_or_die(username, sizeof(username));
  359. #if ENABLE_PAM
  360. pamret = pam_start("login", username, &conv, &pamh);
  361. if (pamret != PAM_SUCCESS) {
  362. failed_msg = "start";
  363. goto pam_auth_failed;
  364. }
  365. /* set TTY (so things like securetty work) */
  366. pamret = pam_set_item(pamh, PAM_TTY, short_tty);
  367. if (pamret != PAM_SUCCESS) {
  368. failed_msg = "set_item(TTY)";
  369. goto pam_auth_failed;
  370. }
  371. /* set RHOST */
  372. if (opt_host) {
  373. pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
  374. if (pamret != PAM_SUCCESS) {
  375. failed_msg = "set_item(RHOST)";
  376. goto pam_auth_failed;
  377. }
  378. }
  379. if (!(opt & LOGIN_OPT_f)) {
  380. pamret = pam_authenticate(pamh, 0);
  381. if (pamret != PAM_SUCCESS) {
  382. failed_msg = "authenticate";
  383. goto pam_auth_failed;
  384. /* TODO: or just "goto auth_failed"
  385. * since user seems to enter wrong password
  386. * (in this case pamret == 7)
  387. */
  388. }
  389. }
  390. /* check that the account is healthy */
  391. pamret = pam_acct_mgmt(pamh, 0);
  392. if (pamret != PAM_SUCCESS) {
  393. failed_msg = "acct_mgmt";
  394. goto pam_auth_failed;
  395. }
  396. /* read user back */
  397. pamuser = NULL;
  398. /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
  399. * thus we cast to (void*) */
  400. if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
  401. failed_msg = "get_item(USER)";
  402. goto pam_auth_failed;
  403. }
  404. if (!pamuser || !pamuser[0])
  405. goto auth_failed;
  406. safe_strncpy(username, pamuser, sizeof(username));
  407. /* Don't use "pw = getpwnam(username);",
  408. * PAM is said to be capable of destroying static storage
  409. * used by getpwnam(). We are using safe(r) function */
  410. pw = NULL;
  411. getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
  412. if (!pw)
  413. goto auth_failed;
  414. pamret = pam_open_session(pamh, 0);
  415. if (pamret != PAM_SUCCESS) {
  416. failed_msg = "open_session";
  417. goto pam_auth_failed;
  418. }
  419. pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
  420. if (pamret != PAM_SUCCESS) {
  421. failed_msg = "setcred";
  422. goto pam_auth_failed;
  423. }
  424. break; /* success, continue login process */
  425. pam_auth_failed:
  426. /* syslog, because we don't want potential attacker
  427. * to know _why_ login failed */
  428. syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
  429. pam_strerror(pamh, pamret), pamret);
  430. login_pam_end(pamh);
  431. safe_strncpy(username, "UNKNOWN", sizeof(username));
  432. #else /* not PAM */
  433. pw = getpwnam(username);
  434. if (!pw) {
  435. strcpy(username, "UNKNOWN");
  436. goto fake_it;
  437. }
  438. if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
  439. goto auth_failed;
  440. if (opt & LOGIN_OPT_f)
  441. break; /* -f USER: success without asking passwd */
  442. if (pw->pw_uid == 0 && !is_tty_secure(short_tty))
  443. goto auth_failed;
  444. /* Don't check the password if password entry is empty (!) */
  445. if (!pw->pw_passwd[0])
  446. break;
  447. fake_it:
  448. /* Password reading and authorization takes place here.
  449. * Note that reads (in no-echo mode) trash tty attributes.
  450. * If we get interrupted by SIGALRM, we need to restore attrs.
  451. */
  452. if (ask_and_check_password(pw) > 0)
  453. break;
  454. #endif /* ENABLE_PAM */
  455. auth_failed:
  456. opt &= ~LOGIN_OPT_f;
  457. bb_do_delay(LOGIN_FAIL_DELAY);
  458. /* TODO: doesn't sound like correct English phrase to me */
  459. puts("Login incorrect");
  460. if (++count == 3) {
  461. syslog(LOG_WARNING, "invalid password for '%s'%s",
  462. username, fromhost);
  463. if (ENABLE_FEATURE_CLEAN_UP)
  464. free(fromhost);
  465. return EXIT_FAILURE;
  466. }
  467. username[0] = '\0';
  468. } /* while (1) */
  469. alarm(0);
  470. /* We can ignore /etc/nologin if we are logging in as root,
  471. * it doesn't matter whether we are run by root or not */
  472. if (pw->pw_uid != 0)
  473. die_if_nologin();
  474. #if ENABLE_LOGIN_SESSION_AS_CHILD
  475. child_pid = vfork();
  476. if (child_pid != 0) {
  477. if (child_pid < 0)
  478. bb_perror_msg("vfork");
  479. else {
  480. wait_for_exitstatus(child_pid);
  481. update_utmp_DEAD_PROCESS(child_pid);
  482. }
  483. IF_PAM(login_pam_end(pamh);)
  484. return 0;
  485. }
  486. #endif
  487. IF_SELINUX(initselinux(username, full_tty, &user_sid);)
  488. /* Try these, but don't complain if they fail.
  489. * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
  490. fchown(0, pw->pw_uid, pw->pw_gid);
  491. fchmod(0, 0600);
  492. update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
  493. /* We trust environment only if we run by root */
  494. if (ENABLE_LOGIN_SCRIPTS && run_by_root)
  495. run_login_script(pw, full_tty);
  496. change_identity(pw);
  497. setup_environment(pw->pw_shell,
  498. (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
  499. pw);
  500. #if ENABLE_PAM
  501. /* Modules such as pam_env will setup the PAM environment,
  502. * which should be copied into the new environment. */
  503. pamenv = pam_getenvlist(pamh);
  504. if (pamenv) while (*pamenv) {
  505. putenv(*pamenv);
  506. pamenv++;
  507. }
  508. #endif
  509. if (access(".hushlogin", F_OK) != 0)
  510. motd();
  511. if (pw->pw_uid == 0)
  512. syslog(LOG_INFO, "root login%s", fromhost);
  513. if (ENABLE_FEATURE_CLEAN_UP)
  514. free(fromhost);
  515. /* well, a simple setexeccon() here would do the job as well,
  516. * but let's play the game for now */
  517. IF_SELINUX(set_current_security_context(user_sid);)
  518. // util-linux login also does:
  519. // /* start new session */
  520. // setsid();
  521. // /* TIOCSCTTY: steal tty from other process group */
  522. // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
  523. // BBox login used to do this (see above):
  524. // bb_setpgrp();
  525. // If this stuff is really needed, add it and explain why!
  526. /* Set signals to defaults */
  527. /* Non-ignored signals revert to SIG_DFL on exec anyway */
  528. /*signal(SIGALRM, SIG_DFL);*/
  529. /* Is this correct? This way user can ctrl-c out of /etc/profile,
  530. * potentially creating security breach (tested with bash 3.0).
  531. * But without this, bash 3.0 will not enable ctrl-c either.
  532. * Maybe bash is buggy?
  533. * Need to find out what standards say about /bin/login -
  534. * should we leave SIGINT etc enabled or disabled? */
  535. signal(SIGINT, SIG_DFL);
  536. /* Exec login shell with no additional parameters */
  537. run_shell(pw->pw_shell, 1, NULL);
  538. /* return EXIT_FAILURE; - not reached */
  539. }