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