blob: 389aae1fcb45862e49d9281d8c9f6345987edb11 [file] [log] [blame]
dtucker@openbsd.org696fb422019-07-07 01:05:00 +00001/* $OpenBSD: hostfile.c,v 1.76 2019/07/07 01:05:00 dtucker Exp $ */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002/*
Damien Miller95def091999-11-25 00:26:21 +11003 * Author: Tatu Ylonen <ylo@cs.hut.fi>
Damien Miller95def091999-11-25 00:26:21 +11004 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
Damien Miller95def091999-11-25 00:26:21 +11006 * Functions for manipulating the known hosts files.
Damien Miller4af51302000-04-16 11:18:38 +10007 *
Damien Millere4340be2000-09-16 13:29:08 +11008 * 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 *
Ben Lindstrom44697232001-07-04 03:32:30 +000015 * Copyright (c) 1999, 2000 Markus Friedl. All rights reserved.
Damien Millere4340be2000-09-16 13:29:08 +110016 * 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.
Damien Miller95def091999-11-25 00:26:21 +110037 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100038
39#include "includes.h"
Damien Millere1776152005-03-01 21:47:37 +110040
Damien Miller8ec8c3e2006-07-10 20:35:38 +100041#include <sys/types.h>
djm@openbsd.org8d4f8722015-01-26 03:04:45 +000042#include <sys/stat.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100043
44#include <netinet/in.h>
45
djm@openbsd.orgc29811c2015-01-18 21:40:23 +000046#include <errno.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100047#include <resolv.h>
Damien Millerded319c2006-09-01 15:38:36 +100048#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100049#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100050#include <stdlib.h>
51#include <string.h>
Damien Miller86687062014-07-02 15:28:02 +100052#include <stdarg.h>
djm@openbsd.org8d4f8722015-01-26 03:04:45 +000053#include <unistd.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100054
Damien Millerd7834352006-08-05 12:39:39 +100055#include "xmalloc.h"
Damien Miller450a7a12000-03-26 13:04:51 +100056#include "match.h"
djm@openbsd.org1129dcf2015-01-15 09:40:00 +000057#include "sshkey.h"
Damien Miller450a7a12000-03-26 13:04:51 +100058#include "hostfile.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000059#include "log.h"
Damien Millerd925dcd2010-12-01 12:21:51 +110060#include "misc.h"
djm@openbsd.org1129dcf2015-01-15 09:40:00 +000061#include "ssherr.h"
Damien Millerb3051d02014-01-10 10:58:53 +110062#include "digest.h"
Damien Miller4e8d9372014-02-04 11:02:42 +110063#include "hmac.h"
Damien Millerd925dcd2010-12-01 12:21:51 +110064
65struct hostkeys {
66 struct hostkey_entry *entries;
67 u_int num_entries;
68};
Damien Millere1776152005-03-01 21:47:37 +110069
djm@openbsd.orgc29811c2015-01-18 21:40:23 +000070/* XXX hmac is too easy to dictionary attack; use bcrypt? */
71
Damien Millere1776152005-03-01 21:47:37 +110072static int
Damien Millerce986542013-07-18 16:12:44 +100073extract_salt(const char *s, u_int l, u_char *salt, size_t salt_len)
Damien Millere1776152005-03-01 21:47:37 +110074{
75 char *p, *b64salt;
76 u_int b64len;
77 int ret;
78
79 if (l < sizeof(HASH_MAGIC) - 1) {
80 debug2("extract_salt: string too short");
81 return (-1);
82 }
83 if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) {
84 debug2("extract_salt: invalid magic identifier");
85 return (-1);
86 }
87 s += sizeof(HASH_MAGIC) - 1;
88 l -= sizeof(HASH_MAGIC) - 1;
89 if ((p = memchr(s, HASH_DELIM, l)) == NULL) {
90 debug2("extract_salt: missing salt termination character");
91 return (-1);
92 }
93
94 b64len = p - s;
95 /* Sanity check */
96 if (b64len == 0 || b64len > 1024) {
97 debug2("extract_salt: bad encoded salt length %u", b64len);
98 return (-1);
99 }
100 b64salt = xmalloc(1 + b64len);
101 memcpy(b64salt, s, b64len);
102 b64salt[b64len] = '\0';
103
104 ret = __b64_pton(b64salt, salt, salt_len);
Darren Tuckera627d422013-06-02 07:31:17 +1000105 free(b64salt);
Damien Millere1776152005-03-01 21:47:37 +1100106 if (ret == -1) {
107 debug2("extract_salt: salt decode error");
108 return (-1);
109 }
Damien Miller4e8d9372014-02-04 11:02:42 +1100110 if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) {
111 debug2("extract_salt: expected salt len %zd, got %d",
112 ssh_hmac_bytes(SSH_DIGEST_SHA1), ret);
Damien Millere1776152005-03-01 21:47:37 +1100113 return (-1);
114 }
Darren Tucker47eede72005-03-14 23:08:12 +1100115
Damien Millere1776152005-03-01 21:47:37 +1100116 return (0);
117}
118
119char *
120host_hash(const char *host, const char *name_from_hostfile, u_int src_len)
121{
Damien Miller4e8d9372014-02-04 11:02:42 +1100122 struct ssh_hmac_ctx *ctx;
Damien Millerce986542013-07-18 16:12:44 +1000123 u_char salt[256], result[256];
124 char uu_salt[512], uu_result[512];
Damien Millere1776152005-03-01 21:47:37 +1100125 static char encoded[1024];
tedu@openbsd.org10363562016-09-17 18:00:27 +0000126 u_int len;
Damien Millere1776152005-03-01 21:47:37 +1100127
Damien Miller4e8d9372014-02-04 11:02:42 +1100128 len = ssh_digest_bytes(SSH_DIGEST_SHA1);
Damien Millere1776152005-03-01 21:47:37 +1100129
130 if (name_from_hostfile == NULL) {
131 /* Create new salt */
tedu@openbsd.org10363562016-09-17 18:00:27 +0000132 arc4random_buf(salt, len);
Damien Millere1776152005-03-01 21:47:37 +1100133 } else {
134 /* Extract salt from known host entry */
135 if (extract_salt(name_from_hostfile, src_len, salt,
136 sizeof(salt)) == -1)
137 return (NULL);
138 }
139
Damien Miller4e8d9372014-02-04 11:02:42 +1100140 if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL ||
141 ssh_hmac_init(ctx, salt, len) < 0 ||
142 ssh_hmac_update(ctx, host, strlen(host)) < 0 ||
143 ssh_hmac_final(ctx, result, sizeof(result)))
144 fatal("%s: ssh_hmac failed", __func__);
145 ssh_hmac_free(ctx);
Damien Millere1776152005-03-01 21:47:37 +1100146
Darren Tucker47eede72005-03-14 23:08:12 +1100147 if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
Damien Millere1776152005-03-01 21:47:37 +1100148 __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
Damien Miller4e8d9372014-02-04 11:02:42 +1100149 fatal("%s: __b64_ntop failed", __func__);
Damien Millere1776152005-03-01 21:47:37 +1100150
151 snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt,
152 HASH_DELIM, uu_result);
153
154 return (encoded);
155}
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000156
Damien Miller5428f641999-11-25 11:54:57 +1100157/*
Damien Miller450a7a12000-03-26 13:04:51 +1000158 * Parses an RSA (number of bits, e, n) or DSA key from a string. Moves the
159 * pointer over the key. Skips any whitespace at the beginning and at end.
Damien Miller5428f641999-11-25 11:54:57 +1100160 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000161
Damien Miller5b2aea92001-12-21 12:47:09 +1100162int
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000163hostfile_read_key(char **cpp, u_int *bitsp, struct sshkey *ret)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000164{
Damien Miller95def091999-11-25 00:26:21 +1100165 char *cp;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000166
Damien Miller95def091999-11-25 00:26:21 +1100167 /* Skip leading whitespace. */
Damien Miller5428f641999-11-25 11:54:57 +1100168 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
169 ;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000170
dtucker@openbsd.org696fb422019-07-07 01:05:00 +0000171 if (sshkey_read(ret, &cp) != 0)
Damien Miller95def091999-11-25 00:26:21 +1100172 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000173
Damien Miller95def091999-11-25 00:26:21 +1100174 /* Skip trailing whitespace. */
Damien Miller5428f641999-11-25 11:54:57 +1100175 for (; *cp == ' ' || *cp == '\t'; cp++)
176 ;
Damien Miller95def091999-11-25 00:26:21 +1100177
178 /* Return results. */
179 *cpp = cp;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000180 if (bitsp != NULL)
181 *bitsp = sshkey_size(ret);
Damien Miller95def091999-11-25 00:26:21 +1100182 return 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000183}
184
Damien Millerd925dcd2010-12-01 12:21:51 +1100185static HostkeyMarker
Damien Miller1aed65e2010-03-04 21:53:35 +1100186check_markers(char **cpp)
187{
188 char marker[32], *sp, *cp = *cpp;
189 int ret = MRK_NONE;
190
191 while (*cp == '@') {
192 /* Only one marker is allowed */
193 if (ret != MRK_NONE)
194 return MRK_ERROR;
195 /* Markers are terminated by whitespace */
196 if ((sp = strchr(cp, ' ')) == NULL &&
197 (sp = strchr(cp, '\t')) == NULL)
198 return MRK_ERROR;
199 /* Extract marker for comparison */
200 if (sp <= cp + 1 || sp >= cp + sizeof(marker))
201 return MRK_ERROR;
202 memcpy(marker, cp, sp - cp);
203 marker[sp - cp] = '\0';
204 if (strcmp(marker, CA_MARKER) == 0)
205 ret = MRK_CA;
206 else if (strcmp(marker, REVOKE_MARKER) == 0)
207 ret = MRK_REVOKE;
208 else
209 return MRK_ERROR;
210
211 /* Skip past marker and any whitespace that follows it */
212 cp = sp;
213 for (; *cp == ' ' || *cp == '\t'; cp++)
214 ;
215 }
216 *cpp = cp;
217 return ret;
218}
219
Damien Millerd925dcd2010-12-01 12:21:51 +1100220struct hostkeys *
221init_hostkeys(void)
222{
223 struct hostkeys *ret = xcalloc(1, sizeof(*ret));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000224
Damien Millerd925dcd2010-12-01 12:21:51 +1100225 ret->entries = NULL;
226 return ret;
227}
228
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000229struct load_callback_ctx {
230 const char *host;
231 u_long num_loaded;
232 struct hostkeys *hostkeys;
233};
234
235static int
236record_hostkey(struct hostkey_foreach_line *l, void *_ctx)
237{
238 struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx;
239 struct hostkeys *hostkeys = ctx->hostkeys;
240 struct hostkey_entry *tmp;
241
242 if (l->status == HKF_STATUS_INVALID) {
djm@openbsd.org398f9ef2015-03-31 22:57:06 +0000243 /* XXX make this verbose() in the future */
244 debug("%s:%ld: parse error in hostkeys file",
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000245 l->path, l->linenum);
246 return 0;
247 }
248
249 debug3("%s: found %skey type %s in file %s:%lu", __func__,
250 l->marker == MRK_NONE ? "" :
251 (l->marker == MRK_CA ? "ca " : "revoked "),
252 sshkey_type(l->key), l->path, l->linenum);
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000253 if ((tmp = recallocarray(hostkeys->entries, hostkeys->num_entries,
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000254 hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL)
255 return SSH_ERR_ALLOC_FAIL;
256 hostkeys->entries = tmp;
257 hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host);
258 hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path);
259 hostkeys->entries[hostkeys->num_entries].line = l->linenum;
260 hostkeys->entries[hostkeys->num_entries].key = l->key;
261 l->key = NULL; /* steal it */
262 hostkeys->entries[hostkeys->num_entries].marker = l->marker;
263 hostkeys->num_entries++;
264 ctx->num_loaded++;
265
266 return 0;
267}
268
Damien Millerd925dcd2010-12-01 12:21:51 +1100269void
270load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000271{
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000272 int r;
273 struct load_callback_ctx ctx;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000274
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000275 ctx.host = host;
276 ctx.num_loaded = 0;
277 ctx.hostkeys = hostkeys;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000278
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000279 if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host, NULL,
280 HKF_WANT_MATCH|HKF_WANT_PARSE_KEY)) != 0) {
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000281 if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT)
282 debug("%s: hostkeys_foreach failed for %s: %s",
283 __func__, path, ssh_err(r));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000284 }
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000285 if (ctx.num_loaded != 0)
286 debug3("%s: loaded %lu keys from %s", __func__,
287 ctx.num_loaded, host);
djm@openbsd.org6fdcaeb2014-10-20 03:43:01 +0000288}
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000289
Damien Millerd925dcd2010-12-01 12:21:51 +1100290void
291free_hostkeys(struct hostkeys *hostkeys)
292{
293 u_int i;
294
295 for (i = 0; i < hostkeys->num_entries; i++) {
Darren Tuckera627d422013-06-02 07:31:17 +1000296 free(hostkeys->entries[i].host);
297 free(hostkeys->entries[i].file);
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000298 sshkey_free(hostkeys->entries[i].key);
Damien Miller1d2c4562014-02-04 11:18:20 +1100299 explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
Damien Millerd925dcd2010-12-01 12:21:51 +1100300 }
Darren Tuckera627d422013-06-02 07:31:17 +1000301 free(hostkeys->entries);
Damien Miller1d2c4562014-02-04 11:18:20 +1100302 explicit_bzero(hostkeys, sizeof(*hostkeys));
Darren Tuckera627d422013-06-02 07:31:17 +1000303 free(hostkeys);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000304}
305
Damien Millerd925dcd2010-12-01 12:21:51 +1100306static int
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000307check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
Damien Millerd925dcd2010-12-01 12:21:51 +1100308{
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000309 int is_cert = sshkey_is_cert(k);
Damien Millerd925dcd2010-12-01 12:21:51 +1100310 u_int i;
311
312 for (i = 0; i < hostkeys->num_entries; i++) {
313 if (hostkeys->entries[i].marker != MRK_REVOKE)
314 continue;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000315 if (sshkey_equal_public(k, hostkeys->entries[i].key))
Damien Millerd925dcd2010-12-01 12:21:51 +1100316 return -1;
317 if (is_cert &&
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000318 sshkey_equal_public(k->cert->signature_key,
Damien Millerd925dcd2010-12-01 12:21:51 +1100319 hostkeys->entries[i].key))
320 return -1;
321 }
322 return 0;
323}
324
325/*
326 * Match keys against a specified key, or look one up by key type.
327 *
328 * If looking for a keytype (key == NULL) and one is found then return
329 * HOST_FOUND, otherwise HOST_NEW.
330 *
331 * If looking for a key (key != NULL):
332 * 1. If the key is a cert and a matching CA is found, return HOST_OK
333 * 2. If the key is not a cert and a matching key is found, return HOST_OK
334 * 3. If no key matches but a key with a different type is found, then
335 * return HOST_CHANGED
336 * 4. If no matching keys are found, then return HOST_NEW.
337 *
338 * Finally, check any found key is not revoked.
339 */
340static HostStatus
341check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000342 struct sshkey *k, int keytype, const struct hostkey_entry **found)
Damien Millerd925dcd2010-12-01 12:21:51 +1100343{
344 u_int i;
345 HostStatus end_return = HOST_NEW;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000346 int want_cert = sshkey_is_cert(k);
Damien Millerd925dcd2010-12-01 12:21:51 +1100347 HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
Damien Millerd925dcd2010-12-01 12:21:51 +1100348
349 if (found != NULL)
350 *found = NULL;
351
352 for (i = 0; i < hostkeys->num_entries; i++) {
Damien Millerd925dcd2010-12-01 12:21:51 +1100353 if (hostkeys->entries[i].marker != want_marker)
354 continue;
355 if (k == NULL) {
356 if (hostkeys->entries[i].key->type != keytype)
357 continue;
358 end_return = HOST_FOUND;
359 if (found != NULL)
360 *found = hostkeys->entries + i;
361 k = hostkeys->entries[i].key;
362 break;
363 }
364 if (want_cert) {
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000365 if (sshkey_equal_public(k->cert->signature_key,
Damien Millerd925dcd2010-12-01 12:21:51 +1100366 hostkeys->entries[i].key)) {
367 /* A matching CA exists */
368 end_return = HOST_OK;
369 if (found != NULL)
370 *found = hostkeys->entries + i;
371 break;
372 }
373 } else {
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000374 if (sshkey_equal(k, hostkeys->entries[i].key)) {
Damien Millerd925dcd2010-12-01 12:21:51 +1100375 end_return = HOST_OK;
376 if (found != NULL)
377 *found = hostkeys->entries + i;
378 break;
379 }
380 /* A non-maching key exists */
381 end_return = HOST_CHANGED;
382 if (found != NULL)
383 *found = hostkeys->entries + i;
384 }
385 }
386 if (check_key_not_revoked(hostkeys, k) != 0) {
387 end_return = HOST_REVOKED;
388 if (found != NULL)
389 *found = NULL;
390 }
391 return end_return;
392}
djm@openbsd.org6fdcaeb2014-10-20 03:43:01 +0000393
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000394HostStatus
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000395check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
Damien Millerd925dcd2010-12-01 12:21:51 +1100396 const struct hostkey_entry **found)
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000397{
398 if (key == NULL)
399 fatal("no key to look up");
Damien Millerd925dcd2010-12-01 12:21:51 +1100400 return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000401}
402
403int
Damien Millerd925dcd2010-12-01 12:21:51 +1100404lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
405 const struct hostkey_entry **found)
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000406{
Damien Millerd925dcd2010-12-01 12:21:51 +1100407 return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
408 found) == HOST_FOUND);
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000409}
410
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000411static int
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000412write_host_entry(FILE *f, const char *host, const char *ip,
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000413 const struct sshkey *key, int store_hash)
414{
415 int r, success = 0;
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000416 char *hashed_host = NULL, *lhost;
417
418 lhost = xstrdup(host);
419 lowercase(lhost);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000420
421 if (store_hash) {
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000422 if ((hashed_host = host_hash(lhost, NULL, 0)) == NULL) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000423 error("%s: host_hash failed", __func__);
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000424 free(lhost);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000425 return 0;
426 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000427 fprintf(f, "%s ", hashed_host);
428 } else if (ip != NULL)
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000429 fprintf(f, "%s,%s ", lhost, ip);
430 else {
431 fprintf(f, "%s ", lhost);
432 }
433 free(lhost);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000434 if ((r = sshkey_write(key, f)) == 0)
435 success = 1;
436 else
437 error("%s: sshkey_write failed: %s", __func__, ssh_err(r));
438 fputc('\n', f);
439 return success;
440}
441
Damien Miller5428f641999-11-25 11:54:57 +1100442/*
443 * Appends an entry to the host file. Returns false if the entry could not
444 * be appended.
445 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000446int
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000447add_host_to_hostfile(const char *filename, const char *host,
448 const struct sshkey *key, int store_hash)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000449{
Damien Miller95def091999-11-25 00:26:21 +1100450 FILE *f;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000451 int success;
Damien Millere1776152005-03-01 21:47:37 +1100452
Damien Miller450a7a12000-03-26 13:04:51 +1000453 if (key == NULL)
Damien Millereba71ba2000-04-29 23:57:08 +1000454 return 1; /* XXX ? */
Damien Miller95def091999-11-25 00:26:21 +1100455 f = fopen(filename, "a");
456 if (!f)
457 return 0;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000458 success = write_host_entry(f, host, NULL, key, store_hash);
Damien Miller95def091999-11-25 00:26:21 +1100459 fclose(f);
Damien Miller450a7a12000-03-26 13:04:51 +1000460 return success;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000461}
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000462
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000463struct host_delete_ctx {
464 FILE *out;
465 int quiet;
466 const char *host;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000467 int *skip_keys; /* XXX split for host/ip? might want to ensure both */
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000468 struct sshkey * const *keys;
469 size_t nkeys;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000470 int modified;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000471};
472
473static int
474host_delete(struct hostkey_foreach_line *l, void *_ctx)
475{
476 struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000477 int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000478 size_t i;
479
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000480 if (l->status == HKF_STATUS_MATCHED) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000481 if (l->marker != MRK_NONE) {
482 /* Don't remove CA and revocation lines */
483 fprintf(ctx->out, "%s\n", l->line);
484 return 0;
485 }
486
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000487 /*
488 * If this line contains one of the keys that we will be
489 * adding later, then don't change it and mark the key for
490 * skipping.
491 */
492 for (i = 0; i < ctx->nkeys; i++) {
493 if (sshkey_equal(ctx->keys[i], l->key)) {
494 ctx->skip_keys[i] = 1;
495 fprintf(ctx->out, "%s\n", l->line);
496 debug3("%s: %s key already at %s:%ld", __func__,
497 sshkey_type(l->key), l->path, l->linenum);
498 return 0;
499 }
500 }
501
502 /*
503 * Hostname matches and has no CA/revoke marker, delete it
504 * by *not* writing the line to ctx->out.
505 */
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000506 do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000507 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000508 l->path, l->linenum, sshkey_type(l->key), ctx->host);
509 ctx->modified = 1;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000510 return 0;
511 }
512 /* Retain non-matching hosts and invalid lines when deleting */
513 if (l->status == HKF_STATUS_INVALID) {
514 do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
515 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
516 l->path, l->linenum);
517 }
518 fprintf(ctx->out, "%s\n", l->line);
519 return 0;
520}
521
522int
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000523hostfile_replace_entries(const char *filename, const char *host, const char *ip,
524 struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000525{
526 int r, fd, oerrno = 0;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000527 int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000528 struct host_delete_ctx ctx;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000529 char *fp, *temp = NULL, *back = NULL;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000530 mode_t omask;
531 size_t i;
532
djm@openbsd.org3076ee72015-01-26 13:36:53 +0000533 omask = umask(077);
534
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000535 memset(&ctx, 0, sizeof(ctx));
536 ctx.host = host;
537 ctx.quiet = quiet;
538 if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
539 return SSH_ERR_ALLOC_FAIL;
540 ctx.keys = keys;
541 ctx.nkeys = nkeys;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000542 ctx.modified = 0;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000543
544 /*
545 * Prepare temporary file for in-place deletion.
546 */
deraadt@openbsd.org1b2d55d2019-06-28 01:23:50 +0000547 if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) == -1 ||
deraadt@openbsd.org5cdbaa72019-06-27 18:03:37 +0000548 (r = asprintf(&back, "%s.old", filename)) == -1) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000549 r = SSH_ERR_ALLOC_FAIL;
550 goto fail;
551 }
552
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000553 if ((fd = mkstemp(temp)) == -1) {
554 oerrno = errno;
555 error("%s: mkstemp: %s", __func__, strerror(oerrno));
556 r = SSH_ERR_SYSTEM_ERROR;
557 goto fail;
558 }
559 if ((ctx.out = fdopen(fd, "w")) == NULL) {
560 oerrno = errno;
561 close(fd);
562 error("%s: fdopen: %s", __func__, strerror(oerrno));
563 r = SSH_ERR_SYSTEM_ERROR;
564 goto fail;
565 }
566
567 /* Remove all entries for the specified host from the file */
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000568 if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000569 HKF_WANT_PARSE_KEY)) != 0) {
570 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
571 goto fail;
572 }
573
574 /* Add the requested keys */
575 for (i = 0; i < nkeys; i++) {
576 if (ctx.skip_keys[i])
577 continue;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000578 if ((fp = sshkey_fingerprint(keys[i], hash_alg,
579 SSH_FP_DEFAULT)) == NULL) {
580 r = SSH_ERR_ALLOC_FAIL;
581 goto fail;
582 }
583 do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s",
584 quiet ? __func__ : "", quiet ? ": " : "", host, filename,
585 sshkey_ssh_name(keys[i]), fp);
586 free(fp);
587 if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000588 r = SSH_ERR_INTERNAL_ERROR;
589 goto fail;
590 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000591 ctx.modified = 1;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000592 }
593 fclose(ctx.out);
594 ctx.out = NULL;
595
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000596 if (ctx.modified) {
597 /* Backup the original file and replace it with the temporary */
598 if (unlink(back) == -1 && errno != ENOENT) {
599 oerrno = errno;
600 error("%s: unlink %.100s: %s", __func__,
601 back, strerror(errno));
602 r = SSH_ERR_SYSTEM_ERROR;
603 goto fail;
604 }
605 if (link(filename, back) == -1) {
606 oerrno = errno;
607 error("%s: link %.100s to %.100s: %s", __func__,
608 filename, back, strerror(errno));
609 r = SSH_ERR_SYSTEM_ERROR;
610 goto fail;
611 }
612 if (rename(temp, filename) == -1) {
613 oerrno = errno;
614 error("%s: rename \"%s\" to \"%s\": %s", __func__,
615 temp, filename, strerror(errno));
616 r = SSH_ERR_SYSTEM_ERROR;
617 goto fail;
618 }
619 } else {
620 /* No changes made; just delete the temporary file */
621 if (unlink(temp) != 0)
622 error("%s: unlink \"%s\": %s", __func__,
623 temp, strerror(errno));
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000624 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000625
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000626 /* success */
627 r = 0;
628 fail:
629 if (temp != NULL && r != 0)
630 unlink(temp);
631 free(temp);
632 free(back);
633 if (ctx.out != NULL)
634 fclose(ctx.out);
635 free(ctx.skip_keys);
djm@openbsd.org3076ee72015-01-26 13:36:53 +0000636 umask(omask);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000637 if (r == SSH_ERR_SYSTEM_ERROR)
638 errno = oerrno;
639 return r;
640}
641
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000642static int
643match_maybe_hashed(const char *host, const char *names, int *was_hashed)
644{
645 int hashed = *names == HASH_DELIM;
646 const char *hashed_host;
647 size_t nlen = strlen(names);
648
649 if (was_hashed != NULL)
650 *was_hashed = hashed;
651 if (hashed) {
652 if ((hashed_host = host_hash(host, names, nlen)) == NULL)
653 return -1;
654 return nlen == strlen(hashed_host) &&
655 strncmp(hashed_host, names, nlen) == 0;
656 }
djm@openbsd.orge661a862015-05-04 06:10:48 +0000657 return match_hostname(host, names) == 1;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000658}
659
660int
661hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000662 const char *host, const char *ip, u_int options)
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000663{
664 FILE *f;
markus@openbsd.org7f906352018-06-06 18:29:18 +0000665 char *line = NULL, ktype[128];
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000666 u_long linenum = 0;
667 char *cp, *cp2;
668 u_int kbits;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000669 int hashed;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000670 int s, r = 0;
671 struct hostkey_foreach_line lineinfo;
markus@openbsd.org7f906352018-06-06 18:29:18 +0000672 size_t linesize = 0, l;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000673
674 memset(&lineinfo, 0, sizeof(lineinfo));
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000675 if (host == NULL && (options & HKF_WANT_MATCH) != 0)
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000676 return SSH_ERR_INVALID_ARGUMENT;
677 if ((f = fopen(path, "r")) == NULL)
678 return SSH_ERR_SYSTEM_ERROR;
679
680 debug3("%s: reading file \"%s\"", __func__, path);
markus@openbsd.org7f906352018-06-06 18:29:18 +0000681 while (getline(&line, &linesize, f) != -1) {
682 linenum++;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000683 line[strcspn(line, "\n")] = '\0';
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000684
djm@openbsd.orgde2997a2018-07-16 03:09:13 +0000685 free(lineinfo.line);
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000686 sshkey_free(lineinfo.key);
687 memset(&lineinfo, 0, sizeof(lineinfo));
688 lineinfo.path = path;
689 lineinfo.linenum = linenum;
markus@openbsd.org7f906352018-06-06 18:29:18 +0000690 lineinfo.line = xstrdup(line);
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000691 lineinfo.marker = MRK_NONE;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000692 lineinfo.status = HKF_STATUS_OK;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000693 lineinfo.keytype = KEY_UNSPEC;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000694
695 /* Skip any leading whitespace, comments and empty lines. */
696 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
697 ;
698 if (!*cp || *cp == '#' || *cp == '\n') {
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000699 if ((options & HKF_WANT_MATCH) == 0) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000700 lineinfo.status = HKF_STATUS_COMMENT;
701 if ((r = callback(&lineinfo, ctx)) != 0)
702 break;
703 }
704 continue;
705 }
706
707 if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
708 verbose("%s: invalid marker at %s:%lu",
709 __func__, path, linenum);
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000710 if ((options & HKF_WANT_MATCH) == 0)
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000711 goto bad;
712 continue;
713 }
714
715 /* Find the end of the host name portion. */
716 for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
717 ;
718 lineinfo.hosts = cp;
719 *cp2++ = '\0';
720
721 /* Check if the host name matches. */
722 if (host != NULL) {
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000723 if ((s = match_maybe_hashed(host, lineinfo.hosts,
724 &hashed)) == -1) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000725 debug2("%s: %s:%ld: bad host hash \"%.32s\"",
726 __func__, path, linenum, lineinfo.hosts);
727 goto bad;
728 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000729 if (s == 1) {
730 lineinfo.status = HKF_STATUS_MATCHED;
731 lineinfo.match |= HKF_MATCH_HOST |
732 (hashed ? HKF_MATCH_HOST_HASHED : 0);
733 }
734 /* Try matching IP address if supplied */
735 if (ip != NULL) {
736 if ((s = match_maybe_hashed(ip, lineinfo.hosts,
737 &hashed)) == -1) {
738 debug2("%s: %s:%ld: bad ip hash "
739 "\"%.32s\"", __func__, path,
740 linenum, lineinfo.hosts);
741 goto bad;
742 }
743 if (s == 1) {
744 lineinfo.status = HKF_STATUS_MATCHED;
745 lineinfo.match |= HKF_MATCH_IP |
746 (hashed ? HKF_MATCH_IP_HASHED : 0);
747 }
748 }
749 /*
750 * Skip this line if host matching requested and
751 * neither host nor address matched.
752 */
753 if ((options & HKF_WANT_MATCH) != 0 &&
754 lineinfo.status != HKF_STATUS_MATCHED)
755 continue;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000756 }
757
758 /* Got a match. Skip host name and any following whitespace */
759 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
760 ;
761 if (*cp2 == '\0' || *cp2 == '#') {
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000762 debug2("%s:%ld: truncated before key type",
763 path, linenum);
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000764 goto bad;
765 }
766 lineinfo.rawkey = cp = cp2;
767
768 if ((options & HKF_WANT_PARSE_KEY) != 0) {
769 /*
770 * Extract the key from the line. This will skip
771 * any leading whitespace. Ignore badly formatted
772 * lines.
773 */
774 if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
775 error("%s: sshkey_new failed", __func__);
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000776 r = SSH_ERR_ALLOC_FAIL;
777 break;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000778 }
779 if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000780 goto bad;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000781 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000782 lineinfo.keytype = lineinfo.key->type;
783 lineinfo.comment = cp;
784 } else {
785 /* Extract and parse key type */
786 l = strcspn(lineinfo.rawkey, " \t");
787 if (l <= 1 || l >= sizeof(ktype) ||
788 lineinfo.rawkey[l] == '\0')
789 goto bad;
790 memcpy(ktype, lineinfo.rawkey, l);
791 ktype[l] = '\0';
792 lineinfo.keytype = sshkey_type_from_name(ktype);
djm@openbsd.org398f9ef2015-03-31 22:57:06 +0000793
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000794 /*
djm@openbsd.org873d3e72017-04-30 23:18:44 +0000795 * Assume legacy RSA1 if the first component is a short
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000796 * decimal number.
797 */
798 if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
799 strspn(ktype, "0123456789") == l)
djm@openbsd.org873d3e72017-04-30 23:18:44 +0000800 goto bad;
djm@openbsd.org398f9ef2015-03-31 22:57:06 +0000801
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000802 /*
803 * Check that something other than whitespace follows
804 * the key type. This won't catch all corruption, but
805 * it does catch trivial truncation.
806 */
807 cp2 += l; /* Skip past key type */
808 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
809 ;
810 if (*cp2 == '\0' || *cp2 == '#') {
811 debug2("%s:%ld: truncated after key type",
812 path, linenum);
813 lineinfo.keytype = KEY_UNSPEC;
814 }
815 if (lineinfo.keytype == KEY_UNSPEC) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000816 bad:
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000817 sshkey_free(lineinfo.key);
818 lineinfo.key = NULL;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000819 lineinfo.status = HKF_STATUS_INVALID;
820 if ((r = callback(&lineinfo, ctx)) != 0)
821 break;
822 continue;
823 }
824 }
825 if ((r = callback(&lineinfo, ctx)) != 0)
826 break;
827 }
828 sshkey_free(lineinfo.key);
markus@openbsd.org7f906352018-06-06 18:29:18 +0000829 free(lineinfo.line);
830 free(line);
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000831 fclose(f);
832 return r;
833}