1/* $OpenBSD: hostfile.c,v 1.50 2010/12/04 13:31:37 djm Exp $ */
2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 *                    All rights reserved
6 * Functions for manipulating the known hosts files.
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose.  Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 *
14 *
15 * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
16 * Copyright (c) 1999 Niels Provos.  All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
20 * are met:
21 * 1. Redistributions of source code must retain the above copyright
22 *    notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 *    notice, this list of conditions and the following disclaimer in the
25 *    documentation and/or other materials provided with the distribution.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38
39#include "includes.h"
40
41#include <sys/types.h>
42
43#include <netinet/in.h>
44
45#ifdef __APPLE_CRYPTO__
46#include "ossl-hmac.h"
47#include "ossl-sha.h"
48#else
49#include <openssl/hmac.h>
50#include <openssl/sha.h>
51#endif
52
53#include <resolv.h>
54#include <stdarg.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58
59#include "xmalloc.h"
60#include "match.h"
61#include "key.h"
62#include "hostfile.h"
63#include "log.h"
64#include "misc.h"
65
66struct hostkeys {
67	struct hostkey_entry *entries;
68	u_int num_entries;
69};
70
71static int
72extract_salt(const char *s, u_int l, char *salt, size_t salt_len)
73{
74	char *p, *b64salt;
75	u_int b64len;
76	int ret;
77
78	if (l < sizeof(HASH_MAGIC) - 1) {
79		debug2("extract_salt: string too short");
80		return (-1);
81	}
82	if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) {
83		debug2("extract_salt: invalid magic identifier");
84		return (-1);
85	}
86	s += sizeof(HASH_MAGIC) - 1;
87	l -= sizeof(HASH_MAGIC) - 1;
88	if ((p = memchr(s, HASH_DELIM, l)) == NULL) {
89		debug2("extract_salt: missing salt termination character");
90		return (-1);
91	}
92
93	b64len = p - s;
94	/* Sanity check */
95	if (b64len == 0 || b64len > 1024) {
96		debug2("extract_salt: bad encoded salt length %u", b64len);
97		return (-1);
98	}
99	b64salt = xmalloc(1 + b64len);
100	memcpy(b64salt, s, b64len);
101	b64salt[b64len] = '\0';
102
103	ret = __b64_pton(b64salt, salt, salt_len);
104	xfree(b64salt);
105	if (ret == -1) {
106		debug2("extract_salt: salt decode error");
107		return (-1);
108	}
109	if (ret != SHA_DIGEST_LENGTH) {
110		debug2("extract_salt: expected salt len %d, got %d",
111		    SHA_DIGEST_LENGTH, ret);
112		return (-1);
113	}
114
115	return (0);
116}
117
118char *
119host_hash(const char *host, const char *name_from_hostfile, u_int src_len)
120{
121	const EVP_MD *md = EVP_sha1();
122	HMAC_CTX mac_ctx;
123	char salt[256], result[256], uu_salt[512], uu_result[512];
124	static char encoded[1024];
125	u_int i, len;
126
127	len = EVP_MD_size(md);
128
129	if (name_from_hostfile == NULL) {
130		/* Create new salt */
131		for (i = 0; i < len; i++)
132			salt[i] = arc4random();
133	} 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
140	HMAC_Init(&mac_ctx, salt, len, md);
141	HMAC_Update(&mac_ctx, host, strlen(host));
142	HMAC_Final(&mac_ctx, result, NULL);
143	HMAC_cleanup(&mac_ctx);
144
145	if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
146	    __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
147		fatal("host_hash: __b64_ntop failed");
148
149	snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt,
150	    HASH_DELIM, uu_result);
151
152	return (encoded);
153}
154
155/*
156 * Parses an RSA (number of bits, e, n) or DSA key from a string.  Moves the
157 * pointer over the key.  Skips any whitespace at the beginning and at end.
158 */
159
160int
161hostfile_read_key(char **cpp, u_int *bitsp, Key *ret)
162{
163	char *cp;
164
165	/* Skip leading whitespace. */
166	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
167		;
168
169	if (key_read(ret, &cp) != 1)
170		return 0;
171
172	/* Skip trailing whitespace. */
173	for (; *cp == ' ' || *cp == '\t'; cp++)
174		;
175
176	/* Return results. */
177	*cpp = cp;
178	if (bitsp != NULL)
179		*bitsp = key_size(ret);
180	return 1;
181}
182
183static int
184hostfile_check_key(int bits, const Key *key, const char *host,
185    const char *filename, u_long linenum)
186{
187	if (key == NULL || key->type != KEY_RSA1 || key->rsa == NULL)
188		return 1;
189	if (bits != BN_num_bits(key->rsa->n)) {
190		logit("Warning: %s, line %lu: keysize mismatch for host %s: "
191		    "actual %d vs. announced %d.",
192		    filename, linenum, host, BN_num_bits(key->rsa->n), bits);
193		logit("Warning: replace %d with %d in %s, line %lu.",
194		    bits, BN_num_bits(key->rsa->n), filename, linenum);
195	}
196	return 1;
197}
198
199static HostkeyMarker
200check_markers(char **cpp)
201{
202	char marker[32], *sp, *cp = *cpp;
203	int ret = MRK_NONE;
204
205	while (*cp == '@') {
206		/* Only one marker is allowed */
207		if (ret != MRK_NONE)
208			return MRK_ERROR;
209		/* Markers are terminated by whitespace */
210		if ((sp = strchr(cp, ' ')) == NULL &&
211		    (sp = strchr(cp, '\t')) == NULL)
212			return MRK_ERROR;
213		/* Extract marker for comparison */
214		if (sp <= cp + 1 || sp >= cp + sizeof(marker))
215			return MRK_ERROR;
216		memcpy(marker, cp, sp - cp);
217		marker[sp - cp] = '\0';
218		if (strcmp(marker, CA_MARKER) == 0)
219			ret = MRK_CA;
220		else if (strcmp(marker, REVOKE_MARKER) == 0)
221			ret = MRK_REVOKE;
222		else
223			return MRK_ERROR;
224
225		/* Skip past marker and any whitespace that follows it */
226		cp = sp;
227		for (; *cp == ' ' || *cp == '\t'; cp++)
228			;
229	}
230	*cpp = cp;
231	return ret;
232}
233
234struct hostkeys *
235init_hostkeys(void)
236{
237	struct hostkeys *ret = xcalloc(1, sizeof(*ret));
238
239	ret->entries = NULL;
240	return ret;
241}
242
243void
244load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
245{
246	FILE *f;
247	char line[8192];
248	u_long linenum = 0, num_loaded = 0;
249	char *cp, *cp2, *hashed_host;
250	HostkeyMarker marker;
251	Key *key;
252	int kbits;
253
254	if ((f = fopen(path, "r")) == NULL)
255		return;
256	debug3("%s: loading entries for host \"%.100s\" from file \"%s\"",
257	    __func__, host, path);
258	while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) {
259		cp = line;
260
261		/* Skip any leading whitespace, comments and empty lines. */
262		for (; *cp == ' ' || *cp == '\t'; cp++)
263			;
264		if (!*cp || *cp == '#' || *cp == '\n')
265			continue;
266
267		if ((marker = check_markers(&cp)) == MRK_ERROR) {
268			verbose("%s: invalid marker at %s:%lu",
269			    __func__, path, linenum);
270			continue;
271		}
272
273		/* Find the end of the host name portion. */
274		for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
275			;
276
277		/* Check if the host name matches. */
278		if (match_hostname(host, cp, (u_int) (cp2 - cp)) != 1) {
279			if (*cp != HASH_DELIM)
280				continue;
281			hashed_host = host_hash(host, cp, (u_int) (cp2 - cp));
282			if (hashed_host == NULL) {
283				debug("Invalid hashed host line %lu of %s",
284				    linenum, path);
285				continue;
286			}
287			if (strncmp(hashed_host, cp, (u_int) (cp2 - cp)) != 0)
288				continue;
289		}
290
291		/* Got a match.  Skip host name. */
292		cp = cp2;
293
294		/*
295		 * Extract the key from the line.  This will skip any leading
296		 * whitespace.  Ignore badly formatted lines.
297		 */
298		key = key_new(KEY_UNSPEC);
299		if (!hostfile_read_key(&cp, &kbits, key)) {
300			key_free(key);
301			key = key_new(KEY_RSA1);
302			if (!hostfile_read_key(&cp, &kbits, key)) {
303				key_free(key);
304				continue;
305			}
306		}
307		if (!hostfile_check_key(kbits, key, host, path, linenum))
308			continue;
309
310		debug3("%s: found %skey type %s in file %s:%lu", __func__,
311		    marker == MRK_NONE ? "" :
312		    (marker == MRK_CA ? "ca " : "revoked "),
313		    key_type(key), path, linenum);
314		hostkeys->entries = xrealloc(hostkeys->entries,
315		    hostkeys->num_entries + 1, sizeof(*hostkeys->entries));
316		hostkeys->entries[hostkeys->num_entries].host = xstrdup(host);
317		hostkeys->entries[hostkeys->num_entries].file = xstrdup(path);
318		hostkeys->entries[hostkeys->num_entries].line = linenum;
319		hostkeys->entries[hostkeys->num_entries].key = key;
320		hostkeys->entries[hostkeys->num_entries].marker = marker;
321		hostkeys->num_entries++;
322		num_loaded++;
323	}
324	debug3("%s: loaded %lu keys", __func__, num_loaded);
325	fclose(f);
326	return;
327}
328
329void
330free_hostkeys(struct hostkeys *hostkeys)
331{
332	u_int i;
333
334	for (i = 0; i < hostkeys->num_entries; i++) {
335		xfree(hostkeys->entries[i].host);
336		xfree(hostkeys->entries[i].file);
337		key_free(hostkeys->entries[i].key);
338		bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
339	}
340	if (hostkeys->entries != NULL)
341		xfree(hostkeys->entries);
342	hostkeys->entries = NULL;
343	hostkeys->num_entries = 0;
344	xfree(hostkeys);
345}
346
347static int
348check_key_not_revoked(struct hostkeys *hostkeys, Key *k)
349{
350	int is_cert = key_is_cert(k);
351	u_int i;
352
353	for (i = 0; i < hostkeys->num_entries; i++) {
354		if (hostkeys->entries[i].marker != MRK_REVOKE)
355			continue;
356		if (key_equal_public(k, hostkeys->entries[i].key))
357			return -1;
358		if (is_cert &&
359		    key_equal_public(k->cert->signature_key,
360		    hostkeys->entries[i].key))
361			return -1;
362	}
363	return 0;
364}
365
366/*
367 * Match keys against a specified key, or look one up by key type.
368 *
369 * If looking for a keytype (key == NULL) and one is found then return
370 * HOST_FOUND, otherwise HOST_NEW.
371 *
372 * If looking for a key (key != NULL):
373 *  1. If the key is a cert and a matching CA is found, return HOST_OK
374 *  2. If the key is not a cert and a matching key is found, return HOST_OK
375 *  3. If no key matches but a key with a different type is found, then
376 *     return HOST_CHANGED
377 *  4. If no matching keys are found, then return HOST_NEW.
378 *
379 * Finally, check any found key is not revoked.
380 */
381static HostStatus
382check_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
383    Key *k, int keytype, const struct hostkey_entry **found)
384{
385	u_int i;
386	HostStatus end_return = HOST_NEW;
387	int want_cert = key_is_cert(k);
388	HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
389	int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2;
390
391	if (found != NULL)
392		*found = NULL;
393
394	for (i = 0; i < hostkeys->num_entries; i++) {
395		if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1)
396			continue;
397		if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1)
398			continue;
399		if (hostkeys->entries[i].marker != want_marker)
400			continue;
401		if (k == NULL) {
402			if (hostkeys->entries[i].key->type != keytype)
403				continue;
404			end_return = HOST_FOUND;
405			if (found != NULL)
406				*found = hostkeys->entries + i;
407			k = hostkeys->entries[i].key;
408			break;
409		}
410		if (want_cert) {
411			if (key_equal_public(k->cert->signature_key,
412			    hostkeys->entries[i].key)) {
413				/* A matching CA exists */
414				end_return = HOST_OK;
415				if (found != NULL)
416					*found = hostkeys->entries + i;
417				break;
418			}
419		} else {
420			if (key_equal(k, hostkeys->entries[i].key)) {
421				end_return = HOST_OK;
422				if (found != NULL)
423					*found = hostkeys->entries + i;
424				break;
425			}
426			/* A non-maching key exists */
427			end_return = HOST_CHANGED;
428			if (found != NULL)
429				*found = hostkeys->entries + i;
430		}
431	}
432	if (check_key_not_revoked(hostkeys, k) != 0) {
433		end_return = HOST_REVOKED;
434		if (found != NULL)
435			*found = NULL;
436	}
437	return end_return;
438}
439
440HostStatus
441check_key_in_hostkeys(struct hostkeys *hostkeys, Key *key,
442    const struct hostkey_entry **found)
443{
444	if (key == NULL)
445		fatal("no key to look up");
446	return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
447}
448
449int
450lookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
451    const struct hostkey_entry **found)
452{
453	return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
454	    found) == HOST_FOUND);
455}
456
457/*
458 * Appends an entry to the host file.  Returns false if the entry could not
459 * be appended.
460 */
461
462int
463add_host_to_hostfile(const char *filename, const char *host, const Key *key,
464    int store_hash)
465{
466	FILE *f;
467	int success = 0;
468	char *hashed_host = NULL;
469
470	if (key == NULL)
471		return 1;	/* XXX ? */
472	f = fopen(filename, "a");
473	if (!f)
474		return 0;
475
476	if (store_hash) {
477		if ((hashed_host = host_hash(host, NULL, 0)) == NULL) {
478			error("add_host_to_hostfile: host_hash failed");
479			fclose(f);
480			return 0;
481		}
482	}
483	fprintf(f, "%s ", store_hash ? hashed_host : host);
484
485	if (key_write(key, f)) {
486		success = 1;
487	} else {
488		error("add_host_to_hostfile: saving key in %s failed", filename);
489	}
490	fprintf(f, "\n");
491	fclose(f);
492	return success;
493}
494