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