[BACK]Return to auth.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/auth.c, Revision 1.126

1.126   ! djm         1: /* $OpenBSD: auth.c,v 1.125 2018/01/08 15:21:49 markus Exp $ */
1.1       markus      2: /*
1.19      deraadt     3:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
1.9       deraadt     4:  *
                      5:  * Redistribution and use in source and binary forms, with or without
                      6:  * modification, are permitted provided that the following conditions
                      7:  * are met:
                      8:  * 1. Redistributions of source code must retain the above copyright
                      9:  *    notice, this list of conditions and the following disclaimer.
                     10:  * 2. Redistributions in binary form must reproduce the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer in the
                     12:  *    documentation and/or other materials provided with the distribution.
                     13:  *
                     14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     15:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     16:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     17:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     18:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     19:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     20:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     21:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     22:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     23:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.1       markus     24:  */
                     25:
1.62      stevesk    26: #include <sys/types.h>
                     27: #include <sys/stat.h>
1.114     djm        28: #include <sys/socket.h>
1.125     markus     29: #include <sys/wait.h>
1.22      markus     30:
1.70      stevesk    31: #include <errno.h>
1.79      dtucker    32: #include <fcntl.h>
1.77      djm        33: #include <login_cap.h>
1.61      stevesk    34: #include <paths.h>
1.68      stevesk    35: #include <pwd.h>
1.69      stevesk    36: #include <stdarg.h>
1.74      stevesk    37: #include <stdio.h>
1.72      stevesk    38: #include <string.h>
1.80      djm        39: #include <unistd.h>
1.109     deraadt    40: #include <limits.h>
1.114     djm        41: #include <netdb.h>
1.1       markus     42:
                     43: #include "xmalloc.h"
1.13      markus     44: #include "match.h"
1.14      markus     45: #include "groupaccess.h"
                     46: #include "log.h"
1.75      deraadt    47: #include "buffer.h"
1.106     millert    48: #include "misc.h"
1.1       markus     49: #include "servconf.h"
1.75      deraadt    50: #include "key.h"
                     51: #include "hostfile.h"
1.2       markus     52: #include "auth.h"
1.13      markus     53: #include "auth-options.h"
1.14      markus     54: #include "canohost.h"
1.24      markus     55: #include "uidswap.h"
1.42      markus     56: #include "packet.h"
1.75      deraadt    57: #ifdef GSSAPI
                     58: #include "ssh-gss.h"
                     59: #endif
1.85      djm        60: #include "authfile.h"
1.67      dtucker    61: #include "monitor_wrap.h"
1.107     djm        62: #include "authfile.h"
                     63: #include "ssherr.h"
1.103     djm        64: #include "compat.h"
1.126   ! djm        65: #include "channels.h"
1.2       markus     66:
1.1       markus     67: /* import */
                     68: extern ServerOptions options;
1.67      dtucker    69: extern int use_privsep;
1.126   ! djm        70: extern struct sshauthopt *auth_opts;
1.1       markus     71:
1.42      markus     72: /* Debugging messages */
                     73: Buffer auth_debug;
                     74: int auth_debug_init;
                     75:
1.1       markus     76: /*
1.12      markus     77:  * Check if the user is allowed to log in via ssh. If user is listed
                     78:  * in DenyUsers or one of user's groups is listed in DenyGroups, false
                     79:  * will be returned. If AllowUsers isn't empty and user isn't listed
                     80:  * there, or if AllowGroups isn't empty and one of user's groups isn't
                     81:  * listed there, false will be returned.
1.1       markus     82:  * If the user's shell is not executable, false will be returned.
1.4       markus     83:  * Otherwise true is returned.
1.1       markus     84:  */
1.5       markus     85: int
1.1       markus     86: allowed_user(struct passwd * pw)
                     87: {
1.114     djm        88:        struct ssh *ssh = active_state; /* XXX */
1.1       markus     89:        struct stat st;
1.35      markus     90:        const char *hostname = NULL, *ipaddr = NULL;
1.117     djm        91:        int r;
1.60      djm        92:        u_int i;
1.1       markus     93:
                     94:        /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1.12      markus     95:        if (!pw || !pw->pw_name)
1.1       markus     96:                return 0;
                     97:
1.7       deraadt    98:        /*
1.84      djm        99:         * Deny if shell does not exist or is not executable unless we
                    100:         * are chrooting.
1.7       deraadt   101:         */
1.84      djm       102:        if (options.chroot_directory == NULL ||
                    103:            strcasecmp(options.chroot_directory, "none") == 0) {
                    104:                char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
                    105:                    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
                    106:
                    107:                if (stat(shell, &st) != 0) {
                    108:                        logit("User %.100s not allowed because shell %.100s "
                    109:                            "does not exist", pw->pw_name, shell);
1.102     djm       110:                        free(shell);
1.84      djm       111:                        return 0;
                    112:                }
                    113:                if (S_ISREG(st.st_mode) == 0 ||
                    114:                    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
                    115:                        logit("User %.100s not allowed because shell %.100s "
                    116:                            "is not executable", pw->pw_name, shell);
1.102     djm       117:                        free(shell);
1.84      djm       118:                        return 0;
                    119:                }
1.102     djm       120:                free(shell);
1.34      stevesk   121:        }
1.1       markus    122:
1.58      dtucker   123:        if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
                    124:            options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1.114     djm       125:                hostname = auth_get_canonical_hostname(ssh, options.use_dns);
                    126:                ipaddr = ssh_remote_ipaddr(ssh);
1.35      markus    127:        }
                    128:
