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