xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/ssh2pgp.c (revision 09afef20633f5fe63d92dfe43ee3a9380dc06883)
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 <inttypes.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
47 
48 #ifdef HAVE_LIMITS_H
49 #include <limits.h>
50 #endif
51 
52 #ifdef HAVE_OPENSSL_CAST_H
53 #include <openssl/cast.h>
54 #endif
55 
56 #include <openssl/pem.h>
57 
58 #include "bufgap.h"
59 #include "fastctype.h"
60 
61 #include "packet-parse.h"
62 #include "netpgpdefs.h"
63 #include "crypto.h"
64 #include "netpgpdigest.h"
65 #include "ops-ssh.h"
66 
67 /* structure for earching for constant strings */
68 typedef struct str_t {
69 	const char	*s;		/* string */
70 	size_t		 len;		/* its length */
71 	int		 type;		/* return type */
72 } str_t;
73 
74 #ifndef USE_ARG
75 #define USE_ARG(x)	/*LINTED*/(void)&x
76 #endif
77 
78 static const uint8_t	base64s[] =
79 /* 000 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
80 /* 016 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
81 /* 032 */       "\0\0\0\0\0\0\0\0\0\0\0?\0\0\0@"
82 /* 048 */       "56789:;<=>\0\0\0\0\0\0"
83 /* 064 */       "\0\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17"
84 /* 080 */       "\20\21\22\23\24\25\26\27\30\31\32\0\0\0\0\0"
85 /* 096 */       "\0\33\34\35\36\37 !\"#$%&'()"
86 /* 112 */       "*+,-./01234\0\0\0\0\0"
87 /* 128 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
88 /* 144 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
89 /* 160 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
90 /* 176 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
91 /* 192 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
92 /* 208 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
93 /* 224 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
94 /* 240 */       "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
95 
96 
97 /* short function to decode from base64 */
98 /* inspired by an ancient copy of b64.c, then rewritten, the bugs are all mine */
99 static int
100 frombase64(char *dst, const char *src, size_t size, int flag)
101 {
102 	uint8_t	out[3];
103 	uint8_t	in[4];
104 	uint8_t	b;
105 	size_t	srcc;
106 	int	dstc;
107 	int	gotc;
108 	int	i;
109 
110 	USE_ARG(flag);
111 	for (dstc = 0, srcc = 0 ; srcc < size; ) {
112 		for (gotc = 0, i = 0; i < 4 && srcc < size; i++) {
113 			for (b = 0x0; srcc < size && b == 0x0 ; ) {
114 				b = base64s[(unsigned)src[srcc++]];
115 			}
116 			if (srcc < size) {
117 				gotc += 1;
118 				if (b) {
119 					in[i] = (uint8_t)(b - 1);
120 				}
121 			} else {
122 				in[i] = 0x0;
123 			}
124 		}
125 		if (gotc) {
126 			out[0] = (uint8_t) (in[0] << 2 | in[1] >> 4);
127 			out[1] = (uint8_t) (in[1] << 4 | in[2] >> 2);
128 			out[2] = (uint8_t) (((in[2] << 6) & 0xc0) | in[3]);
129 			for (i = 0; i < gotc - 1; i++) {
130 				*dst++ = out[i];
131 			}
132 			dstc += gotc - 1;
133 		}
134 	}
135 	return dstc;
136 }
137 
138 #define LINELEN	16
139 
140 /* show hexadecimal/ascii dump */
141 static void
142 show(const char *header, char *in, int len)
143 {
144 	char	line[LINELEN + 1];
145 	int	i;
146 
147 	printf("%s%s", (header) ? header : "", (header) ? "\n" : "");
148 	printf("[%d chars]\n", len);
149 	for (i = 0 ; i < len ; i++) {
150 		if (i % LINELEN == 0) {
151 			printf("%.5d | ", i);
152 		}
153 		printf("%.02x ", (uint8_t)in[i]);
154 		line[i % LINELEN] = (isprint(in[i])) ? in[i] : '.';
155 		if (i % LINELEN == LINELEN - 1) {
156 			line[LINELEN] = 0x0;
157 			printf(" | %s\n", line);
158 		}
159 	}
160 	for ( ; i % LINELEN != 0 ; i++) {
161 		printf("   ");
162 		line[i % LINELEN] = ' ';
163 	}
164 	line[LINELEN] = 0x0;
165 	printf(" | %s\n", line);
166 }
167 
168 /* get a bignum from the buffer gap */
169 static BIGNUM *
170 getbignum(bufgap_t *bg, char *buf, const char *header)
171 {
172 	uint32_t	 len;
173 	BIGNUM		*bignum;
174 
175 	(void) bufgap_getbin(bg, &len, sizeof(len));
176 	len = ntohl(len);
177 	(void) bufgap_seek(bg, sizeof(len), BGFromHere, BGByte);
178 	(void) bufgap_getbin(bg, buf, len);
179 	bignum = BN_bin2bn((const unsigned char *)buf, len, NULL);
180 	if (__ops_get_debug_level(__FILE__)) {
181 		show(header, buf, len);
182 	}
183 	(void) bufgap_seek(bg, len, BGFromHere, BGByte);
184 	return bignum;
185 }
186 
187 static str_t	pkatypes[] = {
188 	{	"ssh-rsa",	7,	OPS_PKA_RSA	},
189 	{	"ssh-dsa",	7,	OPS_PKA_DSA	},
190 	{	NULL,		0,	0		}
191 };
192 
193 /* look for a string in the given array */
194 static int
195 findstr(str_t *array, const char *name)
196 {
197 	str_t	*sp;
198 
199 	for (sp = array ; sp->s ; sp++) {
200 		if (strncmp(name, sp->s, sp->len) == 0) {
201 			return sp->type;
202 		}
203 	}
204 	return -1;
205 }
206 
207 /* convert an ssh (host) pubkey to a pgp pubkey */
208 int
209 __ops_ssh2pubkey(__ops_io_t *io, const char *f, __ops_key_t *key)
210 {
211 	__ops_userid_t	 userid;
212 	__ops_pubkey_t	*pubkey;
213 	struct stat	 st;
214 	bufgap_t	 bg;
215 	uint32_t	 len;
216 	int64_t		 off;
217 	char		 hostname[256];
218 	char		*space;
219 	char	 	*buf;
220 	char	 	*bin;
221 	int		 ok;
222 	int		 cc;
223 
224 	(void) memset(&bg, 0x0, sizeof(bg));
225 	if (!bufgap_open(&bg, f)) {
226 		(void) fprintf(stderr, "can't open '%s'\n", f);
227 		return 0;
228 	}
229 	(void)stat(f, &st);
230 	if ((buf = calloc(1, (size_t)st.st_size)) == NULL) {
231 		(void) fprintf(stderr, "can't calloc %zu bytes for '%s'\n", (size_t)st.st_size, f);
232 		bufgap_close(&bg);
233 		return 0;
234 	}
235 	if ((bin = calloc(1, (size_t)st.st_size)) == NULL) {
236 		(void) fprintf(stderr, "can't calloc %zu bytes for '%s'\n", (size_t)st.st_size, f);
237 		(void) free(buf);
238 		bufgap_close(&bg);
239 		return 0;
240 	}
241 
242 	/* move past ascii type of key */
243 	while (bufgap_peek(&bg, 0) != ' ') {
244 		bufgap_seek(&bg, 1, BGFromHere, BGByte);
245 	}
246 	bufgap_seek(&bg, 1, BGFromHere, BGByte);
247 	off = bufgap_tell(&bg, BGFromBOF, BGByte);
248 
249 	/* convert from base64 to binary */
250 	cc = bufgap_getbin(&bg, buf, st.st_size);
251 	if ((space = strchr(buf, ' ')) != NULL) {
252 		cc = (int)(space - buf);
253 	}
254 	if (__ops_get_debug_level(__FILE__)) {
255 		show(NULL, buf, cc);
256 	}
257 	cc = frombase64(bin, buf, (size_t)cc, 0);
258 	if (__ops_get_debug_level(__FILE__)) {
259 		show("decoded base64:", bin, cc);
260 	}
261 	bufgap_delete(&bg, bufgap_tell(&bg, BGFromEOF, BGByte));
262 	bufgap_insert(&bg, bin, cc);
263 	bufgap_seek(&bg, off, BGFromBOF, BGByte);
264 
265 	/* get the type of key */
266 	(void) bufgap_getbin(&bg, &len, sizeof(len));
267 	len = ntohl(len);
268 	(void) bufgap_seek(&bg, sizeof(len), BGFromHere, BGByte);
269 	(void) bufgap_getbin(&bg, buf, len);
270 	(void) bufgap_seek(&bg, len, BGFromHere, BGByte);
271 
272 	(void) memset(key, 0x0, sizeof(*key));
273 	pubkey = &key->key.seckey.pubkey;
274 	pubkey->version = OPS_V4;
275 	pubkey->birthtime = st.st_mtime;
276 	/* get key type */
277 	ok = 1;
278 	switch (pubkey->alg = findstr(pkatypes, buf)) {
279 	case OPS_PKA_RSA:
280 		/* get the 'e' param of the key */
281 		pubkey->key.rsa.e = getbignum(&bg, buf, "RSA E");
282 		/* get the 'n' param of the key */
283 		pubkey->key.rsa.n = getbignum(&bg, buf, "RSA N");
284 		break;
285 	case OPS_PKA_DSA:
286 		/* get the 'p' param of the key */
287 		pubkey->key.dsa.p = getbignum(&bg, buf, "DSA P");
288 		/* get the 'q' param of the key */
289 		pubkey->key.dsa.q = getbignum(&bg, buf, "DSA Q");
290 		/* get the 'g' param of the key */
291 		pubkey->key.dsa.g = getbignum(&bg, buf, "DSA G");
292 		/* get the 'y' param of the key */
293 		pubkey->key.dsa.y = getbignum(&bg, buf, "DSA Y");
294 		break;
295 	default:
296 		(void) fprintf(stderr, "Unrecognised pubkey type %d for '%s'\n",
297 				pubkey->alg, f);
298 		ok = 0;
299 		break;
300 	}
301 
302 	/* check for stragglers */
303 	if (ok && bufgap_tell(&bg, BGFromEOF, BGByte) > 0) {
304 		printf("%"PRIi64" bytes left\n", bufgap_tell(&bg, BGFromEOF, BGByte));
305 		printf("[%s]\n", bufgap_getstr(&bg));
306 		ok = 0;
307 	}
308 	if (ok) {
309 		(void) memset(&userid, 0x0, sizeof(userid));
310 		(void) gethostname(hostname, sizeof(hostname));
311 		(void) asprintf((char **)(void *)&userid.userid,
312 				"%s (%s) <%.*s>",
313 				hostname,
314 				f,
315 				(int)strlen(space + 1) - 1,
316 				space + 1);
317 		__ops_keyid(key->key_id, sizeof(key->key_id), pubkey);
318 		__ops_add_userid(key, &userid);
319 		__ops_fingerprint(&key->fingerprint, pubkey);
320 		free(userid.userid);
321 		if (__ops_get_debug_level(__FILE__)) {
322 			__ops_print_keydata(io, key, "pub", pubkey);
323 		}
324 	}
325 	(void) free(bin);
326 	(void) free(buf);
327 	bufgap_close(&bg);
328 	return ok;
329 }
330 
331 /* convert an ssh (host) seckey to a pgp seckey */
332 int
333 __ops_ssh2seckey(__ops_io_t *io, const char *f, __ops_key_t *key, __ops_pubkey_t *pubkey)
334 {
335 	unsigned char	sesskey[CAST_KEY_LENGTH];
336 	unsigned char   hashed[OPS_SHA1_HASH_SIZE];
337 	__ops_crypt_t	crypted;
338 	__ops_hash_t	hash;
339 	unsigned int    done = 0;
340 	unsigned int    i = 0;
341 
342 	/* XXX - check for rsa/dsa */
343 	if (!openssl_read_pem_seckey(f, key, "ssh-rsa")) {
344 		return 0;
345 	}
346 	if (__ops_get_debug_level(__FILE__)) {
347 		__ops_print_keydata(io, key, "sec", &key->key.seckey.pubkey);
348 	}
349 	/* let's add some sane defaults */
350 	(void) memcpy(&key->key.seckey.pubkey, pubkey, sizeof(*pubkey));
351 	key->key.seckey.s2k_usage = OPS_S2KU_ENCRYPTED_AND_HASHED;
352 	key->key.seckey.alg = OPS_SA_CAST5;
353 	key->key.seckey.s2k_specifier = OPS_S2KS_SALTED;
354 	key->key.seckey.hash_alg = OPS_HASH_SHA1;
355 	for (done = 0, i = 0; done < CAST_KEY_LENGTH; i++) {
356 		unsigned char   zero = 0;
357 		unsigned 	j;
358 		int             needed;
359 		int             size;
360 
361 		needed = CAST_KEY_LENGTH - done;
362 		size = MIN(needed, OPS_SHA1_HASH_SIZE);
363 
364 		__ops_hash_any(&hash, key->key.seckey.hash_alg);
365 		if (!hash.init(&hash)) {
366 			(void) fprintf(stderr, "write_seckey_body: bad alloc\n");
367 			return 0;
368 		}
369 
370 		/* preload if iterating  */
371 		for (j = 0; j < i; j++) {
372 			/*
373 			 * Coverity shows a DEADCODE error on this
374 			 * line. This is expected since the hardcoded
375 			 * use of SHA1 and CAST5 means that it will
376 			 * not used. This will change however when
377 			 * other algorithms are supported.
378 			 */
379 			hash.add(&hash, &zero, 1);
380 		}
381 
382 		if (key->key.seckey.s2k_specifier == OPS_S2KS_SALTED) {
383 			hash.add(&hash, key->key.seckey.salt, OPS_SALT_SIZE);
384 		}
385 		hash.finish(&hash, hashed);
386 
387 		/*
388 		 * if more in hash than is needed by session key, use
389 		 * the leftmost octets
390 		 */
391 		(void) memcpy(&sesskey[i * OPS_SHA1_HASH_SIZE],
392 				hashed, (unsigned)size);
393 		done += (unsigned)size;
394 		if (done > CAST_KEY_LENGTH) {
395 			(void) fprintf(stderr,
396 				"write_seckey_body: short add\n");
397 			return 0;
398 		}
399 	}
400 	__ops_crypt_any(&crypted, key->key.seckey.alg);
401 	crypted.set_iv(&crypted, key->key.seckey.iv);
402 	crypted.set_crypt_key(&crypted, sesskey);
403 	__ops_encrypt_init(&crypted);
404 	key->key.seckey.pubkey.alg = OPS_PKA_RSA;
405 	__ops_fingerprint(&key->fingerprint, pubkey);
406 	__ops_keyid(key->key_id, sizeof(key->key_id), pubkey);
407 	return 1;
408 }
409 
410 /* read a key from the ssh file, and add it to a keyring */
411 int
412 __ops_ssh2_readkeys(__ops_io_t *io, __ops_keyring_t *pubring,
413 		__ops_keyring_t *secring, const char *pubfile,
414 		const char *secfile)
415 {
416 	__ops_key_t		*pubkey;
417 	__ops_key_t		*seckey;
418 	__ops_key_t		 key;
419 
420 	pubkey = NULL;
421 	(void) memset(&key, 0x0, sizeof(key));
422 	if (pubfile) {
423 		if (__ops_get_debug_level(__FILE__)) {
424 			(void) fprintf(io->errs, "__ops_ssh2_readkeys: pubfile '%s'\n", pubfile);
425 		}
426 		__ops_ssh2pubkey(io, pubfile, &key);
427 		EXPAND_ARRAY(pubring, key);
428 		pubkey = &pubring->keys[pubring->keyc++];
429 		(void) memcpy(pubkey, &key, sizeof(key));
430 		pubkey->type = OPS_PTAG_CT_PUBLIC_KEY;
431 	}
432 	if (secfile) {
433 		if (__ops_get_debug_level(__FILE__)) {
434 			(void) fprintf(io->errs, "__ops_ssh2_readkeys: secfile '%s'\n", secfile);
435 		}
436 		if (pubkey == NULL) {
437 			pubkey = &pubring->keys[0];
438 		}
439 		(void) __ops_ssh2seckey(io, secfile, &key, &pubkey->key.pubkey);
440 		EXPAND_ARRAY(secring, key);
441 		seckey = &secring->keys[secring->keyc++];
442 		(void) memcpy(seckey, &key, sizeof(key));
443 		seckey->type = OPS_PTAG_CT_SECRET_KEY;
444 	}
445 	return 1;
446 }
447