1295367Sdes/* $OpenBSD: hostfile.c,v 1.66 2015/05/04 06:10:48 djm Exp $ */ 257429Smarkm/* 357429Smarkm * Author: Tatu Ylonen <ylo@cs.hut.fi> 457429Smarkm * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 557429Smarkm * All rights reserved 665674Skris * Functions for manipulating the known hosts files. 760576Skris * 865674Skris * As far as I am concerned, the code I have written for this software 965674Skris * can be used freely for any purpose. Any derived versions of this 1065674Skris * software must be clearly marked as such, and if the derived work is 1165674Skris * incompatible with the protocol description in the RFC file, it must be 1265674Skris * called by a name other than "ssh" or "Secure Shell". 1360576Skris * 1460576Skris * 1592559Sdes * Copyright (c) 1999, 2000 Markus Friedl. All rights reserved. 1665674Skris * Copyright (c) 1999 Niels Provos. All rights reserved. 1765674Skris * 1865674Skris * Redistribution and use in source and binary forms, with or without 1965674Skris * modification, are permitted provided that the following conditions 2065674Skris * are met: 2165674Skris * 1. Redistributions of source code must retain the above copyright 2265674Skris * notice, this list of conditions and the following disclaimer. 2365674Skris * 2. Redistributions in binary form must reproduce the above copyright 2465674Skris * notice, this list of conditions and the following disclaimer in the 2565674Skris * documentation and/or other materials provided with the distribution. 2665674Skris * 2765674Skris * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 2865674Skris * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 2965674Skris * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 3065674Skris * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 3165674Skris * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 3265674Skris * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 3365674Skris * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 3465674Skris * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 3565674Skris * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 3665674Skris * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 3757429Smarkm */ 3857429Smarkm 3957429Smarkm#include "includes.h" 4057429Smarkm 41162856Sdes#include <sys/types.h> 42295367Sdes#include <sys/stat.h> 43162856Sdes 44162856Sdes#include <netinet/in.h> 45162856Sdes 46295367Sdes#include <errno.h> 47162856Sdes#include <resolv.h> 48162856Sdes#include <stdarg.h> 49162856Sdes#include <stdio.h> 50162856Sdes#include <stdlib.h> 51162856Sdes#include <string.h> 52295367Sdes#include <stdarg.h> 53295367Sdes#include <unistd.h> 54162856Sdes 55162856Sdes#include "xmalloc.h" 5658582Skris#include "match.h" 57295367Sdes#include "sshkey.h" 5858582Skris#include "hostfile.h" 5976262Sgreen#include "log.h" 60221420Sdes#include "misc.h" 61295367Sdes#include "ssherr.h" 62262566Sdes#include "digest.h" 63264377Sdes#include "hmac.h" 6457429Smarkm 65221420Sdesstruct hostkeys { 66221420Sdes struct hostkey_entry *entries; 67221420Sdes u_int num_entries; 68221420Sdes}; 69221420Sdes 70295367Sdes/* XXX hmac is too easy to dictionary attack; use bcrypt? */ 71295367Sdes 72147005Sdesstatic int 73255767Sdesextract_salt(const char *s, u_int l, u_char *salt, size_t salt_len) 74147005Sdes{ 75147005Sdes char *p, *b64salt; 76147005Sdes u_int b64len; 77147005Sdes int ret; 78147005Sdes 79147005Sdes if (l < sizeof(HASH_MAGIC) - 1) { 80147005Sdes debug2("extract_salt: string too short"); 81147005Sdes return (-1); 82147005Sdes } 83147005Sdes if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) { 84147005Sdes debug2("extract_salt: invalid magic identifier"); 85147005Sdes return (-1); 86147005Sdes } 87147005Sdes s += sizeof(HASH_MAGIC) - 1; 88147005Sdes l -= sizeof(HASH_MAGIC) - 1; 89147005Sdes if ((p = memchr(s, HASH_DELIM, l)) == NULL) { 90147005Sdes debug2("extract_salt: missing salt termination character"); 91147005Sdes return (-1); 92147005Sdes } 93147005Sdes 94147005Sdes b64len = p - s; 95147005Sdes /* Sanity check */ 96147005Sdes if (b64len == 0 || b64len > 1024) { 97147005Sdes debug2("extract_salt: bad encoded salt length %u", b64len); 98147005Sdes return (-1); 99147005Sdes } 100147005Sdes b64salt = xmalloc(1 + b64len); 101147005Sdes memcpy(b64salt, s, b64len); 102147005Sdes b64salt[b64len] = '\0'; 103147005Sdes 104147005Sdes ret = __b64_pton(b64salt, salt, salt_len); 105255767Sdes free(b64salt); 106147005Sdes if (ret == -1) { 107147005Sdes debug2("extract_salt: salt decode error"); 108147005Sdes return (-1); 109147005Sdes } 110264377Sdes if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) { 111264377Sdes debug2("extract_salt: expected salt len %zd, got %d", 112264377Sdes ssh_hmac_bytes(SSH_DIGEST_SHA1), ret); 113147005Sdes return (-1); 114147005Sdes } 115147005Sdes 116147005Sdes return (0); 117147005Sdes} 118147005Sdes 119147005Sdeschar * 120147005Sdeshost_hash(const char *host, const char *name_from_hostfile, u_int src_len) 121147005Sdes{ 122264377Sdes struct ssh_hmac_ctx *ctx; 123255767Sdes u_char salt[256], result[256]; 124255767Sdes char uu_salt[512], uu_result[512]; 125147005Sdes static char encoded[1024]; 126147005Sdes u_int i, len; 127147005Sdes 128264377Sdes len = ssh_digest_bytes(SSH_DIGEST_SHA1); 129147005Sdes 130147005Sdes if (name_from_hostfile == NULL) { 131147005Sdes /* Create new salt */ 132147005Sdes for (i = 0; i < len; i++) 133147005Sdes salt[i] = arc4random(); 134147005Sdes } else { 135147005Sdes /* Extract salt from known host entry */ 136147005Sdes if (extract_salt(name_from_hostfile, src_len, salt, 137147005Sdes sizeof(salt)) == -1) 138147005Sdes return (NULL); 139147005Sdes } 140147005Sdes 141264377Sdes if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL || 142264377Sdes ssh_hmac_init(ctx, salt, len) < 0 || 143264377Sdes ssh_hmac_update(ctx, host, strlen(host)) < 0 || 144264377Sdes ssh_hmac_final(ctx, result, sizeof(result))) 145264377Sdes fatal("%s: ssh_hmac failed", __func__); 146264377Sdes ssh_hmac_free(ctx); 147147005Sdes 148147005Sdes if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 || 149147005Sdes __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1) 150264377Sdes fatal("%s: __b64_ntop failed", __func__); 151147005Sdes 152147005Sdes snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt, 153147005Sdes HASH_DELIM, uu_result); 154147005Sdes 155147005Sdes return (encoded); 156147005Sdes} 157147005Sdes 15857429Smarkm/* 15958582Skris * Parses an RSA (number of bits, e, n) or DSA key from a string. Moves the 16058582Skris * pointer over the key. Skips any whitespace at the beginning and at end. 16157429Smarkm */ 16257429Smarkm 16357429Smarkmint 164295367Sdeshostfile_read_key(char **cpp, u_int *bitsp, struct sshkey *ret) 16557429Smarkm{ 16657429Smarkm char *cp; 167295367Sdes int r; 16857429Smarkm 16957429Smarkm /* Skip leading whitespace. */ 17057429Smarkm for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++) 17157429Smarkm ; 17257429Smarkm 173295367Sdes if ((r = sshkey_read(ret, &cp)) != 0) 17457429Smarkm return 0; 17557429Smarkm 17657429Smarkm /* Skip trailing whitespace. */ 17757429Smarkm for (; *cp == ' ' || *cp == '\t'; cp++) 17857429Smarkm ; 17957429Smarkm 18057429Smarkm /* Return results. */ 18157429Smarkm *cpp = cp; 182295367Sdes if (bitsp != NULL) 183295367Sdes *bitsp = sshkey_size(ret); 18457429Smarkm return 1; 18557429Smarkm} 18657429Smarkm 187221420Sdesstatic HostkeyMarker 188204917Sdescheck_markers(char **cpp) 189204917Sdes{ 190204917Sdes char marker[32], *sp, *cp = *cpp; 191204917Sdes int ret = MRK_NONE; 192204917Sdes 193204917Sdes while (*cp == '@') { 194204917Sdes /* Only one marker is allowed */ 195204917Sdes if (ret != MRK_NONE) 196204917Sdes return MRK_ERROR; 197204917Sdes /* Markers are terminated by whitespace */ 198204917Sdes if ((sp = strchr(cp, ' ')) == NULL && 199204917Sdes (sp = strchr(cp, '\t')) == NULL) 200204917Sdes return MRK_ERROR; 201204917Sdes /* Extract marker for comparison */ 202204917Sdes if (sp <= cp + 1 || sp >= cp + sizeof(marker)) 203204917Sdes return MRK_ERROR; 204204917Sdes memcpy(marker, cp, sp - cp); 205204917Sdes marker[sp - cp] = '\0'; 206204917Sdes if (strcmp(marker, CA_MARKER) == 0) 207204917Sdes ret = MRK_CA; 208204917Sdes else if (strcmp(marker, REVOKE_MARKER) == 0) 209204917Sdes ret = MRK_REVOKE; 210204917Sdes else 211204917Sdes return MRK_ERROR; 212204917Sdes 213204917Sdes /* Skip past marker and any whitespace that follows it */ 214204917Sdes cp = sp; 215204917Sdes for (; *cp == ' ' || *cp == '\t'; cp++) 216204917Sdes ; 217204917Sdes } 218204917Sdes *cpp = cp; 219204917Sdes return ret; 220204917Sdes} 221204917Sdes 222221420Sdesstruct hostkeys * 223221420Sdesinit_hostkeys(void) 224221420Sdes{ 225221420Sdes struct hostkeys *ret = xcalloc(1, sizeof(*ret)); 22657429Smarkm 227221420Sdes ret->entries = NULL; 228221420Sdes return ret; 229221420Sdes} 230221420Sdes 231295367Sdesstruct load_callback_ctx { 232295367Sdes const char *host; 233295367Sdes u_long num_loaded; 234295367Sdes struct hostkeys *hostkeys; 235295367Sdes}; 236295367Sdes 237295367Sdesstatic int 238295367Sdesrecord_hostkey(struct hostkey_foreach_line *l, void *_ctx) 23957429Smarkm{ 240295367Sdes struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx; 241295367Sdes struct hostkeys *hostkeys = ctx->hostkeys; 242295367Sdes struct hostkey_entry *tmp; 24357429Smarkm 244295367Sdes if (l->status == HKF_STATUS_INVALID) { 245295367Sdes /* XXX make this verbose() in the future */ 246295367Sdes debug("%s:%ld: parse error in hostkeys file", 247295367Sdes l->path, l->linenum); 248295367Sdes return 0; 249295367Sdes } 25057429Smarkm 251295367Sdes debug3("%s: found %skey type %s in file %s:%lu", __func__, 252295367Sdes l->marker == MRK_NONE ? "" : 253295367Sdes (l->marker == MRK_CA ? "ca " : "revoked "), 254295367Sdes sshkey_type(l->key), l->path, l->linenum); 255295367Sdes if ((tmp = reallocarray(hostkeys->entries, 256295367Sdes hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL) 257295367Sdes return SSH_ERR_ALLOC_FAIL; 258295367Sdes hostkeys->entries = tmp; 259295367Sdes hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host); 260295367Sdes hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path); 261295367Sdes hostkeys->entries[hostkeys->num_entries].line = l->linenum; 262295367Sdes hostkeys->entries[hostkeys->num_entries].key = l->key; 263295367Sdes l->key = NULL; /* steal it */ 264295367Sdes hostkeys->entries[hostkeys->num_entries].marker = l->marker; 265295367Sdes hostkeys->num_entries++; 266295367Sdes ctx->num_loaded++; 26757429Smarkm 268295367Sdes return 0; 269295367Sdes} 270204917Sdes 271295367Sdesvoid 272295367Sdesload_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path) 273295367Sdes{ 274295367Sdes int r; 275295367Sdes struct load_callback_ctx ctx; 27657429Smarkm 277295367Sdes ctx.host = host; 278295367Sdes ctx.num_loaded = 0; 279295367Sdes ctx.hostkeys = hostkeys; 28057429Smarkm 281295367Sdes if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host, NULL, 282295367Sdes HKF_WANT_MATCH|HKF_WANT_PARSE_KEY)) != 0) { 283295367Sdes if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT) 284295367Sdes debug("%s: hostkeys_foreach failed for %s: %s", 285295367Sdes __func__, path, ssh_err(r)); 286221420Sdes } 287295367Sdes if (ctx.num_loaded != 0) 288295367Sdes debug3("%s: loaded %lu keys from %s", __func__, 289295367Sdes ctx.num_loaded, host); 290295367Sdes} 29176262Sgreen 292221420Sdesvoid 293221420Sdesfree_hostkeys(struct hostkeys *hostkeys) 294221420Sdes{ 295221420Sdes u_int i; 296221420Sdes 297221420Sdes for (i = 0; i < hostkeys->num_entries; i++) { 298255767Sdes free(hostkeys->entries[i].host); 299255767Sdes free(hostkeys->entries[i].file); 300295367Sdes sshkey_free(hostkeys->entries[i].key); 301264377Sdes explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries)); 302221420Sdes } 303255767Sdes free(hostkeys->entries); 304264377Sdes explicit_bzero(hostkeys, sizeof(*hostkeys)); 305255767Sdes free(hostkeys); 306221420Sdes} 307221420Sdes 308221420Sdesstatic int 309295367Sdescheck_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k) 310221420Sdes{ 311295367Sdes int is_cert = sshkey_is_cert(k); 312221420Sdes u_int i; 313221420Sdes 314221420Sdes for (i = 0; i < hostkeys->num_entries; i++) { 315221420Sdes if (hostkeys->entries[i].marker != MRK_REVOKE) 316106130Sdes continue; 317295367Sdes if (sshkey_equal_public(k, hostkeys->entries[i].key)) 318221420Sdes return -1; 319221420Sdes if (is_cert && 320295367Sdes sshkey_equal_public(k->cert->signature_key, 321221420Sdes hostkeys->entries[i].key)) 322221420Sdes return -1; 323221420Sdes } 324221420Sdes return 0; 325221420Sdes} 326106130Sdes 327221420Sdes/* 328221420Sdes * Match keys against a specified key, or look one up by key type. 329221420Sdes * 330221420Sdes * If looking for a keytype (key == NULL) and one is found then return 331221420Sdes * HOST_FOUND, otherwise HOST_NEW. 332221420Sdes * 333221420Sdes * If looking for a key (key != NULL): 334221420Sdes * 1. If the key is a cert and a matching CA is found, return HOST_OK 335221420Sdes * 2. If the key is not a cert and a matching key is found, return HOST_OK 336221420Sdes * 3. If no key matches but a key with a different type is found, then 337221420Sdes * return HOST_CHANGED 338221420Sdes * 4. If no matching keys are found, then return HOST_NEW. 339221420Sdes * 340221420Sdes * Finally, check any found key is not revoked. 341221420Sdes */ 342221420Sdesstatic HostStatus 343221420Sdescheck_hostkeys_by_key_or_type(struct hostkeys *hostkeys, 344295367Sdes struct sshkey *k, int keytype, const struct hostkey_entry **found) 345221420Sdes{ 346221420Sdes u_int i; 347221420Sdes HostStatus end_return = HOST_NEW; 348295367Sdes int want_cert = sshkey_is_cert(k); 349221420Sdes HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE; 350221420Sdes int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2; 351221420Sdes 352221420Sdes if (found != NULL) 353221420Sdes *found = NULL; 354221420Sdes 355221420Sdes for (i = 0; i < hostkeys->num_entries; i++) { 356221420Sdes if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1) 357106130Sdes continue; 358221420Sdes if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1) 359221420Sdes continue; 360221420Sdes if (hostkeys->entries[i].marker != want_marker) 361221420Sdes continue; 362221420Sdes if (k == NULL) { 363221420Sdes if (hostkeys->entries[i].key->type != keytype) 364221420Sdes continue; 365221420Sdes end_return = HOST_FOUND; 366221420Sdes if (found != NULL) 367221420Sdes *found = hostkeys->entries + i; 368221420Sdes k = hostkeys->entries[i].key; 369221420Sdes break; 370221420Sdes } 371221420Sdes if (want_cert) { 372295367Sdes if (sshkey_equal_public(k->cert->signature_key, 373221420Sdes hostkeys->entries[i].key)) { 374221420Sdes /* A matching CA exists */ 375221420Sdes end_return = HOST_OK; 376221420Sdes if (found != NULL) 377221420Sdes *found = hostkeys->entries + i; 378221420Sdes break; 379204917Sdes } 380221420Sdes } else { 381295367Sdes if (sshkey_equal(k, hostkeys->entries[i].key)) { 382221420Sdes end_return = HOST_OK; 383221420Sdes if (found != NULL) 384221420Sdes *found = hostkeys->entries + i; 385221420Sdes break; 386204917Sdes } 387221420Sdes /* A non-maching key exists */ 388221420Sdes end_return = HOST_CHANGED; 389221420Sdes if (found != NULL) 390221420Sdes *found = hostkeys->entries + i; 391204917Sdes } 39257429Smarkm } 393221420Sdes if (check_key_not_revoked(hostkeys, k) != 0) { 394221420Sdes end_return = HOST_REVOKED; 395221420Sdes if (found != NULL) 396221420Sdes *found = NULL; 397221420Sdes } 39857429Smarkm return end_return; 39957429Smarkm} 400295367Sdes 401106130SdesHostStatus 402295367Sdescheck_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key, 403221420Sdes const struct hostkey_entry **found) 404106130Sdes{ 405106130Sdes if (key == NULL) 406106130Sdes fatal("no key to look up"); 407221420Sdes return check_hostkeys_by_key_or_type(hostkeys, key, 0, found); 408106130Sdes} 409106130Sdes 410106130Sdesint 411221420Sdeslookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype, 412221420Sdes const struct hostkey_entry **found) 413106130Sdes{ 414221420Sdes return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype, 415221420Sdes found) == HOST_FOUND); 416106130Sdes} 417106130Sdes 418295367Sdesstatic int 419295367Sdeswrite_host_entry(FILE *f, const char *host, const char *ip, 420295367Sdes const struct sshkey *key, int store_hash) 421295367Sdes{ 422295367Sdes int r, success = 0; 423295367Sdes char *hashed_host = NULL; 424295367Sdes 425295367Sdes if (store_hash) { 426295367Sdes if ((hashed_host = host_hash(host, NULL, 0)) == NULL) { 427295367Sdes error("%s: host_hash failed", __func__); 428295367Sdes return 0; 429295367Sdes } 430295367Sdes fprintf(f, "%s ", hashed_host); 431295367Sdes } else if (ip != NULL) 432295367Sdes fprintf(f, "%s,%s ", host, ip); 433295367Sdes else 434295367Sdes fprintf(f, "%s ", host); 435295367Sdes 436295367Sdes if ((r = sshkey_write(key, f)) == 0) 437295367Sdes success = 1; 438295367Sdes else 439295367Sdes error("%s: sshkey_write failed: %s", __func__, ssh_err(r)); 440295367Sdes fputc('\n', f); 441295367Sdes return success; 442295367Sdes} 443295367Sdes 44457429Smarkm/* 44557429Smarkm * Appends an entry to the host file. Returns false if the entry could not 44657429Smarkm * be appended. 44757429Smarkm */ 44857429Smarkmint 449295367Sdesadd_host_to_hostfile(const char *filename, const char *host, 450295367Sdes const struct sshkey *key, int store_hash) 45157429Smarkm{ 45257429Smarkm FILE *f; 453295367Sdes int success; 454147005Sdes 45558582Skris if (key == NULL) 45660576Skris return 1; /* XXX ? */ 45757429Smarkm f = fopen(filename, "a"); 45857429Smarkm if (!f) 45957429Smarkm return 0; 460295367Sdes success = write_host_entry(f, host, NULL, key, store_hash); 461295367Sdes fclose(f); 462295367Sdes return success; 463295367Sdes} 464147005Sdes 465295367Sdesstruct host_delete_ctx { 466295367Sdes FILE *out; 467295367Sdes int quiet; 468295367Sdes const char *host; 469295367Sdes int *skip_keys; /* XXX split for host/ip? might want to ensure both */ 470295367Sdes struct sshkey * const *keys; 471295367Sdes size_t nkeys; 472295367Sdes int modified; 473295367Sdes}; 474295367Sdes 475295367Sdesstatic int 476295367Sdeshost_delete(struct hostkey_foreach_line *l, void *_ctx) 477295367Sdes{ 478295367Sdes struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx; 479295367Sdes int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE; 480295367Sdes size_t i; 481295367Sdes 482295367Sdes if (l->status == HKF_STATUS_MATCHED) { 483295367Sdes if (l->marker != MRK_NONE) { 484295367Sdes /* Don't remove CA and revocation lines */ 485295367Sdes fprintf(ctx->out, "%s\n", l->line); 486147005Sdes return 0; 487147005Sdes } 488295367Sdes 489295367Sdes /* XXX might need a knob for this later */ 490295367Sdes /* Don't remove RSA1 keys */ 491295367Sdes if (l->key->type == KEY_RSA1) { 492295367Sdes fprintf(ctx->out, "%s\n", l->line); 493295367Sdes return 0; 494295367Sdes } 495295367Sdes 496295367Sdes /* 497295367Sdes * If this line contains one of the keys that we will be 498295367Sdes * adding later, then don't change it and mark the key for 499295367Sdes * skipping. 500295367Sdes */ 501295367Sdes for (i = 0; i < ctx->nkeys; i++) { 502295367Sdes if (sshkey_equal(ctx->keys[i], l->key)) { 503295367Sdes ctx->skip_keys[i] = 1; 504295367Sdes fprintf(ctx->out, "%s\n", l->line); 505295367Sdes debug3("%s: %s key already at %s:%ld", __func__, 506295367Sdes sshkey_type(l->key), l->path, l->linenum); 507295367Sdes return 0; 508295367Sdes } 509295367Sdes } 510295367Sdes 511295367Sdes /* 512295367Sdes * Hostname matches and has no CA/revoke marker, delete it 513295367Sdes * by *not* writing the line to ctx->out. 514295367Sdes */ 515295367Sdes do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s", 516295367Sdes ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "", 517295367Sdes l->path, l->linenum, sshkey_type(l->key), ctx->host); 518295367Sdes ctx->modified = 1; 519295367Sdes return 0; 520147005Sdes } 521295367Sdes /* Retain non-matching hosts and invalid lines when deleting */ 522295367Sdes if (l->status == HKF_STATUS_INVALID) { 523295367Sdes do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry", 524295367Sdes ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "", 525295367Sdes l->path, l->linenum); 526295367Sdes } 527295367Sdes fprintf(ctx->out, "%s\n", l->line); 528295367Sdes return 0; 529295367Sdes} 530147005Sdes 531295367Sdesint 532295367Sdeshostfile_replace_entries(const char *filename, const char *host, const char *ip, 533295367Sdes struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg) 534295367Sdes{ 535295367Sdes int r, fd, oerrno = 0; 536295367Sdes int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE; 537295367Sdes struct host_delete_ctx ctx; 538295367Sdes char *fp, *temp = NULL, *back = NULL; 539295367Sdes mode_t omask; 540295367Sdes size_t i; 541295367Sdes 542295367Sdes omask = umask(077); 543295367Sdes 544295367Sdes memset(&ctx, 0, sizeof(ctx)); 545295367Sdes ctx.host = host; 546295367Sdes ctx.quiet = quiet; 547295367Sdes if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL) 548295367Sdes return SSH_ERR_ALLOC_FAIL; 549295367Sdes ctx.keys = keys; 550295367Sdes ctx.nkeys = nkeys; 551295367Sdes ctx.modified = 0; 552295367Sdes 553295367Sdes /* 554295367Sdes * Prepare temporary file for in-place deletion. 555295367Sdes */ 556295367Sdes if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) < 0 || 557295367Sdes (r = asprintf(&back, "%s.old", filename)) < 0) { 558295367Sdes r = SSH_ERR_ALLOC_FAIL; 559295367Sdes goto fail; 560295367Sdes } 561295367Sdes 562295367Sdes if ((fd = mkstemp(temp)) == -1) { 563295367Sdes oerrno = errno; 564295367Sdes error("%s: mkstemp: %s", __func__, strerror(oerrno)); 565295367Sdes r = SSH_ERR_SYSTEM_ERROR; 566295367Sdes goto fail; 567295367Sdes } 568295367Sdes if ((ctx.out = fdopen(fd, "w")) == NULL) { 569295367Sdes oerrno = errno; 570295367Sdes close(fd); 571295367Sdes error("%s: fdopen: %s", __func__, strerror(oerrno)); 572295367Sdes r = SSH_ERR_SYSTEM_ERROR; 573295367Sdes goto fail; 574295367Sdes } 575295367Sdes 576295367Sdes /* Remove all entries for the specified host from the file */ 577295367Sdes if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip, 578295367Sdes HKF_WANT_PARSE_KEY)) != 0) { 579295367Sdes error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r)); 580295367Sdes goto fail; 581295367Sdes } 582295367Sdes 583295367Sdes /* Add the requested keys */ 584295367Sdes for (i = 0; i < nkeys; i++) { 585295367Sdes if (ctx.skip_keys[i]) 586295367Sdes continue; 587295367Sdes if ((fp = sshkey_fingerprint(keys[i], hash_alg, 588295367Sdes SSH_FP_DEFAULT)) == NULL) { 589295367Sdes r = SSH_ERR_ALLOC_FAIL; 590295367Sdes goto fail; 591295367Sdes } 592295367Sdes do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s", 593295367Sdes quiet ? __func__ : "", quiet ? ": " : "", host, filename, 594295367Sdes sshkey_ssh_name(keys[i]), fp); 595295367Sdes free(fp); 596295367Sdes if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) { 597295367Sdes r = SSH_ERR_INTERNAL_ERROR; 598295367Sdes goto fail; 599295367Sdes } 600295367Sdes ctx.modified = 1; 601295367Sdes } 602295367Sdes fclose(ctx.out); 603295367Sdes ctx.out = NULL; 604295367Sdes 605295367Sdes if (ctx.modified) { 606295367Sdes /* Backup the original file and replace it with the temporary */ 607295367Sdes if (unlink(back) == -1 && errno != ENOENT) { 608295367Sdes oerrno = errno; 609295367Sdes error("%s: unlink %.100s: %s", __func__, 610295367Sdes back, strerror(errno)); 611295367Sdes r = SSH_ERR_SYSTEM_ERROR; 612295367Sdes goto fail; 613295367Sdes } 614295367Sdes if (link(filename, back) == -1) { 615295367Sdes oerrno = errno; 616295367Sdes error("%s: link %.100s to %.100s: %s", __func__, 617295367Sdes filename, back, strerror(errno)); 618295367Sdes r = SSH_ERR_SYSTEM_ERROR; 619295367Sdes goto fail; 620295367Sdes } 621295367Sdes if (rename(temp, filename) == -1) { 622295367Sdes oerrno = errno; 623295367Sdes error("%s: rename \"%s\" to \"%s\": %s", __func__, 624295367Sdes temp, filename, strerror(errno)); 625295367Sdes r = SSH_ERR_SYSTEM_ERROR; 626295367Sdes goto fail; 627295367Sdes } 62858582Skris } else { 629295367Sdes /* No changes made; just delete the temporary file */ 630295367Sdes if (unlink(temp) != 0) 631295367Sdes error("%s: unlink \"%s\": %s", __func__, 632295367Sdes temp, strerror(errno)); 63357429Smarkm } 634295367Sdes 635295367Sdes /* success */ 636295367Sdes r = 0; 637295367Sdes fail: 638295367Sdes if (temp != NULL && r != 0) 639295367Sdes unlink(temp); 640295367Sdes free(temp); 641295367Sdes free(back); 642295367Sdes if (ctx.out != NULL) 643295367Sdes fclose(ctx.out); 644295367Sdes free(ctx.skip_keys); 645295367Sdes umask(omask); 646295367Sdes if (r == SSH_ERR_SYSTEM_ERROR) 647295367Sdes errno = oerrno; 648295367Sdes return r; 649295367Sdes} 650295367Sdes 651295367Sdesstatic int 652295367Sdesmatch_maybe_hashed(const char *host, const char *names, int *was_hashed) 653295367Sdes{ 654295367Sdes int hashed = *names == HASH_DELIM; 655295367Sdes const char *hashed_host; 656295367Sdes size_t nlen = strlen(names); 657295367Sdes 658295367Sdes if (was_hashed != NULL) 659295367Sdes *was_hashed = hashed; 660295367Sdes if (hashed) { 661295367Sdes if ((hashed_host = host_hash(host, names, nlen)) == NULL) 662295367Sdes return -1; 663295367Sdes return nlen == strlen(hashed_host) && 664295367Sdes strncmp(hashed_host, names, nlen) == 0; 665295367Sdes } 666295367Sdes return match_hostname(host, names) == 1; 667295367Sdes} 668295367Sdes 669295367Sdesint 670295367Sdeshostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx, 671295367Sdes const char *host, const char *ip, u_int options) 672295367Sdes{ 673295367Sdes FILE *f; 674295367Sdes char line[8192], oline[8192], ktype[128]; 675295367Sdes u_long linenum = 0; 676295367Sdes char *cp, *cp2; 677295367Sdes u_int kbits; 678295367Sdes int hashed; 679295367Sdes int s, r = 0; 680295367Sdes struct hostkey_foreach_line lineinfo; 681295367Sdes size_t l; 682295367Sdes 683295367Sdes memset(&lineinfo, 0, sizeof(lineinfo)); 684295367Sdes if (host == NULL && (options & HKF_WANT_MATCH) != 0) 685295367Sdes return SSH_ERR_INVALID_ARGUMENT; 686295367Sdes if ((f = fopen(path, "r")) == NULL) 687295367Sdes return SSH_ERR_SYSTEM_ERROR; 688295367Sdes 689295367Sdes debug3("%s: reading file \"%s\"", __func__, path); 690295367Sdes while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) { 691295367Sdes line[strcspn(line, "\n")] = '\0'; 692295367Sdes strlcpy(oline, line, sizeof(oline)); 693295367Sdes 694295367Sdes sshkey_free(lineinfo.key); 695295367Sdes memset(&lineinfo, 0, sizeof(lineinfo)); 696295367Sdes lineinfo.path = path; 697295367Sdes lineinfo.linenum = linenum; 698295367Sdes lineinfo.line = oline; 699295367Sdes lineinfo.marker = MRK_NONE; 700295367Sdes lineinfo.status = HKF_STATUS_OK; 701295367Sdes lineinfo.keytype = KEY_UNSPEC; 702295367Sdes 703295367Sdes /* Skip any leading whitespace, comments and empty lines. */ 704295367Sdes for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 705295367Sdes ; 706295367Sdes if (!*cp || *cp == '#' || *cp == '\n') { 707295367Sdes if ((options & HKF_WANT_MATCH) == 0) { 708295367Sdes lineinfo.status = HKF_STATUS_COMMENT; 709295367Sdes if ((r = callback(&lineinfo, ctx)) != 0) 710295367Sdes break; 711295367Sdes } 712295367Sdes continue; 713295367Sdes } 714295367Sdes 715295367Sdes if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) { 716295367Sdes verbose("%s: invalid marker at %s:%lu", 717295367Sdes __func__, path, linenum); 718295367Sdes if ((options & HKF_WANT_MATCH) == 0) 719295367Sdes goto bad; 720295367Sdes continue; 721295367Sdes } 722295367Sdes 723295367Sdes /* Find the end of the host name portion. */ 724295367Sdes for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++) 725295367Sdes ; 726295367Sdes lineinfo.hosts = cp; 727295367Sdes *cp2++ = '\0'; 728295367Sdes 729295367Sdes /* Check if the host name matches. */ 730295367Sdes if (host != NULL) { 731295367Sdes if ((s = match_maybe_hashed(host, lineinfo.hosts, 732295367Sdes &hashed)) == -1) { 733295367Sdes debug2("%s: %s:%ld: bad host hash \"%.32s\"", 734295367Sdes __func__, path, linenum, lineinfo.hosts); 735295367Sdes goto bad; 736295367Sdes } 737295367Sdes if (s == 1) { 738295367Sdes lineinfo.status = HKF_STATUS_MATCHED; 739295367Sdes lineinfo.match |= HKF_MATCH_HOST | 740295367Sdes (hashed ? HKF_MATCH_HOST_HASHED : 0); 741295367Sdes } 742295367Sdes /* Try matching IP address if supplied */ 743295367Sdes if (ip != NULL) { 744295367Sdes if ((s = match_maybe_hashed(ip, lineinfo.hosts, 745295367Sdes &hashed)) == -1) { 746295367Sdes debug2("%s: %s:%ld: bad ip hash " 747295367Sdes "\"%.32s\"", __func__, path, 748295367Sdes linenum, lineinfo.hosts); 749295367Sdes goto bad; 750295367Sdes } 751295367Sdes if (s == 1) { 752295367Sdes lineinfo.status = HKF_STATUS_MATCHED; 753295367Sdes lineinfo.match |= HKF_MATCH_IP | 754295367Sdes (hashed ? HKF_MATCH_IP_HASHED : 0); 755295367Sdes } 756295367Sdes } 757295367Sdes /* 758295367Sdes * Skip this line if host matching requested and 759295367Sdes * neither host nor address matched. 760295367Sdes */ 761295367Sdes if ((options & HKF_WANT_MATCH) != 0 && 762295367Sdes lineinfo.status != HKF_STATUS_MATCHED) 763295367Sdes continue; 764295367Sdes } 765295367Sdes 766295367Sdes /* Got a match. Skip host name and any following whitespace */ 767295367Sdes for (; *cp2 == ' ' || *cp2 == '\t'; cp2++) 768295367Sdes ; 769295367Sdes if (*cp2 == '\0' || *cp2 == '#') { 770295367Sdes debug2("%s:%ld: truncated before key type", 771295367Sdes path, linenum); 772295367Sdes goto bad; 773295367Sdes } 774295367Sdes lineinfo.rawkey = cp = cp2; 775295367Sdes 776295367Sdes if ((options & HKF_WANT_PARSE_KEY) != 0) { 777295367Sdes /* 778295367Sdes * Extract the key from the line. This will skip 779295367Sdes * any leading whitespace. Ignore badly formatted 780295367Sdes * lines. 781295367Sdes */ 782295367Sdes if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) { 783295367Sdes error("%s: sshkey_new failed", __func__); 784295367Sdes r = SSH_ERR_ALLOC_FAIL; 785295367Sdes break; 786295367Sdes } 787295367Sdes if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) { 788295367Sdes#ifdef WITH_SSH1 789295367Sdes sshkey_free(lineinfo.key); 790295367Sdes lineinfo.key = sshkey_new(KEY_RSA1); 791295367Sdes if (lineinfo.key == NULL) { 792295367Sdes error("%s: sshkey_new fail", __func__); 793295367Sdes r = SSH_ERR_ALLOC_FAIL; 794295367Sdes break; 795295367Sdes } 796295367Sdes if (!hostfile_read_key(&cp, &kbits, 797295367Sdes lineinfo.key)) 798295367Sdes goto bad; 799295367Sdes#else 800295367Sdes goto bad; 801295367Sdes#endif 802295367Sdes } 803295367Sdes lineinfo.keytype = lineinfo.key->type; 804295367Sdes lineinfo.comment = cp; 805295367Sdes } else { 806295367Sdes /* Extract and parse key type */ 807295367Sdes l = strcspn(lineinfo.rawkey, " \t"); 808295367Sdes if (l <= 1 || l >= sizeof(ktype) || 809295367Sdes lineinfo.rawkey[l] == '\0') 810295367Sdes goto bad; 811295367Sdes memcpy(ktype, lineinfo.rawkey, l); 812295367Sdes ktype[l] = '\0'; 813295367Sdes lineinfo.keytype = sshkey_type_from_name(ktype); 814295367Sdes 815295367Sdes /* 816295367Sdes * Assume RSA1 if the first component is a short 817295367Sdes * decimal number. 818295367Sdes */ 819295367Sdes if (lineinfo.keytype == KEY_UNSPEC && l < 8 && 820295367Sdes strspn(ktype, "0123456789") == l) 821295367Sdes lineinfo.keytype = KEY_RSA1; 822295367Sdes 823295367Sdes /* 824295367Sdes * Check that something other than whitespace follows 825295367Sdes * the key type. This won't catch all corruption, but 826295367Sdes * it does catch trivial truncation. 827295367Sdes */ 828295367Sdes cp2 += l; /* Skip past key type */ 829295367Sdes for (; *cp2 == ' ' || *cp2 == '\t'; cp2++) 830295367Sdes ; 831295367Sdes if (*cp2 == '\0' || *cp2 == '#') { 832295367Sdes debug2("%s:%ld: truncated after key type", 833295367Sdes path, linenum); 834295367Sdes lineinfo.keytype = KEY_UNSPEC; 835295367Sdes } 836295367Sdes if (lineinfo.keytype == KEY_UNSPEC) { 837295367Sdes bad: 838295367Sdes sshkey_free(lineinfo.key); 839295367Sdes lineinfo.key = NULL; 840295367Sdes lineinfo.status = HKF_STATUS_INVALID; 841295367Sdes if ((r = callback(&lineinfo, ctx)) != 0) 842295367Sdes break; 843295367Sdes continue; 844295367Sdes } 845295367Sdes } 846295367Sdes if ((r = callback(&lineinfo, ctx)) != 0) 847295367Sdes break; 848295367Sdes } 849295367Sdes sshkey_free(lineinfo.key); 85057429Smarkm fclose(f); 851295367Sdes return r; 85257429Smarkm} 853