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

1.64    ! djm         1: /* $OpenBSD: hostfile.c,v 1.63 2015/01/26 13:36:53 djm 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];
                    123:        u_int i, len;
                    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 */
                    129:                for (i = 0; i < len; i++)
                    130:                        salt[i] = arc4random();
                    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;
1.59      djm       164:        int r;
1.7       markus    165:
                    166:        /* Skip leading whitespace. */
1.9       markus    167:        for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
                    168:                ;
1.1       deraadt   169:
1.59      djm       170:        if ((r = sshkey_read(ret, &cp)) != 0)
1.7       markus    171:                return 0;
                    172:
                    173:        /* Skip trailing whitespace. */
1.9       markus    174:        for (; *cp == ' ' || *cp == '\t'; cp++)
                    175:                ;
1.7       markus    176:
                    177:        /* Return results. */
                    178:        *cpp = cp;
1.59      djm       179:        if (bitsp != NULL)
                    180:                *bitsp = sshkey_size(ret);
1.7       markus    181:        return 1;
1.14      markus    182: }
1.1       deraadt   183:
1.49      djm       184: static HostkeyMarker
1.48      djm       185: check_markers(char **cpp)
                    186: {
                    187:        char marker[32], *sp, *cp = *cpp;
                    188:        int ret = MRK_NONE;
                    189:
                    190:        while (*cp == '@') {
                    191:                /* Only one marker is allowed */
                    192:                if (ret != MRK_NONE)
                    193:                        return MRK_ERROR;
                    194:                /* Markers are terminated by whitespace */
                    195:                if ((sp = strchr(cp, ' ')) == NULL &&
                    196:                    (sp = strchr(cp, '\t')) == NULL)
                    197:                        return MRK_ERROR;
                    198:                /* Extract marker for comparison */
                    199:                if (sp <= cp + 1 || sp >= cp + sizeof(marker))
                    200:                        return MRK_ERROR;
                    201:                memcpy(marker, cp, sp - cp);
                    202:                marker[sp - cp] = '\0';
                    203:                if (strcmp(marker, CA_MARKER) == 0)
                    204:                        ret = MRK_CA;
                    205:                else if (strcmp(marker, REVOKE_MARKER) == 0)
                    206:                        ret = MRK_REVOKE;
                    207:                else
                    208:                        return MRK_ERROR;
                    209:
                    210:                /* Skip past marker and any whitespace that follows it */
                    211:                cp = sp;
                    212:                for (; *cp == ' ' || *cp == '\t'; cp++)
                    213:                        ;
                    214:        }
                    215:        *cpp = cp;
                    216:        return ret;
                    217: }
                    218:
1.49      djm       219: struct hostkeys *
                    220: init_hostkeys(void)
                    221: {
                    222:        struct hostkeys *ret = xcalloc(1, sizeof(*ret));
                    223:
                    224:        ret->entries = NULL;
                    225:        return ret;
                    226: }
1.1       deraadt   227:
1.61      djm       228: struct load_callback_ctx {
                    229:        const char *host;
                    230:        u_long num_loaded;
                    231:        struct hostkeys *hostkeys;
                    232: };
                    233:
                    234: static int
                    235: record_hostkey(struct hostkey_foreach_line *l, void *_ctx)
