1/*-
2 * Copyright (c) 2009 The NetBSD Foundation, Inc.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to The NetBSD Foundation
6 * by Alistair Crooks (agc@NetBSD.org)
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29#include "config.h"
30
31#ifdef HAVE_SYS_CDEFS_H
32#include <sys/cdefs.h>
33#endif
34
35#include <sys/types.h>
36#include <sys/stat.h>
37#include <sys/param.h>
38
39#include <netinet/in.h>
40
41#include <arpa/inet.h>
42
43#include <ctype.h>
44#include <inttypes.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48
49#ifdef HAVE_UNISTD_H
50#include <unistd.h>
51#endif
52
53#ifdef HAVE_LIMITS_H
54#include <limits.h>
55#endif
56
57#ifdef HAVE_OPENSSL_CAST_H
58#include <openssl/cast.h>
59#endif
60
61#include <openssl/pem.h>
62
63#include "bufgap.h"
64
65#include "packet-parse.h"
66#include "netpgpdefs.h"
67#include "netpgpsdk.h"
68#include "crypto.h"
69#include "netpgpdigest.h"
70#include "ssh2pgp.h"
71
72/* structure for earching for constant strings */
73typedef struct str_t {
74	const char	*s;		/* string */
75	size_t		 len;		/* its length */
76	int		 type;		/* return type */
77} str_t;
78
79#ifndef USE_ARG
80#define USE_ARG(x)	/*LINTED*/(void)&x
81#endif
82
83static const uint8_t	base64s[] =
84/* 000 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
85/* 016 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
86/* 032 */       "\0\0\0\0\0\0\0\0\0\0\0?\0\0\0@"
87/* 048 */       "56789:;<=>\0\0\0\0\0\0"
88/* 064 */       "\0\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17"
89/* 080 */       "\20\21\22\23\24\25\26\27\30\31\32\0\0\0\0\0"
90/* 096 */       "\0\33\34\35\36\37 !\"#$%&'()"
91/* 112 */       "*+,-./01234\0\0\0\0\0"
92/* 128 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
93/* 144 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
94/* 160 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
95/* 176 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
96/* 192 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
97/* 208 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
98/* 224 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
99/* 240 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
100
101
102/* short function to decode from base64 */
103/* inspired by an ancient copy of b64.c, then rewritten, the bugs are all mine */
104static int
105frombase64(char *dst, const char *src, size_t size, int flag)
106{
107	uint8_t	out[3];
108	uint8_t	in[4];
109	uint8_t	b;
110	size_t	srcc;
111	int	dstc;
112	int	gotc;
113	int	i;
114
115	USE_ARG(flag);
116	for (dstc = 0, srcc = 0 ; srcc < size; ) {
117		for (gotc = 0, i = 0; i < 4 && srcc < size; i++) {
118			for (b = 0x0; srcc < size && b == 0x0 ; ) {
119				b = base64s[(unsigned)src[srcc++]];
120			}
121			if (srcc < size) {
122				gotc += 1;
123				if (b) {
124					in[i] = (uint8_t)(b - 1);
125				}
126			} else {
127				in[i] = 0x0;
128			}
129		}
130		if (gotc) {
131			out[0] = (uint8_t)((unsigned)in[0] << 2 |
132						(unsigned)in[1] >> 4);
133			out[1] = (uint8_t)((unsigned)in[1] << 4 |
134						(unsigned)in[2] >> 2);
135			out[2] = (uint8_t)(((in[2] << 6) & 0xc0) | in[3]);
136			for (i = 0; i < gotc - 1; i++) {
137				*dst++ = out[i];
138			}
139			dstc += gotc - 1;
140		}
141	}
142	return dstc;
143}
144
145/* get a bignum from the buffer gap */
146static BIGNUM *
147getbignum(bufgap_t *bg, char *buf, const char *header)
148{
149	uint32_t	 len;
150	BIGNUM		*bignum;
151
152	(void) bufgap_getbin(bg, &len, sizeof(len));
153	len = ntohl(len);
154	(void) bufgap_seek(bg, sizeof(len), BGFromHere, BGByte);
155	(void) bufgap_getbin(bg, buf, len);
156	bignum = BN_bin2bn((const uint8_t *)buf, (int)len, NULL);
157	if (pgp_get_debug_level(__FILE__)) {
158		hexdump(stderr, header, (const uint8_t *)(void *)buf, len);
159	}
160	(void) bufgap_seek(bg, len, BGFromHere, BGByte);
161	return bignum;
162}
163
164#if 0
165static int
166putbignum(bufgap_t *bg, BIGNUM *bignum)
167{
168	uint32_t	 len;
169
170	len = BN_num_bytes(bignum);
171	(void) bufgap_insert(bg, &len, sizeof(len));
172	(void) bufgap_insert(bg, buf, len);
173	bignum = BN_bin2bn((const uint8_t *)buf, (int)len, NULL);
174	if (pgp_get_debug_level(__FILE__)) {
175		hexdump(stderr, header, buf, (int)len);
176	}
177	(void) bufgap_seek(bg, len, BGFromHere, BGByte);
178	return bignum;
179}
180#endif
181
182static str_t	pkatypes[] = {
183	{	"ssh-rsa",	7,	PGP_PKA_RSA	},
184	{	"ssh-dss",	7,	PGP_PKA_DSA	},
185	{	"ssh-dsa",	7,	PGP_PKA_DSA	},
186	{	NULL,		0,	0		}
187};
188
189/* look for a string in the given array */
190static int
191findstr(str_t *array, const char *name)
192{
193	str_t	*sp;
194
195	for (sp = array ; sp->s ; sp++) {
196		if (strncmp(name, sp->s, sp->len) == 0) {
197			return sp->type;
198		}
199	}
200	return -1;
201}
202
203/* convert an ssh (host) pubkey to a pgp pubkey */
204int
205pgp_ssh2pubkey(pgp_io_t *io, const char *f, pgp_key_t *key, pgp_hash_alg_t hashtype)
206{
207	pgp_pubkey_t	*pubkey;
208	struct stat	 st;
209	bufgap_t	 bg;
210	uint32_t	 len;
211	int64_t		 off;
212	uint8_t		*userid;
213	char		 hostname[256];
214	char		 owner[256];
215	char		*space;
216	char	 	*buf;
217	char	 	*bin;
218	int		 ok;
219	int		 cc;
220
221	(void) memset(&bg, 0x0, sizeof(bg));
222	if (!bufgap_open(&bg, f)) {
223		(void) fprintf(stderr, "pgp_ssh2pubkey: can't open '%s'\n", f);
224		return 0;
225	}
226	(void)stat(f, &st);
227	if ((buf = calloc(1, (size_t)st.st_size)) == NULL) {
228		(void) fprintf(stderr, "can't calloc %zu bytes for '%s'\n", (size_t)st.st_size, f);
229		bufgap_close(&bg);
230		return 0;
231	}
232	if ((bin = calloc(1, (size_t)st.st_size)) == NULL) {
233		(void) fprintf(stderr, "can't calloc %zu bytes for '%s'\n", (size_t)st.st_size, f);
234		(void) free(buf);
235		bufgap_close(&bg);
236		return 0;
237	}
238
239	/* move past ascii type of key */
240	while (bufgap_peek(&bg, 0) != ' ') {
241		bufgap_seek(&bg, 1, BGFromHere, BGByte);
242	}
243	bufgap_seek(&bg, 1, BGFromHere, BGByte);
244	off = bufgap_tell(&bg, BGFromBOF, BGByte);
245
246	if (bufgap_size(&bg, BGByte) - off < 10) {
247		(void) fprintf(stderr, "bad key file '%s'\n", f);
248		(void) free(buf);
249		bufgap_close(&bg);
250		return 0;
251	}
252
253	/* convert from base64 to binary */
254	cc = bufgap_getbin(&bg, buf, (size_t)bg.bcc);
255	if ((space = strchr(buf, ' ')) != NULL) {
256		cc = (int)(space - buf);
257	}
258	if (pgp_get_debug_level(__FILE__)) {
259		hexdump(stderr, NULL, (const uint8_t *)(const void *)buf, (size_t)cc);
260	}
261	cc = frombase64(bin, buf, (size_t)cc, 0);
262	if (pgp_get_debug_level(__FILE__)) {
263		hexdump(stderr, "decoded base64:", (const uint8_t *)(const void *)bin, (size_t)cc);
264	}
265	bufgap_delete(&bg, (uint64_t)bufgap_tell(&bg, BGFromEOF, BGByte));
266	bufgap_insert(&bg, bin, cc);
267	bufgap_seek(&bg, off, BGFromBOF, BGByte);
268
269	/* get the type of key */
270	(void) bufgap_getbin(&bg, &len, sizeof(len));
271	len = ntohl(len);
272	(void) bufgap_seek(&bg, sizeof(len), BGFromHere, BGByte);
273	(void) bufgap_getbin(&bg, buf, len);
274	(void) bufgap_seek(&bg, len, BGFromHere, BGByte);
275
276	(void) memset(key, 0x0, sizeof(*key));
277	pubkey = &key->key.seckey.pubkey;
278	pubkey->version = PGP_V4;
279	pubkey->birthtime = st.st_mtime;
280	/* get key type */
281	ok = 1;
282	switch (pubkey->alg = findstr(pkatypes, buf)) {
283	case PGP_PKA_RSA:
284		/* get the 'e' param of the key */
285		pubkey->key.rsa.e = getbignum(&bg, buf, "RSA E");
286		/* get the 'n' param of the key */
287		pubkey->key.rsa.n = getbignum(&bg, buf, "RSA N");
288		break;
289	case PGP_PKA_DSA:
290		/* get the 'p' param of the key */
291		pubkey->key.dsa.p = getbignum(&bg, buf, "DSA P");
292		/* get the 'q' param of the key */
293		pubkey->key.dsa.q = getbignum(&bg, buf, "DSA Q");
294		/* get the 'g' param of the key */
295		pubkey->key.dsa.g = getbignum(&bg, buf, "DSA G");
296		/* get the 'y' param of the key */
297		pubkey->key.dsa.y = getbignum(&bg, buf, "DSA Y");
298		break;
299	default:
300		(void) fprintf(stderr, "Unrecognised pubkey type %d for '%s'\n",
301				pubkey->alg, f);
302		ok = 0;
303		break;
304	}
305
306	/* check for stragglers */
307	if (ok && bufgap_tell(&bg, BGFromEOF, BGByte) > 0) {
308		printf("%"PRIi64" bytes left\n", bufgap_tell(&bg, BGFromEOF, BGByte));
309		printf("[%s]\n", bufgap_getstr(&bg));
310		ok = 0;
311	}
312	if (ok) {
313		(void) memset(&userid, 0x0, sizeof(userid));
314		(void) gethostname(hostname, sizeof(hostname));
315		if (strlen(space + 1) - 1 == 0) {
316			(void) snprintf(owner, sizeof(owner), "<root@%s>",
317					hostname);
318		} else {
319			(void) snprintf(owner, sizeof(owner), "<%.*s>",
320				(int)strlen(space + 1) - 1,
321				space + 1);
322		}
323		(void) pgp_asprintf((char **)(void *)&userid,
324						"%s (%s) %s",
325						hostname,
326						f,
327						owner);
328		pgp_keyid(key->sigid, sizeof(key->sigid), pubkey, hashtype);
329		pgp_add_userid(key, userid);
330		pgp_fingerprint(&key->sigfingerprint, pubkey, hashtype);
331		free(userid);
332		if (pgp_get_debug_level(__FILE__)) {
333			/*pgp_print_keydata(io, keyring, key, "pub", pubkey, 0);*/
334			__PGP_USED(io); /* XXX */
335		}
336	}
337	(void) free(bin);
338	(void) free(buf);
339	bufgap_close(&bg);
340	return ok;
341}
342
343/* convert an ssh (host) seckey to a pgp seckey */
344int
345pgp_ssh2seckey(pgp_io_t *io, const char *f, pgp_key_t *key, pgp_pubkey_t *pubkey, pgp_hash_alg_t hashtype)
346{
347	pgp_crypt_t	crypted;
348	pgp_hash_t	hash;
349	unsigned	done = 0;
350	unsigned	i = 0;
351	uint8_t		sesskey[CAST_KEY_LENGTH];
352	uint8_t		hashed[PGP_SHA1_HASH_SIZE];
353	BIGNUM		*tmp;
354
355	__PGP_USED(io);
356	/* XXX - check for rsa/dsa */
357	if (!openssl_read_pem_seckey(f, key, "ssh-rsa", 0)) {
358		return 0;
359	}
360	if (pgp_get_debug_level(__FILE__)) {
361		/*pgp_print_keydata(io, key, "sec", &key->key.seckey.pubkey, 0);*/
362		/* XXX */
363	}
364	/* let's add some sane defaults */
365	(void) memcpy(&key->key.seckey.pubkey, pubkey, sizeof(*pubkey));
366	key->key.seckey.s2k_usage = PGP_S2KU_ENCRYPTED_AND_HASHED;
367	key->key.seckey.alg = PGP_SA_CAST5;
368	key->key.seckey.s2k_specifier = PGP_S2KS_SALTED;
369	key->key.seckey.hash_alg = PGP_HASH_SHA1;
370	if (key->key.seckey.pubkey.alg == PGP_PKA_RSA) {
371		/* openssh and openssl have p and q swapped */
372		tmp = key->key.seckey.key.rsa.p;
373		key->key.seckey.key.rsa.p = key->key.seckey.key.rsa.q;
374		key->key.seckey.key.rsa.q = tmp;
375	}
376	for (done = 0, i = 0; done < CAST_KEY_LENGTH; i++) {
377		unsigned 	j;
378		uint8_t		zero = 0;
379		int             needed;
380		int             size;
381
382		needed = CAST_KEY_LENGTH - done;
383		size = MIN(needed, PGP_SHA1_HASH_SIZE);
384
385		pgp_hash_any(&hash, key->key.seckey.hash_alg);
386		if (!hash.init(&hash)) {
387			(void) fprintf(stderr, "write_seckey_body: bad alloc\n");
388			return 0;
389		}
390
391		/* preload if iterating  */
392		for (j = 0; j < i; j++) {
393			/*
394			 * Coverity shows a DEADCODE error on this
395			 * line. This is expected since the hardcoded
396			 * use of SHA1 and CAST5 means that it will
397			 * not used. This will change however when
398			 * other algorithms are supported.
399			 */
400			hash.add(&hash, &zero, 1);
401		}
402
403		if (key->key.seckey.s2k_specifier == PGP_S2KS_SALTED) {
404			hash.add(&hash, key->key.seckey.salt, PGP_SALT_SIZE);
405		}
406		hash.finish(&hash, hashed);
407
408		/*
409		 * if more in hash than is needed by session key, use
410		 * the leftmost octets
411		 */
412		(void) memcpy(&sesskey[i * PGP_SHA1_HASH_SIZE],
413				hashed, (unsigned)size);
414		done += (unsigned)size;
415		if (done > CAST_KEY_LENGTH) {
416			(void) fprintf(stderr,
417				"write_seckey_body: short add\n");
418			return 0;
419		}
420	}
421	pgp_crypt_any(&crypted, key->key.seckey.alg);
422	crypted.set_iv(&crypted, key->key.seckey.iv);
423	crypted.set_crypt_key(&crypted, sesskey);
424	pgp_encrypt_init(&crypted);
425	key->key.seckey.pubkey.alg = PGP_PKA_RSA;
426	pgp_fingerprint(&key->sigfingerprint, pubkey, hashtype);
427	pgp_keyid(key->sigid, sizeof(key->sigid), pubkey, hashtype);
428	return 1;
429}
430
431/* read a key from the ssh file, and add it to a keyring */
432int
433pgp_ssh2_readkeys(pgp_io_t *io, pgp_keyring_t *pubring,
434		pgp_keyring_t *secring, const char *pubfile,
435		const char *secfile, unsigned hashtype)
436{
437	pgp_key_t		*pubkey;
438	pgp_key_t		*seckey;
439	pgp_key_t		 key;
440
441	pubkey = NULL;
442	(void) memset(&key, 0x0, sizeof(key));
443	if (pubfile) {
444		if (pgp_get_debug_level(__FILE__)) {
445			(void) fprintf(io->errs, "pgp_ssh2_readkeys: pubfile '%s'\n", pubfile);
446		}
447		if (!pgp_ssh2pubkey(io, pubfile, &key, (pgp_hash_alg_t)hashtype)) {
448			(void) fprintf(io->errs, "pgp_ssh2_readkeys: can't read pubkeys '%s'\n", pubfile);
449			return 0;
450		}
451		EXPAND_ARRAY(pubring, key);
452		pubkey = &pubring->keys[pubring->keyc++];
453		(void) memcpy(pubkey, &key, sizeof(key));
454		pubkey->type = PGP_PTAG_CT_PUBLIC_KEY;
455	}
456	if (secfile) {
457		if (pgp_get_debug_level(__FILE__)) {
458			(void) fprintf(io->errs, "pgp_ssh2_readkeys: secfile '%s'\n", secfile);
459		}
460		if (pubkey == NULL) {
461			pubkey = &pubring->keys[0];
462		}
463		if (!pgp_ssh2seckey(io, secfile, &key, &pubkey->key.pubkey, (pgp_hash_alg_t)hashtype)) {
464			(void) fprintf(io->errs, "pgp_ssh2_readkeys: can't read seckeys '%s'\n", secfile);
465			return 0;
466		}
467		EXPAND_ARRAY(secring, key);
468		seckey = &secring->keys[secring->keyc++];
469		(void) memcpy(seckey, &key, sizeof(key));
470		seckey->type = PGP_PTAG_CT_SECRET_KEY;
471	}
472	return 1;
473}
474