1.1       markus    129:        /* Return false if user is listed in DenyUsers */
                    130:        if (options.num_deny_users > 0) {
1.119     dtucker   131:                for (i = 0; i < options.num_deny_users; i++) {
1.117     djm       132:                        r = match_user(pw->pw_name, hostname, ipaddr,
                    133:                            options.deny_users[i]);
                    134:                        if (r < 0) {
                    135:                                fatal("Invalid DenyUsers pattern \"%.100s\"",
                    136:                                    options.deny_users[i]);
1.118     djm       137:                        } else if (r != 0) {
1.57      dtucker   138:                                logit("User %.100s from %.100s not allowed "
                    139:                                    "because listed in DenyUsers",
                    140:                                    pw->pw_name, hostname);
1.1       markus    141:                                return 0;
1.34      stevesk   142:                        }
1.119     dtucker   143:                }
1.1       markus    144:        }
                    145:        /* Return false if AllowUsers isn't empty and user isn't listed there */
                    146:        if (options.num_allow_users > 0) {
1.117     djm       147:                for (i = 0; i < options.num_allow_users; i++) {
                    148:                        r = match_user(pw->pw_name, hostname, ipaddr,
                    149:                            options.allow_users[i]);
                    150:                        if (r < 0) {
                    151:                                fatal("Invalid AllowUsers pattern \"%.100s\"",
                    152:                                    options.allow_users[i]);
                    153:                        } else if (r == 1)
1.1       markus    154:                                break;
1.117     djm       155:                }
1.1       markus    156:                /* i < options.num_allow_users iff we break for loop */
1.34      stevesk   157:                if (i >= options.num_allow_users) {
1.57      dtucker   158:                        logit("User %.100s from %.100s not allowed because "
                    159:                            "not listed in AllowUsers", pw->pw_name, hostname);
1.1       markus    160:                        return 0;
1.34      stevesk   161:                }
1.1       markus    162:        }
                    163:        if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1.12      markus    164:                /* Get the user's group access list (primary and supplementary) */
1.34      stevesk   165:                if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
1.57      dtucker   166:                        logit("User %.100s from %.100s not allowed because "
                    167:                            "not in any group", pw->pw_name, hostname);
1.1       markus    168:                        return 0;
1.34      stevesk   169:                }
1.1       markus    170:
1.12      markus    171:                /* Return false if one of user's groups is listed in DenyGroups */
                    172:                if (options.num_deny_groups > 0)
                    173:                        if (ga_match(options.deny_groups,
                    174:                            options.num_deny_groups)) {
                    175:                                ga_free();
1.57      dtucker   176:                                logit("User %.100s from %.100s not allowed "
                    177:                                    "because a group is listed in DenyGroups",
                    178:                                    pw->pw_name, hostname);
1.1       markus    179:                                return 0;
1.12      markus    180:                        }
1.1       markus    181:                /*
1.12      markus    182:                 * Return false if AllowGroups isn't empty and one of user's groups
1.1       markus    183:                 * isn't listed there
                    184:                 */
1.12      markus    185:                if (options.num_allow_groups > 0)
                    186:                        if (!ga_match(options.allow_groups,
                    187:                            options.num_allow_groups)) {
                    188:                                ga_free();
1.57      dtucker   189:                                logit("User %.100s from %.100s not allowed "
                    190:                                    "because none of user's groups are listed "
                    191:                                    "in AllowGroups", pw->pw_name, hostname);
1.1       markus    192:                                return 0;
1.12      markus    193:                        }
                    194:                ga_free();
1.1       markus    195:        }
                    196:        /* We found no reason not to let this user try to log on... */
                    197:        return 1;
1.13      markus    198: }
                    199:
1.122     djm       200: /*
                    201:  * Formats any key left in authctxt->auth_method_key for inclusion in
                    202:  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
                    203:  */
                    204: static char *
                    205: format_method_key(Authctxt *authctxt)
1.103     djm       206: {
1.122     djm       207:        const struct sshkey *key = authctxt->auth_method_key;
                    208:        const char *methinfo = authctxt->auth_method_info;
                    209:        char *fp, *ret = NULL;
                    210:
                    211:        if (key == NULL)
                    212:                return NULL;
                    213:
                    214:        if (key_is_cert(key)) {
                    215:                fp = sshkey_fingerprint(key->cert->signature_key,
                    216:                    options.fingerprint_hash, SSH_FP_DEFAULT);
                    217:                xasprintf(&ret, "%s ID %s (serial %llu) CA %s %s%s%s",
                    218:                    sshkey_type(key), key->cert->key_id,
                    219:                    (unsigned long long)key->cert->serial,
                    220:                    sshkey_type(key->cert->signature_key),
                    221:                    fp == NULL ? "(null)" : fp,
                    222:                    methinfo == NULL ? "" : ", ",
                    223:                    methinfo == NULL ? "" : methinfo);
                    224:                free(fp);
                    225:        } else {
                    226:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                    227:                    SSH_FP_DEFAULT);
                    228:                xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
                    229:                    fp == NULL ? "(null)" : fp,
                    230:                    methinfo == NULL ? "" : ", ",
                    231:                    methinfo == NULL ? "" : methinfo);
                    232:                free(fp);
                    233:        }
                    234:        return ret;
1.103     djm       235: }
                    236:
                    237: void
