3
0

login.c 14 KB

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