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