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