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

Annotation of src/usr.bin/ssh/hostfile.c, Revision 1.82

1.82    ! djm         1: /* $OpenBSD: hostfile.c,v 1.81 2020/06/26 05:02:03 dtucker Exp $ */
1.1       deraadt     2: /*
1.8       deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Functions for manipulating the known hosts files.
1.16      markus      7:  *
1.20      deraadt     8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
                     13:  *
                     14:  *
1.28      markus     15:  * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
1.20      deraadt    16:  * Copyright (c) 1999 Niels Provos.  All rights reserved.
                     17:  *
                     18:  * Redistribution and use in source and binary forms, with or without
                     19:  * modification, are permitted provided that the following conditions
                     20:  * are met:
                     21:  * 1. Redistributions of source code must retain the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer.
                     23:  * 2. Redistributions in binary form must reproduce the above copyright
                     24:  *    notice, this list of conditions and the following disclaimer in the
                     25:  *    documentation and/or other materials provided with the distribution.
                     26:  *
                     27:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     28:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     29:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     30:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     31:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     32:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     33:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     34:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     35:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     36:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.8       deraadt    37:  */
1.1       deraadt    38:
1.41      stevesk    39: #include <sys/types.h>
1.62      djm        40: #include <sys/stat.h>
1.41      stevesk    41:
                     42: #include <netinet/in.h>
1.33      djm        43:
1.60      djm        44: #include <errno.h>
1.33      djm        45: #include <resolv.h>
1.44      stevesk    46: #include <stdio.h>
1.43      stevesk    47: #include <stdlib.h>
1.42      stevesk    48: #include <string.h>
1.57      djm        49: #include <stdarg.h>
1.62      djm        50: #include <unistd.h>
1.1       deraadt    51:
1.45      deraadt    52: #include "xmalloc.h"
1.14      markus     53: #include "match.h"
1.59      djm        54: #include "sshkey.h"
1.14      markus     55: #include "hostfile.h"
1.24      markus     56: #include "log.h"
1.49      djm        57: #include "misc.h"
1.81      dtucker    58: #include "pathnames.h"
1.59      djm        59: #include "ssherr.h"
1.53      djm        60: #include "digest.h"
1.54      markus     61: #include "hmac.h"
1.49      djm        62:
                     63: struct hostkeys {
                     64:        struct hostkey_entry *entries;
                     65:        u_int num_entries;
                     66: };
1.33      djm        67:
1.60      djm        68: /* XXX hmac is too easy to dictionary attack; use bcrypt? */
                     69:
1.33      djm        70: static int
1.52      djm        71: extract_salt(const char *s, u_int l, u_char *salt, size_t salt_len)
1.33      djm        72: {
                     73:        char *p, *b64salt;
                     74:        u_int b64len;
                     75:        int ret;
                     76:
                     77:        if (l < sizeof(HASH_MAGIC) - 1) {
                     78:                debug2("extract_salt: string too short");
                     79:                return (-1);
                     80:        }
                     81:        if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) {
                     82:                debug2("extract_salt: invalid magic identifier");
                     83:                return (-1);
                     84:        }
                     85:        s += sizeof(HASH_MAGIC) - 1;
                     86:        l -= sizeof(HASH_MAGIC) - 1;
                     87:        if ((p = memchr(s, HASH_DELIM, l)) == NULL) {
                     88:                debug2("extract_salt: missing salt termination character");
                     89:                return (-1);
                     90:        }
                     91:
                     92:        b64len = p - s;
                     93:        /* Sanity check */
                     94:        if (b64len == 0 || b64len > 1024) {
                     95:                debug2("extract_salt: bad encoded salt length %u", b64len);
                     96:                return (-1);
                     97:        }
                     98:        b64salt = xmalloc(1 + b64len);
                     99:        memcpy(b64salt, s, b64len);
                    100:        b64salt[b64len] = '\0';
                    101:
                    102:        ret = __b64_pton(b64salt, salt, salt_len);
1.51      djm       103:        free(b64salt);
1.33      djm       104:        if (ret == -1) {
                    105:                debug2("extract_salt: salt decode error");
                    106:                return (-1);
                    107:        }
1.54      markus    108:        if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) {
                    109:                debug2("extract_salt: expected salt len %zd, got %d",
                    110:                    ssh_hmac_bytes(SSH_DIGEST_SHA1), ret);
1.33      djm       111:                return (-1);
                    112:        }
