source: branches/3.2/mindi-busybox/loginutils/login.c @ 3232

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