1 /* $NetBSD: hostfile.c,v 1.8 2015/07/03 01:00:00 christos Exp $ */ 2 /* $OpenBSD: hostfile.c,v 1.66 2015/05/04 06:10:48 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Functions for manipulating the known hosts files. 8 * 9 * As far as I am concerned, the code I have written for this software 10 * can be used freely for any purpose. Any derived versions of this 11 * software must be clearly marked as such, and if the derived work is 12 * incompatible with the protocol description in the RFC file, it must be 13 * called by a name other than "ssh" or "Secure Shell". 14 * 15 * 16 * Copyright (c) 1999, 2000 Markus Friedl. All rights reserved. 17 * Copyright (c) 1999 Niels Provos. All rights reserved. 18 * 19 * Redistribution and use in source and binary forms, with or without 20 * modification, are permitted provided that the following conditions 21 * are met: 22 * 1. Redistributions of source code must retain the above copyright 23 * notice, this list of conditions and the following disclaimer. 24 * 2. Redistributions in binary form must reproduce the above copyright 25 * notice, this list of conditions and the following disclaimer in the 26 * documentation and/or other materials provided with the distribution. 27 * 28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 38 */ 39 40 #include "includes.h" 41 __RCSID("$NetBSD: hostfile.c,v 1.8 2015/07/03 01:00:00 christos Exp $"); 42 #include <sys/types.h> 43 #include <sys/stat.h> 44 45 #include <netinet/in.h> 46 47 #include <errno.h> 48 #include <resolv.h> 49 #include <stdio.h> 50 #include <stdlib.h> 51 #include <string.h> 52 #include <stdarg.h> 53 #include <time.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 "ssherr.h" 63 #include "digest.h" 64 #include "hmac.h" 65 66 struct hostkeys { 67 struct hostkey_entry *entries; 68 u_int num_entries; 69 }; 70 71 /* XXX hmac is too easy to dictionary attack; use bcrypt? */ 72 73 static int 74 extract_salt(const char *s, u_int l, u_char *salt, size_t salt_len) 75 { 76 char *p, *b64salt; 77 u_int b64len; 78 int ret; 79 80 if (l < sizeof(HASH_MAGIC) - 1) { 81 debug2("extract_salt: string too short"); 82 return (-1); 83 } 84 if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) { 85 debug2("extract_salt: invalid magic identifier"); 86 return (-1); 87 } 88 s += sizeof(HASH_MAGIC) - 1; 89 l -= sizeof(HASH_MAGIC) - 1; 90 if ((p = memchr(s, HASH_DELIM, l)) == NULL) { 91 debug2("extract_salt: missing salt termination character"); 92 return (-1); 93 } 94 95 b64len = p - s; 96 /* Sanity check */ 97 if (b64len == 0 || b64len > 1024) { 98 debug2("extract_salt: bad encoded salt length %u", b64len); 99 return (-1); 100 } 101 b64salt = xmalloc(1 + b64len); 102 memcpy(b64salt, s, b64len); 103 b64salt[b64len] = '\0'; 104 105 ret = __b64_pton(b64salt, salt, salt_len); 106 free(b64salt); 107 if (ret == -1) { 108 debug2("extract_salt: salt decode error"); 109 return (-1); 110 } 111 if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) { 112 debug2("extract_salt: expected salt len %zd, got %d", 113 ssh_hmac_bytes(SSH_DIGEST_SHA1), ret); 114 return (-1); 115 } 116 117 return (0); 118 } 119 120 char * 121 host_hash(const char *host, const char *name_from_hostfile, u_int src_len) 122 { 123 struct ssh_hmac_ctx *ctx; 124 u_char salt[256], result[256]; 125 char uu_salt[512], uu_result[512]; 126 static char encoded[1024]; 127 u_int i, len; 128 129 len = ssh_digest_bytes(SSH_DIGEST_SHA1); 130 131 if (name_from_hostfile == NULL) { 132 /* Create new salt */ 133 for (i = 0; i < len; i++) 134 salt[i] = arc4random(); 135 } else { 136 /* Extract salt from known host entry */ 137 if (extract_salt(name_from_hostfile, src_len, salt, 138 sizeof(salt)) == -1) 139 return (NULL); 140 } 141 142 if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL || 143 ssh_hmac_init(ctx, salt, len) < 0 || 144 ssh_hmac_update(ctx, host, strlen(host)) < 0 || 145 ssh_hmac_final(ctx, result, sizeof(result))) 146 fatal("%s: ssh_hmac failed", __func__); 147 ssh_hmac_free(ctx); 148 149 if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 || 150 __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1) 151 fatal("%s: __b64_ntop failed", __func__); 152 153 snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt, 154 HASH_DELIM, uu_result); 155 156 return (encoded); 157 } 158 159 /* 160 * Parses an RSA (number of bits, e, n) or DSA key from a string. Moves the 161 * pointer over the key. Skips any whitespace at the beginning and at end. 162 */ 163 164 int 165 hostfile_read_key(char **cpp, u_int *bitsp, struct sshkey *ret) 166 { 167 char *cp; 168 int r; 169 170 /* Skip leading whitespace. */ 171 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++) 172 ; 173 174 if ((r = sshkey_read(ret, &cp)) != 0) 175 return 0; 176 177 /* Skip trailing whitespace. */ 178 for (; *cp == ' ' || *cp == '\t'; cp++) 179 ; 180 181 /* Return results. */ 182 *cpp = cp; 183 if (bitsp != NULL) 184 *bitsp = sshkey_size(ret); 185 return 1; 186 } 187 188 static HostkeyMarker 189 check_markers(char **cpp) 190 { 191 char marker[32], *sp, *cp = *cpp; 192 int ret = MRK_NONE; 193 194 while (*cp == '@') { 195 /* Only one marker is allowed */ 196 if (ret != MRK_NONE) 197 return MRK_ERROR; 198 /* Markers are terminated by whitespace */ 199 if ((sp = strchr(cp, ' ')) == NULL && 200 (sp = strchr(cp, '\t')) == NULL) 201 return MRK_ERROR; 202 /* Extract marker for comparison */ 203 if (sp <= cp + 1 || sp >= cp + sizeof(marker)) 204 return MRK_ERROR; 205 memcpy(marker, cp, sp - cp); 206 marker[sp - cp] = '\0'; 207 if (strcmp(marker, CA_MARKER) == 0) 208 ret = MRK_CA; 209 else if (strcmp(marker, REVOKE_MARKER) == 0) 210 ret = MRK_REVOKE; 211 else 212 return MRK_ERROR; 213 214 /* Skip past marker and any whitespace that follows it */ 215 cp = sp; 216 for (; *cp == ' ' || *cp == '\t'; cp++) 217 ; 218 } 219 *cpp = cp; 220 return ret; 221 } 222 223 struct hostkeys * 224 init_hostkeys(void) 225 { 226 struct hostkeys *ret = xcalloc(1, sizeof(*ret)); 227 228 ret->entries = NULL; 229 return ret; 230 } 231 232 struct load_callback_ctx { 233 const char *host; 234 u_long num_loaded; 235 struct hostkeys *hostkeys; 236 }; 237 238 static int 239 record_hostkey(struct hostkey_foreach_line *l, void *_ctx) 240 { 241 struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx; 242 struct hostkeys *hostkeys = ctx->hostkeys; 243 struct hostkey_entry *tmp; 244 245 if (l->status == HKF_STATUS_INVALID) { 246 /* XXX make this verbose() in the future */ 247 debug("%s:%ld: parse error in hostkeys file", 248 l->path, l->linenum); 249 return 0; 250 } 251 252 debug3("%s: found %skey type %s in file %s:%lu", __func__, 253 l->marker == MRK_NONE ? "" : 254 (l->marker == MRK_CA ? "ca " : "revoked "), 255 sshkey_type(l->key), l->path, l->linenum); 256 if ((tmp = reallocarray(hostkeys->entries, 257 hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL) 258 return SSH_ERR_ALLOC_FAIL; 259 hostkeys->entries = tmp; 260 hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host); 261 hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path); 262 hostkeys->entries[hostkeys->num_entries].line = l->linenum; 263 hostkeys->entries[hostkeys->num_entries].key = l->key; 264 l->key = NULL; /* steal it */ 265 hostkeys->entries[hostkeys->num_entries].marker = l->marker; 266 hostkeys->num_entries++; 267 ctx->num_loaded++; 268 269 return 0; 270 } 271 272 void 273 load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path) 274 { 275 int r; 276 struct load_callback_ctx ctx; 277 278 ctx.host = host; 279 ctx.num_loaded = 0; 280 ctx.hostkeys = hostkeys; 281 282 if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host, NULL, 283 HKF_WANT_MATCH|HKF_WANT_PARSE_KEY)) != 0) { 284 if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT) 285 debug("%s: hostkeys_foreach failed for %s: %s", 286 __func__, path, ssh_err(r)); 287 } 288 if (ctx.num_loaded != 0) 289 debug3("%s: loaded %lu keys from %s", __func__, 290 ctx.num_loaded, host); 291 } 292 293 void 294 free_hostkeys(struct hostkeys *hostkeys) 295 { 296 u_int i; 297 298 for (i = 0; i < hostkeys->num_entries; i++) { 299 free(hostkeys->entries[i].host); 300 free(hostkeys->entries[i].file); 301 sshkey_free(hostkeys->entries[i].key); 302 explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries)); 303 } 304 free(hostkeys->entries); 305 explicit_bzero(hostkeys, sizeof(*hostkeys)); 306 free(hostkeys); 307 } 308 309 static int 310 check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k) 311 { 312 int is_cert = sshkey_is_cert(k); 313 u_int i; 314 315 for (i = 0; i < hostkeys->num_entries; i++) { 316 if (hostkeys->entries[i].marker != MRK_REVOKE) 317 continue; 318 if (sshkey_equal_public(k, hostkeys->entries[i].key)) 319 return -1; 320 if (is_cert && 321 sshkey_equal_public(k->cert->signature_key, 322 hostkeys->entries[i].key)) 323 return -1; 324 } 325 return 0; 326 } 327 328 /* 329 * Match keys against a specified key, or look one up by key type. 330 * 331 * If looking for a keytype (key == NULL) and one is found then return 332 * HOST_FOUND, otherwise HOST_NEW. 333 * 334 * If looking for a key (key != NULL): 335 * 1. If the key is a cert and a matching CA is found, return HOST_OK 336 * 2. If the key is not a cert and a matching key is found, return HOST_OK 337 * 3. If no key matches but a key with a different type is found, then 338 * return HOST_CHANGED 339 * 4. If no matching keys are found, then return HOST_NEW. 340 * 341 * Finally, check any found key is not revoked. 342 */ 343 static HostStatus 344 check_hostkeys_by_key_or_type(struct hostkeys *hostkeys, 345 struct sshkey *k, int keytype, const struct hostkey_entry **found) 346 { 347 u_int i; 348 HostStatus end_return = HOST_NEW; 349 int want_cert = sshkey_is_cert(k); 350 HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE; 351 int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2; 352 353 if (found != NULL) 354 *found = NULL; 355 356 for (i = 0; i < hostkeys->num_entries; i++) { 357 if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1) 358 continue; 359 if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1) 360 continue; 361 if (hostkeys->entries[i].marker != want_marker) 362 continue; 363 if (k == NULL) { 364 if (hostkeys->entries[i].key->type != keytype) 365 continue; 366 end_return = HOST_FOUND; 367 if (found != NULL) 368 *found = hostkeys->entries + i; 369 k = hostkeys->entries[i].key; 370 break; 371 } 372 if (want_cert) { 373 if (sshkey_equal_public(k->cert->signature_key, 374 hostkeys->entries[i].key)) { 375 /* A matching CA exists */ 376 end_return = HOST_OK; 377 if (found != NULL) 378 *found = hostkeys->entries + i; 379 break; 380 } 381 } else { 382 if (sshkey_equal(k, hostkeys->entries[i].key)) { 383 end_return = HOST_OK; 384 if (found != NULL) 385 *found = hostkeys->entries + i; 386 break; 387 } 388 /* A non-maching key exists */ 389 end_return = HOST_CHANGED; 390 if (found != NULL) 391 *found = hostkeys->entries + i; 392 } 393 } 394 if (check_key_not_revoked(hostkeys, k) != 0) { 395 end_return = HOST_REVOKED; 396 if (found != NULL) 397 *found = NULL; 398 } 399 return end_return; 400 } 401 402 HostStatus 403 check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key, 404 const struct hostkey_entry **found) 405 { 406 if (key == NULL) 407 fatal("no key to look up"); 408 return check_hostkeys_by_key_or_type(hostkeys, key, 0, found); 409 } 410 411 int 412 lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype, 413 const struct hostkey_entry **found) 414 { 415 return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype, 416 found) == HOST_FOUND); 417 } 418 419 static int 420 write_host_entry(FILE *f, const char *host, const char *ip, 421 const struct sshkey *key, int store_hash) 422 { 423 int r, success = 0; 424 char *hashed_host = NULL; 425 426 if (store_hash) { 427 if ((hashed_host = host_hash(host, NULL, 0)) == NULL) { 428 error("%s: host_hash failed", __func__); 429 return 0; 430 } 431 fprintf(f, "%s ", hashed_host); 432 } else if (ip != NULL) 433 fprintf(f, "%s,%s ", host, ip); 434 else 435 fprintf(f, "%s ", host); 436 437 if ((r = sshkey_write(key, f)) == 0) 438 success = 1; 439 else 440 error("%s: sshkey_write failed: %s", __func__, ssh_err(r)); 441 fputc('\n', f); 442 return success; 443 } 444 445 /* 446 * Appends an entry to the host file. Returns false if the entry could not 447 * be appended. 448 */ 449 int 450 add_host_to_hostfile(const char *filename, const char *host, 451 const struct sshkey *key, int store_hash) 452 { 453 FILE *f; 454 int success; 455 456 if (key == NULL) 457 return 1; /* XXX ? */ 458 f = fopen(filename, "a"); 459 if (!f) 460 return 0; 461 success = write_host_entry(f, host, NULL, key, store_hash); 462 fclose(f); 463 return success; 464 } 465 466 struct host_delete_ctx { 467 FILE *out; 468 int quiet; 469 const char *host; 470 int *skip_keys; /* XXX split for host/ip? might want to ensure both */ 471 struct sshkey * const *keys; 472 size_t nkeys; 473 int modified; 474 }; 475 476 static int 477 host_delete(struct hostkey_foreach_line *l, void *_ctx) 478 { 479 struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx; 480 int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE; 481 size_t i; 482 483 if (l->status == HKF_STATUS_MATCHED) { 484 if (l->marker != MRK_NONE) { 485 /* Don't remove CA and revocation lines */ 486 fprintf(ctx->out, "%s\n", l->line); 487 return 0; 488 } 489 490 /* XXX might need a knob for this later */ 491 /* Don't remove RSA1 keys */ 492 if (l->key->type == KEY_RSA1) { 493 fprintf(ctx->out, "%s\n", l->line); 494 return 0; 495 } 496 497 /* 498 * If this line contains one of the keys that we will be 499 * adding later, then don't change it and mark the key for 500 * skipping. 501 */ 502 for (i = 0; i < ctx->nkeys; i++) { 503 if (sshkey_equal(ctx->keys[i], l->key)) { 504 ctx->skip_keys[i] = 1; 505 fprintf(ctx->out, "%s\n", l->line); 506 debug3("%s: %s key already at %s:%ld", __func__, 507 sshkey_type(l->key), l->path, l->linenum); 508 return 0; 509 } 510 } 511 512 /* 513 * Hostname matches and has no CA/revoke marker, delete it 514 * by *not* writing the line to ctx->out. 515 */ 516 do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s", 517 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "", 518 l->path, l->linenum, sshkey_type(l->key), ctx->host); 519 ctx->modified = 1; 520 return 0; 521 } 522 /* Retain non-matching hosts and invalid lines when deleting */ 523 if (l->status == HKF_STATUS_INVALID) { 524 do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry", 525 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "", 526 l->path, l->linenum); 527 } 528 fprintf(ctx->out, "%s\n", l->line); 529 return 0; 530 } 531 532 int 533 hostfile_replace_entries(const char *filename, const char *host, const char *ip, 534 struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg) 535 { 536 int r, fd, oerrno = 0; 537 int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE; 538 struct host_delete_ctx ctx; 539 char *fp, *temp = NULL, *back = NULL; 540 mode_t omask; 541 size_t i; 542 543 omask = umask(077); 544 545 memset(&ctx, 0, sizeof(ctx)); 546 ctx.host = host; 547 ctx.quiet = quiet; 548 if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL) 549 return SSH_ERR_ALLOC_FAIL; 550 ctx.keys = keys; 551 ctx.nkeys = nkeys; 552 ctx.modified = 0; 553 554 /* 555 * Prepare temporary file for in-place deletion. 556 */ 557 if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) < 0 || 558 (r = asprintf(&back, "%s.old", filename)) < 0) { 559 r = SSH_ERR_ALLOC_FAIL; 560 goto fail; 561 } 562 563 if ((fd = mkstemp(temp)) == -1) { 564 oerrno = errno; 565 error("%s: mkstemp: %s", __func__, strerror(oerrno)); 566 r = SSH_ERR_SYSTEM_ERROR; 567 goto fail; 568 } 569 if ((ctx.out = fdopen(fd, "w")) == NULL) { 570 oerrno = errno; 571 close(fd); 572 error("%s: fdopen: %s", __func__, strerror(oerrno)); 573 r = SSH_ERR_SYSTEM_ERROR; 574 goto fail; 575 } 576 577 /* Remove all entries for the specified host from the file */ 578 if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip, 579 HKF_WANT_PARSE_KEY)) != 0) { 580 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r)); 581 goto fail; 582 } 583 584 /* Add the requested keys */ 585 for (i = 0; i < nkeys; i++) { 586 if (ctx.skip_keys[i]) 587 continue; 588 if ((fp = sshkey_fingerprint(keys[i], hash_alg, 589 SSH_FP_DEFAULT)) == NULL) { 590 r = SSH_ERR_ALLOC_FAIL; 591 goto fail; 592 } 593 do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s", 594 quiet ? __func__ : "", quiet ? ": " : "", host, filename, 595 sshkey_ssh_name(keys[i]), fp); 596 free(fp); 597 if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) { 598 r = SSH_ERR_INTERNAL_ERROR; 599 goto fail; 600 } 601 ctx.modified = 1; 602 } 603 fclose(ctx.out); 604 ctx.out = NULL; 605 606 if (ctx.modified) { 607 /* Backup the original file and replace it with the temporary */ 608 if (unlink(back) == -1 && errno != ENOENT) { 609 oerrno = errno; 610 error("%s: unlink %.100s: %s", __func__, 611 back, strerror(errno)); 612 r = SSH_ERR_SYSTEM_ERROR; 613 goto fail; 614 } 615 if (link(filename, back) == -1) { 616 oerrno = errno; 617 error("%s: link %.100s to %.100s: %s", __func__, 618 filename, back, strerror(errno)); 619 r = SSH_ERR_SYSTEM_ERROR; 620 goto fail; 621 } 622 if (rename(temp, filename) == -1) { 623 oerrno = errno; 624 error("%s: rename \"%s\" to \"%s\": %s", __func__, 625 temp, filename, strerror(errno)); 626 r = SSH_ERR_SYSTEM_ERROR; 627 goto fail; 628 } 629 } else { 630 /* No changes made; just delete the temporary file */ 631 if (unlink(temp) != 0) 632 error("%s: unlink \"%s\": %s", __func__, 633 temp, strerror(errno)); 634 } 635 636 /* success */ 637 r = 0; 638 fail: 639 if (temp != NULL && r != 0) 640 unlink(temp); 641 free(temp); 642 free(back); 643 if (ctx.out != NULL) 644 fclose(ctx.out); 645 free(ctx.skip_keys); 646 umask(omask); 647 if (r == SSH_ERR_SYSTEM_ERROR) 648 errno = oerrno; 649 return r; 650 } 651 652 static int 653 match_maybe_hashed(const char *host, const char *names, int *was_hashed) 654 { 655 int hashed = *names == HASH_DELIM; 656 const char *hashed_host; 657 size_t nlen = strlen(names); 658 659 if (was_hashed != NULL) 660 *was_hashed = hashed; 661 if (hashed) { 662 if ((hashed_host = host_hash(host, names, nlen)) == NULL) 663 return -1; 664 return nlen == strlen(hashed_host) && 665 strncmp(hashed_host, names, nlen) == 0; 666 } 667 return match_hostname(host, names) == 1; 668 } 669 670 int 671 hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx, 672 const char *host, const char *ip, u_int options) 673 { 674 FILE *f; 675 char line[8192], oline[8192], ktype[128]; 676 u_long linenum = 0; 677 char *cp, *cp2; 678 u_int kbits; 679 int hashed; 680 int s, r = 0; 681 struct hostkey_foreach_line lineinfo; 682 size_t l; 683 684 memset(&lineinfo, 0, sizeof(lineinfo)); 685 if (host == NULL && (options & HKF_WANT_MATCH) != 0) 686 return SSH_ERR_INVALID_ARGUMENT; 687 if ((f = fopen(path, "r")) == NULL) 688 return SSH_ERR_SYSTEM_ERROR; 689 690 debug3("%s: reading file \"%s\"", __func__, path); 691 while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) { 692 line[strcspn(line, "\n")] = '\0'; 693 strlcpy(oline, line, sizeof(oline)); 694 695 sshkey_free(lineinfo.key); 696 memset(&lineinfo, 0, sizeof(lineinfo)); 697 lineinfo.path = path; 698 lineinfo.linenum = linenum; 699 lineinfo.line = oline; 700 lineinfo.marker = MRK_NONE; 701 lineinfo.status = HKF_STATUS_OK; 702 lineinfo.keytype = KEY_UNSPEC; 703 704 /* Skip any leading whitespace, comments and empty lines. */ 705 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 706 ; 707 if (!*cp || *cp == '#' || *cp == '\n') { 708 if ((options & HKF_WANT_MATCH) == 0) { 709 lineinfo.status = HKF_STATUS_COMMENT; 710 if ((r = callback(&lineinfo, ctx)) != 0) 711 break; 712 } 713 continue; 714 } 715 716 if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) { 717 verbose("%s: invalid marker at %s:%lu", 718 __func__, path, linenum); 719 if ((options & HKF_WANT_MATCH) == 0) 720 goto bad; 721 continue; 722 } 723 724 /* Find the end of the host name portion. */ 725 for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++) 726 ; 727 lineinfo.hosts = cp; 728 *cp2++ = '\0'; 729 730 /* Check if the host name matches. */ 731 if (host != NULL) { 732 if ((s = match_maybe_hashed(host, lineinfo.hosts, 733 &hashed)) == -1) { 734 debug2("%s: %s:%ld: bad host hash \"%.32s\"", 735 __func__, path, linenum, lineinfo.hosts); 736 goto bad; 737 } 738 if (s == 1) { 739 lineinfo.status = HKF_STATUS_MATCHED; 740 lineinfo.match |= HKF_MATCH_HOST | 741 (hashed ? HKF_MATCH_HOST_HASHED : 0); 742 } 743 /* Try matching IP address if supplied */ 744 if (ip != NULL) { 745 if ((s = match_maybe_hashed(ip, lineinfo.hosts, 746 &hashed)) == -1) { 747 debug2("%s: %s:%ld: bad ip hash " 748 "\"%.32s\"", __func__, path, 749 linenum, lineinfo.hosts); 750 goto bad; 751 } 752 if (s == 1) { 753 lineinfo.status = HKF_STATUS_MATCHED; 754 lineinfo.match |= HKF_MATCH_IP | 755 (hashed ? HKF_MATCH_IP_HASHED : 0); 756 } 757 } 758 /* 759 * Skip this line if host matching requested and 760 * neither host nor address matched. 761 */ 762 if ((options & HKF_WANT_MATCH) != 0 && 763 lineinfo.status != HKF_STATUS_MATCHED) 764 continue; 765 } 766 767 /* Got a match. Skip host name and any following whitespace */ 768 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++) 769 ; 770 if (*cp2 == '\0' || *cp2 == '#') { 771 debug2("%s:%ld: truncated before key type", 772 path, linenum); 773 goto bad; 774 } 775 lineinfo.rawkey = cp = cp2; 776 777 if ((options & HKF_WANT_PARSE_KEY) != 0) { 778 /* 779 * Extract the key from the line. This will skip 780 * any leading whitespace. Ignore badly formatted 781 * lines. 782 */ 783 if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) { 784 error("%s: sshkey_new failed", __func__); 785 r = SSH_ERR_ALLOC_FAIL; 786 break; 787 } 788 if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) { 789 #ifdef WITH_SSH1 790 sshkey_free(lineinfo.key); 791 lineinfo.key = sshkey_new(KEY_RSA1); 792 if (lineinfo.key == NULL) { 793 error("%s: sshkey_new fail", __func__); 794 r = SSH_ERR_ALLOC_FAIL; 795 break; 796 } 797 if (!hostfile_read_key(&cp, &kbits, 798 lineinfo.key)) 799 goto bad; 800 #else 801 goto bad; 802 #endif 803 } 804 lineinfo.keytype = lineinfo.key->type; 805 lineinfo.comment = cp; 806 } else { 807 /* Extract and parse key type */ 808 l = strcspn(lineinfo.rawkey, " \t"); 809 if (l <= 1 || l >= sizeof(ktype) || 810 lineinfo.rawkey[l] == '\0') 811 goto bad; 812 memcpy(ktype, lineinfo.rawkey, l); 813 ktype[l] = '\0'; 814 lineinfo.keytype = sshkey_type_from_name(ktype); 815 816 /* 817 * Assume RSA1 if the first component is a short 818 * decimal number. 819 */ 820 if (lineinfo.keytype == KEY_UNSPEC && l < 8 && 821 strspn(ktype, "0123456789") == l) 822 lineinfo.keytype = KEY_RSA1; 823 824 /* 825 * Check that something other than whitespace follows 826 * the key type. This won't catch all corruption, but 827 * it does catch trivial truncation. 828 */ 829 cp2 += l; /* Skip past key type */ 830 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++) 831 ; 832 if (*cp2 == '\0' || *cp2 == '#') { 833 debug2("%s:%ld: truncated after key type", 834 path, linenum); 835 lineinfo.keytype = KEY_UNSPEC; 836 } 837 if (lineinfo.keytype == KEY_UNSPEC) { 838 bad: 839 sshkey_free(lineinfo.key); 840 lineinfo.key = NULL; 841 lineinfo.status = HKF_STATUS_INVALID; 842 if ((r = callback(&lineinfo, ctx)) != 0) 843 break; 844 continue; 845 } 846 } 847 if ((r = callback(&lineinfo, ctx)) != 0) 848 break; 849 } 850 sshkey_free(lineinfo.key); 851 fclose(f); 852 return r; 853 } 854