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

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