1.98      djm       238: auth_log(Authctxt *authctxt, int authenticated, int partial,
1.103     djm       239:     const char *method, const char *submethod)
1.13      markus    240: {
1.114     djm       241:        struct ssh *ssh = active_state; /* XXX */
1.13      markus    242:        void (*authlog) (const char *fmt,...) = verbose;
1.122     djm       243:        const char *authmsg;
                    244:        char *extra = NULL;
1.67      dtucker   245:
                    246:        if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
                    247:                return;
1.13      markus    248:
                    249:        /* Raise logging level */
                    250:        if (authenticated == 1 ||
                    251:            !authctxt->valid ||
1.54      dtucker   252:            authctxt->failures >= options.max_authtries / 2 ||
1.13      markus    253:            strcmp(method, "password") == 0)
1.47      itojun    254:                authlog = logit;
1.13      markus    255:
                    256:        if (authctxt->postponed)
                    257:                authmsg = "Postponed";
1.98      djm       258:        else if (partial)
                    259:                authmsg = "Partial";
1.13      markus    260:        else
                    261:                authmsg = authenticated ? "Accepted" : "Failed";
                    262:
1.122     djm       263:        if ((extra = format_method_key(authctxt)) == NULL) {
                    264:                if (authctxt->auth_method_info != NULL)
                    265:                        extra = xstrdup(authctxt->auth_method_info);
                    266:        }
                    267:
1.116     markus    268:        authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
1.13      markus    269:            authmsg,
                    270:            method,
1.98      djm       271:            submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
1.56      markus    272:            authctxt->valid ? "" : "invalid user ",
1.29      markus    273:            authctxt->user,
1.114     djm       274:            ssh_remote_ipaddr(ssh),
                    275:            ssh_remote_port(ssh),
1.122     djm       276:            extra != NULL ? ": " : "",
                    277:            extra != NULL ? extra : "");
                    278:
                    279:        free(extra);
1.105     djm       280: }
                    281:
                    282: void
                    283: auth_maxtries_exceeded(Authctxt *authctxt)
                    284: {
1.114     djm       285:        struct ssh *ssh = active_state; /* XXX */
                    286:
1.110     djm       287:        error("maximum authentication attempts exceeded for "
1.116     markus    288:            "%s%.100s from %.200s port %d ssh2",
1.105     djm       289:            authctxt->valid ? "" : "invalid user ",
                    290:            authctxt->user,
1.114     djm       291:            ssh_remote_ipaddr(ssh),
1.116     markus    292:            ssh_remote_port(ssh));
1.110     djm       293:        packet_disconnect("Too many authentication failures");
1.105     djm       294:        /* NOTREACHED */
1.13      markus    295: }
                    296:
                    297: /*
1.17      markus    298:  * Check whether root logins are disallowed.
1.13      markus    299:  */
                    300: int
1.126   ! djm       301: auth_root_allowed(struct ssh *ssh, const char *method)
1.13      markus    302: {
1.17      markus    303:        switch (options.permit_root_login) {
                    304:        case PERMIT_YES:
1.13      markus    305:                return 1;
1.17      markus    306:        case PERMIT_NO_PASSWD:
1.112     deraadt   307:                if (strcmp(method, "publickey") == 0 ||
                    308:                    strcmp(method, "hostbased") == 0 ||
1.113     djm       309:                    strcmp(method, "gssapi-with-mic") == 0)
1.17      markus    310:                        return 1;
                    311:                break;
                    312:        case PERMIT_FORCED_ONLY:
1.126   ! djm       313:                if (auth_opts->force_command != NULL) {
1.47      itojun    314:                        logit("Root login accepted for forced command.");
1.17      markus    315:                        return 1;
                    316:                }
                    317:                break;
1.13      markus    318:        }
1.114     djm       319:        logit("ROOT LOGIN REFUSED FROM %.200s port %d",
                    320:            ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.22      markus    321:        return 0;
                    322: }
                    323:
                    324:
                    325: /*
                    326:  * Given a template and a passwd structure, build a filename
                    327:  * by substituting % tokenised options. Currently, %% becomes '%',
                    328:  * %h becomes the home directory and %u the username.
                    329:  *
                    330:  * This returns a buffer allocated by xmalloc.
                    331:  */
1.93      djm       332: char *
1.59      djm       333: expand_authorized_keys(const char *filename, struct passwd *pw)
1.22      markus    334: {
1.109     deraadt   335:        char *file, ret[PATH_MAX];
1.65      djm       336:        int i;
1.22      markus    337:
1.59      djm       338:        file = percent_expand(filename, "h", pw->pw_dir,
                    339:            "u", pw->pw_name, (char *)NULL);
1.22      markus    340:
                    341:        /*
                    342:         * Ensure that filename starts anchored. If not, be backward
                    343:         * compatible and prepend the '%h/'
                    344:         */
1.59      djm       345:        if (*file == '/')
                    346:                return (file);
                    347:
1.65      djm       348:        i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
                    349:        if (i < 0 || (size_t)i >= sizeof(ret))
1.59      djm       350:                fatal("expand_authorized_keys: path too long");
1.102     djm       351:        free(file);
1.65      djm       352:        return (xstrdup(ret));
1.22      markus    353: }
1.24      markus    354:
1.87      djm       355: char *
                    356: authorized_principals_file(struct passwd *pw)
                    357: {
1.111     djm       358:        if (options.authorized_principals_file == NULL)
1.87      djm       359:                return NULL;
                    360:        return expand_authorized_keys(options.authorized_principals_file, pw);
                    361: }
                    362:
1.24      markus    363: /* return ok if key exists in sysfile or userfile */
                    364: HostStatus
1.121     markus    365: check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
1.24      markus    366:     const char *sysfile, const char *userfile)
                    367: {
                    368:        char *user_hostfile;
                    369:        struct stat st;
1.30      stevesk   370:        HostStatus host_status;
1.91      djm       371:        struct hostkeys *hostkeys;
                    372:        const struct hostkey_entry *found;
1.24      markus    373:
1.91      djm       374:        hostkeys = init_hostkeys();
                    375:        load_hostkeys(hostkeys, host, sysfile);
                    376:        if (userfile != NULL) {
1.24      markus    377:                user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
                    378:                if (options.strict_modes &&
                    379:                    (stat(user_hostfile, &st) == 0) &&
                    380:                    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
1.31      deraadt   381:                    (st.st_mode & 022) != 0)) {
1.47      itojun    382:                        logit("Authentication refused for %.100s: "
1.24      markus    383:                            "bad owner or modes for %.200s",
                    384:                            pw->pw_name, user_hostfile);
1.88      djm       385:                        auth_debug_add("Ignored %.200s: bad ownership or modes",
                    386:                            user_hostfile);
1.24      markus    387:                } else {
                    388:                        temporarily_use_uid(pw);
1.91      djm       389:                        load_hostkeys(hostkeys, host, user_hostfile);
1.24      markus    390:                        restore_uid();
                    391:                }
1.102     djm       392:                free(user_hostfile);
1.24      markus    393:        }
1.91      djm       394:        host_status = check_key_in_hostkeys(hostkeys, key, &found);
                    395:        if (host_status == HOST_REVOKED)
                    396:                error("WARNING: revoked key for %s attempted authentication",
                    397:                    found->host);
                    398:        else if (host_status == HOST_OK)
                    399:                debug("%s: key for %s found at %s:%ld", __func__,
                    400:                    found->host, found->file, found->line);
                    401:        else
                    402:                debug("%s: key for host %s not found", __func__, host);
                    403:
                    404:        free_hostkeys(hostkeys);