1.1       deraadt   236: {
1.61      djm       237:        struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx;
                    238:        struct hostkeys *hostkeys = ctx->hostkeys;
                    239:        struct hostkey_entry *tmp;
                    240:
                    241:        if (l->status == HKF_STATUS_INVALID) {
                    242:                error("%s:%ld: parse error in hostkeys file",
                    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);
                    251:        if ((tmp = reallocarray(hostkeys->entries,
                    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.55      tedu      300:        explicit_bzero(hostkeys, sizeof(*hostkeys));
1.51      djm       301:        free(hostkeys);
1.49      djm       302: }
                    303:
                    304: static int
1.59      djm       305: check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
1.49      djm       306: {
1.59      djm       307:        int is_cert = sshkey_is_cert(k);
1.49      djm       308:        u_int i;
1.7       markus    309:
1.49      djm       310:        for (i = 0; i < hostkeys->num_entries; i++) {
                    311:                if (hostkeys->entries[i].marker != MRK_REVOKE)
1.30      markus    312:                        continue;
1.59      djm       313:                if (sshkey_equal_public(k, hostkeys->entries[i].key))
1.49      djm       314:                        return -1;
                    315:                if (is_cert &&
1.59      djm       316:                    sshkey_equal_public(k->cert->signature_key,
1.49      djm       317:                    hostkeys->entries[i].key))
                    318:                        return -1;
                    319:        }
                    320:        return 0;
                    321: }
                    322:
                    323: /*
                    324:  * Match keys against a specified key, or look one up by key type.
                    325:  *
                    326:  * If looking for a keytype (key == NULL) and one is found then return
                    327:  * HOST_FOUND, otherwise HOST_NEW.
                    328:  *
                    329:  * If looking for a key (key != NULL):
                    330:  *  1. If the key is a cert and a matching CA is found, return HOST_OK
                    331:  *  2. If the key is not a cert and a matching key is found, return HOST_OK
                    332:  *  3. If no key matches but a key with a different type is found, then
                    333:  *     return HOST_CHANGED
                    334:  *  4. If no matching keys are found, then return HOST_NEW.
                    335:  *
                    336:  * Finally, check any found key is not revoked.
                    337:  */
                    338: static HostStatus
                    339: check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
1.59      djm       340:     struct sshkey *k, int keytype, const struct hostkey_entry **found)
1.49      djm       341: {
                    342:        u_int i;
                    343:        HostStatus end_return = HOST_NEW;
1.59      djm       344:        int want_cert = sshkey_is_cert(k);
1.49      djm       345:        HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
                    346:        int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2;
                    347:
                    348:        if (found != NULL)
                    349:                *found = NULL;
1.30      markus    350:
1.49      djm       351:        for (i = 0; i < hostkeys->num_entries; i++) {
                    352:                if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1)
                    353:                        continue;
                    354:                if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1)
1.30      markus    355:                        continue;
1.49      djm       356:                if (hostkeys->entries[i].marker != want_marker)
                    357:                        continue;
                    358:                if (k == NULL) {
                    359:                        if (hostkeys->entries[i].key->type != keytype)
                    360:                                continue;
                    361:                        end_return = HOST_FOUND;
                    362:                        if (found != NULL)
                    363:                                *found = hostkeys->entries + i;
                    364:                        k = hostkeys->entries[i].key;
                    365:                        break;
                    366:                }
                    367:                if (want_cert) {
1.59      djm       368:                        if (sshkey_equal_public(k->cert->signature_key,
1.49      djm       369:                            hostkeys->entries[i].key)) {
                    370:                                /* A matching CA exists */
                    371:                                end_return = HOST_OK;
                    372:                                if (found != NULL)
                    373:                                        *found = hostkeys->entries + i;
                    374:                                break;
1.48      djm       375:                        }
1.49      djm       376:                } else {
1.59      djm       377:                        if (sshkey_equal(k, hostkeys->entries[i].key)) {
1.49      djm       378:                                end_return = HOST_OK;
                    379:                                if (found != NULL)
                    380:                                        *found = hostkeys->entries + i;
                    381:                                break;
1.48      djm       382:                        }
1.49      djm       383:                        /* A non-maching key exists */
                    384:                        end_return = HOST_CHANGED;
                    385:                        if (found != NULL)
                    386:                                *found = hostkeys->entries + i;
1.48      djm       387:                }
1.1       deraadt   388:        }
1.49      djm       389:        if (check_key_not_revoked(hostkeys, k) != 0) {
                    390:                end_return = HOST_REVOKED;
                    391:                if (found != NULL)
                    392:                        *found = NULL;
                    393:        }
1.7       markus    394:        return end_return;
1.30      markus    395: }
1.58      djm       396:
1.30      markus    397: HostStatus
1.59      djm       398: check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
1.49      djm       399:     const struct hostkey_entry **found)
1.30      markus    400: {
                    401:        if (key == NULL)
                    402:                fatal("no key to look up");
1.49      djm       403:        return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
1.30      markus    404: }
                    405:
                    406: int