1.34      deraadt   113:
1.33      djm       114:        return (0);
                    115: }
                    116:
                    117: char *
                    118: host_hash(const char *host, const char *name_from_hostfile, u_int src_len)
                    119: {
1.54      markus    120:        struct ssh_hmac_ctx *ctx;
1.52      djm       121:        u_char salt[256], result[256];
                    122:        char uu_salt[512], uu_result[512];
1.33      djm       123:        static char encoded[1024];
1.67      tedu      124:        u_int len;
1.33      djm       125:
1.54      markus    126:        len = ssh_digest_bytes(SSH_DIGEST_SHA1);
1.33      djm       127:
                    128:        if (name_from_hostfile == NULL) {
                    129:                /* Create new salt */
1.67      tedu      130:                arc4random_buf(salt, len);
1.33      djm       131:        } else {
                    132:                /* Extract salt from known host entry */
                    133:                if (extract_salt(name_from_hostfile, src_len, salt,
                    134:                    sizeof(salt)) == -1)
                    135:                        return (NULL);
                    136:        }
                    137:
1.54      markus    138:        if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL ||
                    139:            ssh_hmac_init(ctx, salt, len) < 0 ||
                    140:            ssh_hmac_update(ctx, host, strlen(host)) < 0 ||
                    141:            ssh_hmac_final(ctx, result, sizeof(result)))
                    142:                fatal("%s: ssh_hmac failed", __func__);
                    143:        ssh_hmac_free(ctx);
1.33      djm       144:
1.34      deraadt   145:        if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
1.33      djm       146:            __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
1.54      markus    147:                fatal("%s: __b64_ntop failed", __func__);
1.33      djm       148:
                    149:        snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt,
                    150:            HASH_DELIM, uu_result);
                    151:
                    152:        return (encoded);
                    153: }
1.1       deraadt   154:
1.9       markus    155: /*
1.14      markus    156:  * Parses an RSA (number of bits, e, n) or DSA key from a string.  Moves the
                    157:  * pointer over the key.  Skips any whitespace at the beginning and at end.
1.9       markus    158:  */
1.1       deraadt   159:
1.29      jakob     160: int
1.59      djm       161: hostfile_read_key(char **cpp, u_int *bitsp, struct sshkey *ret)
1.1       deraadt   162: {
1.7       markus    163:        char *cp;
                    164:
                    165:        /* Skip leading whitespace. */
1.9       markus    166:        for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
                    167:                ;
1.1       deraadt   168:
1.76      dtucker   169:        if (sshkey_read(ret, &cp) != 0)
1.7       markus    170:                return 0;
                    171:
                    172:        /* Skip trailing whitespace. */
1.9       markus    173:        for (; *cp == ' ' || *cp == '\t'; cp++)
                    174:                ;
1.7       markus    175:
                    176:        /* Return results. */
                    177:        *cpp = cp;
1.59      djm       178:        if (bitsp != NULL)
                    179:                *bitsp = sshkey_size(ret);
1.7       markus    180:        return 1;
1.14      markus    181: }
1.1       deraadt   182:
1.49      djm       183: static HostkeyMarker
1.48      djm       184: check_markers(char **cpp)
                    185: {
                    186:        char marker[32], *sp, *cp = *cpp;
                    187:        int ret = MRK_NONE;
                    188:
                    189:        while (*cp == '@') {
                    190:                /* Only one marker is allowed */
                    191:                if (ret != MRK_NONE)
                    192:                        return MRK_ERROR;
                    193:                /* Markers are terminated by whitespace */
                    194:                if ((sp = strchr(cp, ' ')) == NULL &&
                    195:                    (sp = strchr(cp, '\t')) == NULL)
                    196:                        return MRK_ERROR;
                    197:                /* Extract marker for comparison */
                    198:                if (sp <= cp + 1 || sp >= cp + sizeof(marker))
                    199:                        return MRK_ERROR;
                    200:                memcpy(marker, cp, sp - cp);
                    201:                marker[sp - cp] = '\0';
                    202:                if (strcmp(marker, CA_MARKER) == 0)
                    203:                        ret = MRK_CA;
                    204:                else if (strcmp(marker, REVOKE_MARKER) == 0)
                    205:                        ret = MRK_REVOKE;
                    206:                else
                    207:                        return MRK_ERROR;
                    208:
                    209:                /* Skip past marker and any whitespace that follows it */
                    210:                cp = sp;
                    211:                for (; *cp == ' ' || *cp == '\t'; cp++)
                    212:                        ;
                    213:        }
                    214:        *cpp = cp;
                    215:        return ret;
                    216: }
                    217:
1.49      djm       218: struct hostkeys *
                    219: init_hostkeys(void)
                    220: {
                    221:        struct hostkeys *ret = xcalloc(1, sizeof(*ret));
                    222:
                    223:        ret->entries = NULL;
                    224:        return ret;
                    225: }
1.1       deraadt   226:
1.61      djm       227: struct load_callback_ctx {
                    228:        const char *host;
                    229:        u_long num_loaded;
                    230:        struct hostkeys *hostkeys;
                    231: };
                    232:
                    233: static int
                    234: record_hostkey(struct hostkey_foreach_line *l, void *_ctx)