1.24      markus    405:
                    406:        return host_status;
                    407: }
                    408:
1.87      djm       409: static FILE *
                    410: auth_openfile(const char *file, struct passwd *pw, int strict_modes,
                    411:     int log_missing, char *file_type)
1.79      dtucker   412: {
                    413:        char line[1024];
                    414:        struct stat st;
                    415:        int fd;
                    416:        FILE *f;
                    417:
1.81      dtucker   418:        if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
1.87      djm       419:                if (log_missing || errno != ENOENT)
                    420:                        debug("Could not open %s '%s': %s", file_type, file,
1.81      dtucker   421:                           strerror(errno));
1.79      dtucker   422:                return NULL;
1.81      dtucker   423:        }
1.79      dtucker   424:
                    425:        if (fstat(fd, &st) < 0) {
                    426:                close(fd);
                    427:                return NULL;
                    428:        }
                    429:        if (!S_ISREG(st.st_mode)) {
1.87      djm       430:                logit("User %s %s %s is not a regular file",
                    431:                    pw->pw_name, file_type, file);
1.79      dtucker   432:                close(fd);
                    433:                return NULL;
                    434:        }
                    435:        unset_nonblock(fd);
                    436:        if ((f = fdopen(fd, "r")) == NULL) {
                    437:                close(fd);
                    438:                return NULL;
                    439:        }
1.90      djm       440:        if (strict_modes &&
1.123     djm       441:            safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
1.79      dtucker   442:                fclose(f);
                    443:                logit("Authentication refused: %s", line);
1.88      djm       444:                auth_debug_add("Ignored %s: %s", file_type, line);
1.79      dtucker   445:                return NULL;
                    446:        }
                    447:
                    448:        return f;
1.87      djm       449: }
                    450:
                    451:
                    452: FILE *
                    453: auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
                    454: {
                    455:        return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
                    456: }
                    457:
                    458: FILE *
                    459: auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
                    460: {
                    461:        return auth_openfile(file, pw, strict_modes, 0,
                    462:            "authorized principals");
1.37      provos    463: }
                    464:
                    465: struct passwd *
                    466: getpwnamallow(const char *user)
                    467: {
1.114     djm       468:        struct ssh *ssh = active_state; /* XXX */
1.38      provos    469:        extern login_cap_t *lc;
                    470:        auth_session_t *as;
1.37      provos    471:        struct passwd *pw;
1.96      dtucker   472:        struct connection_info *ci = get_connection_info(1, options.use_dns);
1.71      dtucker   473:
1.96      dtucker   474:        ci->user = user;
                    475:        parse_server_match_config(&options, ci);
1.120     djm       476:        log_change_level(options.log_level);
1.124     djm       477:        process_permitopen(ssh, &options);
1.37      provos    478:
                    479:        pw = getpwnam(user);
1.45      stevesk   480:        if (pw == NULL) {
1.114     djm       481:                logit("Invalid user %.100s from %.100s port %d",
                    482:                    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.45      stevesk   483:                return (NULL);
                    484:        }
                    485:        if (!allowed_user(pw))
1.38      provos    486:                return (NULL);
                    487:        if ((lc = login_getclass(pw->pw_class)) == NULL) {
                    488:                debug("unable to get login class: %s", user);
                    489:                return (NULL);
                    490:        }
                    491:        if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
1.43      millert   492:            auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
1.38      provos    493:                debug("Approval failure for %s", user);
1.37      provos    494:                pw = NULL;
1.38      provos    495:        }
                    496:        if (as != NULL)
                    497:                auth_close(as);
1.41      markus    498:        if (pw != NULL)
                    499:                return (pwcopy(pw));
                    500:        return (NULL);
1.85      djm       501: }
                    502:
                    503: /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
                    504: int
