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