1.49      djm       407: lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
                    408:     const struct hostkey_entry **found)
1.30      markus    409: {
1.49      djm       410:        return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
                    411:            found) == HOST_FOUND);
1.1       deraadt   412: }
                    413:
1.62      djm       414: static int
1.64    ! djm       415: write_host_entry(FILE *f, const char *host, const char *ip,
1.62      djm       416:     const struct sshkey *key, int store_hash)
                    417: {
                    418:        int r, success = 0;
                    419:        char *hashed_host = NULL;
                    420:
                    421:        if (store_hash) {
                    422:                if ((hashed_host = host_hash(host, NULL, 0)) == NULL) {
                    423:                        error("%s: host_hash failed", __func__);
                    424:                        return 0;
                    425:                }
1.64    ! djm       426:                fprintf(f, "%s ", hashed_host);
        !           427:        } else if (ip != NULL)
        !           428:                fprintf(f, "%s,%s ", host, ip);
        !           429:        else
        !           430:                fprintf(f, "%s ", host);
1.62      djm       431:
                    432:        if ((r = sshkey_write(key, f)) == 0)
                    433:                success = 1;
                    434:        else
                    435:                error("%s: sshkey_write failed: %s", __func__, ssh_err(r));
                    436:        fputc('\n', f);
                    437:        return success;
                    438: }
                    439:
1.9       markus    440: /*
                    441:  * Appends an entry to the host file.  Returns false if the entry could not
                    442:  * be appended.
                    443:  */
1.2       provos    444: int
1.59      djm       445: add_host_to_hostfile(const char *filename, const char *host,
                    446:     const struct sshkey *key, int store_hash)
1.1       deraadt   447: {
1.7       markus    448:        FILE *f;
1.62      djm       449:        int success;
1.33      djm       450:
1.14      markus    451:        if (key == NULL)
1.17      markus    452:                return 1;       /* XXX ? */
1.7       markus    453:        f = fopen(filename, "a");
                    454:        if (!f)
                    455:                return 0;
1.64    ! djm       456:        success = write_host_entry(f, host, NULL, key, store_hash);
1.62      djm       457:        fclose(f);
                    458:        return success;
                    459: }
                    460:
                    461: struct host_delete_ctx {
                    462:        FILE *out;
                    463:        int quiet;
                    464:        const char *host;
1.64    ! djm       465:        int *skip_keys; /* XXX split for host/ip? might want to ensure both */
1.62      djm       466:        struct sshkey * const *keys;
                    467:        size_t nkeys;
1.64    ! djm       468:        int modified;
1.62      djm       469: };
                    470:
                    471: static int
                    472: host_delete(struct hostkey_foreach_line *l, void *_ctx)
                    473: {
                    474:        struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
1.64    ! djm       475:        int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
1.62      djm       476:        size_t i;
                    477:
1.64    ! djm       478:        if (l->status == HKF_STATUS_MATCHED) {
1.62      djm       479:                if (l->marker != MRK_NONE) {
                    480:                        /* Don't remove CA and revocation lines */
                    481:                        fprintf(ctx->out, "%s\n", l->line);
                    482:                        return 0;
                    483:                }
1.33      djm       484:
1.62      djm       485:                /* XXX might need a knob for this later */
                    486:                /* Don't remove RSA1 keys */
                    487:                if (l->key->type == KEY_RSA1) {
                    488:                        fprintf(ctx->out, "%s\n", l->line);
1.33      djm       489:                        return 0;
                    490:                }
1.62      djm       491:
                    492:                /*
                    493:                 * If this line contains one of the keys that we will be
                    494:                 * adding later, then don't change it and mark the key for
                    495:                 * skipping.
                    496:                 */
                    497:                for (i = 0; i < ctx->nkeys; i++) {
                    498:                        if (sshkey_equal(ctx->keys[i], l->key)) {
                    499:                                ctx->skip_keys[i] = 1;
                    500:                                fprintf(ctx->out, "%s\n", l->line);
                    501:                                debug3("%s: %s key already at %s:%ld", __func__,
                    502:                                    sshkey_type(l->key), l->path, l->linenum);
                    503:                                return 0;
                    504:                        }
                    505:                }
                    506:
                    507:                /*
                    508:                 * Hostname matches and has no CA/revoke marker, delete it
                    509:                 * by *not* writing the line to ctx->out.
                    510:                 */
1.64    ! djm       511:                do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
1.62      djm       512:                    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
1.64    ! djm       513:                    l->path, l->linenum, sshkey_type(l->key), ctx->host);
        !           514:                ctx->modified = 1;
1.62      djm       515:                return 0;
                    516:        }
                    517:        /* Retain non-matching hosts and invalid lines when deleting */
                    518:        if (l->status == HKF_STATUS_INVALID) {
                    519:                do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
                    520:                    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
                    521:                    l->path, l->linenum);
                    522:        }
                    523:        fprintf(ctx->out, "%s\n", l->line);
                    524:        return 0;
                    525: }
                    526:
                    527: int
