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