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