1.64    ! djm       528: hostfile_replace_entries(const char *filename, const char *host, const char *ip,
        !           529:     struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
1.62      djm       530: {
                    531:        int r, fd, oerrno = 0;
1.64    ! djm       532:        int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
1.62      djm       533:        struct host_delete_ctx ctx;
1.64    ! djm       534:        char *fp, *temp = NULL, *back = NULL;
1.62      djm       535:        mode_t omask;
                    536:        size_t i;
                    537:
1.63      djm       538:        omask = umask(077);
                    539:
1.62      djm       540:        memset(&ctx, 0, sizeof(ctx));
                    541:        ctx.host = host;
                    542:        ctx.quiet = quiet;
                    543:        if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
                    544:                return SSH_ERR_ALLOC_FAIL;
                    545:        ctx.keys = keys;
                    546:        ctx.nkeys = nkeys;
1.64    ! djm       547:        ctx.modified = 0;
1.62      djm       548:
                    549:        /*
                    550:         * Prepare temporary file for in-place deletion.
                    551:         */
                    552:        if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) < 0 ||
                    553:            (r = asprintf(&back, "%s.old", filename)) < 0) {
                    554:                r = SSH_ERR_ALLOC_FAIL;
                    555:                goto fail;
                    556:        }
                    557:
                    558:        if ((fd = mkstemp(temp)) == -1) {
                    559:                oerrno = errno;
                    560:                error("%s: mkstemp: %s", __func__, strerror(oerrno));
                    561:                r = SSH_ERR_SYSTEM_ERROR;
                    562:                goto fail;
                    563:        }
                    564:        if ((ctx.out = fdopen(fd, "w")) == NULL) {
                    565:                oerrno = errno;
                    566:                close(fd);
                    567:                error("%s: fdopen: %s", __func__, strerror(oerrno));
                    568:                r = SSH_ERR_SYSTEM_ERROR;
                    569:                goto fail;
                    570:        }
                    571:
                    572:        /* Remove all entries for the specified host from the file */
1.64    ! djm       573:        if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
1.62      djm       574:            HKF_WANT_PARSE_KEY)) != 0) {
                    575:                error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
                    576:                goto fail;
                    577:        }
                    578:
                    579:        /* Add the requested keys */
                    580:        for (i = 0; i < nkeys; i++) {
                    581:                if (ctx.skip_keys[i])
                    582:                        continue;
1.64    ! djm       583:                if ((fp = sshkey_fingerprint(keys[i], hash_alg,
        !           584:                    SSH_FP_DEFAULT)) == NULL) {
        !           585:                        r = SSH_ERR_ALLOC_FAIL;
        !           586:                        goto fail;
        !           587:                }
        !           588:                do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s",
        !           589:                    quiet ? __func__ : "", quiet ? ": " : "", host, filename,
        !           590:                    sshkey_ssh_name(keys[i]), fp);
        !           591:                free(fp);
        !           592:                if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) {
1.62      djm       593:                        r = SSH_ERR_INTERNAL_ERROR;
                    594:                        goto fail;
                    595:                }