1.121     markus    505: auth_key_is_revoked(struct sshkey *key)
1.85      djm       506: {
1.107     djm       507:        char *fp = NULL;
                    508:        int r;
1.85      djm       509:
                    510:        if (options.revoked_keys_file == NULL)
                    511:                return 0;
1.108     djm       512:        if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
                    513:            SSH_FP_DEFAULT)) == NULL) {
1.107     djm       514:                r = SSH_ERR_ALLOC_FAIL;
                    515:                error("%s: fingerprint key: %s", __func__, ssh_err(r));
                    516:                goto out;
                    517:        }
                    518:
                    519:        r = sshkey_check_revoked(key, options.revoked_keys_file);
                    520:        switch (r) {
1.100     djm       521:        case 0:
1.107     djm       522:                break; /* not revoked */
                    523:        case SSH_ERR_KEY_REVOKED:
                    524:                error("Authentication key %s %s revoked by file %s",
                    525:                    sshkey_type(key), fp, options.revoked_keys_file);
                    526:                goto out;
1.100     djm       527:        default:
1.107     djm       528:                error("Error checking authentication key %s %s in "
                    529:                    "revoked keys file %s: %s", sshkey_type(key), fp,
                    530:                    options.revoked_keys_file, ssh_err(r));
                    531:                goto out;
1.100     djm       532:        }
1.107     djm       533:
                    534:        /* Success */
                    535:        r = 0;
                    536:
                    537:  out:
                    538:        free(fp);
                    539:        return r == 0 ? 0 : 1;
