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