1.64    ! djm       596:                ctx.modified = 1;
1.33      djm       597:        }
1.62      djm       598:        fclose(ctx.out);
                    599:        ctx.out = NULL;
1.33      djm       600:
1.64    ! djm       601:        if (ctx.modified) {
        !           602:                /* Backup the original file and replace it with the temporary */
        !           603:                if (unlink(back) == -1 && errno != ENOENT) {
        !           604:                        oerrno = errno;
        !           605:                        error("%s: unlink %.100s: %s", __func__,
        !           606:                            back, strerror(errno));
        !           607:                        r = SSH_ERR_SYSTEM_ERROR;
        !           608:                        goto fail;
        !           609:                }
        !           610:                if (link(filename, back) == -1) {
        !           611:                        oerrno = errno;
        !           612:                        error("%s: link %.100s to %.100s: %s", __func__,
        !           613:                            filename, back, strerror(errno));
        !           614:                        r = SSH_ERR_SYSTEM_ERROR;
        !           615:                        goto fail;
        !           616:                }
        !           617:                if (rename(temp, filename) == -1) {
        !           618:                        oerrno = errno;
        !           619:                        error("%s: rename \"%s\" to \"%s\": %s", __func__,
        !           620:                            temp, filename, strerror(errno));
        !           621:                        r = SSH_ERR_SYSTEM_ERROR;
        !           622:                        goto fail;
        !           623:                }
        !           624:        } else {
        !           625:                /* No changes made; just delete the temporary file */
        !           626:                if (unlink(temp) != 0)
        !           627:                        error("%s: unlink \"%s\": %s", __func__,
        !           628:                            temp, strerror(errno));
1.62      djm       629:        }
1.64    ! djm       630:
1.62      djm       631:        /* success */
                    632:        r = 0;
                    633:  fail:
                    634:        if (temp != NULL && r != 0)
                    635:                unlink(temp);
                    636:        free(temp);
                    637:        free(back);
                    638:        if (ctx.out != NULL)
                    639:                fclose(ctx.out);
                    640:        free(ctx.skip_keys);
1.63      djm       641:        umask(omask);
1.62      djm       642:        if (r == SSH_ERR_SYSTEM_ERROR)
                    643:                errno = oerrno;
                    644:        return r;
1.60      djm       645: }
                    646:
                    647: static int
                    648: match_maybe_hashed(const char *host, const char *names, int *was_hashed)
                    649: {
                    650:        int hashed = *names == HASH_DELIM;
                    651:        const char *hashed_host;
                    652:        size_t nlen = strlen(names);
                    653:
                    654:        if (was_hashed != NULL)
                    655:                *was_hashed = hashed;
                    656:        if (hashed) {
                    657:                if ((hashed_host = host_hash(host, names, nlen)) == NULL)
                    658:                        return -1;
                    659:                return nlen == strlen(hashed_host) &&
                    660:                    strncmp(hashed_host, names, nlen) == 0;
                    661:        }
                    662:        return match_hostname(host, names, nlen) == 1;
                    663: }
                    664:
                    665: int
                    666: hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
