[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.80

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