1.1       deraadt   235: {
1.61      djm       236:        struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx;
                    237:        struct hostkeys *hostkeys = ctx->hostkeys;
                    238:        struct hostkey_entry *tmp;
                    239:
                    240:        if (l->status == HKF_STATUS_INVALID) {
1.65      djm       241:                /* XXX make this verbose() in the future */
                    242:                debug("%s:%ld: parse error in hostkeys file",
1.61      djm       243:                    l->path, l->linenum);
                    244:                return 0;
                    245:        }
1.7       markus    246:
1.61      djm       247:        debug3("%s: found %skey type %s in file %s:%lu", __func__,
                    248:            l->marker == MRK_NONE ? "" :
                    249:            (l->marker == MRK_CA ? "ca " : "revoked "),
                    250:            sshkey_type(l->key), l->path, l->linenum);
1.71      deraadt   251:        if ((tmp = recallocarray(hostkeys->entries, hostkeys->num_entries,
1.61      djm       252:            hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL)
                    253:                return SSH_ERR_ALLOC_FAIL;
                    254:        hostkeys->entries = tmp;
                    255:        hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host);
                    256:        hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path);
                    257:        hostkeys->entries[hostkeys->num_entries].line = l->linenum;
                    258:        hostkeys->entries[hostkeys->num_entries].key = l->key;
                    259:        l->key = NULL; /* steal it */
                    260:        hostkeys->entries[hostkeys->num_entries].marker = l->marker;
                    261:        hostkeys->num_entries++;
                    262:        ctx->num_loaded++;
1.7       markus    263:
1.61      djm       264:        return 0;
                    265: }
1.47      djm       266:
1.61      djm       267: void
                    268: load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
                    269: {
                    270:        int r;
                    271:        struct load_callback_ctx ctx;
1.7       markus    272:
1.61      djm       273:        ctx.host = host;
                    274:        ctx.num_loaded = 0;
                    275:        ctx.hostkeys = hostkeys;
                    276:
1.64      djm       277:        if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host, NULL,
                    278:            HKF_WANT_MATCH|HKF_WANT_PARSE_KEY)) != 0) {
1.61      djm       279:                if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT)
                    280:                        debug("%s: hostkeys_foreach failed for %s: %s",
                    281:                            __func__, path, ssh_err(r));
                    282:        }
                    283:        if (ctx.num_loaded != 0)
                    284:                debug3("%s: loaded %lu keys from %s", __func__,
                    285:                    ctx.num_loaded, host);
1.58      djm       286: }
1.49      djm       287:
                    288: void
                    289: free_hostkeys(struct hostkeys *hostkeys)
                    290: {
                    291:        u_int i;
                    292:
                    293:        for (i = 0; i < hostkeys->num_entries; i++) {
1.51      djm       294:                free(hostkeys->entries[i].host);
                    295:                free(hostkeys->entries[i].file);
1.59      djm       296:                sshkey_free(hostkeys->entries[i].key);
1.55      tedu      297:                explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
1.49      djm       298:        }
1.51      djm       299:        free(hostkeys->entries);
1.78      jsg       300:        freezero(hostkeys, sizeof(*hostkeys));
1.49      djm       301: }
                    302:
                    303: static int
1.59      djm       304: check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
1.49      djm       305: {
1.59      djm       306:        int is_cert = sshkey_is_cert(k);
1.49      djm       307:        u_int i;
1.7       markus    308:
1.49      djm       309:        for (i = 0; i < hostkeys->num_entries; i++) {
                    310:                if (hostkeys->entries[i].marker != MRK_REVOKE)
1.30      markus    311:                        continue;
1.59      djm       312:                if (sshkey_equal_public(k, hostkeys->entries[i].key))
1.49      djm       313:                        return -1;
1.79      markus    314:                if (is_cert && k != NULL &&
1.59      djm       315:                    sshkey_equal_public(k->cert->signature_key,
1.49      djm       316:                    hostkeys->entries[i].key))
                    317:                        return -1;
                    318:        }
                    319:        return 0;
                    320: }
                    321:
                    322: /*
                    323:  * Match keys against a specified key, or look one up by key type.
                    324:  *
                    325:  * If looking for a keytype (key == NULL) and one is found then return
                    326:  * HOST_FOUND, otherwise HOST_NEW.
                    327:  *
                    328:  * If looking for a key (key != NULL):
                    329:  *  1. If the key is a cert and a matching CA is found, return HOST_OK
                    330:  *  2. If the key is not a cert and a matching key is found, return HOST_OK
                    331:  *  3. If no key matches but a key with a different type is found, then
                    332:  *     return HOST_CHANGED
                    333:  *  4. If no matching keys are found, then return HOST_NEW.
                    334:  *
                    335:  * Finally, check any found key is not revoked.
                    336:  */
                    337: static HostStatus
                    338: check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