1.64    ! djm       667:     const char *host, const char *ip, u_int options)
1.60      djm       668: {
                    669:        FILE *f;
1.64    ! djm       670:        char line[8192], oline[8192], ktype[128];
1.60      djm       671:        u_long linenum = 0;
                    672:        char *cp, *cp2;
                    673:        u_int kbits;
1.64    ! djm       674:        int hashed;
1.60      djm       675:        int s, r = 0;
                    676:        struct hostkey_foreach_line lineinfo;
1.64    ! djm       677:        size_t l;
1.60      djm       678:
                    679:        memset(&lineinfo, 0, sizeof(lineinfo));
1.64    ! djm       680:        if (host == NULL && (options & HKF_WANT_MATCH) != 0)
1.60      djm       681:                return SSH_ERR_INVALID_ARGUMENT;
                    682:        if ((f = fopen(path, "r")) == NULL)
                    683:                return SSH_ERR_SYSTEM_ERROR;
                    684:
                    685:        debug3("%s: reading file \"%s\"", __func__, path);
                    686:        while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) {
                    687:                line[strcspn(line, "\n")] = '\0';
                    688:                strlcpy(oline, line, sizeof(oline));
                    689:
                    690:                sshkey_free(lineinfo.key);
                    691:                memset(&lineinfo, 0, sizeof(lineinfo));
                    692:                lineinfo.path = path;
                    693:                lineinfo.linenum = linenum;
                    694:                lineinfo.line = oline;
1.64    ! djm       695:                lineinfo.marker = MRK_NONE;
1.60      djm       696:                lineinfo.status = HKF_STATUS_OK;
1.64    ! djm       697:                lineinfo.keytype = KEY_UNSPEC;
1.60      djm       698:
                    699:                /* Skip any leading whitespace, comments and empty lines. */
                    700:                for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
                    701:                        ;
                    702:                if (!*cp || *cp == '#' || *cp == '\n') {
1.64    ! djm       703:                        if ((options & HKF_WANT_MATCH) == 0) {
1.60      djm       704:                                lineinfo.status = HKF_STATUS_COMMENT;
                    705:                                if ((r = callback(&lineinfo, ctx)) != 0)
                    706:                                        break;
                    707:                        }
                    708:                        continue;
                    709:                }
                    710:
                    711:                if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
                    712:                        verbose("%s: invalid marker at %s:%lu",
                    713:                            __func__, path, linenum);
1.64    ! djm       714:                        if ((options & HKF_WANT_MATCH) == 0)
1.60      djm       715:                                goto bad;
                    716:                        continue;
                    717:                }
                    718:
                    719:                /* Find the end of the host name portion. */
                    720:                for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
                    721:                        ;
                    722:                lineinfo.hosts = cp;
                    723:                *cp2++ = '\0';
                    724:
                    725:                /* Check if the host name matches. */
                    726:                if (host != NULL) {
1.64    ! djm       727:                        if ((s = match_maybe_hashed(host, lineinfo.hosts,
        !           728:                            &hashed)) == -1) {
1.60      djm       729:                                debug2("%s: %s:%ld: bad host hash \"%.32s\"",
                    730:                                    __func__, path, linenum, lineinfo.hosts);
                    731:                                goto bad;
                    732:                        }
1.64    ! djm       733:                        if (s == 1) {
        !           734:                                lineinfo.status = HKF_STATUS_MATCHED;
        !           735:                                lineinfo.match |= HKF_MATCH_HOST |
        !           736:                                    (hashed ? HKF_MATCH_HOST_HASHED : 0);
        !           737:                        }
        !           738:                        /* Try matching IP address if supplied */
        !           739:                        if (ip != NULL) {
        !           740:                                if ((s = match_maybe_hashed(ip, lineinfo.hosts,
        !           741:                                    &hashed)) == -1) {
        !           742:                                        debug2("%s: %s:%ld: bad ip hash "
        !           743:                                            "\"%.32s\"", __func__, path,
        !           744:                                            linenum, lineinfo.hosts);
        !           745:                                        goto bad;
        !           746:                                }
        !           747:                                if (s == 1) {
        !           748:                                        lineinfo.status = HKF_STATUS_MATCHED;
        !           749:                                        lineinfo.match |= HKF_MATCH_IP |
        !           750:                                            (hashed ? HKF_MATCH_IP_HASHED : 0);
        !           751:                                }
        !           752:                        }
        !           753:                        /*
        !           754:                         * Skip this line if host matching requested and
        !           755:                         * neither host nor address matched.
        !           756:                         */
        !           757:                        if ((options & HKF_WANT_MATCH) != 0 &&
        !           758:                            lineinfo.status != HKF_STATUS_MATCHED)
        !           759:                                continue;
1.60      djm       760:                }
                    761:
                    762:                /* Got a match.  Skip host name and any following whitespace */
                    763:                for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
                    764:                        ;
                    765:                if (*cp2 == '\0' || *cp2 == '#') {
1.64    ! djm       766:                        debug2("%s:%ld: truncated before key type",
        !           767:                            path, linenum);
1.60      djm       768:                        goto bad;
                    769:                }
                    770:                lineinfo.rawkey = cp = cp2;
                    771:
                    772:                if ((options & HKF_WANT_PARSE_KEY) != 0) {
                    773:                        /*
                    774:                         * Extract the key from the line.  This will skip
                    775:                         * any leading whitespace.  Ignore badly formatted
                    776:                         * lines.
                    777:                         */
                    778:                        if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
                    779:                                error("%s: sshkey_new failed", __func__);
1.64    ! djm       780:                                r = SSH_ERR_ALLOC_FAIL;
        !           781:                                break;
1.60      djm       782:                        }
                    783:                        if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
                    784: #ifdef WITH_SSH1
                    785:                                sshkey_free(lineinfo.key);
                    786:                                lineinfo.key = sshkey_new(KEY_RSA1);
                    787:                                if (lineinfo.key  == NULL) {
                    788:                                        error("%s: sshkey_new fail", __func__);
1.64    ! djm       789:                                        r = SSH_ERR_ALLOC_FAIL;
        !           790:                                        break;
1.60      djm       791:                                }
                    792:                                if (!hostfile_read_key(&cp, &kbits,
                    793:                                    lineinfo.key))
                    794:                                        goto bad;
                    795: #else
                    796:                                goto bad;
                    797: #endif
                    798:                        }
