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

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