1.59      djm       339:     struct sshkey *k, int keytype, const struct hostkey_entry **found)
1.49      djm       340: {
                    341:        u_int i;
                    342:        HostStatus end_return = HOST_NEW;
1.59      djm       343:        int want_cert = sshkey_is_cert(k);
1.49      djm       344:        HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
                    345:
                    346:        if (found != NULL)
                    347:                *found = NULL;
1.30      markus    348:
1.49      djm       349:        for (i = 0; i < hostkeys->num_entries; i++) {
                    350:                if (hostkeys->entries[i].marker != want_marker)
                    351:                        continue;
                    352:                if (k == NULL) {
                    353:                        if (hostkeys->entries[i].key->type != keytype)
                    354:                                continue;
                    355:                        end_return = HOST_FOUND;
                    356:                        if (found != NULL)
                    357:                                *found = hostkeys->entries + i;
                    358:                        k = hostkeys->entries[i].key;
                    359:                        break;
                    360:                }
                    361:                if (want_cert) {
1.59      djm       362:                        if (sshkey_equal_public(k->cert->signature_key,
1.49      djm       363:                            hostkeys->entries[i].key)) {
                    364:                                /* A matching CA exists */
                    365:                                end_return = HOST_OK;
                    366:                                if (found != NULL)
                    367:                                        *found = hostkeys->entries + i;
                    368:                                break;
1.48      djm       369:                        }
1.49      djm       370:                } else {
1.59      djm       371:                        if (sshkey_equal(k, hostkeys->entries[i].key)) {
1.49      djm       372:                                end_return = HOST_OK;
                    373:                                if (found != NULL)
                    374:                                        *found = hostkeys->entries + i;
                    375:                                break;
1.48      djm       376:                        }
1.49      djm       377:                        /* A non-maching key exists */
                    378:                        end_return = HOST_CHANGED;
                    379:                        if (found != NULL)
                    380:                                *found = hostkeys->entries + i;
1.48      djm       381:                }
1.1       deraadt   382:        }
1.49      djm       383:        if (check_key_not_revoked(hostkeys, k) != 0) {
                    384:                end_return = HOST_REVOKED;
                    385:                if (found != NULL)
                    386:                        *found = NULL;
                    387:        }
1.7       markus    388:        return end_return;
1.30      markus    389: }
1.58      djm       390:
1.30      markus    391: HostStatus
1.59      djm       392: check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
1.49      djm       393:     const struct hostkey_entry **found)
1.30      markus    394: {
                    395:        if (key == NULL)
                    396:                fatal("no key to look up");
1.49      djm       397:        return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
1.30      markus    398: }
                    399:
                    400: int
1.49      djm       401: lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
                    402:     const struct hostkey_entry **found)
1.30      markus    403: {
1.49      djm       404:        return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
                    405:            found) == HOST_FOUND);
1.80      djm       406: }
                    407:
                    408: int
                    409: lookup_marker_in_hostkeys(struct hostkeys *hostkeys, int want_marker)
                    410: {
                    411:        u_int i;
                    412:
                    413:        for (i = 0; i < hostkeys->num_entries; i++) {
                    414:                if (hostkeys->entries[i].marker == (HostkeyMarker)want_marker)
                    415:                        return 1;
                    416:        }
                    417:        return 0;
1.1       deraadt   418: }
                    419:
1.62      djm       420: static int
1.64      djm       421: write_host_entry(FILE *f, const char *host, const char *ip,
1.62      djm       422:     const struct sshkey *key, int store_hash)
                    423: {
                    424:        int r, success = 0;
1.68      djm       425:        char *hashed_host = NULL, *lhost;
                    426:
                    427:        lhost = xstrdup(host);
                    428:        lowercase(lhost);
1.62      djm       429:
                    430:        if (store_hash) {
1.68      djm       431:                if ((hashed_host = host_hash(lhost, NULL, 0)) == NULL) {
1.62      djm       432:                        error("%s: host_hash failed", __func__);
1.68      djm       433:                        free(lhost);
1.62      djm       434:                        return 0;
                    435:                }
1.64      djm       436:                fprintf(f, "%s ", hashed_host);
                    437:        } else if (ip != NULL)
1.68      djm       438:                fprintf(f, "%s,%s ", lhost, ip);
                    439:        else {
                    440:                fprintf(f, "%s ", lhost);
                    441:        }
                    442:        free(lhost);
1.62      djm       443:        if ((r = sshkey_write(key, f)) == 0)
                    444:                success = 1;
                    445:        else
                    446:                error("%s: sshkey_write failed: %s", __func__, ssh_err(r));
                    447:        fputc('\n', f);
                    448:        return success;
                    449: }
                    450:
