1264377Sdes/* $OpenBSD: hostfile.c,v 1.55 2014/01/31 16:39:19 tedu Exp $ */
257429Smarkm/*
357429Smarkm * Author: Tatu Ylonen <ylo@cs.hut.fi>
457429Smarkm * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
557429Smarkm *                    All rights reserved
665674Skris * Functions for manipulating the known hosts files.
760576Skris *
865674Skris * As far as I am concerned, the code I have written for this software
965674Skris * can be used freely for any purpose.  Any derived versions of this
1065674Skris * software must be clearly marked as such, and if the derived work is
1165674Skris * incompatible with the protocol description in the RFC file, it must be
1265674Skris * called by a name other than "ssh" or "Secure Shell".
1360576Skris *
1460576Skris *
1592559Sdes * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
1665674Skris * Copyright (c) 1999 Niels Provos.  All rights reserved.
1765674Skris *
1865674Skris * Redistribution and use in source and binary forms, with or without
1965674Skris * modification, are permitted provided that the following conditions
2065674Skris * are met:
2165674Skris * 1. Redistributions of source code must retain the above copyright
2265674Skris *    notice, this list of conditions and the following disclaimer.
2365674Skris * 2. Redistributions in binary form must reproduce the above copyright
2465674Skris *    notice, this list of conditions and the following disclaimer in the
2565674Skris *    documentation and/or other materials provided with the distribution.
2665674Skris *
2765674Skris * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
2865674Skris * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2965674Skris * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
3065674Skris * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
3165674Skris * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
3265674Skris * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3365674Skris * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3465674Skris * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3565674Skris * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3665674Skris * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3757429Smarkm */
3857429Smarkm
3957429Smarkm#include "includes.h"
4057429Smarkm
41162856Sdes#include <sys/types.h>
42162856Sdes
43162856Sdes#include <netinet/in.h>
44162856Sdes
45162856Sdes#include <resolv.h>
46162856Sdes#include <stdarg.h>
47162856Sdes#include <stdio.h>
48162856Sdes#include <stdlib.h>
49162856Sdes#include <string.h>
50162856Sdes
51162856Sdes#include "xmalloc.h"
5258582Skris#include "match.h"
5358582Skris#include "key.h"
5458582Skris#include "hostfile.h"
5576262Sgreen#include "log.h"
56221420Sdes#include "misc.h"
57262566Sdes#include "digest.h"
58264377Sdes#include "hmac.h"
5957429Smarkm
60221420Sdesstruct hostkeys {
61221420Sdes	struct hostkey_entry *entries;
62221420Sdes	u_int num_entries;
63221420Sdes};
64221420Sdes
65147005Sdesstatic int
66255767Sdesextract_salt(const char *s, u_int l, u_char *salt, size_t salt_len)
67147005Sdes{
68147005Sdes	char *p, *b64salt;
69147005Sdes	u_int b64len;
70147005Sdes	int ret;
71147005Sdes
72147005Sdes	if (l < sizeof(HASH_MAGIC) - 1) {
73147005Sdes		debug2("extract_salt: string too short");
74147005Sdes		return (-1);
75147005Sdes	}
76147005Sdes	if (strncmp(s, HASH_MAGIC, sizeof(HASH_MAGIC) - 1) != 0) {
77147005Sdes		debug2("extract_salt: invalid magic identifier");
78147005Sdes		return (-1);
79147005Sdes	}
80147005Sdes	s += sizeof(HASH_MAGIC) - 1;
81147005Sdes	l -= sizeof(HASH_MAGIC) - 1;
82147005Sdes	if ((p = memchr(s, HASH_DELIM, l)) == NULL) {
83147005Sdes		debug2("extract_salt: missing salt termination character");
84147005Sdes		return (-1);
85147005Sdes	}
86147005Sdes
87147005Sdes	b64len = p - s;
88147005Sdes	/* Sanity check */
89147005Sdes	if (b64len == 0 || b64len > 1024) {
90147005Sdes		debug2("extract_salt: bad encoded salt length %u", b64len);
91147005Sdes		return (-1);
92147005Sdes	}
93147005Sdes	b64salt = xmalloc(1 + b64len);
94147005Sdes	memcpy(b64salt, s, b64len);
95147005Sdes	b64salt[b64len] = '\0';
96147005Sdes
97147005Sdes	ret = __b64_pton(b64salt, salt, salt_len);
98255767Sdes	free(b64salt);
99147005Sdes	if (ret == -1) {
100147005Sdes		debug2("extract_salt: salt decode error");
101147005Sdes		return (-1);
102147005Sdes	}
103264377Sdes	if (ret != (int)ssh_hmac_bytes(SSH_DIGEST_SHA1)) {
104264377Sdes		debug2("extract_salt: expected salt len %zd, got %d",
105264377Sdes		    ssh_hmac_bytes(SSH_DIGEST_SHA1), ret);
106147005Sdes		return (-1);
107147005Sdes	}
108147005Sdes
109147005Sdes	return (0);
110147005Sdes}
111147005Sdes
112147005Sdeschar *
113147005Sdeshost_hash(const char *host, const char *name_from_hostfile, u_int src_len)
114147005Sdes{
115264377Sdes	struct ssh_hmac_ctx *ctx;
116255767Sdes	u_char salt[256], result[256];
117255767Sdes	char uu_salt[512], uu_result[512];
118147005Sdes	static char encoded[1024];
119147005Sdes	u_int i, len;
120147005Sdes
121264377Sdes	len = ssh_digest_bytes(SSH_DIGEST_SHA1);
122147005Sdes
123147005Sdes	if (name_from_hostfile == NULL) {
124147005Sdes		/* Create new salt */
125147005Sdes		for (i = 0; i < len; i++)
126147005Sdes			salt[i] = arc4random();
127147005Sdes	} else {
128147005Sdes		/* Extract salt from known host entry */
129147005Sdes		if (extract_salt(name_from_hostfile, src_len, salt,
130147005Sdes		    sizeof(salt)) == -1)
131147005Sdes			return (NULL);
132147005Sdes	}
133147005Sdes
134264377Sdes	if ((ctx = ssh_hmac_start(SSH_DIGEST_SHA1)) == NULL ||
135264377Sdes	    ssh_hmac_init(ctx, salt, len) < 0 ||
136264377Sdes	    ssh_hmac_update(ctx, host, strlen(host)) < 0 ||
137264377Sdes	    ssh_hmac_final(ctx, result, sizeof(result)))
138264377Sdes		fatal("%s: ssh_hmac failed", __func__);
139264377Sdes	ssh_hmac_free(ctx);
140147005Sdes
141147005Sdes	if (__b64_ntop(salt, len, uu_salt, sizeof(uu_salt)) == -1 ||
142147005Sdes	    __b64_ntop(result, len, uu_result, sizeof(uu_result)) == -1)
143264377Sdes		fatal("%s: __b64_ntop failed", __func__);
144147005Sdes
145147005Sdes	snprintf(encoded, sizeof(encoded), "%s%s%c%s", HASH_MAGIC, uu_salt,
146147005Sdes	    HASH_DELIM, uu_result);
147147005Sdes
148147005Sdes	return (encoded);
149147005Sdes}
150147005Sdes
15157429Smarkm/*
15258582Skris * Parses an RSA (number of bits, e, n) or DSA key from a string.  Moves the
15358582Skris * pointer over the key.  Skips any whitespace at the beginning and at end.
15457429Smarkm */
15557429Smarkm
15657429Smarkmint
157255767Sdeshostfile_read_key(char **cpp, int *bitsp, Key *ret)
15857429Smarkm{
15957429Smarkm	char *cp;
16057429Smarkm
16157429Smarkm	/* Skip leading whitespace. */
16257429Smarkm	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
16357429Smarkm		;
16457429Smarkm
16576262Sgreen	if (key_read(ret, &cp) != 1)
16657429Smarkm		return 0;
16757429Smarkm
16857429Smarkm	/* Skip trailing whitespace. */
16957429Smarkm	for (; *cp == ' ' || *cp == '\t'; cp++)
17057429Smarkm		;
17157429Smarkm
17257429Smarkm	/* Return results. */
17357429Smarkm	*cpp = cp;
174255767Sdes	if (bitsp != NULL) {
175255767Sdes		if ((*bitsp = key_size(ret)) <= 0)
176255767Sdes			return 0;
177255767Sdes	}
17857429Smarkm	return 1;
17957429Smarkm}
18057429Smarkm
18192559Sdesstatic int
182221420Sdeshostfile_check_key(int bits, const Key *key, const char *host,
183221420Sdes    const char *filename, u_long linenum)
18457429Smarkm{
18576262Sgreen	if (key == NULL || key->type != KEY_RSA1 || key->rsa == NULL)
18658582Skris		return 1;
18758582Skris	if (bits != BN_num_bits(key->rsa->n)) {
188221420Sdes		logit("Warning: %s, line %lu: keysize mismatch for host %s: "
18958582Skris		    "actual %d vs. announced %d.",
19058582Skris		    filename, linenum, host, BN_num_bits(key->rsa->n), bits);
191221420Sdes		logit("Warning: replace %d with %d in %s, line %lu.",
19258582Skris		    bits, BN_num_bits(key->rsa->n), filename, linenum);
19357429Smarkm	}
19458582Skris	return 1;
19557429Smarkm}
19657429Smarkm
197221420Sdesstatic HostkeyMarker
198204917Sdescheck_markers(char **cpp)
199204917Sdes{
200204917Sdes	char marker[32], *sp, *cp = *cpp;
201204917Sdes	int ret = MRK_NONE;
202204917Sdes
203204917Sdes	while (*cp == '@') {
204204917Sdes		/* Only one marker is allowed */
205204917Sdes		if (ret != MRK_NONE)
206204917Sdes			return MRK_ERROR;
207204917Sdes		/* Markers are terminated by whitespace */
208204917Sdes		if ((sp = strchr(cp, ' ')) == NULL &&
209204917Sdes		    (sp = strchr(cp, '\t')) == NULL)
210204917Sdes			return MRK_ERROR;
211204917Sdes		/* Extract marker for comparison */
212204917Sdes		if (sp <= cp + 1 || sp >= cp + sizeof(marker))
213204917Sdes			return MRK_ERROR;
214204917Sdes		memcpy(marker, cp, sp - cp);
215204917Sdes		marker[sp - cp] = '\0';
216204917Sdes		if (strcmp(marker, CA_MARKER) == 0)
217204917Sdes			ret = MRK_CA;
218204917Sdes		else if (strcmp(marker, REVOKE_MARKER) == 0)
219204917Sdes			ret = MRK_REVOKE;
220204917Sdes		else
221204917Sdes			return MRK_ERROR;
222204917Sdes
223204917Sdes		/* Skip past marker and any whitespace that follows it */
224204917Sdes		cp = sp;
225204917Sdes		for (; *cp == ' ' || *cp == '\t'; cp++)
226204917Sdes			;
227204917Sdes	}
228204917Sdes	*cpp = cp;
229204917Sdes	return ret;
230204917Sdes}
231204917Sdes
232221420Sdesstruct hostkeys *
233221420Sdesinit_hostkeys(void)
234221420Sdes{
235221420Sdes	struct hostkeys *ret = xcalloc(1, sizeof(*ret));
23657429Smarkm
237221420Sdes	ret->entries = NULL;
238221420Sdes	return ret;
239221420Sdes}
240221420Sdes
241221420Sdesvoid
242221420Sdesload_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
24357429Smarkm{
24457429Smarkm	FILE *f;
24557429Smarkm	char line[8192];
246221420Sdes	u_long linenum = 0, num_loaded = 0;
247147005Sdes	char *cp, *cp2, *hashed_host;
248221420Sdes	HostkeyMarker marker;
249221420Sdes	Key *key;
250221420Sdes	int kbits;
25157429Smarkm
252221420Sdes	if ((f = fopen(path, "r")) == NULL)
253221420Sdes		return;
254221420Sdes	debug3("%s: loading entries for host \"%.100s\" from file \"%s\"",
255221420Sdes	    __func__, host, path);
256221420Sdes	while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) {
25757429Smarkm		cp = line;
25857429Smarkm
25957429Smarkm		/* Skip any leading whitespace, comments and empty lines. */
26057429Smarkm		for (; *cp == ' ' || *cp == '\t'; cp++)
26157429Smarkm			;
26257429Smarkm		if (!*cp || *cp == '#' || *cp == '\n')
26357429Smarkm			continue;
26457429Smarkm
265221420Sdes		if ((marker = check_markers(&cp)) == MRK_ERROR) {
266221420Sdes			verbose("%s: invalid marker at %s:%lu",
267221420Sdes			    __func__, path, linenum);
268204917Sdes			continue;
269221420Sdes		}
270204917Sdes
27157429Smarkm		/* Find the end of the host name portion. */
27257429Smarkm		for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
27357429Smarkm			;
27457429Smarkm
27557429Smarkm		/* Check if the host name matches. */
276147005Sdes		if (match_hostname(host, cp, (u_int) (cp2 - cp)) != 1) {
277147005Sdes			if (*cp != HASH_DELIM)
278147005Sdes				continue;
279147005Sdes			hashed_host = host_hash(host, cp, (u_int) (cp2 - cp));
280147005Sdes			if (hashed_host == NULL) {
281221420Sdes				debug("Invalid hashed host line %lu of %s",
282221420Sdes				    linenum, path);
283147005Sdes				continue;
284147005Sdes			}
285147005Sdes			if (strncmp(hashed_host, cp, (u_int) (cp2 - cp)) != 0)
286147005Sdes				continue;
287147005Sdes		}
28857429Smarkm
28957429Smarkm		/* Got a match.  Skip host name. */
29057429Smarkm		cp = cp2;
29157429Smarkm
29257429Smarkm		/*
29357429Smarkm		 * Extract the key from the line.  This will skip any leading
29457429Smarkm		 * whitespace.  Ignore badly formatted lines.
29557429Smarkm		 */
296221420Sdes		key = key_new(KEY_UNSPEC);
297221420Sdes		if (!hostfile_read_key(&cp, &kbits, key)) {
298221420Sdes			key_free(key);
299221420Sdes			key = key_new(KEY_RSA1);
300221420Sdes			if (!hostfile_read_key(&cp, &kbits, key)) {
301221420Sdes				key_free(key);
302221420Sdes				continue;
303221420Sdes			}
304221420Sdes		}
305221420Sdes		if (!hostfile_check_key(kbits, key, host, path, linenum))
30657429Smarkm			continue;
30757429Smarkm
308221420Sdes		debug3("%s: found %skey type %s in file %s:%lu", __func__,
309221420Sdes		    marker == MRK_NONE ? "" :
310221420Sdes		    (marker == MRK_CA ? "ca " : "revoked "),
311221420Sdes		    key_type(key), path, linenum);
312221420Sdes		hostkeys->entries = xrealloc(hostkeys->entries,
313221420Sdes		    hostkeys->num_entries + 1, sizeof(*hostkeys->entries));
314221420Sdes		hostkeys->entries[hostkeys->num_entries].host = xstrdup(host);
315221420Sdes		hostkeys->entries[hostkeys->num_entries].file = xstrdup(path);
316221420Sdes		hostkeys->entries[hostkeys->num_entries].line = linenum;
317221420Sdes		hostkeys->entries[hostkeys->num_entries].key = key;
318221420Sdes		hostkeys->entries[hostkeys->num_entries].marker = marker;
319221420Sdes		hostkeys->num_entries++;
320221420Sdes		num_loaded++;
321221420Sdes	}
322221420Sdes	debug3("%s: loaded %lu keys", __func__, num_loaded);
323221420Sdes	fclose(f);
324221420Sdes	return;
325221420Sdes}
32676262Sgreen
327221420Sdesvoid
328221420Sdesfree_hostkeys(struct hostkeys *hostkeys)
329221420Sdes{
330221420Sdes	u_int i;
331221420Sdes
332221420Sdes	for (i = 0; i < hostkeys->num_entries; i++) {
333255767Sdes		free(hostkeys->entries[i].host);
334255767Sdes		free(hostkeys->entries[i].file);
335221420Sdes		key_free(hostkeys->entries[i].key);
336264377Sdes		explicit_bzero(hostkeys->entries + i, sizeof(*hostkeys->entries));
337221420Sdes	}
338255767Sdes	free(hostkeys->entries);
339264377Sdes	explicit_bzero(hostkeys, sizeof(*hostkeys));
340255767Sdes	free(hostkeys);
341221420Sdes}
342221420Sdes
343221420Sdesstatic int
344221420Sdescheck_key_not_revoked(struct hostkeys *hostkeys, Key *k)
345221420Sdes{
346221420Sdes	int is_cert = key_is_cert(k);
347221420Sdes	u_int i;
348221420Sdes
349221420Sdes	for (i = 0; i < hostkeys->num_entries; i++) {
350221420Sdes		if (hostkeys->entries[i].marker != MRK_REVOKE)
351106130Sdes			continue;
352221420Sdes		if (key_equal_public(k, hostkeys->entries[i].key))
353221420Sdes			return -1;
354221420Sdes		if (is_cert &&
355221420Sdes		    key_equal_public(k->cert->signature_key,
356221420Sdes		    hostkeys->entries[i].key))
357221420Sdes			return -1;
358221420Sdes	}
359221420Sdes	return 0;
360221420Sdes}
361106130Sdes
362221420Sdes/*
363221420Sdes * Match keys against a specified key, or look one up by key type.
364221420Sdes *
365221420Sdes * If looking for a keytype (key == NULL) and one is found then return
366221420Sdes * HOST_FOUND, otherwise HOST_NEW.
367221420Sdes *
368221420Sdes * If looking for a key (key != NULL):
369221420Sdes *  1. If the key is a cert and a matching CA is found, return HOST_OK
370221420Sdes *  2. If the key is not a cert and a matching key is found, return HOST_OK
371221420Sdes *  3. If no key matches but a key with a different type is found, then
372221420Sdes *     return HOST_CHANGED
373221420Sdes *  4. If no matching keys are found, then return HOST_NEW.
374221420Sdes *
375221420Sdes * Finally, check any found key is not revoked.
376221420Sdes */
377221420Sdesstatic HostStatus
378221420Sdescheck_hostkeys_by_key_or_type(struct hostkeys *hostkeys,
379221420Sdes    Key *k, int keytype, const struct hostkey_entry **found)
380221420Sdes{
381221420Sdes	u_int i;
382221420Sdes	HostStatus end_return = HOST_NEW;
383221420Sdes	int want_cert = key_is_cert(k);
384221420Sdes	HostkeyMarker want_marker = want_cert ? MRK_CA : MRK_NONE;
385221420Sdes	int proto = (k ? k->type : keytype) == KEY_RSA1 ? 1 : 2;
386221420Sdes
387221420Sdes	if (found != NULL)
388221420Sdes		*found = NULL;
389221420Sdes
390221420Sdes	for (i = 0; i < hostkeys->num_entries; i++) {
391221420Sdes		if (proto == 1 && hostkeys->entries[i].key->type != KEY_RSA1)
392106130Sdes			continue;
393221420Sdes		if (proto == 2 && hostkeys->entries[i].key->type == KEY_RSA1)
394221420Sdes			continue;
395221420Sdes		if (hostkeys->entries[i].marker != want_marker)
396221420Sdes			continue;
397221420Sdes		if (k == NULL) {
398221420Sdes			if (hostkeys->entries[i].key->type != keytype)
399221420Sdes				continue;
400221420Sdes			end_return = HOST_FOUND;
401221420Sdes			if (found != NULL)
402221420Sdes				*found = hostkeys->entries + i;
403221420Sdes			k = hostkeys->entries[i].key;
404221420Sdes			break;
405221420Sdes		}
406221420Sdes		if (want_cert) {
407221420Sdes			if (key_equal_public(k->cert->signature_key,
408221420Sdes			    hostkeys->entries[i].key)) {
409221420Sdes				/* A matching CA exists */
410221420Sdes				end_return = HOST_OK;
411221420Sdes				if (found != NULL)
412221420Sdes					*found = hostkeys->entries + i;
413221420Sdes				break;
414204917Sdes			}
415221420Sdes		} else {
416221420Sdes			if (key_equal(k, hostkeys->entries[i].key)) {
417221420Sdes				end_return = HOST_OK;
418221420Sdes				if (found != NULL)
419221420Sdes					*found = hostkeys->entries + i;
420221420Sdes				break;
421204917Sdes			}
422221420Sdes			/* A non-maching key exists */
423221420Sdes			end_return = HOST_CHANGED;
424221420Sdes			if (found != NULL)
425221420Sdes				*found = hostkeys->entries + i;
426204917Sdes		}
42757429Smarkm	}
428221420Sdes	if (check_key_not_revoked(hostkeys, k) != 0) {
429221420Sdes		end_return = HOST_REVOKED;
430221420Sdes		if (found != NULL)
431221420Sdes			*found = NULL;
432221420Sdes	}
43357429Smarkm	return end_return;
43457429Smarkm}
435221420Sdes
436106130SdesHostStatus
437221420Sdescheck_key_in_hostkeys(struct hostkeys *hostkeys, Key *key,
438221420Sdes    const struct hostkey_entry **found)
439106130Sdes{
440106130Sdes	if (key == NULL)
441106130Sdes		fatal("no key to look up");
442221420Sdes	return check_hostkeys_by_key_or_type(hostkeys, key, 0, found);
443106130Sdes}
444106130Sdes
445106130Sdesint
446221420Sdeslookup_key_in_hostkeys_by_type(struct hostkeys *hostkeys, int keytype,
447221420Sdes    const struct hostkey_entry **found)
448106130Sdes{
449221420Sdes	return (check_hostkeys_by_key_or_type(hostkeys, NULL, keytype,
450221420Sdes	    found) == HOST_FOUND);
451106130Sdes}
452106130Sdes
45357429Smarkm/*
45457429Smarkm * Appends an entry to the host file.  Returns false if the entry could not
45557429Smarkm * be appended.
45657429Smarkm */
45757429Smarkm
45857429Smarkmint
459147005Sdesadd_host_to_hostfile(const char *filename, const char *host, const Key *key,
460147005Sdes    int store_hash)
46157429Smarkm{
46257429Smarkm	FILE *f;
46358582Skris	int success = 0;
464149753Sdes	char *hashed_host = NULL;
465147005Sdes
46658582Skris	if (key == NULL)
46760576Skris		return 1;	/* XXX ? */
46857429Smarkm	f = fopen(filename, "a");
46957429Smarkm	if (!f)
47057429Smarkm		return 0;
471147005Sdes
472147005Sdes	if (store_hash) {
473147005Sdes		if ((hashed_host = host_hash(host, NULL, 0)) == NULL) {
474147005Sdes			error("add_host_to_hostfile: host_hash failed");
475147005Sdes			fclose(f);
476147005Sdes			return 0;
477147005Sdes		}
478147005Sdes	}
479147005Sdes	fprintf(f, "%s ", store_hash ? hashed_host : host);
480147005Sdes
48158582Skris	if (key_write(key, f)) {
48258582Skris		success = 1;
48358582Skris	} else {
48460576Skris		error("add_host_to_hostfile: saving key in %s failed", filename);
48557429Smarkm	}
48660576Skris	fprintf(f, "\n");
48757429Smarkm	fclose(f);
48858582Skris	return success;
48957429Smarkm}
490