blob: e23faa9696af1b1998147cd6792c03b43f849062 [file] [log] [blame]
djm@openbsd.orgdb259722017-03-10 04:26:06 +00001/* $OpenBSD: hostfile.c,v 1.68 2017/03/10 04:26:06 djm 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;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000166 int r;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000167
Damien Miller95def091999-11-25 00:26:21 +1100168 /* Skip leading whitespace. */
Damien Miller5428f641999-11-25 11:54:57 +1100169 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
170 ;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000171
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000172 if ((r = sshkey_read(ret, &cp)) != 0)
Damien Miller95def091999-11-25 00:26:21 +1100173 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000174
Damien Miller95def091999-11-25 00:26:21 +1100175 /* Skip trailing whitespace. */
Damien Miller5428f641999-11-25 11:54:57 +1100176 for (; *cp == ' ' || *cp == '\t'; cp++)
177 ;
Damien Miller95def091999-11-25 00:26:21 +1100178
179 /* Return results. */
180 *cpp = cp;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000181 if (bitsp != NULL)
182 *bitsp = sshkey_size(ret);
Damien Miller95def091999-11-25 00:26:21 +1100183 return 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000184}
185
Damien Millerd925dcd2010-12-01 12:21:51 +1100186static HostkeyMarker
Damien Miller1aed65e2010-03-04 21:53:35 +1100187check_markers(char **cpp)
188{
189 char marker[32], *sp, *cp = *cpp;
190 int ret = MRK_NONE;
191
192 while (*cp == '@') {
193 /* Only one marker is allowed */
194 if (ret != MRK_NONE)
195 return MRK_ERROR;
196 /* Markers are terminated by whitespace */
197 if ((sp = strchr(cp, ' ')) == NULL &&
198 (sp = strchr(cp, '\t')) == NULL)
199 return MRK_ERROR;
200 /* Extract marker for comparison */
201 if (sp <= cp + 1 || sp >= cp + sizeof(marker))
202 return MRK_ERROR;
203 memcpy(marker, cp, sp - cp);
204 marker[sp - cp] = '\0';
205 if (strcmp(marker, CA_MARKER) == 0)
206 ret = MRK_CA;
207 else if (strcmp(marker, REVOKE_MARKER) == 0)
208 ret = MRK_REVOKE;
209 else
210 return MRK_ERROR;
211
212 /* Skip past marker and any whitespace that follows it */
213 cp = sp;
214 for (; *cp == ' ' || *cp == '\t'; cp++)
215 ;
216 }
217 *cpp = cp;
218 return ret;
219}
220
Damien Millerd925dcd2010-12-01 12:21:51 +1100221struct hostkeys *
222init_hostkeys(void)
223{
224 struct hostkeys *ret = xcalloc(1, sizeof(*ret));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000225
Damien Millerd925dcd2010-12-01 12:21:51 +1100226 ret->entries = NULL;
227 return ret;
228}
229
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000230struct load_callback_ctx {
231 const char *host;
232 u_long num_loaded;
233 struct hostkeys *hostkeys;
234};
235
236static int
237record_hostkey(struct hostkey_foreach_line *l, void *_ctx)
238{
239 struct load_callback_ctx *ctx = (struct load_callback_ctx *)_ctx;
240 struct hostkeys *hostkeys = ctx->hostkeys;
241 struct hostkey_entry *tmp;
242
243 if (l->status == HKF_STATUS_INVALID) {
djm@openbsd.org398f9ef2015-03-31 22:57:06 +0000244 /* XXX make this verbose() in the future */
245 debug("%s:%ld: parse error in hostkeys file",
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000246 l->path, l->linenum);
247 return 0;
248 }
249
250 debug3("%s: found %skey type %s in file %s:%lu", __func__,
251 l->marker == MRK_NONE ? "" :
252 (l->marker == MRK_CA ? "ca " : "revoked "),
253 sshkey_type(l->key), l->path, l->linenum);
254 if ((tmp = reallocarray(hostkeys->entries,
255 hostkeys->num_entries + 1, sizeof(*hostkeys->entries))) == NULL)
256 return SSH_ERR_ALLOC_FAIL;
257 hostkeys->entries = tmp;
258 hostkeys->entries[hostkeys->num_entries].host = xstrdup(ctx->host);
259 hostkeys->entries[hostkeys->num_entries].file = xstrdup(l->path);
260 hostkeys->entries[hostkeys->num_entries].line = l->linenum;
261 hostkeys->entries[hostkeys->num_entries].key = l->key;
262 l->key = NULL; /* steal it */
263 hostkeys->entries[hostkeys->num_entries].marker = l->marker;
264 hostkeys->num_entries++;
265 ctx->num_loaded++;
266
267 return 0;
268}
269
Damien Millerd925dcd2010-12-01 12:21:51 +1100270void
271load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000272{
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000273 int r;
274 struct load_callback_ctx ctx;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000275
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000276 ctx.host = host;
277 ctx.num_loaded = 0;
278 ctx.hostkeys = hostkeys;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000279
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000280 if ((r = hostkeys_foreach(path, record_hostkey, &ctx, host, NULL,
281 HKF_WANT_MATCH|HKF_WANT_PARSE_KEY)) != 0) {
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000282 if (r != SSH_ERR_SYSTEM_ERROR && errno != ENOENT)
283 debug("%s: hostkeys_foreach failed for %s: %s",
284 __func__, path, ssh_err(r));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000285 }
djm@openbsd.orgec3d0652015-01-18 21:48:09 +0000286 if (ctx.num_loaded != 0)
287 debug3("%s: loaded %lu keys from %s", __func__,
288 ctx.num_loaded, host);
djm@openbsd.org6fdcaeb2014-10-20 03:43:01 +0000289}
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000290
Damien Millerd925dcd2010-12-01 12:21:51 +1100291void
292free_hostkeys(struct hostkeys *hostkeys)
293{
294 u_int i;
295
296 for (i = 0; i < hostkeys->num_entries; i++) {
Darren Tuckera627d422013-06-02 07:31:17 +1000297 free(hostkeys->entries[i].host);
298 free(hostkeys->entries[i].file);
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000299 sshkey_free(hostkeys->entries[i].key);
Damien Miller1d2c4562014-02-04 11:18:20 +1100300 explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
Damien Millerd925dcd2010-12-01 12:21:51 +1100301 }
Darren Tuckera627d422013-06-02 07:31:17 +1000302 free(hostkeys->entries);
Damien Miller1d2c4562014-02-04 11:18:20 +1100303 explicit_bzero(hostkeys, sizeof(*hostkeys));
Darren Tuckera627d422013-06-02 07:31:17 +1000304 free(hostkeys);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000305}
306
Damien Millerd925dcd2010-12-01 12:21:51 +1100307static int
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000308check_key_not_revoked(struct hostkeys *hostkeys, struct sshkey *k)
Damien Millerd925dcd2010-12-01 12:21:51 +1100309{
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000310 int is_cert = sshkey_is_cert(k);
Damien Millerd925dcd2010-12-01 12:21:51 +1100311 u_int i;
312
313 for (i = 0; i < hostkeys->num_entries; i++) {
314 if (hostkeys->entries[i].marker != MRK_REVOKE)
315 continue;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000316 if (sshkey_equal_public(k, hostkeys->entries[i].key))
Damien Millerd925dcd2010-12-01 12:21:51 +1100317 return -1;
318 if (is_cert &&
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000319 sshkey_equal_public(k->cert->signature_key,
Damien Millerd925dcd2010-12-01 12:21:51 +1100320 hostkeys->entries[i].key))
321 return -1;
322 }
323 return 0;
324}
325
326/*
327 * Match keys against a specified key, or look one up by key type.
328 *
329 * If looking for a keytype (key == NULL) and one is found then return
330 * HOST_FOUND, otherwise HOST_NEW.
331 *
332 * If looking for a key (key != NULL):
333 * 1. If the key is a cert and a matching CA is found, return HOST_OK
334 * 2. If the key is not a cert and a matching key is found, return HOST_OK
335 * 3. If no key matches but a key with a different type is found, then
336 * return HOST_CHANGED
337 * 4. If no matching keys are found, then return HOST_NEW.
338 *
339 * Finally, check any found key is not revoked.
340 */
341static HostStatus
342check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000343 struct sshkey *k, int keytype, const struct hostkey_entry **found)
Damien Millerd925dcd2010-12-01 12:21:51 +1100344{
345 u_int i;
346 HostStatus end_return = HOST_NEW;
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000347 int want_cert = sshkey_is_cert(k);
Damien Millerd925dcd2010-12-01 12:21:51 +1100348 HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
349 int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2;
350
351 if (found != NULL)
352 *found = NULL;
353
354 for (i = 0; i < hostkeys->num_entries; i++) {
355 if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1)
356 continue;
357 if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1)
358 continue;
359 if (hostkeys->entries[i].marker != want_marker)
360 continue;
361 if (k == NULL) {
362 if (hostkeys->entries[i].key->type != keytype)
363 continue;
364 end_return = HOST_FOUND;
365 if (found != NULL)
366 *found = hostkeys->entries + i;
367 k = hostkeys->entries[i].key;
368 break;
369 }
370 if (want_cert) {
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000371 if (sshkey_equal_public(k->cert->signature_key,
Damien Millerd925dcd2010-12-01 12:21:51 +1100372 hostkeys->entries[i].key)) {
373 /* A matching CA exists */
374 end_return = HOST_OK;
375 if (found != NULL)
376 *found = hostkeys->entries + i;
377 break;
378 }
379 } else {
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000380 if (sshkey_equal(k, hostkeys->entries[i].key)) {
Damien Millerd925dcd2010-12-01 12:21:51 +1100381 end_return = HOST_OK;
382 if (found != NULL)
383 *found = hostkeys->entries + i;
384 break;
385 }
386 /* A non-maching key exists */
387 end_return = HOST_CHANGED;
388 if (found != NULL)
389 *found = hostkeys->entries + i;
390 }
391 }
392 if (check_key_not_revoked(hostkeys, k) != 0) {
393 end_return = HOST_REVOKED;
394 if (found != NULL)
395 *found = NULL;
396 }
397 return end_return;
398}
djm@openbsd.org6fdcaeb2014-10-20 03:43:01 +0000399
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000400HostStatus
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000401check_key_in_hostkeys(struct hostkeys *hostkeys, struct sshkey *key,
Damien Millerd925dcd2010-12-01 12:21:51 +1100402 const struct hostkey_entry **found)
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000403{
404 if (key == NULL)
405 fatal("no key to look up");
Damien Millerd925dcd2010-12-01 12:21:51 +1100406 return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000407}
408
409int
Damien Millerd925dcd2010-12-01 12:21:51 +1100410lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
411 const struct hostkey_entry **found)
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000412{
Damien Millerd925dcd2010-12-01 12:21:51 +1100413 return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
414 found) == HOST_FOUND);
Ben Lindstrom3ed66402002-08-01 01:21:56 +0000415}
416
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000417static int
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000418write_host_entry(FILE *f, const char *host, const char *ip,
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000419 const struct sshkey *key, int store_hash)
420{
421 int r, success = 0;
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000422 char *hashed_host = NULL, *lhost;
423
424 lhost = xstrdup(host);
425 lowercase(lhost);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000426
427 if (store_hash) {
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000428 if ((hashed_host = host_hash(lhost, NULL, 0)) == NULL) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000429 error("%s: host_hash failed", __func__);
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000430 free(lhost);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000431 return 0;
432 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000433 fprintf(f, "%s ", hashed_host);
434 } else if (ip != NULL)
djm@openbsd.orgdb259722017-03-10 04:26:06 +0000435 fprintf(f, "%s,%s ", lhost, ip);
436 else {
437 fprintf(f, "%s ", lhost);
438 }
439 free(lhost);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000440 if ((r = sshkey_write(key, f)) == 0)
441 success = 1;
442 else
443 error("%s: sshkey_write failed: %s", __func__, ssh_err(r));
444 fputc('\n', f);
445 return success;
446}
447
Damien Miller5428f641999-11-25 11:54:57 +1100448/*
449 * Appends an entry to the host file. Returns false if the entry could not
450 * be appended.
451 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000452int
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000453add_host_to_hostfile(const char *filename, const char *host,
454 const struct sshkey *key, int store_hash)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000455{
Damien Miller95def091999-11-25 00:26:21 +1100456 FILE *f;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000457 int success;
Damien Millere1776152005-03-01 21:47:37 +1100458
Damien Miller450a7a12000-03-26 13:04:51 +1000459 if (key == NULL)
Damien Millereba71ba2000-04-29 23:57:08 +1000460 return 1; /* XXX ? */
Damien Miller95def091999-11-25 00:26:21 +1100461 f = fopen(filename, "a");
462 if (!f)
463 return 0;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000464 success = write_host_entry(f, host, NULL, key, store_hash);
Damien Miller95def091999-11-25 00:26:21 +1100465 fclose(f);
Damien Miller450a7a12000-03-26 13:04:51 +1000466 return success;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000467}
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000468
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000469struct host_delete_ctx {
470 FILE *out;
471 int quiet;
472 const char *host;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000473 int *skip_keys; /* XXX split for host/ip? might want to ensure both */
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000474 struct sshkey * const *keys;
475 size_t nkeys;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000476 int modified;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000477};
478
479static int
480host_delete(struct hostkey_foreach_line *l, void *_ctx)
481{
482 struct host_delete_ctx *ctx = (struct host_delete_ctx *)_ctx;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000483 int loglevel = ctx->quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000484 size_t i;
485
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000486 if (l->status == HKF_STATUS_MATCHED) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000487 if (l->marker != MRK_NONE) {
488 /* Don't remove CA and revocation lines */
489 fprintf(ctx->out, "%s\n", l->line);
490 return 0;
491 }
492
493 /* XXX might need a knob for this later */
494 /* Don't remove RSA1 keys */
495 if (l->key->type == KEY_RSA1) {
496 fprintf(ctx->out, "%s\n", l->line);
497 return 0;
498 }
499
500 /*
501 * If this line contains one of the keys that we will be
502 * adding later, then don't change it and mark the key for
503 * skipping.
504 */
505 for (i = 0; i < ctx->nkeys; i++) {
506 if (sshkey_equal(ctx->keys[i], l->key)) {
507 ctx->skip_keys[i] = 1;
508 fprintf(ctx->out, "%s\n", l->line);
509 debug3("%s: %s key already at %s:%ld", __func__,
510 sshkey_type(l->key), l->path, l->linenum);
511 return 0;
512 }
513 }
514
515 /*
516 * Hostname matches and has no CA/revoke marker, delete it
517 * by *not* writing the line to ctx->out.
518 */
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000519 do_log2(loglevel, "%s%s%s:%ld: Removed %s key for host %s",
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000520 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000521 l->path, l->linenum, sshkey_type(l->key), ctx->host);
522 ctx->modified = 1;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000523 return 0;
524 }
525 /* Retain non-matching hosts and invalid lines when deleting */
526 if (l->status == HKF_STATUS_INVALID) {
527 do_log2(loglevel, "%s%s%s:%ld: invalid known_hosts entry",
528 ctx->quiet ? __func__ : "", ctx->quiet ? ": " : "",
529 l->path, l->linenum);
530 }
531 fprintf(ctx->out, "%s\n", l->line);
532 return 0;
533}
534
535int
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000536hostfile_replace_entries(const char *filename, const char *host, const char *ip,
537 struct sshkey **keys, size_t nkeys, int store_hash, int quiet, int hash_alg)
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000538{
539 int r, fd, oerrno = 0;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000540 int loglevel = quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_VERBOSE;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000541 struct host_delete_ctx ctx;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000542 char *fp, *temp = NULL, *back = NULL;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000543 mode_t omask;
544 size_t i;
545
djm@openbsd.org3076ee72015-01-26 13:36:53 +0000546 omask = umask(077);
547
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000548 memset(&ctx, 0, sizeof(ctx));
549 ctx.host = host;
550 ctx.quiet = quiet;
551 if ((ctx.skip_keys = calloc(nkeys, sizeof(*ctx.skip_keys))) == NULL)
552 return SSH_ERR_ALLOC_FAIL;
553 ctx.keys = keys;
554 ctx.nkeys = nkeys;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000555 ctx.modified = 0;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000556
557 /*
558 * Prepare temporary file for in-place deletion.
559 */
560 if ((r = asprintf(&temp, "%s.XXXXXXXXXXX", filename)) < 0 ||
561 (r = asprintf(&back, "%s.old", filename)) < 0) {
562 r = SSH_ERR_ALLOC_FAIL;
563 goto fail;
564 }
565
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000566 if ((fd = mkstemp(temp)) == -1) {
567 oerrno = errno;
568 error("%s: mkstemp: %s", __func__, strerror(oerrno));
569 r = SSH_ERR_SYSTEM_ERROR;
570 goto fail;
571 }
572 if ((ctx.out = fdopen(fd, "w")) == NULL) {
573 oerrno = errno;
574 close(fd);
575 error("%s: fdopen: %s", __func__, strerror(oerrno));
576 r = SSH_ERR_SYSTEM_ERROR;
577 goto fail;
578 }
579
580 /* Remove all entries for the specified host from the file */
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000581 if ((r = hostkeys_foreach(filename, host_delete, &ctx, host, ip,
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000582 HKF_WANT_PARSE_KEY)) != 0) {
583 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
584 goto fail;
585 }
586
587 /* Add the requested keys */
588 for (i = 0; i < nkeys; i++) {
589 if (ctx.skip_keys[i])
590 continue;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000591 if ((fp = sshkey_fingerprint(keys[i], hash_alg,
592 SSH_FP_DEFAULT)) == NULL) {
593 r = SSH_ERR_ALLOC_FAIL;
594 goto fail;
595 }
596 do_log2(loglevel, "%s%sAdding new key for %s to %s: %s %s",
597 quiet ? __func__ : "", quiet ? ": " : "", host, filename,
598 sshkey_ssh_name(keys[i]), fp);
599 free(fp);
600 if (!write_host_entry(ctx.out, host, ip, keys[i], store_hash)) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000601 r = SSH_ERR_INTERNAL_ERROR;
602 goto fail;
603 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000604 ctx.modified = 1;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000605 }
606 fclose(ctx.out);
607 ctx.out = NULL;
608
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000609 if (ctx.modified) {
610 /* Backup the original file and replace it with the temporary */
611 if (unlink(back) == -1 && errno != ENOENT) {
612 oerrno = errno;
613 error("%s: unlink %.100s: %s", __func__,
614 back, strerror(errno));
615 r = SSH_ERR_SYSTEM_ERROR;
616 goto fail;
617 }
618 if (link(filename, back) == -1) {
619 oerrno = errno;
620 error("%s: link %.100s to %.100s: %s", __func__,
621 filename, back, strerror(errno));
622 r = SSH_ERR_SYSTEM_ERROR;
623 goto fail;
624 }
625 if (rename(temp, filename) == -1) {
626 oerrno = errno;
627 error("%s: rename \"%s\" to \"%s\": %s", __func__,
628 temp, filename, strerror(errno));
629 r = SSH_ERR_SYSTEM_ERROR;
630 goto fail;
631 }
632 } else {
633 /* No changes made; just delete the temporary file */
634 if (unlink(temp) != 0)
635 error("%s: unlink \"%s\": %s", __func__,
636 temp, strerror(errno));
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000637 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000638
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000639 /* success */
640 r = 0;
641 fail:
642 if (temp != NULL && r != 0)
643 unlink(temp);
644 free(temp);
645 free(back);
646 if (ctx.out != NULL)
647 fclose(ctx.out);
648 free(ctx.skip_keys);
djm@openbsd.org3076ee72015-01-26 13:36:53 +0000649 umask(omask);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000650 if (r == SSH_ERR_SYSTEM_ERROR)
651 errno = oerrno;
652 return r;
653}
654
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000655static int
656match_maybe_hashed(const char *host, const char *names, int *was_hashed)
657{
658 int hashed = *names == HASH_DELIM;
659 const char *hashed_host;
660 size_t nlen = strlen(names);
661
662 if (was_hashed != NULL)
663 *was_hashed = hashed;
664 if (hashed) {
665 if ((hashed_host = host_hash(host, names, nlen)) == NULL)
666 return -1;
667 return nlen == strlen(hashed_host) &&
668 strncmp(hashed_host, names, nlen) == 0;
669 }
djm@openbsd.orge661a862015-05-04 06:10:48 +0000670 return match_hostname(host, names) == 1;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000671}
672
673int
674hostkeys_foreach(const char *path, hostkeys_foreach_fn *callback, void *ctx,
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000675 const char *host, const char *ip, u_int options)
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000676{
677 FILE *f;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000678 char line[8192], oline[8192], ktype[128];
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000679 u_long linenum = 0;
680 char *cp, *cp2;
681 u_int kbits;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000682 int hashed;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000683 int s, r = 0;
684 struct hostkey_foreach_line lineinfo;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000685 size_t l;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000686
687 memset(&lineinfo, 0, sizeof(lineinfo));
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000688 if (host == NULL && (options & HKF_WANT_MATCH) != 0)
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000689 return SSH_ERR_INVALID_ARGUMENT;
690 if ((f = fopen(path, "r")) == NULL)
691 return SSH_ERR_SYSTEM_ERROR;
692
693 debug3("%s: reading file \"%s\"", __func__, path);
694 while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) {
695 line[strcspn(line, "\n")] = '\0';
696 strlcpy(oline, line, sizeof(oline));
697
698 sshkey_free(lineinfo.key);
699 memset(&lineinfo, 0, sizeof(lineinfo));
700 lineinfo.path = path;
701 lineinfo.linenum = linenum;
702 lineinfo.line = oline;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000703 lineinfo.marker = MRK_NONE;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000704 lineinfo.status = HKF_STATUS_OK;
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000705 lineinfo.keytype = KEY_UNSPEC;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000706
707 /* Skip any leading whitespace, comments and empty lines. */
708 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
709 ;
710 if (!*cp || *cp == '#' || *cp == '\n') {
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000711 if ((options & HKF_WANT_MATCH) == 0) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000712 lineinfo.status = HKF_STATUS_COMMENT;
713 if ((r = callback(&lineinfo, ctx)) != 0)
714 break;
715 }
716 continue;
717 }
718
719 if ((lineinfo.marker = check_markers(&cp)) == MRK_ERROR) {
720 verbose("%s: invalid marker at %s:%lu",
721 __func__, path, linenum);
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000722 if ((options & HKF_WANT_MATCH) == 0)
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000723 goto bad;
724 continue;
725 }
726
727 /* Find the end of the host name portion. */
728 for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
729 ;
730 lineinfo.hosts = cp;
731 *cp2++ = '\0';
732
733 /* Check if the host name matches. */
734 if (host != NULL) {
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000735 if ((s = match_maybe_hashed(host, lineinfo.hosts,
736 &hashed)) == -1) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000737 debug2("%s: %s:%ld: bad host hash \"%.32s\"",
738 __func__, path, linenum, lineinfo.hosts);
739 goto bad;
740 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000741 if (s == 1) {
742 lineinfo.status = HKF_STATUS_MATCHED;
743 lineinfo.match |= HKF_MATCH_HOST |
744 (hashed ? HKF_MATCH_HOST_HASHED : 0);
745 }
746 /* Try matching IP address if supplied */
747 if (ip != NULL) {
748 if ((s = match_maybe_hashed(ip, lineinfo.hosts,
749 &hashed)) == -1) {
750 debug2("%s: %s:%ld: bad ip hash "
751 "\"%.32s\"", __func__, path,
752 linenum, lineinfo.hosts);
753 goto bad;
754 }
755 if (s == 1) {
756 lineinfo.status = HKF_STATUS_MATCHED;
757 lineinfo.match |= HKF_MATCH_IP |
758 (hashed ? HKF_MATCH_IP_HASHED : 0);
759 }
760 }
761 /*
762 * Skip this line if host matching requested and
763 * neither host nor address matched.
764 */
765 if ((options & HKF_WANT_MATCH) != 0 &&
766 lineinfo.status != HKF_STATUS_MATCHED)
767 continue;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000768 }
769
770 /* Got a match. Skip host name and any following whitespace */
771 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
772 ;
773 if (*cp2 == '\0' || *cp2 == '#') {
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000774 debug2("%s:%ld: truncated before key type",
775 path, linenum);
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000776 goto bad;
777 }
778 lineinfo.rawkey = cp = cp2;
779
780 if ((options & HKF_WANT_PARSE_KEY) != 0) {
781 /*
782 * Extract the key from the line. This will skip
783 * any leading whitespace. Ignore badly formatted
784 * lines.
785 */
786 if ((lineinfo.key = sshkey_new(KEY_UNSPEC)) == NULL) {
787 error("%s: sshkey_new failed", __func__);
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000788 r = SSH_ERR_ALLOC_FAIL;
789 break;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000790 }
791 if (!hostfile_read_key(&cp, &kbits, lineinfo.key)) {
792#ifdef WITH_SSH1
793 sshkey_free(lineinfo.key);
794 lineinfo.key = sshkey_new(KEY_RSA1);
795 if (lineinfo.key == NULL) {
796 error("%s: sshkey_new fail", __func__);
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000797 r = SSH_ERR_ALLOC_FAIL;
798 break;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000799 }
800 if (!hostfile_read_key(&cp, &kbits,
801 lineinfo.key))
802 goto bad;
803#else
804 goto bad;
805#endif
806 }
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000807 lineinfo.keytype = lineinfo.key->type;
808 lineinfo.comment = cp;
809 } else {
810 /* Extract and parse key type */
811 l = strcspn(lineinfo.rawkey, " \t");
812 if (l <= 1 || l >= sizeof(ktype) ||
813 lineinfo.rawkey[l] == '\0')
814 goto bad;
815 memcpy(ktype, lineinfo.rawkey, l);
816 ktype[l] = '\0';
817 lineinfo.keytype = sshkey_type_from_name(ktype);
djm@openbsd.org398f9ef2015-03-31 22:57:06 +0000818
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000819 /*
820 * Assume RSA1 if the first component is a short
821 * decimal number.
822 */
823 if (lineinfo.keytype == KEY_UNSPEC && l < 8 &&
824 strspn(ktype, "0123456789") == l)
825 lineinfo.keytype = KEY_RSA1;
djm@openbsd.org398f9ef2015-03-31 22:57:06 +0000826
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000827 /*
828 * Check that something other than whitespace follows
829 * the key type. This won't catch all corruption, but
830 * it does catch trivial truncation.
831 */
832 cp2 += l; /* Skip past key type */
833 for (; *cp2 == ' ' || *cp2 == '\t'; cp2++)
834 ;
835 if (*cp2 == '\0' || *cp2 == '#') {
836 debug2("%s:%ld: truncated after key type",
837 path, linenum);
838 lineinfo.keytype = KEY_UNSPEC;
839 }
840 if (lineinfo.keytype == KEY_UNSPEC) {
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000841 bad:
djm@openbsd.org6c5c9492015-02-16 22:08:57 +0000842 sshkey_free(lineinfo.key);
843 lineinfo.key = NULL;
djm@openbsd.orgc29811c2015-01-18 21:40:23 +0000844 lineinfo.status = HKF_STATUS_INVALID;
845 if ((r = callback(&lineinfo, ctx)) != 0)
846 break;
847 continue;
848 }
849 }
850 if ((r = callback(&lineinfo, ctx)) != 0)
851 break;
852 }
853 sshkey_free(lineinfo.key);
854 fclose(f);
855 return r;
856}