1.9       markus    451: /*
1.81      dtucker   452:  * Create user ~/.ssh directory if it doesn't exist and we want to write to it.
                    453:  * If notify is set, a message will be emitted if the directory is created.
                    454:  */
                    455: void
                    456: hostfile_create_user_ssh_dir(const char *filename, int notify)
                    457: {
                    458:        char *dotsshdir = NULL, *p;
                    459:        size_t len;
                    460:        struct stat st;
                    461:
                    462:        if ((p = strrchr(filename, '/')) == NULL)
                    463:                return;
                    464:        len = p - filename;
                    465:        dotsshdir = tilde_expand_filename("~/" _PATH_SSH_USER_DIR, getuid());
1.82    ! djm       466:        if (strlen(dotsshdir) > len || strncmp(filename, dotsshdir, len) != 0)
        !           467:                goto out; /* not ~/.ssh prefixed */
        !           468:        if (stat(dotsshdir, &st) == 0)
        !           469:                goto out; /* dir already exists */
1.81      dtucker   470:        else if (errno != ENOENT)
                    471:                error("Could not stat %s: %s", dotsshdir, strerror(errno));
1.82    ! djm       472:        else {
        !           473:                if (mkdir(dotsshdir, 0700) == -1)
        !           474:                        error("Could not create directory '%.200s' (%s).",
        !           475:                            dotsshdir, strerror(errno));
        !           476:                else if (notify)
        !           477:                        logit("Created directory '%s'.", dotsshdir);
        !           478:        }
        !           479:  out:
1.81      dtucker   480:        free(dotsshdir);
                    481: }
1.82    ! djm       482:
1.81      dtucker   483:
                    484: /*
1.9       markus    485:  * Appends an entry to the host file.  Returns false if the entry could not
                    486:  * be appended.
                    487:  */
1.2       provos    488: int
1.59      djm       489: add_host_to_hostfile(const char *filename, const char *host,
                    490:     const struct sshkey *key, int store_hash)
1.1       deraadt   491: {
1.7       markus    492:        FILE *f;
1.62      djm       493:        int success;
1.33      djm       494:
1.14      markus    495:        if (key == NULL)
1.17      markus    496:                return 1;       /* XXX ? */
1.81      dtucker   497:        hostfile_create_user_ssh_dir(filename, 0);
1.7       markus    498:        f = fopen(filename, "a");
                    499:        if (!f)
                    500:                return 0;
1.64      djm       501:        success = write_host_entry(f, host, NULL, key, store_hash);
1.62      djm       502:        fclose(f);
                    503:        return success;
                    504: }
                    505:
                    506: struct host_delete_ctx {
                    507:        FILE *out;
                    508:        int quiet;
                    509:        const char *host;
1.64      djm       510:        int *skip_keys; /* XXX split for host/ip? might want to ensure both */
1.62      djm       511:        struct sshkey * const *keys;
                    512:        size_t nkeys;
1.64      djm       513:        int modified;
1.62      djm       514: };
                    515:
                    516: static int
                    517: host_delete(struct hostkey_foreach_line *l, void *_ctx)
                    518: {
                    519:        struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
1.64      djm       520:        int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
1.62      djm       521:        size_t i;
                    522:
1.64      djm       523:        if (l->status == HKF_STATUS_MATCHED) {
1.62      djm       524:                if (l->marker != MRK_NONE) {
                    525:                        /* Don't remove CA and revocation lines */
                    526:                        fprintf(ctx->out, "%s\n", l->line);
                    527:                        return 0;
                    528:                }
1.33      djm       529:
1.62      djm       530:                /*
                    531:                 * If this line contains one of the keys that we will be
                    532:                 * adding later, then don't change it and mark the key for
                    533:                 * skipping.
                    534:                 */
                    535:                for (i = 0; i < ctx->nkeys; i++) {
                    536:                        if (sshkey_equal(ctx->keys[i], l->key)) {
                    537:                                ctx->skip_keys[i] = 1;
                    538:                                fprintf(ctx->out, "%s\n", l->line);
                    539:                                debug3("%s: %s key already at %s:%ld", __func__,
                    540:                                    sshkey_type(l->key), l->path, l->linenum);
                    541:                                return 0;
                    542:                        }
                    543:                }
                    544:
                    545:                /*
                    546:                 * Hostname matches and has no CA/revoke marker, delete it
                    547:                 * by *not* writing the line to ctx->out.
                    548:                 */
1.64      djm       549:                do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
1.62      djm       550:                    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
1.64      djm       551:                    l->path, l->linenum, sshkey_type(l->key), ctx->host);
                    552:                ctx->modified = 1;
1.62      djm       553:                return 0;
                    554:        }
                    555:        /* Retain non-matching hosts and invalid lines when deleting */
                    556:        if (l->status == HKF_STATUS_INVALID) {
                    557:                do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
                    558:                    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
                    559:                    l->path, l->linenum);
                    560:        }
                    561:        fprintf(ctx->out, "%s\n", l->line);
                    562:        return 0;
                    563: }
                    564:
                    565: int
