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