1.42      markus    540: }
                    541:
                    542: void
                    543: auth_debug_add(const char *fmt,...)
                    544: {
                    545:        char buf[1024];
                    546:        va_list args;
                    547:
                    548:        if (!auth_debug_init)
                    549:                return;
                    550:
                    551:        va_start(args, fmt);
                    552:        vsnprintf(buf, sizeof(buf), fmt, args);
                    553:        va_end(args);
                    554:        buffer_put_cstring(&auth_debug, buf);
                    555: }
                    556:
                    557: void
                    558: auth_debug_send(void)
                    559: {
                    560:        char *msg;
                    561:
                    562:        if (!auth_debug_init)
                    563:                return;
                    564:        while (buffer_len(&auth_debug)) {
                    565:                msg = buffer_get_string(&auth_debug, NULL);
                    566:                packet_send_debug("%s", msg);
1.102     djm       567:                free(msg);
1.42      markus    568:        }
                    569: }
                    570:
                    571: void
                    572: auth_debug_reset(void)
                    573: {
                    574:        if (auth_debug_init)
                    575:                buffer_clear(&auth_debug);
                    576:        else {
                    577:                buffer_init(&auth_debug);
                    578:                auth_debug_init = 1;
                    579:        }
1.49      markus    580: }
                    581:
                    582: struct passwd *
                    583: fakepw(void)
                    584: {
                    585:        static struct passwd fake;
                    586:
                    587:        memset(&fake, 0, sizeof(fake));
                    588:        fake.pw_name = "NOUSER";
                    589:        fake.pw_passwd =
1.51      djm       590:            "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
1.49      markus    591:        fake.pw_gecos = "NOUSER";
1.53      deraadt   592:        fake.pw_uid = (uid_t)-1;
                    593:        fake.pw_gid = (gid_t)-1;
1.49      markus    594:        fake.pw_class = "";
                    595:        fake.pw_dir = "/nonexist";
                    596:        fake.pw_shell = "/nonexist";
                    597:
                    598:        return (&fake);
1.114     djm       599: }
                    600:
                    601: /*
                    602:  * Returns the remote DNS hostname as a string. The returned string must not
                    603:  * be freed. NB. this will usually trigger a DNS query the first time it is
                    604:  * called.
                    605:  * This function does additional checks on the hostname to mitigate some
                    606:  * attacks on legacy rhosts-style authentication.
                    607:  * XXX is RhostsRSAAuthentication vulnerable to these?
                    608:  * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
                    609:  */
                    610:
                    611: static char *
                    612: remote_hostname(struct ssh *ssh)
                    613: {
                    614:        struct sockaddr_storage from;
                    615:        socklen_t fromlen;
                    616:        struct addrinfo hints, *ai, *aitop;
                    617:        char name[NI_MAXHOST], ntop2[NI_MAXHOST];
                    618:        const char *ntop = ssh_remote_ipaddr(ssh);
                    619:
                    620:        /* Get IP address of client. */
                    621:        fromlen = sizeof(from);
                    622:        memset(&from, 0, sizeof(from));
                    623:        if (getpeername(ssh_packet_get_connection_in(ssh),
                    624:            (struct sockaddr *)&from, &fromlen) < 0) {
                    625:                debug("getpeername failed: %.100s", strerror(errno));
                    626:                return strdup(ntop);
                    627:        }
                    628:
                    629:        debug3("Trying to reverse map address %.100s.", ntop);
                    630:        /* Map the IP address to a host name. */
                    631:        if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
                    632:            NULL, 0, NI_NAMEREQD) != 0) {
                    633:                /* Host name not found.  Use ip address. */
                    634:                return strdup(ntop);
                    635:        }
                    636:
                    637:        /*
                    638:         * if reverse lookup result looks like a numeric hostname,
                    639:         * someone is trying to trick us by PTR record like following:
                    640:         *      1.1.1.10.in-addr.arpa.  IN PTR  2.3.4.5
                    641:         */
                    642:        memset(&hints, 0, sizeof(hints));
                    643:        hints.ai_socktype = SOCK_DGRAM; /*dummy*/
                    644:        hints.ai_flags = AI_NUMERICHOST;
                    645:        if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
                    646:                logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
                    647:                    name, ntop);
                    648:                freeaddrinfo(ai);
                    649:                return strdup(ntop);
                    650:        }
                    651:
                    652:        /* Names are stored in lowercase. */
                    653:        lowercase(name);
                    654:
                    655:        /*
                    656:         * Map it back to an IP address and check that the given
                    657:         * address actually is an address of this host.  This is
                    658:         * necessary because anyone with access to a name server can
                    659:         * define arbitrary names for an IP address. Mapping from
                    660:         * name to IP address can be trusted better (but can still be
                    661:         * fooled if the intruder has access to the name server of
                    662:         * the domain).
                    663:         */
                    664:        memset(&hints, 0, sizeof(hints));
                    665:        hints.ai_family = from.ss_family;
                    666:        hints.ai_socktype = SOCK_STREAM;
                    667:        if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
                    668:                logit("reverse mapping checking getaddrinfo for %.700s "
1.115     dtucker   669:                    "[%s] failed.", name, ntop);
1.114     djm       670:                return strdup(ntop);
                    671:        }
                    672:        /* Look for the address from the list of addresses. */
                    673:        for (ai = aitop; ai; ai = ai->ai_next) {
                    674:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
                    675:                    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
                    676:                    (strcmp(ntop, ntop2) == 0))
                    677:                                break;
                    678:        }
                    679:        freeaddrinfo(aitop);
                    680:        /* If we reached the end of the list, the address was not there. */
                    681:        if (ai == NULL) {
                    682:                /* Address not found for the host name. */
                    683:                logit("Address %.100s maps to %.600s, but this does not "
1.115     dtucker   684:                    "map back to the address.", ntop, name);
1.114     djm       685:                return strdup(ntop);
                    686:        }
                    687:        return strdup(name);
                    688: }
                    689:
                    690: /*
                    691:  * Return the canonical name of the host in the other side of the current
                    692:  * connection.  The host name is cached, so it is efficient to call this
                    693:  * several times.
                    694:  */
                    695:
                    696: const char *
                    697: auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
                    698: {
                    699:        static char *dnsname;
                    700:
                    701:        if (!use_dns)
                    702:                return ssh_remote_ipaddr(ssh);
                    703:        else if (dnsname != NULL)
                    704:                return dnsname;
                    705:        else {
                    706:                dnsname = remote_hostname(ssh);
                    707:                return dnsname;
                    708:        }
1.125     markus    709: }
                    710:
                    711: /*
                    712:  * Runs command in a subprocess wuth a minimal environment.
                    713:  * Returns pid on success, 0 on failure.
                    714:  * The child stdout and stderr maybe captured, left attached or sent to
                    715:  * /dev/null depending on the contents of flags.
                    716:  * "tag" is prepended to log messages.
                    717:  * NB. "command" is only used for logging; the actual command executed is
                    718:  * av[0].
                    719:  */
                    720: pid_t
                    721: subprocess(const char *tag, struct passwd *pw, const char *command,
                    722:     int ac, char **av, FILE **child, u_int flags)
                    723: {
                    724:        FILE *f = NULL;
                    725:        struct stat st;
                    726:        int fd, devnull, p[2], i;
                    727:        pid_t pid;
                    728:        char *cp, errmsg[512];
                    729:        u_int envsize;
                    730:        char **child_env;
                    731:
                    732:        if (child != NULL)
                    733:                *child = NULL;
                    734:
                    735:        debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
                    736:            tag, command, pw->pw_name, flags);
                    737:
                    738:        /* Check consistency */
                    739:        if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
                    740:            (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
                    741:                error("%s: inconsistent flags", __func__);
                    742:                return 0;
                    743:        }
                    744:        if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
                    745:                error("%s: inconsistent flags/output", __func__);
                    746:                return 0;
                    747:        }
                    748:
                    749:        /*
                    750:         * If executing an explicit binary, then verify the it exists
                    751:         * and appears safe-ish to execute
                    752:         */
                    753:        if (*av[0] != '/') {
                    754:                error("%s path is not absolute", tag);
                    755:                return 0;
                    756:        }
                    757:        temporarily_use_uid(pw);
                    758:        if (stat(av[0], &st) < 0) {
                    759:                error("Could not stat %s \"%s\": %s", tag,
                    760:                    av[0], strerror(errno));
                    761:                restore_uid();
                    762:                return 0;
                    763:        }
                    764:        if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
                    765:                error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
                    766:                restore_uid();
                    767:                return 0;
                    768:        }
                    769:        /* Prepare to keep the child's stdout if requested */
                    770:        if (pipe(p) != 0) {
                    771:                error("%s: pipe: %s", tag, strerror(errno));
                    772:                restore_uid();
                    773:                return 0;
                    774:        }
                    775:        restore_uid();
                    776:
                    777:        switch ((pid = fork())) {
                    778:        case -1: /* error */
                    779:                error("%s: fork: %s", tag, strerror(errno));
                    780:                close(p[0]);
                    781:                close(p[1]);
                    782:                return 0;
                    783:        case 0: /* child */
                    784:                /* Prepare a minimal environment for the child. */
                    785:                envsize = 5;
                    786:                child_env = xcalloc(sizeof(*child_env), envsize);
                    787:                child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
                    788:                child_set_env(&child_env, &envsize, "USER", pw->pw_name);
                    789:                child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
                    790:                child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
                    791:                if ((cp = getenv("LANG")) != NULL)
                    792:                        child_set_env(&child_env, &envsize, "LANG", cp);
                    793:
                    794:                for (i = 0; i < NSIG; i++)
                    795:                        signal(i, SIG_DFL);
                    796:
                    797:                if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
                    798:                        error("%s: open %s: %s", tag, _PATH_DEVNULL,
                    799:                            strerror(errno));
                    800:                        _exit(1);
                    801:                }
                    802:                if (dup2(devnull, STDIN_FILENO) == -1) {
                    803:                        error("%s: dup2: %s", tag, strerror(errno));
                    804:                        _exit(1);
                    805:                }
                    806:
                    807:                /* Set up stdout as requested; leave stderr in place for now. */
                    808:                fd = -1;
                    809:                if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
                    810:                        fd = p[1];
                    811:                else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
                    812:                        fd = devnull;
                    813:                if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
                    814:                        error("%s: dup2: %s", tag, strerror(errno));
                    815:                        _exit(1);
                    816:                }
                    817:                closefrom(STDERR_FILENO + 1);
                    818:
                    819:                /* Don't use permanently_set_uid() here to avoid fatal() */
                    820:                if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
                    821:                        error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
                    822:                            strerror(errno));
                    823:                        _exit(1);
                    824:                }
                    825:                if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
                    826:                        error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
                    827:                            strerror(errno));
                    828:                        _exit(1);
                    829:                }
                    830:                /* stdin is pointed to /dev/null at this point */
                    831:                if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
                    832:                    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
                    833:                        error("%s: dup2: %s", tag, strerror(errno));
                    834:                        _exit(1);
                    835:                }
                    836:
                    837:                execve(av[0], av, child_env);
                    838:                error("%s exec \"%s\": %s", tag, command, strerror(errno));
                    839:                _exit(127);
                    840:        default: /* parent */
                    841:                break;
                    842:        }
                    843:
                    844:        close(p[1]);
                    845:        if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
                    846:                close(p[0]);
                    847:        else if ((f = fdopen(p[0], "r")) == NULL) {
                    848:                error("%s: fdopen: %s", tag, strerror(errno));
                    849:                close(p[0]);
                    850:                /* Don't leave zombie child */
                    851:                kill(pid, SIGTERM);
                    852:                while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
                    853:                        ;
                    854:                return 0;
                    855:        }
                    856:        /* Success */
                    857:        debug3("%s: %s pid %ld", __func__, tag, (long)pid);
                    858:        if (child != NULL)
                    859:                *child = f;
                    860:        return pid;
