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