xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/packet-parse.c (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
1 /*-
2  * Copyright (c) 2009 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Alistair Crooks (agc@NetBSD.org)
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 /*
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  * \brief Parser for OpenPGP packets
52  */
53 #include "config.h"
54 
55 #ifdef HAVE_SYS_CDEFS_H
56 #include <sys/cdefs.h>
57 #endif
58 
59 #if defined(__NetBSD__)
60 __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved.");
61 __RCSID("$NetBSD: packet-parse.c,v 1.52 2018/11/13 14:52:30 mlelstv Exp $");
62 #endif
63 
64 #include <sys/types.h>
65 #include <sys/param.h>
66 
67 #ifdef HAVE_OPENSSL_CAST_H
68 #include <openssl/cast.h>
69 #endif
70 
71 #include <stdarg.h>
72 #include <stdlib.h>
73 #include <string.h>
74 
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 
79 #ifdef HAVE_LIMITS_H
80 #include <limits.h>
81 #endif
82 
83 #include "packet.h"
84 #include "packet-parse.h"
85 #include "keyring.h"
86 #include "errors.h"
87 #include "packet-show.h"
88 #include "create.h"
89 #include "readerwriter.h"
90 #include "netpgpdefs.h"
91 #include "crypto.h"
92 #include "netpgpdigest.h"
93 
94 #define ERRP(cbinfo, cont, err)	do {					\
95 	cont.u.error = err;						\
96 	CALLBACK(PGP_PARSER_ERROR, cbinfo, &cont);			\
97 	return 0;							\
98 	/*NOTREACHED*/							\
99 } while(/*CONSTCOND*/0)
100 
101 /**
102  * limread_data reads the specified amount of the subregion's data
103  * into a data_t structure
104  *
105  * \param data	Empty structure which will be filled with data
106  * \param len	Number of octets to read
107  * \param subregion
108  * \param stream	How to parse
109  *
110  * \return 1 on success, 0 on failure
111  */
112 static int
113 limread_data(pgp_data_t *data, unsigned len,
114 		  pgp_region_t *subregion, pgp_stream_t *stream)
115 {
116 	data->len = len;
117 
118 	if (subregion->length - subregion->readc < len) {
119 		(void) fprintf(stderr, "limread_data: bad length\n");
120 		return 0;
121 	}
122 
123 	data->contents = calloc(1, data->len);
124 	if (!data->contents) {
125 		return 0;
126 	}
127 
128 	return pgp_limited_read(stream, data->contents, data->len, subregion,
129 			&stream->errors, &stream->readinfo, &stream->cbinfo);
130 }
131 
132 /**
133  * read_data reads the remainder of the subregion's data
134  * into a data_t structure
135  *
136  * \param data
137  * \param subregion
138  * \param stream
139  *
140  * \return 1 on success, 0 on failure
141  */
142 static int
143 read_data(pgp_data_t *data, pgp_region_t *region, pgp_stream_t *stream)
144 {
145 	int	cc;
146 
147 	cc = region->length - region->readc;
148 	return (cc >= 0) ? limread_data(data, (unsigned)cc, region, stream) : 0;
149 }
150 
151 /**
152  * Reads the remainder of the subregion as a string.
153  * It is the user's responsibility to free the memory allocated here.
154  */
155 
156 static int
157 read_unsig_str(uint8_t **str, pgp_region_t *subregion,
158 		     pgp_stream_t *stream)
159 {
160 	size_t	len;
161 
162 	len = subregion->length - subregion->readc;
163 	if ((*str = calloc(1, len + 1)) == NULL) {
164 		return 0;
165 	}
166 	if (len &&
167 	    !pgp_limited_read(stream, *str, len, subregion, &stream->errors,
168 				     &stream->readinfo, &stream->cbinfo)) {
169 		return 0;
170 	}
171 	(*str)[len] = '\0';
172 	return 1;
173 }
174 
175 static int
176 read_string(char **str, pgp_region_t *subregion, pgp_stream_t *stream)
177 {
178 	return read_unsig_str((uint8_t **) str, subregion, stream);
179 }
180 
181 void
182 pgp_init_subregion(pgp_region_t *subregion, pgp_region_t *region)
183 {
184 	(void) memset(subregion, 0x0, sizeof(*subregion));
185 	subregion->parent = region;
186 }
187 
188 /*
189  * XXX: replace pgp_ptag_t with something more appropriate for limiting reads
190  */
191 
192 /**
193  * low-level function to read data from reader function
194  *
195  * Use this function, rather than calling the reader directly.
196  *
197  * If the accumulate flag is set in *stream, the function
198  * adds the read data to the accumulated data, and updates
199  * the accumulated length. This is useful if, for example,
200  * the application wants access to the raw data as well as the
201  * parsed data.
202  *
203  * This function will also try to read the entire amount asked for, but not
204  * if it is over INT_MAX. Obviously many callers will know that they
205  * never ask for that much and so can avoid the extra complexity of
206  * dealing with return codes and filled-in lengths.
207  *
208  * \param *dest
209  * \param *plength
210  * \param flags
211  * \param *stream
212  *
213  * \return PGP_R_OK
214  * \return PGP_R_PARTIAL_READ
215  * \return PGP_R_EOF
216  * \return PGP_R_EARLY_EOF
217  *
218  * \sa #pgp_reader_ret_t for details of return codes
219  */
220 
221 static int
222 sub_base_read(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
223 	      pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
224 {
225 	size_t          n;
226 
227 	/* reading more than this would look like an error */
228 	if (length > INT_MAX)
229 		length = INT_MAX;
230 
231 	for (n = 0; n < length;) {
232 		int	r;
233 
234 		r = readinfo->reader(stream, (char *) dest + n, length - n, errors,
235 			readinfo, cbinfo);
236 		if (r > (int)(length - n)) {
237 			(void) fprintf(stderr, "sub_base_read: bad read\n");
238 			return 0;
239 		}
240 		if (r < 0) {
241 			return r;
242 		}
243 		if (r == 0) {
244 			break;
245 		}
246 		n += (unsigned)r;
247 	}
248 
249 	if (n == 0) {
250 		return 0;
251 	}
252 	if (readinfo->accumulate) {
253 		if (readinfo->asize < readinfo->alength) {
254 			(void) fprintf(stderr, "sub_base_read: bad size\n");
255 			return 0;
256 		}
257 		if (readinfo->alength + n > readinfo->asize) {
258 			uint8_t	*temp;
259 
260 			readinfo->asize = (readinfo->asize * 2) + (unsigned)n;
261 			temp = realloc(readinfo->accumulated, readinfo->asize);
262 			if (temp == NULL) {
263 				(void) fprintf(stderr,
264 					"sub_base_read: bad alloc\n");
265 				return 0;
266 			}
267 			readinfo->accumulated = temp;
268 		}
269 		if (readinfo->asize < readinfo->alength + n) {
270 			(void) fprintf(stderr, "sub_base_read: bad realloc\n");
271 			return 0;
272 		}
273 		(void) memcpy(readinfo->accumulated + readinfo->alength, dest,
274 				n);
275 	}
276 	/* we track length anyway, because it is used for packet offsets */
277 	readinfo->alength += (unsigned)n;
278 	/* and also the position */
279 	readinfo->position += (unsigned)n;
280 
281 	return (int)n;
282 }
283 
284 int
285 pgp_stacked_read(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
286 		 pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
287 {
288 	return sub_base_read(stream, dest, length, errors, readinfo->next, cbinfo);
289 }
290 
291 /* This will do a full read so long as length < MAX_INT */
292 static int
293 base_read(uint8_t *dest, size_t length, pgp_stream_t *stream)
294 {
295 	return sub_base_read(stream, dest, length, &stream->errors, &stream->readinfo,
296 			     &stream->cbinfo);
297 }
298 
299 /*
300  * Read a full size_t's worth. If the return is < than length, then
301  * *last_read tells you why - < 0 for an error, == 0 for EOF
302  */
303 
304 static size_t
305 full_read(pgp_stream_t *stream, uint8_t *dest,
306 		size_t length,
307 		int *last_read,
308 		pgp_error_t **errors,
309 		pgp_reader_t *readinfo,
310 		pgp_cbdata_t *cbinfo)
311 {
312 	size_t          t;
313 	int             r = 0;	/* preset in case some loon calls with length
314 				 * == 0 */
315 
316 	for (t = 0; t < length;) {
317 		r = sub_base_read(stream, dest + t, length - t, errors, readinfo,
318 				cbinfo);
319 		if (r <= 0) {
320 			*last_read = r;
321 			return t;
322 		}
323 		t += (size_t)r;
324 	}
325 
326 	*last_read = r;
327 
328 	return t;
329 }
330 
331 
332 
333 /** Read a scalar value of selected length from reader.
334  *
335  * Read an unsigned scalar value from reader in Big Endian representation.
336  *
337  * This function does not know or care about packet boundaries. It
338  * also assumes that an EOF is an error.
339  *
340  * \param *result	The scalar value is stored here
341  * \param *reader	Our reader
342  * \param length	How many bytes to read
343  * \return		1 on success, 0 on failure
344  */
345 static unsigned
346 _read_scalar(unsigned *result, unsigned length,
347 	     pgp_stream_t *stream)
348 {
349 	unsigned        t = 0;
350 
351 	if (length > sizeof(*result)) {
352 		(void) fprintf(stderr, "_read_scalar: bad length\n");
353 		return 0;
354 	}
355 
356 	while (length--) {
357 		uint8_t	c;
358 		int	r;
359 
360 		r = base_read(&c, 1, stream);
361 		if (r != 1)
362 			return 0;
363 		t = (t << 8) + c;
364 	}
365 
366 	*result = t;
367 	return 1;
368 }
369 
370 /**
371  * \ingroup Core_ReadPackets
372  * \brief Read bytes from a region within the packet.
373  *
374  * Read length bytes into the buffer pointed to by *dest.
375  * Make sure we do not read over the packet boundary.
376  * Updates the Packet Tag's pgp_ptag_t::readc.
377  *
378  * If length would make us read over the packet boundary, or if
379  * reading fails, we call the callback with an error.
380  *
381  * Note that if the region is indeterminate, this can return a short
382  * read - check region->last_read for the length. EOF is indicated by
383  * a success return and region->last_read == 0 in this case (for a
384  * region of known length, EOF is an error).
385  *
386  * This function makes sure to respect packet boundaries.
387  *
388  * \param dest		The destination buffer
389  * \param length	How many bytes to read
390  * \param region	Pointer to packet region
391  * \param errors    Error stack
392  * \param readinfo		Reader info
393  * \param cbinfo	Callback info
394  * \return		1 on success, 0 on error
395  */
396 unsigned
397 pgp_limited_read(pgp_stream_t *stream, uint8_t *dest,
398 			size_t length,
399 			pgp_region_t *region,
400 			pgp_error_t **errors,
401 			pgp_reader_t *readinfo,
402 			pgp_cbdata_t *cbinfo)
403 {
404 	size_t	r;
405 	int	lr;
406 
407 	if (!region->indeterminate &&
408 	    region->readc + length > region->length) {
409 		PGP_ERROR_1(errors, PGP_E_P_NOT_ENOUGH_DATA, "%s",
410 		    "Not enough data");
411 		return 0;
412 	}
413 	r = full_read(stream, dest, length, &lr, errors, readinfo, cbinfo);
414 	if (lr < 0) {
415 		PGP_ERROR_1(errors, PGP_E_R_READ_FAILED, "%s", "Read failed");
416 		return 0;
417 	}
418 	if (!region->indeterminate && r != length) {
419 		PGP_ERROR_1(errors, PGP_E_R_READ_FAILED, "%s", "Read failed");
420 		return 0;
421 	}
422 	region->last_read = (unsigned)r;
423 	do {
424 		region->readc += (unsigned)r;
425 		if (region->parent && region->length > region->parent->length) {
426 			(void) fprintf(stderr,
427 				"ops_limited_read: bad length\n");
428 			return 0;
429 		}
430 	} while ((region = region->parent) != NULL);
431 	return 1;
432 }
433 
434 /**
435    \ingroup Core_ReadPackets
436    \brief Call pgp_limited_read on next in stack
437 */
438 unsigned
439 pgp_stacked_limited_read(pgp_stream_t *stream, uint8_t *dest, unsigned length,
440 			 pgp_region_t *region,
441 			 pgp_error_t **errors,
442 			 pgp_reader_t *readinfo,
443 			 pgp_cbdata_t *cbinfo)
444 {
445 	return pgp_limited_read(stream, dest, length, region, errors,
446 				readinfo->next, cbinfo);
447 }
448 
449 static unsigned
450 limread(uint8_t *dest, unsigned length,
451 	     pgp_region_t *region, pgp_stream_t *info)
452 {
453 	return pgp_limited_read(info, dest, length, region, &info->errors,
454 				&info->readinfo, &info->cbinfo);
455 }
456 
457 static unsigned
458 exact_limread(uint8_t *dest, unsigned len,
459 		   pgp_region_t *region,
460 		   pgp_stream_t *stream)
461 {
462 	unsigned   ret;
463 
464 	stream->exact_read = 1;
465 	ret = limread(dest, len, region, stream);
466 	stream->exact_read = 0;
467 	return ret;
468 }
469 
470 /** Skip over length bytes of this packet.
471  *
472  * Calls limread() to skip over some data.
473  *
474  * This function makes sure to respect packet boundaries.
475  *
476  * \param length	How many bytes to skip
477  * \param *region	Pointer to packet region
478  * \param *stream	How to parse
479  * \return		1 on success, 0 on error (calls the cb with PGP_PARSER_ERROR in limread()).
480  */
481 static int
482 limskip(unsigned length, pgp_region_t *region, pgp_stream_t *stream)
483 {
484 	uint8_t   buf[NETPGP_BUFSIZ];
485 
486 	while (length > 0) {
487 		unsigned	n = length % NETPGP_BUFSIZ;
488 
489 		if (!limread(buf, n, region, stream)) {
490 			return 0;
491 		}
492 		length -= n;
493 	}
494 	return 1;
495 }
496 
497 /** Read a scalar.
498  *
499  * Read a big-endian scalar of length bytes, respecting packet
500  * boundaries (by calling limread() to read the raw data).
501  *
502  * This function makes sure to respect packet boundaries.
503  *
504  * \param *dest		The scalar value is stored here
505  * \param length	How many bytes make up this scalar (at most 4)
506  * \param *region	Pointer to current packet region
507  * \param *stream	How to parse
508  * \param *cb		The callback
509  * \return		1 on success, 0 on error (calls the cb with PGP_PARSER_ERROR in limread()).
510  *
511  * \see RFC4880 3.1
512  */
513 static int
514 limread_scalar(unsigned *dest,
515 			unsigned len,
516 			pgp_region_t *region,
517 			pgp_stream_t *stream)
518 {
519 	uint8_t		c[4] = "";
520 	unsigned        t;
521 	unsigned        n;
522 
523 	if (len > 4) {
524 		(void) fprintf(stderr, "limread_scalar: bad length\n");
525 		return 0;
526 	}
527 	/*LINTED*/
528 	if (/*CONSTCOND*/sizeof(*dest) < 4) {
529 		(void) fprintf(stderr, "limread_scalar: bad dest\n");
530 		return 0;
531 	}
532 	if (!limread(c, len, region, stream)) {
533 		return 0;
534 	}
535 	for (t = 0, n = 0; n < len; ++n) {
536 		t = (t << 8) + c[n];
537 	}
538 	*dest = t;
539 	return 1;
540 }
541 
542 /** Read a scalar.
543  *
544  * Read a big-endian scalar of length bytes, respecting packet
545  * boundaries (by calling limread() to read the raw data).
546  *
547  * The value read is stored in a size_t, which is a different size
548  * from an unsigned on some platforms.
549  *
550  * This function makes sure to respect packet boundaries.
551  *
552  * \param *dest		The scalar value is stored here
553  * \param length	How many bytes make up this scalar (at most 4)
554  * \param *region	Pointer to current packet region
555  * \param *stream	How to parse
556  * \param *cb		The callback
557  * \return		1 on success, 0 on error (calls the cb with PGP_PARSER_ERROR in limread()).
558  *
559  * \see RFC4880 3.1
560  */
561 static int
562 limread_size_t(size_t *dest,
563 				unsigned length,
564 				pgp_region_t *region,
565 				pgp_stream_t *stream)
566 {
567 	unsigned        tmp;
568 
569 	/*
570 	 * Note that because the scalar is at most 4 bytes, we don't care if
571 	 * size_t is bigger than usigned
572 	 */
573 	if (!limread_scalar(&tmp, length, region, stream))
574 		return 0;
575 
576 	*dest = tmp;
577 	return 1;
578 }
579 
580 /** Read a timestamp.
581  *
582  * Timestamps in OpenPGP are unix time, i.e. seconds since The Epoch (1.1.1970).  They are stored in an unsigned scalar
583  * of 4 bytes.
584  *
585  * This function reads the timestamp using limread_scalar().
586  *
587  * This function makes sure to respect packet boundaries.
588  *
589  * \param *dest		The timestamp is stored here
590  * \param *ptag		Pointer to current packet's Packet Tag.
591  * \param *reader	Our reader
592  * \param *cb		The callback
593  * \return		see limread_scalar()
594  *
595  * \see RFC4880 3.5
596  */
597 static int
598 limited_read_time(time_t *dest, pgp_region_t *region,
599 		  pgp_stream_t *stream)
600 {
601 	uint8_t	c;
602 	time_t	mytime = 0;
603 	int	i;
604 
605 	/*
606          * Cannot assume that time_t is 4 octets long -
607 	 * SunOS 5.10 and NetBSD both have 64-bit time_ts.
608          */
609 	if (/* CONSTCOND */sizeof(time_t) == 4) {
610 		return limread_scalar((unsigned *)(void *)dest, 4, region, stream);
611 	}
612 	for (i = 0; i < 4; i++) {
613 		if (!limread(&c, 1, region, stream)) {
614 			return 0;
615 		}
616 		mytime = (mytime << 8) + c;
617 	}
618 	*dest = mytime;
619 	return 1;
620 }
621 
622 /**
623  * \ingroup Core_MPI
624  * Read a multiprecision integer.
625  *
626  * Large numbers (multiprecision integers, MPI) are stored in OpenPGP in two parts.  First there is a 2 byte scalar
627  * indicating the length of the following MPI in Bits.  Then follow the bits that make up the actual number, most
628  * significant bits first (Big Endian).  The most significant bit in the MPI is supposed to be 1 (unless the MPI is
629  * encrypted - then it may be different as the bit count refers to the plain text but the bits are encrypted).
630  *
631  * Unused bits (i.e. those filling up the most significant byte from the left to the first bits that counts) are
632  * supposed to be cleared - I guess. XXX - does anything actually say so?
633  *
634  * This function makes sure to respect packet boundaries.
635  *
636  * \param **pgn		return the integer there - the BIGNUM is created by BN_bin2bn() and probably needs to be freed
637  * 				by the caller XXX right ben?
638  * \param *ptag		Pointer to current packet's Packet Tag.
639  * \param *reader	Our reader
640  * \param *cb		The callback
641  * \return		1 on success, 0 on error (by limread_scalar() or limread() or if the MPI is not properly formed (XXX
642  * 				 see comment below - the callback is called with a PGP_PARSER_ERROR in case of an error)
643  *
644  * \see RFC4880 3.2
645  */
646 static int
647 limread_mpi(BIGNUM **pbn, pgp_region_t *region, pgp_stream_t *stream)
648 {
649 	uint8_t   buf[NETPGP_BUFSIZ] = "";
650 					/* an MPI has a 2 byte length part.
651 					 * Length is given in bits, so the
652 					 * largest we should ever need for
653 					 * the buffer is NETPGP_BUFSIZ bytes. */
654 	unsigned        length;
655 	unsigned        nonzero;
656 	unsigned	ret;
657 
658 	stream->reading_mpi_len = 1;
659 	ret = (unsigned)limread_scalar(&length, 2, region, stream);
660 
661 	stream->reading_mpi_len = 0;
662 	if (!ret)
663 		return 0;
664 
665 	nonzero = length & 7;	/* there should be this many zero bits in the
666 				 * MS byte */
667 	if (!nonzero)
668 		nonzero = 8;
669 	length = (length + 7) / 8;
670 
671 	if (length == 0) {
672 		/* if we try to read a length of 0, then fail */
673 		if (pgp_get_debug_level(__FILE__)) {
674 			(void) fprintf(stderr, "limread_mpi: 0 length\n");
675 		}
676 		return 0;
677 	}
678 	if (length > NETPGP_BUFSIZ) {
679 		(void) fprintf(stderr, "limread_mpi: bad length\n");
680 		return 0;
681 	}
682 	if (!limread(buf, length, region, stream)) {
683 		return 0;
684 	}
685 	if (((unsigned)buf[0] >> nonzero) != 0 ||
686 	    !((unsigned)buf[0] & (1U << (nonzero - 1U)))) {
687 		PGP_ERROR_1(&stream->errors, PGP_E_P_MPI_FORMAT_ERROR,
688 		    "%s", "MPI Format error");
689 		/* XXX: Ben, one part of
690 		 * this constraint does
691 		 * not apply to
692 		 * encrypted MPIs the
693 		 * draft says. -- peter */
694 		return 0;
695 	}
696 	*pbn = BN_bin2bn(buf, (int)length, NULL);
697 	return 1;
698 }
699 
700 static unsigned read_new_length(unsigned *, pgp_stream_t *);
701 
702 /* allocate space, read, and stash data away in a virtual pkt */
703 static void
704 streamread(pgp_stream_t *stream, unsigned c)
705 {
706 	int	cc;
707 
708 	stream->virtualpkt = realloc(stream->virtualpkt, stream->virtualc + c);
709 	cc = stream->readinfo.reader(stream, &stream->virtualpkt[stream->virtualc],
710 		c, &stream->errors, &stream->readinfo, &stream->cbinfo);
711 	stream->virtualc += cc;
712 }
713 
714 /* coalesce all the partial blocks together */
715 static int
716 coalesce_blocks(pgp_stream_t *stream, unsigned length)
717 {
718 	unsigned	c;
719 
720 	stream->coalescing = 1;
721 	/* already read a partial block length - prime the array */
722 	streamread(stream, length);
723 	while (read_new_length(&c, stream) && stream->partial_read) {
724 		/* length we read is partial - add to end of array */
725 		streamread(stream, c);
726 	}
727 	/* not partial - add the last extent to the end of the array */
728 	streamread(stream, c);
729 	stream->coalescing = 0;
730 	return 1;
731 }
732 
733 /** Read some data with a New-Format length from reader.
734  *
735  * \sa Internet-Draft RFC4880.txt Section 4.2.2
736  *
737  * \param *length	Where the decoded length will be put
738  * \param *stream	How to parse
739  * \return		1 if OK, else 0
740  *
741  */
742 
743 static unsigned
744 read_new_length(unsigned *length, pgp_stream_t *stream)
745 {
746 	uint8_t   c;
747 
748 	stream->partial_read = 0;
749 	if (base_read(&c, 1, stream) != 1) {
750 		return 0;
751 	}
752 	if (c < 192) {
753 		/* 1. One-octet packet */
754 		*length = c;
755 		return 1;
756 	}
757 	if (c < 224) {
758 		/* 2. Two-octet packet */
759 		unsigned        t = (c - 192) << 8;
760 
761 		if (base_read(&c, 1, stream) != 1) {
762 			return 0;
763 		}
764 		*length = t + c + 192;
765 		return 1;
766 	}
767 	if (c < 255) {
768 		/* 3. Partial Body Length */
769 		stream->partial_read = 1;
770 		*length = 1 << (c & 0x1f);
771 		if (!stream->coalescing) {
772 			/* we have been called from coalesce_blocks -
773 			 * just return with the partial length */
774 			coalesce_blocks(stream, *length);
775 			*length = stream->virtualc;
776 		}
777 		return 1;
778 	}
779 	/* 4. Five-Octet packet */
780 	return _read_scalar(length, 4, stream);
781 }
782 
783 /** Read the length information for a new format Packet Tag.
784  *
785  * New style Packet Tags encode the length in one to five octets.  This function reads the right amount of bytes and
786  * decodes it to the proper length information.
787  *
788  * This function makes sure to respect packet boundaries.
789  *
790  * \param *length	return the length here
791  * \param *ptag		Pointer to current packet's Packet Tag.
792  * \param *reader	Our reader
793  * \param *cb		The callback
794  * \return		1 on success, 0 on error (by limread_scalar() or limread() or if the MPI is not properly formed (XXX
795  * 				 see comment below)
796  *
797  * \see RFC4880 4.2.2
798  * \see pgp_ptag_t
799  */
800 static int
801 limited_read_new_length(unsigned *length, pgp_region_t *region,
802 			pgp_stream_t *stream)
803 {
804 	uint8_t   c = 0x0;
805 
806 	if (!limread(&c, 1, region, stream)) {
807 		return 0;
808 	}
809 	if (c < 192) {
810 		*length = c;
811 		return 1;
812 	}
813 	if (c < 224) {
814 		unsigned        t = (c - 192) << 8;
815 
816 		if (!limread(&c, 1, region, stream)) {
817 			return 0;
818 		}
819 		*length = t + c + 192;
820 		return 1;
821 	}
822 	if (c < 255) {
823 		stream->partial_read = 1;
824 		*length = 1 << (c & 0x1f);
825 		if (!stream->coalescing) {
826 			/* we have been called from coalesce_blocks -
827 			 * just return with the partial length */
828 			coalesce_blocks(stream, *length);
829 			*length = stream->virtualc;
830 		}
831 		return 1;
832 	}
833 	return limread_scalar(length, 4, region, stream);
834 }
835 
836 /**
837 \ingroup Core_Create
838 \brief Free allocated memory
839 */
840 void
841 pgp_data_free(pgp_data_t *data)
842 {
843 	free(data->contents);
844 	data->contents = NULL;
845 	data->len = 0;
846 }
847 
848 /**
849 \ingroup Core_Create
850 \brief Free allocated memory
851 */
852 static void
853 string_free(char **str)
854 {
855 	free(*str);
856 	*str = NULL;
857 }
858 
859 /**
860 \ingroup Core_Create
861 \brief Free allocated memory
862 */
863 /* ! Free packet memory, set pointer to NULL */
864 void
865 pgp_subpacket_free(pgp_subpacket_t *packet)
866 {
867 	free(packet->raw);
868 	packet->raw = NULL;
869 	packet->tag = PGP_PTAG_CT_RESERVED;
870 }
871 
872 /**
873 \ingroup Core_Create
874 \brief Free allocated memory
875 */
876 static void
877 headers_free(pgp_headers_t *headers)
878 {
879 	unsigned        n;
880 
881 	for (n = 0; n < headers->headerc; ++n) {
882 		free(headers->headers[n].key);
883 		free(headers->headers[n].value);
884 	}
885 	free(headers->headers);
886 	headers->headers = NULL;
887 }
888 
889 /**
890 \ingroup Core_Create
891 \brief Free allocated memory
892 */
893 static void
894 cleartext_trailer_free(struct pgp_hash_t **trailer)
895 {
896 	free(*trailer);
897 	*trailer = NULL;
898 }
899 
900 /**
901 \ingroup Core_Create
902 \brief Free allocated memory
903 */
904 static void
905 cmd_get_passphrase_free(pgp_seckey_passphrase_t *skp)
906 {
907 	if (skp->passphrase && *skp->passphrase) {
908 		free(*skp->passphrase);
909 		*skp->passphrase = NULL;
910 	}
911 }
912 
913 /**
914 \ingroup Core_Create
915 \brief Free allocated memory
916 */
917 static void
918 free_BN(BIGNUM **pp)
919 {
920 	BN_free(*pp);
921 	*pp = NULL;
922 }
923 
924 /**
925  * \ingroup Core_Create
926  * \brief Free the memory used when parsing a signature
927  * \param sig
928  */
929 static void
930 sig_free(pgp_sig_t *sig)
931 {
932 	switch (sig->info.key_alg) {
933 	case PGP_PKA_RSA:
934 	case PGP_PKA_RSA_SIGN_ONLY:
935 		free_BN(&sig->info.sig.rsa.sig);
936 		break;
937 
938 	case PGP_PKA_DSA:
939 		free_BN(&sig->info.sig.dsa.r);
940 		free_BN(&sig->info.sig.dsa.s);
941 		break;
942 
943 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
944 		free_BN(&sig->info.sig.elgamal.r);
945 		free_BN(&sig->info.sig.elgamal.s);
946 		break;
947 
948 	case PGP_PKA_PRIVATE00:
949 	case PGP_PKA_PRIVATE01:
950 	case PGP_PKA_PRIVATE02:
951 	case PGP_PKA_PRIVATE03:
952 	case PGP_PKA_PRIVATE04:
953 	case PGP_PKA_PRIVATE05:
954 	case PGP_PKA_PRIVATE06:
955 	case PGP_PKA_PRIVATE07:
956 	case PGP_PKA_PRIVATE08:
957 	case PGP_PKA_PRIVATE09:
958 	case PGP_PKA_PRIVATE10:
959 		pgp_data_free(&sig->info.sig.unknown);
960 		break;
961 
962 	default:
963 		(void) fprintf(stderr, "sig_free: bad sig type\n");
964 	}
965 }
966 
967 /**
968 \ingroup Core_Create
969 \brief Free allocated memory
970 */
971 /* ! Free any memory allocated when parsing the packet content */
972 void
973 pgp_parser_content_free(pgp_packet_t *c)
974 {
975 	switch (c->tag) {
976 	case PGP_PARSER_PTAG:
977 	case PGP_PTAG_CT_COMPRESSED:
978 	case PGP_PTAG_SS_CREATION_TIME:
979 	case PGP_PTAG_SS_EXPIRATION_TIME:
980 	case PGP_PTAG_SS_KEY_EXPIRY:
981 	case PGP_PTAG_SS_TRUST:
982 	case PGP_PTAG_SS_ISSUER_KEY_ID:
983 	case PGP_PTAG_CT_1_PASS_SIG:
984 	case PGP_PTAG_SS_PRIMARY_USER_ID:
985 	case PGP_PTAG_SS_REVOCABLE:
986 	case PGP_PTAG_SS_REVOCATION_KEY:
987 	case PGP_PTAG_CT_LITDATA_HEADER:
988 	case PGP_PTAG_CT_LITDATA_BODY:
989 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_BODY:
990 	case PGP_PTAG_CT_UNARMOURED_TEXT:
991 	case PGP_PTAG_CT_ARMOUR_TRAILER:
992 	case PGP_PTAG_CT_SIGNATURE_HEADER:
993 	case PGP_PTAG_CT_SE_DATA_HEADER:
994 	case PGP_PTAG_CT_SE_IP_DATA_HEADER:
995 	case PGP_PTAG_CT_SE_IP_DATA_BODY:
996 	case PGP_PTAG_CT_MDC:
997 	case PGP_GET_SECKEY:
998 		break;
999 
1000 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
1001 		headers_free(&c->u.cleartext_head);
1002 		break;
1003 
1004 	case PGP_PTAG_CT_ARMOUR_HEADER:
1005 		headers_free(&c->u.armour_header.headers);
1006 		break;
1007 
1008 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
1009 		cleartext_trailer_free(&c->u.cleartext_trailer);
1010 		break;
1011 
1012 	case PGP_PTAG_CT_TRUST:
1013 		pgp_data_free(&c->u.trust);
1014 		break;
1015 
1016 	case PGP_PTAG_CT_SIGNATURE:
1017 	case PGP_PTAG_CT_SIGNATURE_FOOTER:
1018 		sig_free(&c->u.sig);
1019 		break;
1020 
1021 	case PGP_PTAG_CT_PUBLIC_KEY:
1022 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
1023 		pgp_pubkey_free(&c->u.pubkey);
1024 		break;
1025 
1026 	case PGP_PTAG_CT_USER_ID:
1027 		pgp_userid_free(&c->u.userid);
1028 		break;
1029 
1030 	case PGP_PTAG_SS_SIGNERS_USER_ID:
1031 		pgp_userid_free(&c->u.ss_signer);
1032 		break;
1033 
1034 	case PGP_PTAG_CT_USER_ATTR:
1035 		pgp_data_free(&c->u.userattr);
1036 		break;
1037 
1038 	case PGP_PTAG_SS_PREFERRED_SKA:
1039 		pgp_data_free(&c->u.ss_skapref);
1040 		break;
1041 
1042 	case PGP_PTAG_SS_PREFERRED_HASH:
1043 		pgp_data_free(&c->u.ss_hashpref);
1044 		break;
1045 
1046 	case PGP_PTAG_SS_PREF_COMPRESS:
1047 		pgp_data_free(&c->u.ss_zpref);
1048 		break;
1049 
1050 	case PGP_PTAG_SS_KEY_FLAGS:
1051 		pgp_data_free(&c->u.ss_key_flags);
1052 		break;
1053 
1054 	case PGP_PTAG_SS_KEYSERV_PREFS:
1055 		pgp_data_free(&c->u.ss_key_server_prefs);
1056 		break;
1057 
1058 	case PGP_PTAG_SS_FEATURES:
1059 		pgp_data_free(&c->u.ss_features);
1060 		break;
1061 
1062 	case PGP_PTAG_SS_NOTATION_DATA:
1063 		pgp_data_free(&c->u.ss_notation.name);
1064 		pgp_data_free(&c->u.ss_notation.value);
1065 		break;
1066 
1067 	case PGP_PTAG_SS_REGEXP:
1068 		string_free(&c->u.ss_regexp);
1069 		break;
1070 
1071 	case PGP_PTAG_SS_POLICY_URI:
1072 		string_free(&c->u.ss_policy);
1073 		break;
1074 
1075 	case PGP_PTAG_SS_PREF_KEYSERV:
1076 		string_free(&c->u.ss_keyserv);
1077 		break;
1078 
1079 	case PGP_PTAG_SS_USERDEFINED00:
1080 	case PGP_PTAG_SS_USERDEFINED01:
1081 	case PGP_PTAG_SS_USERDEFINED02:
1082 	case PGP_PTAG_SS_USERDEFINED03:
1083 	case PGP_PTAG_SS_USERDEFINED04:
1084 	case PGP_PTAG_SS_USERDEFINED05:
1085 	case PGP_PTAG_SS_USERDEFINED06:
1086 	case PGP_PTAG_SS_USERDEFINED07:
1087 	case PGP_PTAG_SS_USERDEFINED08:
1088 	case PGP_PTAG_SS_USERDEFINED09:
1089 	case PGP_PTAG_SS_USERDEFINED10:
1090 		pgp_data_free(&c->u.ss_userdef);
1091 		break;
1092 
1093 	case PGP_PTAG_SS_RESERVED:
1094 		pgp_data_free(&c->u.ss_unknown);
1095 		break;
1096 
1097 	case PGP_PTAG_SS_REVOCATION_REASON:
1098 		string_free(&c->u.ss_revocation.reason);
1099 		break;
1100 
1101 	case PGP_PTAG_SS_EMBEDDED_SIGNATURE:
1102 		pgp_data_free(&c->u.ss_embedded_sig);
1103 		break;
1104 
1105 	case PGP_PARSER_PACKET_END:
1106 		pgp_subpacket_free(&c->u.packet);
1107 		break;
1108 
1109 	case PGP_PARSER_ERROR:
1110 	case PGP_PARSER_ERRCODE:
1111 		break;
1112 
1113 	case PGP_PTAG_CT_SECRET_KEY:
1114 	case PGP_PTAG_CT_ENCRYPTED_SECRET_KEY:
1115 		pgp_seckey_free(&c->u.seckey);
1116 		break;
1117 
1118 	case PGP_PTAG_CT_PK_SESSION_KEY:
1119 	case PGP_PTAG_CT_ENCRYPTED_PK_SESSION_KEY:
1120 		pgp_pk_sesskey_free(&c->u.pk_sesskey);
1121 		break;
1122 
1123 	case PGP_GET_PASSPHRASE:
1124 		cmd_get_passphrase_free(&c->u.skey_passphrase);
1125 		break;
1126 
1127 	default:
1128 		fprintf(stderr, "Can't free %d (0x%x)\n", c->tag, c->tag);
1129 	}
1130 }
1131 
1132 /**
1133 \ingroup Core_Create
1134 \brief Free allocated memory
1135 */
1136 void
1137 pgp_pk_sesskey_free(pgp_pk_sesskey_t *sk)
1138 {
1139 	switch (sk->alg) {
1140 	case PGP_PKA_RSA:
1141 		free_BN(&sk->params.rsa.encrypted_m);
1142 		break;
1143 
1144 	case PGP_PKA_ELGAMAL:
1145 		free_BN(&sk->params.elgamal.g_to_k);
1146 		free_BN(&sk->params.elgamal.encrypted_m);
1147 		break;
1148 
1149 	default:
1150 		(void) fprintf(stderr, "pgp_pk_sesskey_free: bad alg\n");
1151 		break;
1152 	}
1153 }
1154 
1155 /**
1156 \ingroup Core_Create
1157 \brief Free allocated memory
1158 */
1159 /* ! Free the memory used when parsing a public key */
1160 void
1161 pgp_pubkey_free(pgp_pubkey_t *p)
1162 {
1163 	switch (p->alg) {
1164 	case PGP_PKA_RSA:
1165 	case PGP_PKA_RSA_ENCRYPT_ONLY:
1166 	case PGP_PKA_RSA_SIGN_ONLY:
1167 		free_BN(&p->key.rsa.n);
1168 		free_BN(&p->key.rsa.e);
1169 		break;
1170 
1171 	case PGP_PKA_DSA:
1172 		free_BN(&p->key.dsa.p);
1173 		free_BN(&p->key.dsa.q);
1174 		free_BN(&p->key.dsa.g);
1175 		free_BN(&p->key.dsa.y);
1176 		break;
1177 
1178 	case PGP_PKA_ELGAMAL:
1179 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1180 		free_BN(&p->key.elgamal.p);
1181 		free_BN(&p->key.elgamal.g);
1182 		free_BN(&p->key.elgamal.y);
1183 		break;
1184 
1185 	case PGP_PKA_NOTHING:
1186 		/* nothing to free */
1187 		break;
1188 
1189 	default:
1190 		(void) fprintf(stderr, "pgp_pubkey_free: bad alg\n");
1191 	}
1192 }
1193 
1194 /**
1195    \ingroup Core_ReadPackets
1196 */
1197 static int
1198 parse_pubkey_data(pgp_pubkey_t *key, pgp_region_t *region,
1199 		      pgp_stream_t *stream)
1200 {
1201 	uint8_t   c = 0x0;
1202 
1203 	if (region->readc != 0) {
1204 		/* We should not have read anything so far */
1205 		(void) fprintf(stderr, "parse_pubkey_data: bad length\n");
1206 		return 0;
1207 	}
1208 	if (!limread(&c, 1, region, stream)) {
1209 		return 0;
1210 	}
1211 	key->version = (pgp_version_t)c;
1212 	switch (key->version) {
1213 	case PGP_V2:
1214 	case PGP_V3:
1215 	case PGP_V4:
1216 		break;
1217 	default:
1218 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_PUBLIC_KEY_VRSN,
1219 			    "Bad public key version (0x%02x)", key->version);
1220 		return 0;
1221 	}
1222 	if (!limited_read_time(&key->birthtime, region, stream)) {
1223 		return 0;
1224 	}
1225 
1226 	key->days_valid = 0;
1227 	if ((key->version == 2 || key->version == 3) &&
1228 	    !limread_scalar(&key->days_valid, 2, region, stream)) {
1229 		return 0;
1230 	}
1231 
1232 	if (!limread(&c, 1, region, stream)) {
1233 		return 0;
1234 	}
1235 	key->alg = c;
1236 
1237 	switch (key->alg) {
1238 	case PGP_PKA_DSA:
1239 		if (!limread_mpi(&key->key.dsa.p, region, stream) ||
1240 		    !limread_mpi(&key->key.dsa.q, region, stream) ||
1241 		    !limread_mpi(&key->key.dsa.g, region, stream) ||
1242 		    !limread_mpi(&key->key.dsa.y, region, stream)) {
1243 			return 0;
1244 		}
1245 		break;
1246 
1247 	case PGP_PKA_RSA:
1248 	case PGP_PKA_RSA_ENCRYPT_ONLY:
1249 	case PGP_PKA_RSA_SIGN_ONLY:
1250 		if (!limread_mpi(&key->key.rsa.n, region, stream) ||
1251 		    !limread_mpi(&key->key.rsa.e, region, stream)) {
1252 			return 0;
1253 		}
1254 		break;
1255 
1256 	case PGP_PKA_ELGAMAL:
1257 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1258 		if (!limread_mpi(&key->key.elgamal.p, region, stream) ||
1259 		    !limread_mpi(&key->key.elgamal.g, region, stream) ||
1260 		    !limread_mpi(&key->key.elgamal.y, region, stream)) {
1261 			return 0;
1262 		}
1263 		break;
1264 
1265 	default:
1266 		PGP_ERROR_1(&stream->errors,
1267 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
1268 			"Unsupported Public Key algorithm (%s)",
1269 			pgp_show_pka(key->alg));
1270 		return 0;
1271 	}
1272 
1273 	return 1;
1274 }
1275 
1276 
1277 /**
1278  * \ingroup Core_ReadPackets
1279  * \brief Parse a public key packet.
1280  *
1281  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
1282  *
1283  * Once the key has been parsed successfully, it is passed to the callback.
1284  *
1285  * \param *ptag		Pointer to the current Packet Tag.  This function should consume the entire packet.
1286  * \param *reader	Our reader
1287  * \param *cb		The callback
1288  * \return		1 on success, 0 on error
1289  *
1290  * \see RFC4880 5.5.2
1291  */
1292 static int
1293 parse_pubkey(pgp_content_enum tag, pgp_region_t *region,
1294 		 pgp_stream_t *stream)
1295 {
1296 	pgp_packet_t pkt;
1297 
1298 	if (!parse_pubkey_data(&pkt.u.pubkey, region, stream)) {
1299 		(void) fprintf(stderr, "parse_pubkey: parse_pubkey_data failed\n");
1300 		return 0;
1301 	}
1302 
1303 	/* XXX: this test should be done for all packets, surely? */
1304 	if (region->readc != region->length) {
1305 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1306 			    "Unconsumed data (%d)", region->length - region->readc);
1307 		return 0;
1308 	}
1309 	CALLBACK(tag, &stream->cbinfo, &pkt);
1310 
1311 	return 1;
1312 }
1313 
1314 /**
1315  * \ingroup Core_ReadPackets
1316  * \brief Parse one user attribute packet.
1317  *
1318  * User attribute packets contain one or more attribute subpackets.
1319  * For now, handle the whole packet as raw data.
1320  */
1321 
1322 static int
1323 parse_userattr(pgp_region_t *region, pgp_stream_t *stream)
1324 {
1325 
1326 	pgp_packet_t pkt;
1327 
1328 	/*
1329 	 * xxx- treat as raw data for now. Could break down further into
1330 	 * attribute sub-packets later - rachel
1331 	 */
1332 	if (region->readc != 0) {
1333 		/* We should not have read anything so far */
1334 		(void) fprintf(stderr, "parse_userattr: bad length\n");
1335 		return 0;
1336 	}
1337 	if (!read_data(&pkt.u.userattr, region, stream)) {
1338 		return 0;
1339 	}
1340 	CALLBACK(PGP_PTAG_CT_USER_ATTR, &stream->cbinfo, &pkt);
1341 	return 1;
1342 }
1343 
1344 /**
1345 \ingroup Core_Create
1346 \brief Free allocated memory
1347 */
1348 /* ! Free the memory used when parsing this packet type */
1349 void
1350 pgp_userid_free(uint8_t **id)
1351 {
1352 	free(*id);
1353 	*id = NULL;
1354 }
1355 
1356 /**
1357  * \ingroup Core_ReadPackets
1358  * \brief Parse a user id.
1359  *
1360  * This function parses an user id packet, which is basically just a char array the size of the packet.
1361  *
1362  * The char array is to be treated as an UTF-8 string.
1363  *
1364  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
1365  *
1366  * Once the userid has been parsed successfully, it is passed to the callback.
1367  *
1368  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1369  * \param *reader	Our reader
1370  * \param *cb		The callback
1371  * \return		1 on success, 0 on error
1372  *
1373  * \see RFC4880 5.11
1374  */
1375 static int
1376 parse_userid(pgp_region_t *region, pgp_stream_t *stream)
1377 {
1378 	pgp_packet_t pkt;
1379 
1380 	 if (region->readc != 0) {
1381 		/* We should not have read anything so far */
1382 		(void) fprintf(stderr, "parse_userid: bad length\n");
1383 		return 0;
1384 	}
1385 
1386 	if ((pkt.u.userid = calloc(1, region->length + 1)) == NULL) {
1387 		(void) fprintf(stderr, "parse_userid: bad alloc\n");
1388 		return 0;
1389 	}
1390 
1391 	if (region->length &&
1392 	    !limread(pkt.u.userid, region->length, region,
1393 			stream)) {
1394 		return 0;
1395 	}
1396 	pkt.u.userid[region->length] = 0x0;
1397 	CALLBACK(PGP_PTAG_CT_USER_ID, &stream->cbinfo, &pkt);
1398 	return 1;
1399 }
1400 
1401 static pgp_hash_t     *
1402 parse_hash_find(pgp_stream_t *stream, const uint8_t *keyid)
1403 {
1404 	pgp_hashtype_t	*hp;
1405 	size_t			 n;
1406 
1407 	for (n = 0, hp = stream->hashes; n < stream->hashc; n++, hp++) {
1408 		if (memcmp(hp->keyid, keyid, PGP_KEY_ID_SIZE) == 0) {
1409 			return &hp->hash;
1410 		}
1411 	}
1412 	return NULL;
1413 }
1414 
1415 /**
1416  * \ingroup Core_Parse
1417  * \brief Parse a version 3 signature.
1418  *
1419  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
1420  *
1421  * Once the signature has been parsed successfully, it is passed to the callback.
1422  *
1423  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1424  * \param *reader	Our reader
1425  * \param *cb		The callback
1426  * \return		1 on success, 0 on error
1427  *
1428  * \see RFC4880 5.2.2
1429  */
1430 static int
1431 parse_v3_sig(pgp_region_t *region,
1432 		   pgp_stream_t *stream)
1433 {
1434 	pgp_packet_t	pkt;
1435 	uint8_t		c = 0x0;
1436 
1437 	/* clear signature */
1438 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1439 
1440 	pkt.u.sig.info.version = PGP_V3;
1441 
1442 	/* hash info length */
1443 	if (!limread(&c, 1, region, stream)) {
1444 		return 0;
1445 	}
1446 	if (c != 5) {
1447 		ERRP(&stream->cbinfo, pkt, "bad hash info length");
1448 	}
1449 
1450 	if (!limread(&c, 1, region, stream)) {
1451 		return 0;
1452 	}
1453 	pkt.u.sig.info.type = (pgp_sig_type_t)c;
1454 	/* XXX: check signature type */
1455 
1456 	if (!limited_read_time(&pkt.u.sig.info.birthtime, region, stream)) {
1457 		return 0;
1458 	}
1459 	pkt.u.sig.info.birthtime_set = 1;
1460 
1461 	if (!limread(pkt.u.sig.info.signer_id, PGP_KEY_ID_SIZE, region,
1462 			stream)) {
1463 		return 0;
1464 	}
1465 	pkt.u.sig.info.signer_id_set = 1;
1466 
1467 	if (!limread(&c, 1, region, stream)) {
1468 		return 0;
1469 	}
1470 	pkt.u.sig.info.key_alg = (pgp_pubkey_alg_t)c;
1471 	/* XXX: check algorithm */
1472 
1473 	if (!limread(&c, 1, region, stream)) {
1474 		return 0;
1475 	}
1476 	pkt.u.sig.info.hash_alg = (pgp_hash_alg_t)c;
1477 	/* XXX: check algorithm */
1478 
1479 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
1480 		return 0;
1481 	}
1482 
1483 	switch (pkt.u.sig.info.key_alg) {
1484 	case PGP_PKA_RSA:
1485 	case PGP_PKA_RSA_SIGN_ONLY:
1486 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
1487 			return 0;
1488 		}
1489 		break;
1490 
1491 	case PGP_PKA_DSA:
1492 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream) ||
1493 		    !limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
1494 			return 0;
1495 		}
1496 		break;
1497 
1498 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1499 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
1500 				stream) ||
1501 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
1502 		    		stream)) {
1503 			return 0;
1504 		}
1505 		break;
1506 
1507 	default:
1508 		PGP_ERROR_1(&stream->errors,
1509 			PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
1510 			"Unsupported signature key algorithm (%s)",
1511 			pgp_show_pka(pkt.u.sig.info.key_alg));
1512 		return 0;
1513 	}
1514 
1515 	if (region->readc != region->length) {
1516 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1517 			"Unconsumed data (%d)",
1518 			region->length - region->readc);
1519 		return 0;
1520 	}
1521 	if (pkt.u.sig.info.signer_id_set) {
1522 		pkt.u.sig.hash = parse_hash_find(stream,
1523 				pkt.u.sig.info.signer_id);
1524 	}
1525 	CALLBACK(PGP_PTAG_CT_SIGNATURE, &stream->cbinfo, &pkt);
1526 	return 1;
1527 }
1528 
1529 /**
1530  * \ingroup Core_ReadPackets
1531  * \brief Parse one signature sub-packet.
1532  *
1533  * Version 4 signatures can have an arbitrary amount of (hashed and
1534  * unhashed) subpackets.  Subpackets are used to hold optional
1535  * attributes of subpackets.
1536  *
1537  * This function parses one such signature subpacket.
1538  *
1539  * Once the subpacket has been parsed successfully, it is passed to the callback.
1540  *
1541  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire subpacket.
1542  * \param *reader	Our reader
1543  * \param *cb		The callback
1544  * \return		1 on success, 0 on error
1545  *
1546  * \see RFC4880 5.2.3
1547  */
1548 static int
1549 parse_one_sig_subpacket(pgp_sig_t *sig,
1550 			      pgp_region_t *region,
1551 			      pgp_stream_t *stream)
1552 {
1553 	pgp_region_t	subregion;
1554 	pgp_packet_t	pkt;
1555 	uint8_t		bools = 0x0;
1556 	uint8_t		c = 0x0;
1557 	unsigned	doread = 1;
1558 	unsigned        t8;
1559 	unsigned        t7;
1560 
1561 	pgp_init_subregion(&subregion, region);
1562 	if (!limited_read_new_length(&subregion.length, region, stream)) {
1563 		return 0;
1564 	}
1565 
1566 	if (subregion.length > region->length) {
1567 		ERRP(&stream->cbinfo, pkt, "Subpacket too long");
1568 	}
1569 
1570 	if (!limread(&c, 1, &subregion, stream)) {
1571 		return 0;
1572 	}
1573 
1574 	t8 = (c & 0x7f) / 8;
1575 	t7 = 1 << (c & 7);
1576 
1577 	pkt.critical = (unsigned)c >> 7;
1578 	pkt.tag = (pgp_content_enum)(PGP_PTAG_SIG_SUBPKT_BASE + (c & 0x7f));
1579 
1580 	/* Application wants it delivered raw */
1581 	if (stream->ss_raw[t8] & t7) {
1582 		pkt.u.ss_raw.tag = pkt.tag;
1583 		pkt.u.ss_raw.length = subregion.length - 1;
1584 		pkt.u.ss_raw.raw = calloc(1, pkt.u.ss_raw.length);
1585 		if (pkt.u.ss_raw.raw == NULL) {
1586 			(void) fprintf(stderr, "parse_one_sig_subpacket: bad alloc\n");
1587 			return 0;
1588 		}
1589 		if (!limread(pkt.u.ss_raw.raw, (unsigned)pkt.u.ss_raw.length,
1590 				&subregion, stream)) {
1591 			return 0;
1592 		}
1593 		CALLBACK(PGP_PTAG_RAW_SS, &stream->cbinfo, &pkt);
1594 		return 1;
1595 	}
1596 	switch (pkt.tag) {
1597 	case PGP_PTAG_SS_CREATION_TIME:
1598 	case PGP_PTAG_SS_EXPIRATION_TIME:
1599 	case PGP_PTAG_SS_KEY_EXPIRY:
1600 		if (!limited_read_time(&pkt.u.ss_time, &subregion, stream))
1601 			return 0;
1602 		if (pkt.tag == PGP_PTAG_SS_CREATION_TIME) {
1603 			sig->info.birthtime = pkt.u.ss_time;
1604 			sig->info.birthtime_set = 1;
1605 		}
1606 		if (pkt.tag == PGP_PTAG_SS_EXPIRATION_TIME) {
1607 			sig->info.duration = pkt.u.ss_time;
1608 			sig->info.duration_set = 1;
1609 		}
1610 		break;
1611 
1612 	case PGP_PTAG_SS_TRUST:
1613 		if (!limread(&pkt.u.ss_trust.level, 1, &subregion, stream) ||
1614 		    !limread(&pkt.u.ss_trust.amount, 1, &subregion, stream)) {
1615 			return 0;
1616 		}
1617 		break;
1618 
1619 	case PGP_PTAG_SS_REVOCABLE:
1620 		if (!limread(&bools, 1, &subregion, stream)) {
1621 			return 0;
1622 		}
1623 		pkt.u.ss_revocable = !!bools;
1624 		break;
1625 
1626 	case PGP_PTAG_SS_ISSUER_KEY_ID:
1627 		if (!limread(pkt.u.ss_issuer, PGP_KEY_ID_SIZE, &subregion, stream)) {
1628 			return 0;
1629 		}
1630 		(void) memcpy(sig->info.signer_id, pkt.u.ss_issuer, PGP_KEY_ID_SIZE);
1631 		sig->info.signer_id_set = 1;
1632 		break;
1633 
1634 	case PGP_PTAG_SS_PREFERRED_SKA:
1635 		if (!read_data(&pkt.u.ss_skapref, &subregion, stream)) {
1636 			return 0;
1637 		}
1638 		break;
1639 
1640 	case PGP_PTAG_SS_PREFERRED_HASH:
1641 		if (!read_data(&pkt.u.ss_hashpref, &subregion, stream)) {
1642 			return 0;
1643 		}
1644 		break;
1645 
1646 	case PGP_PTAG_SS_PREF_COMPRESS:
1647 		if (!read_data(&pkt.u.ss_zpref, &subregion, stream)) {
1648 			return 0;
1649 		}
1650 		break;
1651 
1652 	case PGP_PTAG_SS_PRIMARY_USER_ID:
1653 		if (!limread(&bools, 1, &subregion, stream)) {
1654 			return 0;
1655 		}
1656 		pkt.u.ss_primary_userid = !!bools;
1657 		break;
1658 
1659 	case PGP_PTAG_SS_KEY_FLAGS:
1660 		if (!read_data(&pkt.u.ss_key_flags, &subregion, stream)) {
1661 			return 0;
1662 		}
1663 		break;
1664 
1665 	case PGP_PTAG_SS_KEYSERV_PREFS:
1666 		if (!read_data(&pkt.u.ss_key_server_prefs, &subregion, stream)) {
1667 			return 0;
1668 		}
1669 		break;
1670 
1671 	case PGP_PTAG_SS_FEATURES:
1672 		if (!read_data(&pkt.u.ss_features, &subregion, stream)) {
1673 			return 0;
1674 		}
1675 		break;
1676 
1677 	case PGP_PTAG_SS_SIGNERS_USER_ID:
1678 		if (!read_unsig_str(&pkt.u.ss_signer, &subregion, stream)) {
1679 			return 0;
1680 		}
1681 		break;
1682 
1683 	case PGP_PTAG_SS_EMBEDDED_SIGNATURE:
1684 		/* \todo should do something with this sig? */
1685 		if (!read_data(&pkt.u.ss_embedded_sig, &subregion, stream)) {
1686 			return 0;
1687 		}
1688 		break;
1689 
1690 	case PGP_PTAG_SS_NOTATION_DATA:
1691 		if (!limread_data(&pkt.u.ss_notation.flags, 4,
1692 				&subregion, stream)) {
1693 			return 0;
1694 		}
1695 		if (!limread_size_t(&pkt.u.ss_notation.name.len, 2,
1696 				&subregion, stream)) {
1697 			return 0;
1698 		}
1699 		if (!limread_size_t(&pkt.u.ss_notation.value.len, 2,
1700 				&subregion, stream)) {
1701 			return 0;
1702 		}
1703 		if (!limread_data(&pkt.u.ss_notation.name,
1704 				(unsigned)pkt.u.ss_notation.name.len,
1705 				&subregion, stream)) {
1706 			return 0;
1707 		}
1708 		if (!limread_data(&pkt.u.ss_notation.value,
1709 			   (unsigned)pkt.u.ss_notation.value.len,
1710 			   &subregion, stream)) {
1711 			return 0;
1712 		}
1713 		break;
1714 
1715 	case PGP_PTAG_SS_POLICY_URI:
1716 		if (!read_string(&pkt.u.ss_policy, &subregion, stream)) {
1717 			return 0;
1718 		}
1719 		break;
1720 
1721 	case PGP_PTAG_SS_REGEXP:
1722 		if (!read_string(&pkt.u.ss_regexp, &subregion, stream)) {
1723 			return 0;
1724 		}
1725 		break;
1726 
1727 	case PGP_PTAG_SS_PREF_KEYSERV:
1728 		if (!read_string(&pkt.u.ss_keyserv, &subregion, stream)) {
1729 			return 0;
1730 		}
1731 		break;
1732 
1733 	case PGP_PTAG_SS_USERDEFINED00:
1734 	case PGP_PTAG_SS_USERDEFINED01:
1735 	case PGP_PTAG_SS_USERDEFINED02:
1736 	case PGP_PTAG_SS_USERDEFINED03:
1737 	case PGP_PTAG_SS_USERDEFINED04:
1738 	case PGP_PTAG_SS_USERDEFINED05:
1739 	case PGP_PTAG_SS_USERDEFINED06:
1740 	case PGP_PTAG_SS_USERDEFINED07:
1741 	case PGP_PTAG_SS_USERDEFINED08:
1742 	case PGP_PTAG_SS_USERDEFINED09:
1743 	case PGP_PTAG_SS_USERDEFINED10:
1744 		if (!read_data(&pkt.u.ss_userdef, &subregion, stream)) {
1745 			return 0;
1746 		}
1747 		break;
1748 
1749 	case PGP_PTAG_SS_RESERVED:
1750 		if (!read_data(&pkt.u.ss_unknown, &subregion, stream)) {
1751 			return 0;
1752 		}
1753 		break;
1754 
1755 	case PGP_PTAG_SS_REVOCATION_REASON:
1756 		/* first byte is the machine-readable code */
1757 		if (!limread(&pkt.u.ss_revocation.code, 1, &subregion, stream)) {
1758 			return 0;
1759 		}
1760 		/* the rest is a human-readable UTF-8 string */
1761 		if (!read_string(&pkt.u.ss_revocation.reason, &subregion,
1762 				stream)) {
1763 			return 0;
1764 		}
1765 		break;
1766 
1767 	case PGP_PTAG_SS_REVOCATION_KEY:
1768 		/* octet 0 = class. Bit 0x80 must be set */
1769 		if (!limread(&pkt.u.ss_revocation_key.class, 1,
1770 				&subregion, stream)) {
1771 			return 0;
1772 		}
1773 		if (!(pkt.u.ss_revocation_key.class & 0x80)) {
1774 			printf("Warning: PGP_PTAG_SS_REVOCATION_KEY class: "
1775 			       "Bit 0x80 should be set\n");
1776 			return 0;
1777 		}
1778 		/* octet 1 = algid */
1779 		if (!limread(&pkt.u.ss_revocation_key.algid, 1,
1780 				&subregion, stream)) {
1781 			return 0;
1782 		}
1783 		/* octets 2-21 = fingerprint */
1784 		if (!limread(&pkt.u.ss_revocation_key.fingerprint[0],
1785 				PGP_FINGERPRINT_SIZE, &subregion, stream)) {
1786 			return 0;
1787 		}
1788 		break;
1789 
1790 	default:
1791 		if (stream->ss_parsed[t8] & t7) {
1792 			PGP_ERROR_1(&stream->errors, PGP_E_PROTO_UNKNOWN_SS,
1793 				    "Unknown signature subpacket type (%d)",
1794 				    c & 0x7f);
1795 		}
1796 		doread = 0;
1797 		break;
1798 	}
1799 
1800 	/* Application doesn't want it delivered parsed */
1801 	if (!(stream->ss_parsed[t8] & t7)) {
1802 		if (pkt.critical) {
1803 			PGP_ERROR_1(&stream->errors,
1804 				PGP_E_PROTO_CRITICAL_SS_IGNORED,
1805 				"Critical signature subpacket ignored (%d)",
1806 				c & 0x7f);
1807 		}
1808 		if (!doread &&
1809 		    !limskip(subregion.length - 1, &subregion, stream)) {
1810 			return 0;
1811 		}
1812 		if (doread) {
1813 			pgp_parser_content_free(&pkt);
1814 		}
1815 		return 1;
1816 	}
1817 	if (doread && subregion.readc != subregion.length) {
1818 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1819 			    "Unconsumed data (%d)",
1820 			    subregion.length - subregion.readc);
1821 		return 0;
1822 	}
1823 	CALLBACK(pkt.tag, &stream->cbinfo, &pkt);
1824 	return 1;
1825 }
1826 
1827 /**
1828  * \ingroup Core_ReadPackets
1829  * \brief Parse several signature subpackets.
1830  *
1831  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1832  * This function parses this length and then calls parse_one_sig_subpacket() for each subpacket until the
1833  * entire set is consumed.
1834  *
1835  * This function does not call the callback directly, parse_one_sig_subpacket() does for each subpacket.
1836  *
1837  * \param *ptag		Pointer to the Packet Tag.
1838  * \param *reader	Our reader
1839  * \param *cb		The callback
1840  * \return		1 on success, 0 on error
1841  *
1842  * \see RFC4880 5.2.3
1843  */
1844 static int
1845 parse_sig_subpkts(pgp_sig_t *sig,
1846 			   pgp_region_t *region,
1847 			   pgp_stream_t *stream)
1848 {
1849 	pgp_region_t	subregion;
1850 	pgp_packet_t	pkt;
1851 
1852 	pgp_init_subregion(&subregion, region);
1853 	if (!limread_scalar(&subregion.length, 2, region, stream)) {
1854 		return 0;
1855 	}
1856 
1857 	if (subregion.length > region->length) {
1858 		ERRP(&stream->cbinfo, pkt, "Subpacket set too long");
1859 	}
1860 
1861 	while (subregion.readc < subregion.length) {
1862 		if (!parse_one_sig_subpacket(sig, &subregion, stream)) {
1863 			return 0;
1864 		}
1865 	}
1866 
1867 	if (subregion.readc != subregion.length) {
1868 		if (!limskip(subregion.length - subregion.readc,
1869 				&subregion, stream)) {
1870 			ERRP(&stream->cbinfo, pkt,
1871 "parse_sig_subpkts: subpacket length read mismatch");
1872 		}
1873 		ERRP(&stream->cbinfo, pkt, "Subpacket length mismatch");
1874 	}
1875 	return 1;
1876 }
1877 
1878 /**
1879  * \ingroup Core_ReadPackets
1880  * \brief Parse a version 4 signature.
1881  *
1882  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
1883  *
1884  * Once the signature packet has been parsed successfully, it is passed to the callback.
1885  *
1886  * \param *ptag		Pointer to the Packet Tag.
1887  * \param *reader	Our reader
1888  * \param *cb		The callback
1889  * \return		1 on success, 0 on error
1890  *
1891  * \see RFC4880 5.2.3
1892  */
1893 static int
1894 parse_v4_sig(pgp_region_t *region, pgp_stream_t *stream)
1895 {
1896 	pgp_packet_t	pkt;
1897 	uint8_t		c = 0x0;
1898 
1899 	if (pgp_get_debug_level(__FILE__)) {
1900 		fprintf(stderr, "\nparse_v4_sig\n");
1901 	}
1902 	/* clear signature */
1903 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1904 
1905 	/*
1906 	 * We need to hash the packet data from version through the hashed
1907 	 * subpacket data
1908 	 */
1909 
1910 	pkt.u.sig.v4_hashstart = stream->readinfo.alength - 1;
1911 
1912 	/* Set version,type,algorithms */
1913 
1914 	pkt.u.sig.info.version = PGP_V4;
1915 
1916 	if (!limread(&c, 1, region, stream)) {
1917 		return 0;
1918 	}
1919 	pkt.u.sig.info.type = (pgp_sig_type_t)c;
1920 	if (pgp_get_debug_level(__FILE__)) {
1921 		fprintf(stderr, "signature type=%d (%s)\n",
1922 			pkt.u.sig.info.type,
1923 			pgp_show_sig_type(pkt.u.sig.info.type));
1924 	}
1925 	/* XXX: check signature type */
1926 
1927 	if (!limread(&c, 1, region, stream)) {
1928 		return 0;
1929 	}
1930 	pkt.u.sig.info.key_alg = (pgp_pubkey_alg_t)c;
1931 	/* XXX: check key algorithm */
1932 	if (pgp_get_debug_level(__FILE__)) {
1933 		(void) fprintf(stderr, "key_alg=%d (%s)\n",
1934 			pkt.u.sig.info.key_alg,
1935 			pgp_show_pka(pkt.u.sig.info.key_alg));
1936 	}
1937 	if (!limread(&c, 1, region, stream)) {
1938 		return 0;
1939 	}
1940 	pkt.u.sig.info.hash_alg = (pgp_hash_alg_t)c;
1941 	/* XXX: check hash algorithm */
1942 	if (pgp_get_debug_level(__FILE__)) {
1943 		fprintf(stderr, "hash_alg=%d %s\n",
1944 			pkt.u.sig.info.hash_alg,
1945 		  pgp_show_hash_alg(pkt.u.sig.info.hash_alg));
1946 	}
1947 	CALLBACK(PGP_PTAG_CT_SIGNATURE_HEADER, &stream->cbinfo, &pkt);
1948 
1949 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
1950 		return 0;
1951 	}
1952 
1953 	pkt.u.sig.info.v4_hashlen = stream->readinfo.alength
1954 					- pkt.u.sig.v4_hashstart;
1955 	if (pgp_get_debug_level(__FILE__)) {
1956 		fprintf(stderr, "v4_hashlen=%zd\n", pkt.u.sig.info.v4_hashlen);
1957 	}
1958 
1959 	/* copy hashed subpackets */
1960 	if (pkt.u.sig.info.v4_hashed) {
1961 		free(pkt.u.sig.info.v4_hashed);
1962 	}
1963 	pkt.u.sig.info.v4_hashed = calloc(1, pkt.u.sig.info.v4_hashlen);
1964 	if (pkt.u.sig.info.v4_hashed == NULL) {
1965 		(void) fprintf(stderr, "parse_v4_sig: bad alloc\n");
1966 		return 0;
1967 	}
1968 
1969 	if (!stream->readinfo.accumulate) {
1970 		/* We must accumulate, else we can't check the signature */
1971 		fprintf(stderr, "*** ERROR: must set accumulate to 1\n");
1972 		return 0;
1973 	}
1974 	(void) memcpy(pkt.u.sig.info.v4_hashed,
1975 	       stream->readinfo.accumulated + pkt.u.sig.v4_hashstart,
1976 	       pkt.u.sig.info.v4_hashlen);
1977 
1978 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
1979 		return 0;
1980 	}
1981 
1982 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
1983 		return 0;
1984 	}
1985 
1986 	switch (pkt.u.sig.info.key_alg) {
1987 	case PGP_PKA_RSA:
1988 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
1989 			return 0;
1990 		}
1991 		if (pgp_get_debug_level(__FILE__)) {
1992 			(void) fprintf(stderr, "parse_v4_sig: RSA: sig is\n");
1993 			BN_print_fp(stderr, pkt.u.sig.info.sig.rsa.sig);
1994 			(void) fprintf(stderr, "\n");
1995 		}
1996 		break;
1997 
1998 	case PGP_PKA_DSA:
1999 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream)) {
2000 			/*
2001 			 * usually if this fails, it just means we've reached
2002 			 * the end of the keyring
2003 			 */
2004 			if (pgp_get_debug_level(__FILE__)) {
2005 				(void) fprintf(stderr,
2006 				"Error reading DSA r field in signature");
2007 			}
2008 			return 0;
2009 		}
2010 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
2011 			ERRP(&stream->cbinfo, pkt,
2012 			"Error reading DSA s field in signature");
2013 		}
2014 		break;
2015 
2016 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
2017 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
2018 				stream) ||
2019 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
2020 		    		stream)) {
2021 			return 0;
2022 		}
2023 		break;
2024 
2025 	case PGP_PKA_PRIVATE00:
2026 	case PGP_PKA_PRIVATE01:
2027 	case PGP_PKA_PRIVATE02:
2028 	case PGP_PKA_PRIVATE03:
2029 	case PGP_PKA_PRIVATE04:
2030 	case PGP_PKA_PRIVATE05:
2031 	case PGP_PKA_PRIVATE06:
2032 	case PGP_PKA_PRIVATE07:
2033 	case PGP_PKA_PRIVATE08:
2034 	case PGP_PKA_PRIVATE09:
2035 	case PGP_PKA_PRIVATE10:
2036 		if (!read_data(&pkt.u.sig.info.sig.unknown, region, stream)) {
2037 			return 0;
2038 		}
2039 		break;
2040 
2041 	default:
2042 		PGP_ERROR_1(&stream->errors, PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
2043 			    "Bad v4 signature key algorithm (%s)",
2044 			    pgp_show_pka(pkt.u.sig.info.key_alg));
2045 		return 0;
2046 	}
2047 	if (region->readc != region->length) {
2048 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
2049 			    "Unconsumed data (%d)",
2050 			    region->length - region->readc);
2051 		return 0;
2052 	}
2053 	CALLBACK(PGP_PTAG_CT_SIGNATURE_FOOTER, &stream->cbinfo, &pkt);
2054 	return 1;
2055 }
2056 
2057 /**
2058  * \ingroup Core_ReadPackets
2059  * \brief Parse a signature subpacket.
2060  *
2061  * This function calls the appropriate function to handle v3 or v4 signatures.
2062  *
2063  * Once the signature packet has been parsed successfully, it is passed to the callback.
2064  *
2065  * \param *ptag		Pointer to the Packet Tag.
2066  * \param *reader	Our reader
2067  * \param *cb		The callback
2068  * \return		1 on success, 0 on error
2069  */
2070 static int
2071 parse_sig(pgp_region_t *region, pgp_stream_t *stream)
2072 {
2073 	pgp_packet_t	pkt;
2074 	uint8_t		c = 0x0;
2075 
2076 	if (region->readc != 0) {
2077 		/* We should not have read anything so far */
2078 		(void) fprintf(stderr, "parse_sig: bad length\n");
2079 		return 0;
2080 	}
2081 
2082 	(void) memset(&pkt, 0x0, sizeof(pkt));
2083 	if (!limread(&c, 1, region, stream)) {
2084 		return 0;
2085 	}
2086 	if (c == 2 || c == 3) {
2087 		return parse_v3_sig(region, stream);
2088 	}
2089 	if (c == 4) {
2090 		return parse_v4_sig(region, stream);
2091 	}
2092 	PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_SIGNATURE_VRSN,
2093 		    "Bad signature version (%d)", c);
2094 	return 0;
2095 }
2096 
2097 /**
2098  \ingroup Core_ReadPackets
2099  \brief Parse Compressed packet
2100 */
2101 static int
2102 parse_compressed(pgp_region_t *region, pgp_stream_t *stream)
2103 {
2104 	pgp_packet_t	pkt;
2105 	uint8_t		c = 0x0;
2106 
2107 	if (!limread(&c, 1, region, stream)) {
2108 		return 0;
2109 	}
2110 
2111 	pkt.u.compressed = (pgp_compression_type_t)c;
2112 
2113 	CALLBACK(PGP_PTAG_CT_COMPRESSED, &stream->cbinfo, &pkt);
2114 
2115 	/*
2116 	 * The content of a compressed data packet is more OpenPGP packets
2117 	 * once decompressed, so recursively handle them
2118 	 */
2119 
2120 	return pgp_decompress(region, stream, pkt.u.compressed);
2121 }
2122 
2123 /* XXX: this could be improved by sharing all hashes that are the */
2124 /* same, then duping them just before checking the signature. */
2125 static void
2126 parse_hash_init(pgp_stream_t *stream, pgp_hash_alg_t type,
2127 		    const uint8_t *keyid)
2128 {
2129 	pgp_hashtype_t *hash;
2130 
2131 	hash = realloc(stream->hashes,
2132 			      (stream->hashc + 1) * sizeof(*stream->hashes));
2133 	if (hash == NULL) {
2134 		(void) fprintf(stderr, "parse_hash_init: bad alloc 0\n");
2135 		/* just continue and die here */
2136 		/* XXX - agc - no way to return failure */
2137 	} else {
2138 		stream->hashes = hash;
2139 	}
2140 	hash = &stream->hashes[stream->hashc++];
2141 
2142 	pgp_hash_any(&hash->hash, type);
2143 	if (!hash->hash.init(&hash->hash)) {
2144 		(void) fprintf(stderr, "parse_hash_init: bad alloc\n");
2145 		/* just continue and die here */
2146 		/* XXX - agc - no way to return failure */
2147 	}
2148 	(void) memcpy(hash->keyid, keyid, sizeof(hash->keyid));
2149 }
2150 
2151 /**
2152    \ingroup Core_ReadPackets
2153    \brief Parse a One Pass Signature packet
2154 */
2155 static int
2156 parse_one_pass(pgp_region_t * region, pgp_stream_t * stream)
2157 {
2158 	pgp_packet_t	pkt;
2159 	uint8_t		c = 0x0;
2160 
2161 	if (!limread(&pkt.u.one_pass_sig.version, 1, region, stream)) {
2162 		return 0;
2163 	}
2164 	if (pkt.u.one_pass_sig.version != 3) {
2165 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_ONE_PASS_SIG_VRSN,
2166 			    "Bad one-pass signature version (%d)",
2167 			    pkt.u.one_pass_sig.version);
2168 		return 0;
2169 	}
2170 	if (!limread(&c, 1, region, stream)) {
2171 		return 0;
2172 	}
2173 	pkt.u.one_pass_sig.sig_type = (pgp_sig_type_t)c;
2174 
2175 	if (!limread(&c, 1, region, stream)) {
2176 		return 0;
2177 	}
2178 	pkt.u.one_pass_sig.hash_alg = (pgp_hash_alg_t)c;
2179 
2180 	if (!limread(&c, 1, region, stream)) {
2181 		return 0;
2182 	}
2183 	pkt.u.one_pass_sig.key_alg = (pgp_pubkey_alg_t)c;
2184 
2185 	if (!limread(pkt.u.one_pass_sig.keyid,
2186 			  (unsigned)sizeof(pkt.u.one_pass_sig.keyid),
2187 			  region, stream)) {
2188 		return 0;
2189 	}
2190 
2191 	if (!limread(&c, 1, region, stream)) {
2192 		return 0;
2193 	}
2194 	pkt.u.one_pass_sig.nested = !!c;
2195 	CALLBACK(PGP_PTAG_CT_1_PASS_SIG, &stream->cbinfo, &pkt);
2196 	/* XXX: we should, perhaps, let the app choose whether to hash or not */
2197 	parse_hash_init(stream, pkt.u.one_pass_sig.hash_alg,
2198 			    pkt.u.one_pass_sig.keyid);
2199 	return 1;
2200 }
2201 
2202 /**
2203  \ingroup Core_ReadPackets
2204  \brief Parse a Trust packet
2205 */
2206 static int
2207 parse_trust(pgp_region_t *region, pgp_stream_t *stream)
2208 {
2209 	pgp_packet_t pkt;
2210 
2211 	if (!read_data(&pkt.u.trust, region, stream)) {
2212 		return 0;
2213 	}
2214 	CALLBACK(PGP_PTAG_CT_TRUST, &stream->cbinfo, &pkt);
2215 	return 1;
2216 }
2217 
2218 static void
2219 parse_hash_data(pgp_stream_t *stream, const void *data,
2220 		    size_t length)
2221 {
2222 	size_t          n;
2223 
2224 	for (n = 0; n < stream->hashc; ++n) {
2225 		stream->hashes[n].hash.add(&stream->hashes[n].hash, data, (unsigned)length);
2226 	}
2227 }
2228 
2229 /**
2230    \ingroup Core_ReadPackets
2231    \brief Parse a Literal Data packet
2232 */
2233 static int
2234 parse_litdata(pgp_region_t *region, pgp_stream_t *stream)
2235 {
2236 	pgp_memory_t	*mem;
2237 	pgp_packet_t	 pkt;
2238 	uint8_t		 c = 0x0;
2239 
2240 	if (!limread(&c, 1, region, stream)) {
2241 		return 0;
2242 	}
2243 	pkt.u.litdata_header.format = (pgp_litdata_enum)c;
2244 	if (!limread(&c, 1, region, stream)) {
2245 		return 0;
2246 	}
2247 	if (!limread((uint8_t *)pkt.u.litdata_header.filename,
2248 			(unsigned)c, region, stream)) {
2249 		return 0;
2250 	}
2251 	pkt.u.litdata_header.filename[c] = '\0';
2252 	if (!limited_read_time(&pkt.u.litdata_header.mtime, region, stream)) {
2253 		return 0;
2254 	}
2255 	CALLBACK(PGP_PTAG_CT_LITDATA_HEADER, &stream->cbinfo, &pkt);
2256 	mem = pkt.u.litdata_body.mem = pgp_memory_new();
2257 	pgp_memory_init(pkt.u.litdata_body.mem,
2258 			(unsigned)((region->length * 101) / 100) + 12);
2259 	pkt.u.litdata_body.data = mem->buf;
2260 
2261 	while (region->readc < region->length) {
2262 		unsigned        readc = region->length - region->readc;
2263 
2264 		if (!limread(mem->buf, readc, region, stream)) {
2265 			return 0;
2266 		}
2267 		pkt.u.litdata_body.length = readc;
2268 		parse_hash_data(stream, pkt.u.litdata_body.data, region->length);
2269 		CALLBACK(PGP_PTAG_CT_LITDATA_BODY, &stream->cbinfo, &pkt);
2270 	}
2271 
2272 	/* XXX - get rid of mem here? */
2273 
2274 	return 1;
2275 }
2276 
2277 /**
2278  * \ingroup Core_Create
2279  *
2280  * pgp_seckey_free() frees the memory associated with "key". Note that
2281  * the key itself is not freed.
2282  *
2283  * \param key
2284  */
2285 
2286 void
2287 pgp_seckey_free(pgp_seckey_t *key)
2288 {
2289 	switch (key->pubkey.alg) {
2290 	case PGP_PKA_RSA:
2291 	case PGP_PKA_RSA_ENCRYPT_ONLY:
2292 	case PGP_PKA_RSA_SIGN_ONLY:
2293 		free_BN(&key->key.rsa.d);
2294 		free_BN(&key->key.rsa.p);
2295 		free_BN(&key->key.rsa.q);
2296 		free_BN(&key->key.rsa.u);
2297 		break;
2298 
2299 	case PGP_PKA_DSA:
2300 		free_BN(&key->key.dsa.x);
2301 		break;
2302 
2303 	default:
2304 		(void) fprintf(stderr,
2305 			"pgp_seckey_free: Unknown algorithm: %d (%s)\n",
2306 			key->pubkey.alg,
2307 			pgp_show_pka(key->pubkey.alg));
2308 	}
2309 	free(key->checkhash);
2310 }
2311 
2312 static int
2313 consume_packet(pgp_region_t *region, pgp_stream_t *stream, unsigned warn)
2314 {
2315 	pgp_packet_t	pkt;
2316 	pgp_data_t	remainder;
2317 
2318 	if (region->indeterminate) {
2319 		ERRP(&stream->cbinfo, pkt,
2320 			"Can't consume indeterminate packets");
2321 	}
2322 
2323 	if (read_data(&remainder, region, stream)) {
2324 		/* now throw it away */
2325 		pgp_data_free(&remainder);
2326 		if (warn) {
2327 			PGP_ERROR_1(&stream->errors, PGP_E_P_PACKET_CONSUMED,
2328 			    "%s", "Warning: packet consumer");
2329 		}
2330 		return 1;
2331 	}
2332 	PGP_ERROR_1(&stream->errors, PGP_E_P_PACKET_NOT_CONSUMED,
2333 	    "%s", (warn) ? "Warning: Packet was not consumed" :
2334 	    "Packet was not consumed");
2335 	return warn;
2336 }
2337 
2338 /**
2339  * \ingroup Core_ReadPackets
2340  * \brief Parse a secret key
2341  */
2342 static int
2343 parse_seckey(pgp_region_t *region, pgp_stream_t *stream)
2344 {
2345 	pgp_packet_t		pkt;
2346 	pgp_region_t		encregion;
2347 	pgp_region_t	       *saved_region = NULL;
2348 	pgp_crypt_t		decrypt;
2349 	pgp_hash_t		checkhash;
2350 	unsigned		blocksize;
2351 	unsigned		crypted;
2352 	uint8_t			c = 0x0;
2353 	int			ret = 1;
2354 
2355 	if (pgp_get_debug_level(__FILE__)) {
2356 		fprintf(stderr, "\n---------\nparse_seckey:\n");
2357 		fprintf(stderr,
2358 			"region length=%u, readc=%u, remainder=%u\n",
2359 			region->length, region->readc,
2360 			region->length - region->readc);
2361 	}
2362 	(void) memset(&pkt, 0x0, sizeof(pkt));
2363 	if (!parse_pubkey_data(&pkt.u.seckey.pubkey, region, stream)) {
2364 		return 0;
2365 	}
2366 	if (pgp_get_debug_level(__FILE__)) {
2367 		fprintf(stderr, "parse_seckey: public key parsed\n");
2368 		pgp_print_pubkey(&pkt.u.seckey.pubkey);
2369 	}
2370 	stream->reading_v3_secret = (pkt.u.seckey.pubkey.version != PGP_V4);
2371 
2372 	if (!limread(&c, 1, region, stream)) {
2373 		return 0;
2374 	}
2375 	pkt.u.seckey.s2k_usage = (pgp_s2k_usage_t)c;
2376 
2377 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED ||
2378 	    pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2379 		if (!limread(&c, 1, region, stream)) {
2380 			return 0;
2381 		}
2382 		pkt.u.seckey.alg = (pgp_symm_alg_t)c;
2383 		if (!limread(&c, 1, region, stream)) {
2384 			return 0;
2385 		}
2386 		pkt.u.seckey.s2k_specifier = (pgp_s2k_specifier_t)c;
2387 		switch (pkt.u.seckey.s2k_specifier) {
2388 		case PGP_S2KS_SIMPLE:
2389 		case PGP_S2KS_SALTED:
2390 		case PGP_S2KS_ITERATED_AND_SALTED:
2391 			break;
2392 		default:
2393 			(void) fprintf(stderr,
2394 				"parse_seckey: bad seckey\n");
2395 			return 0;
2396 		}
2397 		if (!limread(&c, 1, region, stream)) {
2398 			return 0;
2399 		}
2400 		pkt.u.seckey.hash_alg = (pgp_hash_alg_t)c;
2401 		if (pkt.u.seckey.s2k_specifier != PGP_S2KS_SIMPLE &&
2402 		    !limread(pkt.u.seckey.salt, 8, region, stream)) {
2403 			return 0;
2404 		}
2405 		if (pkt.u.seckey.s2k_specifier ==
2406 					PGP_S2KS_ITERATED_AND_SALTED) {
2407 			if (!limread(&c, 1, region, stream)) {
2408 				return 0;
2409 			}
2410 			pkt.u.seckey.octetc =
2411 				(16 + ((unsigned)c & 15)) <<
2412 						(((unsigned)c >> 4) + 6);
2413 		}
2414 	} else if (pkt.u.seckey.s2k_usage != PGP_S2KU_NONE) {
2415 		/* this is V3 style, looks just like a V4 simple hash */
2416 		pkt.u.seckey.alg = (pgp_symm_alg_t)c;
2417 		pkt.u.seckey.s2k_usage = PGP_S2KU_ENCRYPTED;
2418 		pkt.u.seckey.s2k_specifier = PGP_S2KS_SIMPLE;
2419 		pkt.u.seckey.hash_alg = PGP_HASH_MD5;
2420 	}
2421 	crypted = pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED ||
2422 		pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED;
2423 
2424 	if (crypted) {
2425 		pgp_packet_t	seckey;
2426 		pgp_hash_t	hashes[(PGP_MAX_KEY_SIZE + PGP_MIN_HASH_SIZE - 1) / PGP_MIN_HASH_SIZE];
2427 		unsigned	passlen;
2428 		uint8_t   	key[PGP_MAX_KEY_SIZE + PGP_MAX_HASH_SIZE];
2429 		char           *passphrase;
2430 		int             hashsize;
2431 		int             keysize;
2432 		int             n;
2433 
2434 		if (pgp_get_debug_level(__FILE__)) {
2435 			(void) fprintf(stderr, "crypted seckey\n");
2436 		}
2437 		blocksize = pgp_block_size(pkt.u.seckey.alg);
2438 		if (blocksize == 0 || blocksize > PGP_MAX_BLOCK_SIZE) {
2439 			(void) fprintf(stderr,
2440 				"parse_seckey: bad blocksize\n");
2441 			return 0;
2442 		}
2443 
2444 		if (!limread(pkt.u.seckey.iv, blocksize, region, stream)) {
2445 			return 0;
2446 		}
2447 		(void) memset(&seckey, 0x0, sizeof(seckey));
2448 		passphrase = NULL;
2449 		seckey.u.skey_passphrase.passphrase = &passphrase;
2450 		seckey.u.skey_passphrase.seckey = &pkt.u.seckey;
2451 		CALLBACK(PGP_GET_PASSPHRASE, &stream->cbinfo, &seckey);
2452 		if (!passphrase) {
2453 			if (pgp_get_debug_level(__FILE__)) {
2454 				/* \todo make into proper error */
2455 				(void) fprintf(stderr,
2456 				"parse_seckey: can't get passphrase\n");
2457 			}
2458 			if (!consume_packet(region, stream, 0)) {
2459 				return 0;
2460 			}
2461 
2462 			CALLBACK(PGP_PTAG_CT_ENCRYPTED_SECRET_KEY,
2463 				&stream->cbinfo, &pkt);
2464 
2465 			return 1;
2466 		}
2467 		keysize = pgp_key_size(pkt.u.seckey.alg);
2468 		if (keysize == 0 || keysize > PGP_MAX_KEY_SIZE) {
2469 			(void) fprintf(stderr,
2470 				"parse_seckey: bad keysize\n");
2471 			return 0;
2472 		}
2473 
2474 		/* Hardcoded SHA1 for just now */
2475 		pkt.u.seckey.hash_alg = PGP_HASH_SHA1;
2476 		hashsize = pgp_hash_size(pkt.u.seckey.hash_alg);
2477 		if (hashsize == 0 || hashsize > PGP_MAX_HASH_SIZE) {
2478 			(void) fprintf(stderr,
2479 				"parse_seckey: bad hashsize\n");
2480 			return 0;
2481 		}
2482 
2483 		for (n = 0; n * hashsize < keysize; ++n) {
2484 			int             i;
2485 
2486 			pgp_hash_any(&hashes[n],
2487 				pkt.u.seckey.hash_alg);
2488 			if (!hashes[n].init(&hashes[n])) {
2489 				(void) fprintf(stderr,
2490 					"parse_seckey: bad alloc\n");
2491 				return 0;
2492 			}
2493 			/* preload hashes with zeroes... */
2494 			for (i = 0; i < n; ++i) {
2495 				hashes[n].add(&hashes[n],
2496 					(const uint8_t *) "", 1);
2497 			}
2498 		}
2499 		passlen = (unsigned)strlen(passphrase);
2500 		for (n = 0; n * hashsize < keysize; ++n) {
2501 			unsigned        i;
2502 
2503 			switch (pkt.u.seckey.s2k_specifier) {
2504 			case PGP_S2KS_SALTED:
2505 				hashes[n].add(&hashes[n],
2506 					pkt.u.seckey.salt,
2507 					PGP_SALT_SIZE);
2508 				/* FALLTHROUGH */
2509 			case PGP_S2KS_SIMPLE:
2510 				hashes[n].add(&hashes[n],
2511 					(uint8_t *)passphrase, (unsigned)passlen);
2512 				break;
2513 
2514 			case PGP_S2KS_ITERATED_AND_SALTED:
2515 				for (i = 0; i < pkt.u.seckey.octetc;
2516 						i += passlen + PGP_SALT_SIZE) {
2517 					unsigned	j;
2518 
2519 					j = passlen + PGP_SALT_SIZE;
2520 					if (i + j > pkt.u.seckey.octetc && i != 0) {
2521 						j = pkt.u.seckey.octetc - i;
2522 					}
2523 					hashes[n].add(&hashes[n],
2524 						pkt.u.seckey.salt,
2525 						(unsigned)(j > PGP_SALT_SIZE) ?
2526 							PGP_SALT_SIZE : j);
2527 					if (j > PGP_SALT_SIZE) {
2528 						hashes[n].add(&hashes[n],
2529 						(uint8_t *) passphrase,
2530 						j - PGP_SALT_SIZE);
2531 					}
2532 				}
2533 				break;
2534 			default:
2535 				break;
2536 			}
2537 		}
2538 
2539 		for (n = 0; n * hashsize < keysize; ++n) {
2540 			int	r;
2541 
2542 			r = hashes[n].finish(&hashes[n], key + n * hashsize);
2543 			if (r != hashsize) {
2544 				(void) fprintf(stderr,
2545 					"parse_seckey: bad r\n");
2546 				return 0;
2547 			}
2548 		}
2549 
2550 		pgp_forget(passphrase, passlen);
2551 
2552 		pgp_crypt_any(&decrypt, pkt.u.seckey.alg);
2553 		if (pgp_get_debug_level(__FILE__)) {
2554 			hexdump(stderr, "input iv", pkt.u.seckey.iv, pgp_block_size(pkt.u.seckey.alg));
2555 			hexdump(stderr, "key", key, CAST_KEY_LENGTH);
2556 		}
2557 		decrypt.set_iv(&decrypt, pkt.u.seckey.iv);
2558 		decrypt.set_crypt_key(&decrypt, key);
2559 
2560 		/* now read encrypted data */
2561 
2562 		pgp_reader_push_decrypt(stream, &decrypt, region);
2563 
2564 		/*
2565 		 * Since all known encryption for PGP doesn't compress, we
2566 		 * can limit to the same length as the current region (for
2567 		 * now).
2568 		 */
2569 		pgp_init_subregion(&encregion, NULL);
2570 		encregion.length = region->length - region->readc;
2571 		if (pkt.u.seckey.pubkey.version != PGP_V4) {
2572 			encregion.length -= 2;
2573 		}
2574 		saved_region = region;
2575 		region = &encregion;
2576 	}
2577 	if (pgp_get_debug_level(__FILE__)) {
2578 		fprintf(stderr, "parse_seckey: end of crypted passphrase\n");
2579 	}
2580 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2581 		/* XXX - Hard-coded SHA1 here ?? Check */
2582 		pkt.u.seckey.checkhash = calloc(1, PGP_SHA1_HASH_SIZE);
2583 		if (pkt.u.seckey.checkhash == NULL) {
2584 			(void) fprintf(stderr, "parse_seckey: bad alloc\n");
2585 			return 0;
2586 		}
2587 		pgp_hash_sha1(&checkhash);
2588 		pgp_reader_push_hash(stream, &checkhash);
2589 	} else {
2590 		pgp_reader_push_sum16(stream);
2591 	}
2592 	if (pgp_get_debug_level(__FILE__)) {
2593 		fprintf(stderr, "parse_seckey: checkhash, reading MPIs\n");
2594 	}
2595 	switch (pkt.u.seckey.pubkey.alg) {
2596 	case PGP_PKA_RSA:
2597 	case PGP_PKA_RSA_ENCRYPT_ONLY:
2598 	case PGP_PKA_RSA_SIGN_ONLY:
2599 		if (!limread_mpi(&pkt.u.seckey.key.rsa.d, region, stream) ||
2600 		    !limread_mpi(&pkt.u.seckey.key.rsa.p, region, stream) ||
2601 		    !limread_mpi(&pkt.u.seckey.key.rsa.q, region, stream) ||
2602 		    !limread_mpi(&pkt.u.seckey.key.rsa.u, region, stream)) {
2603 			ret = 0;
2604 		}
2605 		break;
2606 
2607 	case PGP_PKA_DSA:
2608 		if (!limread_mpi(&pkt.u.seckey.key.dsa.x, region, stream)) {
2609 			ret = 0;
2610 		}
2611 		break;
2612 
2613 	case PGP_PKA_ELGAMAL:
2614 		if (!limread_mpi(&pkt.u.seckey.key.elgamal.x, region, stream)) {
2615 			ret = 0;
2616 		}
2617 		break;
2618 
2619 	default:
2620 		PGP_ERROR_2(&stream->errors,
2621 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2622 			"Unsupported Public Key algorithm %d (%s)",
2623 			pkt.u.seckey.pubkey.alg,
2624 			pgp_show_pka(pkt.u.seckey.pubkey.alg));
2625 		ret = 0;
2626 	}
2627 
2628 	if (pgp_get_debug_level(__FILE__)) {
2629 		(void) fprintf(stderr, "4 MPIs read\n");
2630 	}
2631 	stream->reading_v3_secret = 0;
2632 
2633 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2634 		uint8_t   hash[PGP_CHECKHASH_SIZE];
2635 
2636 		pgp_reader_pop_hash(stream);
2637 		checkhash.finish(&checkhash, hash);
2638 
2639 		if (crypted &&
2640 		    pkt.u.seckey.pubkey.version != PGP_V4) {
2641 			pgp_reader_pop_decrypt(stream);
2642 			region = saved_region;
2643 		}
2644 		if (ret) {
2645 			if (!limread(pkt.u.seckey.checkhash,
2646 				PGP_CHECKHASH_SIZE, region, stream)) {
2647 				return 0;
2648 			}
2649 
2650 			if (memcmp(hash, pkt.u.seckey.checkhash,
2651 					PGP_CHECKHASH_SIZE) != 0) {
2652 				ERRP(&stream->cbinfo, pkt,
2653 					"Hash mismatch in secret key");
2654 			}
2655 		}
2656 	} else {
2657 		uint16_t  sum;
2658 
2659 		sum = pgp_reader_pop_sum16(stream);
2660 		if (crypted &&
2661 		    pkt.u.seckey.pubkey.version != PGP_V4) {
2662 			pgp_reader_pop_decrypt(stream);
2663 			region = saved_region;
2664 		}
2665 		if (ret) {
2666 			if (!limread_scalar(&pkt.u.seckey.checksum, 2,
2667 					region, stream))
2668 				return 0;
2669 
2670 			if (sum != pkt.u.seckey.checksum) {
2671 				ERRP(&stream->cbinfo, pkt,
2672 					"Checksum mismatch in secret key");
2673 			}
2674 		}
2675 	}
2676 
2677 	if (crypted && pkt.u.seckey.pubkey.version == PGP_V4) {
2678 		pgp_reader_pop_decrypt(stream);
2679 	}
2680 	if (region == NULL) {
2681 		(void) fprintf(stderr, "parse_seckey: NULL region\n");
2682 		return 0;
2683 	}
2684 	if (ret && region->readc != region->length) {
2685 		(void) fprintf(stderr, "parse_seckey: bad length\n");
2686 		return 0;
2687 	}
2688 	if (!ret) {
2689 		return 0;
2690 	}
2691 	CALLBACK(PGP_PTAG_CT_SECRET_KEY, &stream->cbinfo, &pkt);
2692 	if (pgp_get_debug_level(__FILE__)) {
2693 		(void) fprintf(stderr, "--- end of parse_seckey\n\n");
2694 	}
2695 	return 1;
2696 }
2697 
2698 /**
2699    \ingroup Core_ReadPackets
2700    \brief Parse a Public Key Session Key packet
2701 */
2702 static int
2703 parse_pk_sesskey(pgp_region_t *region,
2704 		     pgp_stream_t *stream)
2705 {
2706 	const pgp_seckey_t	*secret;
2707 	pgp_packet_t		 sesskey;
2708 	pgp_packet_t		 pkt;
2709 	uint8_t			*iv;
2710 	uint8_t		   	 c = 0x0;
2711 	uint8_t			 cs[2];
2712 	unsigned		 k;
2713 	BIGNUM			*g_to_k;
2714 	BIGNUM			*enc_m;
2715 	int			 n;
2716 	uint8_t		 	 unencoded_m_buf[1024];
2717 
2718 	if (!limread(&c, 1, region, stream)) {
2719 		(void) fprintf(stderr, "parse_pk_sesskey - can't read char in region\n");
2720 		return 0;
2721 	}
2722 	pkt.u.pk_sesskey.version = c;
2723 	if (pkt.u.pk_sesskey.version != 3) {
2724 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_PKSK_VRSN,
2725 			"Bad public-key encrypted session key version (%d)",
2726 			    pkt.u.pk_sesskey.version);
2727 		return 0;
2728 	}
2729 	if (!limread(pkt.u.pk_sesskey.key_id,
2730 			  (unsigned)sizeof(pkt.u.pk_sesskey.key_id), region, stream)) {
2731 		return 0;
2732 	}
2733 	if (pgp_get_debug_level(__FILE__)) {
2734 		hexdump(stderr, "sesskey: pubkey id", pkt.u.pk_sesskey.key_id, sizeof(pkt.u.pk_sesskey.key_id));
2735 	}
2736 	if (!limread(&c, 1, region, stream)) {
2737 		return 0;
2738 	}
2739 	pkt.u.pk_sesskey.alg = (pgp_pubkey_alg_t)c;
2740 	switch (pkt.u.pk_sesskey.alg) {
2741 	case PGP_PKA_RSA:
2742 		if (!limread_mpi(&pkt.u.pk_sesskey.params.rsa.encrypted_m,
2743 				      region, stream)) {
2744 			return 0;
2745 		}
2746 		enc_m = pkt.u.pk_sesskey.params.rsa.encrypted_m;
2747 		g_to_k = NULL;
2748 		break;
2749 
2750 	case PGP_PKA_DSA:
2751 	case PGP_PKA_ELGAMAL:
2752 		if (!limread_mpi(&pkt.u.pk_sesskey.params.elgamal.g_to_k,
2753 				      region, stream) ||
2754 		    !limread_mpi(
2755 			&pkt.u.pk_sesskey.params.elgamal.encrypted_m,
2756 					 region, stream)) {
2757 			return 0;
2758 		}
2759 		g_to_k = pkt.u.pk_sesskey.params.elgamal.g_to_k;
2760 		enc_m = pkt.u.pk_sesskey.params.elgamal.encrypted_m;
2761 		break;
2762 
2763 	default:
2764 		PGP_ERROR_1(&stream->errors,
2765 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2766 			"Unknown public key algorithm in session key (%s)",
2767 			pgp_show_pka(pkt.u.pk_sesskey.alg));
2768 		return 0;
2769 	}
2770 
2771 	(void) memset(&sesskey, 0x0, sizeof(sesskey));
2772 	secret = NULL;
2773 	sesskey.u.get_seckey.seckey = &secret;
2774 	sesskey.u.get_seckey.pk_sesskey = &pkt.u.pk_sesskey;
2775 
2776 	if (pgp_get_debug_level(__FILE__)) {
2777 		(void) fprintf(stderr, "getting secret key via callback\n");
2778 	}
2779 
2780 	CALLBACK(PGP_GET_SECKEY, &stream->cbinfo, &sesskey);
2781 
2782 	if (pgp_get_debug_level(__FILE__)) {
2783 		(void) fprintf(stderr, "got secret key via callback\n");
2784 	}
2785 	if (!secret) {
2786 		CALLBACK(PGP_PTAG_CT_ENCRYPTED_PK_SESSION_KEY, &stream->cbinfo,
2787 			&pkt);
2788 		return 1;
2789 	}
2790 	n = pgp_decrypt_decode_mpi(unencoded_m_buf,
2791 		(unsigned)sizeof(unencoded_m_buf), g_to_k, enc_m, secret);
2792 
2793 	if (n < 1) {
2794 		ERRP(&stream->cbinfo, pkt, "decrypted message too short");
2795 		return 0;
2796 	}
2797 
2798 	/* PKA */
2799 	pkt.u.pk_sesskey.symm_alg = (pgp_symm_alg_t)unencoded_m_buf[0];
2800 	if (pgp_get_debug_level(__FILE__)) {
2801 		(void) fprintf(stderr, "symm alg %d\n", pkt.u.pk_sesskey.symm_alg);
2802 	}
2803 
2804 	if (!pgp_is_sa_supported(pkt.u.pk_sesskey.symm_alg)) {
2805 		/* ERR1P */
2806 		PGP_ERROR_1(&stream->errors, PGP_E_ALG_UNSUPPORTED_SYMMETRIC_ALG,
2807 			    "Symmetric algorithm %s not supported",
2808 			    pgp_show_symm_alg(
2809 				pkt.u.pk_sesskey.symm_alg));
2810 		return 0;
2811 	}
2812 	k = pgp_key_size(pkt.u.pk_sesskey.symm_alg);
2813 	if (pgp_get_debug_level(__FILE__)) {
2814 		(void) fprintf(stderr, "key size %d\n", k);
2815 	}
2816 
2817 	if ((unsigned) n != k + 3) {
2818 		PGP_ERROR_2(&stream->errors, PGP_E_PROTO_DECRYPTED_MSG_WRONG_LEN,
2819 		      "decrypted message wrong length (got %d expected %d)",
2820 			    n, k + 3);
2821 		return 0;
2822 	}
2823 	if (k > sizeof(pkt.u.pk_sesskey.key)) {
2824 		(void) fprintf(stderr, "parse_pk_sesskey: bad keylength\n");
2825 		return 0;
2826 	}
2827 
2828 	(void) memcpy(pkt.u.pk_sesskey.key, unencoded_m_buf + 1, k);
2829 
2830 	if (pgp_get_debug_level(__FILE__)) {
2831 		hexdump(stderr, "recovered sesskey", pkt.u.pk_sesskey.key, k);
2832 	}
2833 	pkt.u.pk_sesskey.checksum = unencoded_m_buf[k + 1] +
2834 			(unencoded_m_buf[k + 2] << 8);
2835 	if (pgp_get_debug_level(__FILE__)) {
2836 		(void) fprintf(stderr, "session key checksum: %2x %2x\n",
2837 			unencoded_m_buf[k + 1], unencoded_m_buf[k + 2]);
2838 	}
2839 
2840 	/* Check checksum */
2841 	pgp_calc_sesskey_checksum(&pkt.u.pk_sesskey, &cs[0]);
2842 	if (unencoded_m_buf[k + 1] != cs[0] ||
2843 	    unencoded_m_buf[k + 2] != cs[1]) {
2844 		PGP_ERROR_4(&stream->errors, PGP_E_PROTO_BAD_SK_CHECKSUM,
2845 		"Session key checksum wrong: expected %2x %2x, got %2x %2x",
2846 		cs[0], cs[1], unencoded_m_buf[k + 1],
2847 		unencoded_m_buf[k + 2]);
2848 		return 0;
2849 	}
2850 
2851 	if (pgp_get_debug_level(__FILE__)) {
2852 		(void) fprintf(stderr, "getting pk session key via callback\n");
2853 	}
2854 	/* all is well */
2855 	CALLBACK(PGP_PTAG_CT_PK_SESSION_KEY, &stream->cbinfo, &pkt);
2856 	if (pgp_get_debug_level(__FILE__)) {
2857 		(void) fprintf(stderr, "got pk session key via callback\n");
2858 	}
2859 
2860 	pgp_crypt_any(&stream->decrypt, pkt.u.pk_sesskey.symm_alg);
2861 	iv = calloc(1, stream->decrypt.blocksize);
2862 	if (iv == NULL) {
2863 		(void) fprintf(stderr, "parse_pk_sesskey: bad alloc\n");
2864 		return 0;
2865 	}
2866 	stream->decrypt.set_iv(&stream->decrypt, iv);
2867 	stream->decrypt.set_crypt_key(&stream->decrypt, pkt.u.pk_sesskey.key);
2868 	pgp_encrypt_init(&stream->decrypt);
2869 	free(iv);
2870 	return 1;
2871 }
2872 
2873 static int
2874 decrypt_se_data(pgp_content_enum tag, pgp_region_t *region,
2875 		    pgp_stream_t *stream)
2876 {
2877 	pgp_crypt_t	*decrypt;
2878 	const int	 printerrors = 1;
2879 	int		 r = 1;
2880 
2881 	decrypt = pgp_get_decrypt(stream);
2882 	if (decrypt) {
2883 		pgp_region_t	encregion;
2884 		unsigned	b = (unsigned)decrypt->blocksize;
2885 		uint8_t		buf[PGP_MAX_BLOCK_SIZE + 2] = "";
2886 
2887 		pgp_reader_push_decrypt(stream, decrypt, region);
2888 
2889 		pgp_init_subregion(&encregion, NULL);
2890 		encregion.length = b + 2;
2891 
2892 		if (!exact_limread(buf, b + 2, &encregion, stream)) {
2893 			return 0;
2894 		}
2895 		if (buf[b - 2] != buf[b] || buf[b - 1] != buf[b + 1]) {
2896 			pgp_reader_pop_decrypt(stream);
2897 			PGP_ERROR_4(&stream->errors,
2898 				PGP_E_PROTO_BAD_SYMMETRIC_DECRYPT,
2899 				"Bad symmetric decrypt (%02x%02x vs %02x%02x)",
2900 				buf[b - 2], buf[b - 1], buf[b], buf[b + 1]);
2901 			return 0;
2902 		}
2903 		if (tag == PGP_PTAG_CT_SE_DATA_BODY) {
2904 			decrypt->decrypt_resync(decrypt);
2905 			decrypt->block_encrypt(decrypt, decrypt->civ,
2906 					decrypt->civ);
2907 		}
2908 		r = pgp_parse(stream, !printerrors);
2909 
2910 		pgp_reader_pop_decrypt(stream);
2911 	} else {
2912 		pgp_packet_t pkt;
2913 
2914 		while (region->readc < region->length) {
2915 			unsigned        len;
2916 
2917 			len = region->length - region->readc;
2918 			if (len > sizeof(pkt.u.se_data_body.data))
2919 				len = sizeof(pkt.u.se_data_body.data);
2920 
2921 			if (!limread(pkt.u.se_data_body.data, len,
2922 					region, stream)) {
2923 				return 0;
2924 			}
2925 			pkt.u.se_data_body.length = len;
2926 			CALLBACK(tag, &stream->cbinfo, &pkt);
2927 		}
2928 	}
2929 
2930 	return r;
2931 }
2932 
2933 static int
2934 decrypt_se_ip_data(pgp_content_enum tag, pgp_region_t *region,
2935 		       pgp_stream_t *stream)
2936 {
2937 	pgp_crypt_t	*decrypt;
2938 	const int	 printerrors = 1;
2939 	int		 r = 1;
2940 
2941 	decrypt = pgp_get_decrypt(stream);
2942 	if (decrypt) {
2943 		if (pgp_get_debug_level(__FILE__)) {
2944 			(void) fprintf(stderr, "decrypt_se_ip_data: decrypt\n");
2945 		}
2946 		pgp_reader_push_decrypt(stream, decrypt, region);
2947 		pgp_reader_push_se_ip_data(stream, decrypt, region);
2948 
2949 		r = pgp_parse(stream, !printerrors);
2950 
2951 		pgp_reader_pop_se_ip_data(stream);
2952 		pgp_reader_pop_decrypt(stream);
2953 	} else {
2954 		pgp_packet_t pkt;
2955 
2956 		if (pgp_get_debug_level(__FILE__)) {
2957 			(void) fprintf(stderr, "decrypt_se_ip_data: no decrypt\n");
2958 		}
2959 		while (region->readc < region->length) {
2960 			unsigned        len;
2961 
2962 			len = region->length - region->readc;
2963 			if (len > sizeof(pkt.u.se_data_body.data)) {
2964 				len = sizeof(pkt.u.se_data_body.data);
2965 			}
2966 
2967 			if (!limread(pkt.u.se_data_body.data,
2968 					len, region, stream)) {
2969 				return 0;
2970 			}
2971 
2972 			pkt.u.se_data_body.length = len;
2973 
2974 			CALLBACK(tag, &stream->cbinfo, &pkt);
2975 		}
2976 	}
2977 
2978 	return r;
2979 }
2980 
2981 /**
2982    \ingroup Core_ReadPackets
2983    \brief Read a Symmetrically Encrypted packet
2984 */
2985 static int
2986 parse_se_data(pgp_region_t *region, pgp_stream_t *stream)
2987 {
2988 	pgp_packet_t pkt;
2989 
2990 	/* there's no info to go with this, so just announce it */
2991 	CALLBACK(PGP_PTAG_CT_SE_DATA_HEADER, &stream->cbinfo, &pkt);
2992 
2993 	/*
2994 	 * The content of an encrypted data packet is more OpenPGP packets
2995 	 * once decrypted, so recursively handle them
2996 	 */
2997 	return decrypt_se_data(PGP_PTAG_CT_SE_DATA_BODY, region, stream);
2998 }
2999 
3000 /**
3001    \ingroup Core_ReadPackets
3002    \brief Read a Symmetrically Encrypted Integrity Protected packet
3003 */
3004 static int
3005 parse_se_ip_data(pgp_region_t *region, pgp_stream_t *stream)
3006 {
3007 	pgp_packet_t	pkt;
3008 	uint8_t		c = 0x0;
3009 
3010 	if (!limread(&c, 1, region, stream)) {
3011 		return 0;
3012 	}
3013 	pkt.u.se_ip_data_header = c;
3014 	if (pgp_get_debug_level(__FILE__)) {
3015 		(void) fprintf(stderr, "parse_se_ip_data: data header %d\n", c);
3016 	}
3017 	if (pkt.u.se_ip_data_header != PGP_SE_IP_DATA_VERSION) {
3018 		(void) fprintf(stderr, "parse_se_ip_data: bad version\n");
3019 		return 0;
3020 	}
3021 
3022 	if (pgp_get_debug_level(__FILE__)) {
3023 		(void) fprintf(stderr, "parse_se_ip_data: region %d,%d\n",
3024 			region->readc, region->length);
3025 		hexdump(stderr, "compressed region", stream->virtualpkt, stream->virtualc);
3026 	}
3027 	/*
3028 	 * The content of an encrypted data packet is more OpenPGP packets
3029 	 * once decrypted, so recursively handle them
3030 	 */
3031 	return decrypt_se_ip_data(PGP_PTAG_CT_SE_IP_DATA_BODY, region, stream);
3032 }
3033 
3034 /**
3035    \ingroup Core_ReadPackets
3036    \brief Read a MDC packet
3037 */
3038 static int
3039 parse_mdc(pgp_region_t *region, pgp_stream_t *stream)
3040 {
3041 	pgp_packet_t pkt;
3042 
3043 	pkt.u.mdc.length = PGP_SHA1_HASH_SIZE;
3044 	if ((pkt.u.mdc.data = calloc(1, PGP_SHA1_HASH_SIZE)) == NULL) {
3045 		(void) fprintf(stderr, "parse_mdc: bad alloc\n");
3046 		return 0;
3047 	}
3048 	if (!limread(pkt.u.mdc.data, PGP_SHA1_HASH_SIZE, region, stream)) {
3049 		return 0;
3050 	}
3051 	CALLBACK(PGP_PTAG_CT_MDC, &stream->cbinfo, &pkt);
3052 	free(pkt.u.mdc.data);
3053 	return 1;
3054 }
3055 
3056 /**
3057  * \ingroup Core_ReadPackets
3058  * \brief Parse one packet.
3059  *
3060  * This function parses the packet tag.  It computes the value of the
3061  * content tag and then calls the appropriate function to handle the
3062  * content.
3063  *
3064  * \param *stream	How to parse
3065  * \param *pktlen	On return, will contain number of bytes in packet
3066  * \return 1 on success, 0 on error, -1 on EOF */
3067 static int
3068 parse_packet(pgp_stream_t *stream, uint32_t *pktlen)
3069 {
3070 	pgp_packet_t		pkt;
3071 	pgp_region_t		region;
3072 	pgp_content_enum	tag;
3073 	uint8_t			ptag;
3074 	unsigned		indeterminate = 0;
3075 	int			ret;
3076 
3077 	pkt.u.ptag.position = stream->readinfo.position;
3078 
3079 	ret = base_read(&ptag, 1, stream);
3080 
3081 	if (pgp_get_debug_level(__FILE__)) {
3082 		(void) fprintf(stderr,
3083 			"parse_packet: base_read returned %d, ptag %d\n",
3084 			ret, ptag);
3085 	}
3086 
3087 	/* errors in the base read are effectively EOF. */
3088 	if (ret <= 0) {
3089 		return -1;
3090 	}
3091 
3092 	*pktlen = 0;
3093 
3094 	if (!(ptag & PGP_PTAG_ALWAYS_SET)) {
3095 		pkt.u.error = "Format error (ptag bit not set)";
3096 		CALLBACK(PGP_PARSER_ERROR, &stream->cbinfo, &pkt);
3097 		return 0;
3098 	}
3099 	pkt.u.ptag.new_format = !!(ptag & PGP_PTAG_NEW_FORMAT);
3100 	if (pkt.u.ptag.new_format) {
3101 		pkt.u.ptag.type = (ptag & PGP_PTAG_NF_CONTENT_TAG_MASK);
3102 		pkt.u.ptag.length_type = 0;
3103 		if (!read_new_length(&pkt.u.ptag.length, stream)) {
3104 			return 0;
3105 		}
3106 	} else {
3107 		unsigned   rb;
3108 
3109 		rb = 0;
3110 		pkt.u.ptag.type = ((unsigned)ptag &
3111 				PGP_PTAG_OF_CONTENT_TAG_MASK)
3112 			>> PGP_PTAG_OF_CONTENT_TAG_SHIFT;
3113 		pkt.u.ptag.length_type = ptag & PGP_PTAG_OF_LENGTH_TYPE_MASK;
3114 		switch (pkt.u.ptag.length_type) {
3115 		case PGP_PTAG_OLD_LEN_1:
3116 			rb = _read_scalar(&pkt.u.ptag.length, 1, stream);
3117 			break;
3118 
3119 		case PGP_PTAG_OLD_LEN_2:
3120 			rb = _read_scalar(&pkt.u.ptag.length, 2, stream);
3121 			break;
3122 
3123 		case PGP_PTAG_OLD_LEN_4:
3124 			rb = _read_scalar(&pkt.u.ptag.length, 4, stream);
3125 			break;
3126 
3127 		case PGP_PTAG_OLD_LEN_INDETERMINATE:
3128 			pkt.u.ptag.length = 0;
3129 			indeterminate = 1;
3130 			rb = 1;
3131 			break;
3132 		}
3133 		if (!rb) {
3134 			return 0;
3135 		}
3136 	}
3137 
3138 	CALLBACK(PGP_PARSER_PTAG, &stream->cbinfo, &pkt);
3139 
3140 	pgp_init_subregion(&region, NULL);
3141 	region.length = pkt.u.ptag.length;
3142 	region.indeterminate = indeterminate;
3143 	if (pgp_get_debug_level(__FILE__)) {
3144 		(void) fprintf(stderr, "parse_packet: type %u\n",
3145 			       pkt.u.ptag.type);
3146 	}
3147 
3148 	/* save tag for accumulator */
3149 	tag = pkt.u.ptag.type;
3150 	switch (pkt.u.ptag.type) {
3151 	case PGP_PTAG_CT_SIGNATURE:
3152 		ret = parse_sig(&region, stream);
3153 		break;
3154 
3155 	case PGP_PTAG_CT_PUBLIC_KEY:
3156 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
3157 		ret = parse_pubkey((pgp_content_enum)pkt.u.ptag.type, &region, stream);
3158 		break;
3159 
3160 	case PGP_PTAG_CT_TRUST:
3161 		ret = parse_trust(&region, stream);
3162 		break;
3163 
3164 	case PGP_PTAG_CT_USER_ID:
3165 		ret = parse_userid(&region, stream);
3166 		break;
3167 
3168 	case PGP_PTAG_CT_COMPRESSED:
3169 		ret = parse_compressed(&region, stream);
3170 		break;
3171 
3172 	case PGP_PTAG_CT_1_PASS_SIG:
3173 		ret = parse_one_pass(&region, stream);
3174 		break;
3175 
3176 	case PGP_PTAG_CT_LITDATA:
3177 		ret = parse_litdata(&region, stream);
3178 		break;
3179 
3180 	case PGP_PTAG_CT_USER_ATTR:
3181 		ret = parse_userattr(&region, stream);
3182 		break;
3183 
3184 	case PGP_PTAG_CT_SECRET_KEY:
3185 		ret = parse_seckey(&region, stream);
3186 		break;
3187 
3188 	case PGP_PTAG_CT_SECRET_SUBKEY:
3189 		ret = parse_seckey(&region, stream);
3190 		break;
3191 
3192 	case PGP_PTAG_CT_PK_SESSION_KEY:
3193 		ret = parse_pk_sesskey(&region, stream);
3194 		break;
3195 
3196 	case PGP_PTAG_CT_SE_DATA:
3197 		ret = parse_se_data(&region, stream);
3198 		break;
3199 
3200 	case PGP_PTAG_CT_SE_IP_DATA:
3201 		ret = parse_se_ip_data(&region, stream);
3202 		break;
3203 
3204 	case PGP_PTAG_CT_MDC:
3205 		ret = parse_mdc(&region, stream);
3206 		break;
3207 
3208 	default:
3209 		PGP_ERROR_1(&stream->errors, PGP_E_P_UNKNOWN_TAG,
3210 			    "Unknown content tag 0x%x",
3211 			    pkt.u.ptag.type);
3212 		ret = 0;
3213 	}
3214 
3215 	/* Ensure that the entire packet has been consumed */
3216 
3217 	if (region.length != region.readc && !region.indeterminate) {
3218 		if (!consume_packet(&region, stream, 0)) {
3219 			ret = -1;
3220 		}
3221 	}
3222 
3223 	/* also consume it if there's been an error? */
3224 	/* \todo decide what to do about an error on an */
3225 	/* indeterminate packet */
3226 	if (ret == 0) {
3227 		if (!consume_packet(&region, stream, 0)) {
3228 			ret = -1;
3229 		}
3230 	}
3231 	/* set pktlen */
3232 
3233 	*pktlen = stream->readinfo.alength;
3234 
3235 	/* do callback on entire packet, if desired and there was no error */
3236 
3237 	if (ret > 0 && stream->readinfo.accumulate) {
3238 		pkt.u.packet.length = stream->readinfo.alength;
3239 		pkt.u.packet.raw = stream->readinfo.accumulated;
3240 		pkt.u.packet.tag = tag;
3241 		stream->readinfo.accumulated = NULL;
3242 		stream->readinfo.asize = 0;
3243 		CALLBACK(PGP_PARSER_PACKET_END, &stream->cbinfo, &pkt);
3244 	}
3245 	stream->readinfo.alength = 0;
3246 
3247 	return (ret < 0) ? -1 : (ret) ? 1 : 0;
3248 }
3249 
3250 /**
3251  * \ingroup Core_ReadPackets
3252  *
3253  * \brief Parse packets from an input stream until EOF or error.
3254  *
3255  * \details Setup the necessary parsing configuration in "stream"
3256  * before calling pgp_parse().
3257  *
3258  * That information includes :
3259  *
3260  * - a "reader" function to be used to get the data to be parsed
3261  *
3262  * - a "callback" function to be called when this library has identified
3263  * a parseable object within the data
3264  *
3265  * - whether the calling function wants the signature subpackets
3266  * returned raw, parsed or not at all.
3267  *
3268  * After returning, stream->errors holds any errors encountered while parsing.
3269  *
3270  * \param stream	Parsing configuration
3271  * \return		1 on success in all packets, 0 on error in any packet
3272  *
3273  * \sa CoreAPI Overview
3274  *
3275  * \sa pgp_print_errors()
3276  *
3277  */
3278 
3279 int
3280 pgp_parse(pgp_stream_t *stream, const int perrors)
3281 {
3282 	uint32_t   pktlen;
3283 	int             r;
3284 
3285 	do {
3286 		r = parse_packet(stream, &pktlen);
3287 	} while (r != -1);
3288 	if (perrors) {
3289 		pgp_print_errors(stream->errors);
3290 	}
3291 	return (stream->errors == NULL);
3292 }
3293 
3294 /**
3295  * \ingroup Core_ReadPackets
3296  *
3297  * \brief Specifies whether one or more signature
3298  * subpacket types should be returned parsed; or raw; or ignored.
3299  *
3300  * \param	stream	Pointer to previously allocated structure
3301  * \param	tag	Packet tag. PGP_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
3302  * \param	type	Parse type
3303  * \todo Make all packet types optional, not just subpackets */
3304 void
3305 pgp_parse_options(pgp_stream_t *stream,
3306 		  pgp_content_enum tag,
3307 		  pgp_parse_type_t type)
3308 {
3309 	unsigned	t7;
3310 	unsigned	t8;
3311 
3312 	if (tag == PGP_PTAG_SS_ALL) {
3313 		int             n;
3314 
3315 		for (n = 0; n < 256; ++n) {
3316 			pgp_parse_options(stream,
3317 				PGP_PTAG_SIG_SUBPKT_BASE + n,
3318 				type);
3319 		}
3320 		return;
3321 	}
3322 	if (tag < PGP_PTAG_SIG_SUBPKT_BASE ||
3323 	    tag > PGP_PTAG_SIG_SUBPKT_BASE + NTAGS - 1) {
3324 		(void) fprintf(stderr, "pgp_parse_options: bad tag\n");
3325 		return;
3326 	}
3327 	t8 = (tag - PGP_PTAG_SIG_SUBPKT_BASE) / 8;
3328 	t7 = 1 << ((tag - PGP_PTAG_SIG_SUBPKT_BASE) & 7);
3329 	switch (type) {
3330 	case PGP_PARSE_RAW:
3331 		stream->ss_raw[t8] |= t7;
3332 		stream->ss_parsed[t8] &= ~t7;
3333 		break;
3334 
3335 	case PGP_PARSE_PARSED:
3336 		stream->ss_raw[t8] &= ~t7;
3337 		stream->ss_parsed[t8] |= t7;
3338 		break;
3339 
3340 	case PGP_PARSE_IGNORE:
3341 		stream->ss_raw[t8] &= ~t7;
3342 		stream->ss_parsed[t8] &= ~t7;
3343 		break;
3344 	}
3345 }
3346 
3347 /**
3348 \ingroup Core_ReadPackets
3349 \brief Free pgp_stream_t struct and its contents
3350 */
3351 void
3352 pgp_stream_delete(pgp_stream_t *stream)
3353 {
3354 	pgp_cbdata_t	*cbinfo;
3355 	pgp_cbdata_t	*next;
3356 
3357 	for (cbinfo = stream->cbinfo.next; cbinfo; cbinfo = next) {
3358 		next = cbinfo->next;
3359 		free(cbinfo);
3360 	}
3361 	if (stream->readinfo.destroyer) {
3362 		stream->readinfo.destroyer(&stream->readinfo);
3363 	}
3364 	pgp_free_errors(stream->errors);
3365 	if (stream->readinfo.accumulated) {
3366 		free(stream->readinfo.accumulated);
3367 	}
3368 	free(stream);
3369 }
3370 
3371 /**
3372 \ingroup Core_ReadPackets
3373 \brief Returns the parse_info's reader_info
3374 \return Pointer to the reader_info inside the parse_info
3375 */
3376 pgp_reader_t *
3377 pgp_readinfo(pgp_stream_t *stream)
3378 {
3379 	return &stream->readinfo;
3380 }
3381 
3382 /**
3383 \ingroup Core_ReadPackets
3384 \brief Sets the parse_info's callback
3385 This is used when adding the first callback in a stack of callbacks.
3386 \sa pgp_callback_push()
3387 */
3388 
3389 void
3390 pgp_set_callback(pgp_stream_t *stream, pgp_cbfunc_t *cb, void *arg)
3391 {
3392 	stream->cbinfo.cbfunc = cb;
3393 	stream->cbinfo.arg = arg;
3394 	stream->cbinfo.errors = &stream->errors;
3395 }
3396 
3397 /**
3398 \ingroup Core_ReadPackets
3399 \brief Adds a further callback to a stack of callbacks
3400 \sa pgp_set_callback()
3401 */
3402 void
3403 pgp_callback_push(pgp_stream_t *stream, pgp_cbfunc_t *cb, void *arg)
3404 {
3405 	pgp_cbdata_t	*cbinfo;
3406 
3407 	if ((cbinfo = calloc(1, sizeof(*cbinfo))) == NULL) {
3408 		(void) fprintf(stderr, "pgp_callback_push: bad alloc\n");
3409 		return;
3410 	}
3411 	(void) memcpy(cbinfo, &stream->cbinfo, sizeof(*cbinfo));
3412 	cbinfo->io = stream->io;
3413 	stream->cbinfo.next = cbinfo;
3414 	pgp_set_callback(stream, cb, arg);
3415 }
3416 
3417 /**
3418 \ingroup Core_ReadPackets
3419 \brief Returns callback's arg
3420 */
3421 void *
3422 pgp_callback_arg(pgp_cbdata_t *cbinfo)
3423 {
3424 	return cbinfo->arg;
3425 }
3426 
3427 /**
3428 \ingroup Core_ReadPackets
3429 \brief Returns callback's errors
3430 */
3431 void *
3432 pgp_callback_errors(pgp_cbdata_t *cbinfo)
3433 {
3434 	return cbinfo->errors;
3435 }
3436 
3437 /**
3438 \ingroup Core_ReadPackets
3439 \brief Calls the parse_cb_info's callback if present
3440 \return Return value from callback, if present; else PGP_FINISHED
3441 */
3442 pgp_cb_ret_t
3443 pgp_callback(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
3444 {
3445 	return (cbinfo->cbfunc) ? cbinfo->cbfunc(pkt, cbinfo) : PGP_FINISHED;
3446 }
3447 
3448 /**
3449 \ingroup Core_ReadPackets
3450 \brief Calls the next callback  in the stack
3451 \return Return value from callback
3452 */
3453 pgp_cb_ret_t
3454 pgp_stacked_callback(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
3455 {
3456 	return pgp_callback(pkt, cbinfo->next);
3457 }
3458 
3459 /**
3460 \ingroup Core_ReadPackets
3461 \brief Returns the parse_info's errors
3462 \return parse_info's errors
3463 */
3464 pgp_error_t    *
3465 pgp_stream_get_errors(pgp_stream_t *stream)
3466 {
3467 	return stream->errors;
3468 }
3469 
3470 pgp_crypt_t    *
3471 pgp_get_decrypt(pgp_stream_t *stream)
3472 {
3473 	return (stream->decrypt.alg) ? &stream->decrypt : NULL;
3474 }
3475