xref: /openbsd-src/usr.bin/ssh/hostfile.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /* $OpenBSD: hostfile.c,v 1.78 2020/02/26 13:40:09 jsg Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Functions for manipulating the known hosts files.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  *
14  *
15  * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 
42 #include <netinet/in.h>
43 
44 #include <errno.h>
45 #include <resolv.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <stdarg.h>
50 #include <unistd.h>
51 
52 #include "xmalloc.h"
53 #include "match.h"
54 #include "sshkey.h"
55 #include "hostfile.h"
56 #include "log.h"
57 #include "misc.h"
58 #include "ssherr.h"
59 #include "digest.h"
60 #include "hmac.h"
61 
62 struct hostkeys {
63 	struct hostkey_entry *entries;
64 	u_int num_entries;
65 };
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 	static char encoded[1024];
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("%s: ssh_hmac failed", __func__);
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("%s: __b64_ntop failed", __func__);
147 
148 	snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt,
149 	    HASH_DELIM, uu_result);
150 
151 	return (encoded);
152 }
153 
154 /*
155  * Parses an RSA (number of bits, e, n) or DSA key from a string.  Moves the
156  * pointer over the key.  Skips any whitespace at the beginning and at end.
157  */
158 
159 int
160 hostfile_read_key(char **cpp, u_int *bitsp, struct sshkey *ret)
161 {
162 	char *cp;
163 
164 	/* Skip leading whitespace. */
165 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
166 		;
167 
168 	if (sshkey_read(ret, &cp) != 0)
169 		return 0;
170 
171 	/* Skip trailing whitespace. */
172 	for (; *cp == ' ' || *cp == '\t'; cp++)
173 		;
174 
175 	/* Return results. */
176 	*cpp = cp;
177 	if (bitsp != NULL)
178 		*bitsp = sshkey_size(ret);
179 	return 1;
180 }
181 
182 static HostkeyMarker
183 check_markers(char **cpp)
184 {
185 	char marker[32], *sp, *cp = *cpp;
186 	int ret = MRK_NONE;
187 
188 	while (*cp == '@') {
189 		/* Only one marker is allowed */
190 		if (ret != MRK_NONE)
191 			return MRK_ERROR;
192 		/* Markers are terminated by whitespace */
193 		if ((sp = strchr(cp, ' ')) == NULL &&
194 		    (sp = strchr(cp, '\t')) == NULL)
195 			return MRK_ERROR;
196 		/* Extract marker for comparison */
197 		if (sp <= cp + 1 || sp >= cp + sizeof(marker))
198 			return MRK_ERROR;
199 		memcpy(marker, cp, sp - cp);
200 		marker[sp - cp] = '\0';
201 		if (strcmp(marker, CA_MARKER) == 0)
202 			ret = MRK_CA;
203 		else if (strcmp(marker, REVOKE_MARKER) == 0)
204 			ret = MRK_REVOKE;
205 		else
206 			return MRK_ERROR;
207 
208 		/* Skip past marker and any whitespace that follows it */
209 		cp = sp;
210 		for (; *cp == ' ' || *cp == '\t'; cp++)
211 			;
212 	}
213 	*cpp = cp;
214 	return ret;
215 }
216 
217 struct hostkeys *
218 init_hostkeys(void)
219 {
220 	struct hostkeys *ret = xcalloc(1, sizeof(*ret));
221 
222 	ret->entries = NULL;
223 	return ret;
224 }
225 
226 struct load_callback_ctx {
227 	const char *host;
228 	u_long num_loaded;
229 	struct hostkeys *hostkeys;
230 };
231 
232 static int
233 record_hostkey(struct hostkey_foreach_line *l, void *_ctx)
234 {
235 	struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx;
236 	struct hostkeys *hostkeys = ctx->hostkeys;
237 	struct hostkey_entry *tmp;
238 
239 	if (l->status == HKF_STATUS_INVALID) {
240 		/* XXX make this verbose() in the future */
241 		debug("%s:%ld: parse error in hostkeys file",
242 		    l->path, l->linenum);
243 		return 0;
244 	}
245 
246 	debug3("%s: found %skey type %s in file %s:%lu", __func__,
247 	    l->marker == MRK_NONE ? "" :
248 	    (l->marker == MRK_CA ? "ca " : "revoked "),
249 	    sshkey_type(l->key), l->path, l->linenum);
250 	if ((tmp = recallocarray(hostkeys->entries, hostkeys->num_entries,
251 	    hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL)
252 		return SSH_ERR_ALLOC_FAIL;
253 	hostkeys->entries = tmp;
254 	hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host);
255 	hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path);
256 	hostkeys->entries[hostkeys->num_entries].line = l->linenum;
257 	hostkeys->entries[hostkeys->num_entries].key = l->key;
258 	l->key = NULL; /* steal it */
259 	hostkeys->entries[hostkeys->num_entries].marker = l->marker;
260 	hostkeys->num_entries++;
261 	ctx->num_loaded++;
262 
263 	return 0;
264 }
265 
266 void
267 load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
268 {
269 	int r;
270 	struct load_callback_ctx ctx;
271 
272 	ctx.host = host;
273 	ctx.num_loaded = 0;
274 	ctx.hostkeys = hostkeys;
275 
276 	if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host, NULL,
277 	    HKF_WANT_MATCH|HKF_WANT_PARSE_KEY)) != 0) {
278 		if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT)
279 			debug("%s: hostkeys_foreach failed for %s: %s",
280 			    __func__, path, ssh_err(r));
281 	}
282 	if (ctx.num_loaded != 0)
283 		debug3("%s: loaded %lu keys from %s", __func__,
284 		    ctx.num_loaded, host);
285 }
286 
287 void
288 free_hostkeys(struct hostkeys *hostkeys)
289 {
290 	u_int i;
291 
292 	for (i = 0; i < hostkeys->num_entries; i++) {
293 		free(hostkeys->entries[i].host);
294 		free(hostkeys->entries[i].file);
295 		sshkey_free(hostkeys->entries[i].key);
296 		explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
297 	}
298 	free(hostkeys->entries);
299 	freezero(hostkeys, sizeof(*hostkeys));
300 }
301 
302 static int
303 check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
304 {
305 	int is_cert = sshkey_is_cert(k);
306 	u_int i;
307 
308 	for (i = 0; i < hostkeys->num_entries; i++) {
309 		if (hostkeys->entries[i].marker != MRK_REVOKE)
310 			continue;
311 		if (sshkey_equal_public(k, hostkeys->entries[i].key))
312 			return -1;
313 		if (is_cert &&
314 		    sshkey_equal_public(k->cert->signature_key,
315 		    hostkeys->entries[i].key))
316 			return -1;
317 	}
318 	return 0;
319 }
320 
321 /*
322  * Match keys against a specified key, or look one up by key type.
323  *
324  * If looking for a keytype (key == NULL) and one is found then return
325  * HOST_FOUND, otherwise HOST_NEW.
326  *
327  * If looking for a key (key != NULL):
328  *  1. If the key is a cert and a matching CA is found, return HOST_OK
329  *  2. If the key is not a cert and a matching key is found, return HOST_OK
330  *  3. If no key matches but a key with a different type is found, then
331  *     return HOST_CHANGED
332  *  4. If no matching keys are found, then return HOST_NEW.
333  *
334  * Finally, check any found key is not revoked.
335  */
336 static HostStatus
337 check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
338     struct sshkey *k, int keytype, const struct hostkey_entry **found)
339 {
340 	u_int i;
341 	HostStatus end_return = HOST_NEW;
342 	int want_cert = sshkey_is_cert(k);
343 	HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
344 
345 	if (found != NULL)
346 		*found = NULL;
347 
348 	for (i = 0; i < hostkeys->num_entries; i++) {
349 		if (hostkeys->entries[i].marker != want_marker)
350 			continue;
351 		if (k == NULL) {
352 			if (hostkeys->entries[i].key->type != keytype)
353 				continue;
354 			end_return = HOST_FOUND;
355 			if (found != NULL)
356 				*found = hostkeys->entries + i;
357 			k = hostkeys->entries[i].key;
358 			break;
359 		}
360 		if (want_cert) {
361 			if (sshkey_equal_public(k->cert->signature_key,
362 			    hostkeys->entries[i].key)) {
363 				/* A matching CA exists */
364 				end_return = HOST_OK;
365 				if (found != NULL)
366 					*found = hostkeys->entries + i;
367 				break;
368 			}
369 		} else {
370 			if (sshkey_equal(k, hostkeys->entries[i].key)) {
371 				end_return = HOST_OK;
372 				if (found != NULL)
373 					*found = hostkeys->entries + i;
374 				break;
375 			}
376 			/* A non-maching key exists */
377 			end_return = HOST_CHANGED;
378 			if (found != NULL)
379 				*found = hostkeys->entries + i;
380 		}
381 	}
382 	if (check_key_not_revoked(hostkeys, k) != 0) {
383 		end_return = HOST_REVOKED;
384 		if (found != NULL)
385 			*found = NULL;
386 	}
387 	return end_return;
388 }
389 
390 HostStatus
391 check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
392     const struct hostkey_entry **found)
393 {
394 	if (key == NULL)
395 		fatal("no key to look up");
396 	return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
397 }
398 
399 int
400 lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
401     const struct hostkey_entry **found)
402 {
403 	return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
404 	    found) == HOST_FOUND);
405 }
406 
407 static int
408 write_host_entry(FILE *f, const char *host, const char *ip,
409     const struct sshkey *key, int store_hash)
410 {
411 	int r, success = 0;
412 	char *hashed_host = NULL, *lhost;
413 
414 	lhost = xstrdup(host);
415 	lowercase(lhost);
416 
417 	if (store_hash) {
418 		if ((hashed_host = host_hash(lhost, NULL, 0)) == NULL) {
419 			error("%s: host_hash failed", __func__);
420 			free(lhost);
421 			return 0;
422 		}
423 		fprintf(f, "%s ", hashed_host);
424 	} else if (ip != NULL)
425 		fprintf(f, "%s,%s ", lhost, ip);
426 	else {
427 		fprintf(f, "%s ", lhost);
428 	}
429 	free(lhost);
430 	if ((r = sshkey_write(key, f)) == 0)
431 		success = 1;
432 	else
433 		error("%s: sshkey_write failed: %s", __func__, ssh_err(r));
434 	fputc('\n', f);
435 	return success;
436 }
437 
438 /*
439  * Appends an entry to the host file.  Returns false if the entry could not
440  * be appended.
441  */
442 int
443 add_host_to_hostfile(const char *filename, const char *host,
444     const struct sshkey *key, int store_hash)
445 {
446 	FILE *f;
447 	int success;
448 
449 	if (key == NULL)
450 		return 1;	/* XXX ? */
451 	f = fopen(filename, "a");
452 	if (!f)
453 		return 0;
454 	success = write_host_entry(f, host, NULL, key, store_hash);
455 	fclose(f);
456 	return success;
457 }
458 
459 struct host_delete_ctx {
460 	FILE *out;
461 	int quiet;
462 	const char *host;
463 	int *skip_keys; /* XXX split for host/ip? might want to ensure both */
464 	struct sshkey * const *keys;
465 	size_t nkeys;
466 	int modified;
467 };
468 
469 static int
470 host_delete(struct hostkey_foreach_line *l, void *_ctx)
471 {
472 	struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
473 	int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
474 	size_t i;
475 
476 	if (l->status == HKF_STATUS_MATCHED) {
477 		if (l->marker != MRK_NONE) {
478 			/* Don't remove CA and revocation lines */
479 			fprintf(ctx->out, "%s\n", l->line);
480 			return 0;
481 		}
482 
483 		/*
484 		 * If this line contains one of the keys that we will be
485 		 * adding later, then don't change it and mark the key for
486 		 * skipping.
487 		 */
488 		for (i = 0; i < ctx->nkeys; i++) {
489 			if (sshkey_equal(ctx->keys[i], l->key)) {
490 				ctx->skip_keys[i] = 1;
491 				fprintf(ctx->out, "%s\n", l->line);
492 				debug3("%s: %s key already at %s:%ld", __func__,
493 				    sshkey_type(l->key), l->path, l->linenum);
494 				return 0;
495 			}
496 		}
497 
498 		/*
499 		 * Hostname matches and has no CA/revoke marker, delete it
500 		 * by *not* writing the line to ctx->out.
501 		 */
502 		do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
503 		    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
504 		    l->path, l->linenum, sshkey_type(l->key), ctx->host);
505 		ctx->modified = 1;
506 		return 0;
507 	}
508 	/* Retain non-matching hosts and invalid lines when deleting */
509 	if (l->status == HKF_STATUS_INVALID) {
510 		do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
511 		    ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
512 		    l->path, l->linenum);
513 	}
514 	fprintf(ctx->out, "%s\n", l->line);
515 	return 0;
516 }
517 
518 int
519 hostfile_replace_entries(const char *filename, const char *host, const char *ip,
520     struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
521 {
522 	int r, fd, oerrno = 0;
523 	int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
524 	struct host_delete_ctx ctx;
525 	char *fp, *temp = NULL, *back = NULL;
526 	mode_t omask;
527 	size_t i;
528 
529 	omask = umask(077);
530 
531 	memset(&ctx, 0, sizeof(ctx));
532 	ctx.host = host;
533 	ctx.quiet = quiet;
534 	if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
535 		return SSH_ERR_ALLOC_FAIL;
536 	ctx.keys = keys;
537 	ctx.nkeys = nkeys;
538 	ctx.modified = 0;
539 
540 	/*
541 	 * Prepare temporary file for in-place deletion.
542 	 */
543 	if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) == -1 ||
544 	    (r = asprintf(&back, "%s.old", filename)) == -1) {
545 		r = SSH_ERR_ALLOC_FAIL;
546 		goto fail;
547 	}
548 
549 	if ((fd = mkstemp(temp)) == -1) {
550 		oerrno = errno;
551 		error("%s: mkstemp: %s", __func__, strerror(oerrno));
552 		r = SSH_ERR_SYSTEM_ERROR;
553 		goto fail;
554 	}
555 	if ((ctx.out = fdopen(fd, "w")) == NULL) {
556 		oerrno = errno;
557 		close(fd);
558 		error("%s: fdopen: %s", __func__, strerror(oerrno));
559 		r = SSH_ERR_SYSTEM_ERROR;
560 		goto fail;
561 	}
562 
563 	/* Remove all entries for the specified host from the file */
564 	if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
565 	    HKF_WANT_PARSE_KEY)) != 0) {
566 		oerrno = errno;
567 		error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
568 		goto fail;
569 	}
570 
571 	/* Add the requested keys */
572 	for (i = 0; i < nkeys; i++) {
573 		if (ctx.skip_keys[i])
574 			continue;
575 		if ((fp = sshkey_fingerprint(keys[i], hash_alg,
576 		    SSH_FP_DEFAULT)) == NULL) {
577 			r = SSH_ERR_ALLOC_FAIL;
578 			goto fail;
579 		}
580 		do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s",
581 		    quiet ? __func__ : "", quiet ? ": " : "", host, filename,
582 		    sshkey_ssh_name(keys[i]), fp);
583 		free(fp);
584 		if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) {
585 			r = SSH_ERR_INTERNAL_ERROR;
586 			goto fail;
587 		}
588 		ctx.modified = 1;
589 	}
590 	fclose(ctx.out);
591 	ctx.out = NULL;
592 
593 	if (ctx.modified) {
594 		/* Backup the original file and replace it with the temporary */
595 		if (unlink(back) == -1 && errno != ENOENT) {
596 			oerrno = errno;
597 			error("%s: unlink %.100s: %s", __func__,
598 			    back, strerror(errno));
599 			r = SSH_ERR_SYSTEM_ERROR;
600 			goto fail;
601 		}
602 		if (link(filename, back) == -1) {
603 			oerrno = errno;
604 			error("%s: link %.100s to %.100s: %s", __func__,
605 			    filename, back, strerror(errno));
606 			r = SSH_ERR_SYSTEM_ERROR;
607 			goto fail;
608 		}
609 		if (rename(temp, filename) == -1) {
610 			oerrno = errno;
611 			error("%s: rename \"%s\" to \"%s\": %s", __func__,
612 			    temp, filename, strerror(errno));
613 			r = SSH_ERR_SYSTEM_ERROR;
614 			goto fail;
615 		}
616 	} else {
617 		/* No changes made; just delete the temporary file */
618 		if (unlink(temp) != 0)
619 			error("%s: unlink \"%s\": %s", __func__,
620 			    temp, strerror(errno));
621 	}
622 
623 	/* success */
624 	r = 0;
625  fail:
626 	if (temp != NULL && r != 0)
627 		unlink(temp);
628 	free(temp);
629 	free(back);
630 	if (ctx.out != NULL)
631 		fclose(ctx.out);
632 	free(ctx.skip_keys);
633 	umask(omask);
634 	if (r == SSH_ERR_SYSTEM_ERROR)
635 		errno = oerrno;
636 	return r;
637 }
638 
639 static int
640 match_maybe_hashed(const char *host, const char *names, int *was_hashed)
641 {
642 	int hashed = *names == HASH_DELIM;
643 	const char *hashed_host;
644 	size_t nlen = strlen(names);
645 
646 	if (was_hashed != NULL)
647 		*was_hashed = hashed;
648 	if (hashed) {
649 		if ((hashed_host = host_hash(host, names, nlen)) == NULL)
650 			return -1;
651 		return nlen == strlen(hashed_host) &&
652 		    strncmp(hashed_host, names, nlen) == 0;
653 	}
654 	return match_hostname(host, names) == 1;
655 }
656 
657 int
658 hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
659     const char *host, const char *ip, u_int options)
660 {
661 	FILE *f;
662 	char *line = NULL, ktype[128];
663 	u_long linenum = 0;
664 	char *cp, *cp2;
665 	u_int kbits;
666 	int hashed;
667 	int s, r = 0;
668 	struct hostkey_foreach_line lineinfo;
669 	size_t linesize = 0, l;
670 
671 	memset(&lineinfo, 0, sizeof(lineinfo));
672 	if (host == NULL && (options & HKF_WANT_MATCH) != 0)
673 		return SSH_ERR_INVALID_ARGUMENT;
674 	if ((f = fopen(path, "r")) == NULL)
675 		return SSH_ERR_SYSTEM_ERROR;
676 
677 	debug3("%s: reading file \"%s\"", __func__, path);
678 	while (getline(&line, &linesize, f) != -1) {
679 		linenum++;
680 		line[strcspn(line, "\n")] = '\0';
681 
682 		free(lineinfo.line);
683 		sshkey_free(lineinfo.key);
684 		memset(&lineinfo, 0, sizeof(lineinfo));
685 		lineinfo.path = path;
686 		lineinfo.linenum = linenum;
687 		lineinfo.line = xstrdup(line);
688 		lineinfo.marker = MRK_NONE;
689 		lineinfo.status = HKF_STATUS_OK;
690 		lineinfo.keytype = KEY_UNSPEC;
691 
692 		/* Skip any leading whitespace, comments and empty lines. */
693 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
694 			;
695 		if (!*cp || *cp == '#' || *cp == '\n') {
696 			if ((options & HKF_WANT_MATCH) == 0) {
697 				lineinfo.status = HKF_STATUS_COMMENT;
698 				if ((r = callback(&lineinfo, ctx)) != 0)
699 					break;
700 			}
701 			continue;
702 		}
703 
704 		if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
705 			verbose("%s: invalid marker at %s:%lu",
706 			    __func__, path, linenum);
707 			if ((options & HKF_WANT_MATCH) == 0)
708 				goto bad;
709 			continue;
710 		}
711 
712 		/* Find the end of the host name portion. */
713 		for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
714 			;
715 		lineinfo.hosts = cp;
716 		*cp2++ = '\0';
717 
718 		/* Check if the host name matches. */
719 		if (host != NULL) {
720 			if ((s = match_maybe_hashed(host, lineinfo.hosts,
721 			    &hashed)) == -1) {
722 				debug2("%s: %s:%ld: bad host hash \"%.32s\"",
723 				    __func__, path, linenum, lineinfo.hosts);
724 				goto bad;
725 			}
726 			if (s == 1) {
727 				lineinfo.status = HKF_STATUS_MATCHED;
728 				lineinfo.match |= HKF_MATCH_HOST |
729 				    (hashed ? HKF_MATCH_HOST_HASHED : 0);
730 			}
731 			/* Try matching IP address if supplied */
732 			if (ip != NULL) {
733 				if ((s = match_maybe_hashed(ip, lineinfo.hosts,
734 				    &hashed)) == -1) {
735 					debug2("%s: %s:%ld: bad ip hash "
736 					    "\"%.32s\"", __func__, path,
737 					    linenum, lineinfo.hosts);
738 					goto bad;
739 				}
740 				if (s == 1) {
741 					lineinfo.status = HKF_STATUS_MATCHED;
742 					lineinfo.match |= HKF_MATCH_IP |
743 					    (hashed ? HKF_MATCH_IP_HASHED : 0);
744 				}
745 			}
746 			/*
747 			 * Skip this line if host matching requested and
748 			 * neither host nor address matched.
749 			 */
750 			if ((options & HKF_WANT_MATCH) != 0 &&
751 			    lineinfo.status != HKF_STATUS_MATCHED)
752 				continue;
753 		}
754 
755 		/* Got a match.  Skip host name and any following whitespace */
756 		for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
757 			;
758 		if (*cp2 == '\0' || *cp2 == '#') {
759 			debug2("%s:%ld: truncated before key type",
760 			    path, linenum);
761 			goto bad;
762 		}
763 		lineinfo.rawkey = cp = cp2;
764 
765 		if ((options & HKF_WANT_PARSE_KEY) != 0) {
766 			/*
767 			 * Extract the key from the line.  This will skip
768 			 * any leading whitespace.  Ignore badly formatted
769 			 * lines.
770 			 */
771 			if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
772 				error("%s: sshkey_new failed", __func__);
773 				r = SSH_ERR_ALLOC_FAIL;
774 				break;
775 			}
776 			if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
777 				goto bad;
778 			}
779 			lineinfo.keytype = lineinfo.key->type;
780 			lineinfo.comment = cp;
781 		} else {
782 			/* Extract and parse key type */
783 			l = strcspn(lineinfo.rawkey, " \t");
784 			if (l <= 1 || l >= sizeof(ktype) ||
785 			    lineinfo.rawkey[l] == '\0')
786 				goto bad;
787 			memcpy(ktype, lineinfo.rawkey, l);
788 			ktype[l] = '\0';
789 			lineinfo.keytype = sshkey_type_from_name(ktype);
790 
791 			/*
792 			 * Assume legacy RSA1 if the first component is a short
793 			 * decimal number.
794 			 */
795 			if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
796 			    strspn(ktype, "0123456789") == l)
797 				goto bad;
798 
799 			/*
800 			 * Check that something other than whitespace follows
801 			 * the key type. This won't catch all corruption, but
802 			 * it does catch trivial truncation.
803 			 */
804 			cp2 += l; /* Skip past key type */
805 			for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
806 				;
807 			if (*cp2 == '\0' || *cp2 == '#') {
808 				debug2("%s:%ld: truncated after key type",
809 				    path, linenum);
810 				lineinfo.keytype = KEY_UNSPEC;
811 			}
812 			if (lineinfo.keytype == KEY_UNSPEC) {
813  bad:
814 				sshkey_free(lineinfo.key);
815 				lineinfo.key = NULL;
816 				lineinfo.status = HKF_STATUS_INVALID;
817 				if ((r = callback(&lineinfo, ctx)) != 0)
818 					break;
819 				continue;
820 			}
821 		}
822 		if ((r = callback(&lineinfo, ctx)) != 0)
823 			break;
824 	}
825 	sshkey_free(lineinfo.key);
826 	free(lineinfo.line);
827 	free(line);
828 	fclose(f);
829 	return r;
830 }
831