1.64      djm       566: hostfile_replace_entries(const char *filename, const char *host, const char *ip,
                    567:     struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
1.62      djm       568: {
                    569:        int r, fd, oerrno = 0;
1.64      djm       570:        int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
1.62      djm       571:        struct host_delete_ctx ctx;
1.64      djm       572:        char *fp, *temp = NULL, *back = NULL;
1.62      djm       573:        mode_t omask;
                    574:        size_t i;
                    575:
1.63      djm       576:        omask = umask(077);
                    577:
1.62      djm       578:        memset(&ctx, 0, sizeof(ctx));
                    579:        ctx.host = host;
                    580:        ctx.quiet = quiet;
                    581:        if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
                    582:                return SSH_ERR_ALLOC_FAIL;
                    583:        ctx.keys = keys;
                    584:        ctx.nkeys = nkeys;
1.64      djm       585:        ctx.modified = 0;
1.62      djm       586:
                    587:        /*
                    588:         * Prepare temporary file for in-place deletion.
                    589:         */
1.75      deraadt   590:        if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) == -1 ||
1.74      deraadt   591:            (r = asprintf(&back, "%s.old", filename)) == -1) {
1.62      djm       592:                r = SSH_ERR_ALLOC_FAIL;
                    593:                goto fail;
                    594:        }
                    595:
                    596:        if ((fd = mkstemp(temp)) == -1) {
                    597:                oerrno = errno;
                    598:                error("%s: mkstemp: %s", __func__, strerror(oerrno));
                    599:                r = SSH_ERR_SYSTEM_ERROR;
                    600:                goto fail;
                    601:        }
                    602:        if ((ctx.out = fdopen(fd, "w")) == NULL) {
                    603:                oerrno = errno;
                    604:                close(fd);
                    605:                error("%s: fdopen: %s", __func__, strerror(oerrno));
                    606:                r = SSH_ERR_SYSTEM_ERROR;
                    607:                goto fail;
                    608:        }
                    609:
                    610:        /* Remove all entries for the specified host from the file */
1.64      djm       611:        if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
1.62      djm       612:            HKF_WANT_PARSE_KEY)) != 0) {
1.77      djm       613:                oerrno = errno;
1.62      djm       614:                error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
                    615:                goto fail;
                    616:        }
                    617:
                    618:        /* Add the requested keys */
                    619:        for (i = 0; i < nkeys; i++) {
                    620:                if (ctx.skip_keys[i])
                    621:                        continue;
1.64      djm       622:                if ((fp = sshkey_fingerprint(keys[i], hash_alg,
                    623:                    SSH_FP_DEFAULT)) == NULL) {
                    624:                        r = SSH_ERR_ALLOC_FAIL;
                    625:                        goto fail;
                    626:                }
                    627:                do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s",
                    628:                    quiet ? __func__ : "", quiet ? ": " : "", host, filename,
                    629:                    sshkey_ssh_name(keys[i]), fp);
                    630:                free(fp);
                    631:                if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) {
1.62      djm       632:                        r = SSH_ERR_INTERNAL_ERROR;
                    633:                        goto fail;
                    634:                }
1.64      djm       635:                ctx.modified = 1;
1.33      djm       636:        }
1.62      djm       637:        fclose(ctx.out);
                    638:        ctx.out = NULL;
1.33      djm       639:
1.64      djm       640:        if (ctx.modified) {
                    641:                /* Backup the original file and replace it with the temporary */
                    642:                if (unlink(back) == -1 && errno != ENOENT) {
                    643:                        oerrno = errno;
                    644:                        error("%s: unlink %.100s: %s", __func__,
                    645:                            back, strerror(errno));
                    646:                        r = SSH_ERR_SYSTEM_ERROR;
                    647:                        goto fail;
                    648:                }
                    649:                if (link(filename, back) == -1) {
                    650:                        oerrno = errno;
                    651:                        error("%s: link %.100s to %.100s: %s", __func__,
                    652:                            filename, back, strerror(errno));
                    653:                        r = SSH_ERR_SYSTEM_ERROR;
                    654:                        goto fail;
                    655:                }
                    656:                if (rename(temp, filename) == -1) {
                    657:                        oerrno = errno;
                    658:                        error("%s: rename \"%s\" to \"%s\": %s", __func__,
                    659:                            temp, filename, strerror(errno));
                    660:                        r = SSH_ERR_SYSTEM_ERROR;
                    661:                        goto fail;
                    662:                }
                    663:        } else {
                    664:                /* No changes made; just delete the temporary file */
                    665:                if (unlink(temp) != 0)
                    666:                        error("%s: unlink \"%s\": %s", __func__,
                    667:                            temp, strerror(errno));
1.62      djm       668:        }
1.64      djm       669:
1.62      djm       670:        /* success */
                    671:        r = 0;
                    672:  fail:
                    673:        if (temp != NULL && r != 0)
                    674:                unlink(temp);
                    675:        free(temp);
                    676:        free(back);
                    677:        if (ctx.out != NULL)
                    678:                fclose(ctx.out);
                    679:        free(ctx.skip_keys);
