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