xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/misc.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*-
2  * Copyright (c) 2009,2010 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 /*
30  * Copyright (c) 2005-2008 Nominet UK (www.nic.uk)
31  * All rights reserved.
32  * Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted
33  * their moral rights under the UK Copyright Design and Patents Act 1988 to
34  * be recorded as the authors of this copyright work.
35  *
36  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
37  * use this file except in compliance with the License.
38  *
39  * You may obtain a copy of the License at
40  *     http://www.apache.org/licenses/LICENSE-2.0
41  *
42  * Unless required by applicable law or agreed to in writing, software
43  * distributed under the License is distributed on an "AS IS" BASIS,
44  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45  *
46  * See the License for the specific language governing permissions and
47  * limitations under the License.
48  */
49 
50 /** \file
51  */
52 #include "config.h"
53 
54 #ifdef HAVE_SYS_CDEFS_H
55 #include <sys/cdefs.h>
56 #endif
57 
58 #if defined(__NetBSD__)
59 __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved.");
60 __RCSID("$NetBSD: misc.c,v 1.43 2020/04/18 19:27:48 jhigh Exp $");
61 #endif
62 
63 #include <sys/types.h>
64 #include <sys/stat.h>
65 #include <sys/mman.h>
66 
67 #include <ctype.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 
73 #ifdef HAVE_UNISTD_H
74 #include <unistd.h>
75 #endif
76 
77 #ifdef HAVE_OPENSSL_RAND_H
78 #include <openssl/rand.h>
79 #endif
80 
81 #include "errors.h"
82 #include "packet.h"
83 #include "crypto.h"
84 #include "create.h"
85 #include "packet-parse.h"
86 #include "packet-show.h"
87 #include "signature.h"
88 #include "netpgpsdk.h"
89 #include "netpgpdefs.h"
90 #include "memory.h"
91 #include "readerwriter.h"
92 #include "version.h"
93 #include "netpgpdigest.h"
94 
95 #ifdef WIN32
96 #define vsnprintf _vsnprintf
97 #endif
98 
99 
100 typedef struct {
101 	pgp_keyring_t		*keyring;
102 } accumulate_t;
103 
104 /**
105  * \ingroup Core_Callbacks
106  */
107 static pgp_cb_ret_t
108 accumulate_cb(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
109 {
110 	const pgp_contents_t	*content = &pkt->u;
111 	pgp_keyring_t		*keyring;
112 	accumulate_t		*accumulate;
113 	pgp_key_t		*key;
114 
115 	if (pgp_get_debug_level(__FILE__)) {
116 		(void) fprintf(stderr, "accumulate callback: packet tag %u\n", pkt->tag);
117 	}
118 	accumulate = pgp_callback_arg(cbinfo);
119 	keyring = accumulate->keyring;
120 	key = keyring->keyc > 0 ? &keyring->keys[keyring->keyc - 1] : NULL;
121 	switch (pkt->tag) {
122 	case PGP_PTAG_CT_PUBLIC_KEY:
123 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
124 		pgp_add_to_pubring(keyring, &content->pubkey, pkt->tag);
125 		return PGP_KEEP_MEMORY;
126 	case PGP_PTAG_CT_SECRET_KEY:
127 	case PGP_PTAG_CT_ENCRYPTED_SECRET_KEY:
128 		pgp_add_to_secring(keyring, &content->seckey);
129 		return PGP_KEEP_MEMORY;
130 	case PGP_PTAG_CT_USER_ID:
131 		if (pgp_get_debug_level(__FILE__)) {
132 			(void) fprintf(stderr, "User ID: %s for key %d\n",
133 					content->userid,
134 					keyring->keyc - 1);
135 		}
136 		if (key != NULL) {
137 			pgp_add_userid(key, content->userid);
138 		} else {
139 			PGP_ERROR_1(cbinfo->errors, PGP_E_P_NO_USERID, "%s",
140 			    "No key for userid found");
141 		}
142 		return PGP_KEEP_MEMORY;
143 	case PGP_PARSER_PACKET_END:
144 		if (key != NULL) {
145 			switch (content->packet.tag) {
146 			case PGP_PTAG_CT_RESERVED:
147 				(void) fprintf(stderr, "Invalid packet tag\n");
148 				break;
149 			case PGP_PTAG_CT_PUBLIC_KEY:
150 			case PGP_PTAG_CT_USER_ID:
151 				break;
152 			default:
153 				pgp_add_subpacket(key, &content->packet);
154 				break;
155 			}
156 			return PGP_KEEP_MEMORY;
157 		}
158 		return PGP_RELEASE_MEMORY;
159 	case PGP_PARSER_ERROR:
160 		(void) fprintf(stderr, "Error: %s\n", content->error);
161 		return PGP_FINISHED;
162 	case PGP_PARSER_ERRCODE:
163 		(void) fprintf(stderr, "parse error: %s\n",
164 				pgp_errcode(content->errcode.errcode));
165 		break;
166 	default:
167 		break;
168 	}
169 	/* XXX: we now exclude so many things, we should either drop this or */
170 	/* do something to pass on copies of the stuff we keep */
171 	return pgp_stacked_callback(pkt, cbinfo);
172 }
173 
174 /**
175  * \ingroup Core_Parse
176  *
177  * Parse packets from an input stream until EOF or error.
178  *
179  * Key data found in the parsed data is added to #keyring.
180  *
181  * \param keyring Pointer to an existing keyring
182  * \param parse Options to use when parsing
183 */
184 int
185 pgp_parse_and_accumulate(pgp_keyring_t *keyring, pgp_stream_t *parse)
186 {
187 	accumulate_t	accumulate;
188 	const int	printerrors = 1;
189 	int             ret;
190 
191 	if (parse->readinfo.accumulate) {
192 		(void) fprintf(stderr,
193 			"pgp_parse_and_accumulate: already init\n");
194 		return 0;
195 	}
196 
197 	(void) memset(&accumulate, 0x0, sizeof(accumulate));
198 
199 	accumulate.keyring = keyring;
200 
201 	pgp_callback_push(parse, accumulate_cb, &accumulate);
202 	parse->readinfo.accumulate = 1;
203 	ret = pgp_parse(parse, !printerrors);
204 
205 	return ret;
206 }
207 
208 
209 /** \file
210  * \brief Error Handling
211  */
212 #define ERRNAME(code)	{ code, #code }
213 
214 static pgp_errcode_name_map_t errcode_name_map[] = {
215 	ERRNAME(PGP_E_OK),
216 	ERRNAME(PGP_E_FAIL),
217 	ERRNAME(PGP_E_SYSTEM_ERROR),
218 	ERRNAME(PGP_E_UNIMPLEMENTED),
219 
220 	ERRNAME(PGP_E_R),
221 	ERRNAME(PGP_E_R_READ_FAILED),
222 	ERRNAME(PGP_E_R_EARLY_EOF),
223 	ERRNAME(PGP_E_R_BAD_FORMAT),
224 	ERRNAME(PGP_E_R_UNCONSUMED_DATA),
225 
226 	ERRNAME(PGP_E_W),
227 	ERRNAME(PGP_E_W_WRITE_FAILED),
228 	ERRNAME(PGP_E_W_WRITE_TOO_SHORT),
229 
230 	ERRNAME(PGP_E_P),
231 	ERRNAME(PGP_E_P_NOT_ENOUGH_DATA),
232 	ERRNAME(PGP_E_P_UNKNOWN_TAG),
233 	ERRNAME(PGP_E_P_PACKET_CONSUMED),
234 	ERRNAME(PGP_E_P_MPI_FORMAT_ERROR),
235 
236 	ERRNAME(PGP_E_C),
237 
238 	ERRNAME(PGP_E_V),
239 	ERRNAME(PGP_E_V_BAD_SIGNATURE),
240 	ERRNAME(PGP_E_V_NO_SIGNATURE),
241 	ERRNAME(PGP_E_V_UNKNOWN_SIGNER),
242 
243 	ERRNAME(PGP_E_ALG),
244 	ERRNAME(PGP_E_ALG_UNSUPPORTED_SYMMETRIC_ALG),
245 	ERRNAME(PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG),
246 	ERRNAME(PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG),
247 	ERRNAME(PGP_E_ALG_UNSUPPORTED_HASH_ALG),
248 
249 	ERRNAME(PGP_E_PROTO),
250 	ERRNAME(PGP_E_PROTO_BAD_SYMMETRIC_DECRYPT),
251 	ERRNAME(PGP_E_PROTO_UNKNOWN_SS),
252 	ERRNAME(PGP_E_PROTO_CRITICAL_SS_IGNORED),
253 	ERRNAME(PGP_E_PROTO_BAD_PUBLIC_KEY_VRSN),
254 	ERRNAME(PGP_E_PROTO_BAD_SIGNATURE_VRSN),
255 	ERRNAME(PGP_E_PROTO_BAD_ONE_PASS_SIG_VRSN),
256 	ERRNAME(PGP_E_PROTO_BAD_PKSK_VRSN),
257 	ERRNAME(PGP_E_PROTO_DECRYPTED_MSG_WRONG_LEN),
258 	ERRNAME(PGP_E_PROTO_BAD_SK_CHECKSUM),
259 
260 	{0x00, NULL},		/* this is the end-of-array marker */
261 };
262 
263 /**
264  * \ingroup Core_Errors
265  * \brief returns error code name
266  * \param errcode
267  * \return error code name or "Unknown"
268  */
269 const char     *
270 pgp_errcode(const pgp_errcode_t errcode)
271 {
272 	return (pgp_str_from_map((int) errcode,
273 			(pgp_map_t *) errcode_name_map));
274 }
275 
276 /* generic grab new storage function */
277 void *
278 pgp_new(size_t size)
279 {
280 	void	*vp;
281 
282 	if ((vp = calloc(1, size)) == NULL) {
283 		(void) fprintf(stderr,
284 			"allocation failure for %" PRIsize "u bytes", size);
285 	}
286 	return vp;
287 }
288 
289 /**
290  * \ingroup Core_Errors
291  * \brief Pushes the given error on the given errorstack
292  * \param errstack Error stack to use
293  * \param errcode Code of error to push
294  * \param sys_errno System errno (used if errcode=PGP_E_SYSTEM_ERROR)
295  * \param file Source filename where error occurred
296  * \param line Line in source file where error occurred
297  * \param fmt Comment
298  *
299  */
300 
301 void
302 pgp_push_error(pgp_error_t **errstack, pgp_errcode_t errcode,
303 		int sys_errno, const char *file, int line, const char *fmt,...)
304 {
305 	/* first get the varargs and generate the comment */
306 	pgp_error_t  *err;
307 	unsigned	maxbuf = 128;
308 	va_list		args;
309 	char           *comment;
310 
311 	if ((comment = calloc(1, maxbuf + 1)) == NULL) {
312 		(void) fprintf(stderr, "calloc comment failure\n");
313 		return;
314 	}
315 
316 	va_start(args, fmt);
317 	vsnprintf(comment, maxbuf + 1, fmt, args);
318 	va_end(args);
319 
320 	/* alloc a new error and add it to the top of the stack */
321 
322 	if ((err = calloc(1, sizeof(*err))) == NULL) {
323 		(void) fprintf(stderr, "calloc comment failure\n");
324 		return;
325 	}
326 
327 	err->next = *errstack;
328 	*errstack = err;
329 
330 	/* fill in the details */
331 	err->errcode = errcode;
332 	err->sys_errno = sys_errno;
333 	err->file = file;
334 	err->line = line;
335 
336 	err->comment = comment;
337 }
338 
339 /**
340 \ingroup Core_Errors
341 \brief print this error
342 \param err Error to print
343 */
344 void
345 pgp_print_error(pgp_error_t *err)
346 {
347 	printf("%s:%d: ", err->file, err->line);
348 	if (err->errcode == PGP_E_SYSTEM_ERROR) {
349 		printf("system error %d returned from %s()\n", err->sys_errno,
350 		       err->comment);
351 	} else {
352 		printf("%s, %s\n", pgp_errcode(err->errcode), err->comment);
353 	}
354 }
355 
356 /**
357 \ingroup Core_Errors
358 \brief Print all errors on stack
359 \param errstack Error stack to print
360 */
361 void
362 pgp_print_errors(pgp_error_t *errstack)
363 {
364 	pgp_error_t    *err;
365 
366 	for (err = errstack; err != NULL; err = err->next) {
367 		pgp_print_error(err);
368 	}
369 }
370 
371 /**
372 \ingroup Core_Errors
373 \brief Return 1 if given error is present anywhere on stack
374 \param errstack Error stack to check
375 \param errcode Error code to look for
376 \return 1 if found; else 0
377 */
378 int
379 pgp_has_error(pgp_error_t *errstack, pgp_errcode_t errcode)
380 {
381 	pgp_error_t    *err;
382 
383 	for (err = errstack; err != NULL; err = err->next) {
384 		if (err->errcode == errcode) {
385 			return 1;
386 		}
387 	}
388 	return 0;
389 }
390 
391 /**
392 \ingroup Core_Errors
393 \brief Frees all errors on stack
394 \param errstack Error stack to free
395 */
396 void
397 pgp_free_errors(pgp_error_t *errstack)
398 {
399 	pgp_error_t    *next;
400 
401 	while (errstack != NULL) {
402 		next = errstack->next;
403 		free(errstack->comment);
404 		free(errstack);
405 		errstack = next;
406 	}
407 }
408 
409 /* hash a 32-bit integer */
410 static int
411 hash_uint32(pgp_hash_t *hash, uint32_t n)
412 {
413 	uint8_t	ibuf[4];
414 
415 	ibuf[0] = (uint8_t)(n >> 24) & 0xff;
416 	ibuf[1] = (uint8_t)(n >> 16) & 0xff;
417 	ibuf[2] = (uint8_t)(n >> 8) & 0xff;
418 	ibuf[3] = (uint8_t)n & 0xff;
419 	(*hash->add)(hash, (const uint8_t *)(void *)ibuf, (unsigned)sizeof(ibuf));
420 	return sizeof(ibuf);
421 }
422 
423 /* hash a string - first length, then string itself */
424 static int
425 hash_string(pgp_hash_t *hash, const uint8_t *buf, uint32_t len)
426 {
427 	if (pgp_get_debug_level(__FILE__)) {
428 		hexdump(stderr, "hash_string", buf, len);
429 	}
430 	hash_uint32(hash, len);
431 	(*hash->add)(hash, buf, len);
432 	return (int)(sizeof(len) + len);
433 }
434 
435 /* hash a bignum, possibly padded - first length, then string itself */
436 static int
437 hash_bignum(pgp_hash_t *hash, BIGNUM *bignum)
438 {
439 	uint8_t	*bn;
440 	size_t	 len;
441 	int	 padbyte;
442 
443 	if (BN_is_zero(bignum)) {
444 		hash_uint32(hash, 0);
445 		return sizeof(len);
446 	}
447 	if ((len = (size_t) BN_num_bytes(bignum)) < 1) {
448 		(void) fprintf(stderr, "hash_bignum: bad size\n");
449 		return 0;
450 	}
451 	if ((bn = calloc(1, len)) == NULL) {
452 		(void) fprintf(stderr, "hash_bignum: bad bn alloc\n");
453 		return 0;
454 	}
455 	BN_bn2bin(bignum, bn + 1);
456 	bn[0] = 0x0;
457 	padbyte = (bn[1] & 0x80) ? 1 : 0;
458 	hash_string(hash, bn + 1 - padbyte, (unsigned)(len + padbyte));
459 	free(bn);
460 	return (int)(sizeof(len) + len + padbyte);
461 }
462 
463 /** \file
464  */
465 
466 /**
467  * \ingroup Core_Keys
468  * \brief Calculate a public key fingerprint.
469  * \param fp Where to put the calculated fingerprint
470  * \param key The key for which the fingerprint is calculated
471  */
472 int
473 pgp_fingerprint(pgp_fingerprint_t *fp, const pgp_pubkey_t *key, pgp_hash_alg_t hashtype)
474 {
475 	pgp_memory_t	*mem;
476 	pgp_hash_t	 hash;
477 	const char	*type;
478 	uint32_t	 len;
479 
480 	mem = pgp_memory_new();
481 	if (key->version == 2 || key->version == 3) {
482 		if (key->alg != PGP_PKA_RSA &&
483 		    key->alg != PGP_PKA_RSA_ENCRYPT_ONLY &&
484 		    key->alg != PGP_PKA_RSA_SIGN_ONLY) {
485 			(void) fprintf(stderr,
486 				"pgp_fingerprint: bad algorithm\n");
487 			return 0;
488 		}
489 		pgp_hash_md5(&hash);
490 		if (!hash.init(&hash)) {
491 			(void) fprintf(stderr,
492 				"pgp_fingerprint: bad md5 alloc\n");
493 			return 0;
494 		}
495 		hash_bignum(&hash, key->key.rsa.n);
496 		hash_bignum(&hash, key->key.rsa.e);
497 		fp->length = hash.finish(&hash, fp->fingerprint);
498 		if (pgp_get_debug_level(__FILE__)) {
499 			hexdump(stderr, "v2/v3 fingerprint", fp->fingerprint, fp->length);
500 		}
501 	} else if (hashtype == PGP_HASH_MD5) {
502 		pgp_hash_md5(&hash);
503 		if (!hash.init(&hash)) {
504 			(void) fprintf(stderr,
505 				"pgp_fingerprint: bad md5 alloc\n");
506 			return 0;
507 		}
508 		type = (key->alg == PGP_PKA_RSA) ? "ssh-rsa" : "ssh-dss";
509 		hash_string(&hash, (const uint8_t *)(const void *)type, (unsigned)strlen(type));
510 		switch(key->alg) {
511 		case PGP_PKA_RSA:
512 			hash_bignum(&hash, key->key.rsa.e);
513 			hash_bignum(&hash, key->key.rsa.n);
514 			break;
515 		case PGP_PKA_DSA:
516 			hash_bignum(&hash, key->key.dsa.p);
517 			hash_bignum(&hash, key->key.dsa.q);
518 			hash_bignum(&hash, key->key.dsa.g);
519 			hash_bignum(&hash, key->key.dsa.y);
520 			break;
521 		default:
522 			break;
523 		}
524 		fp->length = hash.finish(&hash, fp->fingerprint);
525 		if (pgp_get_debug_level(__FILE__)) {
526 			hexdump(stderr, "md5 fingerprint", fp->fingerprint, fp->length);
527 		}
528 	} else {
529 		pgp_build_pubkey(mem, key, 0);
530 		pgp_hash_sha1(&hash);
531 		if (!hash.init(&hash)) {
532 			(void) fprintf(stderr,
533 				"pgp_fingerprint: bad sha1 alloc\n");
534 			return 0;
535 		}
536 		len = (unsigned)pgp_mem_len(mem);
537 		pgp_hash_add_int(&hash, 0x99, 1);
538 		pgp_hash_add_int(&hash, len, 2);
539 		hash.add(&hash, pgp_mem_data(mem), len);
540 		fp->length = hash.finish(&hash, fp->fingerprint);
541 		pgp_memory_free(mem);
542 		if (pgp_get_debug_level(__FILE__)) {
543 			hexdump(stderr, "sha1 fingerprint", fp->fingerprint, fp->length);
544 		}
545 	}
546 	return 1;
547 }
548 
549 /**
550  * \ingroup Core_Keys
551  * \brief Calculate the Key ID from the public key.
552  * \param keyid Space for the calculated ID to be stored
553  * \param key The key for which the ID is calculated
554  */
555 
556 int
557 pgp_keyid(uint8_t *keyid, const size_t idlen, const pgp_pubkey_t *key, pgp_hash_alg_t hashtype)
558 {
559 	pgp_fingerprint_t finger;
560 
561 	if (key->version == 2 || key->version == 3) {
562 		unsigned	n;
563 		uint8_t		bn[NETPGP_BUFSIZ];
564 
565 		n = (unsigned) BN_num_bytes(key->key.rsa.n);
566 		if (n > sizeof(bn)) {
567 			(void) fprintf(stderr, "pgp_keyid: bad num bytes\n");
568 			return 0;
569 		}
570 		if (key->alg != PGP_PKA_RSA &&
571 		    key->alg != PGP_PKA_RSA_ENCRYPT_ONLY &&
572 		    key->alg != PGP_PKA_RSA_SIGN_ONLY) {
573 			(void) fprintf(stderr, "pgp_keyid: bad algorithm\n");
574 			return 0;
575 		}
576 		BN_bn2bin(key->key.rsa.n, bn);
577 		(void) memcpy(keyid, bn + n - idlen, idlen);
578 	} else {
579 		pgp_fingerprint(&finger, key, hashtype);
580 		(void) memcpy(keyid,
581 				finger.fingerprint + finger.length - idlen,
582 				idlen);
583 	}
584 	return 1;
585 }
586 
587 /**
588 \ingroup Core_Hashes
589 \brief Add to the hash
590 \param hash Hash to add to
591 \param n Int to add
592 \param length Length of int in bytes
593 */
594 void
595 pgp_hash_add_int(pgp_hash_t *hash, unsigned n, unsigned length)
596 {
597 	uint8_t   c;
598 
599 	while (length--) {
600 		c = n >> (length * 8);
601 		hash->add(hash, &c, 1);
602 	}
603 }
604 
605 /**
606 \ingroup Core_Hashes
607 \brief Setup hash for given hash algorithm
608 \param hash Hash to set up
609 \param alg Hash algorithm to use
610 */
611 void
612 pgp_hash_any(pgp_hash_t *hash, pgp_hash_alg_t alg)
613 {
614 	switch (alg) {
615 	case PGP_HASH_MD5:
616 		pgp_hash_md5(hash);
617 		break;
618 
619 	case PGP_HASH_SHA1:
620 		pgp_hash_sha1(hash);
621 		break;
622 
623 	case PGP_HASH_SHA256:
624 		pgp_hash_sha256(hash);
625 		break;
626 
627 	case PGP_HASH_SHA384:
628 		pgp_hash_sha384(hash);
629 		break;
630 
631 	case PGP_HASH_SHA512:
632 		pgp_hash_sha512(hash);
633 		break;
634 
635 	case PGP_HASH_SHA224:
636 		pgp_hash_sha224(hash);
637 		break;
638 
639 	default:
640 		(void) fprintf(stderr, "pgp_hash_any: bad algorithm\n");
641 	}
642 }
643 
644 /**
645 \ingroup Core_Hashes
646 \brief Returns size of hash for given hash algorithm
647 \param alg Hash algorithm to use
648 \return Size of hash algorithm in bytes
649 */
650 unsigned
651 pgp_hash_size(pgp_hash_alg_t alg)
652 {
653 	switch (alg) {
654 	case PGP_HASH_MD5:
655 		return 16;
656 
657 	case PGP_HASH_SHA1:
658 		return 20;
659 
660 	case PGP_HASH_SHA256:
661 		return 32;
662 
663 	case PGP_HASH_SHA224:
664 		return 28;
665 
666 	case PGP_HASH_SHA512:
667 		return 64;
668 
669 	case PGP_HASH_SHA384:
670 		return 48;
671 
672 	default:
673 		(void) fprintf(stderr, "pgp_hash_size: bad algorithm\n");
674 	}
675 
676 	return 0;
677 }
678 
679 /**
680 \ingroup Core_Hashes
681 \brief Returns hash enum corresponding to given string
682 \param hash Text name of hash algorithm i.e. "SHA1"
683 \returns Corresponding enum i.e. PGP_HASH_SHA1
684 */
685 pgp_hash_alg_t
686 pgp_str_to_hash_alg(const char *hash)
687 {
688 	if (hash == NULL) {
689 		return PGP_DEFAULT_HASH_ALGORITHM;
690 	}
691 	if (netpgp_strcasecmp(hash, "SHA1") == 0) {
692 		return PGP_HASH_SHA1;
693 	}
694 	if (netpgp_strcasecmp(hash, "MD5") == 0) {
695 		return PGP_HASH_MD5;
696 	}
697 	if (netpgp_strcasecmp(hash, "SHA256") == 0) {
698 		return PGP_HASH_SHA256;
699 	}
700 	/*
701         if (netpgp_strcasecmp(hash,"SHA224") == 0) {
702 		return PGP_HASH_SHA224;
703 	}
704         */
705 	if (netpgp_strcasecmp(hash, "SHA512") == 0) {
706 		return PGP_HASH_SHA512;
707 	}
708 	if (netpgp_strcasecmp(hash, "SHA384") == 0) {
709 		return PGP_HASH_SHA384;
710 	}
711 	return PGP_HASH_UNKNOWN;
712 }
713 
714 /**
715 \ingroup Core_Hashes
716 \brief Hash given data
717 \param out Where to write the hash
718 \param alg Hash algorithm to use
719 \param in Data to hash
720 \param length Length of data
721 \return Size of hash created
722 */
723 unsigned
724 pgp_hash(uint8_t *out, pgp_hash_alg_t alg, const void *in, size_t length)
725 {
726 	pgp_hash_t      hash;
727 
728 	pgp_hash_any(&hash, alg);
729 	if (!hash.init(&hash)) {
730 		(void) fprintf(stderr, "pgp_hash: bad alloc\n");
731 		/* we'll just continue here - don't want to return a 0 hash */
732 		/* XXX - agc - no way to return failure */
733 	}
734 	hash.add(&hash, in, (unsigned)length);
735 	return hash.finish(&hash, out);
736 }
737 
738 /**
739 \ingroup Core_Hashes
740 \brief Calculate hash for MDC packet
741 \param preamble Preamble to hash
742 \param sz_preamble Size of preamble
743 \param plaintext Plaintext to hash
744 \param sz_plaintext Size of plaintext
745 \param hashed Resulting hash
746 */
747 void
748 pgp_calc_mdc_hash(const uint8_t *preamble,
749 			const size_t sz_preamble,
750 			const uint8_t *plaintext,
751 			const unsigned sz_plaintext,
752 			uint8_t *hashed)
753 {
754 	pgp_hash_t	hash;
755 	uint8_t		c;
756 
757 	if (pgp_get_debug_level(__FILE__)) {
758 		hexdump(stderr, "preamble", preamble, sz_preamble);
759 		hexdump(stderr, "plaintext", plaintext, sz_plaintext);
760 	}
761 	/* init */
762 	pgp_hash_any(&hash, PGP_HASH_SHA1);
763 	if (!hash.init(&hash)) {
764 		(void) fprintf(stderr, "pgp_calc_mdc_hash: bad alloc\n");
765 		/* we'll just continue here - it will die anyway */
766 		/* agc - XXX - no way to return failure */
767 	}
768 
769 	/* preamble */
770 	hash.add(&hash, preamble, (unsigned)sz_preamble);
771 	/* plaintext */
772 	hash.add(&hash, plaintext, sz_plaintext);
773 	/* MDC packet tag */
774 	c = MDC_PKT_TAG;
775 	hash.add(&hash, &c, 1);
776 	/* MDC packet len */
777 	c = PGP_SHA1_HASH_SIZE;
778 	hash.add(&hash, &c, 1);
779 
780 	/* finish */
781 	hash.finish(&hash, hashed);
782 
783 	if (pgp_get_debug_level(__FILE__)) {
784 		hexdump(stderr, "hashed", hashed, PGP_SHA1_HASH_SIZE);
785 	}
786 }
787 
788 /**
789 \ingroup HighLevel_Supported
790 \brief Is this Hash Algorithm supported?
791 \param hash_alg Hash Algorithm to check
792 \return 1 if supported; else 0
793 */
794 unsigned
795 pgp_is_hash_alg_supported(const pgp_hash_alg_t *hash_alg)
796 {
797 	switch (*hash_alg) {
798 	case PGP_HASH_MD5:
799 	case PGP_HASH_SHA1:
800 	case PGP_HASH_SHA256:
801 		return 1;
802 
803 	default:
804 		return 0;
805 	}
806 }
807 
808 /* structure to map string to cipher def */
809 typedef struct str2cipher_t {
810 	const char	*s;	/* cipher name */
811 	pgp_symm_alg_t i;	/* cipher def */
812 } str2cipher_t;
813 
814 static str2cipher_t	str2cipher[] = {
815 	{	"cast5",		PGP_SA_CAST5		},
816 	{	"idea",			PGP_SA_IDEA		},
817 	{	"aes128",		PGP_SA_AES_128		},
818 	{	"aes256",		PGP_SA_AES_256		},
819 	{	"blowfish",		PGP_SA_BLOWFISH		},
820 	{	"camellia128",		PGP_SA_CAMELLIA_128	},
821 	{	"camellia256",		PGP_SA_CAMELLIA_256	},
822 	{	"tripledes",		PGP_SA_TRIPLEDES	},
823 	{	NULL,			0			}
824 };
825 
826 /* convert from a string to a cipher definition */
827 pgp_symm_alg_t
828 pgp_str_to_cipher(const char *cipher)
829 {
830 	str2cipher_t	*sp;
831 
832 	for (sp = str2cipher ; cipher && sp->s ; sp++) {
833 		if (netpgp_strcasecmp(cipher, sp->s) == 0) {
834 			return sp->i;
835 		}
836 	}
837 	return PGP_SA_DEFAULT_CIPHER;
838 }
839 
840 void
841 pgp_random(void *dest, size_t length)
842 {
843 	RAND_bytes(dest, (int)length);
844 }
845 
846 /**
847 \ingroup HighLevel_Memory
848 \brief Memory to initialise
849 \param mem memory to initialise
850 \param needed Size to initialise to
851 */
852 void
853 pgp_memory_init(pgp_memory_t *mem, size_t needed)
854 {
855 	uint8_t	*temp;
856 
857 	mem->length = 0;
858 	if (mem->buf) {
859 		if (mem->allocated < needed) {
860 			if ((temp = realloc(mem->buf, needed)) == NULL) {
861 				(void) fprintf(stderr, "pgp_memory_init: bad alloc\n");
862 			} else {
863 				mem->buf = temp;
864 				mem->allocated = needed;
865 			}
866 		}
867 	} else {
868 		if ((mem->buf = calloc(1, needed)) == NULL) {
869 			(void) fprintf(stderr, "pgp_memory_init: bad alloc\n");
870 		} else {
871 			mem->allocated = needed;
872 		}
873 	}
874 }
875 
876 /**
877 \ingroup HighLevel_Memory
878 \brief Pad memory to required length
879 \param mem Memory to use
880 \param length New size
881 */
882 void
883 pgp_memory_pad(pgp_memory_t *mem, size_t length)
884 {
885 	uint8_t	*temp;
886 
887 	if (mem->allocated < mem->length) {
888 		(void) fprintf(stderr, "pgp_memory_pad: bad alloc in\n");
889 		return;
890 	}
891 	if (mem->allocated < mem->length + length) {
892 		mem->allocated = mem->allocated * 2 + length;
893 		temp = realloc(mem->buf, mem->allocated);
894 		if (temp == NULL) {
895 			(void) fprintf(stderr, "pgp_memory_pad: bad alloc\n");
896 		} else {
897 			mem->buf = temp;
898 		}
899 	}
900 	if (mem->allocated < mem->length + length) {
901 		(void) fprintf(stderr, "pgp_memory_pad: bad alloc out\n");
902 	}
903 }
904 
905 /**
906 \ingroup HighLevel_Memory
907 \brief Add data to memory
908 \param mem Memory to which to add
909 \param src Data to add
910 \param length Length of data to add
911 */
912 void
913 pgp_memory_add(pgp_memory_t *mem, const uint8_t *src, size_t length)
914 {
915 	pgp_memory_pad(mem, length);
916 	(void) memcpy(mem->buf + mem->length, src, length);
917 	mem->length += length;
918 }
919 
920 /* XXX: this could be refactored via the writer, but an awful lot of */
921 /* hoops to jump through for 2 lines of code! */
922 void
923 pgp_memory_place_int(pgp_memory_t *mem, unsigned offset, unsigned n,
924 		     size_t length)
925 {
926 	if (mem->allocated < offset + length) {
927 		(void) fprintf(stderr,
928 			"pgp_memory_place_int: bad alloc\n");
929 	} else {
930 		while (length-- > 0) {
931 			mem->buf[offset++] = n >> (length * 8);
932 		}
933 	}
934 }
935 
936 /**
937  * \ingroup HighLevel_Memory
938  * \brief Retains allocated memory and set length of stored data to zero.
939  * \param mem Memory to clear
940  * \sa pgp_memory_release()
941  * \sa pgp_memory_free()
942  */
943 void
944 pgp_memory_clear(pgp_memory_t *mem)
945 {
946 	mem->length = 0;
947 }
948 
949 /**
950 \ingroup HighLevel_Memory
951 \brief Free memory and associated data
952 \param mem Memory to free
953 \note This does not free mem itself
954 \sa pgp_memory_clear()
955 \sa pgp_memory_free()
956 */
957 void
958 pgp_memory_release(pgp_memory_t *mem)
959 {
960 	if (mem->mmapped) {
961 		(void) munmap(mem->buf, mem->length);
962 	} else {
963 		free(mem->buf);
964 	}
965 	mem->buf = NULL;
966 	mem->length = 0;
967 }
968 
969 void
970 pgp_memory_make_packet(pgp_memory_t *out, pgp_content_enum tag)
971 {
972 	size_t          extra;
973 
974 	extra = (out->length < 192) ? 1 : (out->length < 8192 + 192) ? 2 : 5;
975 	pgp_memory_pad(out, extra + 1);
976 	memmove(out->buf + extra + 1, out->buf, out->length);
977 
978 	out->buf[0] = PGP_PTAG_ALWAYS_SET | PGP_PTAG_NEW_FORMAT | tag;
979 
980 	if (out->length < 192) {
981 		out->buf[1] = (uint8_t)out->length;
982 	} else if (out->length < 8192 + 192) {
983 		out->buf[1] = (uint8_t)((out->length - 192) >> 8) + 192;
984 		out->buf[2] = (uint8_t)(out->length - 192);
985 	} else {
986 		out->buf[1] = 0xff;
987 		out->buf[2] = (uint8_t)(out->length >> 24);
988 		out->buf[3] = (uint8_t)(out->length >> 16);
989 		out->buf[4] = (uint8_t)(out->length >> 8);
990 		out->buf[5] = (uint8_t)(out->length);
991 	}
992 
993 	out->length += extra + 1;
994 }
995 
996 /**
997    \ingroup HighLevel_Memory
998    \brief Create a new zeroed pgp_memory_t
999    \return Pointer to new pgp_memory_t
1000    \note Free using pgp_memory_free() after use.
1001    \sa pgp_memory_free()
1002 */
1003 
1004 pgp_memory_t   *
1005 pgp_memory_new(void)
1006 {
1007 	return calloc(1, sizeof(pgp_memory_t));
1008 }
1009 
1010 /**
1011    \ingroup HighLevel_Memory
1012    \brief Free memory ptr and associated memory
1013    \param mem Memory to be freed
1014    \sa pgp_memory_release()
1015    \sa pgp_memory_clear()
1016 */
1017 
1018 void
1019 pgp_memory_free(pgp_memory_t *mem)
1020 {
1021 	pgp_memory_release(mem);
1022 	free(mem);
1023 }
1024 
1025 /**
1026    \ingroup HighLevel_Memory
1027    \brief Get length of data stored in pgp_memory_t struct
1028    \return Number of bytes in data
1029 */
1030 size_t
1031 pgp_mem_len(const pgp_memory_t *mem)
1032 {
1033 	return mem->length;
1034 }
1035 
1036 /**
1037    \ingroup HighLevel_Memory
1038    \brief Get data stored in pgp_memory_t struct
1039    \return Pointer to data
1040 */
1041 void *
1042 pgp_mem_data(pgp_memory_t *mem)
1043 {
1044 	return mem->buf;
1045 }
1046 
1047 /* read a gile into an pgp_memory_t */
1048 int
1049 pgp_mem_readfile(pgp_memory_t *mem, const char *f)
1050 {
1051 	struct stat	 st;
1052 	FILE		*fp;
1053 	int		 cc;
1054 
1055 	if ((fp = fopen(f, "rb")) == NULL) {
1056 		(void) fprintf(stderr,
1057 				"pgp_mem_readfile: can't open \"%s\"\n", f);
1058 		return 0;
1059 	}
1060 	(void) fstat(fileno(fp), &st);
1061 	mem->allocated = (size_t)st.st_size;
1062 	mem->buf = mmap(NULL, mem->allocated, PROT_READ,
1063 				MAP_PRIVATE | MAP_FILE, fileno(fp), 0);
1064 	if (mem->buf == MAP_FAILED) {
1065 		/* mmap failed for some reason - try to allocate memory */
1066 		if ((mem->buf = calloc(1, mem->allocated)) == NULL) {
1067 			(void) fprintf(stderr, "pgp_mem_readfile: calloc\n");
1068 			(void) fclose(fp);
1069 			return 0;
1070 		}
1071 		/* read into contents of mem */
1072 		for (mem->length = 0 ;
1073 		     (cc = (int)read(fileno(fp), &mem->buf[mem->length],
1074 					(size_t)(mem->allocated - mem->length))) > 0 ;
1075 		     mem->length += (size_t)cc) {
1076 		}
1077 	} else {
1078 		mem->length = mem->allocated;
1079 		mem->mmapped = 1;
1080 	}
1081 	(void) fclose(fp);
1082 	return (mem->allocated == mem->length);
1083 }
1084 
1085 typedef struct {
1086 	uint16_t  sum;
1087 } sum16_t;
1088 
1089 
1090 /**
1091  * Searches the given map for the given type.
1092  * Returns a human-readable descriptive string if found,
1093  * returns NULL if not found
1094  *
1095  * It is the responsibility of the calling function to handle the
1096  * error case sensibly (i.e. don't just print out the return string.
1097  *
1098  */
1099 static const char *
1100 str_from_map_or_null(int type, pgp_map_t *map)
1101 {
1102 	pgp_map_t      *row;
1103 
1104 	for (row = map; row->string != NULL; row++) {
1105 		if (row->type == type) {
1106 			return row->string;
1107 		}
1108 	}
1109 	return NULL;
1110 }
1111 
1112 /**
1113  * \ingroup Core_Print
1114  *
1115  * Searches the given map for the given type.
1116  * Returns a readable string if found, "Unknown" if not.
1117  */
1118 
1119 const char     *
1120 pgp_str_from_map(int type, pgp_map_t *map)
1121 {
1122 	const char     *str;
1123 
1124 	str = str_from_map_or_null(type, map);
1125 	return (str) ? str : "Unknown";
1126 }
1127 
1128 #define LINELEN	16
1129 
1130 /* show hexadecimal/ascii dump */
1131 void
1132 hexdump(FILE *fp, const char *header, const uint8_t *src, size_t length)
1133 {
1134 	size_t	i;
1135 	char	line[LINELEN + 1];
1136 
1137 	(void) fprintf(fp, "%s%s", (header) ? header : "", (header) ? "\n" : "");
1138 	(void) fprintf(fp, "[%" PRIsize "u char%s]\n", length, (length == 1) ? "" : "s");
1139 	for (i = 0 ; i < length ; i++) {
1140 		if (i % LINELEN == 0) {
1141 			(void) fprintf(fp, "%.5" PRIsize "u | ", i);
1142 		}
1143 		(void) fprintf(fp, "%.02x ", (uint8_t)src[i]);
1144 		line[i % LINELEN] = (isprint(src[i])) ? src[i] : '.';
1145 		if (i % LINELEN == LINELEN - 1) {
1146 			line[LINELEN] = 0x0;
1147 			(void) fprintf(fp, " | %s\n", line);
1148 		}
1149 	}
1150 	if (i % LINELEN != 0) {
1151 		for ( ; i % LINELEN != 0 ; i++) {
1152 			(void) fprintf(fp, "   ");
1153 			line[i % LINELEN] = ' ';
1154 		}
1155 		line[LINELEN] = 0x0;
1156 		(void) fprintf(fp, " | %s\n", line);
1157 	}
1158 }
1159 
1160 /**
1161  * \ingroup HighLevel_Functions
1162  * \brief Closes down OpenPGP::SDK.
1163  *
1164  * Close down OpenPGP:SDK, release any resources under the control of
1165  * the library.
1166  */
1167 
1168 void
1169 pgp_finish(void)
1170 {
1171 	pgp_crypto_finish();
1172 }
1173 
1174 static int
1175 sum16_reader(pgp_stream_t *stream, void *dest_, size_t length, pgp_error_t **errors,
1176 	     pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
1177 {
1178 	const uint8_t	*dest = dest_;
1179 	sum16_t		*arg = pgp_reader_get_arg(readinfo);
1180 	int		 r;
1181 	int		 n;
1182 
1183 	r = pgp_stacked_read(stream, dest_, length, errors, readinfo, cbinfo);
1184 	if (r < 0) {
1185 		return r;
1186 	}
1187 	for (n = 0; n < r; ++n) {
1188 		arg->sum = (arg->sum + dest[n]) & 0xffff;
1189 	}
1190 	return r;
1191 }
1192 
1193 static void
1194 sum16_destroyer(pgp_reader_t *readinfo)
1195 {
1196 	free(pgp_reader_get_arg(readinfo));
1197 }
1198 
1199 /**
1200    \ingroup Internal_Readers_Sum16
1201    \param stream Parse settings
1202 */
1203 
1204 void
1205 pgp_reader_push_sum16(pgp_stream_t *stream)
1206 {
1207 	sum16_t    *arg;
1208 
1209 	if ((arg = calloc(1, sizeof(*arg))) == NULL) {
1210 		(void) fprintf(stderr, "pgp_reader_push_sum16: bad alloc\n");
1211 	} else {
1212 		pgp_reader_push(stream, sum16_reader, sum16_destroyer, arg);
1213 	}
1214 }
1215 
1216 /**
1217    \ingroup Internal_Readers_Sum16
1218    \param stream Parse settings
1219    \return sum
1220 */
1221 uint16_t
1222 pgp_reader_pop_sum16(pgp_stream_t *stream)
1223 {
1224 	uint16_t	 sum;
1225 	sum16_t		*arg;
1226 
1227 	arg = pgp_reader_get_arg(pgp_readinfo(stream));
1228 	sum = arg->sum;
1229 	pgp_reader_pop(stream);
1230 	free(arg);
1231 	return sum;
1232 }
1233 
1234 /* small useful functions for setting the file-level debugging levels */
1235 /* if the debugv list contains the filename in question, we're debugging it */
1236 
1237 enum {
1238 	MAX_DEBUG_NAMES = 32
1239 };
1240 
1241 static int      debugc;
1242 static char    *debugv[MAX_DEBUG_NAMES];
1243 
1244 /* set the debugging level per filename */
1245 int
1246 pgp_set_debug_level(const char *f)
1247 {
1248 	const char     *name;
1249 	int             i;
1250 
1251 	if (f == NULL) {
1252 		f = "all";
1253 	}
1254 	if ((name = strrchr(f, '/')) == NULL) {
1255 		name = f;
1256 	} else {
1257 		name += 1;
1258 	}
1259 	for (i = 0; i < debugc && i < MAX_DEBUG_NAMES; i++) {
1260 		if (strcmp(debugv[i], name) == 0) {
1261 			return 1;
1262 		}
1263 	}
1264 	if (i == MAX_DEBUG_NAMES) {
1265 		return 0;
1266 	}
1267 	debugv[debugc++] = netpgp_strdup(name);
1268 	return 1;
1269 }
1270 
1271 /* get the debugging level per filename */
1272 int
1273 pgp_get_debug_level(const char *f)
1274 {
1275 	const char     *name;
1276 	int             i;
1277 
1278 	if ((name = strrchr(f, '/')) == NULL) {
1279 		name = f;
1280 	} else {
1281 		name += 1;
1282 	}
1283 	for (i = 0; i < debugc; i++) {
1284 		if (strcmp(debugv[i], "all") == 0 ||
1285 		    strcmp(debugv[i], name) == 0) {
1286 			return 1;
1287 		}
1288 	}
1289 	return 0;
1290 }
1291 
1292 /* return the version for the library */
1293 const char *
1294 pgp_get_info(const char *type)
1295 {
1296 	if (strcmp(type, "version") == 0) {
1297 		return NETPGP_VERSION_STRING;
1298 	}
1299 	if (strcmp(type, "maintainer") == 0) {
1300 		return NETPGP_MAINTAINER;
1301 	}
1302 	return "[unknown]";
1303 }
1304 
1305 /* local version of asprintf so we don't have to play autoconf games */
1306 int
1307 pgp_asprintf(char **ret, const char *fmt, ...)
1308 {
1309 	va_list args;
1310 	char    buf[120 * 1024];	/* XXX - "huge" buffer on stack */
1311 	int     cc;
1312 
1313 	va_start(args, fmt);
1314 	cc = vsnprintf(buf, sizeof(buf), fmt, args);
1315 	va_end(args);
1316 	if ((*ret = calloc(1, (size_t)(cc + 1))) == NULL) {
1317 		*ret = NULL;
1318 		return -1;
1319 	}
1320 	(void) memcpy(*ret, buf, (size_t)cc);
1321 	(*ret)[cc] = 0x0;
1322 	return cc;
1323 }
1324 
1325 void
1326 netpgp_log(const char *fmt, ...)
1327 {
1328 	va_list	 vp;
1329 	time_t	 t;
1330 	char	 buf[BUFSIZ * 2];
1331 	int	 cc;
1332 
1333 	(void) time(&t);
1334 	cc = snprintf(buf, sizeof(buf), "%.24s: netpgp: ", ctime(&t));
1335 	va_start(vp, fmt);
1336 	(void) vsnprintf(&buf[cc], sizeof(buf) - (size_t)cc, fmt, vp);
1337 	va_end(vp);
1338 	/* do something with message */
1339 	/* put into log buffer? */
1340 }
1341 
1342 /* portable replacement for strdup(3) */
1343 char *
1344 netpgp_strdup(const char *s)
1345 {
1346 	size_t	 len;
1347 	char	*cp;
1348 
1349 	len = strlen(s);
1350 	if ((cp = calloc(1, len + 1)) != NULL) {
1351 		(void) memcpy(cp, s, len);
1352 		cp[len] = 0x0;
1353 	}
1354 	return cp;
1355 }
1356 
1357 /* portable replacement for strcasecmp(3) */
1358 int
1359 netpgp_strcasecmp(const char *s1, const char *s2)
1360 {
1361 	int	n;
1362 
1363 	for (n = 0 ; *s1 && *s2 && (n = tolower((uint8_t)*s1) - tolower((uint8_t)*s2)) == 0 ; s1++, s2++) {
1364 	}
1365 	return n;
1366 }
1367