1.63      djm       680:        umask(omask);
1.62      djm       681:        if (r == SSH_ERR_SYSTEM_ERROR)
                    682:                errno = oerrno;
                    683:        return r;
1.60      djm       684: }
                    685:
                    686: static int
                    687: match_maybe_hashed(const char *host, const char *names, int *was_hashed)
                    688: {
                    689:        int hashed = *names == HASH_DELIM;
                    690:        const char *hashed_host;
                    691:        size_t nlen = strlen(names);
                    692:
                    693:        if (was_hashed != NULL)
                    694:                *was_hashed = hashed;
                    695:        if (hashed) {
                    696:                if ((hashed_host = host_hash(host, names, nlen)) == NULL)
                    697:                        return -1;
                    698:                return nlen == strlen(hashed_host) &&
                    699:                    strncmp(hashed_host, names, nlen) == 0;
                    700:        }
1.66      djm       701:        return match_hostname(host, names) == 1;
1.60      djm       702: }
                    703:
                    704: int
                    705: hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
1.64      djm       706:     const char *host, const char *ip, u_int options)
1.60      djm       707: {
                    708:        FILE *f;
1.72      markus    709:        char *line = NULL, ktype[128];
1.60      djm       710:        u_long linenum = 0;
                    711:        char *cp, *cp2;
                    712:        u_int kbits;
1.64      djm       713:        int hashed;
1.60      djm       714:        int s, r = 0;
                    715:        struct hostkey_foreach_line lineinfo;
1.72      markus    716:        size_t linesize = 0, l;
1.60      djm       717:
                    718:        memset(&lineinfo, 0, sizeof(lineinfo));
1.64      djm       719:        if (host == NULL && (options & HKF_WANT_MATCH) != 0)
1.60      djm       720:                return SSH_ERR_INVALID_ARGUMENT;
                    721:        if ((f = fopen(path, "r")) == NULL)
                    722:                return SSH_ERR_SYSTEM_ERROR;
                    723:
                    724:        debug3("%s: reading file \"%s\"", __func__, path);
1.72      markus    725:        while (getline(&line, &linesize, f) != -1) {
                    726:                linenum++;
1.60      djm       727:                line[strcspn(line, "\n")] = '\0';
                    728:
1.73      djm       729:                free(lineinfo.line);
1.60      djm       730:                sshkey_free(lineinfo.key);
                    731:                memset(&lineinfo, 0, sizeof(lineinfo));
                    732:                lineinfo.path = path;
                    733:                lineinfo.linenum = linenum;
1.72      markus    734:                lineinfo.line = xstrdup(line);
1.64      djm       735:                lineinfo.marker = MRK_NONE;
1.60      djm       736:                lineinfo.status = HKF_STATUS_OK;
1.64      djm       737:                lineinfo.keytype = KEY_UNSPEC;
1.60      djm       738:
                    739:                /* Skip any leading whitespace, comments and empty lines. */
                    740:                for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
                    741:                        ;
                    742:                if (!*cp || *cp == '#' || *cp == '\n') {
1.64      djm       743:                        if ((options & HKF_WANT_MATCH) == 0) {
1.60      djm       744:                                lineinfo.status = HKF_STATUS_COMMENT;
                    745:                                if ((r = callback(&lineinfo, ctx)) != 0)
                    746:                                        break;
                    747:                        }
                    748:                        continue;
                    749:                }
                    750:
                    751:                if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
                    752:                        verbose("%s: invalid marker at %s:%lu",
                    753:                            __func__, path, linenum);
1.64      djm       754:                        if ((options & HKF_WANT_MATCH) == 0)
1.60      djm       755:                                goto bad;
                    756:                        continue;
                    757:                }
                    758:
                    759:                /* Find the end of the host name portion. */
                    760:                for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
                    761:                        ;
                    762:                lineinfo.hosts = cp;
                    763:                *cp2++ = '\0';
                    764:
                    765:                /* Check if the host name matches. */
                    766:                if (host != NULL) {
1.64      djm       767:                        if ((s = match_maybe_hashed(host, lineinfo.hosts,
                    768:                            &hashed)) == -1) {
1.60      djm       769:                                debug2("%s: %s:%ld: bad host hash \"%.32s\"",
                    770:                                    __func__, path, linenum, lineinfo.hosts);
                    771:                                goto bad;
                    772:                        }
1.64      djm       773:                        if (s == 1) {
                    774:                                lineinfo.status = HKF_STATUS_MATCHED;
                    775:                                lineinfo.match |= HKF_MATCH_HOST |
                    776:                                    (hashed ? HKF_MATCH_HOST_HASHED : 0);
                    777:                        }
                    778:                        /* Try matching IP address if supplied */
                    779:                        if (ip != NULL) {
                    780:                                if ((s = match_maybe_hashed(ip, lineinfo.hosts,
                    781:                                    &hashed)) == -1) {
                    782:                                        debug2("%s: %s:%ld: bad ip hash "
                    783:                                            "\"%.32s\"", __func__, path,
                    784:                                            linenum, lineinfo.hosts);
                    785:                                        goto bad;
                    786:                                }
                    787:                                if (s == 1) {
                    788:                                        lineinfo.status = HKF_STATUS_MATCHED;
                    789:                                        lineinfo.match |= HKF_MATCH_IP |
                    790:                                            (hashed ? HKF_MATCH_IP_HASHED : 0);
                    791:                                }
                    792:                        }
                    793:                        /*
                    794:                         * Skip this line if host matching requested and
                    795:                         * neither host nor address matched.
                    796:                         */
                    797:                        if ((options & HKF_WANT_MATCH) != 0 &&
                    798:                            lineinfo.status != HKF_STATUS_MATCHED)
                    799:                                continue;
1.60      djm       800:                }
                    801:
                    802:                /* Got a match.  Skip host name and any following whitespace */
                    803:                for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
                    804:                        ;
                    805:                if (*cp2 == '\0' || *cp2 == '#') {
1.64      djm       806:                        debug2("%s:%ld: truncated before key type",
                    807:                            path, linenum);
1.60      djm       808:                        goto bad;
                    809:                }
                    810:                lineinfo.rawkey = cp = cp2;
                    811:
                    812:                if ((options & HKF_WANT_PARSE_KEY) != 0) {
                    813:                        /*
                    814:                         * Extract the key from the line.  This will skip
                    815:                         * any leading whitespace.  Ignore badly formatted
                    816:                         * lines.
                    817:                         */
                    818:                        if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
                    819:                                error("%s: sshkey_new failed", __func__);
1.64      djm       820:                                r = SSH_ERR_ALLOC_FAIL;
                    821:                                break;
1.60      djm       822:                        }
                    823:                        if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
                    824:                                goto bad;
                    825:                        }
