hostfile.c revision 1.24 1 /* $NetBSD: hostfile.c,v 1.24 2025/10/11 15:45:06 christos Exp $ */
2 /* $OpenBSD: hostfile.c,v 1.99 2025/05/06 05:40:56 djm Exp $ */
3
4 /*
5 * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
6 * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
7 * All rights reserved
8 * Functions for manipulating the known hosts files.
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 *
16 *
17 * Copyright (c) 1999, 2000 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Niels Provos. All rights reserved.
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 */
40
41 #include "includes.h"
42 __RCSID("$NetBSD: hostfile.c,v 1.24 2025/10/11 15:45:06 christos Exp $");
43 #include <sys/types.h>
44 #include <sys/stat.h>
45
46 #include <netinet/in.h>
47
48 #include <errno.h>
49 #include <resolv.h>
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.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 "pathnames.h"
63 #include "ssherr.h"
64 #include "digest.h"
65 #include "hmac.h"
66 #include "sshbuf.h"
67
68 /* XXX hmac is too easy to dictionary attack; use bcrypt? */
69
70 static int
71 extract_salt(const char *s, u_int l, u_char *salt, size_t salt_len)
72 {
73 char *p, *b64salt;
74 u_int b64len;
75 int ret;
76
77 if (l < sizeof(HASH_MAGIC) - 1) {
78 debug2("extract_salt: string too short");
79 return (-1);
80 }
81 if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) {
82 debug2("extract_salt: invalid magic identifier");
83 return (-1);
84 }
85 s += sizeof(HASH_MAGIC) - 1;
86 l -= sizeof(HASH_MAGIC) - 1;
87 if ((p = memchr(s, HASH_DELIM, l)) == NULL) {
88 debug2("extract_salt: missing salt termination character");
89 return (-1);
90 }
91
92 b64len = p - s;
93 /* Sanity check */
94 if (b64len == 0 || b64len > 1024) {
95 debug2("extract_salt: bad encoded salt length %u", b64len);
96 return (-1);
97 }
98 b64salt = xmalloc(1 + b64len);
99 memcpy(b64salt, s, b64len);
100 b64salt[b64len] = '\0';
101
102 ret = __b64_pton(b64salt, salt, salt_len);
103 free(b64salt);
104 if (ret == -1) {
105 debug2("extract_salt: salt decode error");
106 return (-1);
107 }
108 if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) {
109 debug2("extract_salt: expected salt len %zd, got %d",
110 ssh_hmac_bytes(SSH_DIGEST_SHA1), ret);
111 return (-1);
112 }
113
114 return (0);
115 }
116
117 char *
118 host_hash(const char *host, const char *name_from_hostfile, u_int src_len)
119 {
120 struct ssh_hmac_ctx *ctx;
121 u_char salt[256], result[256];
122 char uu_salt[512], uu_result[512];
123 char *encoded = NULL;
124 u_int len;
125
126 len = ssh_digest_bytes(SSH_DIGEST_SHA1);
127
128 if (name_from_hostfile == NULL) {
129 /* Create new salt */
130 arc4random_buf(salt, len);
131 } else {
132 /* Extract salt from known host entry */
133 if (extract_salt(name_from_hostfile, src_len, salt,
134 sizeof(salt)) == -1)
135 return (NULL);
136 }
137
138 if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL ||
139 ssh_hmac_init(ctx, salt, len) < 0 ||
140 ssh_hmac_update(ctx, host, strlen(host)) < 0 ||
141 ssh_hmac_final(ctx, result, sizeof(result)))
142 fatal_f("ssh_hmac failed");
143 ssh_hmac_free(ctx);
144
145 if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
146 __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
147 fatal_f("__b64_ntop failed");
148 xasprintf(&encoded, "%s%s%c%s", HASH_MAGIC, uu_salt, HASH_DELIM,
149 uu_result);
150
151 return (encoded);
152 }
153
154 /*
155 * Parses an RSA key from a string. Moves the pointer over the key.
156 * 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_f("found %skey type %s in file %s:%lu",
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->entries[hostkeys->num_entries].note = l->note;
261 hostkeys->num_entries++;
262 ctx->num_loaded++;
263
264 return 0;
265 }
266
267 void
268 load_hostkeys_file(struct hostkeys *hostkeys, const char *host,
269 const char *path, FILE *f, u_int note)
270 {
271 int r;
272 struct load_callback_ctx ctx;
273
274 ctx.host = host;
275 ctx.num_loaded = 0;
276 ctx.hostkeys = hostkeys;
277
278 if ((r = hostkeys_foreach_file(path, f, record_hostkey, &ctx, host,
279 NULL, HKF_WANT_MATCH|HKF_WANT_PARSE_KEY, note)) != 0) {
280 if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT)
281 debug_fr(r, "hostkeys_foreach failed for %s", path);
282 }
283 if (ctx.num_loaded != 0)
284 debug3_f("loaded %lu keys from %s", ctx.num_loaded, host);
285 }
286
287 void
288 load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path,
289 u_int note)
290 {
291 FILE *f;
292
293 if ((f = fopen(path, "r")) == NULL) {
294 debug_f("fopen %s: %s", path, strerror(errno));
295 return;
296 }
297
298 load_hostkeys_file(hostkeys, host, path, f, note);
299 fclose(f);
300 }
301
302 void
303 free_hostkeys(struct hostkeys *hostkeys)
304 {
305 u_int i;
306
307 for (i = 0; i < hostkeys->num_entries; i++) {
308 free(hostkeys->entries[i].host);
309 free(hostkeys->entries[i].file);
310 sshkey_free(hostkeys->entries[i].key);
311 explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
312 }
313 free(hostkeys->entries);
314 freezero(hostkeys, sizeof(*hostkeys));
315 }
316
317 static int
318 check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
319 {
320 int is_cert = sshkey_is_cert(k);
321 u_int i;
322
323 for (i = 0; i < hostkeys->num_entries; i++) {
324 if (hostkeys->entries[i].marker != MRK_REVOKE)
325 continue;
326 if (sshkey_equal_public(k, hostkeys->entries[i].key))
327 return -1;
328 if (is_cert && k != NULL &&
329 sshkey_equal_public(k->cert->signature_key,
330 hostkeys->entries[i].key))
331 return -1;
332 }
333 return 0;
334 }
335
336 /*
337 * Match keys against a specified key, or look one up by key type.
338 *
339 * If looking for a keytype (key == NULL) and one is found then return
340 * HOST_FOUND, otherwise HOST_NEW.
341 *
342 * If looking for a key (key != NULL):
343 * 1. If the key is a cert and a matching CA is found, return HOST_OK
344 * 2. If the key is not a cert and a matching key is found, return HOST_OK
345 * 3. If no key matches but a key with a different type is found, then
346 * return HOST_CHANGED
347 * 4. If no matching keys are found, then return HOST_NEW.
348 *
349 * Finally, check any found key is not revoked.
350 */
351 static HostStatus
352 check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
353 struct sshkey *k, int keytype, int nid, const struct hostkey_entry **found)
354 {
355 u_int i;
356 HostStatus end_return = HOST_NEW;
357 int want_cert = sshkey_is_cert(k);
358 HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
359
360 if (found != NULL)
361 *found = NULL;
362
363 for (i = 0; i < hostkeys->num_entries; i++) {
364 if (hostkeys->entries[i].marker != want_marker)
365 continue;
366 if (k == NULL) {
367 if (hostkeys->entries[i].key->type != keytype)
368 continue;
369 if (nid != -1 &&
370 sshkey_type_plain(keytype) == KEY_ECDSA &&
371 hostkeys->entries[i].key->ecdsa_nid != nid)
372 continue;
373 end_return = HOST_FOUND;
374 if (found != NULL)
375 *found = hostkeys->entries + i;
376 k = hostkeys->entries[i].key;
377 break;
378 }
379 if (want_cert) {
380 if (sshkey_equal_public(k->cert->signature_key,
381 hostkeys->entries[i].key)) {
382 /* A matching CA exists */
383 end_return = HOST_OK;
384 if (found != NULL)
385 *found = hostkeys->entries + i;
386 break;
387 }
388 } else {
389 if (sshkey_equal(k, hostkeys->entries[i].key)) {
390 end_return = HOST_OK;
391 if (found != NULL)
392 *found = hostkeys->entries + i;
393 break;
394 }
395 /* A non-matching key exists */
396 end_return = HOST_CHANGED;
397 if (found != NULL)
398 *found = hostkeys->entries + i;
399 }
400 }
401 if (check_key_not_revoked(hostkeys, k) != 0) {
402 end_return = HOST_REVOKED;
403 if (found != NULL)
404 *found = NULL;
405 }
406 return end_return;
407 }
408
409 HostStatus
410 check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
411 const struct hostkey_entry **found)
412 {
413 if (key == NULL)
414 fatal("no key to look up");
415 return check_hostkeys_by_key_or_type(hostkeys, key, 0, -1, found);
416 }
417
418 int
419 lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype, int nid,
420 const struct hostkey_entry **found)
421 {
422 return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype, nid,
423 found) == HOST_FOUND);
424 }
425
426 int
427 lookup_marker_in_hostkeys(struct hostkeys *hostkeys, int want_marker)
428 {
429 u_int i;
430
431 for (i = 0; i < hostkeys->num_entries; i++) {
432 if (hostkeys->entries[i].marker == (HostkeyMarker)want_marker)
433 return 1;
434 }
435 return 0;
436 }
437
438 static int
439 format_host_entry(struct sshbuf *entry, const char *host, const char *ip,
440 const struct sshkey *key, int store_hash)
441 {
442 int r, success = 0;
443 char *hashed_host = NULL, *lhost;
444
445 lhost = xstrdup(host);
446 lowercase(lhost);
447
448 if (store_hash) {
449 if ((hashed_host = host_hash(lhost, NULL, 0)) == NULL) {
450 error_f("host_hash failed");
451 free(lhost);
452 return 0;
453 }
454 if ((r = sshbuf_putf(entry, "%s ", hashed_host)) != 0)
455 fatal_fr(r, "sshbuf_putf");
456 } else if (ip != NULL) {
457 if ((r = sshbuf_putf(entry, "%s,%s ", lhost, ip)) != 0)
458 fatal_fr(r, "sshbuf_putf");
459 } else {
460 if ((r = sshbuf_putf(entry, "%s ", lhost)) != 0)
461 fatal_fr(r, "sshbuf_putf");
462 }
463 free(hashed_host);
464 free(lhost);
465 if ((r = sshkey_format_text(key, entry)) == 0)
466 success = 1;
467 else
468 error_fr(r, "sshkey_write");
469 if ((r = sshbuf_putf(entry, "\n")) != 0)
470 fatal_fr(r, "sshbuf_putf");
471
472 /* If hashing is enabled, the IP address needs to go on its own line */
473 if (success && store_hash && ip != NULL)
474 success = format_host_entry(entry, ip, NULL, key, 1);
475 return success;
476 }
477
478 static int
479 write_host_entry(FILE *f, const char *host, const char *ip,
480 const struct sshkey *key, int store_hash)
481 {
482 int r, success = 0;
483 struct sshbuf *entry = NULL;
484
485 if ((entry = sshbuf_new()) == NULL)
486 fatal_f("allocation failed");
487 if ((r = format_host_entry(entry, host, ip, key, store_hash)) != 1) {
488 debug_f("failed to format host entry");
489 goto out;
490 }
491 if ((r = fwrite(sshbuf_ptr(entry), sshbuf_len(entry), 1, f)) != 1) {
492 error_f("fwrite: %s", strerror(errno));
493 goto out;
494 }
495 success = 1;
496 out:
497 sshbuf_free(entry);
498 return success;
499 }
500
501 /*
502 * Create user ~/.ssh directory if it doesn't exist and we want to write to it.
503 * If notify is set, a message will be emitted if the directory is created.
504 */
505 void
506 hostfile_create_user_ssh_dir(const char *filename, int notify)
507 {
508 char *dotsshdir = NULL, *p;
509 size_t len;
510 struct stat st;
511
512 if ((p = strrchr(filename, '/')) == NULL)
513 return;
514 len = p - filename;
515 dotsshdir = tilde_expand_filename("~/" _PATH_SSH_USER_DIR, getuid());
516 if (strlen(dotsshdir) > len || strncmp(filename, dotsshdir, len) != 0)
517 goto out; /* not ~/.ssh prefixed */
518 if (stat(dotsshdir, &st) == 0)
519 goto out; /* dir already exists */
520 else if (errno != ENOENT)
521 error("Could not stat %s: %s", dotsshdir, strerror(errno));
522 else {
523 if (mkdir(dotsshdir, 0700) == -1)
524 error("Could not create directory '%.200s' (%s).",
525 dotsshdir, strerror(errno));
526 else if (notify)
527 logit("Created directory '%s'.", dotsshdir);
528 }
529 out:
530 free(dotsshdir);
531 }
532
533
534 /*
535 * Appends an entry to the host file. Returns false if the entry could not
536 * be appended.
537 */
538 int
539 add_host_to_hostfile(const char *filename, const char *host,
540 const struct sshkey *key, int store_hash)
541 {
542 FILE *f;
543 int success, addnl = 0;
544
545 if (key == NULL)
546 return 1; /* XXX ? */
547 hostfile_create_user_ssh_dir(filename, 0);
548 if ((f = fopen(filename, "a+")) == NULL)
549 return 0;
550 setvbuf(f, NULL, _IONBF, 0);
551 /* Make sure we have a terminating newline. */
552 if (fseek(f, -1L, SEEK_END) == 0 && fgetc(f) != '\n')
553 addnl = 1;
554 if (fseek(f, 0L, SEEK_END) != 0 || (addnl && fputc('\n', f) != '\n')) {
555 error("Failed to add terminating newline to %s: %s",
556 filename, strerror(errno));
557 fclose(f);
558 return 0;
559 }
560 success = write_host_entry(f, host, NULL, key, store_hash);
561 fclose(f);
562 return success;
563 }
564
565 struct host_delete_ctx {
566 FILE *out;
567 int quiet;
568 const char *host, *ip;
569 u_int *match_keys; /* mask of HKF_MATCH_* for this key */
570 struct sshkey * const *keys;
571 size_t nkeys;
572 int modified;
573 };
574
575 static int
576 host_delete(struct hostkey_foreach_line *l, void *_ctx)
577 {
578 struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
579 int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
580 size_t i;
581
582 /* Don't remove CA and revocation lines */
583 if (l->status == HKF_STATUS_MATCHED && l->marker == MRK_NONE) {
584 /*
585 * If this line contains one of the keys that we will be
586 * adding later, then don't change it and mark the key for
587 * skipping.
588 */
589 for (i = 0; i < ctx->nkeys; i++) {
590 if (!sshkey_equal(ctx->keys[i], l->key))
591 continue;
592 ctx->match_keys[i] |= l->match;
593 fprintf(ctx->out, "%s\n", l->line);
594 debug3_f("%s key already at %s:%ld",
595 sshkey_type(l->key), l->path, l->linenum);
596 return 0;
597 }
598
599 /*
600 * Hostname matches and has no CA/revoke marker, delete it
601 * by *not* writing the line to ctx->out.
602 */
603 do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
604 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
605 l->path, l->linenum, sshkey_type(l->key), ctx->host);
606 ctx->modified = 1;
607 return 0;
608 }
609 /* Retain non-matching hosts and invalid lines when deleting */
610 if (l->status == HKF_STATUS_INVALID) {
611 do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
612 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
613 l->path, l->linenum);
614 }
615 fprintf(ctx->out, "%s\n", l->line);
616 return 0;
617 }
618
619 int
620 hostfile_replace_entries(const char *filename, const char *host, const char *ip,
621 struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
622 {
623 int r, fd, oerrno = 0;
624 int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
625 struct host_delete_ctx ctx;
626 char *fp, *temp = NULL, *back = NULL;
627 const char *what;
628 mode_t omask;
629 size_t i;
630 u_int want;
631
632 omask = umask(077);
633
634 memset(&ctx, 0, sizeof(ctx));
635 ctx.host = host;
636 ctx.ip = ip;
637 ctx.quiet = quiet;
638
639 if ((ctx.match_keys = calloc(nkeys, sizeof(*ctx.match_keys))) == NULL)
640 return SSH_ERR_ALLOC_FAIL;
641 ctx.keys = keys;
642 ctx.nkeys = nkeys;
643 ctx.modified = 0;
644
645 /*
646 * Prepare temporary file for in-place deletion.
647 */
648 if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) == -1 ||
649 (r = asprintf(&back, "%s.old", filename)) == -1) {
650 r = SSH_ERR_ALLOC_FAIL;
651 goto fail;
652 }
653
654 if ((fd = mkstemp(temp)) == -1) {
655 oerrno = errno;
656 error_f("mkstemp: %s", strerror(oerrno));
657 r = SSH_ERR_SYSTEM_ERROR;
658 goto fail;
659 }
660 if ((ctx.out = fdopen(fd, "w")) == NULL) {
661 oerrno = errno;
662 close(fd);
663 error_f("fdopen: %s", strerror(oerrno));
664 r = SSH_ERR_SYSTEM_ERROR;
665 goto fail;
666 }
667
668 /* Remove stale/mismatching entries for the specified host */
669 if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
670 HKF_WANT_PARSE_KEY, 0)) != 0) {
671 oerrno = errno;
672 error_fr(r, "hostkeys_foreach");
673 goto fail;
674 }
675
676 /* Re-add the requested keys */
677 want = HKF_MATCH_HOST | (ip == NULL ? 0 : HKF_MATCH_IP);
678 for (i = 0; i < nkeys; i++) {
679 if (keys[i] == NULL || (want & ctx.match_keys[i]) == want)
680 continue;
681 if ((fp = sshkey_fingerprint(keys[i], hash_alg,
682 SSH_FP_DEFAULT)) == NULL) {
683 r = SSH_ERR_ALLOC_FAIL;
684 goto fail;
685 }
686 /* write host/ip */
687 what = "";
688 if (ctx.match_keys[i] == 0) {
689 what = "Adding new key";
690 if (!write_host_entry(ctx.out, host, ip,
691 keys[i], store_hash)) {
692 r = SSH_ERR_INTERNAL_ERROR;
693 goto fail;
694 }
695 } else if ((want & ~ctx.match_keys[i]) == HKF_MATCH_HOST) {
696 what = "Fixing match (hostname)";
697 if (!write_host_entry(ctx.out, host, NULL,
698 keys[i], store_hash)) {
699 r = SSH_ERR_INTERNAL_ERROR;
700 goto fail;
701 }
702 } else if ((want & ~ctx.match_keys[i]) == HKF_MATCH_IP) {
703 what = "Fixing match (address)";
704 if (!write_host_entry(ctx.out, ip, NULL,
705 keys[i], store_hash)) {
706 r = SSH_ERR_INTERNAL_ERROR;
707 goto fail;
708 }
709 }
710 do_log2(loglevel, "%s%s%s for %s%s%s to %s: %s %s",
711 quiet ? __func__ : "", quiet ? ": " : "", what,
712 host, ip == NULL ? "" : ",", ip == NULL ? "" : ip, filename,
713 sshkey_ssh_name(keys[i]), fp);
714 free(fp);
715 ctx.modified = 1;
716 }
717 fclose(ctx.out);
718 ctx.out = NULL;
719
720 if (ctx.modified) {
721 /* Backup the original file and replace it with the temporary */
722 if (unlink(back) == -1 && errno != ENOENT) {
723 oerrno = errno;
724 error_f("unlink %.100s: %s", back, strerror(errno));
725 r = SSH_ERR_SYSTEM_ERROR;
726 goto fail;
727 }
728 if (link(filename, back) == -1) {
729 oerrno = errno;
730 error_f("link %.100s to %.100s: %s", filename,
731 back, strerror(errno));
732 r = SSH_ERR_SYSTEM_ERROR;
733 goto fail;
734 }
735 if (rename(temp, filename) == -1) {
736 oerrno = errno;
737 error_f("rename \"%s\" to \"%s\": %s", temp,
738 filename, strerror(errno));
739 r = SSH_ERR_SYSTEM_ERROR;
740 goto fail;
741 }
742 } else {
743 /* No changes made; just delete the temporary file */
744 if (unlink(temp) != 0)
745 error_f("unlink \"%s\": %s", temp, strerror(errno));
746 }
747
748 /* success */
749 r = 0;
750 fail:
751 if (temp != NULL && r != 0)
752 unlink(temp);
753 free(temp);
754 free(back);
755 if (ctx.out != NULL)
756 fclose(ctx.out);
757 free(ctx.match_keys);
758 umask(omask);
759 if (r == SSH_ERR_SYSTEM_ERROR)
760 errno = oerrno;
761 return r;
762 }
763
764 static int
765 match_maybe_hashed(const char *host, const char *names, int *was_hashed)
766 {
767 int hashed = *names == HASH_DELIM, ret;
768 char *hashed_host = NULL;
769 size_t nlen = strlen(names);
770
771 if (was_hashed != NULL)
772 *was_hashed = hashed;
773 if (hashed) {
774 if ((hashed_host = host_hash(host, names, nlen)) == NULL)
775 return -1;
776 ret = (nlen == strlen(hashed_host) &&
777 strncmp(hashed_host, names, nlen) == 0);
778 free(hashed_host);
779 return ret;
780 }
781 return match_hostname(host, names) == 1;
782 }
783
784 int
785 hostkeys_foreach_file(const char *path, FILE *f, hostkeys_foreach_fn *callback,
786 void *ctx, const char *host, const char *ip, u_int options, u_int note)
787 {
788 char *line = NULL, ktype[128];
789 u_long linenum = 0;
790 char *cp, *cp2;
791 u_int kbits;
792 int hashed;
793 int s, r = 0;
794 struct hostkey_foreach_line lineinfo;
795 size_t linesize = 0, l;
796
797 memset(&lineinfo, 0, sizeof(lineinfo));
798 if (host == NULL && (options & HKF_WANT_MATCH) != 0)
799 return SSH_ERR_INVALID_ARGUMENT;
800
801 while (getline(&line, &linesize, f) != -1) {
802 linenum++;
803 line[strcspn(line, "\n")] = '\0';
804
805 free(lineinfo.line);
806 sshkey_free(lineinfo.key);
807 memset(&lineinfo, 0, sizeof(lineinfo));
808 lineinfo.path = path;
809 lineinfo.linenum = linenum;
810 lineinfo.line = xstrdup(line);
811 lineinfo.marker = MRK_NONE;
812 lineinfo.status = HKF_STATUS_OK;
813 lineinfo.keytype = KEY_UNSPEC;
814 lineinfo.note = note;
815
816 /* Skip any leading whitespace, comments and empty lines. */
817 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
818 ;
819 if (!*cp || *cp == '#' || *cp == '\n') {
820 if ((options & HKF_WANT_MATCH) == 0) {
821 lineinfo.status = HKF_STATUS_COMMENT;
822 if ((r = callback(&lineinfo, ctx)) != 0)
823 break;
824 }
825 continue;
826 }
827
828 if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
829 verbose_f("invalid marker at %s:%lu", path, linenum);
830 if ((options & HKF_WANT_MATCH) == 0)
831 goto bad;
832 continue;
833 }
834
835 /* Find the end of the host name portion. */
836 for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
837 ;
838 if (*cp2 == '\0') {
839 verbose_f("truncated line at %s:%lu", path, linenum);
840 if ((options & HKF_WANT_MATCH) == 0)
841 goto bad;
842 continue;
843 }
844 lineinfo.hosts = cp;
845 *cp2++ = '\0';
846
847 /* Check if the host name matches. */
848 if (host != NULL) {
849 if ((s = match_maybe_hashed(host, lineinfo.hosts,
850 &hashed)) == -1) {
851 debug2_f("%s:%ld: bad host hash \"%.32s\"",
852 path, linenum, lineinfo.hosts);
853 goto bad;
854 }
855 if (s == 1) {
856 lineinfo.status = HKF_STATUS_MATCHED;
857 lineinfo.match |= HKF_MATCH_HOST |
858 (hashed ? HKF_MATCH_HOST_HASHED : 0);
859 }
860 /* Try matching IP address if supplied */
861 if (ip != NULL) {
862 if ((s = match_maybe_hashed(ip, lineinfo.hosts,
863 &hashed)) == -1) {
864 debug2_f("%s:%ld: bad ip hash "
865 "\"%.32s\"", path, linenum,
866 lineinfo.hosts);
867 goto bad;
868 }
869 if (s == 1) {
870 lineinfo.status = HKF_STATUS_MATCHED;
871 lineinfo.match |= HKF_MATCH_IP |
872 (hashed ? HKF_MATCH_IP_HASHED : 0);
873 }
874 }
875 /*
876 * Skip this line if host matching requested and
877 * neither host nor address matched.
878 */
879 if ((options & HKF_WANT_MATCH) != 0 &&
880 lineinfo.status != HKF_STATUS_MATCHED)
881 continue;
882 }
883
884 /* Got a match. Skip host name and any following whitespace */
885 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
886 ;
887 if (*cp2 == '\0' || *cp2 == '#') {
888 debug2("%s:%ld: truncated before key type",
889 path, linenum);
890 goto bad;
891 }
892 lineinfo.rawkey = cp = cp2;
893
894 if ((options & HKF_WANT_PARSE_KEY) != 0) {
895 /*
896 * Extract the key from the line. This will skip
897 * any leading whitespace. Ignore badly formatted
898 * lines.
899 */
900 if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
901 error_f("sshkey_new failed");
902 r = SSH_ERR_ALLOC_FAIL;
903 break;
904 }
905 if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
906 goto bad;
907 }
908 lineinfo.keytype = lineinfo.key->type;
909 lineinfo.comment = cp;
910 } else {
911 /* Extract and parse key type */
912 l = strcspn(lineinfo.rawkey, " \t");
913 if (l <= 1 || l >= sizeof(ktype) ||
914 lineinfo.rawkey[l] == '\0')
915 goto bad;
916 memcpy(ktype, lineinfo.rawkey, l);
917 ktype[l] = '\0';
918 lineinfo.keytype = sshkey_type_from_name(ktype);
919
920 /*
921 * Assume legacy RSA1 if the first component is a short
922 * decimal number.
923 */
924 if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
925 strspn(ktype, "0123456789") == l)
926 goto bad;
927
928 /*
929 * Check that something other than whitespace follows
930 * the key type. This won't catch all corruption, but
931 * it does catch trivial truncation.
932 */
933 cp2 += l; /* Skip past key type */
934 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
935 ;
936 if (*cp2 == '\0' || *cp2 == '#') {
937 debug2("%s:%ld: truncated after key type",
938 path, linenum);
939 lineinfo.keytype = KEY_UNSPEC;
940 }
941 if (lineinfo.keytype == KEY_UNSPEC) {
942 bad:
943 sshkey_free(lineinfo.key);
944 lineinfo.key = NULL;
945 lineinfo.status = HKF_STATUS_INVALID;
946 if ((r = callback(&lineinfo, ctx)) != 0)
947 break;
948 continue;
949 }
950 }
951 if ((r = callback(&lineinfo, ctx)) != 0)
952 break;
953 }
954 sshkey_free(lineinfo.key);
955 free(lineinfo.line);
956 free(line);
957 return r;
958 }
959
960 int
961 hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
962 const char *host, const char *ip, u_int options, u_int note)
963 {
964 FILE *f;
965 int r, oerrno;
966
967 if ((f = fopen(path, "r")) == NULL)
968 return SSH_ERR_SYSTEM_ERROR;
969
970 debug3_f("reading file \"%s\"", path);
971 r = hostkeys_foreach_file(path, f, callback, ctx, host, ip,
972 options, note);
973 oerrno = errno;
974 fclose(f);
975 errno = oerrno;
976 return r;
977 }
978