Annotation of src/usr.bin/ssh/hostfile.c, Revision 1.63
1.63 ! djm 1: /* $OpenBSD: hostfile.c,v 1.62 2015/01/26 03:04:45 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.44 stevesk 46: #include <stdio.h>
1.43 stevesk 47: #include <stdlib.h>
1.42 stevesk 48: #include <string.h>
1.57 djm 49: #include <stdarg.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.59 djm 58: #include "ssherr.h"
1.53 djm 59: #include "digest.h"
1.54 markus 60: #include "hmac.h"
1.49 djm 61:
62: struct hostkeys {
63: struct hostkey_entry *entries;
64: u_int num_entries;
65: };
1.33 djm 66:
1.60 djm 67: /* XXX hmac is too easy to dictionary attack; use bcrypt? */
68:
1.33 djm 69: static int
1.52 djm 70: extract_salt(const char *s, u_int l, u_char *salt, size_t salt_len)
1.33 djm 71: {
72: char *p, *b64salt;
73: u_int b64len;
74: int ret;
75:
76: if (l < sizeof(HASH_MAGIC) - 1) {
77: debug2("extract_salt: string too short");
78: return (-1);
79: }
80: if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) {
81: debug2("extract_salt: invalid magic identifier");
82: return (-1);
83: }
84: s += sizeof(HASH_MAGIC) - 1;
85: l -= sizeof(HASH_MAGIC) - 1;
86: if ((p = memchr(s, HASH_DELIM, l)) == NULL) {
87: debug2("extract_salt: missing salt termination character");
88: return (-1);
89: }
90:
91: b64len = p - s;
92: /* Sanity check */
93: if (b64len == 0 || b64len > 1024) {
94: debug2("extract_salt: bad encoded salt length %u", b64len);
95: return (-1);
96: }
97: b64salt = xmalloc(1 + b64len);
98: memcpy(b64salt, s, b64len);
99: b64salt[b64len] = '\0';
100:
101: ret = __b64_pton(b64salt, salt, salt_len);
1.51 djm 102: free(b64salt);
1.33 djm 103: if (ret == -1) {
104: debug2("extract_salt: salt decode error");
105: return (-1);
106: }
1.54 markus 107: if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) {
108: debug2("extract_salt: expected salt len %zd, got %d",
109: ssh_hmac_bytes(SSH_DIGEST_SHA1), ret);
1.33 djm 110: return (-1);
111: }
1.34 deraadt 112:
1.33 djm 113: return (0);
114: }
115:
116: char *
117: host_hash(const char *host, const char *name_from_hostfile, u_int src_len)
118: {
1.54 markus 119: struct ssh_hmac_ctx *ctx;
1.52 djm 120: u_char salt[256], result[256];
121: char uu_salt[512], uu_result[512];
1.33 djm 122: static char encoded[1024];
123: u_int i, len;
124:
1.54 markus 125: len = ssh_digest_bytes(SSH_DIGEST_SHA1);
1.33 djm 126:
127: if (name_from_hostfile == NULL) {
128: /* Create new salt */
129: for (i = 0; i < len; i++)
130: salt[i] = arc4random();
131: } else {
132: /* Extract salt from known host entry */
133: if (extract_salt(name_from_hostfile, src_len, salt,
134: sizeof(salt)) == -1)
135: return (NULL);
136: }
137:
1.54 markus 138: if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL ||
139: ssh_hmac_init(ctx, salt, len) < 0 ||
140: ssh_hmac_update(ctx, host, strlen(host)) < 0 ||
141: ssh_hmac_final(ctx, result, sizeof(result)))
142: fatal("%s: ssh_hmac failed", __func__);
143: ssh_hmac_free(ctx);
1.33 djm 144:
1.34 deraadt 145: if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
1.33 djm 146: __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
1.54 markus 147: fatal("%s: __b64_ntop failed", __func__);
1.33 djm 148:
149: snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt,
150: HASH_DELIM, uu_result);
151:
152: return (encoded);
153: }
1.1 deraadt 154:
1.9 markus 155: /*
1.14 markus 156: * Parses an RSA (number of bits, e, n) or DSA key from a string. Moves the
157: * pointer over the key. Skips any whitespace at the beginning and at end.
1.9 markus 158: */
1.1 deraadt 159:
1.29 jakob 160: int
1.59 djm 161: hostfile_read_key(char **cpp, u_int *bitsp, struct sshkey *ret)
1.1 deraadt 162: {
1.7 markus 163: char *cp;
1.59 djm 164: int r;
1.7 markus 165:
166: /* Skip leading whitespace. */
1.9 markus 167: for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
168: ;
1.1 deraadt 169:
1.59 djm 170: if ((r = sshkey_read(ret, &cp)) != 0)
1.7 markus 171: return 0;
172:
173: /* Skip trailing whitespace. */
1.9 markus 174: for (; *cp == ' ' || *cp == '\t'; cp++)
175: ;
1.7 markus 176:
177: /* Return results. */
178: *cpp = cp;
1.59 djm 179: if (bitsp != NULL)
180: *bitsp = sshkey_size(ret);
1.7 markus 181: return 1;
1.14 markus 182: }
1.1 deraadt 183:
1.27 itojun 184: static int
1.59 djm 185: hostfile_check_key(int bits, const struct sshkey *key, const char *host,
1.49 djm 186: const char *filename, u_long linenum)
1.1 deraadt 187: {
1.56 markus 188: #ifdef WITH_SSH1
1.21 markus 189: if (key == NULL || key->type != KEY_RSA1 || key->rsa == NULL)
1.14 markus 190: return 1;
191: if (bits != BN_num_bits(key->rsa->n)) {
1.49 djm 192: logit("Warning: %s, line %lu: keysize mismatch for host %s: "
1.14 markus 193: "actual %d vs. announced %d.",
194: filename, linenum, host, BN_num_bits(key->rsa->n), bits);
1.49 djm 195: logit("Warning: replace %d with %d in %s, line %lu.",
1.14 markus 196: bits, BN_num_bits(key->rsa->n), filename, linenum);
1.1 deraadt 197: }
1.56 markus 198: #endif
1.14 markus 199: return 1;
1.1 deraadt 200: }
201:
1.49 djm 202: static HostkeyMarker
1.48 djm 203: check_markers(char **cpp)
204: {
205: char marker[32], *sp, *cp = *cpp;
206: int ret = MRK_NONE;
207:
208: while (*cp == '@') {
209: /* Only one marker is allowed */
210: if (ret != MRK_NONE)
211: return MRK_ERROR;
212: /* Markers are terminated by whitespace */
213: if ((sp = strchr(cp, ' ')) == NULL &&
214: (sp = strchr(cp, '\t')) == NULL)
215: return MRK_ERROR;
216: /* Extract marker for comparison */
217: if (sp <= cp + 1 || sp >= cp + sizeof(marker))
218: return MRK_ERROR;
219: memcpy(marker, cp, sp - cp);
220: marker[sp - cp] = '\0';
221: if (strcmp(marker, CA_MARKER) == 0)
222: ret = MRK_CA;
223: else if (strcmp(marker, REVOKE_MARKER) == 0)
224: ret = MRK_REVOKE;
225: else
226: return MRK_ERROR;
227:
228: /* Skip past marker and any whitespace that follows it */
229: cp = sp;
230: for (; *cp == ' ' || *cp == '\t'; cp++)
231: ;
232: }
233: *cpp = cp;
234: return ret;
235: }
236:
1.49 djm 237: struct hostkeys *
238: init_hostkeys(void)
239: {
240: struct hostkeys *ret = xcalloc(1, sizeof(*ret));
241:
242: ret->entries = NULL;
243: return ret;
244: }
1.1 deraadt 245:
1.61 djm 246: struct load_callback_ctx {
247: const char *host;
248: u_long num_loaded;
249: struct hostkeys *hostkeys;
250: };
251:
252: static int
253: record_hostkey(struct hostkey_foreach_line *l, void *_ctx)
1.1 deraadt 254: {
1.61 djm 255: struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx;
256: struct hostkeys *hostkeys = ctx->hostkeys;
257: struct hostkey_entry *tmp;
258:
259: if (l->status == HKF_STATUS_INVALID) {
260: error("%s:%ld: parse error in hostkeys file",
261: l->path, l->linenum);
262: return 0;
263: }
1.7 markus 264:
1.61 djm 265: debug3("%s: found %skey type %s in file %s:%lu", __func__,
266: l->marker == MRK_NONE ? "" :
267: (l->marker == MRK_CA ? "ca " : "revoked "),
268: sshkey_type(l->key), l->path, l->linenum);
269: if ((tmp = reallocarray(hostkeys->entries,
270: hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL)
271: return SSH_ERR_ALLOC_FAIL;
272: hostkeys->entries = tmp;
273: hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host);
274: hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path);
275: hostkeys->entries[hostkeys->num_entries].line = l->linenum;
276: hostkeys->entries[hostkeys->num_entries].key = l->key;
277: l->key = NULL; /* steal it */
278: hostkeys->entries[hostkeys->num_entries].marker = l->marker;
279: hostkeys->num_entries++;
280: ctx->num_loaded++;
1.7 markus 281:
1.61 djm 282: return 0;
283: }
1.47 djm 284:
1.61 djm 285: void
286: load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
287: {
288: int r;
289: struct load_callback_ctx ctx;
1.7 markus 290:
1.61 djm 291: ctx.host = host;
292: ctx.num_loaded = 0;
293: ctx.hostkeys = hostkeys;
294:
295: if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host,
296: HKF_WANT_MATCH_HOST|HKF_WANT_PARSE_KEY)) != 0) {
297: if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT)
298: debug("%s: hostkeys_foreach failed for %s: %s",
299: __func__, path, ssh_err(r));
300: }
301: if (ctx.num_loaded != 0)
302: debug3("%s: loaded %lu keys from %s", __func__,
303: ctx.num_loaded, host);
1.58 djm 304: }
1.49 djm 305:
306: void
307: free_hostkeys(struct hostkeys *hostkeys)
308: {
309: u_int i;
310:
311: for (i = 0; i < hostkeys->num_entries; i++) {
1.51 djm 312: free(hostkeys->entries[i].host);
313: free(hostkeys->entries[i].file);
1.59 djm 314: sshkey_free(hostkeys->entries[i].key);
1.55 tedu 315: explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
1.49 djm 316: }
1.51 djm 317: free(hostkeys->entries);
1.55 tedu 318: explicit_bzero(hostkeys, sizeof(*hostkeys));
1.51 djm 319: free(hostkeys);
1.49 djm 320: }
321:
322: static int
1.59 djm 323: check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
1.49 djm 324: {
1.59 djm 325: int is_cert = sshkey_is_cert(k);
1.49 djm 326: u_int i;
1.7 markus 327:
1.49 djm 328: for (i = 0; i < hostkeys->num_entries; i++) {
329: if (hostkeys->entries[i].marker != MRK_REVOKE)
1.30 markus 330: continue;
1.59 djm 331: if (sshkey_equal_public(k, hostkeys->entries[i].key))
1.49 djm 332: return -1;
333: if (is_cert &&
1.59 djm 334: sshkey_equal_public(k->cert->signature_key,
1.49 djm 335: hostkeys->entries[i].key))
336: return -1;
337: }
338: return 0;
339: }
340:
341: /*
342: * Match keys against a specified key, or look one up by key type.
343: *
344: * If looking for a keytype (key == NULL) and one is found then return
345: * HOST_FOUND, otherwise HOST_NEW.
346: *
347: * If looking for a key (key != NULL):
348: * 1. If the key is a cert and a matching CA is found, return HOST_OK
349: * 2. If the key is not a cert and a matching key is found, return HOST_OK
350: * 3. If no key matches but a key with a different type is found, then
351: * return HOST_CHANGED
352: * 4. If no matching keys are found, then return HOST_NEW.
353: *
354: * Finally, check any found key is not revoked.
355: */
356: static HostStatus
357: check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
1.59 djm 358: struct sshkey *k, int keytype, const struct hostkey_entry **found)
1.49 djm 359: {
360: u_int i;
361: HostStatus end_return = HOST_NEW;
1.59 djm 362: int want_cert = sshkey_is_cert(k);
1.49 djm 363: HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
364: int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2;
365:
366: if (found != NULL)
367: *found = NULL;
1.30 markus 368:
1.49 djm 369: for (i = 0; i < hostkeys->num_entries; i++) {
370: if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1)
371: continue;
372: if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1)
1.30 markus 373: continue;
1.49 djm 374: if (hostkeys->entries[i].marker != want_marker)
375: continue;
376: if (k == NULL) {
377: if (hostkeys->entries[i].key->type != keytype)
378: continue;
379: end_return = HOST_FOUND;
380: if (found != NULL)
381: *found = hostkeys->entries + i;
382: k = hostkeys->entries[i].key;
383: break;
384: }
385: if (want_cert) {
1.59 djm 386: if (sshkey_equal_public(k->cert->signature_key,
1.49 djm 387: hostkeys->entries[i].key)) {
388: /* A matching CA exists */
389: end_return = HOST_OK;
390: if (found != NULL)
391: *found = hostkeys->entries + i;
392: break;
1.48 djm 393: }
1.49 djm 394: } else {
1.59 djm 395: if (sshkey_equal(k, hostkeys->entries[i].key)) {
1.49 djm 396: end_return = HOST_OK;
397: if (found != NULL)
398: *found = hostkeys->entries + i;
399: break;
1.48 djm 400: }
1.49 djm 401: /* A non-maching key exists */
402: end_return = HOST_CHANGED;
403: if (found != NULL)
404: *found = hostkeys->entries + i;
1.48 djm 405: }
1.1 deraadt 406: }
1.49 djm 407: if (check_key_not_revoked(hostkeys, k) != 0) {
408: end_return = HOST_REVOKED;
409: if (found != NULL)
410: *found = NULL;
411: }
1.7 markus 412: return end_return;
1.30 markus 413: }
1.58 djm 414:
1.30 markus 415: HostStatus
1.59 djm 416: check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
1.49 djm 417: const struct hostkey_entry **found)
1.30 markus 418: {
419: if (key == NULL)
420: fatal("no key to look up");
1.49 djm 421: return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
1.30 markus 422: }
423:
424: int
1.49 djm 425: lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
426: const struct hostkey_entry **found)
1.30 markus 427: {
1.49 djm 428: return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
429: found) == HOST_FOUND);
1.1 deraadt 430: }
431:
1.62 djm 432: static int
433: write_host_entry(FILE *f, const char *host,
434: const struct sshkey *key, int store_hash)
435: {
436: int r, success = 0;
437: char *hashed_host = NULL;
438:
439: if (store_hash) {
440: if ((hashed_host = host_hash(host, NULL, 0)) == NULL) {
441: error("%s: host_hash failed", __func__);
442: return 0;
443: }
444: }
445: fprintf(f, "%s ", store_hash ? hashed_host : host);
446:
447: if ((r = sshkey_write(key, f)) == 0)
448: success = 1;
449: else
450: error("%s: sshkey_write failed: %s", __func__, ssh_err(r));
451: fputc('\n', f);
452: return success;
453: }
454:
1.9 markus 455: /*
456: * Appends an entry to the host file. Returns false if the entry could not
457: * be appended.
458: */
1.2 provos 459: int
1.59 djm 460: add_host_to_hostfile(const char *filename, const char *host,
461: const struct sshkey *key, int store_hash)
1.1 deraadt 462: {
1.7 markus 463: FILE *f;
1.62 djm 464: int success;
1.33 djm 465:
1.14 markus 466: if (key == NULL)
1.17 markus 467: return 1; /* XXX ? */
1.7 markus 468: f = fopen(filename, "a");
469: if (!f)
470: return 0;
1.62 djm 471: success = write_host_entry(f, host, key, store_hash);
472: fclose(f);
473: return success;
474: }
475:
476: struct host_delete_ctx {
477: FILE *out;
478: int quiet;
479: const char *host;
480: int *skip_keys;
481: struct sshkey * const *keys;
482: size_t nkeys;
483: };
484:
485: static int
486: host_delete(struct hostkey_foreach_line *l, void *_ctx)
487: {
488: struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
489: int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO;
490: size_t i;
491:
492: if (l->status == HKF_STATUS_HOST_MATCHED) {
493: if (l->marker != MRK_NONE) {
494: /* Don't remove CA and revocation lines */
495: fprintf(ctx->out, "%s\n", l->line);
496: return 0;
497: }
1.33 djm 498:
1.62 djm 499: /* XXX might need a knob for this later */
500: /* Don't remove RSA1 keys */
501: if (l->key->type == KEY_RSA1) {
502: fprintf(ctx->out, "%s\n", l->line);
1.33 djm 503: return 0;
504: }
1.62 djm 505:
506: /*
507: * If this line contains one of the keys that we will be
508: * adding later, then don't change it and mark the key for
509: * skipping.
510: */
511: for (i = 0; i < ctx->nkeys; i++) {
512: if (sshkey_equal(ctx->keys[i], l->key)) {
513: ctx->skip_keys[i] = 1;
514: fprintf(ctx->out, "%s\n", l->line);
515: debug3("%s: %s key already at %s:%ld", __func__,
516: sshkey_type(l->key), l->path, l->linenum);
517: return 0;
518: }
519: }
520:
521: /*
522: * Hostname matches and has no CA/revoke marker, delete it
523: * by *not* writing the line to ctx->out.
524: */
525: do_log2(loglevel, "%s%s%s:%ld: Host %s removed",
526: ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
527: l->path, l->linenum, ctx->host);
528: return 0;
529: }
530: /* Retain non-matching hosts and invalid lines when deleting */
531: if (l->status == HKF_STATUS_INVALID) {
532: do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
533: ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
534: l->path, l->linenum);
535: }
536: fprintf(ctx->out, "%s\n", l->line);
537: return 0;
538: }
539:
540: int
541: hostfile_replace_entries(const char *filename, const char *host,
542: struct sshkey **keys, size_t nkeys, int store_hash, int quiet)
543: {
544: int r, fd, oerrno = 0;
545: int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO;
546: struct host_delete_ctx ctx;
547: char *temp = NULL, *back = NULL;
548: mode_t omask;
549: size_t i;
550:
1.63 ! djm 551: omask = umask(077);
! 552:
1.62 djm 553: memset(&ctx, 0, sizeof(ctx));
554: ctx.host = host;
555: ctx.quiet = quiet;
556: if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
557: return SSH_ERR_ALLOC_FAIL;
558: ctx.keys = keys;
559: ctx.nkeys = nkeys;
560:
561: /*
562: * Prepare temporary file for in-place deletion.
563: */
564: if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) < 0 ||
565: (r = asprintf(&back, "%s.old", filename)) < 0) {
566: r = SSH_ERR_ALLOC_FAIL;
567: goto fail;
568: }
569:
570: if ((fd = mkstemp(temp)) == -1) {
571: oerrno = errno;
572: error("%s: mkstemp: %s", __func__, strerror(oerrno));
573: r = SSH_ERR_SYSTEM_ERROR;
574: goto fail;
575: }
576: if ((ctx.out = fdopen(fd, "w")) == NULL) {
577: oerrno = errno;
578: close(fd);
579: error("%s: fdopen: %s", __func__, strerror(oerrno));
580: r = SSH_ERR_SYSTEM_ERROR;
581: goto fail;
582: }
583:
584: /* Remove all entries for the specified host from the file */
585: if ((r = hostkeys_foreach(filename, host_delete, &ctx, host,
586: HKF_WANT_PARSE_KEY)) != 0) {
587: error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
588: goto fail;
589: }
590:
591: /* Add the requested keys */
592: for (i = 0; i < nkeys; i++) {
593: if (ctx.skip_keys[i])
594: continue;
595: do_log2(loglevel, "%s%sadd %s key to %s",
596: quiet ? __func__ : "", quiet ? ": " : NULL,
597: sshkey_type(keys[i]), filename);
598: if (!write_host_entry(ctx.out, host, keys[i], store_hash)) {
599: r = SSH_ERR_INTERNAL_ERROR;
600: goto fail;
601: }
1.33 djm 602: }
1.62 djm 603: fclose(ctx.out);
604: ctx.out = NULL;
1.33 djm 605:
1.62 djm 606: /* Backup the original file and replace it with the temporary */
607: if (unlink(back) == -1 && errno != ENOENT) {
608: oerrno = errno;
609: error("%s: unlink %.100s: %s", __func__, back, strerror(errno));
610: r = SSH_ERR_SYSTEM_ERROR;
611: goto fail;
612: }
613: if (link(filename, back) == -1) {
614: oerrno = errno;
615: error("%s: link %.100s to %.100s: %s", __func__, filename, back,
616: strerror(errno));
617: r = SSH_ERR_SYSTEM_ERROR;
618: goto fail;
619: }
620: if (rename(temp, filename) == -1) {
621: oerrno = errno;
622: error("%s: rename \"%s\" to \"%s\": %s", __func__,
623: temp, filename, strerror(errno));
624: r = SSH_ERR_SYSTEM_ERROR;
625: goto fail;
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);
1.63 ! djm 637: umask(omask);
1.62 djm 638: if (r == SSH_ERR_SYSTEM_ERROR)
639: errno = oerrno;
640: return r;
1.60 djm 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, nlen) == 1;
659: }
660:
661: int
662: hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
663: const char *host, u_int options)
664: {
665: FILE *f;
666: char line[8192], oline[8192];
667: u_long linenum = 0;
668: char *cp, *cp2;
669: u_int kbits;
670: int s, r = 0;
671: struct hostkey_foreach_line lineinfo;
672:
673: memset(&lineinfo, 0, sizeof(lineinfo));
674: if (host == NULL && (options & HKF_WANT_MATCH_HOST) != 0)
675: return SSH_ERR_INVALID_ARGUMENT;
676: if ((f = fopen(path, "r")) == NULL)
677: return SSH_ERR_SYSTEM_ERROR;
678:
679: debug3("%s: reading file \"%s\"", __func__, path);
680: while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) {
681: line[strcspn(line, "\n")] = '\0';
682: strlcpy(oline, line, sizeof(oline));
683:
684: sshkey_free(lineinfo.key);
685: memset(&lineinfo, 0, sizeof(lineinfo));
686: lineinfo.path = path;
687: lineinfo.linenum = linenum;
688: lineinfo.line = oline;
689: lineinfo.status = HKF_STATUS_OK;
690:
691: /* Skip any leading whitespace, comments and empty lines. */
692: for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
693: ;
694: if (!*cp || *cp == '#' || *cp == '\n') {
695: if ((options & HKF_WANT_MATCH_HOST) == 0) {
696: lineinfo.status = HKF_STATUS_COMMENT;
697: if ((r = callback(&lineinfo, ctx)) != 0)
698: break;
699: }
700: continue;
701: }
702:
703: if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
704: verbose("%s: invalid marker at %s:%lu",
705: __func__, path, linenum);
706: if ((options & HKF_WANT_MATCH_HOST) == 0)
707: goto bad;
708: continue;
709: }
710:
711: /* Find the end of the host name portion. */
712: for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
713: ;
714: lineinfo.hosts = cp;
715: *cp2++ = '\0';
716:
717: /* Check if the host name matches. */
718: if (host != NULL) {
719: s = match_maybe_hashed(host, lineinfo.hosts,
720: &lineinfo.was_hashed);
721: if (s == 1)
722: lineinfo.status = HKF_STATUS_HOST_MATCHED;
723: else if ((options & HKF_WANT_MATCH_HOST) != 0)
724: continue;
725: else if (s == -1) {
726: debug2("%s: %s:%ld: bad host hash \"%.32s\"",
727: __func__, path, linenum, lineinfo.hosts);
728: goto bad;
729: }
730: }
731:
732: /* Got a match. Skip host name and any following whitespace */
733: for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
734: ;
735: if (*cp2 == '\0' || *cp2 == '#') {
736: debug2("%s:%ld: truncated before key", path, linenum);
737: goto bad;
738: }
739: lineinfo.rawkey = cp = cp2;
740:
741: if ((options & HKF_WANT_PARSE_KEY) != 0) {
742: /*
743: * Extract the key from the line. This will skip
744: * any leading whitespace. Ignore badly formatted
745: * lines.
746: */
747: if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
748: error("%s: sshkey_new failed", __func__);
749: return SSH_ERR_ALLOC_FAIL;
750: }
751: if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
752: #ifdef WITH_SSH1
753: sshkey_free(lineinfo.key);
754: lineinfo.key = sshkey_new(KEY_RSA1);
755: if (lineinfo.key == NULL) {
756: error("%s: sshkey_new fail", __func__);
757: return SSH_ERR_ALLOC_FAIL;
758: }
759: if (!hostfile_read_key(&cp, &kbits,
760: lineinfo.key))
761: goto bad;
762: #else
763: goto bad;
764: #endif
765: }
766: if (!hostfile_check_key(kbits, lineinfo.key, host,
767: path, linenum)) {
768: bad:
769: lineinfo.status = HKF_STATUS_INVALID;
770: if ((r = callback(&lineinfo, ctx)) != 0)
771: break;
772: continue;
773: }
774: }
775: if ((r = callback(&lineinfo, ctx)) != 0)
776: break;
777: }
778: sshkey_free(lineinfo.key);
779: fclose(f);
780: return r;
1.1 deraadt 781: }