1.64      djm       826:                        lineinfo.keytype = lineinfo.key->type;
                    827:                        lineinfo.comment = cp;
                    828:                } else {
                    829:                        /* Extract and parse key type */
                    830:                        l = strcspn(lineinfo.rawkey, " \t");
                    831:                        if (l <= 1 || l >= sizeof(ktype) ||
                    832:                            lineinfo.rawkey[l] == '\0')
                    833:                                goto bad;
                    834:                        memcpy(ktype, lineinfo.rawkey, l);
                    835:                        ktype[l] = '\0';
                    836:                        lineinfo.keytype = sshkey_type_from_name(ktype);
1.65      djm       837:
1.64      djm       838:                        /*
1.70      djm       839:                         * Assume legacy RSA1 if the first component is a short
1.64      djm       840:                         * decimal number.
                    841:                         */
                    842:                        if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
                    843:                            strspn(ktype, "0123456789") == l)
1.70      djm       844:                                goto bad;
1.65      djm       845:
1.64      djm       846:                        /*
                    847:                         * Check that something other than whitespace follows
                    848:                         * the key type. This won't catch all corruption, but
                    849:                         * it does catch trivial truncation.
                    850:                         */
                    851:                        cp2 += l; /* Skip past key type */
                    852:                        for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
                    853:                                ;
                    854:                        if (*cp2 == '\0' || *cp2 == '#') {
                    855:                                debug2("%s:%ld: truncated after key type",
                    856:                                    path, linenum);
                    857:                                lineinfo.keytype = KEY_UNSPEC;
                    858:                        }
                    859:                        if (lineinfo.keytype == KEY_UNSPEC) {
1.60      djm       860:  bad:
1.64      djm       861:                                sshkey_free(lineinfo.key);
                    862:                                lineinfo.key = NULL;
1.60      djm       863:                                lineinfo.status = HKF_STATUS_INVALID;
                    864:                                if ((r = callback(&lineinfo, ctx)) != 0)
                    865:                                        break;
                    866:                                continue;
                    867:                        }
                    868:                }
                    869:                if ((r = callback(&lineinfo, ctx)) != 0)
                    870:                        break;
                    871:        }
                    872:        sshkey_free(lineinfo.key);
1.72      markus    873:        free(lineinfo.line);
                    874:        free(line);
1.60      djm       875:        fclose(f);
                    876:        return r;
1.1       deraadt   877: }