1 /* $NetBSD: hostfile.c,v 1.25 2026/04/08 18:58:40 christos Exp $ */ 2 /* $OpenBSD: hostfile.c,v 1.100 2025/11/25 00:57:04 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.25 2026/04/08 18:58:40 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 = NULL, *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 fp = NULL; 716 ctx.modified = 1; 717 } 718 fclose(ctx.out); 719 ctx.out = NULL; 720 721 if (ctx.modified) { 722 /* Backup the original file and replace it with the temporary */ 723 if (unlink(back) == -1 && errno != ENOENT) { 724 oerrno = errno; 725 error_f("unlink %.100s: %s", back, strerror(errno)); 726 r = SSH_ERR_SYSTEM_ERROR; 727 goto fail; 728 } 729 if (link(filename, back) == -1) { 730 oerrno = errno; 731 error_f("link %.100s to %.100s: %s", filename, 732 back, strerror(errno)); 733 r = SSH_ERR_SYSTEM_ERROR; 734 goto fail; 735 } 736 if (rename(temp, filename) == -1) { 737 oerrno = errno; 738 error_f("rename \"%s\" to \"%s\": %s", temp, 739 filename, strerror(errno)); 740 r = SSH_ERR_SYSTEM_ERROR; 741 goto fail; 742 } 743 } else { 744 /* No changes made; just delete the temporary file */ 745 if (unlink(temp) != 0) 746 error_f("unlink \"%s\": %s", temp, strerror(errno)); 747 } 748 749 /* success */ 750 r = 0; 751 fail: 752 if (temp != NULL && r != 0) 753 unlink(temp); 754 free(temp); 755 free(back); 756 free(fp); 757 if (ctx.out != NULL) 758 fclose(ctx.out); 759 free(ctx.match_keys); 760 umask(omask); 761 if (r == SSH_ERR_SYSTEM_ERROR) 762 errno = oerrno; 763 return r; 764 } 765 766 static int 767 match_maybe_hashed(const char *host, const char *names, int *was_hashed) 768 { 769 int hashed = *names == HASH_DELIM, ret; 770 char *hashed_host = NULL; 771 size_t nlen = strlen(names); 772 773 if (was_hashed != NULL) 774 *was_hashed = hashed; 775 if (hashed) { 776 if ((hashed_host = host_hash(host, names, nlen)) == NULL) 777 return -1; 778 ret = (nlen == strlen(hashed_host) && 779 strncmp(hashed_host, names, nlen) == 0); 780 free(hashed_host); 781 return ret; 782 } 783 return match_hostname(host, names) == 1; 784 } 785 786 int 787 hostkeys_foreach_file(const char *path, FILE *f, hostkeys_foreach_fn *callback, 788 void *ctx, const char *host, const char *ip, u_int options, u_int note) 789 { 790 char *line = NULL, ktype[128]; 791 u_long linenum = 0; 792 char *cp, *cp2; 793 u_int kbits; 794 int hashed; 795 int s, r = 0; 796 struct hostkey_foreach_line lineinfo; 797 size_t linesize = 0, l; 798 799 memset(&lineinfo, 0, sizeof(lineinfo)); 800 if (host == NULL && (options & HKF_WANT_MATCH) != 0) 801 return SSH_ERR_INVALID_ARGUMENT; 802 803 while (getline(&line, &linesize, f) != -1) { 804 linenum++; 805 line[strcspn(line, "\n")] = '\0'; 806 807 free(lineinfo.line); 808 sshkey_free(lineinfo.key); 809 memset(&lineinfo, 0, sizeof(lineinfo)); 810 lineinfo.path = path; 811 lineinfo.linenum = linenum; 812 lineinfo.line = xstrdup(line); 813 lineinfo.marker = MRK_NONE; 814 lineinfo.status = HKF_STATUS_OK; 815 lineinfo.keytype = KEY_UNSPEC; 816 lineinfo.note = note; 817 818 /* Skip any leading whitespace, comments and empty lines. */ 819 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 820 ; 821 if (!*cp || *cp == '#' || *cp == '\n') { 822 if ((options & HKF_WANT_MATCH) == 0) { 823 lineinfo.status = HKF_STATUS_COMMENT; 824 if ((r = callback(&lineinfo, ctx)) != 0) 825 break; 826 } 827 continue; 828 } 829 830 if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) { 831 verbose_f("invalid marker at %s:%lu", path, linenum); 832 if ((options & HKF_WANT_MATCH) == 0) 833 goto bad; 834 continue; 835 } 836 837 /* Find the end of the host name portion. */ 838 for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++) 839 ; 840 if (*cp2 == '\0') { 841 verbose_f("truncated line at %s:%lu", path, linenum); 842 if ((options & HKF_WANT_MATCH) == 0) 843 goto bad; 844 continue; 845 } 846 lineinfo.hosts = cp; 847 *cp2++ = '\0'; 848 849 /* Check if the host name matches. */ 850 if (host != NULL) { 851 if ((s = match_maybe_hashed(host, lineinfo.hosts, 852 &hashed)) == -1) { 853 debug2_f("%s:%ld: bad host hash \"%.32s\"", 854 path, linenum, lineinfo.hosts); 855 goto bad; 856 } 857 if (s == 1) { 858 lineinfo.status = HKF_STATUS_MATCHED; 859 lineinfo.match |= HKF_MATCH_HOST | 860 (hashed ? HKF_MATCH_HOST_HASHED : 0); 861 } 862 /* Try matching IP address if supplied */ 863 if (ip != NULL) { 864 if ((s = match_maybe_hashed(ip, lineinfo.hosts, 865 &hashed)) == -1) { 866 debug2_f("%s:%ld: bad ip hash " 867 "\"%.32s\"", path, linenum, 868 lineinfo.hosts); 869 goto bad; 870 } 871 if (s == 1) { 872 lineinfo.status = HKF_STATUS_MATCHED; 873 lineinfo.match |= HKF_MATCH_IP | 874 (hashed ? HKF_MATCH_IP_HASHED : 0); 875 } 876 } 877 /* 878 * Skip this line if host matching requested and 879 * neither host nor address matched. 880 */ 881 if ((options & HKF_WANT_MATCH) != 0 && 882 lineinfo.status != HKF_STATUS_MATCHED) 883 continue; 884 } 885 886 /* Got a match. Skip host name and any following whitespace */ 887 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++) 888 ; 889 if (*cp2 == '\0' || *cp2 == '#') { 890 debug2("%s:%ld: truncated before key type", 891 path, linenum); 892 goto bad; 893 } 894 lineinfo.rawkey = cp = cp2; 895 896 if ((options & HKF_WANT_PARSE_KEY) != 0) { 897 /* 898 * Extract the key from the line. This will skip 899 * any leading whitespace. Ignore badly formatted 900 * lines. 901 */ 902 if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) { 903 error_f("sshkey_new failed"); 904 r = SSH_ERR_ALLOC_FAIL; 905 break; 906 } 907 if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) { 908 goto bad; 909 } 910 lineinfo.keytype = lineinfo.key->type; 911 lineinfo.comment = cp; 912 } else { 913 /* Extract and parse key type */ 914 l = strcspn(lineinfo.rawkey, " \t"); 915 if (l <= 1 || l >= sizeof(ktype) || 916 lineinfo.rawkey[l] == '\0') 917 goto bad; 918 memcpy(ktype, lineinfo.rawkey, l); 919 ktype[l] = '\0'; 920 lineinfo.keytype = sshkey_type_from_name(ktype); 921 922 /* 923 * Assume legacy RSA1 if the first component is a short 924 * decimal number. 925 */ 926 if (lineinfo.keytype == KEY_UNSPEC && l < 8 && 927 strspn(ktype, "0123456789") == l) 928 goto bad; 929 930 /* 931 * Check that something other than whitespace follows 932 * the key type. This won't catch all corruption, but 933 * it does catch trivial truncation. 934 */ 935 cp2 += l; /* Skip past key type */ 936 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++) 937 ; 938 if (*cp2 == '\0' || *cp2 == '#') { 939 debug2("%s:%ld: truncated after key type", 940 path, linenum); 941 lineinfo.keytype = KEY_UNSPEC; 942 } 943 if (lineinfo.keytype == KEY_UNSPEC) { 944 bad: 945 sshkey_free(lineinfo.key); 946 lineinfo.key = NULL; 947 lineinfo.status = HKF_STATUS_INVALID; 948 if ((r = callback(&lineinfo, ctx)) != 0) 949 break; 950 continue; 951 } 952 } 953 if ((r = callback(&lineinfo, ctx)) != 0) 954 break; 955 } 956 sshkey_free(lineinfo.key); 957 free(lineinfo.line); 958 free(line); 959 return r; 960 } 961 962 int 963 hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx, 964 const char *host, const char *ip, u_int options, u_int note) 965 { 966 FILE *f; 967 int r, oerrno; 968 969 if ((f = fopen(path, "r")) == NULL) 970 return SSH_ERR_SYSTEM_ERROR; 971 972 debug3_f("reading file \"%s\"", path); 973 r = hostkeys_foreach_file(path, f, callback, ctx, host, ip, 974 options, note); 975 oerrno = errno; 976 fclose(f); 977 errno = oerrno; 978 return r; 979 } 980