1 /*
2  * Copyright (c) 2017-2020, [Ribose Inc](https://www.ribose.com).
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without modification,
6  * are permitted provided that the following conditions are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *
11  * 2.  Redistributions in binary form must reproduce the above copyright notice,
12  *     this list of conditions and the following disclaimer in the documentation
13  *     and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "config.h"
28 #include <sys/stat.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <string>
33 #include <vector>
34 #include <time.h>
35 #include <rnp/rnp_def.h>
36 #include "stream-ctx.h"
37 #include "stream-def.h"
38 #include "stream-parse.h"
39 #include "stream-armor.h"
40 #include "stream-packet.h"
41 #include "stream-sig.h"
42 #include "str-utils.h"
43 #include "types.h"
44 #include "crypto/s2k.h"
45 #include "crypto.h"
46 #include "crypto/signatures.h"
47 #include "fingerprint.h"
48 #include "pgp-key.h"
49 
50 #ifdef HAVE_ZLIB_H
51 #include <zlib.h>
52 #endif
53 #ifdef HAVE_BZLIB_H
54 #include <bzlib.h>
55 #endif
56 
57 typedef enum pgp_message_t {
58     PGP_MESSAGE_UNKNOWN = 0,
59     PGP_MESSAGE_NORMAL,
60     PGP_MESSAGE_DETACHED,
61     PGP_MESSAGE_CLEARTEXT
62 } pgp_message_t;
63 
64 typedef struct pgp_processing_ctx_t {
65     pgp_parse_handler_t     handler;
66     pgp_source_t *          signed_src;
67     pgp_source_t *          literal_src;
68     pgp_message_t           msg_type;
69     pgp_dest_t              output;
70     std::list<pgp_source_t> sources;
71 
72     ~pgp_processing_ctx_t();
73 } pgp_processing_ctx_t;
74 
75 /* common fields for encrypted, compressed and literal data */
76 typedef struct pgp_source_packet_param_t {
77     pgp_source_t *readsrc;                  /* source to read from, could be partial*/
78     pgp_source_t *origsrc;                  /* original source passed to init_*_src */
79     bool          partial;                  /* partial length packet */
80     bool          indeterminate;            /* indeterminate length packet */
81     uint8_t       hdr[PGP_MAX_HEADER_SIZE]; /* PGP packet header, needed for AEAD */
82     size_t        hdrlen;                   /* length of the header */
83     size_t        len; /* packet body length if non-partial and non-indeterminate */
84 } pgp_source_packet_param_t;
85 
86 typedef struct pgp_source_encrypted_param_t {
87     pgp_source_packet_param_t     pkt;            /* underlying packet-related params */
88     std::vector<pgp_sk_sesskey_t> symencs;        /* array of sym-encrypted session keys */
89     std::vector<pgp_pk_sesskey_t> pubencs;        /* array of pk-encrypted session keys */
90     bool                          has_mdc;        /* encrypted with mdc, i.e. tag 18 */
91     bool                          mdc_validated;  /* mdc was validated already */
92     bool                          aead;           /* AEAD encrypted data packet, tag 20 */
93     bool                          aead_validated; /* we read and validated last chunk */
94     pgp_crypt_t                   decrypt;        /* decrypting crypto */
95     pgp_hash_t                    mdc;            /* mdc SHA1 hash */
96     size_t                        chunklen;       /* size of AEAD chunk in bytes */
97     size_t                        chunkin;  /* number of bytes read from the current chunk */
98     size_t                        chunkidx; /* index of the current chunk */
99     uint8_t                       cache[PGP_AEAD_CACHE_LEN]; /* read cache */
100     size_t                        cachelen;                  /* number of bytes in the cache */
101     size_t                        cachepos; /* index of first unread byte in the cache */
102     pgp_aead_hdr_t                aead_hdr; /* AEAD encryption parameters */
103     uint8_t                       aead_ad[PGP_AEAD_MAX_AD_LEN]; /* additional data */
104     size_t                        aead_adlen; /* length of the additional data */
105     pgp_symm_alg_t                salg;       /* data encryption algorithm */
106     pgp_parse_handler_t *         handler;    /* parsing handler with callbacks */
107 } pgp_source_encrypted_param_t;
108 
109 typedef struct pgp_source_signed_param_t {
110     pgp_parse_handler_t *handler;         /* parsing handler with callbacks */
111     pgp_source_t *       readsrc;         /* source to read from */
112     bool                 detached;        /* detached signature */
113     bool                 cleartext;       /* source is cleartext signed */
114     bool                 clr_eod;         /* cleartext data is over */
115     bool                 clr_fline;       /* first line of the cleartext */
116     bool                 clr_mline;       /* in the middle of the very long line */
117     uint8_t              out[CT_BUF_LEN]; /* cleartext output cache for easier parsing */
118     size_t               outlen;          /* total bytes in out */
119     size_t               outpos;          /* offset of first available byte in out */
120     bool                 max_line_warn;   /* warning about too long line is already issued */
121     size_t               text_line_len;   /* length of a current line in a text document */
122     long stripped_crs; /* number of trailing CR characters stripped from the end of the last
123                           processed chunk */
124 
125     std::vector<pgp_one_pass_sig_t>   onepasses;  /* list of one-pass singatures */
126     std::list<pgp_signature_t>        sigs;       /* list of signatures */
127     std::vector<pgp_signature_info_t> siginfos;   /* signature validation info */
128     std::vector<pgp_hash_t>           hashes;     /* hash contexts */
129     std::vector<pgp_hash_t>           txt_hashes; /* hash contexts for text-mode sigs */
130 
131     pgp_source_signed_param_t() = default;
132     ~pgp_source_signed_param_t();
133 } pgp_source_signed_param_t;
134 
135 typedef struct pgp_source_compressed_param_t {
136     pgp_source_packet_param_t pkt; /* underlying packet-related params */
137     pgp_compression_type_t    alg;
138     union {
139         z_stream  z;
140         bz_stream bz;
141     };
142     uint8_t in[PGP_INPUT_CACHE_SIZE / 2];
143     size_t  inpos;
144     size_t  inlen;
145     bool    zend;
146 } pgp_source_compressed_param_t;
147 
148 typedef struct pgp_source_literal_param_t {
149     pgp_source_packet_param_t pkt; /* underlying packet-related params */
150     pgp_literal_hdr_t         hdr; /* literal packet fields */
151 } pgp_source_literal_param_t;
152 
153 typedef struct pgp_source_partial_param_t {
154     pgp_source_t *readsrc; /* source to read from */
155     int           type;    /* type of the packet */
156     size_t        psize;   /* size of the current part */
157     size_t        pleft;   /* bytes left to read from the current part */
158     bool          last;    /* current part is last */
159 } pgp_source_partial_param_t;
160 
161 static bool
is_pgp_source(pgp_source_t & src)162 is_pgp_source(pgp_source_t &src)
163 {
164     uint8_t buf;
165     if (!src_peek_eq(&src, &buf, 1)) {
166         return false;
167     }
168 
169     switch (get_packet_type(buf)) {
170     case PGP_PKT_PK_SESSION_KEY:
171     case PGP_PKT_SK_SESSION_KEY:
172     case PGP_PKT_ONE_PASS_SIG:
173     case PGP_PKT_SIGNATURE:
174     case PGP_PKT_SE_DATA:
175     case PGP_PKT_SE_IP_DATA:
176     case PGP_PKT_COMPRESSED:
177     case PGP_PKT_LITDATA:
178     case PGP_PKT_MARKER:
179         return true;
180     default:
181         return false;
182     }
183 }
184 
185 static bool
partial_pkt_src_read(pgp_source_t * src,void * buf,size_t len,size_t * readres)186 partial_pkt_src_read(pgp_source_t *src, void *buf, size_t len, size_t *readres)
187 {
188     if (src->eof) {
189         *readres = 0;
190         return true;
191     }
192 
193     pgp_source_partial_param_t *param = (pgp_source_partial_param_t *) src->param;
194     if (!param) {
195         return false;
196     }
197 
198     size_t read;
199     size_t write = 0;
200     while (len > 0) {
201         if (!param->pleft && param->last) {
202             // we have the last chunk
203             *readres = write;
204             return true;
205         }
206         if (!param->pleft) {
207             // reading next chunk
208             if (!stream_read_partial_chunk_len(param->readsrc, &read, &param->last)) {
209                 return false;
210             }
211             param->psize = read;
212             param->pleft = read;
213         }
214 
215         if (!param->pleft) {
216             *readres = write;
217             return true;
218         }
219 
220         read = param->pleft > len ? len : param->pleft;
221         if (!src_read(param->readsrc, buf, read, &read)) {
222             RNP_LOG("failed to read data chunk");
223             return false;
224         }
225         if (!read) {
226             RNP_LOG("unexpected eof");
227             *readres = write;
228             return true;
229         }
230         write += read;
231         len -= read;
232         buf = (uint8_t *) buf + read;
233         param->pleft -= read;
234     }
235 
236     *readres = write;
237     return true;
238 }
239 
240 static void
partial_pkt_src_close(pgp_source_t * src)241 partial_pkt_src_close(pgp_source_t *src)
242 {
243     pgp_source_partial_param_t *param = (pgp_source_partial_param_t *) src->param;
244     if (param) {
245         free(src->param);
246         src->param = NULL;
247     }
248 }
249 
250 static rnp_result_t
init_partial_pkt_src(pgp_source_t * src,pgp_source_t * readsrc)251 init_partial_pkt_src(pgp_source_t *src, pgp_source_t *readsrc)
252 {
253     pgp_source_partial_param_t *param;
254     uint8_t                     buf[2];
255 
256     if (!stream_partial_pkt_len(readsrc)) {
257         RNP_LOG("wrong call on non-partial len packet");
258         return RNP_ERROR_BAD_FORMAT;
259     }
260 
261     if (!init_src_common(src, sizeof(*param))) {
262         return RNP_ERROR_OUT_OF_MEMORY;
263     }
264 
265     /* we are sure that there are 2 bytes in readsrc */
266     param = (pgp_source_partial_param_t *) src->param;
267     (void) src_read_eq(readsrc, buf, 2);
268     param->type = get_packet_type(buf[0]);
269     param->psize = get_partial_pkt_len(buf[1]);
270     param->pleft = param->psize;
271     param->last = false;
272     param->readsrc = readsrc;
273 
274     src->read = partial_pkt_src_read;
275     src->close = partial_pkt_src_close;
276     src->type = PGP_STREAM_PARLEN_PACKET;
277 
278     if (param->psize < PGP_PARTIAL_PKT_FIRST_PART_MIN_SIZE) {
279         RNP_LOG("first part of partial length packet sequence has size %d and that's less "
280                 "than allowed by the protocol",
281                 (int) param->psize);
282     }
283 
284     return RNP_SUCCESS;
285 }
286 
287 static bool
literal_src_read(pgp_source_t * src,void * buf,size_t len,size_t * read)288 literal_src_read(pgp_source_t *src, void *buf, size_t len, size_t *read)
289 {
290     pgp_source_literal_param_t *param = (pgp_source_literal_param_t *) src->param;
291     if (!param) {
292         return false;
293     }
294     return src_read(param->pkt.readsrc, buf, len, read);
295 }
296 
297 static void
literal_src_close(pgp_source_t * src)298 literal_src_close(pgp_source_t *src)
299 {
300     pgp_source_literal_param_t *param = (pgp_source_literal_param_t *) src->param;
301     if (param) {
302         if (param->pkt.partial) {
303             src_close(param->pkt.readsrc);
304             free(param->pkt.readsrc);
305             param->pkt.readsrc = NULL;
306         }
307 
308         free(src->param);
309         src->param = NULL;
310     }
311 }
312 
313 static bool
compressed_src_read(pgp_source_t * src,void * buf,size_t len,size_t * readres)314 compressed_src_read(pgp_source_t *src, void *buf, size_t len, size_t *readres)
315 {
316     pgp_source_compressed_param_t *param = (pgp_source_compressed_param_t *) src->param;
317     if (param == NULL) {
318         return false;
319     }
320 
321     if (src->eof || param->zend) {
322         *readres = 0;
323         return true;
324     }
325 
326     if ((param->alg == PGP_C_ZIP) || (param->alg == PGP_C_ZLIB)) {
327         param->z.next_out = (Bytef *) buf;
328         param->z.avail_out = len;
329         param->z.next_in = param->in + param->inpos;
330         param->z.avail_in = param->inlen - param->inpos;
331 
332         while ((param->z.avail_out > 0) && (!param->zend)) {
333             if (param->z.avail_in == 0) {
334                 size_t read = 0;
335                 if (!src_read(param->pkt.readsrc, param->in, sizeof(param->in), &read)) {
336                     RNP_LOG("failed to read data");
337                     return false;
338                 }
339                 param->z.next_in = param->in;
340                 param->z.avail_in = read;
341                 param->inlen = read;
342                 param->inpos = 0;
343             }
344             int ret = inflate(&param->z, Z_SYNC_FLUSH);
345             if (ret == Z_STREAM_END) {
346                 param->zend = true;
347                 if (param->z.avail_in > 0) {
348                     RNP_LOG("data beyond the end of z stream");
349                 }
350                 break;
351             }
352             if (ret != Z_OK) {
353                 RNP_LOG("inflate error %d", ret);
354                 return false;
355             }
356             if (!param->z.avail_in && src_eof(param->pkt.readsrc)) {
357                 RNP_LOG("unexpected end of zlib stream");
358                 return false;
359             }
360         }
361         param->inpos = param->z.next_in - param->in;
362         *readres = len - param->z.avail_out;
363         return true;
364     }
365 #ifdef HAVE_BZLIB_H
366     if (param->alg == PGP_C_BZIP2) {
367         param->bz.next_out = (char *) buf;
368         param->bz.avail_out = len;
369         param->bz.next_in = (char *) (param->in + param->inpos);
370         param->bz.avail_in = param->inlen - param->inpos;
371 
372         while ((param->bz.avail_out > 0) && (!param->zend)) {
373             if (param->bz.avail_in == 0) {
374                 size_t read = 0;
375                 if (!src_read(param->pkt.readsrc, param->in, sizeof(param->in), &read)) {
376                     RNP_LOG("failed to read data");
377                     return false;
378                 }
379                 param->bz.next_in = (char *) param->in;
380                 param->bz.avail_in = read;
381                 param->inlen = read;
382                 param->inpos = 0;
383             }
384             int ret = BZ2_bzDecompress(&param->bz);
385             if (ret == BZ_STREAM_END) {
386                 param->zend = true;
387                 if (param->bz.avail_in > 0) {
388                     RNP_LOG("data beyond the end of z stream");
389                 }
390                 break;
391             }
392             if (ret != BZ_OK) {
393                 RNP_LOG("bzdecompress error %d", ret);
394                 return false;
395             }
396             if (!param->bz.avail_in && src_eof(param->pkt.readsrc)) {
397                 RNP_LOG("unexpected end of bzip stream");
398                 return false;
399             }
400         }
401 
402         param->inpos = (uint8_t *) param->bz.next_in - param->in;
403         *readres = len - param->bz.avail_out;
404         return true;
405     }
406 #endif
407     return false;
408 }
409 
410 static void
compressed_src_close(pgp_source_t * src)411 compressed_src_close(pgp_source_t *src)
412 {
413     pgp_source_compressed_param_t *param = (pgp_source_compressed_param_t *) src->param;
414     if (!param) {
415         return;
416     }
417 
418     if (param->pkt.partial) {
419         src_close(param->pkt.readsrc);
420         free(param->pkt.readsrc);
421         param->pkt.readsrc = NULL;
422     }
423 
424 #ifdef HAVE_BZLIB_H
425     if (param->alg == PGP_C_BZIP2) {
426         BZ2_bzDecompressEnd(&param->bz);
427     }
428 #endif
429     if ((param->alg == PGP_C_ZIP) || (param->alg == PGP_C_ZLIB)) {
430         inflateEnd(&param->z);
431     }
432 
433     free(src->param);
434     src->param = NULL;
435 }
436 
437 static bool
encrypted_start_aead_chunk(pgp_source_encrypted_param_t * param,size_t idx,bool last)438 encrypted_start_aead_chunk(pgp_source_encrypted_param_t *param, size_t idx, bool last)
439 {
440     uint8_t nonce[PGP_AEAD_MAX_NONCE_LEN];
441     size_t  nlen;
442 
443     /* set chunk index for additional data */
444     STORE64BE(param->aead_ad + param->aead_adlen - 8, idx);
445 
446     if (last) {
447         uint64_t total = idx * param->chunklen;
448         if (idx && param->chunkin) {
449             total -= param->chunklen - param->chunkin;
450         }
451 
452         if (!param->chunkin) {
453             /* reset the crypto in case we had empty chunk before the last one */
454             pgp_cipher_aead_reset(&param->decrypt);
455         }
456         STORE64BE(param->aead_ad + param->aead_adlen, total);
457         param->aead_adlen += 8;
458     }
459 
460     if (!pgp_cipher_aead_set_ad(&param->decrypt, param->aead_ad, param->aead_adlen)) {
461         RNP_LOG("failed to set ad");
462         return false;
463     }
464 
465     /* setup chunk */
466     param->chunkidx = idx;
467     param->chunkin = 0;
468 
469     /* set chunk index for nonce */
470     nlen = pgp_cipher_aead_nonce(param->aead_hdr.aalg, param->aead_hdr.iv, nonce, idx);
471 
472     RNP_DHEX("authenticated data: ", param->aead_ad, param->aead_adlen);
473     RNP_DHEX("nonce: ", nonce, nlen);
474 
475     /* start cipher */
476     return pgp_cipher_aead_start(&param->decrypt, nonce, nlen);
477 }
478 
479 /* read and decrypt bytes to the cache. Should be called only on empty cache. */
480 static bool
encrypted_src_read_aead_part(pgp_source_encrypted_param_t * param)481 encrypted_src_read_aead_part(pgp_source_encrypted_param_t *param)
482 {
483     bool   lastchunk = false;
484     bool   chunkend = false;
485     bool   res = false;
486     size_t read;
487     size_t tagread;
488     size_t taglen;
489 
490     param->cachepos = 0;
491     param->cachelen = 0;
492 
493     if (param->aead_validated) {
494         return true;
495     }
496 
497     /* it is always 16 for defined EAX and OCB, however this may change in future */
498     taglen = pgp_cipher_aead_tag_len(param->aead_hdr.aalg);
499     read = sizeof(param->cache) - 2 * PGP_AEAD_MAX_TAG_LEN;
500 
501     if (read >= param->chunklen - param->chunkin) {
502         read = param->chunklen - param->chunkin;
503         chunkend = true;
504     } else {
505         read = read - read % pgp_cipher_aead_granularity(&param->decrypt);
506     }
507 
508     if (!src_read(param->pkt.readsrc, param->cache, read, &read)) {
509         return false;
510     }
511 
512     /* checking whether we have enough input for the final tags */
513     if (!src_peek(param->pkt.readsrc, param->cache + read, taglen * 2, &tagread)) {
514         return false;
515     }
516 
517     if (tagread < taglen * 2) {
518         /* this would mean the end of the stream */
519         if ((param->chunkin == 0) && (read + tagread == taglen)) {
520             /* we have empty chunk and final tag */
521             chunkend = false;
522             lastchunk = true;
523         } else if (read + tagread >= 2 * taglen) {
524             /* we have end of chunk and final tag */
525             chunkend = true;
526             lastchunk = true;
527         } else {
528             RNP_LOG("unexpected end of data");
529             return false;
530         }
531     }
532 
533     if (!chunkend && !lastchunk) {
534         param->chunkin += read;
535         res = pgp_cipher_aead_update(&param->decrypt, param->cache, param->cache, read);
536         if (res) {
537             param->cachelen = read;
538         }
539         return res;
540     }
541 
542     if (chunkend) {
543         if (tagread > taglen) {
544             src_skip(param->pkt.readsrc, tagread - taglen);
545         }
546 
547         RNP_DHEX("tag: ", param->cache + read + tagread - 2 * taglen, taglen);
548 
549         res = pgp_cipher_aead_finish(
550           &param->decrypt, param->cache, param->cache, read + tagread - taglen);
551         if (!res) {
552             RNP_LOG("failed to finalize aead chunk");
553             return res;
554         }
555         param->cachelen = read + tagread - 2 * taglen;
556         param->chunkin += param->cachelen;
557 
558         RNP_DHEX("decrypted data: ", param->cache, param->cachelen);
559     }
560 
561     size_t chunkidx = param->chunkidx;
562     if (chunkend && param->chunkin) {
563         chunkidx++;
564     }
565 
566     if (!(res = encrypted_start_aead_chunk(param, chunkidx, lastchunk))) {
567         RNP_LOG("failed to start aead chunk");
568         return res;
569     }
570 
571     if (lastchunk) {
572         if (tagread > 0) {
573             src_skip(param->pkt.readsrc, tagread);
574         }
575 
576         size_t off = read + tagread - taglen;
577 
578         RNP_DHEX("tag: ", param->cache + off, taglen);
579 
580         res = pgp_cipher_aead_finish(
581           &param->decrypt, param->cache + off, param->cache + off, taglen);
582         if (!res) {
583             RNP_LOG("wrong last chunk");
584             return res;
585         }
586         param->aead_validated = true;
587     }
588 
589     return res;
590 }
591 
592 static bool
encrypted_src_read_aead(pgp_source_t * src,void * buf,size_t len,size_t * read)593 encrypted_src_read_aead(pgp_source_t *src, void *buf, size_t len, size_t *read)
594 {
595     pgp_source_encrypted_param_t *param = (pgp_source_encrypted_param_t *) src->param;
596     size_t                        cbytes;
597     size_t                        left = len;
598 
599     do {
600         /* check whether we have something in the cache */
601         cbytes = param->cachelen - param->cachepos;
602         if (cbytes > 0) {
603             if (cbytes >= left) {
604                 memcpy(buf, param->cache + param->cachepos, left);
605                 param->cachepos += left;
606                 if (param->cachepos == param->cachelen) {
607                     param->cachepos = param->cachelen = 0;
608                 }
609                 *read = len;
610                 return true;
611             }
612             memcpy(buf, param->cache + param->cachepos, cbytes);
613             buf = (uint8_t *) buf + cbytes;
614             left -= cbytes;
615             param->cachepos = param->cachelen = 0;
616         }
617 
618         /* read something into cache */
619         if (!encrypted_src_read_aead_part(param)) {
620             return false;
621         }
622     } while ((left > 0) && (param->cachelen > 0));
623 
624     *read = len - left;
625     return true;
626 }
627 
628 static bool
encrypted_src_read_cfb(pgp_source_t * src,void * buf,size_t len,size_t * readres)629 encrypted_src_read_cfb(pgp_source_t *src, void *buf, size_t len, size_t *readres)
630 {
631     pgp_source_encrypted_param_t *param = (pgp_source_encrypted_param_t *) src->param;
632     if (param == NULL) {
633         return false;
634     }
635 
636     if (src->eof) {
637         *readres = 0;
638         return true;
639     }
640 
641     size_t read;
642     if (!src_read(param->pkt.readsrc, buf, len, &read)) {
643         return false;
644     }
645     if (!read) {
646         *readres = 0;
647         return true;
648     }
649 
650     bool    parsemdc = false;
651     uint8_t mdcbuf[MDC_V1_SIZE];
652     if (param->has_mdc) {
653         size_t mdcread = 0;
654         /* make sure there are always 22 bytes left on input */
655         if (!src_peek(param->pkt.readsrc, mdcbuf, MDC_V1_SIZE, &mdcread) ||
656             (mdcread + read < MDC_V1_SIZE)) {
657             RNP_LOG("wrong mdc read state");
658             return false;
659         }
660         if (mdcread < MDC_V1_SIZE) {
661             src_skip(param->pkt.readsrc, mdcread);
662             size_t mdcsub = MDC_V1_SIZE - mdcread;
663             memmove(&mdcbuf[mdcsub], mdcbuf, mdcread);
664             memcpy(mdcbuf, (uint8_t *) buf + read - mdcsub, mdcsub);
665             read -= mdcsub;
666             parsemdc = true;
667         }
668     }
669 
670     pgp_cipher_cfb_decrypt(&param->decrypt, (uint8_t *) buf, (uint8_t *) buf, read);
671 
672     if (param->has_mdc) {
673         pgp_hash_add(&param->mdc, buf, read);
674 
675         if (parsemdc) {
676             pgp_cipher_cfb_decrypt(&param->decrypt, mdcbuf, mdcbuf, MDC_V1_SIZE);
677             pgp_cipher_cfb_finish(&param->decrypt);
678             pgp_hash_add(&param->mdc, mdcbuf, 2);
679             uint8_t hash[PGP_SHA1_HASH_SIZE] = {0};
680             pgp_hash_finish(&param->mdc, hash);
681 
682             if ((mdcbuf[0] != MDC_PKT_TAG) || (mdcbuf[1] != MDC_V1_SIZE - 2)) {
683                 RNP_LOG("mdc header check failed");
684                 return false;
685             }
686 
687             if (memcmp(&mdcbuf[2], hash, PGP_SHA1_HASH_SIZE) != 0) {
688                 RNP_LOG("mdc hash check failed");
689                 return false;
690             }
691             param->mdc_validated = true;
692         }
693     }
694     *readres = read;
695     return true;
696 }
697 
698 static rnp_result_t
encrypted_src_finish(pgp_source_t * src)699 encrypted_src_finish(pgp_source_t *src)
700 {
701     pgp_source_encrypted_param_t *param = (pgp_source_encrypted_param_t *) src->param;
702 
703     /* report to the handler that decryption is finished */
704     if (param->handler->on_decryption_done) {
705         bool validated =
706           (param->has_mdc && param->mdc_validated) || (param->aead && param->aead_validated);
707         param->handler->on_decryption_done(validated, param->handler->param);
708     }
709 
710     if (param->aead) {
711         if (!param->aead_validated) {
712             RNP_LOG("aead last chunk was not validated");
713             return RNP_ERROR_BAD_STATE;
714         }
715         return RNP_SUCCESS;
716     }
717 
718     if (param->has_mdc && !param->mdc_validated) {
719         RNP_LOG("mdc was not validated");
720         return RNP_ERROR_BAD_STATE;
721     }
722 
723     return RNP_SUCCESS;
724 }
725 
726 static void
encrypted_src_close(pgp_source_t * src)727 encrypted_src_close(pgp_source_t *src)
728 {
729     pgp_source_encrypted_param_t *param = (pgp_source_encrypted_param_t *) src->param;
730     if (!param) {
731         return;
732     }
733     if (param->pkt.partial) {
734         src_close(param->pkt.readsrc);
735         free(param->pkt.readsrc);
736         param->pkt.readsrc = NULL;
737     }
738 
739     if (param->aead) {
740         pgp_cipher_aead_destroy(&param->decrypt);
741     } else {
742         pgp_cipher_cfb_finish(&param->decrypt);
743     }
744 
745     delete param;
746     src->param = NULL;
747 }
748 
749 static bool
add_hash_for_sig(pgp_source_signed_param_t * param,pgp_sig_type_t stype,pgp_hash_alg_t halg)750 add_hash_for_sig(pgp_source_signed_param_t *param, pgp_sig_type_t stype, pgp_hash_alg_t halg)
751 {
752     /* Cleartext always uses param->hashes instead of param->txt_hashes */
753     if (!param->cleartext && (stype == PGP_SIG_TEXT)) {
754         return pgp_hash_list_add(param->txt_hashes, halg);
755     }
756     return pgp_hash_list_add(param->hashes, halg);
757 }
758 
759 static const pgp_hash_t *
get_hash_for_sig(pgp_source_signed_param_t * param,pgp_signature_info_t * sinfo)760 get_hash_for_sig(pgp_source_signed_param_t *param, pgp_signature_info_t *sinfo)
761 {
762     /* Cleartext always uses param->hashes instead of param->txt_hashes */
763     if (!param->cleartext && (sinfo->sig->type() == PGP_SIG_TEXT)) {
764         return pgp_hash_list_get(param->txt_hashes, sinfo->sig->halg);
765     }
766     return pgp_hash_list_get(param->hashes, sinfo->sig->halg);
767 }
768 
769 static void
signed_validate_signature(pgp_source_signed_param_t * param,pgp_signature_info_t * sinfo)770 signed_validate_signature(pgp_source_signed_param_t *param, pgp_signature_info_t *sinfo)
771 {
772     pgp_hash_t shash = {};
773 
774     /* Get the hash context and clone it. */
775     const pgp_hash_t *hash = get_hash_for_sig(param, sinfo);
776     if (!hash || !pgp_hash_copy(&shash, hash)) {
777         RNP_LOG("failed to clone hash context");
778         sinfo->valid = false;
779         return;
780     }
781 
782     /* fill the signature info */
783     signature_check(sinfo, &shash);
784 }
785 
786 static long
stripped_line_len(uint8_t * begin,uint8_t * end)787 stripped_line_len(uint8_t *begin, uint8_t *end)
788 {
789     uint8_t *stripped_end = end;
790 
791     while (stripped_end >= begin && (*stripped_end == CH_CR || *stripped_end == CH_LF)) {
792         stripped_end--;
793     }
794 
795     return stripped_end - begin + 1;
796 }
797 
798 static void
signed_src_update(pgp_source_t * src,const void * buf,size_t len)799 signed_src_update(pgp_source_t *src, const void *buf, size_t len)
800 {
801     if (!len) {
802         return;
803     }
804     /* check for extremely unlikely pointer overflow/wrap case */
805     if (((uint8_t *) buf + len) < ((uint8_t *) buf + len - 1)) {
806         signed_src_update(src, buf, len - 1);
807         uint8_t last = *((uint8_t *) buf + len - 1);
808         signed_src_update(src, &last, 1);
809     }
810     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
811     pgp_hash_list_update(param->hashes, buf, len);
812     /* update text-mode sig hashes */
813     if (param->txt_hashes.empty()) {
814         return;
815     }
816 
817     uint8_t *ch = (uint8_t *) buf;
818     uint8_t *linebeg = ch;
819     uint8_t *end = (uint8_t *) buf + len;
820     /* we support LF and CRLF line endings */
821     while (ch < end) {
822         /* continue if not reached LF */
823         if (*ch != CH_LF) {
824             if (*ch != CH_CR && param->stripped_crs > 0) {
825                 while (param->stripped_crs--) {
826                     pgp_hash_list_update(param->txt_hashes, ST_CR, 1);
827                 }
828                 param->stripped_crs = 0;
829             }
830 
831             if (!param->max_line_warn && param->text_line_len >= MAXIMUM_GNUPG_LINELEN) {
832                 RNP_LOG("Canonical text document signature: line is too long, may cause "
833                         "incompatibility with other implementations. Consider using binary "
834                         "signature instead.");
835                 param->max_line_warn = true;
836             }
837 
838             ch++;
839             param->text_line_len++;
840             continue;
841         }
842         /* reached eol: dump line contents */
843         param->stripped_crs = 0;
844         param->text_line_len = 0;
845         if (ch > linebeg) {
846             long stripped_len = stripped_line_len(linebeg, ch);
847             if (stripped_len > 0) {
848                 pgp_hash_list_update(param->txt_hashes, linebeg, stripped_len);
849             }
850         }
851         /* dump EOL */
852         pgp_hash_list_update(param->txt_hashes, ST_CRLF, 2);
853 
854         ch++;
855         linebeg = ch;
856     }
857     /* check if we have undumped line contents */
858     if (linebeg < end) {
859         long stripped_len = stripped_line_len(linebeg, end - 1);
860         if (stripped_len < end - linebeg) {
861             param->stripped_crs = end - linebeg - stripped_len;
862         }
863         if (stripped_len > 0) {
864             pgp_hash_list_update(param->txt_hashes, linebeg, stripped_len);
865         }
866     }
867 }
868 
869 static bool
signed_src_read(pgp_source_t * src,void * buf,size_t len,size_t * read)870 signed_src_read(pgp_source_t *src, void *buf, size_t len, size_t *read)
871 {
872     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
873     if (!param) {
874         return false;
875     }
876     return src_read(param->readsrc, buf, len, read);
877 }
878 
879 static void
signed_src_close(pgp_source_t * src)880 signed_src_close(pgp_source_t *src)
881 {
882     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
883     if (!param) {
884         return;
885     }
886     delete param;
887     src->param = NULL;
888 }
889 
890 static rnp_result_t
signed_read_single_signature(pgp_source_signed_param_t * param,pgp_source_t * readsrc,pgp_signature_t ** sig)891 signed_read_single_signature(pgp_source_signed_param_t *param,
892                              pgp_source_t *             readsrc,
893                              pgp_signature_t **         sig)
894 {
895     uint8_t ptag;
896     if (!src_peek_eq(readsrc, &ptag, 1)) {
897         RNP_LOG("failed to read signature packet header");
898         return RNP_ERROR_READ;
899     }
900 
901     int ptype = get_packet_type(ptag);
902     if (ptype != PGP_PKT_SIGNATURE) {
903         RNP_LOG("unexpected packet %d", ptype);
904         return RNP_ERROR_BAD_FORMAT;
905     }
906 
907     try {
908         param->siginfos.emplace_back();
909         pgp_signature_info_t &siginfo = param->siginfos.back();
910         pgp_signature_t       readsig;
911         if (readsig.parse(*readsrc)) {
912             RNP_LOG("failed to parse signature");
913             siginfo.unknown = true;
914             if (sig) {
915                 *sig = NULL;
916             }
917             return RNP_SUCCESS;
918         }
919         param->sigs.push_back(std::move(readsig));
920         siginfo.sig = &param->sigs.back();
921         if (sig) {
922             *sig = siginfo.sig;
923         }
924         return RNP_SUCCESS;
925     } catch (const std::exception &e) {
926         RNP_LOG("%s", e.what());
927         return RNP_ERROR_OUT_OF_MEMORY;
928     }
929 }
930 
931 static rnp_result_t
signed_read_cleartext_signatures(pgp_source_t * src)932 signed_read_cleartext_signatures(pgp_source_t *src)
933 {
934     pgp_source_t               armor = {0};
935     rnp_result_t               ret = RNP_ERROR_BAD_FORMAT;
936     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
937 
938     if ((ret = init_armored_src(&armor, param->readsrc)) != RNP_SUCCESS) {
939         return ret;
940     }
941 
942     while (!src_eof(&armor)) {
943         if ((ret = signed_read_single_signature(param, &armor, NULL)) != RNP_SUCCESS) {
944             goto finish;
945         }
946     }
947 
948     ret = RNP_SUCCESS;
949 
950 finish:
951     src_close(&armor);
952     return ret;
953 }
954 
955 static rnp_result_t
signed_read_signatures(pgp_source_t * src)956 signed_read_signatures(pgp_source_t *src)
957 {
958     pgp_signature_t *          sig = NULL;
959     rnp_result_t               ret;
960     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
961 
962     /* reading signatures */
963     for (auto op = param->onepasses.rbegin(); op != param->onepasses.rend(); op++) {
964         if ((ret = signed_read_single_signature(param, src, &sig)) != RNP_SUCCESS) {
965             return ret;
966         }
967 
968         if (!sig || !sig->matches_onepass(*op)) {
969             RNP_LOG("signature doesn't match one-pass");
970             return RNP_ERROR_BAD_FORMAT;
971         }
972     }
973 
974     return RNP_SUCCESS;
975 }
976 
977 static rnp_result_t
signed_src_finish(pgp_source_t * src)978 signed_src_finish(pgp_source_t *src)
979 {
980     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
981     pgp_key_request_ctx_t      keyctx;
982     pgp_key_t *                key = NULL;
983     rnp_result_t               ret = RNP_ERROR_GENERIC;
984 
985     if (param->cleartext) {
986         ret = signed_read_cleartext_signatures(src);
987     } else {
988         ret = signed_read_signatures(src);
989     }
990 
991     if (ret != RNP_SUCCESS) {
992         return ret;
993     }
994 
995     if (!src_eof(src)) {
996         RNP_LOG("warning: unexpected data on the stream end");
997     }
998 
999     /* validating signatures */
1000     keyctx.op = PGP_OP_VERIFY;
1001     keyctx.search.type = PGP_KEY_SEARCH_KEYID;
1002 
1003     for (auto &sinfo : param->siginfos) {
1004         if (!sinfo.sig) {
1005             continue;
1006         }
1007 
1008         /* we need public key, however may fallback to secret later on */
1009         keyctx.secret = false;
1010 
1011         /* Get the key id */
1012         if (!sinfo.sig->has_keyid()) {
1013             RNP_LOG("cannot get signer's key id from signature");
1014             sinfo.unknown = true;
1015             continue;
1016         }
1017         keyctx.search.by.keyid = sinfo.sig->keyid();
1018 
1019         /* Get the public key */
1020         if (!(key = pgp_request_key(param->handler->key_provider, &keyctx))) {
1021             // fallback to secret key
1022             keyctx.secret = true;
1023             if (!(key = pgp_request_key(param->handler->key_provider, &keyctx))) {
1024                 RNP_LOG("signer's key not found");
1025                 sinfo.no_signer = true;
1026                 continue;
1027             }
1028         }
1029         sinfo.signer = key;
1030         /* validate signature */
1031         signed_validate_signature(param, &sinfo);
1032     }
1033 
1034     /* checking the validation results */
1035     ret = RNP_SUCCESS;
1036     for (auto &sinfo : param->siginfos) {
1037         if (sinfo.no_signer && param->handler->ctx->discard) {
1038             /* if output is discarded then we interested in verification */
1039             ret = RNP_ERROR_SIGNATURE_INVALID;
1040             continue;
1041         }
1042         if (!sinfo.no_signer && (!sinfo.valid || (sinfo.expired))) {
1043             /* do not report error if signer not found */
1044             ret = RNP_ERROR_SIGNATURE_INVALID;
1045         }
1046     }
1047 
1048     /* call the callback with signature infos */
1049     if (param->handler->on_signatures) {
1050         param->handler->on_signatures(param->siginfos, param->handler->param);
1051     }
1052     return ret;
1053 }
1054 
1055 /*
1056  * str is a string to tokenize.
1057  * delims is a string containing a list of delimiter characters.
1058  * result is a container<string_type> that supports push_back.
1059  */
1060 template <typename T>
1061 static void
tokenize(const typename T::value_type & str,const typename T::value_type & delims,T & result)1062 tokenize(const typename T::value_type &str, const typename T::value_type &delims, T &result)
1063 {
1064     typedef typename T::value_type::size_type string_size_t;
1065     const string_size_t                       npos = T::value_type::npos;
1066 
1067     result.clear();
1068     string_size_t current;
1069     string_size_t next = 0;
1070     do {
1071         next = str.find_first_not_of(delims, next);
1072         if (next == npos) {
1073             break;
1074         }
1075         current = next;
1076         next = str.find_first_of(delims, current);
1077         string_size_t count = (next == npos) ? npos : (next - current);
1078         result.push_back(str.substr(current, count));
1079     } while (next != npos);
1080 }
1081 
1082 static bool
cleartext_parse_headers(pgp_source_t * src)1083 cleartext_parse_headers(pgp_source_t *src)
1084 {
1085     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
1086     char                       hdr[1024] = {0};
1087     char *                     hval;
1088     pgp_hash_alg_t             halg;
1089     size_t                     hdrlen;
1090 
1091     do {
1092         if (!src_peek_line(param->readsrc, hdr, sizeof(hdr), &hdrlen)) {
1093             RNP_LOG("failed to peek line");
1094             return false;
1095         }
1096 
1097         if (!hdrlen) {
1098             break;
1099         }
1100 
1101         if (rnp_is_blank_line(hdr, hdrlen)) {
1102             src_skip(param->readsrc, hdrlen);
1103             break;
1104         }
1105 
1106         if ((hdrlen >= 6) && !strncmp(hdr, ST_HEADER_HASH, 6)) {
1107             hval = hdr + 6;
1108 
1109             std::string remainder = hval;
1110 
1111             const std::string        delimiters = ", \t";
1112             std::vector<std::string> tokens;
1113 
1114             tokenize(remainder, delimiters, tokens);
1115 
1116             for (const auto &token : tokens) {
1117                 if ((halg = pgp_str_to_hash_alg(token.c_str())) == PGP_HASH_UNKNOWN) {
1118                     RNP_LOG("unknown halg: %s", token.c_str());
1119                 }
1120                 add_hash_for_sig(param, PGP_SIG_TEXT, halg);
1121             }
1122         } else {
1123             RNP_LOG("unknown header '%s'", hdr);
1124         }
1125 
1126         src_skip(param->readsrc, hdrlen);
1127 
1128         if (!src_skip_eol(param->readsrc)) {
1129             return false;
1130         }
1131     } while (1);
1132 
1133     /* we have exactly one empty line after the headers */
1134     return src_skip_eol(param->readsrc);
1135 }
1136 
1137 static void
cleartext_process_line(pgp_source_t * src,const uint8_t * buf,size_t len,bool eol)1138 cleartext_process_line(pgp_source_t *src, const uint8_t *buf, size_t len, bool eol)
1139 {
1140     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
1141     uint8_t *                  bufen = (uint8_t *) buf + len - 1;
1142 
1143     /* check for dashes only if we are not in the middle */
1144     if (!param->clr_mline && (len > 0) && (buf[0] == CH_DASH)) {
1145         if ((len > 1) && (buf[1] == CH_SPACE)) {
1146             buf += 2;
1147             len -= 2;
1148         } else if ((len > 5) && !memcmp(buf, ST_DASHES, 5)) {
1149             param->clr_eod = true;
1150             return;
1151         } else {
1152             RNP_LOG("dash at the line begin");
1153         }
1154     }
1155 
1156     /* hash eol if it is not the first line and we are not in the middle */
1157     if (!param->clr_fline && !param->clr_mline) {
1158         /* we hash \r\n after the previous line to not hash the last eol before the sig */
1159         signed_src_update(src, ST_CRLF, 2);
1160     }
1161 
1162     if (!len) {
1163         return;
1164     }
1165 
1166     if (len + param->outlen > sizeof(param->out)) {
1167         RNP_LOG("wrong state");
1168         return;
1169     }
1170 
1171     /* if we have eol after this line then strip trailing spaces and tabs */
1172     if (eol) {
1173         for (; (bufen >= buf) &&
1174                ((*bufen == CH_SPACE) || (*bufen == CH_TAB) || (*bufen == CH_CR));
1175              bufen--)
1176             ;
1177     }
1178 
1179     if ((len = bufen + 1 - buf)) {
1180         memcpy(param->out + param->outlen, buf, len);
1181         param->outlen += len;
1182         signed_src_update(src, buf, len);
1183     }
1184 }
1185 
1186 static bool
cleartext_src_read(pgp_source_t * src,void * buf,size_t len,size_t * readres)1187 cleartext_src_read(pgp_source_t *src, void *buf, size_t len, size_t *readres)
1188 {
1189     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
1190     if (!param) {
1191         return false;
1192     }
1193 
1194     uint8_t  srcb[CT_BUF_LEN];
1195     uint8_t *cur, *en, *bg;
1196     size_t   read = 0;
1197     size_t   origlen = len;
1198 
1199     read = param->outlen - param->outpos;
1200     if (read >= len) {
1201         memcpy(buf, param->out + param->outpos, len);
1202         param->outpos += len;
1203         if (param->outpos == param->outlen) {
1204             param->outpos = param->outlen = 0;
1205         }
1206         *readres = len;
1207         return true;
1208     } else if (read > 0) {
1209         memcpy(buf, param->out + param->outpos, read);
1210         len -= read;
1211         buf = (uint8_t *) buf + read;
1212         param->outpos = param->outlen = 0;
1213     }
1214 
1215     if (param->clr_eod) {
1216         *readres = origlen - len;
1217         return true;
1218     }
1219 
1220     do {
1221         if (!src_peek(param->readsrc, srcb, sizeof(srcb), &read)) {
1222             return false;
1223         } else if (!read) {
1224             break;
1225         }
1226 
1227         /* processing data line by line, eol could be \n or \r\n */
1228         for (cur = srcb, bg = srcb, en = cur + read; cur < en; cur++) {
1229             if ((*cur == CH_LF) ||
1230                 ((*cur == CH_CR) && (cur + 1 < en) && (*(cur + 1) == CH_LF))) {
1231                 cleartext_process_line(src, bg, cur - bg, true);
1232                 /* processing eol */
1233                 if (param->clr_eod) {
1234                     break;
1235                 }
1236 
1237                 /* processing eol */
1238                 param->clr_fline = false;
1239                 param->clr_mline = false;
1240                 if (*cur == CH_CR) {
1241                     param->out[param->outlen++] = *cur++;
1242                 }
1243                 param->out[param->outlen++] = *cur;
1244                 bg = cur + 1;
1245             }
1246         }
1247 
1248         /* if line is larger then 4k then just dump it out */
1249         if ((bg == srcb) && !param->clr_eod) {
1250             /* if last char is \r then do not dump it */
1251             if ((en > bg) && (*(en - 1) == CH_CR)) {
1252                 en--;
1253             }
1254             cleartext_process_line(src, bg, en - bg, false);
1255             param->clr_mline = true;
1256             bg = en;
1257         }
1258         src_skip(param->readsrc, bg - srcb);
1259 
1260         /* put data from the param->out to buf */
1261         read = param->outlen > len ? len : param->outlen;
1262         memcpy(buf, param->out, read);
1263         buf = (uint8_t *) buf + read;
1264         len -= read;
1265 
1266         if (read == param->outlen) {
1267             param->outlen = 0;
1268         } else {
1269             param->outpos = read;
1270         }
1271 
1272         /* we got to the signature marker */
1273         if (param->clr_eod || !len) {
1274             break;
1275         }
1276     } while (1);
1277 
1278     *readres = origlen - len;
1279     return true;
1280 }
1281 
1282 static bool
encrypted_decrypt_cfb_header(pgp_source_encrypted_param_t * param,pgp_symm_alg_t alg,uint8_t * key)1283 encrypted_decrypt_cfb_header(pgp_source_encrypted_param_t *param,
1284                              pgp_symm_alg_t                alg,
1285                              uint8_t *                     key)
1286 {
1287     pgp_crypt_t crypt;
1288     uint8_t     enchdr[PGP_MAX_BLOCK_SIZE + 2];
1289     uint8_t     dechdr[PGP_MAX_BLOCK_SIZE + 2];
1290     unsigned    blsize;
1291 
1292     if (!(blsize = pgp_block_size(alg))) {
1293         return false;
1294     }
1295 
1296     /* reading encrypted header to check the password validity */
1297     if (!src_peek_eq(param->pkt.readsrc, enchdr, blsize + 2)) {
1298         RNP_LOG("failed to read encrypted header");
1299         return false;
1300     }
1301 
1302     /* having symmetric key in keybuf let's decrypt blocksize + 2 bytes and check them */
1303     if (!pgp_cipher_cfb_start(&crypt, alg, key, NULL)) {
1304         RNP_LOG("failed to start cipher");
1305         return false;
1306     }
1307 
1308     pgp_cipher_cfb_decrypt(&crypt, dechdr, enchdr, blsize + 2);
1309 
1310     if ((dechdr[blsize] != dechdr[blsize - 2]) || (dechdr[blsize + 1] != dechdr[blsize - 1])) {
1311         RNP_LOG("checksum check failed");
1312         goto error;
1313     }
1314 
1315     src_skip(param->pkt.readsrc, blsize + 2);
1316     param->decrypt = crypt;
1317 
1318     /* init mdc if it is here */
1319     /* RFC 4880, 5.13: Unlike the Symmetrically Encrypted Data Packet, no special CFB
1320      * resynchronization is done after encrypting this prefix data. */
1321     if (!param->has_mdc) {
1322         pgp_cipher_cfb_resync(&param->decrypt, enchdr + 2);
1323         return true;
1324     }
1325 
1326     if (!pgp_hash_create(&param->mdc, PGP_HASH_SHA1)) {
1327         RNP_LOG("cannot create sha1 hash");
1328         goto error;
1329     }
1330 
1331     pgp_hash_add(&param->mdc, dechdr, blsize + 2);
1332     return true;
1333 
1334 error:
1335     pgp_cipher_cfb_finish(&crypt);
1336     return false;
1337 }
1338 
1339 static bool
encrypted_start_aead(pgp_source_encrypted_param_t * param,pgp_symm_alg_t alg,uint8_t * key)1340 encrypted_start_aead(pgp_source_encrypted_param_t *param, pgp_symm_alg_t alg, uint8_t *key)
1341 {
1342     size_t gran;
1343 
1344     if (alg != param->aead_hdr.ealg) {
1345         return false;
1346     }
1347 
1348     /* initialize cipher with key */
1349     if (!pgp_cipher_aead_init(
1350           &param->decrypt, param->aead_hdr.ealg, param->aead_hdr.aalg, key, true)) {
1351         return false;
1352     }
1353 
1354     gran = pgp_cipher_aead_granularity(&param->decrypt);
1355     if (gran > sizeof(param->cache)) {
1356         RNP_LOG("wrong granularity");
1357         return false;
1358     }
1359 
1360     return encrypted_start_aead_chunk(param, 0, false);
1361 }
1362 
1363 static bool
encrypted_try_key(pgp_source_encrypted_param_t * param,pgp_pk_sesskey_t * sesskey,pgp_key_pkt_t * seckey,rng_t * rng)1364 encrypted_try_key(pgp_source_encrypted_param_t *param,
1365                   pgp_pk_sesskey_t *            sesskey,
1366                   pgp_key_pkt_t *               seckey,
1367                   rng_t *                       rng)
1368 {
1369     pgp_encrypted_material_t encmaterial;
1370     try {
1371         if (!sesskey->parse_material(encmaterial)) {
1372             return false;
1373         }
1374     } catch (const std::exception &e) {
1375         RNP_LOG("%s", e.what());
1376         return false;
1377     }
1378 
1379     rnp::secure_array<uint8_t, PGP_MPINT_SIZE> decbuf;
1380     /* Decrypting session key value */
1381     rnp_result_t        err;
1382     bool                res = false;
1383     pgp_key_material_t *keymaterial = &seckey->material;
1384     size_t              declen = 0;
1385     switch (sesskey->alg) {
1386     case PGP_PKA_RSA:
1387     case PGP_PKA_RSA_ENCRYPT_ONLY:
1388         err =
1389           rsa_decrypt_pkcs1(rng, decbuf.data(), &declen, &encmaterial.rsa, &keymaterial->rsa);
1390         if (err) {
1391             RNP_LOG("RSA decryption failure");
1392             return false;
1393         }
1394         break;
1395     case PGP_PKA_SM2:
1396         declen = decbuf.size();
1397         err = sm2_decrypt(decbuf.data(), &declen, &encmaterial.sm2, &keymaterial->ec);
1398         if (err != RNP_SUCCESS) {
1399             RNP_LOG("SM2 decryption failure, error %x", (int) err);
1400             return false;
1401         }
1402         break;
1403     case PGP_PKA_ELGAMAL:
1404     case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN: {
1405         const rnp_result_t ret = elgamal_decrypt_pkcs1(
1406           rng, decbuf.data(), &declen, &encmaterial.eg, &keymaterial->eg);
1407         if (ret) {
1408             RNP_LOG("ElGamal decryption failure [%X]", ret);
1409             return false;
1410         }
1411         break;
1412     }
1413     case PGP_PKA_ECDH: {
1414         pgp_fingerprint_t fingerprint;
1415         if (pgp_fingerprint(fingerprint, *seckey)) {
1416             RNP_LOG("ECDH fingerprint calculation failed");
1417             return false;
1418         }
1419         declen = decbuf.size();
1420         err = ecdh_decrypt_pkcs5(
1421           decbuf.data(), &declen, &encmaterial.ecdh, &keymaterial->ec, fingerprint);
1422         if (err != RNP_SUCCESS) {
1423             RNP_LOG("ECDH decryption error %u", err);
1424             return false;
1425         }
1426         break;
1427     }
1428     default:
1429         RNP_LOG("unsupported public key algorithm %d\n", seckey->alg);
1430         return false;
1431     }
1432 
1433     /* Check algorithm and key length */
1434     pgp_symm_alg_t salg = (pgp_symm_alg_t) decbuf[0];
1435     if (!pgp_is_sa_supported(salg)) {
1436         RNP_LOG("unsupported symmetric algorithm %d", (int) salg);
1437         return false;
1438     }
1439 
1440     size_t keylen = pgp_key_size(salg);
1441     if (declen != keylen + 3) {
1442         RNP_LOG("invalid symmetric key length");
1443         return false;
1444     }
1445 
1446     /* Validate checksum */
1447     rnp::secure_array<unsigned, 1> checksum;
1448     for (unsigned i = 1; i <= keylen; i++) {
1449         checksum[0] += decbuf[i];
1450     }
1451 
1452     if ((checksum[0] & 0xffff) !=
1453         (decbuf[keylen + 2] | ((unsigned) decbuf[keylen + 1] << 8))) {
1454         RNP_LOG("wrong checksum\n");
1455         return false;
1456     }
1457 
1458     if (!param->aead) {
1459         /* Decrypt header */
1460         res = encrypted_decrypt_cfb_header(param, salg, &decbuf[1]);
1461     } else {
1462         /* Start AEAD decrypting, assuming we have correct key */
1463         res = encrypted_start_aead(param, salg, &decbuf[1]);
1464     }
1465     if (res) {
1466         param->salg = salg;
1467     }
1468     return res;
1469 }
1470 
1471 static bool
encrypted_sesk_set_ad(pgp_crypt_t * crypt,pgp_sk_sesskey_t * skey)1472 encrypted_sesk_set_ad(pgp_crypt_t *crypt, pgp_sk_sesskey_t *skey)
1473 {
1474     /* TODO: this method is exact duplicate as in stream-write.c. Not sure where to put it */
1475     uint8_t ad_data[4];
1476 
1477     ad_data[0] = PGP_PKT_SK_SESSION_KEY | PGP_PTAG_ALWAYS_SET | PGP_PTAG_NEW_FORMAT;
1478     ad_data[1] = skey->version;
1479     ad_data[2] = skey->alg;
1480     ad_data[3] = skey->aalg;
1481 
1482     RNP_DHEX("sesk ad: ", ad_data, 4);
1483     return pgp_cipher_aead_set_ad(crypt, ad_data, 4);
1484 }
1485 
1486 static int
encrypted_try_password(pgp_source_encrypted_param_t * param,const char * password)1487 encrypted_try_password(pgp_source_encrypted_param_t *param, const char *password)
1488 {
1489     bool keyavail = false; /* tried password at least once */
1490 
1491     for (auto &skey : param->symencs) {
1492         rnp::secure_array<uint8_t, PGP_MAX_KEY_SIZE + 1> keybuf;
1493         /* deriving symmetric key from password */
1494         size_t keysize = pgp_key_size(skey.alg);
1495         if (!keysize || !pgp_s2k_derive_key(&skey.s2k, password, keybuf.data(), keysize)) {
1496             continue;
1497         }
1498         RNP_DHEX("derived key: ", keybuf.data(), keysize);
1499         pgp_crypt_t    crypt;
1500         pgp_symm_alg_t alg;
1501 
1502         if (skey.version == PGP_SKSK_V4) {
1503             /* v4 symmetrically-encrypted session key */
1504             if (skey.enckeylen > 0) {
1505                 /* decrypting session key */
1506                 if (!pgp_cipher_cfb_start(&crypt, skey.alg, keybuf.data(), NULL)) {
1507                     continue;
1508                 }
1509 
1510                 pgp_cipher_cfb_decrypt(&crypt, keybuf.data(), skey.enckey, skey.enckeylen);
1511                 pgp_cipher_cfb_finish(&crypt);
1512 
1513                 alg = (pgp_symm_alg_t) keybuf[0];
1514                 keysize = pgp_key_size(alg);
1515                 if (!keysize || (keysize + 1 != skey.enckeylen)) {
1516                     continue;
1517                 }
1518                 memmove(keybuf.data(), keybuf.data() + 1, keysize);
1519             } else {
1520                 alg = (pgp_symm_alg_t) skey.alg;
1521             }
1522 
1523             if (!pgp_block_size(alg)) {
1524                 continue;
1525             }
1526             keyavail = true;
1527         } else if (skey.version == PGP_SKSK_V5) {
1528             /* v5 AEAD-encrypted session key */
1529             size_t  taglen = pgp_cipher_aead_tag_len(skey.aalg);
1530             uint8_t nonce[PGP_AEAD_MAX_NONCE_LEN];
1531             size_t  noncelen;
1532 
1533             if (!taglen || (keysize != skey.enckeylen - taglen)) {
1534                 continue;
1535             }
1536             alg = skey.alg;
1537 
1538             /* initialize cipher */
1539             if (!pgp_cipher_aead_init(&crypt, skey.alg, skey.aalg, keybuf.data(), true)) {
1540                 continue;
1541             }
1542 
1543             /* set additional data */
1544             if (!encrypted_sesk_set_ad(&crypt, &skey)) {
1545                 RNP_LOG("failed to set ad");
1546                 continue;
1547             }
1548 
1549             /* calculate nonce */
1550             noncelen = pgp_cipher_aead_nonce(skey.aalg, skey.iv, nonce, 0);
1551 
1552             RNP_DHEX("nonce: ", nonce, noncelen);
1553             RNP_DHEX("encrypted key: ", skey.enckey, skey.enckeylen);
1554 
1555             /* start cipher, decrypt key and verify tag */
1556             keyavail = pgp_cipher_aead_start(&crypt, nonce, noncelen);
1557             bool decres = keyavail && pgp_cipher_aead_finish(
1558                                         &crypt, keybuf.data(), skey.enckey, skey.enckeylen);
1559 
1560             if (decres) {
1561                 RNP_DHEX("decrypted key: ", keybuf.data(), pgp_key_size(param->aead_hdr.ealg));
1562             }
1563 
1564             pgp_cipher_aead_destroy(&crypt);
1565 
1566             /* we have decrypted key so let's start decryption */
1567             if (!keyavail || !decres) {
1568                 continue;
1569             }
1570         } else {
1571             continue;
1572         }
1573 
1574         /* Decrypt header for CFB */
1575         if (!param->aead && !encrypted_decrypt_cfb_header(param, alg, keybuf.data())) {
1576             continue;
1577         }
1578         if (param->aead && !encrypted_start_aead(param, param->aead_hdr.ealg, keybuf.data())) {
1579             continue;
1580         }
1581 
1582         param->salg = param->aead ? param->aead_hdr.ealg : alg;
1583         /* inform handler that we used this symenc */
1584         if (param->handler->on_decryption_start) {
1585             param->handler->on_decryption_start(NULL, &skey, param->handler->param);
1586         }
1587         return 1;
1588     }
1589 
1590     if (!keyavail) {
1591         RNP_LOG("no supported sk available");
1592         return -1;
1593     }
1594     return 0;
1595 }
1596 
1597 /** @brief Initialize common to stream packets params, including partial data source */
1598 static rnp_result_t
init_packet_params(pgp_source_packet_param_t * param)1599 init_packet_params(pgp_source_packet_param_t *param)
1600 {
1601     pgp_source_t *partsrc;
1602     rnp_result_t  errcode;
1603 
1604     param->origsrc = NULL;
1605 
1606     /* save packet header */
1607     if (!stream_pkt_hdr_len(param->readsrc, &param->hdrlen)) {
1608         return RNP_ERROR_BAD_FORMAT;
1609     }
1610     if (!src_peek_eq(param->readsrc, param->hdr, param->hdrlen)) {
1611         return RNP_ERROR_READ;
1612     }
1613 
1614     /* initialize partial reader if needed */
1615     if (stream_partial_pkt_len(param->readsrc)) {
1616         if ((partsrc = (pgp_source_t *) calloc(1, sizeof(*partsrc))) == NULL) {
1617             return RNP_ERROR_OUT_OF_MEMORY;
1618         }
1619         errcode = init_partial_pkt_src(partsrc, param->readsrc);
1620         if (errcode != RNP_SUCCESS) {
1621             free(partsrc);
1622             return errcode;
1623         }
1624         param->partial = true;
1625         param->origsrc = param->readsrc;
1626         param->readsrc = partsrc;
1627     } else if (stream_old_indeterminate_pkt_len(param->readsrc)) {
1628         param->indeterminate = true;
1629         src_skip(param->readsrc, 1);
1630     } else {
1631         if (!stream_read_pkt_len(param->readsrc, &param->len)) {
1632             RNP_LOG("cannot read pkt len");
1633             return RNP_ERROR_BAD_FORMAT;
1634         }
1635     }
1636     return RNP_SUCCESS;
1637 }
1638 
1639 rnp_result_t
init_literal_src(pgp_source_t * src,pgp_source_t * readsrc)1640 init_literal_src(pgp_source_t *src, pgp_source_t *readsrc)
1641 {
1642     rnp_result_t                ret = RNP_ERROR_GENERIC;
1643     pgp_source_literal_param_t *param;
1644     uint8_t                     bt;
1645     uint8_t                     tstbuf[4];
1646 
1647     if (!init_src_common(src, sizeof(*param))) {
1648         return RNP_ERROR_OUT_OF_MEMORY;
1649     }
1650 
1651     param = (pgp_source_literal_param_t *) src->param;
1652     param->pkt.readsrc = readsrc;
1653     src->read = literal_src_read;
1654     src->close = literal_src_close;
1655     src->type = PGP_STREAM_LITERAL;
1656 
1657     /* Reading packet length/checking whether it is partial */
1658     if ((ret = init_packet_params(&param->pkt))) {
1659         goto finish;
1660     }
1661 
1662     /* data format */
1663     if (!src_read_eq(param->pkt.readsrc, &bt, 1)) {
1664         RNP_LOG("failed to read data format");
1665         ret = RNP_ERROR_READ;
1666         goto finish;
1667     }
1668 
1669     switch (bt) {
1670     case 'b':
1671     case 't':
1672     case 'u':
1673     case 'l':
1674     case '1':
1675         break;
1676     default:
1677         RNP_LOG("unknown data format %d", (int) bt);
1678         ret = RNP_ERROR_BAD_FORMAT;
1679         goto finish;
1680     }
1681     param->hdr.format = bt;
1682     /* file name */
1683     if (!src_read_eq(param->pkt.readsrc, &bt, 1)) {
1684         RNP_LOG("failed to read file name length");
1685         ret = RNP_ERROR_READ;
1686         goto finish;
1687     }
1688     if ((bt > 0) && !src_read_eq(param->pkt.readsrc, param->hdr.fname, bt)) {
1689         RNP_LOG("failed to read file name");
1690         ret = RNP_ERROR_READ;
1691         goto finish;
1692     }
1693     param->hdr.fname[bt] = 0;
1694     param->hdr.fname_len = bt;
1695     /* timestamp */
1696     if (!src_read_eq(param->pkt.readsrc, tstbuf, 4)) {
1697         RNP_LOG("failed to read file timestamp");
1698         ret = RNP_ERROR_READ;
1699         goto finish;
1700     }
1701 
1702     param->hdr.timestamp = ((uint32_t) tstbuf[0] << 24) | ((uint32_t) tstbuf[1] << 16) |
1703                            ((uint32_t) tstbuf[2] << 8) | (uint32_t) tstbuf[3];
1704 
1705     if (!param->pkt.indeterminate && !param->pkt.partial) {
1706         /* format filename-length filename timestamp */
1707         const uint16_t nbytes = 1 + 1 + bt + 4;
1708         if (param->pkt.len < nbytes) {
1709             ret = RNP_ERROR_BAD_FORMAT;
1710             goto finish;
1711         }
1712         src->size = param->pkt.len - nbytes;
1713         src->knownsize = 1;
1714     }
1715 
1716     ret = RNP_SUCCESS;
1717 finish:
1718     if (ret != RNP_SUCCESS) {
1719         src_close(src);
1720     }
1721     return ret;
1722 }
1723 
1724 bool
get_literal_src_hdr(pgp_source_t * src,pgp_literal_hdr_t * hdr)1725 get_literal_src_hdr(pgp_source_t *src, pgp_literal_hdr_t *hdr)
1726 {
1727     pgp_source_literal_param_t *param;
1728 
1729     if (src->type != PGP_STREAM_LITERAL) {
1730         RNP_LOG("wrong stream");
1731         return false;
1732     }
1733 
1734     param = (pgp_source_literal_param_t *) src->param;
1735     *hdr = param->hdr;
1736     return true;
1737 }
1738 
1739 rnp_result_t
init_compressed_src(pgp_source_t * src,pgp_source_t * readsrc)1740 init_compressed_src(pgp_source_t *src, pgp_source_t *readsrc)
1741 {
1742     rnp_result_t                   errcode = RNP_ERROR_GENERIC;
1743     pgp_source_compressed_param_t *param;
1744     uint8_t                        alg;
1745     int                            zret;
1746 
1747     if (!init_src_common(src, sizeof(*param))) {
1748         return RNP_ERROR_OUT_OF_MEMORY;
1749     }
1750 
1751     param = (pgp_source_compressed_param_t *) src->param;
1752     param->pkt.readsrc = readsrc;
1753     src->read = compressed_src_read;
1754     src->close = compressed_src_close;
1755     src->type = PGP_STREAM_COMPRESSED;
1756 
1757     /* Reading packet length/checking whether it is partial */
1758     errcode = init_packet_params(&param->pkt);
1759     if (errcode != RNP_SUCCESS) {
1760         goto finish;
1761     }
1762 
1763     /* Reading compression algorithm */
1764     if (!src_read_eq(param->pkt.readsrc, &alg, 1)) {
1765         RNP_LOG("failed to read compression algorithm");
1766         errcode = RNP_ERROR_READ;
1767         goto finish;
1768     }
1769 
1770     /* Initializing decompression */
1771     switch (alg) {
1772     case PGP_C_ZIP:
1773     case PGP_C_ZLIB:
1774         (void) memset(&param->z, 0x0, sizeof(param->z));
1775         zret =
1776           alg == PGP_C_ZIP ? (int) inflateInit2(&param->z, -15) : (int) inflateInit(&param->z);
1777         if (zret != Z_OK) {
1778             RNP_LOG("failed to init zlib, error %d", zret);
1779             errcode = RNP_ERROR_READ;
1780             goto finish;
1781         }
1782         break;
1783 #ifdef HAVE_BZLIB_H
1784     case PGP_C_BZIP2:
1785         (void) memset(&param->bz, 0x0, sizeof(param->bz));
1786         zret = BZ2_bzDecompressInit(&param->bz, 0, 0);
1787         if (zret != BZ_OK) {
1788             RNP_LOG("failed to init bz, error %d", zret);
1789             errcode = RNP_ERROR_READ;
1790             goto finish;
1791         }
1792         break;
1793 #endif
1794     default:
1795         RNP_LOG("unknown compression algorithm: %d", (int) alg);
1796         errcode = RNP_ERROR_BAD_FORMAT;
1797         goto finish;
1798     }
1799     param->alg = (pgp_compression_type_t) alg;
1800     param->inlen = 0;
1801     param->inpos = 0;
1802 
1803     errcode = RNP_SUCCESS;
1804 finish:
1805     if (errcode != RNP_SUCCESS) {
1806         src_close(src);
1807     }
1808     return errcode;
1809 }
1810 
1811 bool
get_compressed_src_alg(pgp_source_t * src,uint8_t * alg)1812 get_compressed_src_alg(pgp_source_t *src, uint8_t *alg)
1813 {
1814     pgp_source_compressed_param_t *param;
1815 
1816     if (src->type != PGP_STREAM_COMPRESSED) {
1817         RNP_LOG("wrong stream");
1818         return false;
1819     }
1820 
1821     param = (pgp_source_compressed_param_t *) src->param;
1822     *alg = param->alg;
1823     return true;
1824 }
1825 
1826 bool
get_aead_src_hdr(pgp_source_t * src,pgp_aead_hdr_t * hdr)1827 get_aead_src_hdr(pgp_source_t *src, pgp_aead_hdr_t *hdr)
1828 {
1829     uint8_t hdrbt[4] = {0};
1830 
1831     if (!src_read_eq(src, hdrbt, 4)) {
1832         return false;
1833     }
1834 
1835     hdr->version = hdrbt[0];
1836     hdr->ealg = (pgp_symm_alg_t) hdrbt[1];
1837     hdr->aalg = (pgp_aead_alg_t) hdrbt[2];
1838     hdr->csize = hdrbt[3];
1839 
1840     if (!(hdr->ivlen = pgp_cipher_aead_nonce_len(hdr->aalg))) {
1841         RNP_LOG("wrong aead nonce length: alg %d", (int) hdr->aalg);
1842         return false;
1843     }
1844 
1845     return src_read_eq(src, hdr->iv, hdr->ivlen);
1846 }
1847 
1848 static rnp_result_t
encrypted_read_packet_data(pgp_source_encrypted_param_t * param)1849 encrypted_read_packet_data(pgp_source_encrypted_param_t *param)
1850 {
1851     int ptype;
1852     /* Reading pk/sk encrypted session key(s) */
1853     try {
1854         bool stop = false;
1855         while (!stop) {
1856             uint8_t ptag;
1857             if (!src_peek_eq(param->pkt.readsrc, &ptag, 1)) {
1858                 RNP_LOG("failed to read packet header");
1859                 return RNP_ERROR_READ;
1860             }
1861             ptype = get_packet_type(ptag);
1862             switch (ptype) {
1863             case PGP_PKT_SK_SESSION_KEY: {
1864                 pgp_sk_sesskey_t skey;
1865                 rnp_result_t     ret = skey.parse(*param->pkt.readsrc);
1866                 if (ret) {
1867                     return ret;
1868                 }
1869                 param->symencs.push_back(skey);
1870                 break;
1871             }
1872             case PGP_PKT_PK_SESSION_KEY: {
1873                 pgp_pk_sesskey_t pkey;
1874                 rnp_result_t     ret = pkey.parse(*param->pkt.readsrc);
1875                 if (ret) {
1876                     return ret;
1877                 }
1878                 param->pubencs.push_back(pkey);
1879                 break;
1880             }
1881             case PGP_PKT_SE_DATA:
1882             case PGP_PKT_SE_IP_DATA:
1883             case PGP_PKT_AEAD_ENCRYPTED:
1884                 stop = true;
1885                 break;
1886             default:
1887                 RNP_LOG("unknown packet type: %d", ptype);
1888                 return RNP_ERROR_BAD_FORMAT;
1889             }
1890         }
1891     } catch (const rnp::rnp_exception &e) {
1892         RNP_LOG("%s: %d", e.what(), e.code());
1893         return e.code();
1894     } catch (const std::exception &e) {
1895         RNP_LOG("%s", e.what());
1896         return RNP_ERROR_GENERIC;
1897     }
1898 
1899     /* Reading packet length/checking whether it is partial */
1900     rnp_result_t errcode = init_packet_params(&param->pkt);
1901     if (errcode) {
1902         return errcode;
1903     }
1904 
1905     /* Reading header of encrypted packet */
1906     if (ptype == PGP_PKT_AEAD_ENCRYPTED) {
1907         param->aead = true;
1908         uint8_t hdr[4];
1909         if (!src_peek_eq(param->pkt.readsrc, hdr, 4)) {
1910             return RNP_ERROR_READ;
1911         }
1912 
1913         if (!get_aead_src_hdr(param->pkt.readsrc, &param->aead_hdr)) {
1914             RNP_LOG("failed to read AEAD header");
1915             return RNP_ERROR_READ;
1916         }
1917 
1918         /* check AEAD encrypted data packet header */
1919         if (param->aead_hdr.version != 1) {
1920             RNP_LOG("unknown aead ver: %d", param->aead_hdr.version);
1921             return RNP_ERROR_BAD_FORMAT;
1922         }
1923         if ((param->aead_hdr.aalg != PGP_AEAD_EAX) && (param->aead_hdr.aalg != PGP_AEAD_OCB)) {
1924             RNP_LOG("unknown aead alg: %d", (int) param->aead_hdr.aalg);
1925             return RNP_ERROR_BAD_FORMAT;
1926         }
1927         if (param->aead_hdr.csize > 56) {
1928             RNP_LOG("too large chunk size: %d", param->aead_hdr.csize);
1929             return RNP_ERROR_BAD_FORMAT;
1930         }
1931         param->chunklen = 1L << (param->aead_hdr.csize + 6);
1932 
1933         /* build additional data */
1934         param->aead_adlen = 13;
1935         param->aead_ad[0] = param->pkt.hdr[0];
1936         memcpy(param->aead_ad + 1, hdr, 4);
1937         memset(param->aead_ad + 5, 0, 8);
1938     } else if (ptype == PGP_PKT_SE_IP_DATA) {
1939         uint8_t mdcver;
1940         if (!src_read_eq(param->pkt.readsrc, &mdcver, 1)) {
1941             return RNP_ERROR_READ;
1942         }
1943 
1944         if (mdcver != 1) {
1945             RNP_LOG("unknown mdc ver: %d", (int) mdcver);
1946             return RNP_ERROR_BAD_FORMAT;
1947         }
1948         param->has_mdc = true;
1949         param->mdc_validated = false;
1950     }
1951 
1952     return RNP_SUCCESS;
1953 }
1954 
1955 static rnp_result_t
init_encrypted_src(pgp_parse_handler_t * handler,pgp_source_t * src,pgp_source_t * readsrc)1956 init_encrypted_src(pgp_parse_handler_t *handler, pgp_source_t *src, pgp_source_t *readsrc)
1957 {
1958     rnp_result_t                  errcode = RNP_ERROR_GENERIC;
1959     pgp_source_encrypted_param_t *param;
1960     pgp_key_t *                   seckey = NULL;
1961     pgp_key_pkt_t *               decrypted_seckey = NULL;
1962     int                           intres;
1963     bool                          have_key = false;
1964 
1965     if (!init_src_common(src, 0)) {
1966         return RNP_ERROR_OUT_OF_MEMORY;
1967     }
1968     try {
1969         param = new pgp_source_encrypted_param_t();
1970     } catch (const std::exception &e) {
1971         RNP_LOG("%s", e.what());
1972         return RNP_ERROR_OUT_OF_MEMORY;
1973     }
1974     src->param = param;
1975     param->pkt.readsrc = readsrc;
1976     param->handler = handler;
1977 
1978     src->close = encrypted_src_close;
1979     src->finish = encrypted_src_finish;
1980     src->type = PGP_STREAM_ENCRYPTED;
1981 
1982     /* Read the packet-related information */
1983     errcode = encrypted_read_packet_data(param);
1984     if (errcode != RNP_SUCCESS) {
1985         goto finish;
1986     }
1987 
1988     src->read = param->aead ? encrypted_src_read_aead : encrypted_src_read_cfb;
1989 
1990     /* Obtaining the symmetric key */
1991     have_key = false;
1992 
1993     if (!handler->password_provider) {
1994         RNP_LOG("no password provider");
1995         errcode = RNP_ERROR_BAD_PARAMETERS;
1996         goto finish;
1997     }
1998 
1999     /* informing handler about the available pubencs/symencs */
2000     if (handler->on_recipients) {
2001         handler->on_recipients(param->pubencs, param->symencs, handler->param);
2002     }
2003 
2004     /* Trying public-key decryption */
2005     if (!param->pubencs.empty()) {
2006         if (!handler->key_provider) {
2007             RNP_LOG("no key provider");
2008             errcode = RNP_ERROR_BAD_PARAMETERS;
2009             goto finish;
2010         }
2011 
2012         pgp_key_request_ctx_t keyctx = {};
2013         keyctx.op = PGP_OP_DECRYPT_SYM;
2014         keyctx.secret = true;
2015         keyctx.search.type = PGP_KEY_SEARCH_KEYID;
2016 
2017         for (auto &pubenc : param->pubencs) {
2018             keyctx.search.by.keyid = pubenc.key_id;
2019             /* Get the key if any */
2020             if (!(seckey = pgp_request_key(handler->key_provider, &keyctx))) {
2021                 errcode = RNP_ERROR_NO_SUITABLE_KEY;
2022                 continue;
2023             }
2024             /* Decrypt key */
2025             if (seckey->encrypted()) {
2026                 pgp_password_ctx_t pass_ctx{.op = PGP_OP_DECRYPT, .key = seckey};
2027                 decrypted_seckey =
2028                   pgp_decrypt_seckey(seckey, handler->password_provider, &pass_ctx);
2029                 if (!decrypted_seckey) {
2030                     errcode = RNP_ERROR_BAD_PASSWORD;
2031                     continue;
2032                 }
2033             } else {
2034                 decrypted_seckey = &seckey->pkt();
2035             }
2036 
2037             /* Try to initialize the decryption */
2038             if (encrypted_try_key(
2039                   param, &pubenc, decrypted_seckey, rnp_ctx_rng_handle(handler->ctx))) {
2040                 have_key = true;
2041                 /* inform handler that we used this pubenc */
2042                 if (handler->on_decryption_start) {
2043                     handler->on_decryption_start(&pubenc, NULL, handler->param);
2044                 }
2045             }
2046 
2047             /* Destroy decrypted key */
2048             if (seckey->encrypted()) {
2049                 delete decrypted_seckey;
2050                 decrypted_seckey = NULL;
2051             }
2052 
2053             if (have_key) {
2054                 break;
2055             }
2056         }
2057     }
2058 
2059     /* Trying password-based decryption */
2060     if (!have_key && !param->symencs.empty()) {
2061         rnp::secure_array<char, MAX_PASSWORD_LENGTH> password;
2062         pgp_password_ctx_t pass_ctx{.op = PGP_OP_DECRYPT_SYM, .key = NULL};
2063         if (!pgp_request_password(
2064               handler->password_provider, &pass_ctx, password.data(), password.size())) {
2065             errcode = RNP_ERROR_BAD_PASSWORD;
2066             goto finish;
2067         }
2068 
2069         intres = encrypted_try_password(param, password.data());
2070         if (intres > 0) {
2071             have_key = true;
2072         } else if (intres < 0) {
2073             errcode = RNP_ERROR_NOT_SUPPORTED;
2074         } else {
2075             errcode = RNP_ERROR_BAD_PASSWORD;
2076         }
2077     }
2078 
2079     if (!have_key) {
2080         RNP_LOG("failed to obtain decrypting key or password");
2081         if (!errcode) {
2082             errcode = RNP_ERROR_NO_SUITABLE_KEY;
2083         }
2084         goto finish;
2085     }
2086 
2087     /* report decryption start to the handler */
2088     if (handler->on_decryption_info) {
2089         handler->on_decryption_info(
2090           param->has_mdc, param->aead_hdr.aalg, param->salg, handler->param);
2091     }
2092     errcode = RNP_SUCCESS;
2093 finish:
2094     if (errcode != RNP_SUCCESS) {
2095         src_close(src);
2096     }
2097     return errcode;
2098 }
2099 
2100 static rnp_result_t
init_cleartext_signed_src(pgp_source_t * src)2101 init_cleartext_signed_src(pgp_source_t *src)
2102 {
2103     char                       buf[64];
2104     size_t                     hdrlen = strlen(ST_CLEAR_BEGIN);
2105     pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) src->param;
2106 
2107     /* checking header line */
2108     if (!src_read_eq(param->readsrc, buf, hdrlen)) {
2109         RNP_LOG("failed to read header");
2110         return RNP_ERROR_READ;
2111     }
2112 
2113     if (memcmp(ST_CLEAR_BEGIN, buf, hdrlen)) {
2114         RNP_LOG("wrong header");
2115         return RNP_ERROR_BAD_FORMAT;
2116     }
2117 
2118     /* eol */
2119     if (!src_skip_eol(param->readsrc)) {
2120         RNP_LOG("no eol after the cleartext header");
2121         return RNP_ERROR_BAD_FORMAT;
2122     }
2123 
2124     /* parsing Hash headers */
2125     if (!cleartext_parse_headers(src)) {
2126         return RNP_ERROR_BAD_FORMAT;
2127     }
2128 
2129     /* now we are good to go */
2130     param->clr_fline = true;
2131     return RNP_SUCCESS;
2132 }
2133 
~pgp_source_signed_param_t()2134 pgp_source_signed_param_t::~pgp_source_signed_param_t()
2135 {
2136     for (auto &hash : hashes) {
2137         pgp_hash_finish(&hash, NULL);
2138     }
2139     for (auto &hash : txt_hashes) {
2140         pgp_hash_finish(&hash, NULL);
2141     }
2142 }
2143 
2144 #define MAX_SIG_ERRORS 65536
2145 
2146 static rnp_result_t
init_signed_src(pgp_parse_handler_t * handler,pgp_source_t * src,pgp_source_t * readsrc)2147 init_signed_src(pgp_parse_handler_t *handler, pgp_source_t *src, pgp_source_t *readsrc)
2148 {
2149     rnp_result_t               errcode = RNP_ERROR_GENERIC;
2150     pgp_source_signed_param_t *param;
2151     uint8_t                    ptag;
2152     int                        ptype;
2153     pgp_signature_t *          sig = NULL;
2154     bool                       cleartext;
2155     size_t                     sigerrors = 0;
2156 
2157     if (!init_src_common(src, 0)) {
2158         return RNP_ERROR_OUT_OF_MEMORY;
2159     }
2160     try {
2161         param = new pgp_source_signed_param_t();
2162     } catch (const std::exception &e) {
2163         RNP_LOG("%s", e.what());
2164         return RNP_ERROR_OUT_OF_MEMORY;
2165     }
2166     src->param = param;
2167 
2168     cleartext = is_cleartext_source(readsrc);
2169     param->readsrc = readsrc;
2170     param->handler = handler;
2171     param->cleartext = cleartext;
2172     param->stripped_crs = 0;
2173     src->read = cleartext ? cleartext_src_read : signed_src_read;
2174     src->close = signed_src_close;
2175     src->finish = signed_src_finish;
2176     src->type = cleartext ? PGP_STREAM_CLEARTEXT : PGP_STREAM_SIGNED;
2177 
2178     /* we need key provider to validate signatures */
2179     if (!handler->key_provider) {
2180         RNP_LOG("no key provider");
2181         errcode = RNP_ERROR_BAD_PARAMETERS;
2182         goto finish;
2183     }
2184 
2185     if (cleartext) {
2186         errcode = init_cleartext_signed_src(src);
2187         goto finish;
2188     }
2189 
2190     /* Reading one-pass and signature packets */
2191     while (true) {
2192         /* stop early if we are in zip-bomb with erroneous packets */
2193         if (sigerrors >= MAX_SIG_ERRORS) {
2194             RNP_LOG("Too many one-pass/signature errors. Stopping.");
2195             errcode = RNP_ERROR_BAD_FORMAT;
2196             goto finish;
2197         }
2198 
2199         size_t readb = readsrc->readb;
2200         if (!src_peek_eq(readsrc, &ptag, 1)) {
2201             RNP_LOG("failed to read packet header");
2202             errcode = RNP_ERROR_READ;
2203             goto finish;
2204         }
2205 
2206         ptype = get_packet_type(ptag);
2207 
2208         if (ptype == PGP_PKT_ONE_PASS_SIG) {
2209             pgp_one_pass_sig_t onepass;
2210             try {
2211                 errcode = onepass.parse(*readsrc);
2212             } catch (const std::exception &e) {
2213                 errcode = RNP_ERROR_GENERIC;
2214             }
2215             if (errcode) {
2216                 if (errcode == RNP_ERROR_READ) {
2217                     goto finish;
2218                 }
2219                 if (readb == readsrc->readb) {
2220                     errcode = RNP_ERROR_BAD_FORMAT;
2221                     goto finish;
2222                 }
2223                 sigerrors++;
2224                 continue;
2225             }
2226 
2227             try {
2228                 param->onepasses.push_back(onepass);
2229             } catch (const std::exception &e) {
2230                 RNP_LOG("%s", e.what());
2231                 errcode = RNP_ERROR_OUT_OF_MEMORY;
2232                 goto finish;
2233             }
2234 
2235             /* adding hash context */
2236             if (!add_hash_for_sig(param, onepass.type, onepass.halg)) {
2237                 RNP_LOG("Failed to create hash %d for onepass %d.",
2238                         (int) onepass.halg,
2239                         (int) onepass.type);
2240                 errcode = RNP_ERROR_BAD_PARAMETERS;
2241                 goto finish;
2242             }
2243 
2244             if (onepass.nested) {
2245                 /* despite the name non-zero value means that it is the last one-pass */
2246                 break;
2247             }
2248         } else if (ptype == PGP_PKT_SIGNATURE) {
2249             /* no need to check the error here - we already know tag */
2250             if (signed_read_single_signature(param, readsrc, &sig)) {
2251                 sigerrors++;
2252             }
2253             /* adding hash context */
2254             if (sig && !add_hash_for_sig(param, sig->type(), sig->halg)) {
2255                 RNP_LOG(
2256                   "Failed to create hash %d for sig %d.", (int) sig->halg, (int) sig->type());
2257                 errcode = RNP_ERROR_BAD_PARAMETERS;
2258                 goto finish;
2259             }
2260         } else {
2261             break;
2262         }
2263 
2264         /* check if we are not it endless loop */
2265         if (readb == readsrc->readb) {
2266             errcode = RNP_ERROR_BAD_FORMAT;
2267             goto finish;
2268         }
2269         /* for detached signature we'll get eof */
2270         if (src_eof(readsrc)) {
2271             param->detached = true;
2272             break;
2273         }
2274     }
2275 
2276     /* checking what we have now */
2277     if (param->onepasses.empty() && param->sigs.empty()) {
2278         RNP_LOG("no signatures");
2279         errcode = RNP_ERROR_BAD_PARAMETERS;
2280         goto finish;
2281     }
2282     if (!param->onepasses.empty() && !param->sigs.empty()) {
2283         RNP_LOG("warning: one-passes are mixed with signatures");
2284     }
2285 
2286     errcode = RNP_SUCCESS;
2287 finish:
2288     if (errcode != RNP_SUCCESS) {
2289         src_close(src);
2290     }
2291 
2292     return errcode;
2293 }
2294 
~pgp_processing_ctx_t()2295 pgp_processing_ctx_t::~pgp_processing_ctx_t()
2296 {
2297     for (auto &src : sources) {
2298         src_close(&src);
2299     }
2300 }
2301 
2302 /** @brief build PGP source sequence down to the literal data packet
2303  *
2304  **/
2305 static rnp_result_t
init_packet_sequence(pgp_processing_ctx_t & ctx,pgp_source_t & src)2306 init_packet_sequence(pgp_processing_ctx_t &ctx, pgp_source_t &src)
2307 {
2308     pgp_source_t *lsrc = &src;
2309     size_t        srcnum = ctx.sources.size();
2310 
2311     while (1) {
2312         uint8_t ptag = 0;
2313         if (!src_peek_eq(lsrc, &ptag, 1)) {
2314             RNP_LOG("cannot read packet tag");
2315             return RNP_ERROR_READ;
2316         }
2317 
2318         int type = get_packet_type(ptag);
2319         if (type < 0) {
2320             RNP_LOG("wrong pkt tag %d", (int) ptag);
2321             return RNP_ERROR_BAD_FORMAT;
2322         }
2323 
2324         if (ctx.sources.size() - srcnum == MAXIMUM_NESTING_LEVEL) {
2325             RNP_LOG("Too many nested OpenPGP packets");
2326             return RNP_ERROR_BAD_FORMAT;
2327         }
2328 
2329         pgp_source_t psrc = {};
2330         rnp_result_t ret = RNP_ERROR_BAD_FORMAT;
2331         switch (type) {
2332         case PGP_PKT_PK_SESSION_KEY:
2333         case PGP_PKT_SK_SESSION_KEY:
2334             ret = init_encrypted_src(&ctx.handler, &psrc, lsrc);
2335             break;
2336         case PGP_PKT_ONE_PASS_SIG:
2337         case PGP_PKT_SIGNATURE:
2338             ret = init_signed_src(&ctx.handler, &psrc, lsrc);
2339             break;
2340         case PGP_PKT_COMPRESSED:
2341             ret = init_compressed_src(&psrc, lsrc);
2342             break;
2343         case PGP_PKT_LITDATA:
2344             if ((lsrc != &src) && (lsrc->type != PGP_STREAM_ENCRYPTED) &&
2345                 (lsrc->type != PGP_STREAM_SIGNED) && (lsrc->type != PGP_STREAM_COMPRESSED)) {
2346                 RNP_LOG("unexpected literal pkt");
2347                 ret = RNP_ERROR_BAD_FORMAT;
2348                 break;
2349             }
2350             ret = init_literal_src(&psrc, lsrc);
2351             break;
2352         case PGP_PKT_MARKER:
2353             if (ctx.sources.size() != srcnum) {
2354                 RNP_LOG("Warning: marker packet wrapped in pgp stream.");
2355             }
2356             ret = stream_parse_marker(*lsrc);
2357             if (ret) {
2358                 RNP_LOG("Invalid marker packet");
2359                 return ret;
2360             }
2361             continue;
2362         default:
2363             RNP_LOG("unexpected pkt %d", type);
2364             ret = RNP_ERROR_BAD_FORMAT;
2365         }
2366 
2367         if (ret) {
2368             return ret;
2369         }
2370 
2371         try {
2372             ctx.sources.push_back(psrc);
2373             lsrc = &ctx.sources.back();
2374         } catch (const std::exception &e) {
2375             src_close(&psrc);
2376             RNP_LOG("%s", e.what());
2377             return RNP_ERROR_OUT_OF_MEMORY;
2378         }
2379 
2380         if (lsrc->type == PGP_STREAM_LITERAL) {
2381             ctx.literal_src = lsrc;
2382             ctx.msg_type = PGP_MESSAGE_NORMAL;
2383             return RNP_SUCCESS;
2384         }
2385         if (lsrc->type == PGP_STREAM_SIGNED) {
2386             ctx.signed_src = lsrc;
2387             pgp_source_signed_param_t *param = (pgp_source_signed_param_t *) lsrc->param;
2388             if (param->detached) {
2389                 ctx.msg_type = PGP_MESSAGE_DETACHED;
2390                 return RNP_SUCCESS;
2391             }
2392         }
2393     }
2394 }
2395 
2396 static rnp_result_t
init_cleartext_sequence(pgp_processing_ctx_t & ctx,pgp_source_t & src)2397 init_cleartext_sequence(pgp_processing_ctx_t &ctx, pgp_source_t &src)
2398 {
2399     pgp_source_t clrsrc = {};
2400     rnp_result_t res;
2401 
2402     if ((res = init_signed_src(&ctx.handler, &clrsrc, &src))) {
2403         return res;
2404     }
2405     try {
2406         ctx.sources.push_back(clrsrc);
2407     } catch (const std::exception &e) {
2408         RNP_LOG("%s", e.what());
2409         src_close(&clrsrc);
2410         return RNP_ERROR_OUT_OF_MEMORY;
2411     }
2412     return RNP_SUCCESS;
2413 }
2414 
2415 static rnp_result_t
init_armored_sequence(pgp_processing_ctx_t & ctx,pgp_source_t & src)2416 init_armored_sequence(pgp_processing_ctx_t &ctx, pgp_source_t &src)
2417 {
2418     pgp_source_t armorsrc = {};
2419     rnp_result_t res;
2420 
2421     if ((res = init_armored_src(&armorsrc, &src))) {
2422         return res;
2423     }
2424 
2425     try {
2426         ctx.sources.push_back(armorsrc);
2427     } catch (const std::exception &e) {
2428         RNP_LOG("%s", e.what());
2429         src_close(&armorsrc);
2430         return RNP_ERROR_OUT_OF_MEMORY;
2431     }
2432     return init_packet_sequence(ctx, ctx.sources.back());
2433 }
2434 
2435 rnp_result_t
process_pgp_source(pgp_parse_handler_t * handler,pgp_source_t & src)2436 process_pgp_source(pgp_parse_handler_t *handler, pgp_source_t &src)
2437 {
2438     rnp_result_t         res = RNP_ERROR_BAD_FORMAT;
2439     rnp_result_t         fres;
2440     pgp_processing_ctx_t ctx = {};
2441     pgp_source_t *       decsrc = NULL;
2442     pgp_source_t         datasrc = {0};
2443     pgp_dest_t *         outdest = NULL;
2444     bool                 closeout = true;
2445     uint8_t *            readbuf = NULL;
2446     char *               filename = NULL;
2447 
2448     ctx.handler = *handler;
2449     /* Building readers sequence. Checking whether it is binary data */
2450     if (is_pgp_source(src)) {
2451         res = init_packet_sequence(ctx, src);
2452     } else {
2453         /* Trying armored or cleartext data */
2454         if (is_cleartext_source(&src)) {
2455             /* Initializing cleartext message */
2456             res = init_cleartext_sequence(ctx, src);
2457         } else if (is_armored_source(&src)) {
2458             /* Initializing armored message */
2459             res = init_armored_sequence(ctx, src);
2460         } else {
2461             RNP_LOG("not an OpenPGP data provided");
2462             res = RNP_ERROR_BAD_FORMAT;
2463             goto finish;
2464         }
2465     }
2466 
2467     if (res != RNP_SUCCESS) {
2468         goto finish;
2469     }
2470 
2471     if ((readbuf = (uint8_t *) calloc(1, PGP_INPUT_CACHE_SIZE)) == NULL) {
2472         RNP_LOG("allocation failure");
2473         res = RNP_ERROR_OUT_OF_MEMORY;
2474         goto finish;
2475     }
2476 
2477     if (ctx.msg_type == PGP_MESSAGE_DETACHED) {
2478         /* detached signature case */
2479         if (!handler->ctx->detached) {
2480             RNP_LOG("Unexpected detached signature input.");
2481             res = RNP_ERROR_BAD_STATE;
2482             goto finish;
2483         }
2484         if (!handler->src_provider || !handler->src_provider(handler, &datasrc)) {
2485             RNP_LOG("no data source for detached signature verification");
2486             res = RNP_ERROR_READ;
2487             goto finish;
2488         }
2489 
2490         while (!datasrc.eof) {
2491             size_t read = 0;
2492             if (!src_read(&datasrc, readbuf, PGP_INPUT_CACHE_SIZE, &read)) {
2493                 res = RNP_ERROR_GENERIC;
2494                 break;
2495             }
2496             if (read > 0) {
2497                 signed_src_update(ctx.signed_src, readbuf, read);
2498             }
2499         }
2500         src_close(&datasrc);
2501     } else {
2502         if (handler->ctx->detached) {
2503             RNP_LOG("Detached signature expected.");
2504             res = RNP_ERROR_BAD_STATE;
2505             goto finish;
2506         }
2507         /* file processing case */
2508         decsrc = &ctx.sources.back();
2509         if (ctx.literal_src) {
2510             filename = ((pgp_source_literal_param_t *) ctx.literal_src)->hdr.fname;
2511         }
2512 
2513         if (!handler->dest_provider ||
2514             !handler->dest_provider(handler, &outdest, &closeout, filename)) {
2515             res = RNP_ERROR_WRITE;
2516             goto finish;
2517         }
2518 
2519         /* reading the input */
2520         while (!decsrc->eof) {
2521             size_t read = 0;
2522             if (!src_read(decsrc, readbuf, PGP_INPUT_CACHE_SIZE, &read)) {
2523                 res = RNP_ERROR_GENERIC;
2524                 break;
2525             }
2526             if (!read) {
2527                 continue;
2528             }
2529             if (ctx.signed_src) {
2530                 signed_src_update(ctx.signed_src, readbuf, read);
2531             }
2532             dst_write(outdest, readbuf, read);
2533             if (outdest->werr != RNP_SUCCESS) {
2534                 RNP_LOG("failed to output data");
2535                 res = RNP_ERROR_WRITE;
2536                 break;
2537             }
2538         }
2539     }
2540 
2541     /* finalizing the input. Signatures are checked on this step */
2542     if (res == RNP_SUCCESS) {
2543         for (auto &src : ctx.sources) {
2544             fres = src_finish(&src);
2545             if (fres) {
2546                 res = fres;
2547             }
2548         }
2549     }
2550 
2551     if (closeout && (ctx.msg_type != PGP_MESSAGE_DETACHED)) {
2552         dst_close(outdest, res != RNP_SUCCESS);
2553     }
2554 
2555 finish:
2556     free(readbuf);
2557     return res;
2558 }
2559