1.126   ! djm       861: }
        !           862:
        !           863: /* These functions link key/cert options to the auth framework */
        !           864:
        !           865: /* Log sshauthopt options locally and (optionally) for remote transmission */
        !           866: void
        !           867: auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
        !           868: {
        !           869:        int do_env = options.permit_user_env && opts->nenv > 0;
        !           870:        int do_permitopen = opts->npermitopen > 0 &&
        !           871:            (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
        !           872:        size_t i;
        !           873:        char msg[1024], tbuf[32];
        !           874:
        !           875:        snprintf(tbuf, sizeof(tbuf), "%d", opts->force_tun_device);
        !           876:        /* Try to keep this alphabetically sorted */
        !           877:        snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s",
        !           878:            opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
        !           879:            opts->force_command == NULL ? "" : " command",
        !           880:            do_env ?  " environment" : "",
        !           881:            do_permitopen ?  " permitopen" : "",
        !           882:            opts->permit_port_forwarding_flag ? " port-forwarding" : "",
        !           883:            opts->cert_principals == NULL ? "" : " principals",
        !           884:            opts->permit_pty_flag ? " pty" : "",
        !           885:            opts->force_tun_device == -1 ? "" : " tun=",
        !           886:            opts->force_tun_device == -1 ? "" : tbuf,
        !           887:            opts->permit_user_rc ? " user-rc" : "",
        !           888:            opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
        !           889:
        !           890:        debug("%s: %s", loc, msg);
        !           891:        if (do_remote)
        !           892:                auth_debug_add("%s: %s", loc, msg);
        !           893:
        !           894:        if (options.permit_user_env) {
        !           895:                for (i = 0; i < opts->nenv; i++) {
        !           896:                        debug("%s: environment: %s", loc, opts->env[i]);
        !           897:                        if (do_remote) {
        !           898:                                auth_debug_add("%s: environment: %s",
        !           899:                                    loc, opts->env[i]);
        !           900:                        }
        !           901:                }
        !           902:        }
        !           903:
        !           904:        /* Go into a little more details for the local logs. */
        !           905:        if (opts->cert_principals != NULL) {
        !           906:                debug("%s: authorized principals: \"%s\"",
        !           907:                    loc, opts->cert_principals);
        !           908:        }
        !           909:        if (opts->force_command != NULL)
        !           910:                debug("%s: forced command: \"%s\"", loc, opts->force_command);
        !           911:        if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
        !           912:                for (i = 0; i < opts->npermitopen; i++) {
        !           913:                        debug("%s: permitted open: %s",
        !           914:                            loc, opts->permitopen[i]);
        !           915:                }
        !           916:        }
        !           917: }
        !           918:
        !           919: /* Activate a new set of key/cert options; merging with what is there. */
        !           920: int
        !           921: auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
        !           922: {
        !           923:        struct sshauthopt *old = auth_opts;
        !           924:        const char *emsg = NULL;
        !           925:
        !           926:        debug("%s: setting new authentication options", __func__);
        !           927:        if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
        !           928:                error("Inconsistent authentication options: %s", emsg);
        !           929:                return -1;
        !           930:        }
        !           931:        return 0;
        !           932: }
        !           933:
        !           934: /* Disable forwarding, etc for the session */
        !           935: void
        !           936: auth_restrict_session(struct ssh *ssh)
        !           937: {
        !           938:        struct sshauthopt *restricted;
        !           939:
        !           940:        debug("%s: restricting session", __func__);
        !           941:
        !           942:        /* A blank sshauthopt defaults to permitting nothing */
        !           943:        restricted = sshauthopt_new();
        !           944:        restricted->restricted = 1;
        !           945:
        !           946:        if (auth_activate_options(ssh, restricted) != 0)
        !           947:                fatal("%s: failed to restrict session", __func__);
        !           948:        sshauthopt_free(restricted);
        !           949: }
        !           950:
        !           951: int
        !           952: auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
        !           953:     struct sshauthopt *opts, int allow_cert_authority, const char *loc)
        !           954: {
        !           955:        const char *remote_ip = ssh_remote_ipaddr(ssh);
        !           956:        const char *remote_host = auth_get_canonical_hostname(ssh,
        !           957:            options.use_dns);
        !           958:
        !           959:        /* Consistency checks */
        !           960:        if (opts->cert_principals != NULL && !opts->cert_authority) {
        !           961:                debug("%s: principals on non-CA key", loc);
        !           962:                auth_debug_add("%s: principals on non-CA key", loc);
        !           963:                /* deny access */
        !           964:                return -1;
        !           965:        }
        !           966:        /* cert-authority flag isn't valid in authorized_principals files */
        !           967:        if (!allow_cert_authority && opts->cert_authority) {
        !           968:                debug("%s: cert-authority flag invalid here", loc);
        !           969:                auth_debug_add("%s: cert-authority flag invalid here", loc);
        !           970:                /* deny access */
        !           971:                return -1;
        !           972:        }
        !           973:
        !           974:        /* Perform from= checks */
        !           975:        if (opts->required_from_host_keys != NULL) {
        !           976:                switch (match_host_and_ip(remote_host, remote_ip,
        !           977:                    opts->required_from_host_keys )) {
        !           978:                case 1:
        !           979:                        /* Host name matches. */
        !           980:                        break;
        !           981:                case -1:
        !           982:                default:
        !           983:                        debug("%s: invalid from criteria", loc);
        !           984:                        auth_debug_add("%s: invalid from criteria", loc);
        !           985:                        /* FALLTHROUGH */
        !           986:                case 0:
        !           987:                        logit("%s: Authentication tried for %.100s with "
        !           988:                            "correct key but not from a permitted "
        !           989:                            "host (host=%.200s, ip=%.200s, required=%.200s).",
        !           990:                            loc, pw->pw_name, remote_host, remote_ip,
        !           991:                            opts->required_from_host_keys);
        !           992:                        auth_debug_add("%s: Your host '%.200s' is not "
        !           993:                            "permitted to use this key for login.",
        !           994:                            loc, remote_host);
        !           995:                        /* deny access */
        !           996:                        return -1;
        !           997:                }
        !           998:        }
        !           999:        /* Check source-address restriction from certificate */
        !          1000:        if (opts->required_from_host_cert != NULL) {
        !          1001:                switch (addr_match_cidr_list(remote_ip,
        !          1002:                    opts->required_from_host_cert)) {
        !          1003:                case 1:
        !          1004:                        /* accepted */
        !          1005:                        break;
        !          1006:                case -1:
        !          1007:                default:
        !          1008:                        /* invalid */
        !          1009:                        error("%s: Certificate source-address invalid",
        !          1010:                            loc);
        !          1011:                        /* FALLTHROUGH */
        !          1012:                case 0:
        !          1013:                        logit("%s: Authentication tried for %.100s with valid "
        !          1014:                            "certificate but not from a permitted source "
        !          1015:                            "address (%.200s).", loc, pw->pw_name, remote_ip);
        !          1016:                        auth_debug_add("%s: Your address '%.200s' is not "
        !          1017:                            "permitted to use this certificate for login.",
        !          1018:                            loc, remote_ip);
        !          1019:                        return -1;
        !          1020:                }
        !          1021:        }
        !          1022:        /*
        !          1023:         *
        !          1024:         * XXX this is spammy. We should report remotely only for keys
        !          1025:         *     that are successful in actual auth attempts, and not PK_OK
        !          1026:         *     tests.
        !          1027:         */
        !          1028:        auth_log_authopts(loc, opts, 1);
        !          1029:
        !          1030:        return 0;
1.1       markus   1031: }