xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/misc.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
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.42 2018/11/13 14:52:30 mlelstv 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 	{	"camellia128",		PGP_SA_CAMELLIA_128	},
820 	{	"camellia256",		PGP_SA_CAMELLIA_256	},
821 	{	"tripledes",		PGP_SA_TRIPLEDES	},
822 	{	NULL,			0			}
823 };
824 
825 /* convert from a string to a cipher definition */
826 pgp_symm_alg_t
827 pgp_str_to_cipher(const char *cipher)
828 {
829 	str2cipher_t	*sp;
830 
831 	for (sp = str2cipher ; cipher && sp->s ; sp++) {
832 		if (netpgp_strcasecmp(cipher, sp->s) == 0) {
833 			return sp->i;
834 		}
835 	}
836 	return PGP_SA_DEFAULT_CIPHER;
837 }
838 
839 void
840 pgp_random(void *dest, size_t length)
841 {
842 	RAND_bytes(dest, (int)length);
843 }
844 
845 /**
846 \ingroup HighLevel_Memory
847 \brief Memory to initialise
848 \param mem memory to initialise
849 \param needed Size to initialise to
850 */
851 void
852 pgp_memory_init(pgp_memory_t *mem, size_t needed)
853 {
854 	uint8_t	*temp;
855 
856 	mem->length = 0;
857 	if (mem->buf) {
858 		if (mem->allocated < needed) {
859 			if ((temp = realloc(mem->buf, needed)) == NULL) {
860 				(void) fprintf(stderr, "pgp_memory_init: bad alloc\n");
861 			} else {
862 				mem->buf = temp;
863 				mem->allocated = needed;
864 			}
865 		}
866 	} else {
867 		if ((mem->buf = calloc(1, needed)) == NULL) {
868 			(void) fprintf(stderr, "pgp_memory_init: bad alloc\n");
869 		} else {
870 			mem->allocated = needed;
871 		}
872 	}
873 }
874 
875 /**
876 \ingroup HighLevel_Memory
877 \brief Pad memory to required length
878 \param mem Memory to use
879 \param length New size
880 */
881 void
882 pgp_memory_pad(pgp_memory_t *mem, size_t length)
883 {
884 	uint8_t	*temp;
885 
886 	if (mem->allocated < mem->length) {
887 		(void) fprintf(stderr, "pgp_memory_pad: bad alloc in\n");
888 		return;
889 	}
890 	if (mem->allocated < mem->length + length) {
891 		mem->allocated = mem->allocated * 2 + length;
892 		temp = realloc(mem->buf, mem->allocated);
893 		if (temp == NULL) {
894 			(void) fprintf(stderr, "pgp_memory_pad: bad alloc\n");
895 		} else {
896 			mem->buf = temp;
897 		}
898 	}
899 	if (mem->allocated < mem->length + length) {
900 		(void) fprintf(stderr, "pgp_memory_pad: bad alloc out\n");
901 	}
902 }
903 
904 /**
905 \ingroup HighLevel_Memory
906 \brief Add data to memory
907 \param mem Memory to which to add
908 \param src Data to add
909 \param length Length of data to add
910 */
911 void
912 pgp_memory_add(pgp_memory_t *mem, const uint8_t *src, size_t length)
913 {
914 	pgp_memory_pad(mem, length);
915 	(void) memcpy(mem->buf + mem->length, src, length);
916 	mem->length += length;
917 }
918 
919 /* XXX: this could be refactored via the writer, but an awful lot of */
920 /* hoops to jump through for 2 lines of code! */
921 void
922 pgp_memory_place_int(pgp_memory_t *mem, unsigned offset, unsigned n,
923 		     size_t length)
924 {
925 	if (mem->allocated < offset + length) {
926 		(void) fprintf(stderr,
927 			"pgp_memory_place_int: bad alloc\n");
928 	} else {
929 		while (length-- > 0) {
930 			mem->buf[offset++] = n >> (length * 8);
931 		}
932 	}
933 }
934 
935 /**
936  * \ingroup HighLevel_Memory
937  * \brief Retains allocated memory and set length of stored data to zero.
938  * \param mem Memory to clear
939  * \sa pgp_memory_release()
940  * \sa pgp_memory_free()
941  */
942 void
943 pgp_memory_clear(pgp_memory_t *mem)
944 {
945 	mem->length = 0;
946 }
947 
948 /**
949 \ingroup HighLevel_Memory
950 \brief Free memory and associated data
951 \param mem Memory to free
952 \note This does not free mem itself
953 \sa pgp_memory_clear()
954 \sa pgp_memory_free()
955 */
956 void
957 pgp_memory_release(pgp_memory_t *mem)
958 {
959 	if (mem->mmapped) {
960 		(void) munmap(mem->buf, mem->length);
961 	} else {
962 		free(mem->buf);
963 	}
964 	mem->buf = NULL;
965 	mem->length = 0;
966 }
967 
968 void
969 pgp_memory_make_packet(pgp_memory_t *out, pgp_content_enum tag)
970 {
971 	size_t          extra;
972 
973 	extra = (out->length < 192) ? 1 : (out->length < 8192 + 192) ? 2 : 5;
974 	pgp_memory_pad(out, extra + 1);
975 	memmove(out->buf + extra + 1, out->buf, out->length);
976 
977 	out->buf[0] = PGP_PTAG_ALWAYS_SET | PGP_PTAG_NEW_FORMAT | tag;
978 
979 	if (out->length < 192) {
980 		out->buf[1] = (uint8_t)out->length;
981 	} else if (out->length < 8192 + 192) {
982 		out->buf[1] = (uint8_t)((out->length - 192) >> 8) + 192;
983 		out->buf[2] = (uint8_t)(out->length - 192);
984 	} else {
985 		out->buf[1] = 0xff;
986 		out->buf[2] = (uint8_t)(out->length >> 24);
987 		out->buf[3] = (uint8_t)(out->length >> 16);
988 		out->buf[4] = (uint8_t)(out->length >> 8);
989 		out->buf[5] = (uint8_t)(out->length);
990 	}
991 
992 	out->length += extra + 1;
993 }
994 
995 /**
996    \ingroup HighLevel_Memory
997    \brief Create a new zeroed pgp_memory_t
998    \return Pointer to new pgp_memory_t
999    \note Free using pgp_memory_free() after use.
1000    \sa pgp_memory_free()
1001 */
1002 
1003 pgp_memory_t   *
1004 pgp_memory_new(void)
1005 {
1006 	return calloc(1, sizeof(pgp_memory_t));
1007 }
1008 
1009 /**
1010    \ingroup HighLevel_Memory
1011    \brief Free memory ptr and associated memory
1012    \param mem Memory to be freed
1013    \sa pgp_memory_release()
1014    \sa pgp_memory_clear()
1015 */
1016 
1017 void
1018 pgp_memory_free(pgp_memory_t *mem)
1019 {
1020 	pgp_memory_release(mem);
1021 	free(mem);
1022 }
1023 
1024 /**
1025    \ingroup HighLevel_Memory
1026    \brief Get length of data stored in pgp_memory_t struct
1027    \return Number of bytes in data
1028 */
1029 size_t
1030 pgp_mem_len(const pgp_memory_t *mem)
1031 {
1032 	return mem->length;
1033 }
1034 
1035 /**
1036    \ingroup HighLevel_Memory
1037    \brief Get data stored in pgp_memory_t struct
1038    \return Pointer to data
1039 */
1040 void *
1041 pgp_mem_data(pgp_memory_t *mem)
1042 {
1043 	return mem->buf;
1044 }
1045 
1046 /* read a gile into an pgp_memory_t */
1047 int
1048 pgp_mem_readfile(pgp_memory_t *mem, const char *f)
1049 {
1050 	struct stat	 st;
1051 	FILE		*fp;
1052 	int		 cc;
1053 
1054 	if ((fp = fopen(f, "rb")) == NULL) {
1055 		(void) fprintf(stderr,
1056 				"pgp_mem_readfile: can't open \"%s\"\n", f);
1057 		return 0;
1058 	}
1059 	(void) fstat(fileno(fp), &st);
1060 	mem->allocated = (size_t)st.st_size;
1061 	mem->buf = mmap(NULL, mem->allocated, PROT_READ,
1062 				MAP_PRIVATE | MAP_FILE, fileno(fp), 0);
1063 	if (mem->buf == MAP_FAILED) {
1064 		/* mmap failed for some reason - try to allocate memory */
1065 		if ((mem->buf = calloc(1, mem->allocated)) == NULL) {
1066 			(void) fprintf(stderr, "pgp_mem_readfile: calloc\n");
1067 			(void) fclose(fp);
1068 			return 0;
1069 		}
1070 		/* read into contents of mem */
1071 		for (mem->length = 0 ;
1072 		     (cc = (int)read(fileno(fp), &mem->buf[mem->length],
1073 					(size_t)(mem->allocated - mem->length))) > 0 ;
1074 		     mem->length += (size_t)cc) {
1075 		}
1076 	} else {
1077 		mem->length = mem->allocated;
1078 		mem->mmapped = 1;
1079 	}
1080 	(void) fclose(fp);
1081 	return (mem->allocated == mem->length);
1082 }
1083 
1084 typedef struct {
1085 	uint16_t  sum;
1086 } sum16_t;
1087 
1088 
1089 /**
1090  * Searches the given map for the given type.
1091  * Returns a human-readable descriptive string if found,
1092  * returns NULL if not found
1093  *
1094  * It is the responsibility of the calling function to handle the
1095  * error case sensibly (i.e. don't just print out the return string.
1096  *
1097  */
1098 static const char *
1099 str_from_map_or_null(int type, pgp_map_t *map)
1100 {
1101 	pgp_map_t      *row;
1102 
1103 	for (row = map; row->string != NULL; row++) {
1104 		if (row->type == type) {
1105 			return row->string;
1106 		}
1107 	}
1108 	return NULL;
1109 }
1110 
1111 /**
1112  * \ingroup Core_Print
1113  *
1114  * Searches the given map for the given type.
1115  * Returns a readable string if found, "Unknown" if not.
1116  */
1117 
1118 const char     *
1119 pgp_str_from_map(int type, pgp_map_t *map)
1120 {
1121 	const char     *str;
1122 
1123 	str = str_from_map_or_null(type, map);
1124 	return (str) ? str : "Unknown";
1125 }
1126 
1127 #define LINELEN	16
1128 
1129 /* show hexadecimal/ascii dump */
1130 void
1131 hexdump(FILE *fp, const char *header, const uint8_t *src, size_t length)
1132 {
1133 	size_t	i;
1134 	char	line[LINELEN + 1];
1135 
1136 	(void) fprintf(fp, "%s%s", (header) ? header : "", (header) ? "\n" : "");
1137 	(void) fprintf(fp, "[%" PRIsize "u char%s]\n", length, (length == 1) ? "" : "s");
1138 	for (i = 0 ; i < length ; i++) {
1139 		if (i % LINELEN == 0) {
1140 			(void) fprintf(fp, "%.5" PRIsize "u | ", i);
1141 		}
1142 		(void) fprintf(fp, "%.02x ", (uint8_t)src[i]);
1143 		line[i % LINELEN] = (isprint(src[i])) ? src[i] : '.';
1144 		if (i % LINELEN == LINELEN - 1) {
1145 			line[LINELEN] = 0x0;
1146 			(void) fprintf(fp, " | %s\n", line);
1147 		}
1148 	}
1149 	if (i % LINELEN != 0) {
1150 		for ( ; i % LINELEN != 0 ; i++) {
1151 			(void) fprintf(fp, "   ");
1152 			line[i % LINELEN] = ' ';
1153 		}
1154 		line[LINELEN] = 0x0;
1155 		(void) fprintf(fp, " | %s\n", line);
1156 	}
1157 }
1158 
1159 /**
1160  * \ingroup HighLevel_Functions
1161  * \brief Closes down OpenPGP::SDK.
1162  *
1163  * Close down OpenPGP:SDK, release any resources under the control of
1164  * the library.
1165  */
1166 
1167 void
1168 pgp_finish(void)
1169 {
1170 	pgp_crypto_finish();
1171 }
1172 
1173 static int
1174 sum16_reader(pgp_stream_t *stream, void *dest_, size_t length, pgp_error_t **errors,
1175 	     pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
1176 {
1177 	const uint8_t	*dest = dest_;
1178 	sum16_t		*arg = pgp_reader_get_arg(readinfo);
1179 	int		 r;
1180 	int		 n;
1181 
1182 	r = pgp_stacked_read(stream, dest_, length, errors, readinfo, cbinfo);
1183 	if (r < 0) {
1184 		return r;
1185 	}
1186 	for (n = 0; n < r; ++n) {
1187 		arg->sum = (arg->sum + dest[n]) & 0xffff;
1188 	}
1189 	return r;
1190 }
1191 
1192 static void
1193 sum16_destroyer(pgp_reader_t *readinfo)
1194 {
1195 	free(pgp_reader_get_arg(readinfo));
1196 }
1197 
1198 /**
1199    \ingroup Internal_Readers_Sum16
1200    \param stream Parse settings
1201 */
1202 
1203 void
1204 pgp_reader_push_sum16(pgp_stream_t *stream)
1205 {
1206 	sum16_t    *arg;
1207 
1208 	if ((arg = calloc(1, sizeof(*arg))) == NULL) {
1209 		(void) fprintf(stderr, "pgp_reader_push_sum16: bad alloc\n");
1210 	} else {
1211 		pgp_reader_push(stream, sum16_reader, sum16_destroyer, arg);
1212 	}
1213 }
1214 
1215 /**
1216    \ingroup Internal_Readers_Sum16
1217    \param stream Parse settings
1218    \return sum
1219 */
1220 uint16_t
1221 pgp_reader_pop_sum16(pgp_stream_t *stream)
1222 {
1223 	uint16_t	 sum;
1224 	sum16_t		*arg;
1225 
1226 	arg = pgp_reader_get_arg(pgp_readinfo(stream));
1227 	sum = arg->sum;
1228 	pgp_reader_pop(stream);
1229 	free(arg);
1230 	return sum;
1231 }
1232 
1233 /* small useful functions for setting the file-level debugging levels */
1234 /* if the debugv list contains the filename in question, we're debugging it */
1235 
1236 enum {
1237 	MAX_DEBUG_NAMES = 32
1238 };
1239 
1240 static int      debugc;
1241 static char    *debugv[MAX_DEBUG_NAMES];
1242 
1243 /* set the debugging level per filename */
1244 int
1245 pgp_set_debug_level(const char *f)
1246 {
1247 	const char     *name;
1248 	int             i;
1249 
1250 	if (f == NULL) {
1251 		f = "all";
1252 	}
1253 	if ((name = strrchr(f, '/')) == NULL) {
1254 		name = f;
1255 	} else {
1256 		name += 1;
1257 	}
1258 	for (i = 0; i < debugc && i < MAX_DEBUG_NAMES; i++) {
1259 		if (strcmp(debugv[i], name) == 0) {
1260 			return 1;
1261 		}
1262 	}
1263 	if (i == MAX_DEBUG_NAMES) {
1264 		return 0;
1265 	}
1266 	debugv[debugc++] = netpgp_strdup(name);
1267 	return 1;
1268 }
1269 
1270 /* get the debugging level per filename */
1271 int
1272 pgp_get_debug_level(const char *f)
1273 {
1274 	const char     *name;
1275 	int             i;
1276 
1277 	if ((name = strrchr(f, '/')) == NULL) {
1278 		name = f;
1279 	} else {
1280 		name += 1;
1281 	}
1282 	for (i = 0; i < debugc; i++) {
1283 		if (strcmp(debugv[i], "all") == 0 ||
1284 		    strcmp(debugv[i], name) == 0) {
1285 			return 1;
1286 		}
1287 	}
1288 	return 0;
1289 }
1290 
1291 /* return the version for the library */
1292 const char *
1293 pgp_get_info(const char *type)
1294 {
1295 	if (strcmp(type, "version") == 0) {
1296 		return NETPGP_VERSION_STRING;
1297 	}
1298 	if (strcmp(type, "maintainer") == 0) {
1299 		return NETPGP_MAINTAINER;
1300 	}
1301 	return "[unknown]";
1302 }
1303 
1304 /* local version of asprintf so we don't have to play autoconf games */
1305 int
1306 pgp_asprintf(char **ret, const char *fmt, ...)
1307 {
1308 	va_list args;
1309 	char    buf[120 * 1024];	/* XXX - "huge" buffer on stack */
1310 	int     cc;
1311 
1312 	va_start(args, fmt);
1313 	cc = vsnprintf(buf, sizeof(buf), fmt, args);
1314 	va_end(args);
1315 	if ((*ret = calloc(1, (size_t)(cc + 1))) == NULL) {
1316 		*ret = NULL;
1317 		return -1;
1318 	}
1319 	(void) memcpy(*ret, buf, (size_t)cc);
1320 	(*ret)[cc] = 0x0;
1321 	return cc;
1322 }
1323 
1324 void
1325 netpgp_log(const char *fmt, ...)
1326 {
1327 	va_list	 vp;
1328 	time_t	 t;
1329 	char	 buf[BUFSIZ * 2];
1330 	int	 cc;
1331 
1332 	(void) time(&t);
1333 	cc = snprintf(buf, sizeof(buf), "%.24s: netpgp: ", ctime(&t));
1334 	va_start(vp, fmt);
1335 	(void) vsnprintf(&buf[cc], sizeof(buf) - (size_t)cc, fmt, vp);
1336 	va_end(vp);
1337 	/* do something with message */
1338 	/* put into log buffer? */
1339 }
1340 
1341 /* portable replacement for strdup(3) */
1342 char *
1343 netpgp_strdup(const char *s)
1344 {
1345 	size_t	 len;
1346 	char	*cp;
1347 
1348 	len = strlen(s);
1349 	if ((cp = calloc(1, len + 1)) != NULL) {
1350 		(void) memcpy(cp, s, len);
1351 		cp[len] = 0x0;
1352 	}
1353 	return cp;
1354 }
1355 
1356 /* portable replacement for strcasecmp(3) */
1357 int
1358 netpgp_strcasecmp(const char *s1, const char *s2)
1359 {
1360 	int	n;
1361 
1362 	for (n = 0 ; *s1 && *s2 && (n = tolower((uint8_t)*s1) - tolower((uint8_t)*s2)) == 0 ; s1++, s2++) {
1363 	}
1364 	return n;
1365 }
1366