xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/misc.c (revision d427c17d1eac306eaa82ecccc703ac5991592c03)
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.30 2010/05/25 01:05:10 agc Exp $");
61 #endif
62 
63 #include <sys/types.h>
64 #include <sys/stat.h>
65 #include <sys/mman.h>
66 
67 #include <stdarg.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 
72 #ifdef HAVE_UNISTD_H
73 #include <unistd.h>
74 #endif
75 
76 #ifdef HAVE_OPENSSL_RAND_H
77 #include <openssl/rand.h>
78 #endif
79 
80 #include "errors.h"
81 #include "packet.h"
82 #include "crypto.h"
83 #include "create.h"
84 #include "fastctype.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 	__ops_keyring_t  *keyring;
102 } accumulate_t;
103 
104 /**
105  * \ingroup Core_Callbacks
106  */
107 static __ops_cb_ret_t
108 accumulate_cb(const __ops_packet_t *pkt, __ops_cbdata_t *cbinfo)
109 {
110 	const __ops_contents_t	*content = &pkt->u;
111 	__ops_keyring_t		*keyring;
112 	accumulate_t		*accumulate;
113 
114 	accumulate = __ops_callback_arg(cbinfo);
115 	keyring = accumulate->keyring;
116 	switch (pkt->tag) {
117 	case OPS_PTAG_CT_PUBLIC_KEY:
118 	case OPS_PTAG_CT_SECRET_KEY:
119 	case OPS_PTAG_CT_ENCRYPTED_SECRET_KEY:
120 		if (__ops_get_debug_level(__FILE__)) {
121 			(void) fprintf(stderr, "Creating key %u - tag %u\n",
122 				keyring->keyc, pkt->tag);
123 		}
124 		if (pkt->tag == OPS_PTAG_CT_PUBLIC_KEY) {
125 			__ops_add_to_pubring(keyring, &content->pubkey);
126 		} else {
127 			__ops_add_to_secring(keyring, &content->seckey);
128 		}
129 		return OPS_KEEP_MEMORY;
130 	case OPS_PTAG_CT_USER_ID:
131 		if (__ops_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 (keyring->keyc > 0) {
137 			__ops_add_userid(&keyring->keys[keyring->keyc - 1],
138 						content->userid);
139 			return OPS_KEEP_MEMORY;
140 		}
141 		OPS_ERROR(cbinfo->errors, OPS_E_P_NO_USERID, "No userid found");
142 		return OPS_KEEP_MEMORY;
143 
144 	case OPS_PARSER_PACKET_END:
145 		if (keyring->keyc > 0) {
146 			__ops_add_subpacket(&keyring->keys[keyring->keyc - 1],
147 						&content->packet);
148 			return OPS_KEEP_MEMORY;
149 		}
150 		return OPS_RELEASE_MEMORY;
151 
152 	case OPS_PARSER_ERROR:
153 		(void) fprintf(stderr, "Error: %s\n", content->error);
154 		return OPS_FINISHED;
155 
156 	case OPS_PARSER_ERRCODE:
157 		(void) fprintf(stderr, "parse error: %s\n",
158 				__ops_errcode(content->errcode.errcode));
159 		break;
160 
161 	default:
162 		break;
163 	}
164 
165 	/* XXX: we now exclude so many things, we should either drop this or */
166 	/* do something to pass on copies of the stuff we keep */
167 	return __ops_stacked_callback(pkt, cbinfo);
168 }
169 
170 /**
171  * \ingroup Core_Parse
172  *
173  * Parse packets from an input stream until EOF or error.
174  *
175  * Key data found in the parsed data is added to #keyring.
176  *
177  * \param keyring Pointer to an existing keyring
178  * \param parse Options to use when parsing
179 */
180 int
181 __ops_parse_and_accumulate(__ops_keyring_t *keyring, __ops_stream_t *parse)
182 {
183 	accumulate_t	accumulate;
184 	const int	printerrors = 1;
185 	int             ret;
186 
187 	if (parse->readinfo.accumulate) {
188 		(void) fprintf(stderr,
189 			"__ops_parse_and_accumulate: already init\n");
190 		return 0;
191 	}
192 
193 	(void) memset(&accumulate, 0x0, sizeof(accumulate));
194 
195 	accumulate.keyring = keyring;
196 
197 	__ops_callback_push(parse, accumulate_cb, &accumulate);
198 	parse->readinfo.accumulate = 1;
199 	ret = __ops_parse(parse, !printerrors);
200 
201 	return ret;
202 }
203 
204 
205 /** \file
206  * \brief Error Handling
207  */
208 #define ERRNAME(code)	{ code, #code }
209 
210 static __ops_errcode_name_map_t errcode_name_map[] = {
211 	ERRNAME(OPS_E_OK),
212 	ERRNAME(OPS_E_FAIL),
213 	ERRNAME(OPS_E_SYSTEM_ERROR),
214 	ERRNAME(OPS_E_UNIMPLEMENTED),
215 
216 	ERRNAME(OPS_E_R),
217 	ERRNAME(OPS_E_R_READ_FAILED),
218 	ERRNAME(OPS_E_R_EARLY_EOF),
219 	ERRNAME(OPS_E_R_BAD_FORMAT),
220 	ERRNAME(OPS_E_R_UNCONSUMED_DATA),
221 
222 	ERRNAME(OPS_E_W),
223 	ERRNAME(OPS_E_W_WRITE_FAILED),
224 	ERRNAME(OPS_E_W_WRITE_TOO_SHORT),
225 
226 	ERRNAME(OPS_E_P),
227 	ERRNAME(OPS_E_P_NOT_ENOUGH_DATA),
228 	ERRNAME(OPS_E_P_UNKNOWN_TAG),
229 	ERRNAME(OPS_E_P_PACKET_CONSUMED),
230 	ERRNAME(OPS_E_P_MPI_FORMAT_ERROR),
231 
232 	ERRNAME(OPS_E_C),
233 
234 	ERRNAME(OPS_E_V),
235 	ERRNAME(OPS_E_V_BAD_SIGNATURE),
236 	ERRNAME(OPS_E_V_NO_SIGNATURE),
237 	ERRNAME(OPS_E_V_UNKNOWN_SIGNER),
238 
239 	ERRNAME(OPS_E_ALG),
240 	ERRNAME(OPS_E_ALG_UNSUPPORTED_SYMMETRIC_ALG),
241 	ERRNAME(OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG),
242 	ERRNAME(OPS_E_ALG_UNSUPPORTED_SIGNATURE_ALG),
243 	ERRNAME(OPS_E_ALG_UNSUPPORTED_HASH_ALG),
244 
245 	ERRNAME(OPS_E_PROTO),
246 	ERRNAME(OPS_E_PROTO_BAD_SYMMETRIC_DECRYPT),
247 	ERRNAME(OPS_E_PROTO_UNKNOWN_SS),
248 	ERRNAME(OPS_E_PROTO_CRITICAL_SS_IGNORED),
249 	ERRNAME(OPS_E_PROTO_BAD_PUBLIC_KEY_VRSN),
250 	ERRNAME(OPS_E_PROTO_BAD_SIGNATURE_VRSN),
251 	ERRNAME(OPS_E_PROTO_BAD_ONE_PASS_SIG_VRSN),
252 	ERRNAME(OPS_E_PROTO_BAD_PKSK_VRSN),
253 	ERRNAME(OPS_E_PROTO_DECRYPTED_MSG_WRONG_LEN),
254 	ERRNAME(OPS_E_PROTO_BAD_SK_CHECKSUM),
255 
256 	{0x00, NULL},		/* this is the end-of-array marker */
257 };
258 
259 /**
260  * \ingroup Core_Errors
261  * \brief returns error code name
262  * \param errcode
263  * \return error code name or "Unknown"
264  */
265 const char     *
266 __ops_errcode(const __ops_errcode_t errcode)
267 {
268 	return (__ops_str_from_map((int) errcode,
269 			(__ops_map_t *) errcode_name_map));
270 }
271 
272 /* generic grab new storage function */
273 void *
274 __ops_new(size_t size)
275 {
276 	void	*vp;
277 
278 	if ((vp = calloc(1, size)) == NULL) {
279 		(void) fprintf(stderr,
280 			"allocation failure for %" PRIsize "u bytes", size);
281 	}
282 	return vp;
283 }
284 
285 /**
286  * \ingroup Core_Errors
287  * \brief Pushes the given error on the given errorstack
288  * \param errstack Error stack to use
289  * \param errcode Code of error to push
290  * \param sys_errno System errno (used if errcode=OPS_E_SYSTEM_ERROR)
291  * \param file Source filename where error occurred
292  * \param line Line in source file where error occurred
293  * \param fmt Comment
294  *
295  */
296 
297 void
298 __ops_push_error(__ops_error_t **errstack, __ops_errcode_t errcode,
299 		int sys_errno, const char *file, int line, const char *fmt,...)
300 {
301 	/* first get the varargs and generate the comment */
302 	__ops_error_t  *err;
303 	unsigned	maxbuf = 128;
304 	va_list		args;
305 	char           *comment;
306 
307 	if ((comment = calloc(1, maxbuf + 1)) == NULL) {
308 		(void) fprintf(stderr, "calloc comment failure\n");
309 		return;
310 	}
311 
312 	va_start(args, fmt);
313 	vsnprintf(comment, maxbuf + 1, fmt, args);
314 	va_end(args);
315 
316 	/* alloc a new error and add it to the top of the stack */
317 
318 	if ((err = calloc(1, sizeof(*err))) == NULL) {
319 		(void) fprintf(stderr, "calloc comment failure\n");
320 		return;
321 	}
322 
323 	err->next = *errstack;
324 	*errstack = err;
325 
326 	/* fill in the details */
327 	err->errcode = errcode;
328 	err->sys_errno = sys_errno;
329 	err->file = file;
330 	err->line = line;
331 
332 	err->comment = comment;
333 }
334 
335 /**
336 \ingroup Core_Errors
337 \brief print this error
338 \param err Error to print
339 */
340 void
341 __ops_print_error(__ops_error_t *err)
342 {
343 	printf("%s:%d: ", err->file, err->line);
344 	if (err->errcode == OPS_E_SYSTEM_ERROR) {
345 		printf("system error %d returned from %s()\n", err->sys_errno,
346 		       err->comment);
347 	} else {
348 		printf("%s, %s\n", __ops_errcode(err->errcode), err->comment);
349 	}
350 }
351 
352 /**
353 \ingroup Core_Errors
354 \brief Print all errors on stack
355 \param errstack Error stack to print
356 */
357 void
358 __ops_print_errors(__ops_error_t *errstack)
359 {
360 	__ops_error_t    *err;
361 
362 	for (err = errstack; err != NULL; err = err->next) {
363 		__ops_print_error(err);
364 	}
365 }
366 
367 /**
368 \ingroup Core_Errors
369 \brief Return 1 if given error is present anywhere on stack
370 \param errstack Error stack to check
371 \param errcode Error code to look for
372 \return 1 if found; else 0
373 */
374 int
375 __ops_has_error(__ops_error_t *errstack, __ops_errcode_t errcode)
376 {
377 	__ops_error_t    *err;
378 
379 	for (err = errstack; err != NULL; err = err->next) {
380 		if (err->errcode == errcode) {
381 			return 1;
382 		}
383 	}
384 	return 0;
385 }
386 
387 /**
388 \ingroup Core_Errors
389 \brief Frees all errors on stack
390 \param errstack Error stack to free
391 */
392 void
393 __ops_free_errors(__ops_error_t *errstack)
394 {
395 	__ops_error_t    *next;
396 
397 	while (errstack != NULL) {
398 		next = errstack->next;
399 		free(errstack->comment);
400 		free(errstack);
401 		errstack = next;
402 	}
403 }
404 
405 /** \file
406  */
407 
408 /**
409  * \ingroup Core_Keys
410  * \brief Calculate a public key fingerprint.
411  * \param fp Where to put the calculated fingerprint
412  * \param key The key for which the fingerprint is calculated
413  */
414 
415 void
416 __ops_fingerprint(__ops_fingerprint_t *fp, const __ops_pubkey_t *key)
417 {
418 	if (key->version == 2 || key->version == 3) {
419 		unsigned char  *bn;
420 		size_t		n;
421 		__ops_hash_t	md5;
422 
423 		if (key->alg != OPS_PKA_RSA &&
424 		    key->alg != OPS_PKA_RSA_ENCRYPT_ONLY &&
425 		    key->alg != OPS_PKA_RSA_SIGN_ONLY) {
426 			(void) fprintf(stderr,
427 				"__ops_fingerprint: bad algorithm\n");
428 			return;
429 		}
430 
431 		__ops_hash_md5(&md5);
432 		if (!md5.init(&md5)) {
433 			(void) fprintf(stderr,
434 				"__ops_fingerprint: bad md5 alloc\n");
435 				return;
436 		}
437 
438 		n = (size_t) BN_num_bytes(key->key.rsa.n);
439 		if ((bn = calloc(1, n)) == NULL) {
440 			(void) fprintf(stderr,
441 				"__ops_fingerprint: bad bn alloc\n");
442 			return;
443 		}
444 		BN_bn2bin(key->key.rsa.n, bn);
445 		md5.add(&md5, bn, n);
446 		free(bn);
447 
448 		n = (size_t) BN_num_bytes(key->key.rsa.e);
449 		if ((bn = calloc(1, n)) == NULL) {
450 			(void) fprintf(stderr,
451 				"__ops_fingerprint: bad bn alloc 2\n");
452 			return;
453 		}
454 		BN_bn2bin(key->key.rsa.e, bn);
455 		md5.add(&md5, bn, n);
456 		free(bn);
457 
458 		md5.finish(&md5, fp->fingerprint);
459 		fp->length = 16;
460 	} else {
461 		__ops_memory_t	*mem = __ops_memory_new();
462 		__ops_hash_t	 sha1;
463 		size_t		 len;
464 
465 		__ops_build_pubkey(mem, key, 0);
466 
467 		if (__ops_get_debug_level(__FILE__)) {
468 			fprintf(stderr, "-> creating key fingerprint\n");
469 		}
470 		__ops_hash_sha1(&sha1);
471 		if (!sha1.init(&sha1)) {
472 			(void) fprintf(stderr,
473 				"__ops_fingerprint: bad sha1 alloc\n");
474 			return;
475 		}
476 
477 		len = __ops_mem_len(mem);
478 
479 		__ops_hash_add_int(&sha1, 0x99, 1);
480 		__ops_hash_add_int(&sha1, len, 2);
481 		sha1.add(&sha1, __ops_mem_data(mem), len);
482 		sha1.finish(&sha1, fp->fingerprint);
483 
484 		if (__ops_get_debug_level(__FILE__)) {
485 			fprintf(stderr, "<- finished making key fingerprint\n");
486 		}
487 		fp->length = OPS_FINGERPRINT_SIZE;
488 
489 		__ops_memory_free(mem);
490 	}
491 }
492 
493 /**
494  * \ingroup Core_Keys
495  * \brief Calculate the Key ID from the public key.
496  * \param keyid Space for the calculated ID to be stored
497  * \param key The key for which the ID is calculated
498  */
499 
500 void
501 __ops_keyid(uint8_t *keyid, const size_t idlen, const __ops_pubkey_t *key)
502 {
503 	__ops_fingerprint_t finger;
504 
505 	if (key->version == 2 || key->version == 3) {
506 		unsigned	n;
507 		uint8_t		bn[NETPGP_BUFSIZ];
508 
509 		n = (unsigned) BN_num_bytes(key->key.rsa.n);
510 		if (n > sizeof(bn)) {
511 			(void) fprintf(stderr, "__ops_keyid: bad num bytes\n");
512 			return;
513 		}
514 		if (key->alg != OPS_PKA_RSA &&
515 		    key->alg != OPS_PKA_RSA_ENCRYPT_ONLY &&
516 		    key->alg != OPS_PKA_RSA_SIGN_ONLY) {
517 			(void) fprintf(stderr, "__ops_keyid: bad algorithm\n");
518 			return;
519 		}
520 		BN_bn2bin(key->key.rsa.n, bn);
521 		(void) memcpy(keyid, bn + n - idlen, idlen);
522 	} else {
523 		__ops_fingerprint(&finger, key);
524 		(void) memcpy(keyid,
525 				finger.fingerprint + finger.length - idlen,
526 				idlen);
527 	}
528 }
529 
530 /**
531 \ingroup Core_Hashes
532 \brief Add to the hash
533 \param hash Hash to add to
534 \param n Int to add
535 \param length Length of int in bytes
536 */
537 void
538 __ops_hash_add_int(__ops_hash_t *hash, unsigned n, unsigned length)
539 {
540 	uint8_t   c;
541 
542 	while (length--) {
543 		c = n >> (length * 8);
544 		hash->add(hash, &c, 1);
545 	}
546 }
547 
548 /**
549 \ingroup Core_Hashes
550 \brief Setup hash for given hash algorithm
551 \param hash Hash to set up
552 \param alg Hash algorithm to use
553 */
554 void
555 __ops_hash_any(__ops_hash_t *hash, __ops_hash_alg_t alg)
556 {
557 	switch (alg) {
558 	case OPS_HASH_MD5:
559 		__ops_hash_md5(hash);
560 		break;
561 
562 	case OPS_HASH_SHA1:
563 		__ops_hash_sha1(hash);
564 		break;
565 
566 	case OPS_HASH_SHA256:
567 		__ops_hash_sha256(hash);
568 		break;
569 
570 	case OPS_HASH_SHA384:
571 		__ops_hash_sha384(hash);
572 		break;
573 
574 	case OPS_HASH_SHA512:
575 		__ops_hash_sha512(hash);
576 		break;
577 
578 	case OPS_HASH_SHA224:
579 		__ops_hash_sha224(hash);
580 		break;
581 
582 	default:
583 		(void) fprintf(stderr, "__ops_hash_any: bad algorithm\n");
584 	}
585 }
586 
587 /**
588 \ingroup Core_Hashes
589 \brief Returns size of hash for given hash algorithm
590 \param alg Hash algorithm to use
591 \return Size of hash algorithm in bytes
592 */
593 unsigned
594 __ops_hash_size(__ops_hash_alg_t alg)
595 {
596 	switch (alg) {
597 	case OPS_HASH_MD5:
598 		return 16;
599 
600 	case OPS_HASH_SHA1:
601 		return 20;
602 
603 	case OPS_HASH_SHA256:
604 		return 32;
605 
606 	case OPS_HASH_SHA224:
607 		return 28;
608 
609 	case OPS_HASH_SHA512:
610 		return 64;
611 
612 	case OPS_HASH_SHA384:
613 		return 48;
614 
615 	default:
616 		(void) fprintf(stderr, "__ops_hash_size: bad algorithm\n");
617 	}
618 
619 	return 0;
620 }
621 
622 /**
623 \ingroup Core_Hashes
624 \brief Returns hash enum corresponding to given string
625 \param hash Text name of hash algorithm i.e. "SHA1"
626 \returns Corresponding enum i.e. OPS_HASH_SHA1
627 */
628 __ops_hash_alg_t
629 __ops_str_to_hash_alg(const char *hash)
630 {
631 	if (hash == NULL) {
632 		return OPS_DEFAULT_HASH_ALGORITHM;
633 	}
634 	if (netpgp_strcasecmp(hash, "SHA1") == 0) {
635 		return OPS_HASH_SHA1;
636 	}
637 	if (netpgp_strcasecmp(hash, "MD5") == 0) {
638 		return OPS_HASH_MD5;
639 	}
640 	if (netpgp_strcasecmp(hash, "SHA256") == 0) {
641 		return OPS_HASH_SHA256;
642 	}
643 	/*
644         if (netpgp_strcasecmp(hash,"SHA224") == 0) {
645 		return OPS_HASH_SHA224;
646 	}
647         */
648 	if (netpgp_strcasecmp(hash, "SHA512") == 0) {
649 		return OPS_HASH_SHA512;
650 	}
651 	if (netpgp_strcasecmp(hash, "SHA384") == 0) {
652 		return OPS_HASH_SHA384;
653 	}
654 	return OPS_HASH_UNKNOWN;
655 }
656 
657 /**
658 \ingroup Core_Hashes
659 \brief Hash given data
660 \param out Where to write the hash
661 \param alg Hash algorithm to use
662 \param in Data to hash
663 \param length Length of data
664 \return Size of hash created
665 */
666 unsigned
667 __ops_hash(uint8_t *out, __ops_hash_alg_t alg, const void *in, size_t length)
668 {
669 	__ops_hash_t      hash;
670 
671 	__ops_hash_any(&hash, alg);
672 	if (!hash.init(&hash)) {
673 		(void) fprintf(stderr, "__ops_hash: bad alloc\n");
674 		/* we'll just continue here - don't want to return a 0 hash */
675 		/* XXX - agc - no way to return failure */
676 	}
677 	hash.add(&hash, in, length);
678 	return hash.finish(&hash, out);
679 }
680 
681 /**
682 \ingroup Core_Hashes
683 \brief Calculate hash for MDC packet
684 \param preamble Preamble to hash
685 \param sz_preamble Size of preamble
686 \param plaintext Plaintext to hash
687 \param sz_plaintext Size of plaintext
688 \param hashed Resulting hash
689 */
690 void
691 __ops_calc_mdc_hash(const uint8_t *preamble,
692 			const size_t sz_preamble,
693 			const uint8_t *plaintext,
694 			const unsigned sz_plaintext,
695 			uint8_t *hashed)
696 {
697 	__ops_hash_t	hash;
698 	uint8_t		c;
699 
700 	if (__ops_get_debug_level(__FILE__)) {
701 		(void) fprintf(stderr, "__ops_calc_mdc_hash():\npreamble: ");
702 		hexdump(stderr, preamble, sz_preamble, " ");
703 		(void) fprintf(stderr, "\nplaintext (len=%u): ", sz_plaintext);
704 		hexdump(stderr, plaintext, sz_plaintext, " ");
705 		(void) fprintf(stderr, "\n");
706 	}
707 	/* init */
708 	__ops_hash_any(&hash, OPS_HASH_SHA1);
709 	if (!hash.init(&hash)) {
710 		(void) fprintf(stderr, "__ops_calc_mdc_hash: bad alloc\n");
711 		/* we'll just continue here - it will die anyway */
712 		/* agc - XXX - no way to return failure */
713 	}
714 
715 	/* preamble */
716 	hash.add(&hash, preamble, sz_preamble);
717 	/* plaintext */
718 	hash.add(&hash, plaintext, sz_plaintext);
719 	/* MDC packet tag */
720 	c = MDC_PKT_TAG;
721 	hash.add(&hash, &c, 1);
722 	/* MDC packet len */
723 	c = OPS_SHA1_HASH_SIZE;
724 	hash.add(&hash, &c, 1);
725 
726 	/* finish */
727 	hash.finish(&hash, hashed);
728 
729 	if (__ops_get_debug_level(__FILE__)) {
730 		(void) fprintf(stderr, "\nhashed (len=%d): ", OPS_SHA1_HASH_SIZE);
731 		hexdump(stderr, hashed, OPS_SHA1_HASH_SIZE, " ");
732 		(void) fprintf(stderr, "\n");
733 	}
734 }
735 
736 /**
737 \ingroup HighLevel_Supported
738 \brief Is this Hash Algorithm supported?
739 \param hash_alg Hash Algorithm to check
740 \return 1 if supported; else 0
741 */
742 unsigned
743 __ops_is_hash_alg_supported(const __ops_hash_alg_t *hash_alg)
744 {
745 	switch (*hash_alg) {
746 	case OPS_HASH_MD5:
747 	case OPS_HASH_SHA1:
748 	case OPS_HASH_SHA256:
749 		return 1;
750 
751 	default:
752 		return 0;
753 	}
754 }
755 
756 void
757 __ops_random(void *dest, size_t length)
758 {
759 	RAND_bytes(dest, (int)length);
760 }
761 
762 /**
763 \ingroup HighLevel_Memory
764 \brief Memory to initialise
765 \param mem memory to initialise
766 \param needed Size to initialise to
767 */
768 void
769 __ops_memory_init(__ops_memory_t *mem, size_t needed)
770 {
771 	uint8_t	*temp;
772 
773 	mem->length = 0;
774 	if (mem->buf) {
775 		if (mem->allocated < needed) {
776 			if ((temp = realloc(mem->buf, needed)) == NULL) {
777 				(void) fprintf(stderr, "__ops_memory_init: bad alloc\n");
778 			} else {
779 				mem->buf = temp;
780 				mem->allocated = needed;
781 			}
782 		}
783 	} else {
784 		if ((mem->buf = calloc(1, needed)) == NULL) {
785 			(void) fprintf(stderr, "__ops_memory_init: bad alloc\n");
786 		} else {
787 			mem->allocated = needed;
788 		}
789 	}
790 }
791 
792 /**
793 \ingroup HighLevel_Memory
794 \brief Pad memory to required length
795 \param mem Memory to use
796 \param length New size
797 */
798 void
799 __ops_memory_pad(__ops_memory_t *mem, size_t length)
800 {
801 	uint8_t	*temp;
802 
803 	if (mem->allocated < mem->length) {
804 		(void) fprintf(stderr, "__ops_memory_pad: bad alloc in\n");
805 		return;
806 	}
807 	if (mem->allocated < mem->length + length) {
808 		mem->allocated = mem->allocated * 2 + length;
809 		temp = realloc(mem->buf, mem->allocated);
810 		if (temp == NULL) {
811 			(void) fprintf(stderr, "__ops_memory_pad: bad alloc\n");
812 		} else {
813 			mem->buf = temp;
814 		}
815 	}
816 	if (mem->allocated < mem->length + length) {
817 		(void) fprintf(stderr, "__ops_memory_pad: bad alloc out\n");
818 	}
819 }
820 
821 /**
822 \ingroup HighLevel_Memory
823 \brief Add data to memory
824 \param mem Memory to which to add
825 \param src Data to add
826 \param length Length of data to add
827 */
828 void
829 __ops_memory_add(__ops_memory_t *mem, const uint8_t *src, size_t length)
830 {
831 	__ops_memory_pad(mem, length);
832 	(void) memcpy(mem->buf + mem->length, src, length);
833 	mem->length += length;
834 }
835 
836 /* XXX: this could be refactored via the writer, but an awful lot of */
837 /* hoops to jump through for 2 lines of code! */
838 void
839 __ops_memory_place_int(__ops_memory_t *mem, unsigned offset, unsigned n,
840 		     size_t length)
841 {
842 	if (mem->allocated < offset + length) {
843 		(void) fprintf(stderr,
844 			"__ops_memory_place_int: bad alloc\n");
845 	} else {
846 		while (length-- > 0) {
847 			mem->buf[offset++] = n >> (length * 8);
848 		}
849 	}
850 }
851 
852 /**
853  * \ingroup HighLevel_Memory
854  * \brief Retains allocated memory and set length of stored data to zero.
855  * \param mem Memory to clear
856  * \sa __ops_memory_release()
857  * \sa __ops_memory_free()
858  */
859 void
860 __ops_memory_clear(__ops_memory_t *mem)
861 {
862 	mem->length = 0;
863 }
864 
865 /**
866 \ingroup HighLevel_Memory
867 \brief Free memory and associated data
868 \param mem Memory to free
869 \note This does not free mem itself
870 \sa __ops_memory_clear()
871 \sa __ops_memory_free()
872 */
873 void
874 __ops_memory_release(__ops_memory_t *mem)
875 {
876 	if (mem->mmapped) {
877 		(void) munmap(mem->buf, mem->length);
878 	} else {
879 		free(mem->buf);
880 	}
881 	mem->buf = NULL;
882 	mem->length = 0;
883 }
884 
885 void
886 __ops_memory_make_packet(__ops_memory_t *out, __ops_content_enum tag)
887 {
888 	size_t          extra;
889 
890 	extra = (out->length < 192) ? 1 : (out->length < 8192 + 192) ? 2 : 5;
891 	__ops_memory_pad(out, extra + 1);
892 	memmove(out->buf + extra + 1, out->buf, out->length);
893 
894 	out->buf[0] = OPS_PTAG_ALWAYS_SET | OPS_PTAG_NEW_FORMAT | tag;
895 
896 	if (out->length < 192) {
897 		out->buf[1] = out->length;
898 	} else if (out->length < 8192 + 192) {
899 		out->buf[1] = ((out->length - 192) >> 8) + 192;
900 		out->buf[2] = out->length - 192;
901 	} else {
902 		out->buf[1] = 0xff;
903 		out->buf[2] = out->length >> 24;
904 		out->buf[3] = out->length >> 16;
905 		out->buf[4] = out->length >> 8;
906 		out->buf[5] = out->length;
907 	}
908 
909 	out->length += extra + 1;
910 }
911 
912 /**
913    \ingroup HighLevel_Memory
914    \brief Create a new zeroed __ops_memory_t
915    \return Pointer to new __ops_memory_t
916    \note Free using __ops_memory_free() after use.
917    \sa __ops_memory_free()
918 */
919 
920 __ops_memory_t   *
921 __ops_memory_new(void)
922 {
923 	return calloc(1, sizeof(__ops_memory_t));
924 }
925 
926 /**
927    \ingroup HighLevel_Memory
928    \brief Free memory ptr and associated memory
929    \param mem Memory to be freed
930    \sa __ops_memory_release()
931    \sa __ops_memory_clear()
932 */
933 
934 void
935 __ops_memory_free(__ops_memory_t *mem)
936 {
937 	__ops_memory_release(mem);
938 	free(mem);
939 }
940 
941 /**
942    \ingroup HighLevel_Memory
943    \brief Get length of data stored in __ops_memory_t struct
944    \return Number of bytes in data
945 */
946 size_t
947 __ops_mem_len(const __ops_memory_t *mem)
948 {
949 	return mem->length;
950 }
951 
952 /**
953    \ingroup HighLevel_Memory
954    \brief Get data stored in __ops_memory_t struct
955    \return Pointer to data
956 */
957 void *
958 __ops_mem_data(__ops_memory_t *mem)
959 {
960 	return mem->buf;
961 }
962 
963 /* read a gile into an __ops_memory_t */
964 int
965 __ops_mem_readfile(__ops_memory_t *mem, const char *f)
966 {
967 	struct stat	 st;
968 	FILE		*fp;
969 	int		 cc;
970 
971 	if ((fp = fopen(f, "rb")) == NULL) {
972 		(void) fprintf(stderr,
973 				"__ops_mem_readfile: can't open \"%s\"\n", f);
974 		return 0;
975 	}
976 	(void) fstat(fileno(fp), &st);
977 	mem->allocated = (size_t)st.st_size;
978 	mem->buf = mmap(NULL, mem->allocated, PROT_READ,
979 				MAP_PRIVATE | MAP_FILE, fileno(fp), 0);
980 	if (mem->buf == MAP_FAILED) {
981 		/* mmap failed for some reason - try to allocate memory */
982 		if ((mem->buf = calloc(1, mem->allocated)) == NULL) {
983 			(void) fprintf(stderr, "__ops_mem_readfile: calloc\n");
984 			(void) fclose(fp);
985 			return 0;
986 		}
987 		/* read into contents of mem */
988 		for (mem->length = 0 ;
989 		     (cc = read(fileno(fp), &mem->buf[mem->length],
990 					mem->allocated - mem->length)) > 0 ;
991 		     mem->length += (size_t)cc) {
992 		}
993 	} else {
994 		mem->length = mem->allocated;
995 		mem->mmapped = 1;
996 	}
997 	(void) fclose(fp);
998 	return (mem->allocated == mem->length);
999 }
1000 
1001 typedef struct {
1002 	uint16_t  sum;
1003 } sum16_t;
1004 
1005 
1006 /**
1007  * Searches the given map for the given type.
1008  * Returns a human-readable descriptive string if found,
1009  * returns NULL if not found
1010  *
1011  * It is the responsibility of the calling function to handle the
1012  * error case sensibly (i.e. don't just print out the return string.
1013  *
1014  */
1015 static const char *
1016 str_from_map_or_null(int type, __ops_map_t *map)
1017 {
1018 	__ops_map_t      *row;
1019 
1020 	for (row = map; row->string != NULL; row++) {
1021 		if (row->type == type) {
1022 			return row->string;
1023 		}
1024 	}
1025 	return NULL;
1026 }
1027 
1028 /**
1029  * \ingroup Core_Print
1030  *
1031  * Searches the given map for the given type.
1032  * Returns a readable string if found, "Unknown" if not.
1033  */
1034 
1035 const char     *
1036 __ops_str_from_map(int type, __ops_map_t *map)
1037 {
1038 	const char     *str;
1039 
1040 	str = str_from_map_or_null(type, map);
1041 	return (str) ? str : "Unknown";
1042 }
1043 
1044 void
1045 hexdump(FILE *fp, const uint8_t *src, size_t length, const char *sep)
1046 {
1047 	unsigned i;
1048 
1049 	for (i = 0 ; i < length ; i += 2) {
1050 		(void) fprintf(fp, "%02x", *src++);
1051 		(void) fprintf(fp, "%02x%s", *src++, sep);
1052 	}
1053 }
1054 
1055 /**
1056  * \ingroup HighLevel_Functions
1057  * \brief Closes down OpenPGP::SDK.
1058  *
1059  * Close down OpenPGP:SDK, release any resources under the control of
1060  * the library.
1061  */
1062 
1063 void
1064 __ops_finish(void)
1065 {
1066 	__ops_crypto_finish();
1067 }
1068 
1069 static int
1070 sum16_reader(void *dest_, size_t length, __ops_error_t **errors,
1071 	     __ops_reader_t *readinfo, __ops_cbdata_t *cbinfo)
1072 {
1073 	const uint8_t	*dest = dest_;
1074 	sum16_t		*arg = __ops_reader_get_arg(readinfo);
1075 	int		 r;
1076 	int		 n;
1077 
1078 	r = __ops_stacked_read(dest_, length, errors, readinfo, cbinfo);
1079 	if (r < 0) {
1080 		return r;
1081 	}
1082 	for (n = 0; n < r; ++n) {
1083 		arg->sum = (arg->sum + dest[n]) & 0xffff;
1084 	}
1085 	return r;
1086 }
1087 
1088 static void
1089 sum16_destroyer(__ops_reader_t *readinfo)
1090 {
1091 	free(__ops_reader_get_arg(readinfo));
1092 }
1093 
1094 /**
1095    \ingroup Internal_Readers_Sum16
1096    \param stream Parse settings
1097 */
1098 
1099 void
1100 __ops_reader_push_sum16(__ops_stream_t *stream)
1101 {
1102 	sum16_t    *arg;
1103 
1104 	if ((arg = calloc(1, sizeof(*arg))) == NULL) {
1105 		(void) fprintf(stderr, "__ops_reader_push_sum16: bad alloc\n");
1106 	} else {
1107 		__ops_reader_push(stream, sum16_reader, sum16_destroyer, arg);
1108 	}
1109 }
1110 
1111 /**
1112    \ingroup Internal_Readers_Sum16
1113    \param stream Parse settings
1114    \return sum
1115 */
1116 uint16_t
1117 __ops_reader_pop_sum16(__ops_stream_t *stream)
1118 {
1119 	uint16_t	 sum;
1120 	sum16_t		*arg;
1121 
1122 	arg = __ops_reader_get_arg(__ops_readinfo(stream));
1123 	sum = arg->sum;
1124 	__ops_reader_pop(stream);
1125 	free(arg);
1126 	return sum;
1127 }
1128 
1129 /* small useful functions for setting the file-level debugging levels */
1130 /* if the debugv list contains the filename in question, we're debugging it */
1131 
1132 enum {
1133 	MAX_DEBUG_NAMES = 32
1134 };
1135 
1136 static int      debugc;
1137 static char    *debugv[MAX_DEBUG_NAMES];
1138 
1139 /* set the debugging level per filename */
1140 int
1141 __ops_set_debug_level(const char *f)
1142 {
1143 	const char     *name;
1144 	int             i;
1145 
1146 	if (f == NULL) {
1147 		f = "all";
1148 	}
1149 	if ((name = strrchr(f, '/')) == NULL) {
1150 		name = f;
1151 	} else {
1152 		name += 1;
1153 	}
1154 	for (i = 0; i < debugc && i < MAX_DEBUG_NAMES; i++) {
1155 		if (strcmp(debugv[i], name) == 0) {
1156 			return 1;
1157 		}
1158 	}
1159 	if (i == MAX_DEBUG_NAMES) {
1160 		return 0;
1161 	}
1162 	debugv[debugc++] = netpgp_strdup(name);
1163 	return 1;
1164 }
1165 
1166 /* get the debugging level per filename */
1167 int
1168 __ops_get_debug_level(const char *f)
1169 {
1170 	const char     *name;
1171 	int             i;
1172 
1173 	if ((name = strrchr(f, '/')) == NULL) {
1174 		name = f;
1175 	} else {
1176 		name += 1;
1177 	}
1178 	for (i = 0; i < debugc; i++) {
1179 		if (strcmp(debugv[i], "all") == 0 ||
1180 		    strcmp(debugv[i], name) == 0) {
1181 			return 1;
1182 		}
1183 	}
1184 	return 0;
1185 }
1186 
1187 /* return the version for the library */
1188 const char *
1189 __ops_get_info(const char *type)
1190 {
1191 	if (strcmp(type, "version") == 0) {
1192 		return NETPGP_VERSION_STRING;
1193 	}
1194 	if (strcmp(type, "maintainer") == 0) {
1195 		return NETPGP_MAINTAINER;
1196 	}
1197 	return "[unknown]";
1198 }
1199 
1200 /* local version of asprintf so we don't have to play autoconf games */
1201 int
1202 __ops_asprintf(char **ret, const char *fmt, ...)
1203 {
1204 	va_list args;
1205 	char    buf[120 * 1024];	/* XXX - "huge" buffer on stack */
1206 	int     cc;
1207 
1208 	va_start(args, fmt);
1209 	cc = vsnprintf(buf, sizeof(buf), fmt, args);
1210 	va_end(args);
1211 	if ((*ret = calloc(1, (size_t)(cc + 1))) == NULL) {
1212 		*ret = NULL;
1213 		return -1;
1214 	}
1215 	(void) memcpy(*ret, buf, (size_t)cc);
1216 	(*ret)[cc] = 0x0;
1217 	return cc;
1218 }
1219 
1220 void
1221 netpgp_log(const char *fmt, ...)
1222 {
1223 	va_list	 vp;
1224 	time_t	 t;
1225 	char	 buf[BUFSIZ * 2];
1226 	int	 cc;
1227 
1228 	(void) time(&t);
1229 	cc = snprintf(buf, sizeof(buf), "%.24s: netpgp: ", ctime(&t));
1230 	va_start(vp, fmt);
1231 	(void) vsnprintf(&buf[cc], sizeof(buf) - (size_t)cc, fmt, vp);
1232 	va_end(vp);
1233 	/* do something with message */
1234 	/* put into log buffer? */
1235 }
1236 
1237 /* portable replacement for strdup(3) */
1238 char *
1239 netpgp_strdup(const char *s)
1240 {
1241 	size_t	 len;
1242 	char	*cp;
1243 
1244 	len = strlen(s);
1245 	if ((cp = calloc(1, len + 1)) != NULL) {
1246 		(void) memcpy(cp, s, len);
1247 		cp[len] = 0x0;
1248 	}
1249 	return cp;
1250 }
1251 
1252 /* portable replacement for strcasecmp(3) */
1253 int
1254 netpgp_strcasecmp(const char *s1, const char *s2)
1255 {
1256 	int	n;
1257 
1258 	for (n = 0 ; *s1 && *s2 && (n = tolower(*s1) - tolower(*s2)) == 0 ; s1++, s2++) {
1259 	}
1260 	return n;
1261 }
1262