xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/packet-parse.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
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.53 2020/10/14 05:19:41 jhigh 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_SS_ISSUER_FINGERPRINT:
988 	case PGP_PTAG_CT_LITDATA_HEADER:
989 	case PGP_PTAG_CT_LITDATA_BODY:
990 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_BODY:
991 	case PGP_PTAG_CT_UNARMOURED_TEXT:
992 	case PGP_PTAG_CT_ARMOUR_TRAILER:
993 	case PGP_PTAG_CT_SIGNATURE_HEADER:
994 	case PGP_PTAG_CT_SE_DATA_HEADER:
995 	case PGP_PTAG_CT_SE_IP_DATA_HEADER:
996 	case PGP_PTAG_CT_SE_IP_DATA_BODY:
997 	case PGP_PTAG_CT_MDC:
998 	case PGP_GET_SECKEY:
999 		break;
1000 
1001 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
1002 		headers_free(&c->u.cleartext_head);
1003 		break;
1004 
1005 	case PGP_PTAG_CT_ARMOUR_HEADER:
1006 		headers_free(&c->u.armour_header.headers);
1007 		break;
1008 
1009 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
1010 		cleartext_trailer_free(&c->u.cleartext_trailer);
1011 		break;
1012 
1013 	case PGP_PTAG_CT_TRUST:
1014 		pgp_data_free(&c->u.trust);
1015 		break;
1016 
1017 	case PGP_PTAG_CT_SIGNATURE:
1018 	case PGP_PTAG_CT_SIGNATURE_FOOTER:
1019 		sig_free(&c->u.sig);
1020 		break;
1021 
1022 	case PGP_PTAG_CT_PUBLIC_KEY:
1023 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
1024 		pgp_pubkey_free(&c->u.pubkey);
1025 		break;
1026 
1027 	case PGP_PTAG_CT_USER_ID:
1028 		pgp_userid_free(&c->u.userid);
1029 		break;
1030 
1031 	case PGP_PTAG_SS_SIGNERS_USER_ID:
1032 		pgp_userid_free(&c->u.ss_signer);
1033 		break;
1034 
1035 	case PGP_PTAG_CT_USER_ATTR:
1036 		pgp_data_free(&c->u.userattr);
1037 		break;
1038 
1039 	case PGP_PTAG_SS_PREFERRED_SKA:
1040 		pgp_data_free(&c->u.ss_skapref);
1041 		break;
1042 
1043 	case PGP_PTAG_SS_PREFERRED_HASH:
1044 		pgp_data_free(&c->u.ss_hashpref);
1045 		break;
1046 
1047 	case PGP_PTAG_SS_PREF_COMPRESS:
1048 		pgp_data_free(&c->u.ss_zpref);
1049 		break;
1050 
1051 	case PGP_PTAG_SS_KEY_FLAGS:
1052 		pgp_data_free(&c->u.ss_key_flags);
1053 		break;
1054 
1055 	case PGP_PTAG_SS_KEYSERV_PREFS:
1056 		pgp_data_free(&c->u.ss_key_server_prefs);
1057 		break;
1058 
1059 	case PGP_PTAG_SS_FEATURES:
1060 		pgp_data_free(&c->u.ss_features);
1061 		break;
1062 
1063 	case PGP_PTAG_SS_NOTATION_DATA:
1064 		pgp_data_free(&c->u.ss_notation.name);
1065 		pgp_data_free(&c->u.ss_notation.value);
1066 		break;
1067 
1068 	case PGP_PTAG_SS_REGEXP:
1069 		string_free(&c->u.ss_regexp);
1070 		break;
1071 
1072 	case PGP_PTAG_SS_POLICY_URI:
1073 		string_free(&c->u.ss_policy);
1074 		break;
1075 
1076 	case PGP_PTAG_SS_PREF_KEYSERV:
1077 		string_free(&c->u.ss_keyserv);
1078 		break;
1079 
1080 	case PGP_PTAG_SS_USERDEFINED00:
1081 	case PGP_PTAG_SS_USERDEFINED01:
1082 	case PGP_PTAG_SS_USERDEFINED02:
1083 	case PGP_PTAG_SS_USERDEFINED03:
1084 	case PGP_PTAG_SS_USERDEFINED04:
1085 	case PGP_PTAG_SS_USERDEFINED05:
1086 	case PGP_PTAG_SS_USERDEFINED06:
1087 	case PGP_PTAG_SS_USERDEFINED07:
1088 	case PGP_PTAG_SS_USERDEFINED08:
1089 	case PGP_PTAG_SS_USERDEFINED09:
1090 	case PGP_PTAG_SS_USERDEFINED10:
1091 		pgp_data_free(&c->u.ss_userdef);
1092 		break;
1093 
1094 	case PGP_PTAG_SS_RESERVED:
1095 		pgp_data_free(&c->u.ss_unknown);
1096 		break;
1097 
1098 	case PGP_PTAG_SS_REVOCATION_REASON:
1099 		string_free(&c->u.ss_revocation.reason);
1100 		break;
1101 
1102 	case PGP_PTAG_SS_EMBEDDED_SIGNATURE:
1103 		pgp_data_free(&c->u.ss_embedded_sig);
1104 		break;
1105 
1106 	case PGP_PARSER_PACKET_END:
1107 		pgp_subpacket_free(&c->u.packet);
1108 		break;
1109 
1110 	case PGP_PARSER_ERROR:
1111 	case PGP_PARSER_ERRCODE:
1112 		break;
1113 
1114 	case PGP_PTAG_CT_SECRET_KEY:
1115 	case PGP_PTAG_CT_ENCRYPTED_SECRET_KEY:
1116 		pgp_seckey_free(&c->u.seckey);
1117 		break;
1118 
1119 	case PGP_PTAG_CT_PK_SESSION_KEY:
1120 	case PGP_PTAG_CT_ENCRYPTED_PK_SESSION_KEY:
1121 		pgp_pk_sesskey_free(&c->u.pk_sesskey);
1122 		break;
1123 
1124 	case PGP_GET_PASSPHRASE:
1125 		cmd_get_passphrase_free(&c->u.skey_passphrase);
1126 		break;
1127 
1128 	default:
1129 		fprintf(stderr, "Can't free %d (0x%x)\n", c->tag, c->tag);
1130 	}
1131 }
1132 
1133 /**
1134 \ingroup Core_Create
1135 \brief Free allocated memory
1136 */
1137 void
1138 pgp_pk_sesskey_free(pgp_pk_sesskey_t *sk)
1139 {
1140 	switch (sk->alg) {
1141 	case PGP_PKA_RSA:
1142 		free_BN(&sk->params.rsa.encrypted_m);
1143 		break;
1144 
1145 	case PGP_PKA_ELGAMAL:
1146 		free_BN(&sk->params.elgamal.g_to_k);
1147 		free_BN(&sk->params.elgamal.encrypted_m);
1148 		break;
1149 
1150 	default:
1151 		(void) fprintf(stderr, "pgp_pk_sesskey_free: bad alg\n");
1152 		break;
1153 	}
1154 }
1155 
1156 /**
1157 \ingroup Core_Create
1158 \brief Free allocated memory
1159 */
1160 /* ! Free the memory used when parsing a public key */
1161 void
1162 pgp_pubkey_free(pgp_pubkey_t *p)
1163 {
1164 	switch (p->alg) {
1165 	case PGP_PKA_RSA:
1166 	case PGP_PKA_RSA_ENCRYPT_ONLY:
1167 	case PGP_PKA_RSA_SIGN_ONLY:
1168 		free_BN(&p->key.rsa.n);
1169 		free_BN(&p->key.rsa.e);
1170 		break;
1171 
1172 	case PGP_PKA_DSA:
1173 		free_BN(&p->key.dsa.p);
1174 		free_BN(&p->key.dsa.q);
1175 		free_BN(&p->key.dsa.g);
1176 		free_BN(&p->key.dsa.y);
1177 		break;
1178 
1179 	case PGP_PKA_ELGAMAL:
1180 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1181 		free_BN(&p->key.elgamal.p);
1182 		free_BN(&p->key.elgamal.g);
1183 		free_BN(&p->key.elgamal.y);
1184 		break;
1185 
1186 	case PGP_PKA_NOTHING:
1187 		/* nothing to free */
1188 		break;
1189 
1190 	default:
1191 		(void) fprintf(stderr, "pgp_pubkey_free: bad alg\n");
1192 	}
1193 }
1194 
1195 /**
1196    \ingroup Core_ReadPackets
1197 */
1198 static int
1199 parse_pubkey_data(pgp_pubkey_t *key, pgp_region_t *region,
1200 		      pgp_stream_t *stream)
1201 {
1202 	uint8_t   c = 0x0;
1203 
1204 	if (region->readc != 0) {
1205 		/* We should not have read anything so far */
1206 		(void) fprintf(stderr, "parse_pubkey_data: bad length\n");
1207 		return 0;
1208 	}
1209 	if (!limread(&c, 1, region, stream)) {
1210 		return 0;
1211 	}
1212 	key->version = (pgp_version_t)c;
1213 	switch (key->version) {
1214 	case PGP_V2:
1215 	case PGP_V3:
1216 	case PGP_V4:
1217 		break;
1218 	default:
1219 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_PUBLIC_KEY_VRSN,
1220 			    "Bad public key version (0x%02x)", key->version);
1221 		return 0;
1222 	}
1223 	if (!limited_read_time(&key->birthtime, region, stream)) {
1224 		return 0;
1225 	}
1226 
1227 	key->days_valid = 0;
1228 	if ((key->version == 2 || key->version == 3) &&
1229 	    !limread_scalar(&key->days_valid, 2, region, stream)) {
1230 		return 0;
1231 	}
1232 
1233 	if (!limread(&c, 1, region, stream)) {
1234 		return 0;
1235 	}
1236 	key->alg = c;
1237 
1238 	switch (key->alg) {
1239 	case PGP_PKA_DSA:
1240 		if (!limread_mpi(&key->key.dsa.p, region, stream) ||
1241 		    !limread_mpi(&key->key.dsa.q, region, stream) ||
1242 		    !limread_mpi(&key->key.dsa.g, region, stream) ||
1243 		    !limread_mpi(&key->key.dsa.y, region, stream)) {
1244 			return 0;
1245 		}
1246 		break;
1247 
1248 	case PGP_PKA_RSA:
1249 	case PGP_PKA_RSA_ENCRYPT_ONLY:
1250 	case PGP_PKA_RSA_SIGN_ONLY:
1251 		if (!limread_mpi(&key->key.rsa.n, region, stream) ||
1252 		    !limread_mpi(&key->key.rsa.e, region, stream)) {
1253 			return 0;
1254 		}
1255 		break;
1256 
1257 	case PGP_PKA_ELGAMAL:
1258 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1259 		if (!limread_mpi(&key->key.elgamal.p, region, stream) ||
1260 		    !limread_mpi(&key->key.elgamal.g, region, stream) ||
1261 		    !limread_mpi(&key->key.elgamal.y, region, stream)) {
1262 			return 0;
1263 		}
1264 		break;
1265 
1266 	default:
1267 		PGP_ERROR_1(&stream->errors,
1268 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
1269 			"Unsupported Public Key algorithm (%s)",
1270 			pgp_show_pka(key->alg));
1271 		return 0;
1272 	}
1273 
1274 	return 1;
1275 }
1276 
1277 
1278 /**
1279  * \ingroup Core_ReadPackets
1280  * \brief Parse a public key packet.
1281  *
1282  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
1283  *
1284  * Once the key has been parsed successfully, it is passed to the callback.
1285  *
1286  * \param *ptag		Pointer to the current Packet Tag.  This function should consume the entire packet.
1287  * \param *reader	Our reader
1288  * \param *cb		The callback
1289  * \return		1 on success, 0 on error
1290  *
1291  * \see RFC4880 5.5.2
1292  */
1293 static int
1294 parse_pubkey(pgp_content_enum tag, pgp_region_t *region,
1295 		 pgp_stream_t *stream)
1296 {
1297 	pgp_packet_t pkt;
1298 
1299 	if (!parse_pubkey_data(&pkt.u.pubkey, region, stream)) {
1300 		(void) fprintf(stderr, "parse_pubkey: parse_pubkey_data failed\n");
1301 		return 0;
1302 	}
1303 
1304 	/* XXX: this test should be done for all packets, surely? */
1305 	if (region->readc != region->length) {
1306 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1307 			    "Unconsumed data (%d)", region->length - region->readc);
1308 		return 0;
1309 	}
1310 	CALLBACK(tag, &stream->cbinfo, &pkt);
1311 
1312 	return 1;
1313 }
1314 
1315 /**
1316  * \ingroup Core_ReadPackets
1317  * \brief Parse one user attribute packet.
1318  *
1319  * User attribute packets contain one or more attribute subpackets.
1320  * For now, handle the whole packet as raw data.
1321  */
1322 
1323 static int
1324 parse_userattr(pgp_region_t *region, pgp_stream_t *stream)
1325 {
1326 
1327 	pgp_packet_t pkt;
1328 
1329 	/*
1330 	 * xxx- treat as raw data for now. Could break down further into
1331 	 * attribute sub-packets later - rachel
1332 	 */
1333 	if (region->readc != 0) {
1334 		/* We should not have read anything so far */
1335 		(void) fprintf(stderr, "parse_userattr: bad length\n");
1336 		return 0;
1337 	}
1338 	if (!read_data(&pkt.u.userattr, region, stream)) {
1339 		return 0;
1340 	}
1341 	CALLBACK(PGP_PTAG_CT_USER_ATTR, &stream->cbinfo, &pkt);
1342 	return 1;
1343 }
1344 
1345 /**
1346 \ingroup Core_Create
1347 \brief Free allocated memory
1348 */
1349 /* ! Free the memory used when parsing this packet type */
1350 void
1351 pgp_userid_free(uint8_t **id)
1352 {
1353 	free(*id);
1354 	*id = NULL;
1355 }
1356 
1357 /**
1358  * \ingroup Core_ReadPackets
1359  * \brief Parse a user id.
1360  *
1361  * This function parses an user id packet, which is basically just a char array the size of the packet.
1362  *
1363  * The char array is to be treated as an UTF-8 string.
1364  *
1365  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
1366  *
1367  * Once the userid has been parsed successfully, it is passed to the callback.
1368  *
1369  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1370  * \param *reader	Our reader
1371  * \param *cb		The callback
1372  * \return		1 on success, 0 on error
1373  *
1374  * \see RFC4880 5.11
1375  */
1376 static int
1377 parse_userid(pgp_region_t *region, pgp_stream_t *stream)
1378 {
1379 	pgp_packet_t pkt;
1380 
1381 	 if (region->readc != 0) {
1382 		/* We should not have read anything so far */
1383 		(void) fprintf(stderr, "parse_userid: bad length\n");
1384 		return 0;
1385 	}
1386 
1387 	if ((pkt.u.userid = calloc(1, region->length + 1)) == NULL) {
1388 		(void) fprintf(stderr, "parse_userid: bad alloc\n");
1389 		return 0;
1390 	}
1391 
1392 	if (region->length &&
1393 	    !limread(pkt.u.userid, region->length, region,
1394 			stream)) {
1395 		return 0;
1396 	}
1397 	pkt.u.userid[region->length] = 0x0;
1398 	CALLBACK(PGP_PTAG_CT_USER_ID, &stream->cbinfo, &pkt);
1399 	return 1;
1400 }
1401 
1402 static pgp_hash_t     *
1403 parse_hash_find(pgp_stream_t *stream, const uint8_t *keyid)
1404 {
1405 	pgp_hashtype_t	*hp;
1406 	size_t			 n;
1407 
1408 	for (n = 0, hp = stream->hashes; n < stream->hashc; n++, hp++) {
1409 		if (memcmp(hp->keyid, keyid, PGP_KEY_ID_SIZE) == 0) {
1410 			return &hp->hash;
1411 		}
1412 	}
1413 	return NULL;
1414 }
1415 
1416 /**
1417  * \ingroup Core_Parse
1418  * \brief Parse a version 3 signature.
1419  *
1420  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
1421  *
1422  * Once the signature has been parsed successfully, it is passed to the callback.
1423  *
1424  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1425  * \param *reader	Our reader
1426  * \param *cb		The callback
1427  * \return		1 on success, 0 on error
1428  *
1429  * \see RFC4880 5.2.2
1430  */
1431 static int
1432 parse_v3_sig(pgp_region_t *region,
1433 		   pgp_stream_t *stream)
1434 {
1435 	pgp_packet_t	pkt;
1436 	uint8_t		c = 0x0;
1437 
1438 	/* clear signature */
1439 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1440 
1441 	pkt.u.sig.info.version = PGP_V3;
1442 
1443 	/* hash info length */
1444 	if (!limread(&c, 1, region, stream)) {
1445 		return 0;
1446 	}
1447 	if (c != 5) {
1448 		ERRP(&stream->cbinfo, pkt, "bad hash info length");
1449 	}
1450 
1451 	if (!limread(&c, 1, region, stream)) {
1452 		return 0;
1453 	}
1454 	pkt.u.sig.info.type = (pgp_sig_type_t)c;
1455 	/* XXX: check signature type */
1456 
1457 	if (!limited_read_time(&pkt.u.sig.info.birthtime, region, stream)) {
1458 		return 0;
1459 	}
1460 	pkt.u.sig.info.birthtime_set = 1;
1461 
1462 	if (!limread(pkt.u.sig.info.signer_id, PGP_KEY_ID_SIZE, region,
1463 			stream)) {
1464 		return 0;
1465 	}
1466 	pkt.u.sig.info.signer_id_set = 1;
1467 
1468 	if (!limread(&c, 1, region, stream)) {
1469 		return 0;
1470 	}
1471 	pkt.u.sig.info.key_alg = (pgp_pubkey_alg_t)c;
1472 	/* XXX: check algorithm */
1473 
1474 	if (!limread(&c, 1, region, stream)) {
1475 		return 0;
1476 	}
1477 	pkt.u.sig.info.hash_alg = (pgp_hash_alg_t)c;
1478 	/* XXX: check algorithm */
1479 
1480 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
1481 		return 0;
1482 	}
1483 
1484 	switch (pkt.u.sig.info.key_alg) {
1485 	case PGP_PKA_RSA:
1486 	case PGP_PKA_RSA_SIGN_ONLY:
1487 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
1488 			return 0;
1489 		}
1490 		break;
1491 
1492 	case PGP_PKA_DSA:
1493 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream) ||
1494 		    !limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
1495 			return 0;
1496 		}
1497 		break;
1498 
1499 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1500 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
1501 				stream) ||
1502 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
1503 		    		stream)) {
1504 			return 0;
1505 		}
1506 		break;
1507 
1508 	default:
1509 		PGP_ERROR_1(&stream->errors,
1510 			PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
1511 			"Unsupported signature key algorithm (%s)",
1512 			pgp_show_pka(pkt.u.sig.info.key_alg));
1513 		return 0;
1514 	}
1515 
1516 	if (region->readc != region->length) {
1517 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1518 			"Unconsumed data (%d)",
1519 			region->length - region->readc);
1520 		return 0;
1521 	}
1522 	if (pkt.u.sig.info.signer_id_set) {
1523 		pkt.u.sig.hash = parse_hash_find(stream,
1524 				pkt.u.sig.info.signer_id);
1525 	}
1526 	CALLBACK(PGP_PTAG_CT_SIGNATURE, &stream->cbinfo, &pkt);
1527 	return 1;
1528 }
1529 
1530 /**
1531  * \ingroup Core_ReadPackets
1532  * \brief Parse one signature sub-packet.
1533  *
1534  * Version 4 signatures can have an arbitrary amount of (hashed and
1535  * unhashed) subpackets.  Subpackets are used to hold optional
1536  * attributes of subpackets.
1537  *
1538  * This function parses one such signature subpacket.
1539  *
1540  * Once the subpacket has been parsed successfully, it is passed to the callback.
1541  *
1542  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire subpacket.
1543  * \param *reader	Our reader
1544  * \param *cb		The callback
1545  * \return		1 on success, 0 on error
1546  *
1547  * \see RFC4880 5.2.3
1548  */
1549 static int
1550 parse_one_sig_subpacket(pgp_sig_t *sig,
1551 			      pgp_region_t *region,
1552 			      pgp_stream_t *stream)
1553 {
1554 	pgp_region_t	subregion;
1555 	pgp_packet_t	pkt;
1556 	uint8_t		bools = 0x0;
1557 	uint8_t		c = 0x0;
1558 	uint8_t		temp = 0x0;
1559 	unsigned	doread = 1;
1560 	unsigned        t8;
1561 	unsigned        t7;
1562 
1563 	pgp_init_subregion(&subregion, region);
1564 	if (!limited_read_new_length(&subregion.length, region, stream)) {
1565 		return 0;
1566 	}
1567 
1568 	if (subregion.length > region->length) {
1569 		ERRP(&stream->cbinfo, pkt, "Subpacket too long");
1570 	}
1571 
1572 	if (!limread(&c, 1, &subregion, stream)) {
1573 		return 0;
1574 	}
1575 
1576 	t8 = (c & 0x7f) / 8;
1577 	t7 = 1 << (c & 7);
1578 
1579 	pkt.critical = (unsigned)c >> 7;
1580 	pkt.tag = (pgp_content_enum)(PGP_PTAG_SIG_SUBPKT_BASE + (c & 0x7f));
1581 
1582 	/* Application wants it delivered raw */
1583 	if (stream->ss_raw[t8] & t7) {
1584 		pkt.u.ss_raw.tag = pkt.tag;
1585 		pkt.u.ss_raw.length = subregion.length - 1;
1586 		pkt.u.ss_raw.raw = calloc(1, pkt.u.ss_raw.length);
1587 		if (pkt.u.ss_raw.raw == NULL) {
1588 			(void) fprintf(stderr, "parse_one_sig_subpacket: bad alloc\n");
1589 			return 0;
1590 		}
1591 		if (!limread(pkt.u.ss_raw.raw, (unsigned)pkt.u.ss_raw.length,
1592 				&subregion, stream)) {
1593 			return 0;
1594 		}
1595 		CALLBACK(PGP_PTAG_RAW_SS, &stream->cbinfo, &pkt);
1596 		return 1;
1597 	}
1598 	switch (pkt.tag) {
1599 	case PGP_PTAG_SS_CREATION_TIME:
1600 	case PGP_PTAG_SS_EXPIRATION_TIME:
1601 	case PGP_PTAG_SS_KEY_EXPIRY:
1602 		if (!limited_read_time(&pkt.u.ss_time, &subregion, stream))
1603 			return 0;
1604 		if (pkt.tag == PGP_PTAG_SS_CREATION_TIME) {
1605 			sig->info.birthtime = pkt.u.ss_time;
1606 			sig->info.birthtime_set = 1;
1607 		}
1608 		if (pkt.tag == PGP_PTAG_SS_EXPIRATION_TIME) {
1609 			sig->info.duration = pkt.u.ss_time;
1610 			sig->info.duration_set = 1;
1611 		}
1612 		break;
1613 
1614 	case PGP_PTAG_SS_TRUST:
1615 		if (!limread(&pkt.u.ss_trust.level, 1, &subregion, stream) ||
1616 		    !limread(&pkt.u.ss_trust.amount, 1, &subregion, stream)) {
1617 			return 0;
1618 		}
1619 		break;
1620 
1621 	case PGP_PTAG_SS_REVOCABLE:
1622 		if (!limread(&bools, 1, &subregion, stream)) {
1623 			return 0;
1624 		}
1625 		pkt.u.ss_revocable = !!bools;
1626 		break;
1627 
1628 	case PGP_PTAG_SS_ISSUER_KEY_ID:
1629 		if (!limread(pkt.u.ss_issuer, PGP_KEY_ID_SIZE, &subregion, stream)) {
1630 			return 0;
1631 		}
1632 		(void) memcpy(sig->info.signer_id, pkt.u.ss_issuer, PGP_KEY_ID_SIZE);
1633 		sig->info.signer_id_set = 1;
1634 		break;
1635 
1636 	case PGP_PTAG_SS_PREFERRED_SKA:
1637 		if (!read_data(&pkt.u.ss_skapref, &subregion, stream)) {
1638 			return 0;
1639 		}
1640 		break;
1641 
1642 	case PGP_PTAG_SS_PREFERRED_HASH:
1643 		if (!read_data(&pkt.u.ss_hashpref, &subregion, stream)) {
1644 			return 0;
1645 		}
1646 		break;
1647 
1648 	case PGP_PTAG_SS_PREF_COMPRESS:
1649 		if (!read_data(&pkt.u.ss_zpref, &subregion, stream)) {
1650 			return 0;
1651 		}
1652 		break;
1653 
1654 	case PGP_PTAG_SS_PRIMARY_USER_ID:
1655 		if (!limread(&bools, 1, &subregion, stream)) {
1656 			return 0;
1657 		}
1658 		pkt.u.ss_primary_userid = !!bools;
1659 		break;
1660 
1661 	case PGP_PTAG_SS_KEY_FLAGS:
1662 		if (!read_data(&pkt.u.ss_key_flags, &subregion, stream)) {
1663 			return 0;
1664 		}
1665 		break;
1666 
1667 	case PGP_PTAG_SS_KEYSERV_PREFS:
1668 		if (!read_data(&pkt.u.ss_key_server_prefs, &subregion, stream)) {
1669 			return 0;
1670 		}
1671 		break;
1672 
1673 	case PGP_PTAG_SS_FEATURES:
1674 		if (!read_data(&pkt.u.ss_features, &subregion, stream)) {
1675 			return 0;
1676 		}
1677 		break;
1678 
1679 	case PGP_PTAG_SS_SIGNERS_USER_ID:
1680 		if (!read_unsig_str(&pkt.u.ss_signer, &subregion, stream)) {
1681 			return 0;
1682 		}
1683 		break;
1684 
1685 	case PGP_PTAG_SS_EMBEDDED_SIGNATURE:
1686 		/* \todo should do something with this sig? */
1687 		if (!read_data(&pkt.u.ss_embedded_sig, &subregion, stream)) {
1688 			return 0;
1689 		}
1690 		break;
1691 
1692 	case PGP_PTAG_SS_NOTATION_DATA:
1693 		if (!limread_data(&pkt.u.ss_notation.flags, 4,
1694 				&subregion, stream)) {
1695 			return 0;
1696 		}
1697 		if (!limread_size_t(&pkt.u.ss_notation.name.len, 2,
1698 				&subregion, stream)) {
1699 			return 0;
1700 		}
1701 		if (!limread_size_t(&pkt.u.ss_notation.value.len, 2,
1702 				&subregion, stream)) {
1703 			return 0;
1704 		}
1705 		if (!limread_data(&pkt.u.ss_notation.name,
1706 				(unsigned)pkt.u.ss_notation.name.len,
1707 				&subregion, stream)) {
1708 			return 0;
1709 		}
1710 		if (!limread_data(&pkt.u.ss_notation.value,
1711 			   (unsigned)pkt.u.ss_notation.value.len,
1712 			   &subregion, stream)) {
1713 			return 0;
1714 		}
1715 		break;
1716 
1717 	case PGP_PTAG_SS_POLICY_URI:
1718 		if (!read_string(&pkt.u.ss_policy, &subregion, stream)) {
1719 			return 0;
1720 		}
1721 		break;
1722 
1723 	case PGP_PTAG_SS_REGEXP:
1724 		if (!read_string(&pkt.u.ss_regexp, &subregion, stream)) {
1725 			return 0;
1726 		}
1727 		break;
1728 
1729 	case PGP_PTAG_SS_PREF_KEYSERV:
1730 		if (!read_string(&pkt.u.ss_keyserv, &subregion, stream)) {
1731 			return 0;
1732 		}
1733 		break;
1734 
1735 	case PGP_PTAG_SS_USERDEFINED00:
1736 	case PGP_PTAG_SS_USERDEFINED01:
1737 	case PGP_PTAG_SS_USERDEFINED02:
1738 	case PGP_PTAG_SS_USERDEFINED03:
1739 	case PGP_PTAG_SS_USERDEFINED04:
1740 	case PGP_PTAG_SS_USERDEFINED05:
1741 	case PGP_PTAG_SS_USERDEFINED06:
1742 	case PGP_PTAG_SS_USERDEFINED07:
1743 	case PGP_PTAG_SS_USERDEFINED08:
1744 	case PGP_PTAG_SS_USERDEFINED09:
1745 	case PGP_PTAG_SS_USERDEFINED10:
1746 		if (!read_data(&pkt.u.ss_userdef, &subregion, stream)) {
1747 			return 0;
1748 		}
1749 		break;
1750 
1751 	case PGP_PTAG_SS_RESERVED:
1752 		if (!read_data(&pkt.u.ss_unknown, &subregion, stream)) {
1753 			return 0;
1754 		}
1755 		break;
1756 
1757 	case PGP_PTAG_SS_REVOCATION_REASON:
1758 		/* first byte is the machine-readable code */
1759 		if (!limread(&pkt.u.ss_revocation.code, 1, &subregion, stream)) {
1760 			return 0;
1761 		}
1762 		/* the rest is a human-readable UTF-8 string */
1763 		if (!read_string(&pkt.u.ss_revocation.reason, &subregion,
1764 				stream)) {
1765 			return 0;
1766 		}
1767 		break;
1768 
1769 	case PGP_PTAG_SS_ISSUER_FINGERPRINT:
1770 		/* octet 0: version */
1771 		/* 	0x04:20 bytes, 0x05:32 bytes */
1772 		if (!limread(&temp, 1, &subregion, stream)) {
1773 			return 0;
1774 		}
1775 
1776 		switch (temp) {
1777 			case 0x04: pkt.u.ss_issuer_fingerprint.len = 20; break;
1778 			case 0x05: pkt.u.ss_issuer_fingerprint.len = 32; break;
1779 			default:
1780 				return 0;
1781 		}
1782 
1783 		if (!limread(pkt.u.ss_issuer_fingerprint.fingerprint,
1784 			pkt.u.ss_issuer_fingerprint.len, &subregion, stream)) {
1785 			return 0;
1786 		}
1787 		break;
1788 
1789 	case PGP_PTAG_SS_REVOCATION_KEY:
1790 		/* octet 0 = class. Bit 0x80 must be set */
1791 		if (!limread(&pkt.u.ss_revocation_key.class, 1,
1792 				&subregion, stream)) {
1793 			return 0;
1794 		}
1795 		if (!(pkt.u.ss_revocation_key.class & 0x80)) {
1796 			printf("Warning: PGP_PTAG_SS_REVOCATION_KEY class: "
1797 			       "Bit 0x80 should be set\n");
1798 			return 0;
1799 		}
1800 		/* octet 1 = algid */
1801 		if (!limread(&pkt.u.ss_revocation_key.algid, 1,
1802 				&subregion, stream)) {
1803 			return 0;
1804 		}
1805 		/* octets 2-21 = fingerprint */
1806 		if (!limread(&pkt.u.ss_revocation_key.fingerprint[0],
1807 				PGP_FINGERPRINT_SIZE, &subregion, stream)) {
1808 			return 0;
1809 		}
1810 		break;
1811 
1812 	default:
1813 		if (stream->ss_parsed[t8] & t7) {
1814 			PGP_ERROR_1(&stream->errors, PGP_E_PROTO_UNKNOWN_SS,
1815 				    "Unknown signature subpacket type (%d)",
1816 				    c & 0x7f);
1817 		}
1818 		doread = 0;
1819 		break;
1820 	}
1821 
1822 	/* Application doesn't want it delivered parsed */
1823 	if (!(stream->ss_parsed[t8] & t7)) {
1824 		if (pkt.critical) {
1825 			PGP_ERROR_1(&stream->errors,
1826 				PGP_E_PROTO_CRITICAL_SS_IGNORED,
1827 				"Critical signature subpacket ignored (%d)",
1828 				c & 0x7f);
1829 		}
1830 		if (!doread &&
1831 		    !limskip(subregion.length - 1, &subregion, stream)) {
1832 			return 0;
1833 		}
1834 		if (doread) {
1835 			pgp_parser_content_free(&pkt);
1836 		}
1837 		return 1;
1838 	}
1839 	if (doread && subregion.readc != subregion.length) {
1840 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1841 			    "Unconsumed data (%d)",
1842 			    subregion.length - subregion.readc);
1843 		return 0;
1844 	}
1845 	CALLBACK(pkt.tag, &stream->cbinfo, &pkt);
1846 	return 1;
1847 }
1848 
1849 /**
1850  * \ingroup Core_ReadPackets
1851  * \brief Parse several signature subpackets.
1852  *
1853  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1854  * This function parses this length and then calls parse_one_sig_subpacket() for each subpacket until the
1855  * entire set is consumed.
1856  *
1857  * This function does not call the callback directly, parse_one_sig_subpacket() does for each subpacket.
1858  *
1859  * \param *ptag		Pointer to the Packet Tag.
1860  * \param *reader	Our reader
1861  * \param *cb		The callback
1862  * \return		1 on success, 0 on error
1863  *
1864  * \see RFC4880 5.2.3
1865  */
1866 static int
1867 parse_sig_subpkts(pgp_sig_t *sig,
1868 			   pgp_region_t *region,
1869 			   pgp_stream_t *stream)
1870 {
1871 	pgp_region_t	subregion;
1872 	pgp_packet_t	pkt;
1873 
1874 	pgp_init_subregion(&subregion, region);
1875 	if (!limread_scalar(&subregion.length, 2, region, stream)) {
1876 		return 0;
1877 	}
1878 
1879 	if (subregion.length > region->length) {
1880 		ERRP(&stream->cbinfo, pkt, "Subpacket set too long");
1881 	}
1882 
1883 	while (subregion.readc < subregion.length) {
1884 		if (!parse_one_sig_subpacket(sig, &subregion, stream)) {
1885 			return 0;
1886 		}
1887 	}
1888 
1889 	if (subregion.readc != subregion.length) {
1890 		if (!limskip(subregion.length - subregion.readc,
1891 				&subregion, stream)) {
1892 			ERRP(&stream->cbinfo, pkt,
1893 "parse_sig_subpkts: subpacket length read mismatch");
1894 		}
1895 		ERRP(&stream->cbinfo, pkt, "Subpacket length mismatch");
1896 	}
1897 	return 1;
1898 }
1899 
1900 /**
1901  * \ingroup Core_ReadPackets
1902  * \brief Parse a version 4 signature.
1903  *
1904  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
1905  *
1906  * Once the signature packet has been parsed successfully, it is passed to the callback.
1907  *
1908  * \param *ptag		Pointer to the Packet Tag.
1909  * \param *reader	Our reader
1910  * \param *cb		The callback
1911  * \return		1 on success, 0 on error
1912  *
1913  * \see RFC4880 5.2.3
1914  */
1915 static int
1916 parse_v4_sig(pgp_region_t *region, pgp_stream_t *stream)
1917 {
1918 	pgp_packet_t	pkt;
1919 	uint8_t		c = 0x0;
1920 
1921 	if (pgp_get_debug_level(__FILE__)) {
1922 		fprintf(stderr, "\nparse_v4_sig\n");
1923 	}
1924 	/* clear signature */
1925 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1926 
1927 	/*
1928 	 * We need to hash the packet data from version through the hashed
1929 	 * subpacket data
1930 	 */
1931 
1932 	pkt.u.sig.v4_hashstart = stream->readinfo.alength - 1;
1933 
1934 	/* Set version,type,algorithms */
1935 
1936 	pkt.u.sig.info.version = PGP_V4;
1937 
1938 	if (!limread(&c, 1, region, stream)) {
1939 		return 0;
1940 	}
1941 	pkt.u.sig.info.type = (pgp_sig_type_t)c;
1942 	if (pgp_get_debug_level(__FILE__)) {
1943 		fprintf(stderr, "signature type=%d (%s)\n",
1944 			pkt.u.sig.info.type,
1945 			pgp_show_sig_type(pkt.u.sig.info.type));
1946 	}
1947 	/* XXX: check signature type */
1948 
1949 	if (!limread(&c, 1, region, stream)) {
1950 		return 0;
1951 	}
1952 	pkt.u.sig.info.key_alg = (pgp_pubkey_alg_t)c;
1953 	/* XXX: check key algorithm */
1954 	if (pgp_get_debug_level(__FILE__)) {
1955 		(void) fprintf(stderr, "key_alg=%d (%s)\n",
1956 			pkt.u.sig.info.key_alg,
1957 			pgp_show_pka(pkt.u.sig.info.key_alg));
1958 	}
1959 	if (!limread(&c, 1, region, stream)) {
1960 		return 0;
1961 	}
1962 	pkt.u.sig.info.hash_alg = (pgp_hash_alg_t)c;
1963 	/* XXX: check hash algorithm */
1964 	if (pgp_get_debug_level(__FILE__)) {
1965 		fprintf(stderr, "hash_alg=%d %s\n",
1966 			pkt.u.sig.info.hash_alg,
1967 		  pgp_show_hash_alg(pkt.u.sig.info.hash_alg));
1968 	}
1969 	CALLBACK(PGP_PTAG_CT_SIGNATURE_HEADER, &stream->cbinfo, &pkt);
1970 
1971 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
1972 		return 0;
1973 	}
1974 
1975 	pkt.u.sig.info.v4_hashlen = stream->readinfo.alength
1976 					- pkt.u.sig.v4_hashstart;
1977 	if (pgp_get_debug_level(__FILE__)) {
1978 		fprintf(stderr, "v4_hashlen=%zd\n", pkt.u.sig.info.v4_hashlen);
1979 	}
1980 
1981 	/* copy hashed subpackets */
1982 	if (pkt.u.sig.info.v4_hashed) {
1983 		free(pkt.u.sig.info.v4_hashed);
1984 	}
1985 	pkt.u.sig.info.v4_hashed = calloc(1, pkt.u.sig.info.v4_hashlen);
1986 	if (pkt.u.sig.info.v4_hashed == NULL) {
1987 		(void) fprintf(stderr, "parse_v4_sig: bad alloc\n");
1988 		return 0;
1989 	}
1990 
1991 	if (!stream->readinfo.accumulate) {
1992 		/* We must accumulate, else we can't check the signature */
1993 		fprintf(stderr, "*** ERROR: must set accumulate to 1\n");
1994 		return 0;
1995 	}
1996 	(void) memcpy(pkt.u.sig.info.v4_hashed,
1997 	       stream->readinfo.accumulated + pkt.u.sig.v4_hashstart,
1998 	       pkt.u.sig.info.v4_hashlen);
1999 
2000 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
2001 		return 0;
2002 	}
2003 
2004 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
2005 		return 0;
2006 	}
2007 
2008 	switch (pkt.u.sig.info.key_alg) {
2009 	case PGP_PKA_RSA:
2010 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
2011 			return 0;
2012 		}
2013 		if (pgp_get_debug_level(__FILE__)) {
2014 			(void) fprintf(stderr, "parse_v4_sig: RSA: sig is\n");
2015 			BN_print_fp(stderr, pkt.u.sig.info.sig.rsa.sig);
2016 			(void) fprintf(stderr, "\n");
2017 		}
2018 		break;
2019 
2020 	case PGP_PKA_DSA:
2021 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream)) {
2022 			/*
2023 			 * usually if this fails, it just means we've reached
2024 			 * the end of the keyring
2025 			 */
2026 			if (pgp_get_debug_level(__FILE__)) {
2027 				(void) fprintf(stderr,
2028 				"Error reading DSA r field in signature");
2029 			}
2030 			return 0;
2031 		}
2032 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
2033 			ERRP(&stream->cbinfo, pkt,
2034 			"Error reading DSA s field in signature");
2035 		}
2036 		break;
2037 
2038 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
2039 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
2040 				stream) ||
2041 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
2042 		    		stream)) {
2043 			return 0;
2044 		}
2045 		break;
2046 
2047 	case PGP_PKA_PRIVATE00:
2048 	case PGP_PKA_PRIVATE01:
2049 	case PGP_PKA_PRIVATE02:
2050 	case PGP_PKA_PRIVATE03:
2051 	case PGP_PKA_PRIVATE04:
2052 	case PGP_PKA_PRIVATE05:
2053 	case PGP_PKA_PRIVATE06:
2054 	case PGP_PKA_PRIVATE07:
2055 	case PGP_PKA_PRIVATE08:
2056 	case PGP_PKA_PRIVATE09:
2057 	case PGP_PKA_PRIVATE10:
2058 		if (!read_data(&pkt.u.sig.info.sig.unknown, region, stream)) {
2059 			return 0;
2060 		}
2061 		break;
2062 
2063 	default:
2064 		PGP_ERROR_1(&stream->errors, PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
2065 			    "Bad v4 signature key algorithm (%s)",
2066 			    pgp_show_pka(pkt.u.sig.info.key_alg));
2067 		return 0;
2068 	}
2069 	if (region->readc != region->length) {
2070 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
2071 			    "Unconsumed data (%d)",
2072 			    region->length - region->readc);
2073 		return 0;
2074 	}
2075 	CALLBACK(PGP_PTAG_CT_SIGNATURE_FOOTER, &stream->cbinfo, &pkt);
2076 	return 1;
2077 }
2078 
2079 /**
2080  * \ingroup Core_ReadPackets
2081  * \brief Parse a signature subpacket.
2082  *
2083  * This function calls the appropriate function to handle v3 or v4 signatures.
2084  *
2085  * Once the signature packet has been parsed successfully, it is passed to the callback.
2086  *
2087  * \param *ptag		Pointer to the Packet Tag.
2088  * \param *reader	Our reader
2089  * \param *cb		The callback
2090  * \return		1 on success, 0 on error
2091  */
2092 static int
2093 parse_sig(pgp_region_t *region, pgp_stream_t *stream)
2094 {
2095 	pgp_packet_t	pkt;
2096 	uint8_t		c = 0x0;
2097 
2098 	if (region->readc != 0) {
2099 		/* We should not have read anything so far */
2100 		(void) fprintf(stderr, "parse_sig: bad length\n");
2101 		return 0;
2102 	}
2103 
2104 	(void) memset(&pkt, 0x0, sizeof(pkt));
2105 	if (!limread(&c, 1, region, stream)) {
2106 		return 0;
2107 	}
2108 	if (c == 2 || c == 3) {
2109 		return parse_v3_sig(region, stream);
2110 	}
2111 	if (c == 4) {
2112 		return parse_v4_sig(region, stream);
2113 	}
2114 	PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_SIGNATURE_VRSN,
2115 		    "Bad signature version (%d)", c);
2116 	return 0;
2117 }
2118 
2119 /**
2120  \ingroup Core_ReadPackets
2121  \brief Parse Compressed packet
2122 */
2123 static int
2124 parse_compressed(pgp_region_t *region, pgp_stream_t *stream)
2125 {
2126 	pgp_packet_t	pkt;
2127 	uint8_t		c = 0x0;
2128 
2129 	if (!limread(&c, 1, region, stream)) {
2130 		return 0;
2131 	}
2132 
2133 	pkt.u.compressed = (pgp_compression_type_t)c;
2134 
2135 	CALLBACK(PGP_PTAG_CT_COMPRESSED, &stream->cbinfo, &pkt);
2136 
2137 	/*
2138 	 * The content of a compressed data packet is more OpenPGP packets
2139 	 * once decompressed, so recursively handle them
2140 	 */
2141 
2142 	return pgp_decompress(region, stream, pkt.u.compressed);
2143 }
2144 
2145 /* XXX: this could be improved by sharing all hashes that are the */
2146 /* same, then duping them just before checking the signature. */
2147 static void
2148 parse_hash_init(pgp_stream_t *stream, pgp_hash_alg_t type,
2149 		    const uint8_t *keyid)
2150 {
2151 	pgp_hashtype_t *hash;
2152 
2153 	hash = realloc(stream->hashes,
2154 			      (stream->hashc + 1) * sizeof(*stream->hashes));
2155 	if (hash == NULL) {
2156 		(void) fprintf(stderr, "parse_hash_init: bad alloc 0\n");
2157 		/* just continue and die here */
2158 		/* XXX - agc - no way to return failure */
2159 	} else {
2160 		stream->hashes = hash;
2161 	}
2162 	hash = &stream->hashes[stream->hashc++];
2163 
2164 	pgp_hash_any(&hash->hash, type);
2165 	if (!hash->hash.init(&hash->hash)) {
2166 		(void) fprintf(stderr, "parse_hash_init: bad alloc\n");
2167 		/* just continue and die here */
2168 		/* XXX - agc - no way to return failure */
2169 	}
2170 	(void) memcpy(hash->keyid, keyid, sizeof(hash->keyid));
2171 }
2172 
2173 /**
2174    \ingroup Core_ReadPackets
2175    \brief Parse a One Pass Signature packet
2176 */
2177 static int
2178 parse_one_pass(pgp_region_t * region, pgp_stream_t * stream)
2179 {
2180 	pgp_packet_t	pkt;
2181 	uint8_t		c = 0x0;
2182 
2183 	if (!limread(&pkt.u.one_pass_sig.version, 1, region, stream)) {
2184 		return 0;
2185 	}
2186 	if (pkt.u.one_pass_sig.version != 3) {
2187 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_ONE_PASS_SIG_VRSN,
2188 			    "Bad one-pass signature version (%d)",
2189 			    pkt.u.one_pass_sig.version);
2190 		return 0;
2191 	}
2192 	if (!limread(&c, 1, region, stream)) {
2193 		return 0;
2194 	}
2195 	pkt.u.one_pass_sig.sig_type = (pgp_sig_type_t)c;
2196 
2197 	if (!limread(&c, 1, region, stream)) {
2198 		return 0;
2199 	}
2200 	pkt.u.one_pass_sig.hash_alg = (pgp_hash_alg_t)c;
2201 
2202 	if (!limread(&c, 1, region, stream)) {
2203 		return 0;
2204 	}
2205 	pkt.u.one_pass_sig.key_alg = (pgp_pubkey_alg_t)c;
2206 
2207 	if (!limread(pkt.u.one_pass_sig.keyid,
2208 			  (unsigned)sizeof(pkt.u.one_pass_sig.keyid),
2209 			  region, stream)) {
2210 		return 0;
2211 	}
2212 
2213 	if (!limread(&c, 1, region, stream)) {
2214 		return 0;
2215 	}
2216 	pkt.u.one_pass_sig.nested = !!c;
2217 	CALLBACK(PGP_PTAG_CT_1_PASS_SIG, &stream->cbinfo, &pkt);
2218 	/* XXX: we should, perhaps, let the app choose whether to hash or not */
2219 	parse_hash_init(stream, pkt.u.one_pass_sig.hash_alg,
2220 			    pkt.u.one_pass_sig.keyid);
2221 	return 1;
2222 }
2223 
2224 /**
2225  \ingroup Core_ReadPackets
2226  \brief Parse a Trust packet
2227 */
2228 static int
2229 parse_trust(pgp_region_t *region, pgp_stream_t *stream)
2230 {
2231 	pgp_packet_t pkt;
2232 
2233 	if (!read_data(&pkt.u.trust, region, stream)) {
2234 		return 0;
2235 	}
2236 	CALLBACK(PGP_PTAG_CT_TRUST, &stream->cbinfo, &pkt);
2237 	return 1;
2238 }
2239 
2240 static void
2241 parse_hash_data(pgp_stream_t *stream, const void *data,
2242 		    size_t length)
2243 {
2244 	size_t          n;
2245 
2246 	for (n = 0; n < stream->hashc; ++n) {
2247 		stream->hashes[n].hash.add(&stream->hashes[n].hash, data, (unsigned)length);
2248 	}
2249 }
2250 
2251 /**
2252    \ingroup Core_ReadPackets
2253    \brief Parse a Literal Data packet
2254 */
2255 static int
2256 parse_litdata(pgp_region_t *region, pgp_stream_t *stream)
2257 {
2258 	pgp_memory_t	*mem;
2259 	pgp_packet_t	 pkt;
2260 	uint8_t		 c = 0x0;
2261 
2262 	if (!limread(&c, 1, region, stream)) {
2263 		return 0;
2264 	}
2265 	pkt.u.litdata_header.format = (pgp_litdata_enum)c;
2266 	if (!limread(&c, 1, region, stream)) {
2267 		return 0;
2268 	}
2269 	if (!limread((uint8_t *)pkt.u.litdata_header.filename,
2270 			(unsigned)c, region, stream)) {
2271 		return 0;
2272 	}
2273 	pkt.u.litdata_header.filename[c] = '\0';
2274 	if (!limited_read_time(&pkt.u.litdata_header.mtime, region, stream)) {
2275 		return 0;
2276 	}
2277 	CALLBACK(PGP_PTAG_CT_LITDATA_HEADER, &stream->cbinfo, &pkt);
2278 	mem = pkt.u.litdata_body.mem = pgp_memory_new();
2279 	pgp_memory_init(pkt.u.litdata_body.mem,
2280 			(unsigned)((region->length * 101) / 100) + 12);
2281 	pkt.u.litdata_body.data = mem->buf;
2282 
2283 	while (region->readc < region->length) {
2284 		unsigned        readc = region->length - region->readc;
2285 
2286 		if (!limread(mem->buf, readc, region, stream)) {
2287 			return 0;
2288 		}
2289 		pkt.u.litdata_body.length = readc;
2290 		parse_hash_data(stream, pkt.u.litdata_body.data, region->length);
2291 		CALLBACK(PGP_PTAG_CT_LITDATA_BODY, &stream->cbinfo, &pkt);
2292 	}
2293 
2294 	/* XXX - get rid of mem here? */
2295 
2296 	return 1;
2297 }
2298 
2299 /**
2300  * \ingroup Core_Create
2301  *
2302  * pgp_seckey_free() frees the memory associated with "key". Note that
2303  * the key itself is not freed.
2304  *
2305  * \param key
2306  */
2307 
2308 void
2309 pgp_seckey_free(pgp_seckey_t *key)
2310 {
2311 	switch (key->pubkey.alg) {
2312 	case PGP_PKA_RSA:
2313 	case PGP_PKA_RSA_ENCRYPT_ONLY:
2314 	case PGP_PKA_RSA_SIGN_ONLY:
2315 		free_BN(&key->key.rsa.d);
2316 		free_BN(&key->key.rsa.p);
2317 		free_BN(&key->key.rsa.q);
2318 		free_BN(&key->key.rsa.u);
2319 		break;
2320 
2321 	case PGP_PKA_DSA:
2322 		free_BN(&key->key.dsa.x);
2323 		break;
2324 
2325 	default:
2326 		(void) fprintf(stderr,
2327 			"pgp_seckey_free: Unknown algorithm: %d (%s)\n",
2328 			key->pubkey.alg,
2329 			pgp_show_pka(key->pubkey.alg));
2330 	}
2331 	free(key->checkhash);
2332 }
2333 
2334 static int
2335 consume_packet(pgp_region_t *region, pgp_stream_t *stream, unsigned warn)
2336 {
2337 	pgp_packet_t	pkt;
2338 	pgp_data_t	remainder;
2339 
2340 	if (region->indeterminate) {
2341 		ERRP(&stream->cbinfo, pkt,
2342 			"Can't consume indeterminate packets");
2343 	}
2344 
2345 	if (read_data(&remainder, region, stream)) {
2346 		/* now throw it away */
2347 		pgp_data_free(&remainder);
2348 		if (warn) {
2349 			PGP_ERROR_1(&stream->errors, PGP_E_P_PACKET_CONSUMED,
2350 			    "%s", "Warning: packet consumer");
2351 		}
2352 		return 1;
2353 	}
2354 	PGP_ERROR_1(&stream->errors, PGP_E_P_PACKET_NOT_CONSUMED,
2355 	    "%s", (warn) ? "Warning: Packet was not consumed" :
2356 	    "Packet was not consumed");
2357 	return warn;
2358 }
2359 
2360 /**
2361  * \ingroup Core_ReadPackets
2362  * \brief Parse a secret key
2363  */
2364 static int
2365 parse_seckey(pgp_region_t *region, pgp_stream_t *stream)
2366 {
2367 	pgp_packet_t		pkt;
2368 	pgp_region_t		encregion;
2369 	pgp_region_t	       *saved_region = NULL;
2370 	pgp_crypt_t		decrypt;
2371 	pgp_hash_t		checkhash;
2372 	unsigned		blocksize;
2373 	unsigned		crypted;
2374 	uint8_t			c = 0x0;
2375 	int			ret = 1;
2376 
2377 	if (pgp_get_debug_level(__FILE__)) {
2378 		fprintf(stderr, "\n---------\nparse_seckey:\n");
2379 		fprintf(stderr,
2380 			"region length=%u, readc=%u, remainder=%u\n",
2381 			region->length, region->readc,
2382 			region->length - region->readc);
2383 	}
2384 	(void) memset(&pkt, 0x0, sizeof(pkt));
2385 	if (!parse_pubkey_data(&pkt.u.seckey.pubkey, region, stream)) {
2386 		return 0;
2387 	}
2388 	if (pgp_get_debug_level(__FILE__)) {
2389 		fprintf(stderr, "parse_seckey: public key parsed\n");
2390 		pgp_print_pubkey(&pkt.u.seckey.pubkey);
2391 	}
2392 	stream->reading_v3_secret = (pkt.u.seckey.pubkey.version != PGP_V4);
2393 
2394 	if (!limread(&c, 1, region, stream)) {
2395 		return 0;
2396 	}
2397 	pkt.u.seckey.s2k_usage = (pgp_s2k_usage_t)c;
2398 
2399 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED ||
2400 	    pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2401 		if (!limread(&c, 1, region, stream)) {
2402 			return 0;
2403 		}
2404 		pkt.u.seckey.alg = (pgp_symm_alg_t)c;
2405 		if (!limread(&c, 1, region, stream)) {
2406 			return 0;
2407 		}
2408 		pkt.u.seckey.s2k_specifier = (pgp_s2k_specifier_t)c;
2409 		switch (pkt.u.seckey.s2k_specifier) {
2410 		case PGP_S2KS_SIMPLE:
2411 		case PGP_S2KS_SALTED:
2412 		case PGP_S2KS_ITERATED_AND_SALTED:
2413 			break;
2414 		default:
2415 			(void) fprintf(stderr,
2416 				"parse_seckey: bad seckey\n");
2417 			return 0;
2418 		}
2419 		if (!limread(&c, 1, region, stream)) {
2420 			return 0;
2421 		}
2422 		pkt.u.seckey.hash_alg = (pgp_hash_alg_t)c;
2423 		if (pkt.u.seckey.s2k_specifier != PGP_S2KS_SIMPLE &&
2424 		    !limread(pkt.u.seckey.salt, 8, region, stream)) {
2425 			return 0;
2426 		}
2427 		if (pkt.u.seckey.s2k_specifier ==
2428 					PGP_S2KS_ITERATED_AND_SALTED) {
2429 			if (!limread(&c, 1, region, stream)) {
2430 				return 0;
2431 			}
2432 			pkt.u.seckey.octetc =
2433 				(16 + ((unsigned)c & 15)) <<
2434 						(((unsigned)c >> 4) + 6);
2435 		}
2436 	} else if (pkt.u.seckey.s2k_usage != PGP_S2KU_NONE) {
2437 		/* this is V3 style, looks just like a V4 simple hash */
2438 		pkt.u.seckey.alg = (pgp_symm_alg_t)c;
2439 		pkt.u.seckey.s2k_usage = PGP_S2KU_ENCRYPTED;
2440 		pkt.u.seckey.s2k_specifier = PGP_S2KS_SIMPLE;
2441 		pkt.u.seckey.hash_alg = PGP_HASH_MD5;
2442 	}
2443 	crypted = pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED ||
2444 		pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED;
2445 
2446 	if (crypted) {
2447 		pgp_packet_t	seckey;
2448 		pgp_hash_t	hashes[(PGP_MAX_KEY_SIZE + PGP_MIN_HASH_SIZE - 1) / PGP_MIN_HASH_SIZE];
2449 		unsigned	passlen;
2450 		uint8_t   	key[PGP_MAX_KEY_SIZE + PGP_MAX_HASH_SIZE];
2451 		char           *passphrase;
2452 		int             hashsize;
2453 		int             keysize;
2454 		int             n;
2455 
2456 		if (pgp_get_debug_level(__FILE__)) {
2457 			(void) fprintf(stderr, "crypted seckey\n");
2458 		}
2459 		blocksize = pgp_block_size(pkt.u.seckey.alg);
2460 		if (blocksize == 0 || blocksize > PGP_MAX_BLOCK_SIZE) {
2461 			(void) fprintf(stderr,
2462 				"parse_seckey: bad blocksize\n");
2463 			return 0;
2464 		}
2465 
2466 		if (!limread(pkt.u.seckey.iv, blocksize, region, stream)) {
2467 			return 0;
2468 		}
2469 		(void) memset(&seckey, 0x0, sizeof(seckey));
2470 		passphrase = NULL;
2471 		seckey.u.skey_passphrase.passphrase = &passphrase;
2472 		seckey.u.skey_passphrase.seckey = &pkt.u.seckey;
2473 		CALLBACK(PGP_GET_PASSPHRASE, &stream->cbinfo, &seckey);
2474 		if (!passphrase) {
2475 			if (pgp_get_debug_level(__FILE__)) {
2476 				/* \todo make into proper error */
2477 				(void) fprintf(stderr,
2478 				"parse_seckey: can't get passphrase\n");
2479 			}
2480 			if (!consume_packet(region, stream, 0)) {
2481 				return 0;
2482 			}
2483 
2484 			CALLBACK(PGP_PTAG_CT_ENCRYPTED_SECRET_KEY,
2485 				&stream->cbinfo, &pkt);
2486 
2487 			return 1;
2488 		}
2489 		keysize = pgp_key_size(pkt.u.seckey.alg);
2490 		if (keysize == 0 || keysize > PGP_MAX_KEY_SIZE) {
2491 			(void) fprintf(stderr,
2492 				"parse_seckey: bad keysize\n");
2493 			return 0;
2494 		}
2495 
2496 		/* Hardcoded SHA1 for just now */
2497 		pkt.u.seckey.hash_alg = PGP_HASH_SHA1;
2498 		hashsize = pgp_hash_size(pkt.u.seckey.hash_alg);
2499 		if (hashsize == 0 || hashsize > PGP_MAX_HASH_SIZE) {
2500 			(void) fprintf(stderr,
2501 				"parse_seckey: bad hashsize\n");
2502 			return 0;
2503 		}
2504 
2505 		for (n = 0; n * hashsize < keysize; ++n) {
2506 			int             i;
2507 
2508 			pgp_hash_any(&hashes[n],
2509 				pkt.u.seckey.hash_alg);
2510 			if (!hashes[n].init(&hashes[n])) {
2511 				(void) fprintf(stderr,
2512 					"parse_seckey: bad alloc\n");
2513 				return 0;
2514 			}
2515 			/* preload hashes with zeroes... */
2516 			for (i = 0; i < n; ++i) {
2517 				hashes[n].add(&hashes[n],
2518 					(const uint8_t *) "", 1);
2519 			}
2520 		}
2521 		passlen = (unsigned)strlen(passphrase);
2522 		for (n = 0; n * hashsize < keysize; ++n) {
2523 			unsigned        i;
2524 
2525 			switch (pkt.u.seckey.s2k_specifier) {
2526 			case PGP_S2KS_SALTED:
2527 				hashes[n].add(&hashes[n],
2528 					pkt.u.seckey.salt,
2529 					PGP_SALT_SIZE);
2530 				/* FALLTHROUGH */
2531 			case PGP_S2KS_SIMPLE:
2532 				hashes[n].add(&hashes[n],
2533 					(uint8_t *)passphrase, (unsigned)passlen);
2534 				break;
2535 
2536 			case PGP_S2KS_ITERATED_AND_SALTED:
2537 				for (i = 0; i < pkt.u.seckey.octetc;
2538 						i += passlen + PGP_SALT_SIZE) {
2539 					unsigned	j;
2540 
2541 					j = passlen + PGP_SALT_SIZE;
2542 					if (i + j > pkt.u.seckey.octetc && i != 0) {
2543 						j = pkt.u.seckey.octetc - i;
2544 					}
2545 					hashes[n].add(&hashes[n],
2546 						pkt.u.seckey.salt,
2547 						(unsigned)(j > PGP_SALT_SIZE) ?
2548 							PGP_SALT_SIZE : j);
2549 					if (j > PGP_SALT_SIZE) {
2550 						hashes[n].add(&hashes[n],
2551 						(uint8_t *) passphrase,
2552 						j - PGP_SALT_SIZE);
2553 					}
2554 				}
2555 				break;
2556 			default:
2557 				break;
2558 			}
2559 		}
2560 
2561 		for (n = 0; n * hashsize < keysize; ++n) {
2562 			int	r;
2563 
2564 			r = hashes[n].finish(&hashes[n], key + n * hashsize);
2565 			if (r != hashsize) {
2566 				(void) fprintf(stderr,
2567 					"parse_seckey: bad r\n");
2568 				return 0;
2569 			}
2570 		}
2571 
2572 		pgp_forget(passphrase, passlen);
2573 
2574 		pgp_crypt_any(&decrypt, pkt.u.seckey.alg);
2575 		if (pgp_get_debug_level(__FILE__)) {
2576 			hexdump(stderr, "input iv", pkt.u.seckey.iv, pgp_block_size(pkt.u.seckey.alg));
2577 			hexdump(stderr, "key", key, CAST_KEY_LENGTH);
2578 		}
2579 		decrypt.set_iv(&decrypt, pkt.u.seckey.iv);
2580 		decrypt.set_crypt_key(&decrypt, key);
2581 
2582 		/* now read encrypted data */
2583 
2584 		pgp_reader_push_decrypt(stream, &decrypt, region);
2585 
2586 		/*
2587 		 * Since all known encryption for PGP doesn't compress, we
2588 		 * can limit to the same length as the current region (for
2589 		 * now).
2590 		 */
2591 		pgp_init_subregion(&encregion, NULL);
2592 		encregion.length = region->length - region->readc;
2593 		if (pkt.u.seckey.pubkey.version != PGP_V4) {
2594 			encregion.length -= 2;
2595 		}
2596 		saved_region = region;
2597 		region = &encregion;
2598 	}
2599 	if (pgp_get_debug_level(__FILE__)) {
2600 		fprintf(stderr, "parse_seckey: end of crypted passphrase\n");
2601 	}
2602 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2603 		/* XXX - Hard-coded SHA1 here ?? Check */
2604 		pkt.u.seckey.checkhash = calloc(1, PGP_SHA1_HASH_SIZE);
2605 		if (pkt.u.seckey.checkhash == NULL) {
2606 			(void) fprintf(stderr, "parse_seckey: bad alloc\n");
2607 			return 0;
2608 		}
2609 		pgp_hash_sha1(&checkhash);
2610 		pgp_reader_push_hash(stream, &checkhash);
2611 	} else {
2612 		pgp_reader_push_sum16(stream);
2613 	}
2614 	if (pgp_get_debug_level(__FILE__)) {
2615 		fprintf(stderr, "parse_seckey: checkhash, reading MPIs\n");
2616 	}
2617 	switch (pkt.u.seckey.pubkey.alg) {
2618 	case PGP_PKA_RSA:
2619 	case PGP_PKA_RSA_ENCRYPT_ONLY:
2620 	case PGP_PKA_RSA_SIGN_ONLY:
2621 		if (!limread_mpi(&pkt.u.seckey.key.rsa.d, region, stream) ||
2622 		    !limread_mpi(&pkt.u.seckey.key.rsa.p, region, stream) ||
2623 		    !limread_mpi(&pkt.u.seckey.key.rsa.q, region, stream) ||
2624 		    !limread_mpi(&pkt.u.seckey.key.rsa.u, region, stream)) {
2625 			ret = 0;
2626 		}
2627 		break;
2628 
2629 	case PGP_PKA_DSA:
2630 		if (!limread_mpi(&pkt.u.seckey.key.dsa.x, region, stream)) {
2631 			ret = 0;
2632 		}
2633 		break;
2634 
2635 	case PGP_PKA_ELGAMAL:
2636 		if (!limread_mpi(&pkt.u.seckey.key.elgamal.x, region, stream)) {
2637 			ret = 0;
2638 		}
2639 		break;
2640 
2641 	default:
2642 		PGP_ERROR_2(&stream->errors,
2643 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2644 			"Unsupported Public Key algorithm %d (%s)",
2645 			pkt.u.seckey.pubkey.alg,
2646 			pgp_show_pka(pkt.u.seckey.pubkey.alg));
2647 		ret = 0;
2648 	}
2649 
2650 	if (pgp_get_debug_level(__FILE__)) {
2651 		(void) fprintf(stderr, "4 MPIs read\n");
2652 	}
2653 	stream->reading_v3_secret = 0;
2654 
2655 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2656 		uint8_t   hash[PGP_CHECKHASH_SIZE];
2657 
2658 		pgp_reader_pop_hash(stream);
2659 		checkhash.finish(&checkhash, hash);
2660 
2661 		if (crypted &&
2662 		    pkt.u.seckey.pubkey.version != PGP_V4) {
2663 			pgp_reader_pop_decrypt(stream);
2664 			region = saved_region;
2665 		}
2666 		if (ret) {
2667 			if (!limread(pkt.u.seckey.checkhash,
2668 				PGP_CHECKHASH_SIZE, region, stream)) {
2669 				return 0;
2670 			}
2671 
2672 			if (memcmp(hash, pkt.u.seckey.checkhash,
2673 					PGP_CHECKHASH_SIZE) != 0) {
2674 				ERRP(&stream->cbinfo, pkt,
2675 					"Hash mismatch in secret key");
2676 			}
2677 		}
2678 	} else {
2679 		uint16_t  sum;
2680 
2681 		sum = pgp_reader_pop_sum16(stream);
2682 		if (crypted &&
2683 		    pkt.u.seckey.pubkey.version != PGP_V4) {
2684 			pgp_reader_pop_decrypt(stream);
2685 			region = saved_region;
2686 		}
2687 		if (ret) {
2688 			if (!limread_scalar(&pkt.u.seckey.checksum, 2,
2689 					region, stream))
2690 				return 0;
2691 
2692 			if (sum != pkt.u.seckey.checksum) {
2693 				ERRP(&stream->cbinfo, pkt,
2694 					"Checksum mismatch in secret key");
2695 			}
2696 		}
2697 	}
2698 
2699 	if (crypted && pkt.u.seckey.pubkey.version == PGP_V4) {
2700 		pgp_reader_pop_decrypt(stream);
2701 	}
2702 	if (region == NULL) {
2703 		(void) fprintf(stderr, "parse_seckey: NULL region\n");
2704 		return 0;
2705 	}
2706 	if (ret && region->readc != region->length) {
2707 		(void) fprintf(stderr, "parse_seckey: bad length\n");
2708 		return 0;
2709 	}
2710 	if (!ret) {
2711 		return 0;
2712 	}
2713 	CALLBACK(PGP_PTAG_CT_SECRET_KEY, &stream->cbinfo, &pkt);
2714 	if (pgp_get_debug_level(__FILE__)) {
2715 		(void) fprintf(stderr, "--- end of parse_seckey\n\n");
2716 	}
2717 	return 1;
2718 }
2719 
2720 /**
2721    \ingroup Core_ReadPackets
2722    \brief Parse a Public Key Session Key packet
2723 */
2724 static int
2725 parse_pk_sesskey(pgp_region_t *region,
2726 		     pgp_stream_t *stream)
2727 {
2728 	const pgp_seckey_t	*secret;
2729 	pgp_packet_t		 sesskey;
2730 	pgp_packet_t		 pkt;
2731 	uint8_t			*iv;
2732 	uint8_t		   	 c = 0x0;
2733 	uint8_t			 cs[2];
2734 	unsigned		 k;
2735 	BIGNUM			*g_to_k;
2736 	BIGNUM			*enc_m;
2737 	int			 n;
2738 	uint8_t		 	 unencoded_m_buf[1024];
2739 
2740 	if (!limread(&c, 1, region, stream)) {
2741 		(void) fprintf(stderr, "parse_pk_sesskey - can't read char in region\n");
2742 		return 0;
2743 	}
2744 	pkt.u.pk_sesskey.version = c;
2745 	if (pkt.u.pk_sesskey.version != 3) {
2746 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_PKSK_VRSN,
2747 			"Bad public-key encrypted session key version (%d)",
2748 			    pkt.u.pk_sesskey.version);
2749 		return 0;
2750 	}
2751 	if (!limread(pkt.u.pk_sesskey.key_id,
2752 			  (unsigned)sizeof(pkt.u.pk_sesskey.key_id), region, stream)) {
2753 		return 0;
2754 	}
2755 	if (pgp_get_debug_level(__FILE__)) {
2756 		hexdump(stderr, "sesskey: pubkey id", pkt.u.pk_sesskey.key_id, sizeof(pkt.u.pk_sesskey.key_id));
2757 	}
2758 	if (!limread(&c, 1, region, stream)) {
2759 		return 0;
2760 	}
2761 	pkt.u.pk_sesskey.alg = (pgp_pubkey_alg_t)c;
2762 	switch (pkt.u.pk_sesskey.alg) {
2763 	case PGP_PKA_RSA:
2764 		if (!limread_mpi(&pkt.u.pk_sesskey.params.rsa.encrypted_m,
2765 				      region, stream)) {
2766 			return 0;
2767 		}
2768 		enc_m = pkt.u.pk_sesskey.params.rsa.encrypted_m;
2769 		g_to_k = NULL;
2770 		break;
2771 
2772 	case PGP_PKA_DSA:
2773 	case PGP_PKA_ELGAMAL:
2774 		if (!limread_mpi(&pkt.u.pk_sesskey.params.elgamal.g_to_k,
2775 				      region, stream) ||
2776 		    !limread_mpi(
2777 			&pkt.u.pk_sesskey.params.elgamal.encrypted_m,
2778 					 region, stream)) {
2779 			return 0;
2780 		}
2781 		g_to_k = pkt.u.pk_sesskey.params.elgamal.g_to_k;
2782 		enc_m = pkt.u.pk_sesskey.params.elgamal.encrypted_m;
2783 		break;
2784 
2785 	default:
2786 		PGP_ERROR_1(&stream->errors,
2787 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2788 			"Unknown public key algorithm in session key (%s)",
2789 			pgp_show_pka(pkt.u.pk_sesskey.alg));
2790 		return 0;
2791 	}
2792 
2793 	(void) memset(&sesskey, 0x0, sizeof(sesskey));
2794 	secret = NULL;
2795 	sesskey.u.get_seckey.seckey = &secret;
2796 	sesskey.u.get_seckey.pk_sesskey = &pkt.u.pk_sesskey;
2797 
2798 	if (pgp_get_debug_level(__FILE__)) {
2799 		(void) fprintf(stderr, "getting secret key via callback\n");
2800 	}
2801 
2802 	CALLBACK(PGP_GET_SECKEY, &stream->cbinfo, &sesskey);
2803 
2804 	if (pgp_get_debug_level(__FILE__)) {
2805 		(void) fprintf(stderr, "got secret key via callback\n");
2806 	}
2807 	if (!secret) {
2808 		CALLBACK(PGP_PTAG_CT_ENCRYPTED_PK_SESSION_KEY, &stream->cbinfo,
2809 			&pkt);
2810 		return 1;
2811 	}
2812 	n = pgp_decrypt_decode_mpi(unencoded_m_buf,
2813 		(unsigned)sizeof(unencoded_m_buf), g_to_k, enc_m, secret);
2814 
2815 	if (n < 1) {
2816 		ERRP(&stream->cbinfo, pkt, "decrypted message too short");
2817 		return 0;
2818 	}
2819 
2820 	/* PKA */
2821 	pkt.u.pk_sesskey.symm_alg = (pgp_symm_alg_t)unencoded_m_buf[0];
2822 	if (pgp_get_debug_level(__FILE__)) {
2823 		(void) fprintf(stderr, "symm alg %d\n", pkt.u.pk_sesskey.symm_alg);
2824 	}
2825 
2826 	if (!pgp_is_sa_supported(pkt.u.pk_sesskey.symm_alg)) {
2827 		/* ERR1P */
2828 		PGP_ERROR_1(&stream->errors, PGP_E_ALG_UNSUPPORTED_SYMMETRIC_ALG,
2829 			    "Symmetric algorithm %s not supported",
2830 			    pgp_show_symm_alg(
2831 				pkt.u.pk_sesskey.symm_alg));
2832 		return 0;
2833 	}
2834 	k = pgp_key_size(pkt.u.pk_sesskey.symm_alg);
2835 	if (pgp_get_debug_level(__FILE__)) {
2836 		(void) fprintf(stderr, "key size %d\n", k);
2837 	}
2838 
2839 	if ((unsigned) n != k + 3) {
2840 		PGP_ERROR_2(&stream->errors, PGP_E_PROTO_DECRYPTED_MSG_WRONG_LEN,
2841 		      "decrypted message wrong length (got %d expected %d)",
2842 			    n, k + 3);
2843 		return 0;
2844 	}
2845 	if (k > sizeof(pkt.u.pk_sesskey.key)) {
2846 		(void) fprintf(stderr, "parse_pk_sesskey: bad keylength\n");
2847 		return 0;
2848 	}
2849 
2850 	(void) memcpy(pkt.u.pk_sesskey.key, unencoded_m_buf + 1, k);
2851 
2852 	if (pgp_get_debug_level(__FILE__)) {
2853 		hexdump(stderr, "recovered sesskey", pkt.u.pk_sesskey.key, k);
2854 	}
2855 	pkt.u.pk_sesskey.checksum = unencoded_m_buf[k + 1] +
2856 			(unencoded_m_buf[k + 2] << 8);
2857 	if (pgp_get_debug_level(__FILE__)) {
2858 		(void) fprintf(stderr, "session key checksum: %2x %2x\n",
2859 			unencoded_m_buf[k + 1], unencoded_m_buf[k + 2]);
2860 	}
2861 
2862 	/* Check checksum */
2863 	pgp_calc_sesskey_checksum(&pkt.u.pk_sesskey, &cs[0]);
2864 	if (unencoded_m_buf[k + 1] != cs[0] ||
2865 	    unencoded_m_buf[k + 2] != cs[1]) {
2866 		PGP_ERROR_4(&stream->errors, PGP_E_PROTO_BAD_SK_CHECKSUM,
2867 		"Session key checksum wrong: expected %2x %2x, got %2x %2x",
2868 		cs[0], cs[1], unencoded_m_buf[k + 1],
2869 		unencoded_m_buf[k + 2]);
2870 		return 0;
2871 	}
2872 
2873 	if (pgp_get_debug_level(__FILE__)) {
2874 		(void) fprintf(stderr, "getting pk session key via callback\n");
2875 	}
2876 	/* all is well */
2877 	CALLBACK(PGP_PTAG_CT_PK_SESSION_KEY, &stream->cbinfo, &pkt);
2878 	if (pgp_get_debug_level(__FILE__)) {
2879 		(void) fprintf(stderr, "got pk session key via callback\n");
2880 	}
2881 
2882 	pgp_crypt_any(&stream->decrypt, pkt.u.pk_sesskey.symm_alg);
2883 	iv = calloc(1, stream->decrypt.blocksize);
2884 	if (iv == NULL) {
2885 		(void) fprintf(stderr, "parse_pk_sesskey: bad alloc\n");
2886 		return 0;
2887 	}
2888 	stream->decrypt.set_iv(&stream->decrypt, iv);
2889 	stream->decrypt.set_crypt_key(&stream->decrypt, pkt.u.pk_sesskey.key);
2890 	pgp_encrypt_init(&stream->decrypt);
2891 	free(iv);
2892 	return 1;
2893 }
2894 
2895 static int
2896 decrypt_se_data(pgp_content_enum tag, pgp_region_t *region,
2897 		    pgp_stream_t *stream)
2898 {
2899 	pgp_crypt_t	*decrypt;
2900 	const int	 printerrors = 1;
2901 	int		 r = 1;
2902 
2903 	decrypt = pgp_get_decrypt(stream);
2904 	if (decrypt) {
2905 		pgp_region_t	encregion;
2906 		unsigned	b = (unsigned)decrypt->blocksize;
2907 		uint8_t		buf[PGP_MAX_BLOCK_SIZE + 2] = "";
2908 
2909 		pgp_reader_push_decrypt(stream, decrypt, region);
2910 
2911 		pgp_init_subregion(&encregion, NULL);
2912 		encregion.length = b + 2;
2913 
2914 		if (!exact_limread(buf, b + 2, &encregion, stream)) {
2915 			return 0;
2916 		}
2917 		if (buf[b - 2] != buf[b] || buf[b - 1] != buf[b + 1]) {
2918 			pgp_reader_pop_decrypt(stream);
2919 			PGP_ERROR_4(&stream->errors,
2920 				PGP_E_PROTO_BAD_SYMMETRIC_DECRYPT,
2921 				"Bad symmetric decrypt (%02x%02x vs %02x%02x)",
2922 				buf[b - 2], buf[b - 1], buf[b], buf[b + 1]);
2923 			return 0;
2924 		}
2925 		if (tag == PGP_PTAG_CT_SE_DATA_BODY) {
2926 			decrypt->decrypt_resync(decrypt);
2927 			decrypt->block_encrypt(decrypt, decrypt->civ,
2928 					decrypt->civ);
2929 		}
2930 		r = pgp_parse(stream, !printerrors);
2931 
2932 		pgp_reader_pop_decrypt(stream);
2933 	} else {
2934 		pgp_packet_t pkt;
2935 
2936 		while (region->readc < region->length) {
2937 			unsigned        len;
2938 
2939 			len = region->length - region->readc;
2940 			if (len > sizeof(pkt.u.se_data_body.data))
2941 				len = sizeof(pkt.u.se_data_body.data);
2942 
2943 			if (!limread(pkt.u.se_data_body.data, len,
2944 					region, stream)) {
2945 				return 0;
2946 			}
2947 			pkt.u.se_data_body.length = len;
2948 			CALLBACK(tag, &stream->cbinfo, &pkt);
2949 		}
2950 	}
2951 
2952 	return r;
2953 }
2954 
2955 static int
2956 decrypt_se_ip_data(pgp_content_enum tag, pgp_region_t *region,
2957 		       pgp_stream_t *stream)
2958 {
2959 	pgp_crypt_t	*decrypt;
2960 	const int	 printerrors = 1;
2961 	int		 r = 1;
2962 
2963 	decrypt = pgp_get_decrypt(stream);
2964 	if (decrypt) {
2965 		if (pgp_get_debug_level(__FILE__)) {
2966 			(void) fprintf(stderr, "decrypt_se_ip_data: decrypt\n");
2967 		}
2968 		pgp_reader_push_decrypt(stream, decrypt, region);
2969 		pgp_reader_push_se_ip_data(stream, decrypt, region);
2970 
2971 		r = pgp_parse(stream, !printerrors);
2972 
2973 		pgp_reader_pop_se_ip_data(stream);
2974 		pgp_reader_pop_decrypt(stream);
2975 	} else {
2976 		pgp_packet_t pkt;
2977 
2978 		if (pgp_get_debug_level(__FILE__)) {
2979 			(void) fprintf(stderr, "decrypt_se_ip_data: no decrypt\n");
2980 		}
2981 		while (region->readc < region->length) {
2982 			unsigned        len;
2983 
2984 			len = region->length - region->readc;
2985 			if (len > sizeof(pkt.u.se_data_body.data)) {
2986 				len = sizeof(pkt.u.se_data_body.data);
2987 			}
2988 
2989 			if (!limread(pkt.u.se_data_body.data,
2990 					len, region, stream)) {
2991 				return 0;
2992 			}
2993 
2994 			pkt.u.se_data_body.length = len;
2995 
2996 			CALLBACK(tag, &stream->cbinfo, &pkt);
2997 		}
2998 	}
2999 
3000 	return r;
3001 }
3002 
3003 /**
3004    \ingroup Core_ReadPackets
3005    \brief Read a Symmetrically Encrypted packet
3006 */
3007 static int
3008 parse_se_data(pgp_region_t *region, pgp_stream_t *stream)
3009 {
3010 	pgp_packet_t pkt;
3011 
3012 	/* there's no info to go with this, so just announce it */
3013 	CALLBACK(PGP_PTAG_CT_SE_DATA_HEADER, &stream->cbinfo, &pkt);
3014 
3015 	/*
3016 	 * The content of an encrypted data packet is more OpenPGP packets
3017 	 * once decrypted, so recursively handle them
3018 	 */
3019 	return decrypt_se_data(PGP_PTAG_CT_SE_DATA_BODY, region, stream);
3020 }
3021 
3022 /**
3023    \ingroup Core_ReadPackets
3024    \brief Read a Symmetrically Encrypted Integrity Protected packet
3025 */
3026 static int
3027 parse_se_ip_data(pgp_region_t *region, pgp_stream_t *stream)
3028 {
3029 	pgp_packet_t	pkt;
3030 	uint8_t		c = 0x0;
3031 
3032 	if (!limread(&c, 1, region, stream)) {
3033 		return 0;
3034 	}
3035 	pkt.u.se_ip_data_header = c;
3036 	if (pgp_get_debug_level(__FILE__)) {
3037 		(void) fprintf(stderr, "parse_se_ip_data: data header %d\n", c);
3038 	}
3039 	if (pkt.u.se_ip_data_header != PGP_SE_IP_DATA_VERSION) {
3040 		(void) fprintf(stderr, "parse_se_ip_data: bad version\n");
3041 		return 0;
3042 	}
3043 
3044 	if (pgp_get_debug_level(__FILE__)) {
3045 		(void) fprintf(stderr, "parse_se_ip_data: region %d,%d\n",
3046 			region->readc, region->length);
3047 		hexdump(stderr, "compressed region", stream->virtualpkt, stream->virtualc);
3048 	}
3049 	/*
3050 	 * The content of an encrypted data packet is more OpenPGP packets
3051 	 * once decrypted, so recursively handle them
3052 	 */
3053 	return decrypt_se_ip_data(PGP_PTAG_CT_SE_IP_DATA_BODY, region, stream);
3054 }
3055 
3056 /**
3057    \ingroup Core_ReadPackets
3058    \brief Read a MDC packet
3059 */
3060 static int
3061 parse_mdc(pgp_region_t *region, pgp_stream_t *stream)
3062 {
3063 	pgp_packet_t pkt;
3064 
3065 	pkt.u.mdc.length = PGP_SHA1_HASH_SIZE;
3066 	if ((pkt.u.mdc.data = calloc(1, PGP_SHA1_HASH_SIZE)) == NULL) {
3067 		(void) fprintf(stderr, "parse_mdc: bad alloc\n");
3068 		return 0;
3069 	}
3070 	if (!limread(pkt.u.mdc.data, PGP_SHA1_HASH_SIZE, region, stream)) {
3071 		return 0;
3072 	}
3073 	CALLBACK(PGP_PTAG_CT_MDC, &stream->cbinfo, &pkt);
3074 	free(pkt.u.mdc.data);
3075 	return 1;
3076 }
3077 
3078 /**
3079  * \ingroup Core_ReadPackets
3080  * \brief Parse one packet.
3081  *
3082  * This function parses the packet tag.  It computes the value of the
3083  * content tag and then calls the appropriate function to handle the
3084  * content.
3085  *
3086  * \param *stream	How to parse
3087  * \param *pktlen	On return, will contain number of bytes in packet
3088  * \return 1 on success, 0 on error, -1 on EOF */
3089 static int
3090 parse_packet(pgp_stream_t *stream, uint32_t *pktlen)
3091 {
3092 	pgp_packet_t		pkt;
3093 	pgp_region_t		region;
3094 	pgp_content_enum	tag;
3095 	uint8_t			ptag;
3096 	unsigned		indeterminate = 0;
3097 	int			ret;
3098 
3099 	pkt.u.ptag.position = stream->readinfo.position;
3100 
3101 	ret = base_read(&ptag, 1, stream);
3102 
3103 	if (pgp_get_debug_level(__FILE__)) {
3104 		(void) fprintf(stderr,
3105 			"parse_packet: base_read returned %d, ptag %d\n",
3106 			ret, ptag);
3107 	}
3108 
3109 	/* errors in the base read are effectively EOF. */
3110 	if (ret <= 0) {
3111 		return -1;
3112 	}
3113 
3114 	*pktlen = 0;
3115 
3116 	if (!(ptag & PGP_PTAG_ALWAYS_SET)) {
3117 		pkt.u.error = "Format error (ptag bit not set)";
3118 		CALLBACK(PGP_PARSER_ERROR, &stream->cbinfo, &pkt);
3119 		return 0;
3120 	}
3121 	pkt.u.ptag.new_format = !!(ptag & PGP_PTAG_NEW_FORMAT);
3122 	if (pkt.u.ptag.new_format) {
3123 		pkt.u.ptag.type = (ptag & PGP_PTAG_NF_CONTENT_TAG_MASK);
3124 		pkt.u.ptag.length_type = 0;
3125 		if (!read_new_length(&pkt.u.ptag.length, stream)) {
3126 			return 0;
3127 		}
3128 	} else {
3129 		unsigned   rb;
3130 
3131 		rb = 0;
3132 		pkt.u.ptag.type = ((unsigned)ptag &
3133 				PGP_PTAG_OF_CONTENT_TAG_MASK)
3134 			>> PGP_PTAG_OF_CONTENT_TAG_SHIFT;
3135 		pkt.u.ptag.length_type = ptag & PGP_PTAG_OF_LENGTH_TYPE_MASK;
3136 		switch (pkt.u.ptag.length_type) {
3137 		case PGP_PTAG_OLD_LEN_1:
3138 			rb = _read_scalar(&pkt.u.ptag.length, 1, stream);
3139 			break;
3140 
3141 		case PGP_PTAG_OLD_LEN_2:
3142 			rb = _read_scalar(&pkt.u.ptag.length, 2, stream);
3143 			break;
3144 
3145 		case PGP_PTAG_OLD_LEN_4:
3146 			rb = _read_scalar(&pkt.u.ptag.length, 4, stream);
3147 			break;
3148 
3149 		case PGP_PTAG_OLD_LEN_INDETERMINATE:
3150 			pkt.u.ptag.length = 0;
3151 			indeterminate = 1;
3152 			rb = 1;
3153 			break;
3154 		}
3155 		if (!rb) {
3156 			return 0;
3157 		}
3158 	}
3159 
3160 	CALLBACK(PGP_PARSER_PTAG, &stream->cbinfo, &pkt);
3161 
3162 	pgp_init_subregion(&region, NULL);
3163 	region.length = pkt.u.ptag.length;
3164 	region.indeterminate = indeterminate;
3165 	if (pgp_get_debug_level(__FILE__)) {
3166 		(void) fprintf(stderr, "parse_packet: type %u\n",
3167 			       pkt.u.ptag.type);
3168 	}
3169 
3170 	/* save tag for accumulator */
3171 	tag = pkt.u.ptag.type;
3172 	switch (pkt.u.ptag.type) {
3173 	case PGP_PTAG_CT_SIGNATURE:
3174 		ret = parse_sig(&region, stream);
3175 		break;
3176 
3177 	case PGP_PTAG_CT_PUBLIC_KEY:
3178 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
3179 		ret = parse_pubkey((pgp_content_enum)pkt.u.ptag.type, &region, stream);
3180 		break;
3181 
3182 	case PGP_PTAG_CT_TRUST:
3183 		ret = parse_trust(&region, stream);
3184 		break;
3185 
3186 	case PGP_PTAG_CT_USER_ID:
3187 		ret = parse_userid(&region, stream);
3188 		break;
3189 
3190 	case PGP_PTAG_CT_COMPRESSED:
3191 		ret = parse_compressed(&region, stream);
3192 		break;
3193 
3194 	case PGP_PTAG_CT_1_PASS_SIG:
3195 		ret = parse_one_pass(&region, stream);
3196 		break;
3197 
3198 	case PGP_PTAG_CT_LITDATA:
3199 		ret = parse_litdata(&region, stream);
3200 		break;
3201 
3202 	case PGP_PTAG_CT_USER_ATTR:
3203 		ret = parse_userattr(&region, stream);
3204 		break;
3205 
3206 	case PGP_PTAG_CT_SECRET_KEY:
3207 		ret = parse_seckey(&region, stream);
3208 		break;
3209 
3210 	case PGP_PTAG_CT_SECRET_SUBKEY:
3211 		ret = parse_seckey(&region, stream);
3212 		break;
3213 
3214 	case PGP_PTAG_CT_PK_SESSION_KEY:
3215 		ret = parse_pk_sesskey(&region, stream);
3216 		break;
3217 
3218 	case PGP_PTAG_CT_SE_DATA:
3219 		ret = parse_se_data(&region, stream);
3220 		break;
3221 
3222 	case PGP_PTAG_CT_SE_IP_DATA:
3223 		ret = parse_se_ip_data(&region, stream);
3224 		break;
3225 
3226 	case PGP_PTAG_CT_MDC:
3227 		ret = parse_mdc(&region, stream);
3228 		break;
3229 
3230 	default:
3231 		PGP_ERROR_1(&stream->errors, PGP_E_P_UNKNOWN_TAG,
3232 			    "Unknown content tag 0x%x",
3233 			    pkt.u.ptag.type);
3234 		ret = 0;
3235 	}
3236 
3237 	/* Ensure that the entire packet has been consumed */
3238 
3239 	if (region.length != region.readc && !region.indeterminate) {
3240 		if (!consume_packet(&region, stream, 0)) {
3241 			ret = -1;
3242 		}
3243 	}
3244 
3245 	/* also consume it if there's been an error? */
3246 	/* \todo decide what to do about an error on an */
3247 	/* indeterminate packet */
3248 	if (ret == 0) {
3249 		if (!consume_packet(&region, stream, 0)) {
3250 			ret = -1;
3251 		}
3252 	}
3253 	/* set pktlen */
3254 
3255 	*pktlen = stream->readinfo.alength;
3256 
3257 	/* do callback on entire packet, if desired and there was no error */
3258 
3259 	if (ret > 0 && stream->readinfo.accumulate) {
3260 		pkt.u.packet.length = stream->readinfo.alength;
3261 		pkt.u.packet.raw = stream->readinfo.accumulated;
3262 		pkt.u.packet.tag = tag;
3263 		stream->readinfo.accumulated = NULL;
3264 		stream->readinfo.asize = 0;
3265 		CALLBACK(PGP_PARSER_PACKET_END, &stream->cbinfo, &pkt);
3266 	}
3267 	stream->readinfo.alength = 0;
3268 
3269 	return (ret < 0) ? -1 : (ret) ? 1 : 0;
3270 }
3271 
3272 /**
3273  * \ingroup Core_ReadPackets
3274  *
3275  * \brief Parse packets from an input stream until EOF or error.
3276  *
3277  * \details Setup the necessary parsing configuration in "stream"
3278  * before calling pgp_parse().
3279  *
3280  * That information includes :
3281  *
3282  * - a "reader" function to be used to get the data to be parsed
3283  *
3284  * - a "callback" function to be called when this library has identified
3285  * a parseable object within the data
3286  *
3287  * - whether the calling function wants the signature subpackets
3288  * returned raw, parsed or not at all.
3289  *
3290  * After returning, stream->errors holds any errors encountered while parsing.
3291  *
3292  * \param stream	Parsing configuration
3293  * \return		1 on success in all packets, 0 on error in any packet
3294  *
3295  * \sa CoreAPI Overview
3296  *
3297  * \sa pgp_print_errors()
3298  *
3299  */
3300 
3301 int
3302 pgp_parse(pgp_stream_t *stream, const int perrors)
3303 {
3304 	uint32_t   pktlen;
3305 	int             r;
3306 
3307 	do {
3308 		r = parse_packet(stream, &pktlen);
3309 	} while (r != -1);
3310 	if (perrors) {
3311 		pgp_print_errors(stream->errors);
3312 	}
3313 	return (stream->errors == NULL);
3314 }
3315 
3316 /**
3317  * \ingroup Core_ReadPackets
3318  *
3319  * \brief Specifies whether one or more signature
3320  * subpacket types should be returned parsed; or raw; or ignored.
3321  *
3322  * \param	stream	Pointer to previously allocated structure
3323  * \param	tag	Packet tag. PGP_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
3324  * \param	type	Parse type
3325  * \todo Make all packet types optional, not just subpackets */
3326 void
3327 pgp_parse_options(pgp_stream_t *stream,
3328 		  pgp_content_enum tag,
3329 		  pgp_parse_type_t type)
3330 {
3331 	unsigned	t7;
3332 	unsigned	t8;
3333 
3334 	if (tag == PGP_PTAG_SS_ALL) {
3335 		int             n;
3336 
3337 		for (n = 0; n < 256; ++n) {
3338 			pgp_parse_options(stream,
3339 				PGP_PTAG_SIG_SUBPKT_BASE + n,
3340 				type);
3341 		}
3342 		return;
3343 	}
3344 	if (tag < PGP_PTAG_SIG_SUBPKT_BASE ||
3345 	    tag > PGP_PTAG_SIG_SUBPKT_BASE + NTAGS - 1) {
3346 		(void) fprintf(stderr, "pgp_parse_options: bad tag\n");
3347 		return;
3348 	}
3349 	t8 = (tag - PGP_PTAG_SIG_SUBPKT_BASE) / 8;
3350 	t7 = 1 << ((tag - PGP_PTAG_SIG_SUBPKT_BASE) & 7);
3351 	switch (type) {
3352 	case PGP_PARSE_RAW:
3353 		stream->ss_raw[t8] |= t7;
3354 		stream->ss_parsed[t8] &= ~t7;
3355 		break;
3356 
3357 	case PGP_PARSE_PARSED:
3358 		stream->ss_raw[t8] &= ~t7;
3359 		stream->ss_parsed[t8] |= t7;
3360 		break;
3361 
3362 	case PGP_PARSE_IGNORE:
3363 		stream->ss_raw[t8] &= ~t7;
3364 		stream->ss_parsed[t8] &= ~t7;
3365 		break;
3366 	}
3367 }
3368 
3369 /**
3370 \ingroup Core_ReadPackets
3371 \brief Free pgp_stream_t struct and its contents
3372 */
3373 void
3374 pgp_stream_delete(pgp_stream_t *stream)
3375 {
3376 	pgp_cbdata_t	*cbinfo;
3377 	pgp_cbdata_t	*next;
3378 
3379 	for (cbinfo = stream->cbinfo.next; cbinfo; cbinfo = next) {
3380 		next = cbinfo->next;
3381 		free(cbinfo);
3382 	}
3383 	if (stream->readinfo.destroyer) {
3384 		stream->readinfo.destroyer(&stream->readinfo);
3385 	}
3386 	pgp_free_errors(stream->errors);
3387 	if (stream->readinfo.accumulated) {
3388 		free(stream->readinfo.accumulated);
3389 	}
3390 	free(stream);
3391 }
3392 
3393 /**
3394 \ingroup Core_ReadPackets
3395 \brief Returns the parse_info's reader_info
3396 \return Pointer to the reader_info inside the parse_info
3397 */
3398 pgp_reader_t *
3399 pgp_readinfo(pgp_stream_t *stream)
3400 {
3401 	return &stream->readinfo;
3402 }
3403 
3404 /**
3405 \ingroup Core_ReadPackets
3406 \brief Sets the parse_info's callback
3407 This is used when adding the first callback in a stack of callbacks.
3408 \sa pgp_callback_push()
3409 */
3410 
3411 void
3412 pgp_set_callback(pgp_stream_t *stream, pgp_cbfunc_t *cb, void *arg)
3413 {
3414 	stream->cbinfo.cbfunc = cb;
3415 	stream->cbinfo.arg = arg;
3416 	stream->cbinfo.errors = &stream->errors;
3417 }
3418 
3419 /**
3420 \ingroup Core_ReadPackets
3421 \brief Adds a further callback to a stack of callbacks
3422 \sa pgp_set_callback()
3423 */
3424 void
3425 pgp_callback_push(pgp_stream_t *stream, pgp_cbfunc_t *cb, void *arg)
3426 {
3427 	pgp_cbdata_t	*cbinfo;
3428 
3429 	if ((cbinfo = calloc(1, sizeof(*cbinfo))) == NULL) {
3430 		(void) fprintf(stderr, "pgp_callback_push: bad alloc\n");
3431 		return;
3432 	}
3433 	(void) memcpy(cbinfo, &stream->cbinfo, sizeof(*cbinfo));
3434 	cbinfo->io = stream->io;
3435 	stream->cbinfo.next = cbinfo;
3436 	pgp_set_callback(stream, cb, arg);
3437 }
3438 
3439 /**
3440 \ingroup Core_ReadPackets
3441 \brief Returns callback's arg
3442 */
3443 void *
3444 pgp_callback_arg(pgp_cbdata_t *cbinfo)
3445 {
3446 	return cbinfo->arg;
3447 }
3448 
3449 /**
3450 \ingroup Core_ReadPackets
3451 \brief Returns callback's errors
3452 */
3453 void *
3454 pgp_callback_errors(pgp_cbdata_t *cbinfo)
3455 {
3456 	return cbinfo->errors;
3457 }
3458 
3459 /**
3460 \ingroup Core_ReadPackets
3461 \brief Calls the parse_cb_info's callback if present
3462 \return Return value from callback, if present; else PGP_FINISHED
3463 */
3464 pgp_cb_ret_t
3465 pgp_callback(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
3466 {
3467 	return (cbinfo->cbfunc) ? cbinfo->cbfunc(pkt, cbinfo) : PGP_FINISHED;
3468 }
3469 
3470 /**
3471 \ingroup Core_ReadPackets
3472 \brief Calls the next callback  in the stack
3473 \return Return value from callback
3474 */
3475 pgp_cb_ret_t
3476 pgp_stacked_callback(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
3477 {
3478 	return pgp_callback(pkt, cbinfo->next);
3479 }
3480 
3481 /**
3482 \ingroup Core_ReadPackets
3483 \brief Returns the parse_info's errors
3484 \return parse_info's errors
3485 */
3486 pgp_error_t    *
3487 pgp_stream_get_errors(pgp_stream_t *stream)
3488 {
3489 	return stream->errors;
3490 }
3491 
3492 pgp_crypt_t    *
3493 pgp_get_decrypt(pgp_stream_t *stream)
3494 {
3495 	return (stream->decrypt.alg) ? &stream->decrypt : NULL;
3496 }
3497