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