xref: /openssh-portable/hostfile.c (revision 32b2502a)
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 #ifdef WITH_SELINUX
475 		ssh_selinux_setfscreatecon(dotsshdir);
476 #endif
477 		if (mkdir(dotsshdir, 0700) == -1)
478 			error("Could not create directory '%.200s' (%s).",
479 			    dotsshdir, strerror(errno));
480 		else if (notify)
481 			logit("Created directory '%s'.", dotsshdir);
482 #ifdef WITH_SELINUX
483 		ssh_selinux_setfscreatecon(NULL);
484 #endif
485 	}
486 	free(dotsshdir);
487 }
488 
489 /*
490  * Appends an entry to the host file.  Returns false if the entry could not
491  * be appended.
492  */
493 int
494 add_host_to_hostfile(const char *filename, const char *host,
495     const struct sshkey *key, int store_hash)
496 {
497 	FILE *f;
498 	int success;
499 
500 	if (key == NULL)
501 		return 1;	/* XXX ? */
502 	hostfile_create_user_ssh_dir(filename, 0);
503 	f = fopen(filename, "a");
504 	if (!f)
505 		return 0;
506 	success = write_host_entry(f, host, NULL, key, store_hash);
507 	fclose(f);
508 	return success;
509 }
510 
511 struct host_delete_ctx {
512 	FILE *out;
513 	int quiet;
514 	const char *host;
515 	int *skip_keys; /* XXX split for host/ip? might want to ensure both */
516 	struct sshkey * const *keys;
517 	size_t nkeys;
518 	int modified;
519 };
520 
521 static int
522 host_delete(struct hostkey_foreach_line *l, void *_ctx)
523 {
524 	struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
525 	int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
526 	size_t i;
527 
528 	if (l->status == HKF_STATUS_MATCHED) {
529 		if (l->marker != MRK_NONE) {
530 			/* Don't remove CA and revocation lines */
531 			fprintf(ctx->out, "%s\n", l->line);
532 			return 0;
533 		}
534 
535 		/*
536 		 * If this line contains one of the keys that we will be
537 		 * adding later, then don't change it and mark the key for
538 		 * skipping.
539 		 */
540 		for (i = 0; i < ctx->nkeys; i++) {
541 			if (sshkey_equal(ctx->keys[i], l->key)) {
542 				ctx->skip_keys[i] = 1;
543 				fprintf(ctx->out, "%s\n", l->line);
544 				debug3("%s: %s key already at %s:%ld", __func__,
545 				    sshkey_type(l->key), l->path, l->linenum);
546 				return 0;
547 			}
548 		}
549 
550 		/*
551 		 * Hostname matches and has no CA/revoke marker, delete it
552 		 * by *not* writing the line to ctx->out.
553 		 */
554 		do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
555 		    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
556 		    l->path, l->linenum, sshkey_type(l->key), ctx->host);
557 		ctx->modified = 1;
558 		return 0;
559 	}
560 	/* Retain non-matching hosts and invalid lines when deleting */
561 	if (l->status == HKF_STATUS_INVALID) {
562 		do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
563 		    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
564 		    l->path, l->linenum);
565 	}
566 	fprintf(ctx->out, "%s\n", l->line);
567 	return 0;
568 }
569 
570 int
571 hostfile_replace_entries(const char *filename, const char *host, const char *ip,
572     struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
573 {
574 	int r, fd, oerrno = 0;
575 	int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
576 	struct host_delete_ctx ctx;
577 	char *fp, *temp = NULL, *back = NULL;
578 	mode_t omask;
579 	size_t i;
580 
581 	omask = umask(077);
582 
583 	memset(&ctx, 0, sizeof(ctx));
584 	ctx.host = host;
585 	ctx.quiet = quiet;
586 	if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
587 		return SSH_ERR_ALLOC_FAIL;
588 	ctx.keys = keys;
589 	ctx.nkeys = nkeys;
590 	ctx.modified = 0;
591 
592 	/*
593 	 * Prepare temporary file for in-place deletion.
594 	 */
595 	if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) == -1 ||
596 	    (r = asprintf(&back, "%s.old", filename)) == -1) {
597 		r = SSH_ERR_ALLOC_FAIL;
598 		goto fail;
599 	}
600 
601 	if ((fd = mkstemp(temp)) == -1) {
602 		oerrno = errno;
603 		error("%s: mkstemp: %s", __func__, strerror(oerrno));
604 		r = SSH_ERR_SYSTEM_ERROR;
605 		goto fail;
606 	}
607 	if ((ctx.out = fdopen(fd, "w")) == NULL) {
608 		oerrno = errno;
609 		close(fd);
610 		error("%s: fdopen: %s", __func__, strerror(oerrno));
611 		r = SSH_ERR_SYSTEM_ERROR;
612 		goto fail;
613 	}
614 
615 	/* Remove all entries for the specified host from the file */
616 	if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
617 	    HKF_WANT_PARSE_KEY)) != 0) {
618 		oerrno = errno;
619 		error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
620 		goto fail;
621 	}
622 
623 	/* Add the requested keys */
624 	for (i = 0; i < nkeys; i++) {
625 		if (ctx.skip_keys[i])
626 			continue;
627 		if ((fp = sshkey_fingerprint(keys[i], hash_alg,
628 		    SSH_FP_DEFAULT)) == NULL) {
629 			r = SSH_ERR_ALLOC_FAIL;
630 			goto fail;
631 		}
632 		do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s",
633 		    quiet ? __func__ : "", quiet ? ": " : "", host, filename,
634 		    sshkey_ssh_name(keys[i]), fp);
635 		free(fp);
636 		if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) {
637 			r = SSH_ERR_INTERNAL_ERROR;
638 			goto fail;
639 		}
640 		ctx.modified = 1;
641 	}
642 	fclose(ctx.out);
643 	ctx.out = NULL;
644 
645 	if (ctx.modified) {
646 		/* Backup the original file and replace it with the temporary */
647 		if (unlink(back) == -1 && errno != ENOENT) {
648 			oerrno = errno;
649 			error("%s: unlink %.100s: %s", __func__,
650 			    back, strerror(errno));
651 			r = SSH_ERR_SYSTEM_ERROR;
652 			goto fail;
653 		}
654 		if (link(filename, back) == -1) {
655 			oerrno = errno;
656 			error("%s: link %.100s to %.100s: %s", __func__,
657 			    filename, back, strerror(errno));
658 			r = SSH_ERR_SYSTEM_ERROR;
659 			goto fail;
660 		}
661 		if (rename(temp, filename) == -1) {
662 			oerrno = errno;
663 			error("%s: rename \"%s\" to \"%s\": %s", __func__,
664 			    temp, filename, strerror(errno));
665 			r = SSH_ERR_SYSTEM_ERROR;
666 			goto fail;
667 		}
668 	} else {
669 		/* No changes made; just delete the temporary file */
670 		if (unlink(temp) != 0)
671 			error("%s: unlink \"%s\": %s", __func__,
672 			    temp, strerror(errno));
673 	}
674 
675 	/* success */
676 	r = 0;
677  fail:
678 	if (temp != NULL && r != 0)
679 		unlink(temp);
680 	free(temp);
681 	free(back);
682 	if (ctx.out != NULL)
683 		fclose(ctx.out);
684 	free(ctx.skip_keys);
685 	umask(omask);
686 	if (r == SSH_ERR_SYSTEM_ERROR)
687 		errno = oerrno;
688 	return r;
689 }
690 
691 static int
692 match_maybe_hashed(const char *host, const char *names, int *was_hashed)
693 {
694 	int hashed = *names == HASH_DELIM;
695 	const char *hashed_host;
696 	size_t nlen = strlen(names);
697 
698 	if (was_hashed != NULL)
699 		*was_hashed = hashed;
700 	if (hashed) {
701 		if ((hashed_host = host_hash(host, names, nlen)) == NULL)
702 			return -1;
703 		return nlen == strlen(hashed_host) &&
704 		    strncmp(hashed_host, names, nlen) == 0;
705 	}
706 	return match_hostname(host, names) == 1;
707 }
708 
709 int
710 hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
711     const char *host, const char *ip, u_int options)
712 {
713 	FILE *f;
714 	char *line = NULL, ktype[128];
715 	u_long linenum = 0;
716 	char *cp, *cp2;
717 	u_int kbits;
718 	int hashed;
719 	int s, r = 0;
720 	struct hostkey_foreach_line lineinfo;
721 	size_t linesize = 0, l;
722 
723 	memset(&lineinfo, 0, sizeof(lineinfo));
724 	if (host == NULL && (options & HKF_WANT_MATCH) != 0)
725 		return SSH_ERR_INVALID_ARGUMENT;
726 	if ((f = fopen(path, "r")) == NULL)
727 		return SSH_ERR_SYSTEM_ERROR;
728 
729 	debug3("%s: reading file \"%s\"", __func__, path);
730 	while (getline(&line, &linesize, f) != -1) {
731 		linenum++;
732 		line[strcspn(line, "\n")] = '\0';
733 
734 		free(lineinfo.line);
735 		sshkey_free(lineinfo.key);
736 		memset(&lineinfo, 0, sizeof(lineinfo));
737 		lineinfo.path = path;
738 		lineinfo.linenum = linenum;
739 		lineinfo.line = xstrdup(line);
740 		lineinfo.marker = MRK_NONE;
741 		lineinfo.status = HKF_STATUS_OK;
742 		lineinfo.keytype = KEY_UNSPEC;
743 
744 		/* Skip any leading whitespace, comments and empty lines. */
745 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
746 			;
747 		if (!*cp || *cp == '#' || *cp == '\n') {
748 			if ((options & HKF_WANT_MATCH) == 0) {
749 				lineinfo.status = HKF_STATUS_COMMENT;
750 				if ((r = callback(&lineinfo, ctx)) != 0)
751 					break;
752 			}
753 			continue;
754 		}
755 
756 		if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
757 			verbose("%s: invalid marker at %s:%lu",
758 			    __func__, path, linenum);
759 			if ((options & HKF_WANT_MATCH) == 0)
760 				goto bad;
761 			continue;
762 		}
763 
764 		/* Find the end of the host name portion. */
765 		for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
766 			;
767 		lineinfo.hosts = cp;
768 		*cp2++ = '\0';
769 
770 		/* Check if the host name matches. */
771 		if (host != NULL) {
772 			if ((s = match_maybe_hashed(host, lineinfo.hosts,
773 			    &hashed)) == -1) {
774 				debug2("%s: %s:%ld: bad host hash \"%.32s\"",
775 				    __func__, path, linenum, lineinfo.hosts);
776 				goto bad;
777 			}
778 			if (s == 1) {
779 				lineinfo.status = HKF_STATUS_MATCHED;
780 				lineinfo.match |= HKF_MATCH_HOST |
781 				    (hashed ? HKF_MATCH_HOST_HASHED : 0);
782 			}
783 			/* Try matching IP address if supplied */
784 			if (ip != NULL) {
785 				if ((s = match_maybe_hashed(ip, lineinfo.hosts,
786 				    &hashed)) == -1) {
787 					debug2("%s: %s:%ld: bad ip hash "
788 					    "\"%.32s\"", __func__, path,
789 					    linenum, lineinfo.hosts);
790 					goto bad;
791 				}
792 				if (s == 1) {
793 					lineinfo.status = HKF_STATUS_MATCHED;
794 					lineinfo.match |= HKF_MATCH_IP |
795 					    (hashed ? HKF_MATCH_IP_HASHED : 0);
796 				}
797 			}
798 			/*
799 			 * Skip this line if host matching requested and
800 			 * neither host nor address matched.
801 			 */
802 			if ((options & HKF_WANT_MATCH) != 0 &&
803 			    lineinfo.status != HKF_STATUS_MATCHED)
804 				continue;
805 		}
806 
807 		/* Got a match.  Skip host name and any following whitespace */
808 		for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
809 			;
810 		if (*cp2 == '\0' || *cp2 == '#') {
811 			debug2("%s:%ld: truncated before key type",
812 			    path, linenum);
813 			goto bad;
814 		}
815 		lineinfo.rawkey = cp = cp2;
816 
817 		if ((options & HKF_WANT_PARSE_KEY) != 0) {
818 			/*
819 			 * Extract the key from the line.  This will skip
820 			 * any leading whitespace.  Ignore badly formatted
821 			 * lines.
822 			 */
823 			if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
824 				error("%s: sshkey_new failed", __func__);
825 				r = SSH_ERR_ALLOC_FAIL;
826 				break;
827 			}
828 			if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
829 				goto bad;
830 			}
831 			lineinfo.keytype = lineinfo.key->type;
832 			lineinfo.comment = cp;
833 		} else {
834 			/* Extract and parse key type */
835 			l = strcspn(lineinfo.rawkey, " \t");
836 			if (l <= 1 || l >= sizeof(ktype) ||
837 			    lineinfo.rawkey[l] == '\0')
838 				goto bad;
839 			memcpy(ktype, lineinfo.rawkey, l);
840 			ktype[l] = '\0';
841 			lineinfo.keytype = sshkey_type_from_name(ktype);
842 
843 			/*
844 			 * Assume legacy RSA1 if the first component is a short
845 			 * decimal number.
846 			 */
847 			if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
848 			    strspn(ktype, "0123456789") == l)
849 				goto bad;
850 
851 			/*
852 			 * Check that something other than whitespace follows
853 			 * the key type. This won't catch all corruption, but
854 			 * it does catch trivial truncation.
855 			 */
856 			cp2 += l; /* Skip past key type */
857 			for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
858 				;
859 			if (*cp2 == '\0' || *cp2 == '#') {
860 				debug2("%s:%ld: truncated after key type",
861 				    path, linenum);
862 				lineinfo.keytype = KEY_UNSPEC;
863 			}
864 			if (lineinfo.keytype == KEY_UNSPEC) {
865  bad:
866 				sshkey_free(lineinfo.key);
867 				lineinfo.key = NULL;
868 				lineinfo.status = HKF_STATUS_INVALID;
869 				if ((r = callback(&lineinfo, ctx)) != 0)
870 					break;
871 				continue;
872 			}
873 		}
874 		if ((r = callback(&lineinfo, ctx)) != 0)
875 			break;
876 	}
877 	sshkey_free(lineinfo.key);
878 	free(lineinfo.line);
879 	free(line);
880 	fclose(f);
881 	return r;
882 }
883