1.64    ! djm       799:                        lineinfo.keytype = lineinfo.key->type;
        !           800:                        lineinfo.comment = cp;
        !           801:                } else {
        !           802:                        /* Extract and parse key type */
        !           803:                        l = strcspn(lineinfo.rawkey, " \t");
        !           804:                        if (l <= 1 || l >= sizeof(ktype) ||
        !           805:                            lineinfo.rawkey[l] == '\0')
        !           806:                                goto bad;
        !           807:                        memcpy(ktype, lineinfo.rawkey, l);
        !           808:                        ktype[l] = '\0';
        !           809:                        lineinfo.keytype = sshkey_type_from_name(ktype);
        !           810: #ifdef WITH_SSH1
        !           811:                        /*
        !           812:                         * Assume RSA1 if the first component is a short
        !           813:                         * decimal number.
        !           814:                         */
        !           815:                        if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
        !           816:                            strspn(ktype, "0123456789") == l)
        !           817:                                lineinfo.keytype = KEY_RSA1;
        !           818: #endif
        !           819:                        /*
        !           820:                         * Check that something other than whitespace follows
        !           821:                         * the key type. This won't catch all corruption, but
        !           822:                         * it does catch trivial truncation.
        !           823:                         */
        !           824:                        cp2 += l; /* Skip past key type */
        !           825:                        for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
        !           826:                                ;
        !           827:                        if (*cp2 == '\0' || *cp2 == '#') {
        !           828:                                debug2("%s:%ld: truncated after key type",
        !           829:                                    path, linenum);
        !           830:                                lineinfo.keytype = KEY_UNSPEC;
        !           831:                        }
        !           832:                        if (lineinfo.keytype == KEY_UNSPEC) {
1.60      djm       833:  bad:
1.64    ! djm       834:                                sshkey_free(lineinfo.key);
        !           835:                                lineinfo.key = NULL;
1.60      djm       836:                                lineinfo.status = HKF_STATUS_INVALID;
                    837:                                if ((r = callback(&lineinfo, ctx)) != 0)
                    838:                                        break;
                    839:                                continue;
                    840:                        }
                    841:                }
                    842:                if ((r = callback(&lineinfo, ctx)) != 0)
                    843:                        break;
                    844:        }
                    845:        sshkey_free(lineinfo.key);
                    846:        fclose(f);
                    847:        return r;
1.1       deraadt   848: }