xref: /minix3/crypto/external/bsd/netpgp/dist/src/lib/reader.c (revision ebfedea0ce5bbe81e252ddf32d732e40fb633fae)
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 #include "config.h"
50 
51 #ifdef HAVE_SYS_CDEFS_H
52 #include <sys/cdefs.h>
53 #endif
54 
55 #if defined(__NetBSD__)
56 __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved.");
57 __RCSID("$NetBSD: reader.c,v 1.49 2012/03/05 02:20:18 christos Exp $");
58 #endif
59 
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 
63 #ifdef HAVE_SYS_MMAN_H
64 #include <sys/mman.h>
65 #endif
66 
67 #ifdef HAVE_SYS_PARAM_H
68 #include <sys/param.h>
69 #endif
70 
71 #ifdef HAVE_FCNTL_H
72 #include <fcntl.h>
73 #endif
74 
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 
79 #ifdef HAVE_DIRECT_H
80 #include <direct.h>
81 #endif
82 
83 #ifdef HAVE_INTTYPES_H
84 #include <inttypes.h>
85 #endif
86 
87 #ifdef HAVE_OPENSSL_IDEA_H
88 #include <openssl/cast.h>
89 #endif
90 
91 #ifdef HAVE_OPENSSL_IDEA_H
92 #include <openssl/idea.h>
93 #endif
94 
95 #ifdef HAVE_OPENSSL_AES_H
96 #include <openssl/aes.h>
97 #endif
98 
99 #ifdef HAVE_OPENSSL_DES_H
100 #include <openssl/des.h>
101 #endif
102 
103 #include <string.h>
104 #include <stdlib.h>
105 #include <stdio.h>
106 
107 #ifdef HAVE_TERMIOS_H
108 #include <termios.h>
109 #endif
110 
111 #ifdef HAVE_ERRNO_H
112 #include <errno.h>
113 #endif
114 
115 #ifdef HAVE_UNISTD_H
116 #include <unistd.h>
117 #endif
118 
119 #ifdef HAVE_LIMITS_H
120 #include <limits.h>
121 #endif
122 
123 #include "errors.h"
124 #include "crypto.h"
125 #include "create.h"
126 #include "signature.h"
127 #include "packet.h"
128 #include "packet-parse.h"
129 #include "packet-show.h"
130 #include "packet.h"
131 #include "keyring.h"
132 #include "readerwriter.h"
133 #include "netpgpsdk.h"
134 #include "netpgpdefs.h"
135 #include "netpgpdigest.h"
136 
137 /* data from partial blocks is queued up in virtual block in stream */
138 static int
read_partial_data(pgp_stream_t * stream,void * dest,size_t length)139 read_partial_data(pgp_stream_t *stream, void *dest, size_t length)
140 {
141 	unsigned	n;
142 
143 	if (pgp_get_debug_level(__FILE__)) {
144 		(void) fprintf(stderr, "fd_reader: coalesced data, off %d\n",
145 				stream->virtualoff);
146 	}
147 	n = MIN(stream->virtualc - stream->virtualoff, (unsigned)length);
148 	(void) memcpy(dest, &stream->virtualpkt[stream->virtualoff], n);
149 	stream->virtualoff += n;
150 	if (stream->virtualoff == stream->virtualc) {
151 		free(stream->virtualpkt);
152 		stream->virtualpkt = NULL;
153 		stream->virtualc = stream->virtualoff = 0;
154 	}
155 	return (int)n;
156 }
157 
158 /* get a pass phrase from the user */
159 int
pgp_getpassphrase(void * in,char * phrase,size_t size)160 pgp_getpassphrase(void *in, char *phrase, size_t size)
161 {
162 	char	*p;
163 
164 	if (in == NULL) {
165 		while ((p = getpass("netpgp passphrase: ")) == NULL) {
166 		}
167 		(void) snprintf(phrase, size, "%s", p);
168 	} else {
169 		if (fgets(phrase, (int)size, in) == NULL) {
170 			return 0;
171 		}
172 		phrase[strlen(phrase) - 1] = 0x0;
173 	}
174 	return 1;
175 }
176 
177 /**
178  * \ingroup Internal_Readers_Generic
179  * \brief Starts reader stack
180  * \param stream Parse settings
181  * \param reader Reader to use
182  * \param destroyer Destroyer to use
183  * \param vp Reader-specific arg
184  */
185 void
pgp_reader_set(pgp_stream_t * stream,pgp_reader_func_t * reader,pgp_reader_destroyer_t * destroyer,void * vp)186 pgp_reader_set(pgp_stream_t *stream,
187 		pgp_reader_func_t *reader,
188 		pgp_reader_destroyer_t *destroyer,
189 		void *vp)
190 {
191 	stream->readinfo.reader = reader;
192 	stream->readinfo.destroyer = destroyer;
193 	stream->readinfo.arg = vp;
194 }
195 
196 /**
197  * \ingroup Internal_Readers_Generic
198  * \brief Adds to reader stack
199  * \param stream Parse settings
200  * \param reader Reader to use
201  * \param destroyer Reader's destroyer
202  * \param vp Reader-specific arg
203  */
204 void
pgp_reader_push(pgp_stream_t * stream,pgp_reader_func_t * reader,pgp_reader_destroyer_t * destroyer,void * vp)205 pgp_reader_push(pgp_stream_t *stream,
206 		pgp_reader_func_t *reader,
207 		pgp_reader_destroyer_t *destroyer,
208 		void *vp)
209 {
210 	pgp_reader_t *readinfo;
211 
212 	if ((readinfo = calloc(1, sizeof(*readinfo))) == NULL) {
213 		(void) fprintf(stderr, "pgp_reader_push: bad alloc\n");
214 	} else {
215 		*readinfo = stream->readinfo;
216 		(void) memset(&stream->readinfo, 0x0, sizeof(stream->readinfo));
217 		stream->readinfo.next = readinfo;
218 		stream->readinfo.parent = stream;
219 
220 		/* should copy accumulate flags from other reader? RW */
221 		stream->readinfo.accumulate = readinfo->accumulate;
222 
223 		pgp_reader_set(stream, reader, destroyer, vp);
224 	}
225 }
226 
227 /**
228  * \ingroup Internal_Readers_Generic
229  * \brief Removes from reader stack
230  * \param stream Parse settings
231  */
232 void
pgp_reader_pop(pgp_stream_t * stream)233 pgp_reader_pop(pgp_stream_t *stream)
234 {
235 	pgp_reader_t *next = stream->readinfo.next;
236 
237 	stream->readinfo = *next;
238 	free(next);
239 }
240 
241 /**
242  * \ingroup Internal_Readers_Generic
243  * \brief Gets arg from reader
244  * \param readinfo Reader info
245  * \return Pointer to reader info's arg
246  */
247 void           *
pgp_reader_get_arg(pgp_reader_t * readinfo)248 pgp_reader_get_arg(pgp_reader_t *readinfo)
249 {
250 	return readinfo->arg;
251 }
252 
253 /**************************************************************************/
254 
255 #define CRC24_POLY 0x1864cfbL
256 
257 enum {
258 	NONE = 0,
259 	BEGIN_PGP_MESSAGE,
260 	BEGIN_PGP_PUBLIC_KEY_BLOCK,
261 	BEGIN_PGP_PRIVATE_KEY_BLOCK,
262 	BEGIN_PGP_MULTI,
263 	BEGIN_PGP_SIGNATURE,
264 
265 	END_PGP_MESSAGE,
266 	END_PGP_PUBLIC_KEY_BLOCK,
267 	END_PGP_PRIVATE_KEY_BLOCK,
268 	END_PGP_MULTI,
269 	END_PGP_SIGNATURE,
270 
271 	BEGIN_PGP_SIGNED_MESSAGE
272 };
273 
274 /**
275  * \struct dearmour_t
276  */
277 typedef struct {
278 	enum {
279 		OUTSIDE_BLOCK = 0,
280 		BASE64,
281 		AT_TRAILER_NAME
282 	} state;
283 	int		lastseen;
284 	pgp_stream_t *parse_info;
285 	unsigned	seen_nl:1;
286 	unsigned	prev_nl:1;
287 	unsigned	allow_headers_without_gap:1;
288 			/* !< allow headers in armoured data that are
289 			* not separated from the data by a blank line
290 			* */
291 	unsigned	allow_no_gap:1;
292 			/* !< allow no blank line at the start of
293 			* armoured data */
294 	unsigned	allow_trailing_whitespace:1;
295 			/* !< allow armoured stuff to have trailing
296 			* whitespace where we wouldn't strictly expect
297 			* it */
298 	/* it is an error to get a cleartext message without a sig */
299 	unsigned   	expect_sig:1;
300 	unsigned   	got_sig:1;
301 	/* base64 stuff */
302 	unsigned        buffered;
303 	uint8_t		buffer[3];
304 	unsigned	eof64;
305 	uint32_t   checksum;
306 	uint32_t   read_checksum;
307 	/* unarmoured text blocks */
308 	uint8_t   unarmoured[NETPGP_BUFSIZ];
309 	size_t          unarmoredc;
310 	/* pushed back data (stored backwards) */
311 	uint8_t  *pushback;
312 	unsigned        pushbackc;
313 	/* armoured block headers */
314 	pgp_headers_t	headers;
315 } dearmour_t;
316 
317 static void
push_back(dearmour_t * dearmour,const uint8_t * buf,unsigned length)318 push_back(dearmour_t *dearmour, const uint8_t *buf,
319 	  unsigned length)
320 {
321 	unsigned        n;
322 
323 	if (dearmour->pushback) {
324 		(void) fprintf(stderr, "push_back: already pushed back\n");
325 	} else if ((dearmour->pushback = calloc(1, length)) == NULL) {
326 		(void) fprintf(stderr, "push_back: bad alloc\n");
327 	} else {
328 		for (n = 0; n < length; ++n) {
329 			dearmour->pushback[n] = buf[(length - n) - 1];
330 		}
331 		dearmour->pushbackc = length;
332 	}
333 }
334 
335 /* this struct holds a textual header line */
336 typedef struct headerline_t {
337 	const char	*s;		/* the header line */
338 	size_t		 len;		/* its length */
339 	int		 type;		/* the defined type */
340 } headerline_t;
341 
342 static headerline_t	headerlines[] = {
343 	{ "BEGIN PGP MESSAGE",		17, BEGIN_PGP_MESSAGE },
344 	{ "BEGIN PGP PUBLIC KEY BLOCK",	26, BEGIN_PGP_PUBLIC_KEY_BLOCK },
345 	{ "BEGIN PGP PRIVATE KEY BLOCK",27, BEGIN_PGP_PRIVATE_KEY_BLOCK },
346 	{ "BEGIN PGP MESSAGE, PART ",	25, BEGIN_PGP_MULTI },
347 	{ "BEGIN PGP SIGNATURE",	19, BEGIN_PGP_SIGNATURE },
348 
349 	{ "END PGP MESSAGE",		15, END_PGP_MESSAGE },
350 	{ "END PGP PUBLIC KEY BLOCK",	24, END_PGP_PUBLIC_KEY_BLOCK },
351 	{ "END PGP PRIVATE KEY BLOCK",	25, END_PGP_PRIVATE_KEY_BLOCK },
352 	{ "END PGP MESSAGE, PART ",	22, END_PGP_MULTI },
353 	{ "END PGP SIGNATURE",		17, END_PGP_SIGNATURE },
354 
355 	{ "BEGIN PGP SIGNED MESSAGE",	24, BEGIN_PGP_SIGNED_MESSAGE },
356 
357 	{ NULL,				0, -1	}
358 };
359 
360 /* search through the table of header lines */
361 static int
findheaderline(char * headerline)362 findheaderline(char *headerline)
363 {
364 	headerline_t	*hp;
365 
366 	for (hp = headerlines ; hp->s ; hp++) {
367 		if (strncmp(headerline, hp->s, hp->len) == 0) {
368 			break;
369 		}
370 	}
371 	return hp->type;
372 }
373 
374 static int
set_lastseen_headerline(dearmour_t * dearmour,char * hdr,pgp_error_t ** errors)375 set_lastseen_headerline(dearmour_t *dearmour, char *hdr, pgp_error_t **errors)
376 {
377 	int	lastseen;
378 	int	prev;
379 
380 	prev = dearmour->lastseen;
381 	if ((lastseen = findheaderline(hdr)) == -1) {
382 		PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
383 			"Unrecognised Header Line %s", hdr);
384 		return 0;
385 	}
386 	dearmour->lastseen = lastseen;
387 	if (pgp_get_debug_level(__FILE__)) {
388 		printf("set header: hdr=%s, dearmour->lastseen=%d, prev=%d\n",
389 			hdr, dearmour->lastseen, prev);
390 	}
391 	switch (dearmour->lastseen) {
392 	case NONE:
393 		PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
394 			"Unrecognised last seen Header Line %s", hdr);
395 		break;
396 
397 	case END_PGP_MESSAGE:
398 		if (prev != BEGIN_PGP_MESSAGE) {
399 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
400 				"Got END PGP MESSAGE, but not after BEGIN");
401 		}
402 		break;
403 
404 	case END_PGP_PUBLIC_KEY_BLOCK:
405 		if (prev != BEGIN_PGP_PUBLIC_KEY_BLOCK) {
406 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
407 			"Got END PGP PUBLIC KEY BLOCK, but not after BEGIN");
408 		}
409 		break;
410 
411 	case END_PGP_PRIVATE_KEY_BLOCK:
412 		if (prev != BEGIN_PGP_PRIVATE_KEY_BLOCK) {
413 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
414 			"Got END PGP PRIVATE KEY BLOCK, but not after BEGIN");
415 		}
416 		break;
417 
418 	case BEGIN_PGP_MULTI:
419 	case END_PGP_MULTI:
420 		PGP_ERROR_1(errors, PGP_E_R_UNSUPPORTED, "%s",
421 			"Multi-part messages are not yet supported");
422 		break;
423 
424 	case END_PGP_SIGNATURE:
425 		if (prev != BEGIN_PGP_SIGNATURE) {
426 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
427 			"Got END PGP SIGNATURE, but not after BEGIN");
428 		}
429 		break;
430 
431 	case BEGIN_PGP_MESSAGE:
432 	case BEGIN_PGP_PUBLIC_KEY_BLOCK:
433 	case BEGIN_PGP_PRIVATE_KEY_BLOCK:
434 	case BEGIN_PGP_SIGNATURE:
435 	case BEGIN_PGP_SIGNED_MESSAGE:
436 		break;
437 	}
438 	return 1;
439 }
440 
441 static int
read_char(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo,unsigned skip)442 read_char(pgp_stream_t *stream, dearmour_t *dearmour,
443 		pgp_error_t **errors,
444 		pgp_reader_t *readinfo,
445 		pgp_cbdata_t *cbinfo,
446 		unsigned skip)
447 {
448 	uint8_t   c;
449 
450 	do {
451 		if (dearmour->pushbackc) {
452 			c = dearmour->pushback[--dearmour->pushbackc];
453 			if (dearmour->pushbackc == 0) {
454 				free(dearmour->pushback);
455 				dearmour->pushback = NULL;
456 			}
457 		} else if (pgp_stacked_read(stream, &c, 1, errors, readinfo,
458 					cbinfo) != 1) {
459 			return -1;
460 		}
461 	} while (skip && c == '\r');
462 	dearmour->prev_nl = dearmour->seen_nl;
463 	dearmour->seen_nl = c == '\n';
464 	return c;
465 }
466 
467 static int
eat_whitespace(pgp_stream_t * stream,int first,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo,unsigned skip)468 eat_whitespace(pgp_stream_t *stream, int first,
469 	       dearmour_t *dearmour,
470 	       pgp_error_t **errors,
471 	       pgp_reader_t *readinfo,
472 	       pgp_cbdata_t *cbinfo,
473 	       unsigned skip)
474 {
475 	int             c = first;
476 
477 	while (c == ' ' || c == '\t') {
478 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, skip);
479 	}
480 	return c;
481 }
482 
483 static int
read_and_eat_whitespace(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo,unsigned skip)484 read_and_eat_whitespace(pgp_stream_t *stream, dearmour_t *dearmour,
485 			pgp_error_t **errors,
486 			pgp_reader_t *readinfo,
487 			pgp_cbdata_t *cbinfo,
488 			unsigned skip)
489 {
490 	int             c;
491 
492 	do {
493 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, skip);
494 	} while (c == ' ' || c == '\t');
495 	return c;
496 }
497 
498 static void
flush(dearmour_t * dearmour,pgp_cbdata_t * cbinfo)499 flush(dearmour_t *dearmour, pgp_cbdata_t *cbinfo)
500 {
501 	pgp_packet_t	content;
502 
503 	if (dearmour->unarmoredc > 0) {
504 		content.u.unarmoured_text.data = dearmour->unarmoured;
505 		content.u.unarmoured_text.length = (unsigned)dearmour->unarmoredc;
506 		CALLBACK(PGP_PTAG_CT_UNARMOURED_TEXT, cbinfo, &content);
507 		dearmour->unarmoredc = 0;
508 	}
509 }
510 
511 static int
unarmoured_read_char(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo,unsigned skip)512 unarmoured_read_char(pgp_stream_t *stream, dearmour_t *dearmour,
513 			pgp_error_t **errors,
514 			pgp_reader_t *readinfo,
515 			pgp_cbdata_t *cbinfo,
516 			unsigned skip)
517 {
518 	int             c;
519 
520 	do {
521 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 0);
522 		if (c < 0) {
523 			return c;
524 		}
525 		dearmour->unarmoured[dearmour->unarmoredc++] = c;
526 		if (dearmour->unarmoredc == sizeof(dearmour->unarmoured)) {
527 			flush(dearmour, cbinfo);
528 		}
529 	} while (skip && c == '\r');
530 	return c;
531 }
532 
533 /**
534  * \param headers
535  * \param key
536  *
537  * \return header value if found, otherwise NULL
538  */
539 static const char *
find_header(pgp_headers_t * headers,const char * key)540 find_header(pgp_headers_t *headers, const char *key)
541 {
542 	unsigned        n;
543 
544 	for (n = 0; n < headers->headerc; ++n) {
545 		if (strcmp(headers->headers[n].key, key) == 0) {
546 			return headers->headers[n].value;
547 		}
548 	}
549 	return NULL;
550 }
551 
552 /**
553  * \param dest
554  * \param src
555  */
556 static void
dup_headers(pgp_headers_t * dest,const pgp_headers_t * src)557 dup_headers(pgp_headers_t *dest, const pgp_headers_t *src)
558 {
559 	unsigned        n;
560 
561 	if ((dest->headers = calloc(src->headerc, sizeof(*dest->headers))) == NULL) {
562 		(void) fprintf(stderr, "dup_headers: bad alloc\n");
563 	} else {
564 		dest->headerc = src->headerc;
565 		for (n = 0; n < src->headerc; ++n) {
566 			dest->headers[n].key = netpgp_strdup(src->headers[n].key);
567 			dest->headers[n].value = netpgp_strdup(src->headers[n].value);
568 		}
569 	}
570 }
571 
572 /*
573  * Note that this skips CRs so implementations always see just straight LFs
574  * as line terminators
575  */
576 static int
process_dash_escaped(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)577 process_dash_escaped(pgp_stream_t *stream, dearmour_t *dearmour,
578 			pgp_error_t **errors,
579 			pgp_reader_t *readinfo,
580 			pgp_cbdata_t *cbinfo)
581 {
582 	pgp_fixed_body_t	*body;
583 	pgp_packet_t		 content2;
584 	pgp_packet_t		 content;
585 	const char		*hashstr;
586 	pgp_hash_t		*hash;
587 	int			 total;
588 
589 	body = &content.u.cleartext_body;
590 	if ((hash = calloc(1, sizeof(*hash))) == NULL) {
591 		PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
592 			"process_dash_escaped: bad alloc");
593 		return -1;
594 	}
595 	hashstr = find_header(&dearmour->headers, "Hash");
596 	if (hashstr) {
597 		pgp_hash_alg_t alg;
598 
599 		alg = pgp_str_to_hash_alg(hashstr);
600 		if (!pgp_is_hash_alg_supported(&alg)) {
601 			free(hash);
602 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
603 				"Unsupported hash algorithm '%s'", hashstr);
604 			return -1;
605 		}
606 		if (alg == PGP_HASH_UNKNOWN) {
607 			free(hash);
608 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
609 				"Unknown hash algorithm '%s'", hashstr);
610 			return -1;
611 		}
612 		pgp_hash_any(hash, alg);
613 	} else {
614 		pgp_hash_md5(hash);
615 	}
616 
617 	if (!hash->init(hash)) {
618 		PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
619 			"can't initialise hash");
620 		return -1;
621 	}
622 
623 	body->length = 0;
624 	total = 0;
625 	for (;;) {
626 		int             c;
627 		unsigned        count;
628 
629 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 1);
630 		if (c < 0) {
631 			return -1;
632 		}
633 		if (dearmour->prev_nl && c == '-') {
634 			if ((c = read_char(stream, dearmour, errors, readinfo, cbinfo,
635 						0)) < 0) {
636 				return -1;
637 			}
638 			if (c != ' ') {
639 				/* then this had better be a trailer! */
640 				if (c != '-') {
641 					PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
642 					    "%s", "Bad dash-escaping");
643 				}
644 				for (count = 2; count < 5; ++count) {
645 					if ((c = read_char(stream, dearmour, errors,
646 						readinfo, cbinfo, 0)) < 0) {
647 						return -1;
648 					}
649 					if (c != '-') {
650 						PGP_ERROR_1(errors,
651 						PGP_E_R_BAD_FORMAT, "%s",
652 						"Bad dash-escaping (2)");
653 					}
654 				}
655 				dearmour->state = AT_TRAILER_NAME;
656 				break;
657 			}
658 			/* otherwise we read the next character */
659 			if ((c = read_char(stream, dearmour, errors, readinfo, cbinfo,
660 						0)) < 0) {
661 				return -1;
662 			}
663 		}
664 		if (c == '\n' && body->length) {
665 			if (memchr(body->data + 1, '\n', body->length - 1)
666 						!= NULL) {
667 				(void) fprintf(stderr,
668 				"process_dash_escaped: newline found\n");
669 				return -1;
670 			}
671 			if (body->data[0] == '\n') {
672 				hash->add(hash, (const uint8_t *)"\r", 1);
673 			}
674 			hash->add(hash, body->data, body->length);
675 			if (pgp_get_debug_level(__FILE__)) {
676 				fprintf(stderr, "Got body:\n%s\n", body->data);
677 			}
678 			CALLBACK(PGP_PTAG_CT_SIGNED_CLEARTEXT_BODY, cbinfo,
679 						&content);
680 			body->length = 0;
681 		}
682 		body->data[body->length++] = c;
683 		total += 1;
684 		if (body->length == sizeof(body->data)) {
685 			if (pgp_get_debug_level(__FILE__)) {
686 				(void) fprintf(stderr, "Got body (2):\n%s\n",
687 						body->data);
688 			}
689 			CALLBACK(PGP_PTAG_CT_SIGNED_CLEARTEXT_BODY, cbinfo,
690 					&content);
691 			body->length = 0;
692 		}
693 	}
694 	if (body->data[0] != '\n') {
695 		(void) fprintf(stderr,
696 			"process_dash_escaped: no newline in body data\n");
697 		return -1;
698 	}
699 	if (body->length != 1) {
700 		(void) fprintf(stderr,
701 			"process_dash_escaped: bad body length\n");
702 		return -1;
703 	}
704 	/* don't send that one character, because it's part of the trailer */
705 	(void) memset(&content2, 0x0, sizeof(content2));
706 	CALLBACK(PGP_PTAG_CT_SIGNED_CLEARTEXT_TRAILER, cbinfo, &content2);
707 	return total;
708 }
709 
710 static int
add_header(dearmour_t * dearmour,const char * key,const char * value)711 add_header(dearmour_t *dearmour, const char *key, const char *value)
712 {
713 	int	n;
714 
715 	/*
716          * Check that the header is valid
717          */
718 	if (strcmp(key, "Version") == 0 ||
719 	    strcmp(key, "Comment") == 0 ||
720 	    strcmp(key, "MessageID") == 0 ||
721 	    strcmp(key, "Hash") == 0 ||
722 	    strcmp(key, "Charset") == 0) {
723 		n = dearmour->headers.headerc;
724 		dearmour->headers.headers = realloc(dearmour->headers.headers,
725 				(n + 1) * sizeof(*dearmour->headers.headers));
726 		if (dearmour->headers.headers == NULL) {
727 			(void) fprintf(stderr, "add_header: bad alloc\n");
728 			return 0;
729 		}
730 		dearmour->headers.headers[n].key = netpgp_strdup(key);
731 		dearmour->headers.headers[n].value = netpgp_strdup(value);
732 		dearmour->headers.headerc = n + 1;
733 		return 1;
734 	}
735 	return 0;
736 }
737 
738 /* \todo what does a return value of 0 indicate? 1 is good, -1 is bad */
739 static int
parse_headers(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)740 parse_headers(pgp_stream_t *stream, dearmour_t *dearmour, pgp_error_t **errors,
741 	      pgp_reader_t * readinfo, pgp_cbdata_t * cbinfo)
742 {
743 	unsigned        nbuf;
744 	unsigned        size;
745 	unsigned	first = 1;
746 	char           *buf;
747 	int             ret = 1;
748 
749 	nbuf = 0;
750 	size = 80;
751 	if ((buf = calloc(1, size)) == NULL) {
752 		(void) fprintf(stderr, "parse_headers: bad calloc\n");
753 		return -1;
754 	}
755 	for (;;) {
756 		int             c;
757 
758 		if ((c = read_char(stream, dearmour, errors, readinfo, cbinfo, 1)) < 0) {
759 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
760 			    "%s", "Unexpected EOF");
761 			ret = -1;
762 			break;
763 		}
764 		if (c == '\n') {
765 			char           *s;
766 
767 			if (nbuf == 0) {
768 				break;
769 			}
770 
771 			if (nbuf >= size) {
772 				(void) fprintf(stderr,
773 					"parse_headers: bad size\n");
774 				return -1;
775 			}
776 			buf[nbuf] = '\0';
777 
778 			if ((s = strchr(buf, ':')) == NULL) {
779 				if (!first && !dearmour->allow_headers_without_gap) {
780 					/*
781 					 * then we have seriously malformed
782 					 * armour
783 					 */
784 					PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
785 					    "%s", "No colon in armour header");
786 					ret = -1;
787 					break;
788 				} else {
789 					if (first &&
790 					    !(dearmour->allow_headers_without_gap || dearmour->allow_no_gap)) {
791 						PGP_ERROR_1(errors,
792 						    PGP_E_R_BAD_FORMAT,
793 						    "%s", "No colon in"
794 						    " armour header (2)");
795 						/*
796 						 * then we have a nasty
797 						 * armoured block with no
798 						 * headers, not even a blank
799 						 * line.
800 						 */
801 						buf[nbuf] = '\n';
802 						push_back(dearmour, (uint8_t *) buf, nbuf + 1);
803 						ret = -1;
804 						break;
805 					}
806 				}
807 			} else {
808 				*s = '\0';
809 				if (s[1] != ' ') {
810 					PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
811 					    "%s", "No space in armour header");
812 					ret = -1;
813 					goto end;
814 				}
815 				if (!add_header(dearmour, buf, s + 2)) {
816 					PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "Invalid header %s", buf);
817 					ret = -1;
818 					goto end;
819 				}
820 				nbuf = 0;
821 			}
822 			first = 0;
823 		} else {
824 			if (size <= nbuf + 1) {
825 				size += size + 80;
826 				buf = realloc(buf, size);
827 				if (buf == NULL) {
828 					(void) fprintf(stderr, "bad alloc\n");
829 					ret = -1;
830 					goto end;
831 				}
832 			}
833 			buf[nbuf++] = c;
834 		}
835 	}
836 
837 end:
838 	free(buf);
839 
840 	return ret;
841 }
842 
843 static int
read4(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo,int * pc,unsigned * pn,uint32_t * pl)844 read4(pgp_stream_t *stream, dearmour_t *dearmour, pgp_error_t **errors,
845       pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo,
846       int *pc, unsigned *pn, uint32_t *pl)
847 {
848 	int             n, c;
849 	uint32_t   l = 0;
850 
851 	for (n = 0; n < 4; ++n) {
852 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 1);
853 		if (c < 0) {
854 			dearmour->eof64 = 1;
855 			return -1;
856 		}
857 		if (c == '-' || c == '=') {
858 			break;
859 		}
860 		l <<= 6;
861 		if (c >= 'A' && c <= 'Z') {
862 			l += (uint32_t)(c - 'A');
863 		} else if (c >= 'a' && c <= 'z') {
864 			l += (uint32_t)(c - 'a') + 26;
865 		} else if (c >= '0' && c <= '9') {
866 			l += (uint32_t)(c - '0') + 52;
867 		} else if (c == '+') {
868 			l += 62;
869 		} else if (c == '/') {
870 			l += 63;
871 		} else {
872 			--n;
873 			l >>= 6;
874 		}
875 	}
876 
877 	*pc = c;
878 	*pn = n;
879 	*pl = l;
880 
881 	return 4;
882 }
883 
884 unsigned
pgp_crc24(unsigned checksum,uint8_t c)885 pgp_crc24(unsigned checksum, uint8_t c)
886 {
887 	unsigned        i;
888 
889 	checksum ^= c << 16;
890 	for (i = 0; i < 8; i++) {
891 		checksum <<= 1;
892 		if (checksum & 0x1000000)
893 			checksum ^= CRC24_POLY;
894 	}
895 	return (unsigned)(checksum & 0xffffffL);
896 }
897 
898 static int
decode64(pgp_stream_t * stream,dearmour_t * dearmour,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)899 decode64(pgp_stream_t *stream, dearmour_t *dearmour, pgp_error_t **errors,
900 	 pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
901 {
902 	unsigned        n;
903 	int             n2;
904 	uint32_t	l;
905 	int             c;
906 	int             ret;
907 
908 	if (dearmour->buffered) {
909 		(void) fprintf(stderr, "decode64: bad dearmour->buffered\n");
910 		return 0;
911 	}
912 
913 	ret = read4(stream, dearmour, errors, readinfo, cbinfo, &c, &n, &l);
914 	if (ret < 0) {
915 		PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
916 		    "Badly formed base64");
917 		return 0;
918 	}
919 	if (n == 3) {
920 		if (c != '=') {
921 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
922 			    "%s", "Badly terminated base64 (2)");
923 			return 0;
924 		}
925 		dearmour->buffered = 2;
926 		dearmour->eof64 = 1;
927 		l >>= 2;
928 	} else if (n == 2) {
929 		if (c != '=') {
930 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
931 			    "%s", "Badly terminated base64 (3)");
932 			return 0;
933 		}
934 		dearmour->buffered = 1;
935 		dearmour->eof64 = 1;
936 		l >>= 4;
937 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 0);
938 		if (c != '=') {
939 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
940 			    "%s", "Badly terminated base64");
941 			return 0;
942 		}
943 	} else if (n == 0) {
944 		if (!dearmour->prev_nl || c != '=') {
945 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
946 			    "%s", "Badly terminated base64 (4)");
947 			return 0;
948 		}
949 		dearmour->buffered = 0;
950 	} else {
951 		if (n != 4) {
952 			(void) fprintf(stderr,
953 				"decode64: bad n (!= 4)\n");
954 			return 0;
955 		}
956 		dearmour->buffered = 3;
957 		if (c == '-' || c == '=') {
958 			(void) fprintf(stderr, "decode64: bad c\n");
959 			return 0;
960 		}
961 	}
962 
963 	if (dearmour->buffered < 3 && dearmour->buffered > 0) {
964 		/* then we saw padding */
965 		if (c != '=') {
966 			(void) fprintf(stderr, "decode64: bad c (=)\n");
967 			return 0;
968 		}
969 		c = read_and_eat_whitespace(stream, dearmour, errors, readinfo, cbinfo,
970 				1);
971 		if (c != '\n') {
972 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
973 			    "%s", "No newline at base64 end");
974 			return 0;
975 		}
976 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 0);
977 		if (c != '=') {
978 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
979 			    "%s", "No checksum at base64 end");
980 			return 0;
981 		}
982 	}
983 	if (c == '=') {
984 		/* now we are at the checksum */
985 		ret = read4(stream, dearmour, errors, readinfo, cbinfo, &c, &n,
986 				&dearmour->read_checksum);
987 		if (ret < 0 || n != 4) {
988 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
989 			    "%s", "Error in checksum");
990 			return 0;
991 		}
992 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 1);
993 		if (dearmour->allow_trailing_whitespace)
994 			c = eat_whitespace(stream, c, dearmour, errors, readinfo, cbinfo,
995 					1);
996 		if (c != '\n') {
997 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
998 			    "%s", "Badly terminated checksum");
999 			return 0;
1000 		}
1001 		c = read_char(stream, dearmour, errors, readinfo, cbinfo, 0);
1002 		if (c != '-') {
1003 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
1004 			    "%s", "Bad base64 trailer (2)");
1005 			return 0;
1006 		}
1007 	}
1008 	if (c == '-') {
1009 		for (n = 0; n < 4; ++n)
1010 			if (read_char(stream, dearmour, errors, readinfo, cbinfo,
1011 						0) != '-') {
1012 				PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
1013 				    "Bad base64 trailer");
1014 				return 0;
1015 			}
1016 		dearmour->eof64 = 1;
1017 	} else {
1018 		if (!dearmour->buffered) {
1019 			(void) fprintf(stderr, "decode64: not buffered\n");
1020 			return 0;
1021 		}
1022 	}
1023 
1024 	for (n = 0; n < dearmour->buffered; ++n) {
1025 		dearmour->buffer[n] = (uint8_t)l;
1026 		l >>= 8;
1027 	}
1028 
1029 	for (n2 = dearmour->buffered - 1; n2 >= 0; --n2)
1030 		dearmour->checksum = pgp_crc24((unsigned)dearmour->checksum,
1031 					dearmour->buffer[n2]);
1032 
1033 	if (dearmour->eof64 && dearmour->read_checksum != dearmour->checksum) {
1034 		PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
1035 		    "Checksum mismatch");
1036 		return 0;
1037 	}
1038 	return 1;
1039 }
1040 
1041 static void
base64(dearmour_t * dearmour)1042 base64(dearmour_t *dearmour)
1043 {
1044 	dearmour->state = BASE64;
1045 	dearmour->checksum = CRC24_INIT;
1046 	dearmour->eof64 = 0;
1047 	dearmour->buffered = 0;
1048 }
1049 
1050 /* This reader is rather strange in that it can generate callbacks for */
1051 /* content - this is because plaintext is not encapsulated in PGP */
1052 /* packets... it also calls back for the text between the blocks. */
1053 
1054 static int
armoured_data_reader(pgp_stream_t * stream,void * dest_,size_t length,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)1055 armoured_data_reader(pgp_stream_t *stream, void *dest_, size_t length, pgp_error_t **errors,
1056 		     pgp_reader_t *readinfo,
1057 		     pgp_cbdata_t *cbinfo)
1058 {
1059 	pgp_packet_t	 content;
1060 	dearmour_t	*dearmour;
1061 	unsigned	 first;
1062 	uint8_t		*dest = dest_;
1063 	char		 buf[1024];
1064 	int		 saved;
1065 	int              ret;
1066 
1067 	dearmour = pgp_reader_get_arg(readinfo);
1068 	saved = (int)length;
1069 	if (dearmour->eof64 && !dearmour->buffered) {
1070 		if (dearmour->state != OUTSIDE_BLOCK &&
1071 		    dearmour->state != AT_TRAILER_NAME) {
1072 			(void) fprintf(stderr,
1073 				"armoured_data_reader: bad dearmour state\n");
1074 			return 0;
1075 		}
1076 	}
1077 
1078 	while (length > 0) {
1079 		unsigned        count;
1080 		unsigned        n;
1081 		int             c;
1082 
1083 		flush(dearmour, cbinfo);
1084 		switch (dearmour->state) {
1085 		case OUTSIDE_BLOCK:
1086 			/*
1087 			 * This code returns EOF rather than EARLY_EOF
1088 			 * because if we don't see a header line at all, then
1089 			 * it is just an EOF (and not a BLOCK_END)
1090 			 */
1091 			while (!dearmour->seen_nl) {
1092 				if ((c = unarmoured_read_char(stream, dearmour, errors,
1093 						readinfo, cbinfo, 1)) < 0) {
1094 					return 0;
1095 				}
1096 			}
1097 
1098 			/*
1099 			 * flush at this point so we definitely have room for
1100 			 * the header, and so we can easily erase it from the
1101 			 * buffer
1102 			 */
1103 			flush(dearmour, cbinfo);
1104 			/* Find and consume the 5 leading '-' */
1105 			for (count = 0; count < 5; ++count) {
1106 				if ((c = unarmoured_read_char(stream, dearmour, errors,
1107 						readinfo, cbinfo, 0)) < 0) {
1108 					return 0;
1109 				}
1110 				if (c != '-') {
1111 					goto reloop;
1112 				}
1113 			}
1114 
1115 			/* Now find the block type */
1116 			for (n = 0; n < sizeof(buf) - 1;) {
1117 				if ((c = unarmoured_read_char(stream, dearmour, errors,
1118 						readinfo, cbinfo, 0)) < 0) {
1119 					return 0;
1120 				}
1121 				if (c == '-') {
1122 					goto got_minus;
1123 				}
1124 				buf[n++] = c;
1125 			}
1126 			/* then I guess this wasn't a proper header */
1127 			break;
1128 
1129 got_minus:
1130 			buf[n] = '\0';
1131 
1132 			/* Consume trailing '-' */
1133 			for (count = 1; count < 5; ++count) {
1134 				if ((c = unarmoured_read_char(stream, dearmour, errors,
1135 						readinfo, cbinfo, 0)) < 0) {
1136 					return 0;
1137 				}
1138 				if (c != '-') {
1139 					/* wasn't a header after all */
1140 					goto reloop;
1141 				}
1142 			}
1143 
1144 			/* Consume final NL */
1145 			if ((c = unarmoured_read_char(stream, dearmour, errors, readinfo,
1146 						cbinfo, 1)) < 0) {
1147 				return 0;
1148 			}
1149 			if (dearmour->allow_trailing_whitespace) {
1150 				if ((c = eat_whitespace(stream, c, dearmour, errors,
1151 						readinfo, cbinfo, 1)) < 0) {
1152 					return 0;
1153 				}
1154 			}
1155 			if (c != '\n') {
1156 				/* wasn't a header line after all */
1157 				break;
1158 			}
1159 
1160 			/*
1161 			 * Now we've seen the header, scrub it from the
1162 			 * buffer
1163 			 */
1164 			dearmour->unarmoredc = 0;
1165 
1166 			/*
1167 			 * But now we've seen a header line, then errors are
1168 			 * EARLY_EOF
1169 			 */
1170 			if ((ret = parse_headers(stream, dearmour, errors, readinfo,
1171 					cbinfo)) <= 0) {
1172 				return -1;
1173 			}
1174 
1175 			if (!set_lastseen_headerline(dearmour, buf, errors)) {
1176 				return -1;
1177 			}
1178 
1179 			if (strcmp(buf, "BEGIN PGP SIGNED MESSAGE") == 0) {
1180 				dup_headers(&content.u.cleartext_head,
1181 					&dearmour->headers);
1182 				CALLBACK(PGP_PTAG_CT_SIGNED_CLEARTEXT_HEADER,
1183 					cbinfo,
1184 					&content);
1185 				ret = process_dash_escaped(stream, dearmour, errors,
1186 						readinfo, cbinfo);
1187 				if (ret <= 0) {
1188 					return ret;
1189 				}
1190 			} else {
1191 				content.u.armour_header.type = buf;
1192 				content.u.armour_header.headers =
1193 						dearmour->headers;
1194 				(void) memset(&dearmour->headers, 0x0,
1195 						sizeof(dearmour->headers));
1196 				CALLBACK(PGP_PTAG_CT_ARMOUR_HEADER, cbinfo,
1197 						&content);
1198 				base64(dearmour);
1199 			}
1200 			break;
1201 
1202 		case BASE64:
1203 			first = 1;
1204 			while (length > 0) {
1205 				if (!dearmour->buffered) {
1206 					if (!dearmour->eof64) {
1207 						ret = decode64(stream, dearmour,
1208 							errors, readinfo, cbinfo);
1209 						if (ret <= 0) {
1210 							return ret;
1211 						}
1212 					}
1213 					if (!dearmour->buffered) {
1214 						if (!dearmour->eof64) {
1215 							(void) fprintf(stderr,
1216 "armoured_data_reader: bad dearmour eof64\n");
1217 							return 0;
1218 						}
1219 						if (first) {
1220 							dearmour->state =
1221 								AT_TRAILER_NAME;
1222 							goto reloop;
1223 						}
1224 						return -1;
1225 					}
1226 				}
1227 				if (!dearmour->buffered) {
1228 					(void) fprintf(stderr,
1229 			"armoured_data_reader: bad dearmour buffered\n");
1230 					return 0;
1231 				}
1232 				*dest = dearmour->buffer[--dearmour->buffered];
1233 				++dest;
1234 				--length;
1235 				first = 0;
1236 			}
1237 			if (dearmour->eof64 && !dearmour->buffered) {
1238 				dearmour->state = AT_TRAILER_NAME;
1239 			}
1240 			break;
1241 
1242 		case AT_TRAILER_NAME:
1243 			for (n = 0; n < sizeof(buf) - 1;) {
1244 				if ((c = read_char(stream, dearmour, errors, readinfo,
1245 						cbinfo, 0)) < 0) {
1246 					return -1;
1247 				}
1248 				if (c == '-') {
1249 					goto got_minus2;
1250 				}
1251 				buf[n++] = c;
1252 			}
1253 			/* then I guess this wasn't a proper trailer */
1254 			PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT, "%s",
1255 			    "Bad ASCII armour trailer");
1256 			break;
1257 
1258 got_minus2:
1259 			buf[n] = '\0';
1260 
1261 			if (!set_lastseen_headerline(dearmour, buf, errors)) {
1262 				return -1;
1263 			}
1264 
1265 			/* Consume trailing '-' */
1266 			for (count = 1; count < 5; ++count) {
1267 				if ((c = read_char(stream, dearmour, errors, readinfo,
1268 						cbinfo, 0)) < 0) {
1269 					return -1;
1270 				}
1271 				if (c != '-') {
1272 					/* wasn't a trailer after all */
1273 					PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
1274 					    "%s",
1275 					    "Bad ASCII armour trailer (2)");
1276 				}
1277 			}
1278 
1279 			/* Consume final NL */
1280 			if ((c = read_char(stream, dearmour, errors, readinfo, cbinfo,
1281 						1)) < 0) {
1282 				return -1;
1283 			}
1284 			if (dearmour->allow_trailing_whitespace) {
1285 				if ((c = eat_whitespace(stream, c, dearmour, errors,
1286 						readinfo, cbinfo, 1)) < 0) {
1287 					return 0;
1288 				}
1289 			}
1290 			if (c != '\n') {
1291 				/* wasn't a trailer line after all */
1292 				PGP_ERROR_1(errors, PGP_E_R_BAD_FORMAT,
1293 				    "%s", "Bad ASCII armour trailer (3)");
1294 			}
1295 
1296 			if (strncmp(buf, "BEGIN ", 6) == 0) {
1297 				if (!set_lastseen_headerline(dearmour, buf,
1298 						errors)) {
1299 					return -1;
1300 				}
1301 				if ((ret = parse_headers(stream, dearmour, errors,
1302 						readinfo, cbinfo)) <= 0) {
1303 					return ret;
1304 				}
1305 				content.u.armour_header.type = buf;
1306 				content.u.armour_header.headers =
1307 						dearmour->headers;
1308 				(void) memset(&dearmour->headers, 0x0,
1309 						sizeof(dearmour->headers));
1310 				CALLBACK(PGP_PTAG_CT_ARMOUR_HEADER, cbinfo,
1311 						&content);
1312 				base64(dearmour);
1313 			} else {
1314 				content.u.armour_trailer = buf;
1315 				CALLBACK(PGP_PTAG_CT_ARMOUR_TRAILER, cbinfo,
1316 						&content);
1317 				dearmour->state = OUTSIDE_BLOCK;
1318 			}
1319 			break;
1320 		}
1321 reloop:
1322 		continue;
1323 	}
1324 
1325 	return saved;
1326 }
1327 
1328 static void
armoured_data_destroyer(pgp_reader_t * readinfo)1329 armoured_data_destroyer(pgp_reader_t *readinfo)
1330 {
1331 	free(pgp_reader_get_arg(readinfo));
1332 }
1333 
1334 /**
1335  * \ingroup Core_Readers_Armour
1336  * \brief Pushes dearmouring reader onto stack
1337  * \param parse_info Usual structure containing information about to how to do the parse
1338  * \sa pgp_reader_pop_dearmour()
1339  */
1340 void
pgp_reader_push_dearmour(pgp_stream_t * parse_info)1341 pgp_reader_push_dearmour(pgp_stream_t *parse_info)
1342 /*
1343  * This function originally had these params to cater for packets which
1344  * didn't strictly match the RFC. The initial 0.5 release is only going to
1345  * support strict checking. If it becomes desirable to support loose checking
1346  * of armoured packets and these params are reinstated, parse_headers() must
1347  * be fixed so that these flags work correctly.
1348  *
1349  * // Allow headers in armoured data that are not separated from the data by a
1350  * blank line unsigned without_gap,
1351  *
1352  * // Allow no blank line at the start of armoured data unsigned no_gap,
1353  *
1354  * //Allow armoured data to have trailing whitespace where we strictly would not
1355  * expect it			      unsigned trailing_whitespace
1356  */
1357 {
1358 	dearmour_t *dearmour;
1359 
1360 	if ((dearmour = calloc(1, sizeof(*dearmour))) == NULL) {
1361 		(void) fprintf(stderr, "pgp_reader_push_dearmour: bad alloc\n");
1362 	} else {
1363 		dearmour->seen_nl = 1;
1364 		/*
1365 		    dearmour->allow_headers_without_gap=without_gap;
1366 		    dearmour->allow_no_gap=no_gap;
1367 		    dearmour->allow_trailing_whitespace=trailing_whitespace;
1368 		*/
1369 		dearmour->expect_sig = 0;
1370 		dearmour->got_sig = 0;
1371 
1372 		pgp_reader_push(parse_info, armoured_data_reader,
1373 			armoured_data_destroyer, dearmour);
1374 	}
1375 }
1376 
1377 /**
1378  * \ingroup Core_Readers_Armour
1379  * \brief Pops dearmour reader from stock
1380  * \param stream
1381  * \sa pgp_reader_push_dearmour()
1382  */
1383 void
pgp_reader_pop_dearmour(pgp_stream_t * stream)1384 pgp_reader_pop_dearmour(pgp_stream_t *stream)
1385 {
1386 	dearmour_t *dearmour;
1387 
1388 	dearmour = pgp_reader_get_arg(pgp_readinfo(stream));
1389 	free(dearmour);
1390 	pgp_reader_pop(stream);
1391 }
1392 
1393 /**************************************************************************/
1394 
1395 /* this is actually used for *decrypting* */
1396 typedef struct {
1397 	uint8_t		 decrypted[1024 * 15];
1398 	size_t		 c;
1399 	size_t		 off;
1400 	pgp_crypt_t	*decrypt;
1401 	pgp_region_t	*region;
1402 	unsigned	 prevplain:1;
1403 } encrypted_t;
1404 
1405 static int
encrypted_data_reader(pgp_stream_t * stream,void * dest,size_t length,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)1406 encrypted_data_reader(pgp_stream_t *stream, void *dest,
1407 			size_t length,
1408 			pgp_error_t **errors,
1409 			pgp_reader_t *readinfo,
1410 			pgp_cbdata_t *cbinfo)
1411 {
1412 	encrypted_t	*encrypted;
1413 	char		*cdest;
1414 	int		 saved;
1415 
1416 	encrypted = pgp_reader_get_arg(readinfo);
1417 	saved = (int)length;
1418 	/*
1419 	 * V3 MPIs have the count plain and the cipher is reset after each
1420 	 * count
1421 	 */
1422 	if (encrypted->prevplain && !readinfo->parent->reading_mpi_len) {
1423 		if (!readinfo->parent->reading_v3_secret) {
1424 			(void) fprintf(stderr,
1425 				"encrypted_data_reader: bad v3 secret\n");
1426 			return -1;
1427 		}
1428 		encrypted->decrypt->decrypt_resync(encrypted->decrypt);
1429 		encrypted->prevplain = 0;
1430 	} else if (readinfo->parent->reading_v3_secret &&
1431 		   readinfo->parent->reading_mpi_len) {
1432 		encrypted->prevplain = 1;
1433 	}
1434 	while (length > 0) {
1435 		if (encrypted->c) {
1436 			unsigned        n;
1437 
1438 			/*
1439 			 * if we are reading v3 we should never read
1440 			 * more than we're asked for */
1441 			if (length < encrypted->c &&
1442 			     (readinfo->parent->reading_v3_secret ||
1443 			      readinfo->parent->exact_read)) {
1444 				(void) fprintf(stderr,
1445 					"encrypted_data_reader: bad v3 read\n");
1446 				return 0;
1447 			}
1448 			n = (int)MIN(length, encrypted->c);
1449 			(void) memcpy(dest,
1450 				encrypted->decrypted + encrypted->off, n);
1451 			encrypted->c -= n;
1452 			encrypted->off += n;
1453 			length -= n;
1454 			cdest = dest;
1455 			cdest += n;
1456 			dest = cdest;
1457 		} else {
1458 			unsigned	n = encrypted->region->length;
1459 			uint8_t		buffer[1024];
1460 
1461 			if (!n) {
1462 				return -1;
1463 			}
1464 			if (!encrypted->region->indeterminate) {
1465 				n -= encrypted->region->readc;
1466 				if (n == 0) {
1467 					return (int)(saved - length);
1468 				}
1469 				if (n > sizeof(buffer)) {
1470 					n = sizeof(buffer);
1471 				}
1472 			} else {
1473 				n = sizeof(buffer);
1474 			}
1475 
1476 			/*
1477 			 * we can only read as much as we're asked for
1478 			 * in v3 keys because they're partially
1479 			 * unencrypted!  */
1480 			if ((readinfo->parent->reading_v3_secret ||
1481 			     readinfo->parent->exact_read) && n > length) {
1482 				n = (unsigned)length;
1483 			}
1484 
1485 			if (!pgp_stacked_limited_read(stream, buffer, n,
1486 				encrypted->region, errors, readinfo, cbinfo)) {
1487 				return -1;
1488 			}
1489 			if (!readinfo->parent->reading_v3_secret ||
1490 			    !readinfo->parent->reading_mpi_len) {
1491 				encrypted->c =
1492 					pgp_decrypt_se_ip(encrypted->decrypt,
1493 					encrypted->decrypted, buffer, n);
1494 
1495 				if (pgp_get_debug_level(__FILE__)) {
1496 					hexdump(stderr, "encrypted", buffer, 16);
1497 					hexdump(stderr, "decrypted", encrypted->decrypted, 16);
1498 				}
1499 			} else {
1500 				(void) memcpy(
1501 	&encrypted->decrypted[encrypted->off], buffer, n);
1502 				encrypted->c = n;
1503 			}
1504 
1505 			if (encrypted->c == 0) {
1506 				(void) fprintf(stderr,
1507 				"encrypted_data_reader: 0 decrypted count\n");
1508 				return 0;
1509 			}
1510 
1511 			encrypted->off = 0;
1512 		}
1513 	}
1514 
1515 	return saved;
1516 }
1517 
1518 static void
encrypted_data_destroyer(pgp_reader_t * readinfo)1519 encrypted_data_destroyer(pgp_reader_t *readinfo)
1520 {
1521 	free(pgp_reader_get_arg(readinfo));
1522 }
1523 
1524 /**
1525  * \ingroup Core_Readers_SE
1526  * \brief Pushes decryption reader onto stack
1527  * \sa pgp_reader_pop_decrypt()
1528  */
1529 void
pgp_reader_push_decrypt(pgp_stream_t * stream,pgp_crypt_t * decrypt,pgp_region_t * region)1530 pgp_reader_push_decrypt(pgp_stream_t *stream, pgp_crypt_t *decrypt,
1531 			pgp_region_t *region)
1532 {
1533 	encrypted_t	*encrypted;
1534 
1535 	if ((encrypted = calloc(1, sizeof(*encrypted))) == NULL) {
1536 		(void) fprintf(stderr, "pgp_reader_push_decrypted: bad alloc\n");
1537 	} else {
1538 		encrypted->decrypt = decrypt;
1539 		encrypted->region = region;
1540 		pgp_decrypt_init(encrypted->decrypt);
1541 		pgp_reader_push(stream, encrypted_data_reader,
1542 			encrypted_data_destroyer, encrypted);
1543 	}
1544 }
1545 
1546 /**
1547  * \ingroup Core_Readers_Encrypted
1548  * \brief Pops decryption reader from stack
1549  * \sa pgp_reader_push_decrypt()
1550  */
1551 void
pgp_reader_pop_decrypt(pgp_stream_t * stream)1552 pgp_reader_pop_decrypt(pgp_stream_t *stream)
1553 {
1554 	encrypted_t	*encrypted;
1555 
1556 	encrypted = pgp_reader_get_arg(pgp_readinfo(stream));
1557 	encrypted->decrypt->decrypt_finish(encrypted->decrypt);
1558 	free(encrypted);
1559 	pgp_reader_pop(stream);
1560 }
1561 
1562 /**************************************************************************/
1563 
1564 typedef struct {
1565 	/* boolean: 0 once we've done the preamble/MDC checks */
1566 	/* and are reading from the plaintext */
1567 	int              passed_checks;
1568 	uint8_t		*plaintext;
1569 	size_t           plaintext_available;
1570 	size_t           plaintext_offset;
1571 	pgp_region_t	*region;
1572 	pgp_crypt_t	*decrypt;
1573 } decrypt_se_ip_t;
1574 
1575 /*
1576   Gets entire SE_IP data packet.
1577   Verifies leading preamble
1578   Verifies trailing MDC packet
1579   Then passes up plaintext as requested
1580 */
1581 static int
se_ip_data_reader(pgp_stream_t * stream,void * dest_,size_t len,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)1582 se_ip_data_reader(pgp_stream_t *stream, void *dest_,
1583 			size_t len,
1584 			pgp_error_t **errors,
1585 			pgp_reader_t *readinfo,
1586 			pgp_cbdata_t *cbinfo)
1587 {
1588 	decrypt_se_ip_t	*se_ip;
1589 	pgp_region_t	 decrypted_region;
1590 	unsigned	 n = 0;
1591 
1592 	se_ip = pgp_reader_get_arg(readinfo);
1593 	if (!se_ip->passed_checks) {
1594 		uint8_t		*buf = NULL;
1595 		uint8_t		hashed[PGP_SHA1_HASH_SIZE];
1596 		uint8_t		*preamble;
1597 		uint8_t		*plaintext;
1598 		uint8_t		*mdc;
1599 		uint8_t		*mdc_hash;
1600 		pgp_hash_t	hash;
1601 		size_t		b;
1602 		size_t          sz_preamble;
1603 		size_t          sz_mdc_hash;
1604 		size_t          sz_mdc;
1605 		size_t          sz_plaintext;
1606 
1607 		pgp_hash_any(&hash, PGP_HASH_SHA1);
1608 		if (!hash.init(&hash)) {
1609 			(void) fprintf(stderr,
1610 				"se_ip_data_reader: can't init hash\n");
1611 			return -1;
1612 		}
1613 
1614 		pgp_init_subregion(&decrypted_region, NULL);
1615 		decrypted_region.length =
1616 			se_ip->region->length - se_ip->region->readc;
1617 		if ((buf = calloc(1, decrypted_region.length)) == NULL) {
1618 			(void) fprintf(stderr, "se_ip_data_reader: bad alloc\n");
1619 			return -1;
1620 		}
1621 
1622 		/* read entire SE IP packet */
1623 		if (!pgp_stacked_limited_read(stream, buf, decrypted_region.length,
1624 				&decrypted_region, errors, readinfo, cbinfo)) {
1625 			free(buf);
1626 			return -1;
1627 		}
1628 		if (pgp_get_debug_level(__FILE__)) {
1629 			hexdump(stderr, "SE IP packet", buf, decrypted_region.length);
1630 		}
1631 		/* verify leading preamble */
1632 		if (pgp_get_debug_level(__FILE__)) {
1633 			hexdump(stderr, "preamble", buf, se_ip->decrypt->blocksize);
1634 		}
1635 		b = se_ip->decrypt->blocksize;
1636 		if (buf[b - 2] != buf[b] || buf[b - 1] != buf[b + 1]) {
1637 			fprintf(stderr,
1638 			"Bad symmetric decrypt (%02x%02x vs %02x%02x)\n",
1639 				buf[b - 2], buf[b - 1], buf[b], buf[b + 1]);
1640 			PGP_ERROR_1(errors, PGP_E_PROTO_BAD_SYMMETRIC_DECRYPT,
1641 			    "%s", "Bad symmetric decrypt when parsing SE IP"
1642 			    " packet");
1643 			free(buf);
1644 			return -1;
1645 		}
1646 		/* Verify trailing MDC hash */
1647 
1648 		sz_preamble = se_ip->decrypt->blocksize + 2;
1649 		sz_mdc_hash = PGP_SHA1_HASH_SIZE;
1650 		sz_mdc = 1 + 1 + sz_mdc_hash;
1651 		sz_plaintext = (decrypted_region.length - sz_preamble) - sz_mdc;
1652 
1653 		preamble = buf;
1654 		plaintext = buf + sz_preamble;
1655 		mdc = plaintext + sz_plaintext;
1656 		mdc_hash = mdc + 2;
1657 
1658 		if (pgp_get_debug_level(__FILE__)) {
1659 			hexdump(stderr, "plaintext", plaintext, sz_plaintext);
1660 			hexdump(stderr, "mdc", mdc, sz_mdc);
1661 		}
1662 		pgp_calc_mdc_hash(preamble, sz_preamble, plaintext,
1663 				(unsigned)sz_plaintext, hashed);
1664 
1665 		if (memcmp(mdc_hash, hashed, PGP_SHA1_HASH_SIZE) != 0) {
1666 			PGP_ERROR_1(errors, PGP_E_V_BAD_HASH, "%s",
1667 			    "Bad hash in MDC packet");
1668 			free(buf);
1669 			return 0;
1670 		}
1671 		/* all done with the checks */
1672 		/* now can start reading from the plaintext */
1673 		if (se_ip->plaintext) {
1674 			(void) fprintf(stderr,
1675 				"se_ip_data_reader: bad plaintext\n");
1676 			return 0;
1677 		}
1678 		if ((se_ip->plaintext = calloc(1, sz_plaintext)) == NULL) {
1679 			(void) fprintf(stderr,
1680 				"se_ip_data_reader: bad alloc\n");
1681 			return 0;
1682 		}
1683 		memcpy(se_ip->plaintext, plaintext, sz_plaintext);
1684 		se_ip->plaintext_available = sz_plaintext;
1685 
1686 		se_ip->passed_checks = 1;
1687 
1688 		free(buf);
1689 	}
1690 	n = (unsigned)len;
1691 	if (n > se_ip->plaintext_available) {
1692 		n = (unsigned)se_ip->plaintext_available;
1693 	}
1694 
1695 	memcpy(dest_, se_ip->plaintext + se_ip->plaintext_offset, n);
1696 	se_ip->plaintext_available -= n;
1697 	se_ip->plaintext_offset += n;
1698 	/* len -= n; - not used at all, for info only */
1699 
1700 	return n;
1701 }
1702 
1703 static void
se_ip_data_destroyer(pgp_reader_t * readinfo)1704 se_ip_data_destroyer(pgp_reader_t *readinfo)
1705 {
1706 	decrypt_se_ip_t	*se_ip;
1707 
1708 	se_ip = pgp_reader_get_arg(readinfo);
1709 	free(se_ip->plaintext);
1710 	free(se_ip);
1711 }
1712 
1713 /**
1714    \ingroup Internal_Readers_SEIP
1715 */
1716 void
pgp_reader_push_se_ip_data(pgp_stream_t * stream,pgp_crypt_t * decrypt,pgp_region_t * region)1717 pgp_reader_push_se_ip_data(pgp_stream_t *stream, pgp_crypt_t *decrypt,
1718 			   pgp_region_t * region)
1719 {
1720 	decrypt_se_ip_t *se_ip;
1721 
1722 	if ((se_ip = calloc(1, sizeof(*se_ip))) == NULL) {
1723 		(void) fprintf(stderr, "pgp_reader_push_se_ip_data: bad alloc\n");
1724 	} else {
1725 		se_ip->region = region;
1726 		se_ip->decrypt = decrypt;
1727 		pgp_reader_push(stream, se_ip_data_reader, se_ip_data_destroyer,
1728 				se_ip);
1729 	}
1730 }
1731 
1732 /**
1733    \ingroup Internal_Readers_SEIP
1734  */
1735 void
pgp_reader_pop_se_ip_data(pgp_stream_t * stream)1736 pgp_reader_pop_se_ip_data(pgp_stream_t *stream)
1737 {
1738 	/*
1739 	 * decrypt_se_ip_t
1740 	 * *se_ip=pgp_reader_get_arg(pgp_readinfo(stream));
1741 	 */
1742 	/* free(se_ip); */
1743 	pgp_reader_pop(stream);
1744 }
1745 
1746 /**************************************************************************/
1747 
1748 /** Arguments for reader_fd
1749  */
1750 typedef struct mmap_reader_t {
1751 	void		*mem;		/* memory mapped file */
1752 	uint64_t	 size;		/* size of file */
1753 	uint64_t	 offset;	/* current offset in file */
1754 	int		 fd;		/* file descriptor */
1755 } mmap_reader_t;
1756 
1757 
1758 /**
1759  * \ingroup Core_Readers
1760  *
1761  * pgp_reader_fd() attempts to read up to "plength" bytes from the file
1762  * descriptor in "parse_info" into the buffer starting at "dest" using the
1763  * rules contained in "flags"
1764  *
1765  * \param	dest	Pointer to previously allocated buffer
1766  * \param	plength Number of bytes to try to read
1767  * \param	flags	Rules about reading to use
1768  * \param	readinfo	Reader info
1769  * \param	cbinfo	Callback info
1770  *
1771  * \return	n	Number of bytes read
1772  *
1773  * PGP_R_EARLY_EOF and PGP_R_ERROR push errors on the stack
1774  */
1775 static int
fd_reader(pgp_stream_t * stream,void * dest,size_t length,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)1776 fd_reader(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
1777 	  pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
1778 {
1779 	mmap_reader_t	*reader;
1780 	int		 n;
1781 
1782 	__PGP_USED(cbinfo);
1783 	reader = pgp_reader_get_arg(readinfo);
1784 	if (!stream->coalescing && stream->virtualc && stream->virtualoff < stream->virtualc) {
1785 		n = read_partial_data(stream, dest, length);
1786 	} else {
1787 		n = (int)read(reader->fd, dest, length);
1788 	}
1789 	if (n == 0) {
1790 		return 0;
1791 	}
1792 	if (n < 0) {
1793 		PGP_SYSTEM_ERROR_1(errors, PGP_E_R_READ_FAILED, "read",
1794 				   "file descriptor %d", reader->fd);
1795 		return -1;
1796 	}
1797 	return n;
1798 }
1799 
1800 static void
reader_fd_destroyer(pgp_reader_t * readinfo)1801 reader_fd_destroyer(pgp_reader_t *readinfo)
1802 {
1803 	free(pgp_reader_get_arg(readinfo));
1804 }
1805 
1806 /**
1807    \ingroup Core_Readers_First
1808    \brief Starts stack with file reader
1809 */
1810 
1811 void
pgp_reader_set_fd(pgp_stream_t * stream,int fd)1812 pgp_reader_set_fd(pgp_stream_t *stream, int fd)
1813 {
1814 	mmap_reader_t *reader;
1815 
1816 	if ((reader = calloc(1, sizeof(*reader))) == NULL) {
1817 		(void) fprintf(stderr, "pgp_reader_set_fd: bad alloc\n");
1818 	} else {
1819 		reader->fd = fd;
1820 		pgp_reader_set(stream, fd_reader, reader_fd_destroyer, reader);
1821 	}
1822 }
1823 
1824 /**************************************************************************/
1825 
1826 typedef struct {
1827 	const uint8_t *buffer;
1828 	size_t          length;
1829 	size_t          offset;
1830 } reader_mem_t;
1831 
1832 static int
mem_reader(pgp_stream_t * stream,void * dest,size_t length,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)1833 mem_reader(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
1834 	   pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
1835 {
1836 	reader_mem_t *reader = pgp_reader_get_arg(readinfo);
1837 	unsigned        n;
1838 
1839 	__PGP_USED(cbinfo);
1840 	__PGP_USED(errors);
1841 	if (!stream->coalescing && stream->virtualc && stream->virtualoff < stream->virtualc) {
1842 		n = read_partial_data(stream, dest, length);
1843 	} else {
1844 		if (reader->offset + length > reader->length) {
1845 			n = (unsigned)(reader->length - reader->offset);
1846 		} else {
1847 			n = (unsigned)length;
1848 		}
1849 		if (n == (unsigned)0) {
1850 			return 0;
1851 		}
1852 		memcpy(dest, reader->buffer + reader->offset, n);
1853 		reader->offset += n;
1854 	}
1855 	return n;
1856 }
1857 
1858 static void
mem_destroyer(pgp_reader_t * readinfo)1859 mem_destroyer(pgp_reader_t *readinfo)
1860 {
1861 	free(pgp_reader_get_arg(readinfo));
1862 }
1863 
1864 /**
1865    \ingroup Core_Readers_First
1866    \brief Starts stack with memory reader
1867 */
1868 
1869 void
pgp_reader_set_memory(pgp_stream_t * stream,const void * buffer,size_t length)1870 pgp_reader_set_memory(pgp_stream_t *stream, const void *buffer,
1871 		      size_t length)
1872 {
1873 	reader_mem_t *mem;
1874 
1875 	if ((mem = calloc(1, sizeof(*mem))) == NULL) {
1876 		(void) fprintf(stderr, "pgp_reader_set_memory: bad alloc\n");
1877 	} else {
1878 		mem->buffer = buffer;
1879 		mem->length = length;
1880 		mem->offset = 0;
1881 		pgp_reader_set(stream, mem_reader, mem_destroyer, mem);
1882 	}
1883 }
1884 
1885 /**************************************************************************/
1886 
1887 /**
1888  \ingroup Core_Writers
1889  \brief Create and initialise output and mem; Set for writing to mem
1890  \param output Address where new output pointer will be set
1891  \param mem Address when new mem pointer will be set
1892  \param bufsz Initial buffer size (will automatically be increased when necessary)
1893  \note It is the caller's responsiblity to free output and mem.
1894  \sa pgp_teardown_memory_write()
1895 */
1896 void
pgp_setup_memory_write(pgp_output_t ** output,pgp_memory_t ** mem,size_t bufsz)1897 pgp_setup_memory_write(pgp_output_t **output, pgp_memory_t **mem, size_t bufsz)
1898 {
1899 	/*
1900          * initialise needed structures for writing to memory
1901          */
1902 
1903 	*output = pgp_output_new();
1904 	*mem = pgp_memory_new();
1905 
1906 	pgp_memory_init(*mem, bufsz);
1907 
1908 	pgp_writer_set_memory(*output, *mem);
1909 }
1910 
1911 /**
1912    \ingroup Core_Writers
1913    \brief Closes writer and frees output and mem
1914    \param output
1915    \param mem
1916    \sa pgp_setup_memory_write()
1917 */
1918 void
pgp_teardown_memory_write(pgp_output_t * output,pgp_memory_t * mem)1919 pgp_teardown_memory_write(pgp_output_t *output, pgp_memory_t *mem)
1920 {
1921 	pgp_writer_close(output);/* new */
1922 	pgp_output_delete(output);
1923 	pgp_memory_free(mem);
1924 }
1925 
1926 /**
1927    \ingroup Core_Readers
1928    \brief Create parse_info and sets to read from memory
1929    \param stream Address where new parse_info will be set
1930    \param mem Memory to read from
1931    \param arg Reader-specific arg
1932    \param callback Callback to use with reader
1933    \param accumulate Set if we need to accumulate as we read. (Usually 0 unless doing signature verification)
1934    \note It is the caller's responsiblity to free parse_info
1935    \sa pgp_teardown_memory_read()
1936 */
1937 void
pgp_setup_memory_read(pgp_io_t * io,pgp_stream_t ** stream,pgp_memory_t * mem,void * vp,pgp_cb_ret_t callback (const pgp_packet_t *,pgp_cbdata_t *),unsigned accumulate)1938 pgp_setup_memory_read(pgp_io_t *io,
1939 			pgp_stream_t **stream,
1940 			pgp_memory_t *mem,
1941 			void *vp,
1942 			pgp_cb_ret_t callback(const pgp_packet_t *,
1943 						pgp_cbdata_t *),
1944 			unsigned accumulate)
1945 {
1946 	*stream = pgp_new(sizeof(**stream));
1947 	(*stream)->io = (*stream)->cbinfo.io = io;
1948 	pgp_set_callback(*stream, callback, vp);
1949 	pgp_reader_set_memory(*stream,
1950 			      pgp_mem_data(mem),
1951 			      pgp_mem_len(mem));
1952 	if (accumulate) {
1953 		(*stream)->readinfo.accumulate = 1;
1954 	}
1955 }
1956 
1957 /**
1958    \ingroup Core_Readers
1959    \brief Frees stream and mem
1960    \param stream
1961    \param mem
1962    \sa pgp_setup_memory_read()
1963 */
1964 void
pgp_teardown_memory_read(pgp_stream_t * stream,pgp_memory_t * mem)1965 pgp_teardown_memory_read(pgp_stream_t *stream, pgp_memory_t *mem)
1966 {
1967 	pgp_stream_delete(stream);
1968 	pgp_memory_free(mem);
1969 }
1970 
1971 /**
1972  \ingroup Core_Writers
1973  \brief Create and initialise output and mem; Set for writing to file
1974  \param output Address where new output pointer will be set
1975  \param filename File to write to
1976  \param allow_overwrite Allows file to be overwritten, if set.
1977  \return Newly-opened file descriptor
1978  \note It is the caller's responsiblity to free output and to close fd.
1979  \sa pgp_teardown_file_write()
1980 */
1981 int
pgp_setup_file_write(pgp_output_t ** output,const char * filename,unsigned allow_overwrite)1982 pgp_setup_file_write(pgp_output_t **output, const char *filename,
1983 			unsigned allow_overwrite)
1984 {
1985 	int             fd = 0;
1986 	int             flags = 0;
1987 
1988 	/*
1989          * initialise needed structures for writing to file
1990          */
1991 	if (filename == NULL) {
1992 		/* write to stdout */
1993 		fd = STDOUT_FILENO;
1994 	} else {
1995 		flags = O_WRONLY | O_CREAT;
1996 		if (allow_overwrite)
1997 			flags |= O_TRUNC;
1998 		else
1999 			flags |= O_EXCL;
2000 #ifdef O_BINARY
2001 		flags |= O_BINARY;
2002 #endif
2003 		fd = open(filename, flags, 0600);
2004 		if (fd < 0) {
2005 			perror(filename);
2006 			return fd;
2007 		}
2008 	}
2009 	*output = pgp_output_new();
2010 	pgp_writer_set_fd(*output, fd);
2011 	return fd;
2012 }
2013 
2014 /**
2015    \ingroup Core_Writers
2016    \brief Closes writer, frees info, closes fd
2017    \param output
2018    \param fd
2019 */
2020 void
pgp_teardown_file_write(pgp_output_t * output,int fd)2021 pgp_teardown_file_write(pgp_output_t *output, int fd)
2022 {
2023 	pgp_writer_close(output);
2024 	close(fd);
2025 	pgp_output_delete(output);
2026 }
2027 
2028 /**
2029    \ingroup Core_Writers
2030    \brief As pgp_setup_file_write, but appends to file
2031 */
2032 int
pgp_setup_file_append(pgp_output_t ** output,const char * filename)2033 pgp_setup_file_append(pgp_output_t **output, const char *filename)
2034 {
2035 	int	fd;
2036 
2037 	/*
2038          * initialise needed structures for writing to file
2039          */
2040 #ifdef O_BINARY
2041 	fd = open(filename, O_WRONLY | O_APPEND | O_BINARY, 0600);
2042 #else
2043 	fd = open(filename, O_WRONLY | O_APPEND, 0600);
2044 #endif
2045 	if (fd >= 0) {
2046 		*output = pgp_output_new();
2047 		pgp_writer_set_fd(*output, fd);
2048 	}
2049 	return fd;
2050 }
2051 
2052 /**
2053    \ingroup Core_Writers
2054    \brief As pgp_teardown_file_write()
2055 */
2056 void
pgp_teardown_file_append(pgp_output_t * output,int fd)2057 pgp_teardown_file_append(pgp_output_t *output, int fd)
2058 {
2059 	pgp_teardown_file_write(output, fd);
2060 }
2061 
2062 /**
2063    \ingroup Core_Readers
2064    \brief Creates parse_info, opens file, and sets to read from file
2065    \param stream Address where new parse_info will be set
2066    \param filename Name of file to read
2067    \param vp Reader-specific arg
2068    \param callback Callback to use when reading
2069    \param accumulate Set if we need to accumulate as we read. (Usually 0 unless doing signature verification)
2070    \note It is the caller's responsiblity to free parse_info and to close fd
2071    \sa pgp_teardown_file_read()
2072 */
2073 int
pgp_setup_file_read(pgp_io_t * io,pgp_stream_t ** stream,const char * filename,void * vp,pgp_cb_ret_t callback (const pgp_packet_t *,pgp_cbdata_t *),unsigned accumulate)2074 pgp_setup_file_read(pgp_io_t *io,
2075 			pgp_stream_t **stream,
2076 			const char *filename,
2077 			void *vp,
2078 			pgp_cb_ret_t callback(const pgp_packet_t *,
2079 						pgp_cbdata_t *),
2080 			unsigned accumulate)
2081 {
2082 	int	fd;
2083 
2084 #ifdef O_BINARY
2085 	fd = open(filename, O_RDONLY | O_BINARY);
2086 #else
2087 	fd = open(filename, O_RDONLY);
2088 #endif
2089 	if (fd < 0) {
2090 		(void) fprintf(io->errs, "can't open \"%s\"\n", filename);
2091 		return fd;
2092 	}
2093 	*stream = pgp_new(sizeof(**stream));
2094 	(*stream)->io = (*stream)->cbinfo.io = io;
2095 	pgp_set_callback(*stream, callback, vp);
2096 #ifdef USE_MMAP_FOR_FILES
2097 	pgp_reader_set_mmap(*stream, fd);
2098 #else
2099 	pgp_reader_set_fd(*stream, fd);
2100 #endif
2101 	if (accumulate) {
2102 		(*stream)->readinfo.accumulate = 1;
2103 	}
2104 	return fd;
2105 }
2106 
2107 /**
2108    \ingroup Core_Readers
2109    \brief Frees stream and closes fd
2110    \param stream
2111    \param fd
2112    \sa pgp_setup_file_read()
2113 */
2114 void
pgp_teardown_file_read(pgp_stream_t * stream,int fd)2115 pgp_teardown_file_read(pgp_stream_t *stream, int fd)
2116 {
2117 	close(fd);
2118 	pgp_stream_delete(stream);
2119 }
2120 
2121 pgp_cb_ret_t
pgp_litdata_cb(const pgp_packet_t * pkt,pgp_cbdata_t * cbinfo)2122 pgp_litdata_cb(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
2123 {
2124 	const pgp_contents_t	*content = &pkt->u;
2125 
2126 	if (pgp_get_debug_level(__FILE__)) {
2127 		printf("pgp_litdata_cb: ");
2128 		pgp_print_packet(&cbinfo->printstate, pkt);
2129 	}
2130 	/* Read data from packet into static buffer */
2131 	switch (pkt->tag) {
2132 	case PGP_PTAG_CT_LITDATA_BODY:
2133 		/* if writer enabled, use it */
2134 		if (cbinfo->output) {
2135 			if (pgp_get_debug_level(__FILE__)) {
2136 				printf("pgp_litdata_cb: length is %u\n",
2137 					content->litdata_body.length);
2138 			}
2139 			pgp_write(cbinfo->output,
2140 					content->litdata_body.data,
2141 					content->litdata_body.length);
2142 		}
2143 		break;
2144 
2145 	case PGP_PTAG_CT_LITDATA_HEADER:
2146 		/* ignore */
2147 		break;
2148 
2149 	default:
2150 		break;
2151 	}
2152 
2153 	return PGP_RELEASE_MEMORY;
2154 }
2155 
2156 pgp_cb_ret_t
pgp_pk_sesskey_cb(const pgp_packet_t * pkt,pgp_cbdata_t * cbinfo)2157 pgp_pk_sesskey_cb(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
2158 {
2159 	const pgp_contents_t	*content = &pkt->u;
2160 	unsigned		 from;
2161 	pgp_io_t		*io;
2162 
2163 	io = cbinfo->io;
2164 	if (pgp_get_debug_level(__FILE__)) {
2165 		pgp_print_packet(&cbinfo->printstate, pkt);
2166 	}
2167 	/* Read data from packet into static buffer */
2168 	switch (pkt->tag) {
2169 	case PGP_PTAG_CT_PK_SESSION_KEY:
2170 		if (pgp_get_debug_level(__FILE__)) {
2171 			printf("PGP_PTAG_CT_PK_SESSION_KEY\n");
2172 		}
2173 		if (!cbinfo->cryptinfo.secring) {
2174 			(void) fprintf(io->errs,
2175 				"pgp_pk_sesskey_cb: bad keyring\n");
2176 			return (pgp_cb_ret_t)0;
2177 		}
2178 		from = 0;
2179 		cbinfo->cryptinfo.keydata =
2180 			pgp_getkeybyid(io, cbinfo->cryptinfo.secring,
2181 				content->pk_sesskey.key_id, &from, NULL);
2182 		if (!cbinfo->cryptinfo.keydata) {
2183 			break;
2184 		}
2185 		break;
2186 
2187 	default:
2188 		break;
2189 	}
2190 
2191 	return PGP_RELEASE_MEMORY;
2192 }
2193 
2194 /**
2195  \ingroup Core_Callbacks
2196 
2197 \brief Callback to get secret key, decrypting if necessary.
2198 
2199 @verbatim
2200  This callback does the following:
2201  * finds the session key in the keyring
2202  * gets a passphrase if required
2203  * decrypts the secret key, if necessary
2204  * sets the seckey in the content struct
2205 @endverbatim
2206 */
2207 
2208 pgp_cb_ret_t
pgp_get_seckey_cb(const pgp_packet_t * pkt,pgp_cbdata_t * cbinfo)2209 pgp_get_seckey_cb(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
2210 {
2211 	const pgp_contents_t	*content = &pkt->u;
2212 	const pgp_seckey_t	*secret;
2213 	const pgp_key_t		*pubkey;
2214 	const pgp_key_t		*keypair;
2215 	unsigned		 from;
2216 	pgp_io_t		*io;
2217 	int			 i;
2218 
2219 	io = cbinfo->io;
2220 	if (pgp_get_debug_level(__FILE__)) {
2221 		pgp_print_packet(&cbinfo->printstate, pkt);
2222 	}
2223 	switch (pkt->tag) {
2224 	case PGP_GET_SECKEY:
2225 		/* print key from pubring */
2226 		from = 0;
2227 		pubkey = pgp_getkeybyid(io, cbinfo->cryptinfo.pubring,
2228 				content->get_seckey.pk_sesskey->key_id,
2229 				&from, NULL);
2230 		/* validate key from secring */
2231 		from = 0;
2232 		cbinfo->cryptinfo.keydata =
2233 			pgp_getkeybyid(io, cbinfo->cryptinfo.secring,
2234 				content->get_seckey.pk_sesskey->key_id,
2235 				&from, NULL);
2236 		if (!cbinfo->cryptinfo.keydata ||
2237 		    !pgp_is_key_secret(cbinfo->cryptinfo.keydata)) {
2238 			return (pgp_cb_ret_t)0;
2239 		}
2240 		keypair = cbinfo->cryptinfo.keydata;
2241 		if (pubkey == NULL) {
2242 			pubkey = keypair;
2243 		}
2244 		secret = NULL;
2245 		cbinfo->gotpass = 0;
2246 		for (i = 0 ; cbinfo->numtries == -1 || i < cbinfo->numtries ; i++) {
2247 			/* print out the user id */
2248 			pgp_print_keydata(io, cbinfo->cryptinfo.pubring, pubkey,
2249 				"signature ", &pubkey->key.pubkey, 0);
2250 			/* now decrypt key */
2251 			secret = pgp_decrypt_seckey(keypair, cbinfo->passfp);
2252 			if (secret != NULL) {
2253 				break;
2254 			}
2255 			(void) fprintf(io->errs, "Bad passphrase\n");
2256 		}
2257 		if (secret == NULL) {
2258 			(void) fprintf(io->errs, "Exhausted passphrase attempts\n");
2259 			return (pgp_cb_ret_t)PGP_RELEASE_MEMORY;
2260 		}
2261 		cbinfo->gotpass = 1;
2262 		*content->get_seckey.seckey = secret;
2263 		break;
2264 
2265 	default:
2266 		break;
2267 	}
2268 
2269 	return PGP_RELEASE_MEMORY;
2270 }
2271 
2272 /**
2273  \ingroup HighLevel_Callbacks
2274  \brief Callback to use when you need to prompt user for passphrase
2275  \param contents
2276  \param cbinfo
2277 */
2278 pgp_cb_ret_t
get_passphrase_cb(const pgp_packet_t * pkt,pgp_cbdata_t * cbinfo)2279 get_passphrase_cb(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
2280 {
2281 	const pgp_contents_t	*content = &pkt->u;
2282 	pgp_io_t		*io;
2283 
2284 	io = cbinfo->io;
2285 	if (pgp_get_debug_level(__FILE__)) {
2286 		pgp_print_packet(&cbinfo->printstate, pkt);
2287 	}
2288 	if (cbinfo->cryptinfo.keydata == NULL) {
2289 		(void) fprintf(io->errs, "get_passphrase_cb: NULL keydata\n");
2290 	} else {
2291 		pgp_print_keydata(io, cbinfo->cryptinfo.pubring, cbinfo->cryptinfo.keydata, "signature ",
2292 			&cbinfo->cryptinfo.keydata->key.pubkey, 0);
2293 	}
2294 	switch (pkt->tag) {
2295 	case PGP_GET_PASSPHRASE:
2296 		*(content->skey_passphrase.passphrase) =
2297 				netpgp_strdup(getpass("netpgp passphrase: "));
2298 		return PGP_KEEP_MEMORY;
2299 	default:
2300 		break;
2301 	}
2302 	return PGP_RELEASE_MEMORY;
2303 }
2304 
2305 unsigned
pgp_reader_set_accumulate(pgp_stream_t * stream,unsigned state)2306 pgp_reader_set_accumulate(pgp_stream_t *stream, unsigned state)
2307 {
2308 	return stream->readinfo.accumulate = state;
2309 }
2310 
2311 /**************************************************************************/
2312 
2313 static int
hash_reader(pgp_stream_t * stream,void * dest,size_t length,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)2314 hash_reader(pgp_stream_t *stream, void *dest,
2315 		size_t length,
2316 		pgp_error_t **errors,
2317 		pgp_reader_t *readinfo,
2318 		pgp_cbdata_t *cbinfo)
2319 {
2320 	pgp_hash_t	*hash = pgp_reader_get_arg(readinfo);
2321 	int		 r;
2322 
2323 	r = pgp_stacked_read(stream, dest, length, errors, readinfo, cbinfo);
2324 	if (r <= 0) {
2325 		return r;
2326 	}
2327 	hash->add(hash, dest, (unsigned)r);
2328 	return r;
2329 }
2330 
2331 /**
2332    \ingroup Internal_Readers_Hash
2333    \brief Push hashed data reader on stack
2334 */
2335 void
pgp_reader_push_hash(pgp_stream_t * stream,pgp_hash_t * hash)2336 pgp_reader_push_hash(pgp_stream_t *stream, pgp_hash_t *hash)
2337 {
2338 	if (!hash->init(hash)) {
2339 		(void) fprintf(stderr, "pgp_reader_push_hash: can't init hash\n");
2340 		/* just continue and die */
2341 		/* XXX - agc - no way to return failure */
2342 	}
2343 	pgp_reader_push(stream, hash_reader, NULL, hash);
2344 }
2345 
2346 /**
2347    \ingroup Internal_Readers_Hash
2348    \brief Pop hashed data reader from stack
2349 */
2350 void
pgp_reader_pop_hash(pgp_stream_t * stream)2351 pgp_reader_pop_hash(pgp_stream_t *stream)
2352 {
2353 	pgp_reader_pop(stream);
2354 }
2355 
2356 /* read memory from the previously mmap-ed file */
2357 static int
mmap_reader(pgp_stream_t * stream,void * dest,size_t length,pgp_error_t ** errors,pgp_reader_t * readinfo,pgp_cbdata_t * cbinfo)2358 mmap_reader(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
2359 	  pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
2360 {
2361 	mmap_reader_t	*mem = pgp_reader_get_arg(readinfo);
2362 	unsigned	 n;
2363 	char		*cmem = mem->mem;
2364 
2365 	__PGP_USED(errors);
2366 	__PGP_USED(cbinfo);
2367 	if (!stream->coalescing && stream->virtualc && stream->virtualoff < stream->virtualc) {
2368 		n = read_partial_data(stream, dest, length);
2369 	} else {
2370 		n = (unsigned)MIN(length, (unsigned)(mem->size - mem->offset));
2371 		if (n > 0) {
2372 			(void) memcpy(dest, &cmem[(int)mem->offset], (unsigned)n);
2373 			mem->offset += n;
2374 		}
2375 	}
2376 	return (int)n;
2377 }
2378 
2379 /* tear down the mmap, close the fd */
2380 static void
mmap_destroyer(pgp_reader_t * readinfo)2381 mmap_destroyer(pgp_reader_t *readinfo)
2382 {
2383 	mmap_reader_t *mem = pgp_reader_get_arg(readinfo);
2384 
2385 	(void) munmap(mem->mem, (unsigned)mem->size);
2386 	(void) close(mem->fd);
2387 	free(pgp_reader_get_arg(readinfo));
2388 }
2389 
2390 /* set up the file to use mmap-ed memory if available, file IO otherwise */
2391 void
pgp_reader_set_mmap(pgp_stream_t * stream,int fd)2392 pgp_reader_set_mmap(pgp_stream_t *stream, int fd)
2393 {
2394 	mmap_reader_t	*mem;
2395 	struct stat	 st;
2396 
2397 	if (fstat(fd, &st) != 0) {
2398 		(void) fprintf(stderr, "pgp_reader_set_mmap: can't fstat\n");
2399 	} else if ((mem = calloc(1, sizeof(*mem))) == NULL) {
2400 		(void) fprintf(stderr, "pgp_reader_set_mmap: bad alloc\n");
2401 	} else {
2402 		mem->size = (uint64_t)st.st_size;
2403 		mem->offset = 0;
2404 		mem->fd = fd;
2405 		mem->mem = mmap(NULL, (size_t)st.st_size, PROT_READ,
2406 				MAP_PRIVATE | MAP_FILE, fd, 0);
2407 		if (mem->mem == MAP_FAILED) {
2408 			pgp_reader_set(stream, fd_reader, reader_fd_destroyer,
2409 					mem);
2410 		} else {
2411 			pgp_reader_set(stream, mmap_reader, mmap_destroyer,
2412 					mem);
2413 		}
2414 	}
2415 }
2416