xref: /netbsd-src/crypto/external/bsd/openssh/dist/hostfile.c (revision 7d62b00eb9ad855ffcd7da46b41e23feb5476fac)
1 /*	$NetBSD: hostfile.c,v 1.22 2022/02/23 19:07:20 christos Exp $	*/
2 /* $OpenBSD: hostfile.c,v 1.93 2022/01/06 22:02:52 djm Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * Functions for manipulating the known hosts files.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
17  * Copyright (c) 1999 Niels Provos.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include "includes.h"
41 __RCSID("$NetBSD: hostfile.c,v 1.22 2022/02/23 19:07:20 christos Exp $");
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 
45 #include <netinet/in.h>
46 
47 #include <errno.h>
48 #include <resolv.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 #include "xmalloc.h"
56 #include "match.h"
57 #include "sshkey.h"
58 #include "hostfile.h"
59 #include "log.h"
60 #include "misc.h"
61 #include "pathnames.h"
62 #include "ssherr.h"
63 #include "digest.h"
64 #include "hmac.h"
65 #include "sshbuf.h"
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 	char *encoded = NULL;
123 	u_int len;
124 
125 	len = ssh_digest_bytes(SSH_DIGEST_SHA1);
126 
127 	if (name_from_hostfile == NULL) {
128 		/* Create new salt */
129 		arc4random_buf(salt, len);
130 	} else {
131 		/* Extract salt from known host entry */
132 		if (extract_salt(name_from_hostfile, src_len, salt,
133 		    sizeof(salt)) == -1)
134 			return (NULL);
135 	}
136 
137 	if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL ||
138 	    ssh_hmac_init(ctx, salt, len) < 0 ||
139 	    ssh_hmac_update(ctx, host, strlen(host)) < 0 ||
140 	    ssh_hmac_final(ctx, result, sizeof(result)))
141 		fatal_f("ssh_hmac failed");
142 	ssh_hmac_free(ctx);
143 
144 	if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
145 	    __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
146 		fatal_f("__b64_ntop failed");
147 	xasprintf(&encoded, "%s%s%c%s", HASH_MAGIC, uu_salt, HASH_DELIM,
148 	    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(hashed_host);
460 	free(lhost);
461 	if ((r = sshkey_write(key, f)) == 0)
462 		success = 1;
463 	else
464 		error_fr(r, "sshkey_write");
465 	fputc('\n', f);
466 	/* If hashing is enabled, the IP address needs to go on its own line */
467 	if (success && store_hash && ip != NULL)
468 		success = write_host_entry(f, ip, NULL, key, 1);
469 	return success;
470 }
471 
472 /*
473  * Create user ~/.ssh directory if it doesn't exist and we want to write to it.
474  * If notify is set, a message will be emitted if the directory is created.
475  */
476 void
477 hostfile_create_user_ssh_dir(const char *filename, int notify)
478 {
479 	char *dotsshdir = NULL, *p;
480 	size_t len;
481 	struct stat st;
482 
483 	if ((p = strrchr(filename, '/')) == NULL)
484 		return;
485 	len = p - filename;
486 	dotsshdir = tilde_expand_filename("~/" _PATH_SSH_USER_DIR, getuid());
487 	if (strlen(dotsshdir) > len || strncmp(filename, dotsshdir, len) != 0)
488 		goto out; /* not ~/.ssh prefixed */
489 	if (stat(dotsshdir, &st) == 0)
490 		goto out; /* dir already exists */
491 	else if (errno != ENOENT)
492 		error("Could not stat %s: %s", dotsshdir, strerror(errno));
493 	else {
494 		if (mkdir(dotsshdir, 0700) == -1)
495 			error("Could not create directory '%.200s' (%s).",
496 			    dotsshdir, strerror(errno));
497 		else if (notify)
498 			logit("Created directory '%s'.", dotsshdir);
499 	}
500  out:
501 	free(dotsshdir);
502 }
503 
504 
505 /*
506  * Appends an entry to the host file.  Returns false if the entry could not
507  * be appended.
508  */
509 int
510 add_host_to_hostfile(const char *filename, const char *host,
511     const struct sshkey *key, int store_hash)
512 {
513 	FILE *f;
514 	int success;
515 
516 	if (key == NULL)
517 		return 1;	/* XXX ? */
518 	hostfile_create_user_ssh_dir(filename, 0);
519 	f = fopen(filename, "a");
520 	if (!f)
521 		return 0;
522 	success = write_host_entry(f, host, NULL, key, store_hash);
523 	fclose(f);
524 	return success;
525 }
526 
527 struct host_delete_ctx {
528 	FILE *out;
529 	int quiet;
530 	const char *host, *ip;
531 	u_int *match_keys;	/* mask of HKF_MATCH_* for this key */
532 	struct sshkey * const *keys;
533 	size_t nkeys;
534 	int modified;
535 };
536 
537 static int
538 host_delete(struct hostkey_foreach_line *l, void *_ctx)
539 {
540 	struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
541 	int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
542 	size_t i;
543 
544 	/* Don't remove CA and revocation lines */
545 	if (l->status == HKF_STATUS_MATCHED && l->marker == MRK_NONE) {
546 		/*
547 		 * If this line contains one of the keys that we will be
548 		 * adding later, then don't change it and mark the key for
549 		 * skipping.
550 		 */
551 		for (i = 0; i < ctx->nkeys; i++) {
552 			if (!sshkey_equal(ctx->keys[i], l->key))
553 				continue;
554 			ctx->match_keys[i] |= l->match;
555 			fprintf(ctx->out, "%s\n", l->line);
556 			debug3_f("%s key already at %s:%ld",
557 			    sshkey_type(l->key), l->path, l->linenum);
558 			return 0;
559 		}
560 
561 		/*
562 		 * Hostname matches and has no CA/revoke marker, delete it
563 		 * by *not* writing the line to ctx->out.
564 		 */
565 		do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
566 		    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
567 		    l->path, l->linenum, sshkey_type(l->key), ctx->host);
568 		ctx->modified = 1;
569 		return 0;
570 	}
571 	/* Retain non-matching hosts and invalid lines when deleting */
572 	if (l->status == HKF_STATUS_INVALID) {
573 		do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
574 		    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
575 		    l->path, l->linenum);
576 	}
577 	fprintf(ctx->out, "%s\n", l->line);
578 	return 0;
579 }
580 
581 int
582 hostfile_replace_entries(const char *filename, const char *host, const char *ip,
583     struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
584 {
585 	int r, fd, oerrno = 0;
586 	int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
587 	struct host_delete_ctx ctx;
588 	char *fp, *temp = NULL, *back = NULL;
589 	const char *what;
590 	mode_t omask;
591 	size_t i;
592 	u_int want;
593 
594 	omask = umask(077);
595 
596 	memset(&ctx, 0, sizeof(ctx));
597 	ctx.host = host;
598 	ctx.ip = ip;
599 	ctx.quiet = quiet;
600 
601 	if ((ctx.match_keys = calloc(nkeys, sizeof(*ctx.match_keys))) == NULL)
602 		return SSH_ERR_ALLOC_FAIL;
603 	ctx.keys = keys;
604 	ctx.nkeys = nkeys;
605 	ctx.modified = 0;
606 
607 	/*
608 	 * Prepare temporary file for in-place deletion.
609 	 */
610 	if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) == -1 ||
611 	    (r = asprintf(&back, "%s.old", filename)) == -1) {
612 		r = SSH_ERR_ALLOC_FAIL;
613 		goto fail;
614 	}
615 
616 	if ((fd = mkstemp(temp)) == -1) {
617 		oerrno = errno;
618 		error_f("mkstemp: %s", strerror(oerrno));
619 		r = SSH_ERR_SYSTEM_ERROR;
620 		goto fail;
621 	}
622 	if ((ctx.out = fdopen(fd, "w")) == NULL) {
623 		oerrno = errno;
624 		close(fd);
625 		error_f("fdopen: %s", strerror(oerrno));
626 		r = SSH_ERR_SYSTEM_ERROR;
627 		goto fail;
628 	}
629 
630 	/* Remove stale/mismatching entries for the specified host */
631 	if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
632 	    HKF_WANT_PARSE_KEY, 0)) != 0) {
633 		oerrno = errno;
634 		error_fr(r, "hostkeys_foreach");
635 		goto fail;
636 	}
637 
638 	/* Re-add the requested keys */
639 	want = HKF_MATCH_HOST | (ip == NULL ? 0 : HKF_MATCH_IP);
640 	for (i = 0; i < nkeys; i++) {
641 		if (keys[i] == NULL || (want & ctx.match_keys[i]) == want)
642 			continue;
643 		if ((fp = sshkey_fingerprint(keys[i], hash_alg,
644 		    SSH_FP_DEFAULT)) == NULL) {
645 			r = SSH_ERR_ALLOC_FAIL;
646 			goto fail;
647 		}
648 		/* write host/ip */
649 		what = "";
650 		if (ctx.match_keys[i] == 0) {
651 			what = "Adding new key";
652 			if (!write_host_entry(ctx.out, host, ip,
653 			    keys[i], store_hash)) {
654 				r = SSH_ERR_INTERNAL_ERROR;
655 				goto fail;
656 			}
657 		} else if ((want & ~ctx.match_keys[i]) == HKF_MATCH_HOST) {
658 			what = "Fixing match (hostname)";
659 			if (!write_host_entry(ctx.out, host, NULL,
660 			    keys[i], store_hash)) {
661 				r = SSH_ERR_INTERNAL_ERROR;
662 				goto fail;
663 			}
664 		} else if ((want & ~ctx.match_keys[i]) == HKF_MATCH_IP) {
665 			what = "Fixing match (address)";
666 			if (!write_host_entry(ctx.out, ip, NULL,
667 			    keys[i], store_hash)) {
668 				r = SSH_ERR_INTERNAL_ERROR;
669 				goto fail;
670 			}
671 		}
672 		do_log2(loglevel, "%s%s%s for %s%s%s to %s: %s %s",
673 		    quiet ? __func__ : "", quiet ? ": " : "", what,
674 		    host, ip == NULL ? "" : ",", ip == NULL ? "" : ip, filename,
675 		    sshkey_ssh_name(keys[i]), fp);
676 		free(fp);
677 		ctx.modified = 1;
678 	}
679 	fclose(ctx.out);
680 	ctx.out = NULL;
681 
682 	if (ctx.modified) {
683 		/* Backup the original file and replace it with the temporary */
684 		if (unlink(back) == -1 && errno != ENOENT) {
685 			oerrno = errno;
686 			error_f("unlink %.100s: %s", back, strerror(errno));
687 			r = SSH_ERR_SYSTEM_ERROR;
688 			goto fail;
689 		}
690 		if (link(filename, back) == -1) {
691 			oerrno = errno;
692 			error_f("link %.100s to %.100s: %s", filename,
693 			    back, strerror(errno));
694 			r = SSH_ERR_SYSTEM_ERROR;
695 			goto fail;
696 		}
697 		if (rename(temp, filename) == -1) {
698 			oerrno = errno;
699 			error_f("rename \"%s\" to \"%s\": %s", temp,
700 			    filename, strerror(errno));
701 			r = SSH_ERR_SYSTEM_ERROR;
702 			goto fail;
703 		}
704 	} else {
705 		/* No changes made; just delete the temporary file */
706 		if (unlink(temp) != 0)
707 			error_f("unlink \"%s\": %s", temp, strerror(errno));
708 	}
709 
710 	/* success */
711 	r = 0;
712  fail:
713 	if (temp != NULL && r != 0)
714 		unlink(temp);
715 	free(temp);
716 	free(back);
717 	if (ctx.out != NULL)
718 		fclose(ctx.out);
719 	free(ctx.match_keys);
720 	umask(omask);
721 	if (r == SSH_ERR_SYSTEM_ERROR)
722 		errno = oerrno;
723 	return r;
724 }
725 
726 static int
727 match_maybe_hashed(const char *host, const char *names, int *was_hashed)
728 {
729 	int hashed = *names == HASH_DELIM, ret;
730 	char *hashed_host = NULL;
731 	size_t nlen = strlen(names);
732 
733 	if (was_hashed != NULL)
734 		*was_hashed = hashed;
735 	if (hashed) {
736 		if ((hashed_host = host_hash(host, names, nlen)) == NULL)
737 			return -1;
738 		ret = (nlen == strlen(hashed_host) &&
739 		    strncmp(hashed_host, names, nlen) == 0);
740 		free(hashed_host);
741 		return ret;
742 	}
743 	return match_hostname(host, names) == 1;
744 }
745 
746 int
747 hostkeys_foreach_file(const char *path, FILE *f, hostkeys_foreach_fn *callback,
748     void *ctx, const char *host, const char *ip, u_int options, u_int note)
749 {
750 	char *line = NULL, ktype[128];
751 	u_long linenum = 0;
752 	char *cp, *cp2;
753 	u_int kbits;
754 	int hashed;
755 	int s, r = 0;
756 	struct hostkey_foreach_line lineinfo;
757 	size_t linesize = 0, l;
758 
759 	memset(&lineinfo, 0, sizeof(lineinfo));
760 	if (host == NULL && (options & HKF_WANT_MATCH) != 0)
761 		return SSH_ERR_INVALID_ARGUMENT;
762 
763 	while (getline(&line, &linesize, f) != -1) {
764 		linenum++;
765 		line[strcspn(line, "\n")] = '\0';
766 
767 		free(lineinfo.line);
768 		sshkey_free(lineinfo.key);
769 		memset(&lineinfo, 0, sizeof(lineinfo));
770 		lineinfo.path = path;
771 		lineinfo.linenum = linenum;
772 		lineinfo.line = xstrdup(line);
773 		lineinfo.marker = MRK_NONE;
774 		lineinfo.status = HKF_STATUS_OK;
775 		lineinfo.keytype = KEY_UNSPEC;
776 		lineinfo.note = note;
777 
778 		/* Skip any leading whitespace, comments and empty lines. */
779 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
780 			;
781 		if (!*cp || *cp == '#' || *cp == '\n') {
782 			if ((options & HKF_WANT_MATCH) == 0) {
783 				lineinfo.status = HKF_STATUS_COMMENT;
784 				if ((r = callback(&lineinfo, ctx)) != 0)
785 					break;
786 			}
787 			continue;
788 		}
789 
790 		if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
791 			verbose_f("invalid marker at %s:%lu", path, linenum);
792 			if ((options & HKF_WANT_MATCH) == 0)
793 				goto bad;
794 			continue;
795 		}
796 
797 		/* Find the end of the host name portion. */
798 		for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
799 			;
800 		lineinfo.hosts = cp;
801 		*cp2++ = '\0';
802 
803 		/* Check if the host name matches. */
804 		if (host != NULL) {
805 			if ((s = match_maybe_hashed(host, lineinfo.hosts,
806 			    &hashed)) == -1) {
807 				debug2_f("%s:%ld: bad host hash \"%.32s\"",
808 				    path, linenum, lineinfo.hosts);
809 				goto bad;
810 			}
811 			if (s == 1) {
812 				lineinfo.status = HKF_STATUS_MATCHED;
813 				lineinfo.match |= HKF_MATCH_HOST |
814 				    (hashed ? HKF_MATCH_HOST_HASHED : 0);
815 			}
816 			/* Try matching IP address if supplied */
817 			if (ip != NULL) {
818 				if ((s = match_maybe_hashed(ip, lineinfo.hosts,
819 				    &hashed)) == -1) {
820 					debug2_f("%s:%ld: bad ip hash "
821 					    "\"%.32s\"", path, linenum,
822 					    lineinfo.hosts);
823 					goto bad;
824 				}
825 				if (s == 1) {
826 					lineinfo.status = HKF_STATUS_MATCHED;
827 					lineinfo.match |= HKF_MATCH_IP |
828 					    (hashed ? HKF_MATCH_IP_HASHED : 0);
829 				}
830 			}
831 			/*
832 			 * Skip this line if host matching requested and
833 			 * neither host nor address matched.
834 			 */
835 			if ((options & HKF_WANT_MATCH) != 0 &&
836 			    lineinfo.status != HKF_STATUS_MATCHED)
837 				continue;
838 		}
839 
840 		/* Got a match.  Skip host name and any following whitespace */
841 		for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
842 			;
843 		if (*cp2 == '\0' || *cp2 == '#') {
844 			debug2("%s:%ld: truncated before key type",
845 			    path, linenum);
846 			goto bad;
847 		}
848 		lineinfo.rawkey = cp = cp2;
849 
850 		if ((options & HKF_WANT_PARSE_KEY) != 0) {
851 			/*
852 			 * Extract the key from the line.  This will skip
853 			 * any leading whitespace.  Ignore badly formatted
854 			 * lines.
855 			 */
856 			if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
857 				error_f("sshkey_new failed");
858 				r = SSH_ERR_ALLOC_FAIL;
859 				break;
860 			}
861 			if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
862 				goto bad;
863 			}
864 			lineinfo.keytype = lineinfo.key->type;
865 			lineinfo.comment = cp;
866 		} else {
867 			/* Extract and parse key type */
868 			l = strcspn(lineinfo.rawkey, " \t");
869 			if (l <= 1 || l >= sizeof(ktype) ||
870 			    lineinfo.rawkey[l] == '\0')
871 				goto bad;
872 			memcpy(ktype, lineinfo.rawkey, l);
873 			ktype[l] = '\0';
874 			lineinfo.keytype = sshkey_type_from_name(ktype);
875 
876 			/*
877 			 * Assume legacy RSA1 if the first component is a short
878 			 * decimal number.
879 			 */
880 			if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
881 			    strspn(ktype, "0123456789") == l)
882 				goto bad;
883 
884 			/*
885 			 * Check that something other than whitespace follows
886 			 * the key type. This won't catch all corruption, but
887 			 * it does catch trivial truncation.
888 			 */
889 			cp2 += l; /* Skip past key type */
890 			for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
891 				;
892 			if (*cp2 == '\0' || *cp2 == '#') {
893 				debug2("%s:%ld: truncated after key type",
894 				    path, linenum);
895 				lineinfo.keytype = KEY_UNSPEC;
896 			}
897 			if (lineinfo.keytype == KEY_UNSPEC) {
898  bad:
899 				sshkey_free(lineinfo.key);
900 				lineinfo.key = NULL;
901 				lineinfo.status = HKF_STATUS_INVALID;
902 				if ((r = callback(&lineinfo, ctx)) != 0)
903 					break;
904 				continue;
905 			}
906 		}
907 		if ((r = callback(&lineinfo, ctx)) != 0)
908 			break;
909 	}
910 	sshkey_free(lineinfo.key);
911 	free(lineinfo.line);
912 	free(line);
913 	return r;
914 }
915 
916 int
917 hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
918     const char *host, const char *ip, u_int options, u_int note)
919 {
920 	FILE *f;
921 	int r, oerrno;
922 
923 	if ((f = fopen(path, "r")) == NULL)
924 		return SSH_ERR_SYSTEM_ERROR;
925 
926 	debug3_f("reading file \"%s\"", path);
927 	r = hostkeys_foreach_file(path, f, callback, ctx, host, ip,
928 	    options, note);
929 	oerrno = errno;
930 	fclose(f);
931 	errno = oerrno;
932 	return r;
933 }
934