Bump to 2.4.3
[platform/upstream/gpg2.git] / g10 / parse-packet.c
1 /* parse-packet.c  - read packets
2  * Copyright (C) 1998-2007, 2009-2010 Free Software Foundation, Inc.
3  * Copyright (C) 2014, 2018 Werner Koch
4  * Copyright (C) 2015 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  * SPDX-License-Identifier: GPL-3.0+
21  */
22
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "gpg.h"
29 #include "../common/util.h"
30 #include "packet.h"
31 #include "../common/iobuf.h"
32 #include "filter.h"
33 #include "photoid.h"
34 #include "options.h"
35 #include "main.h"
36 #include "../common/i18n.h"
37 #include "../common/host2net.h"
38 #include "../common/mbox-util.h"
39
40
41 static int mpi_print_mode;
42 static int list_mode;
43 static estream_t listfp;
44
45 /* A linked list of known notation names.  Note that the FLAG is used
46  * to store the length of the name to speed up the check.  */
47 static strlist_t known_notations_list;
48
49
50 static int parse (parse_packet_ctx_t ctx, PACKET *pkt, int onlykeypkts,
51                   off_t * retpos, int *skip, IOBUF out, int do_skip
52 #if DEBUG_PARSE_PACKET
53                   , const char *dbg_w, const char *dbg_f, int dbg_l
54 #endif
55   );
56 static int copy_packet (IOBUF inp, IOBUF out, int pkttype,
57                         unsigned long pktlen, int partial);
58 static void skip_packet (IOBUF inp, int pkttype,
59                          unsigned long pktlen, int partial);
60 static void *read_rest (IOBUF inp, size_t pktlen);
61 static int parse_marker (IOBUF inp, int pkttype, unsigned long pktlen);
62 static int parse_symkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
63                             PACKET * packet);
64 static int parse_pubkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
65                             PACKET * packet);
66 static int parse_onepass_sig (IOBUF inp, int pkttype, unsigned long pktlen,
67                               PKT_onepass_sig * ops);
68 static int parse_key (IOBUF inp, int pkttype, unsigned long pktlen,
69                       byte * hdr, int hdrlen, PACKET * packet);
70 static int parse_user_id (IOBUF inp, int pkttype, unsigned long pktlen,
71                           PACKET * packet);
72 static int parse_attribute (IOBUF inp, int pkttype, unsigned long pktlen,
73                             PACKET * packet);
74 static int parse_comment (IOBUF inp, int pkttype, unsigned long pktlen,
75                           PACKET * packet);
76 static gpg_error_t parse_ring_trust (parse_packet_ctx_t ctx,
77                                      unsigned long pktlen);
78 static int parse_plaintext (IOBUF inp, int pkttype, unsigned long pktlen,
79                             PACKET * packet, int new_ctb, int partial);
80 static int parse_compressed (IOBUF inp, int pkttype, unsigned long pktlen,
81                              PACKET * packet, int new_ctb);
82 static int parse_encrypted (IOBUF inp, int pkttype, unsigned long pktlen,
83                             PACKET * packet, int new_ctb, int partial);
84 static gpg_error_t parse_encrypted_aead (IOBUF inp, int pkttype,
85                                          unsigned long pktlen, PACKET *packet,
86                                          int partial);
87 static int parse_mdc (IOBUF inp, int pkttype, unsigned long pktlen,
88                       PACKET * packet, int new_ctb);
89 static int parse_gpg_control (IOBUF inp, int pkttype, unsigned long pktlen,
90                               PACKET * packet, int partial);
91
92 /* Read a 16-bit value in MSB order (big endian) from an iobuf.  */
93 static unsigned short
94 read_16 (IOBUF inp)
95 {
96   unsigned short a;
97   a = (unsigned short)iobuf_get_noeof (inp) << 8;
98   a |= iobuf_get_noeof (inp);
99   return a;
100 }
101
102
103 /* Read a 32-bit value in MSB order (big endian) from an iobuf.  */
104 static unsigned long
105 read_32 (IOBUF inp)
106 {
107   unsigned long a;
108   a = (unsigned long)iobuf_get_noeof (inp) << 24;
109   a |= iobuf_get_noeof (inp) << 16;
110   a |= iobuf_get_noeof (inp) << 8;
111   a |= iobuf_get_noeof (inp);
112   return a;
113 }
114
115
116 /* Read an external representation of an MPI and return the MPI.  The
117    external format is a 16-bit unsigned value stored in network byte
118    order giving the number of bits for the following integer.  The
119    integer is stored MSB first and is left padded with zero bits to
120    align on a byte boundary.
121
122    The caller must set *RET_NREAD to the maximum number of bytes to
123    read from the pipeline INP.  This function sets *RET_NREAD to be
124    the number of bytes actually read from the pipeline.
125
126    If SECURE is true, the integer is stored in secure memory
127    (allocated using gcry_xmalloc_secure).  */
128 static gcry_mpi_t
129 mpi_read (iobuf_t inp, unsigned int *ret_nread, int secure)
130 {
131   int c, c1, c2, i;
132   unsigned int nmax = *ret_nread;
133   unsigned int nbits, nbytes;
134   size_t nread = 0;
135   gcry_mpi_t a = NULL;
136   byte *buf = NULL;
137   byte *p;
138
139   if (!nmax)
140     goto overflow;
141
142   if ((c = c1 = iobuf_get (inp)) == -1)
143     goto leave;
144   if (++nread == nmax)
145     goto overflow;
146   nbits = c << 8;
147   if ((c = c2 = iobuf_get (inp)) == -1)
148     goto leave;
149   ++nread;
150   nbits |= c;
151   if (nbits > MAX_EXTERN_MPI_BITS)
152     {
153       log_error ("mpi too large (%u bits)\n", nbits);
154       goto leave;
155     }
156
157   nbytes = (nbits + 7) / 8;
158   buf = secure ? gcry_xmalloc_secure (nbytes + 2) : gcry_xmalloc (nbytes + 2);
159   p = buf;
160   p[0] = c1;
161   p[1] = c2;
162   for (i = 0; i < nbytes; i++)
163     {
164       if (nread == nmax)
165         goto overflow;
166
167       c = iobuf_get (inp);
168       if (c == -1)
169         goto leave;
170
171       p[i + 2] = c;
172       nread ++;
173     }
174
175   if (gcry_mpi_scan (&a, GCRYMPI_FMT_PGP, buf, nread, &nread))
176     a = NULL;
177
178   *ret_nread = nread;
179   gcry_free(buf);
180   return a;
181
182  overflow:
183   log_error ("mpi larger than indicated length (%u bits)\n", 8*nmax);
184  leave:
185   *ret_nread = nread;
186   gcry_free(buf);
187   return a;
188 }
189
190
191 /* Read an external representation of an SOS and return the opaque MPI
192    with GCRYMPI_FLAG_USER2.  The external format is a 16-bit unsigned
193    value stored in network byte order giving information for the
194    following octets.
195
196    The caller must set *RET_NREAD to the maximum number of bytes to
197    read from the pipeline INP.  This function sets *RET_NREAD to be
198    the number of bytes actually read from the pipeline.
199
200    If SECURE is true, the integer is stored in secure memory
201    (allocated using gcry_xmalloc_secure).  */
202 static gcry_mpi_t
203 sos_read (iobuf_t inp, unsigned int *ret_nread, int secure)
204 {
205   int c, c1, c2, i;
206   unsigned int nmax = *ret_nread;
207   unsigned int nbits, nbytes;
208   size_t nread = 0;
209   gcry_mpi_t a = NULL;
210   byte *buf = NULL;
211   byte *p;
212
213   if (!nmax)
214     goto overflow;
215
216   if ((c = c1 = iobuf_get (inp)) == -1)
217     goto leave;
218   if (++nread == nmax)
219     goto overflow;
220   nbits = c << 8;
221   if ((c = c2 = iobuf_get (inp)) == -1)
222     goto leave;
223   ++nread;
224   nbits |= c;
225   if (nbits > MAX_EXTERN_MPI_BITS)
226     {
227       log_error ("mpi too large (%u bits)\n", nbits);
228       goto leave;
229     }
230
231   nbytes = (nbits + 7) / 8;
232   buf = secure ? gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes);
233   p = buf;
234   for (i = 0; i < nbytes; i++)
235     {
236       if (nread == nmax)
237         goto overflow;
238
239       c = iobuf_get (inp);
240       if (c == -1)
241         goto leave;
242
243       p[i] = c;
244       nread ++;
245     }
246
247   a = gcry_mpi_set_opaque (NULL, buf, nbits);
248   gcry_mpi_set_flag (a, GCRYMPI_FLAG_USER2);
249   *ret_nread = nread;
250   return a;
251
252  overflow:
253   log_error ("mpi larger than indicated length (%u bits)\n", 8*nmax);
254  leave:
255   *ret_nread = nread;
256   gcry_free(buf);
257   return a;
258 }
259
260
261 /* Register STRING as a known critical notation name.  */
262 void
263 register_known_notation (const char *string)
264 {
265   strlist_t sl;
266
267   if (!known_notations_list)
268     {
269       sl = add_to_strlist (&known_notations_list,
270                            "preferred-email-encoding@pgp.com");
271       sl->flags = 32;  /* Length of the string.  */
272     }
273   if (!string)
274     return; /* Only initialized the default known notations.  */
275
276   /* In --set-notation we use an exclamation mark to indicate a
277    * critical notation.  As a convenience skip this here.  */
278   if (*string == '!')
279     string++;
280
281   if (!*string || strlist_find (known_notations_list, string))
282     return; /* Empty string or already registered.  */
283
284   sl = add_to_strlist (&known_notations_list, string);
285   sl->flags = strlen (string);
286 }
287
288
289 int
290 set_packet_list_mode (int mode)
291 {
292   int old = list_mode;
293   list_mode = mode;
294
295   /* We use stdout only if invoked by the --list-packets command
296      but switch to stderr in all other cases.  This breaks the
297      previous behaviour but that seems to be more of a bug than
298      intentional.  I don't believe that any application makes use of
299      this long standing annoying way of printing to stdout except when
300      doing a --list-packets. If this assumption fails, it will be easy
301      to add an option for the listing stream.  Note that we initialize
302      it only once; mainly because there is code which switches
303      opt.list_mode back to 1 and we want to have all output to the
304      same stream.  The MPI_PRINT_MODE will be enabled if the
305      corresponding debug flag is set or if we are in --list-packets
306      and --verbose is given.
307
308      Using stderr is not actually very clean because it bypasses the
309      logging code but it is a special thing anyway.  I am not sure
310      whether using log_stream() would be better.  Perhaps we should
311      enable the list mode only with a special option. */
312   if (!listfp)
313     {
314       if (opt.list_packets)
315         {
316           listfp = es_stdout;
317           if (opt.verbose)
318             mpi_print_mode = 1;
319         }
320       else
321         listfp = es_stderr;
322
323       if (DBG_MPI)
324         mpi_print_mode = 1;
325     }
326   return old;
327 }
328
329
330 /* If OPT.VERBOSE is set, print a warning that the algorithm ALGO is
331    not suitable for signing and encryption.  */
332 static void
333 unknown_pubkey_warning (int algo)
334 {
335   static byte unknown_pubkey_algos[256];
336
337   /* First check whether the algorithm is usable but not suitable for
338      encryption/signing.  */
339   if (pubkey_get_npkey (algo))
340     {
341       if (opt.verbose && !glo_ctrl.silence_parse_warnings)
342         {
343           if (!pubkey_get_nsig (algo))
344             log_info ("public key algorithm %s not suitable for %s\n",
345                       openpgp_pk_algo_name (algo), "signing");
346           if (!pubkey_get_nenc (algo))
347             log_info ("public key algorithm %s not suitable for %s\n",
348                       openpgp_pk_algo_name (algo), "encryption");
349         }
350     }
351   else
352     {
353       algo &= 0xff;
354       if (!unknown_pubkey_algos[algo])
355         {
356           if (opt.verbose && !glo_ctrl.silence_parse_warnings)
357             log_info (_("can't handle public key algorithm %d\n"), algo);
358           unknown_pubkey_algos[algo] = 1;
359         }
360     }
361 }
362
363
364 #if DEBUG_PARSE_PACKET
365 int
366 dbg_parse_packet (parse_packet_ctx_t ctx, PACKET *pkt,
367                   const char *dbg_f, int dbg_l)
368 {
369   int skip, rc;
370
371   do
372     {
373       rc = parse (ctx, pkt, 0, NULL, &skip, NULL, 0, "parse", dbg_f, dbg_l);
374     }
375   while (skip && ! rc);
376   return rc;
377 }
378 #else /*!DEBUG_PARSE_PACKET*/
379 int
380 parse_packet (parse_packet_ctx_t ctx, PACKET *pkt)
381 {
382   int skip, rc;
383
384   do
385     {
386       rc = parse (ctx, pkt, 0, NULL, &skip, NULL, 0);
387     }
388   while (skip && ! rc);
389   return rc;
390 }
391 #endif /*!DEBUG_PARSE_PACKET*/
392
393
394 /*
395  * Like parse packet, but only return secret or public (sub)key
396  * packets.
397  */
398 #if DEBUG_PARSE_PACKET
399 int
400 dbg_search_packet (parse_packet_ctx_t ctx, PACKET *pkt,
401                    off_t * retpos, int with_uid,
402                    const char *dbg_f, int dbg_l)
403 {
404   int skip, rc;
405
406   do
407     {
408       rc = parse (ctx, pkt, with_uid ? 2 : 1, retpos, &skip, NULL, 0, "search",
409                   dbg_f, dbg_l);
410     }
411   while (skip && ! rc);
412   return rc;
413 }
414 #else /*!DEBUG_PARSE_PACKET*/
415 int
416 search_packet (parse_packet_ctx_t ctx, PACKET *pkt,
417                off_t * retpos, int with_uid)
418 {
419   int skip, rc;
420
421   do
422     {
423       rc = parse (ctx, pkt, with_uid ? 2 : 1, retpos, &skip, NULL, 0);
424     }
425   while (skip && ! rc);
426   return rc;
427 }
428 #endif /*!DEBUG_PARSE_PACKET*/
429
430
431 /*
432  * Copy all packets from INP to OUT, thereby removing unused spaces.
433  */
434 #if DEBUG_PARSE_PACKET
435 int
436 dbg_copy_all_packets (iobuf_t inp, iobuf_t out, const char *dbg_f, int dbg_l)
437 {
438   PACKET pkt;
439   struct parse_packet_ctx_s parsectx;
440   int skip, rc = 0;
441
442   if (! out)
443     log_bug ("copy_all_packets: OUT may not be NULL.\n");
444
445   init_parse_packet (&parsectx, inp);
446
447   do
448     {
449       init_packet (&pkt);
450     }
451   while (!
452          (rc =
453           parse (&parsectx, &pkt, 0, NULL, &skip, out, 0, "copy",
454                  dbg_f, dbg_l)));
455
456   deinit_parse_packet (&parsectx);
457
458   return rc;
459 }
460 #else /*!DEBUG_PARSE_PACKET*/
461 int
462 copy_all_packets (iobuf_t inp, iobuf_t out)
463 {
464   PACKET pkt;
465   struct parse_packet_ctx_s parsectx;
466   int skip, rc = 0;
467
468   if (! out)
469     log_bug ("copy_all_packets: OUT may not be NULL.\n");
470
471   init_parse_packet (&parsectx, inp);
472
473   do
474     {
475       init_packet (&pkt);
476     }
477   while (!(rc = parse (&parsectx, &pkt, 0, NULL, &skip, out, 0)));
478
479   deinit_parse_packet (&parsectx);
480
481   return rc;
482 }
483 #endif /*!DEBUG_PARSE_PACKET*/
484
485
486 /*
487  * Copy some packets from INP to OUT, thereby removing unused spaces.
488  * Stop at offset STOPoff (i.e. don't copy packets at this or later
489  * offsets)
490  */
491 #if DEBUG_PARSE_PACKET
492 int
493 dbg_copy_some_packets (iobuf_t inp, iobuf_t out, off_t stopoff,
494                        const char *dbg_f, int dbg_l)
495 {
496   int rc = 0;
497   PACKET pkt;
498   int skip;
499   struct parse_packet_ctx_s parsectx;
500
501   init_parse_packet (&parsectx, inp);
502
503   do
504     {
505       if (iobuf_tell (inp) >= stopoff)
506         {
507           deinit_parse_packet (&parsectx);
508           return 0;
509         }
510       init_packet (&pkt);
511     }
512   while (!(rc = parse (&parsectx, &pkt, 0, NULL, &skip, out, 0,
513                        "some", dbg_f, dbg_l)));
514
515   deinit_parse_packet (&parsectx);
516
517   return rc;
518 }
519 #else /*!DEBUG_PARSE_PACKET*/
520 int
521 copy_some_packets (iobuf_t inp, iobuf_t out, off_t stopoff)
522 {
523   int rc = 0;
524   PACKET pkt;
525   struct parse_packet_ctx_s parsectx;
526   int skip;
527
528   init_parse_packet (&parsectx, inp);
529
530   do
531     {
532       if (iobuf_tell (inp) >= stopoff)
533         {
534           deinit_parse_packet (&parsectx);
535           return 0;
536         }
537       init_packet (&pkt);
538     }
539   while (!(rc = parse (&parsectx, &pkt, 0, NULL, &skip, out, 0)));
540
541   deinit_parse_packet (&parsectx);
542
543   return rc;
544 }
545 #endif /*!DEBUG_PARSE_PACKET*/
546
547
548 /*
549  * Skip over N packets
550  */
551 #if DEBUG_PARSE_PACKET
552 int
553 dbg_skip_some_packets (iobuf_t inp, unsigned n, const char *dbg_f, int dbg_l)
554 {
555   int rc = 0;
556   int skip;
557   PACKET pkt;
558   struct parse_packet_ctx_s parsectx;
559
560   init_parse_packet (&parsectx, inp);
561
562   for (; n && !rc; n--)
563     {
564       init_packet (&pkt);
565       rc = parse (&parsectx, &pkt, 0, NULL, &skip, NULL, 1, "skip",
566                   dbg_f, dbg_l);
567     }
568
569   deinit_parse_packet (&parsectx);
570
571   return rc;
572 }
573 #else /*!DEBUG_PARSE_PACKET*/
574 int
575 skip_some_packets (iobuf_t inp, unsigned int n)
576 {
577   int rc = 0;
578   int skip;
579   PACKET pkt;
580   struct parse_packet_ctx_s parsectx;
581
582   init_parse_packet (&parsectx, inp);
583
584   for (; n && !rc; n--)
585     {
586       init_packet (&pkt);
587       rc = parse (&parsectx, &pkt, 0, NULL, &skip, NULL, 1);
588     }
589
590   deinit_parse_packet (&parsectx);
591
592   return rc;
593 }
594 #endif /*!DEBUG_PARSE_PACKET*/
595
596
597 /* Parse a packet and save it in *PKT.
598
599    If OUT is not NULL and the packet is valid (its type is not 0),
600    then the header, the initial length field and the packet's contents
601    are written to OUT.  In this case, the packet is not saved in *PKT.
602
603    ONLYKEYPKTS is a simple packet filter.  If ONLYKEYPKTS is set to 1,
604    then only public subkey packets, public key packets, private subkey
605    packets and private key packets are parsed.  The rest are skipped
606    (i.e., the header and the contents are read from the pipeline and
607    discarded).  If ONLYKEYPKTS is set to 2, then in addition to the
608    above 4 types of packets, user id packets are also accepted.
609
610    DO_SKIP is a more coarse grained filter.  Unless ONLYKEYPKTS is set
611    to 2 and the packet is a user id packet, all packets are skipped.
612
613    Finally, if a packet is invalid (it's type is 0), it is skipped.
614
615    If a packet is skipped and SKIP is not NULL, then *SKIP is set to
616    1.
617
618    Note: ONLYKEYPKTS and DO_SKIP are only respected if OUT is NULL,
619    i.e., the packets are not simply being copied.
620
621    If RETPOS is not NULL, then the position of CTX->INP (as returned by
622    iobuf_tell) is saved there before any data is read from CTX->INP.
623   */
624 static int
625 parse (parse_packet_ctx_t ctx, PACKET *pkt, int onlykeypkts, off_t * retpos,
626        int *skip, IOBUF out, int do_skip
627 #if DEBUG_PARSE_PACKET
628        , const char *dbg_w, const char *dbg_f, int dbg_l
629 #endif
630        )
631 {
632   int rc = 0;
633   iobuf_t inp;
634   int c, ctb, pkttype, lenbytes;
635   unsigned long pktlen;
636   byte hdr[8];
637   int hdrlen;
638   int new_ctb = 0, partial = 0;
639   int with_uid = (onlykeypkts == 2);
640   off_t pos;
641
642   *skip = 0;
643   inp = ctx->inp;
644
645  again:
646   log_assert (!pkt->pkt.generic);
647   if (retpos || list_mode)
648     {
649       pos = iobuf_tell (inp);
650       if (retpos)
651         *retpos = pos;
652     }
653   else
654     pos = 0; /* (silence compiler warning) */
655
656   /* The first byte of a packet is the so-called tag.  The highest bit
657      must be set.  */
658   if ((ctb = iobuf_get (inp)) == -1)
659     {
660       rc = -1;
661       goto leave;
662     }
663   hdrlen = 0;
664   hdr[hdrlen++] = ctb;
665
666   if (!(ctb & 0x80))
667     {
668       log_error ("%s: invalid packet (ctb=%02x)\n", iobuf_where (inp), ctb);
669       rc = gpg_error (GPG_ERR_INV_PACKET);
670       goto leave;
671     }
672
673   /* Immediately following the header is the length.  There are two
674      formats: the old format and the new format.  If bit 6 (where the
675      least significant bit is bit 0) is set in the tag, then we are
676      dealing with a new format packet.  Otherwise, it is an old format
677      packet.  */
678   pktlen = 0;
679   new_ctb = !!(ctb & 0x40);
680   if (new_ctb)
681     {
682       /* Get the packet's type.  This is encoded in the 6 least
683          significant bits of the tag.  */
684       pkttype = ctb & 0x3f;
685
686       /* Extract the packet's length.  New format packets have 4 ways
687          to encode the packet length.  The value of the first byte
688          determines the encoding and partially determines the length.
689          See section 4.2.2 of RFC 4880 for details.  */
690       if ((c = iobuf_get (inp)) == -1)
691         {
692           log_error ("%s: 1st length byte missing\n", iobuf_where (inp));
693           rc = gpg_error (GPG_ERR_INV_PACKET);
694           goto leave;
695         }
696
697
698       hdr[hdrlen++] = c;
699       if (c < 192)
700         pktlen = c;
701       else if (c < 224)
702         {
703           pktlen = (c - 192) * 256;
704           if ((c = iobuf_get (inp)) == -1)
705             {
706               log_error ("%s: 2nd length byte missing\n",
707                          iobuf_where (inp));
708               rc = gpg_error (GPG_ERR_INV_PACKET);
709               goto leave;
710             }
711           hdr[hdrlen++] = c;
712           pktlen += c + 192;
713         }
714       else if (c == 255)
715         {
716           int i;
717           char value[4];
718
719           for (i = 0; i < 4; i ++)
720             {
721               if ((c = iobuf_get (inp)) == -1)
722                 {
723                   log_error ("%s: 4 byte length invalid\n", iobuf_where (inp));
724                   rc = gpg_error (GPG_ERR_INV_PACKET);
725                   goto leave;
726                 }
727               value[i] = hdr[hdrlen++] = c;
728             }
729
730           pktlen = buf32_to_ulong (value);
731         }
732       else /* Partial body length.  */
733         {
734           switch (pkttype)
735             {
736             case PKT_PLAINTEXT:
737             case PKT_ENCRYPTED:
738             case PKT_ENCRYPTED_MDC:
739             case PKT_ENCRYPTED_AEAD:
740             case PKT_COMPRESSED:
741               iobuf_set_partial_body_length_mode (inp, c & 0xff);
742               pktlen = 0;       /* To indicate partial length.  */
743               partial = 1;
744               break;
745
746             default:
747               log_error ("%s: partial length invalid for"
748                          " packet type %d\n", iobuf_where (inp), pkttype);
749               rc = gpg_error (GPG_ERR_INV_PACKET);
750               goto leave;
751             }
752         }
753
754     }
755   else
756     /* This is an old format packet.  */
757     {
758       /* Extract the packet's type.  This is encoded in bits 2-5.  */
759       pkttype = (ctb >> 2) & 0xf;
760
761       /* The type of length encoding is encoded in bits 0-1 of the
762          tag.  */
763       lenbytes = ((ctb & 3) == 3) ? 0 : (1 << (ctb & 3));
764       if (!lenbytes)
765         {
766           pktlen = 0;   /* Don't know the value.  */
767           /* This isn't really partial, but we can treat it the same
768              in a "read until the end" sort of way.  */
769           partial = 1;
770           if (pkttype != PKT_ENCRYPTED && pkttype != PKT_PLAINTEXT
771               && pkttype != PKT_COMPRESSED)
772             {
773               log_error ("%s: indeterminate length for invalid"
774                          " packet type %d\n", iobuf_where (inp), pkttype);
775               rc = gpg_error (GPG_ERR_INV_PACKET);
776               goto leave;
777             }
778         }
779       else
780         {
781           for (; lenbytes; lenbytes--)
782             {
783               pktlen <<= 8;
784               c = iobuf_get (inp);
785               if (c == -1)
786                 {
787                   log_error ("%s: length invalid\n", iobuf_where (inp));
788                   rc = gpg_error (GPG_ERR_INV_PACKET);
789                   goto leave;
790                 }
791               pktlen |= hdr[hdrlen++] = c;
792             }
793         }
794     }
795
796   /* Sometimes the decompressing layer enters an error state in which
797      it simply outputs 0xff for every byte read.  If we have a stream
798      of 0xff bytes, then it will be detected as a new format packet
799      with type 63 and a 4-byte encoded length that is 4G-1.  Since
800      packets with type 63 are private and we use them as a control
801      packet, which won't be 4 GB, we reject such packets as
802      invalid.  */
803   if (pkttype == 63 && pktlen == 0xFFFFFFFF)
804     {
805       /* With some probability this is caused by a problem in the
806        * the uncompressing layer - in some error cases it just loops
807        * and spits out 0xff bytes. */
808       log_error ("%s: garbled packet detected\n", iobuf_where (inp));
809       g10_exit (2);
810     }
811
812   if (out && pkttype)
813     {
814       /* This type of copying won't work if the packet uses a partial
815          body length.  (In other words, this only works if HDR is
816          actually the length.)  Currently, no callers require this
817          functionality so we just log this as an error.  */
818       if (partial)
819         {
820           log_error ("parse: Can't copy partial packet.  Aborting.\n");
821           rc = gpg_error (GPG_ERR_INV_PACKET);
822           goto leave;
823         }
824
825       rc = iobuf_write (out, hdr, hdrlen);
826       if (!rc)
827         rc = copy_packet (inp, out, pkttype, pktlen, partial);
828       goto leave;
829     }
830
831   if (with_uid && pkttype == PKT_USER_ID)
832     /* If ONLYKEYPKTS is set to 2, then we never skip user id packets,
833        even if DO_SKIP is set.  */
834     ;
835   else if (do_skip
836            /* type==0 is not allowed.  This is an invalid packet.  */
837            || !pkttype
838            /* When ONLYKEYPKTS is set, we don't skip keys.  */
839            || (onlykeypkts && pkttype != PKT_PUBLIC_SUBKEY
840                && pkttype != PKT_PUBLIC_KEY
841                && pkttype != PKT_SECRET_SUBKEY && pkttype != PKT_SECRET_KEY))
842     {
843       iobuf_skip_rest (inp, pktlen, partial);
844       *skip = 1;
845       rc = 0;
846       goto leave;
847     }
848
849   if (DBG_PACKET)
850     {
851 #if DEBUG_PARSE_PACKET
852       log_debug ("parse_packet(iob=%d): type=%d length=%lu%s (%s.%s.%d)\n",
853                  iobuf_id (inp), pkttype, pktlen, new_ctb ? " (new_ctb)" : "",
854                  dbg_w, dbg_f, dbg_l);
855 #else
856       log_debug ("parse_packet(iob=%d): type=%d length=%lu%s\n",
857                  iobuf_id (inp), pkttype, pktlen,
858                  new_ctb ? " (new_ctb)" : "");
859 #endif
860     }
861
862   if (list_mode)
863     es_fprintf (listfp, "# off=%lu ctb=%02x tag=%d hlen=%d plen=%lu%s%s\n",
864                 (unsigned long)pos, ctb, pkttype, hdrlen, pktlen,
865                 partial? (new_ctb ? " partial" : " indeterminate") :"",
866                 new_ctb? " new-ctb":"");
867
868   /* Count it.  */
869   ctx->n_parsed_packets++;
870
871   pkt->pkttype = pkttype;
872   rc = GPG_ERR_UNKNOWN_PACKET;  /* default error */
873   switch (pkttype)
874     {
875     case PKT_PUBLIC_KEY:
876     case PKT_PUBLIC_SUBKEY:
877     case PKT_SECRET_KEY:
878     case PKT_SECRET_SUBKEY:
879       pkt->pkt.public_key = xmalloc_clear (sizeof *pkt->pkt.public_key);
880       rc = parse_key (inp, pkttype, pktlen, hdr, hdrlen, pkt);
881       break;
882     case PKT_SYMKEY_ENC:
883       rc = parse_symkeyenc (inp, pkttype, pktlen, pkt);
884       break;
885     case PKT_PUBKEY_ENC:
886       rc = parse_pubkeyenc (inp, pkttype, pktlen, pkt);
887       break;
888     case PKT_SIGNATURE:
889       pkt->pkt.signature = xmalloc_clear (sizeof *pkt->pkt.signature);
890       rc = parse_signature (inp, pkttype, pktlen, pkt->pkt.signature);
891       break;
892     case PKT_ONEPASS_SIG:
893       pkt->pkt.onepass_sig = xmalloc_clear (sizeof *pkt->pkt.onepass_sig);
894       rc = parse_onepass_sig (inp, pkttype, pktlen, pkt->pkt.onepass_sig);
895       break;
896     case PKT_USER_ID:
897       rc = parse_user_id (inp, pkttype, pktlen, pkt);
898       break;
899     case PKT_ATTRIBUTE:
900       pkt->pkttype = pkttype = PKT_USER_ID;     /* we store it in the userID */
901       rc = parse_attribute (inp, pkttype, pktlen, pkt);
902       break;
903     case PKT_OLD_COMMENT:
904     case PKT_COMMENT:
905       rc = parse_comment (inp, pkttype, pktlen, pkt);
906       break;
907     case PKT_RING_TRUST:
908       {
909         rc = parse_ring_trust (ctx, pktlen);
910         if (!rc)
911           goto again; /* Directly read the next packet.  */
912       }
913       break;
914     case PKT_PLAINTEXT:
915       rc = parse_plaintext (inp, pkttype, pktlen, pkt, new_ctb, partial);
916       break;
917     case PKT_COMPRESSED:
918       rc = parse_compressed (inp, pkttype, pktlen, pkt, new_ctb);
919       break;
920     case PKT_ENCRYPTED:
921     case PKT_ENCRYPTED_MDC:
922       rc = parse_encrypted (inp, pkttype, pktlen, pkt, new_ctb, partial);
923       break;
924     case PKT_MDC:
925       rc = parse_mdc (inp, pkttype, pktlen, pkt, new_ctb);
926       break;
927     case PKT_ENCRYPTED_AEAD:
928       rc = parse_encrypted_aead (inp, pkttype, pktlen, pkt, partial);
929       break;
930     case PKT_GPG_CONTROL:
931       rc = parse_gpg_control (inp, pkttype, pktlen, pkt, partial);
932       break;
933     case PKT_MARKER:
934       rc = parse_marker (inp, pkttype, pktlen);
935       break;
936     default:
937       /* Unknown packet.  Skip it.  */
938       skip_packet (inp, pkttype, pktlen, partial);
939       break;
940     }
941
942   /* Store a shallow copy of certain packets in the context.  */
943   free_packet (NULL, ctx);
944   if (!rc && (pkttype == PKT_PUBLIC_KEY
945               || pkttype == PKT_SECRET_KEY
946               || pkttype == PKT_USER_ID
947               || pkttype == PKT_ATTRIBUTE
948               || pkttype == PKT_SIGNATURE))
949     {
950       ctx->last_pkt = *pkt;
951     }
952
953  leave:
954   /* FIXME: We leak in case of an error (see the xmalloc's above).  */
955   if (!rc && iobuf_error (inp))
956     rc = GPG_ERR_INV_KEYRING;
957
958   /* FIXME: We use only the error code for now to avoid problems with
959      callers which have not been checked to always use gpg_err_code()
960      when comparing error codes.  */
961   return rc == -1? -1 : gpg_err_code (rc);
962 }
963
964
965 static void
966 dump_hex_line (int c, int *i)
967 {
968   if (*i && !(*i % 8))
969     {
970       if (*i && !(*i % 24))
971         es_fprintf (listfp, "\n%4d:", *i);
972       else
973         es_putc (' ', listfp);
974     }
975   if (c == -1)
976     es_fprintf (listfp, " EOF");
977   else
978     es_fprintf (listfp, " %02x", c);
979   ++*i;
980 }
981
982
983 /* Copy the contents of a packet from the pipeline IN to the pipeline
984    OUT.
985
986    The header and length have already been read from INP and the
987    decoded values are given as PKGTYPE and PKTLEN.
988
989    If the packet is a partial body length packet (RFC 4880, Section
990    4.2.2.4), then iobuf_set_partial_block_modeiobuf_set_partial_block_mode
991    should already have been called on INP and PARTIAL should be set.
992
993    If PARTIAL is set or PKTLEN is 0 and PKTTYPE is PKT_COMPRESSED,
994    copy until the first EOF is encountered on INP.
995
996    Returns 0 on success and an error code if an error occurs.  */
997 static int
998 copy_packet (IOBUF inp, IOBUF out, int pkttype,
999              unsigned long pktlen, int partial)
1000 {
1001   int rc;
1002   int n;
1003   char buf[100];
1004
1005   if (partial)
1006     {
1007       while ((n = iobuf_read (inp, buf, sizeof (buf))) != -1)
1008         if ((rc = iobuf_write (out, buf, n)))
1009           return rc;            /* write error */
1010     }
1011   else if (!pktlen && pkttype == PKT_COMPRESSED)
1012     {
1013       log_debug ("copy_packet: compressed!\n");
1014       /* compressed packet, copy till EOF */
1015       while ((n = iobuf_read (inp, buf, sizeof (buf))) != -1)
1016         if ((rc = iobuf_write (out, buf, n)))
1017           return rc;            /* write error */
1018     }
1019   else
1020     {
1021       for (; pktlen; pktlen -= n)
1022         {
1023           n = pktlen > sizeof (buf) ? sizeof (buf) : pktlen;
1024           n = iobuf_read (inp, buf, n);
1025           if (n == -1)
1026             return gpg_error (GPG_ERR_EOF);
1027           if ((rc = iobuf_write (out, buf, n)))
1028             return rc;          /* write error */
1029         }
1030     }
1031   return 0;
1032 }
1033
1034
1035 /* Skip an unknown packet.  PKTTYPE is the packet's type, PKTLEN is
1036    the length of the packet's content and PARTIAL is whether partial
1037    body length encoding in used (in this case PKTLEN is ignored).  */
1038 static void
1039 skip_packet (IOBUF inp, int pkttype, unsigned long pktlen, int partial)
1040 {
1041   if (list_mode)
1042     {
1043       es_fprintf (listfp, ":unknown packet: type %2d, length %lu\n",
1044                   pkttype, pktlen);
1045       if (pkttype)
1046         {
1047           int c, i = 0;
1048           es_fputs ("dump:", listfp);
1049           if (partial)
1050             {
1051               while ((c = iobuf_get (inp)) != -1)
1052                 dump_hex_line (c, &i);
1053             }
1054           else
1055             {
1056               for (; pktlen; pktlen--)
1057                 {
1058                   dump_hex_line ((c = iobuf_get (inp)), &i);
1059                   if (c == -1)
1060                     break;
1061                 }
1062             }
1063           es_putc ('\n', listfp);
1064           return;
1065         }
1066     }
1067   iobuf_skip_rest (inp, pktlen, partial);
1068 }
1069
1070
1071 /* Read PKTLEN bytes from INP and return them in a newly allocated
1072  * buffer.  In case of an error (including reading fewer than PKTLEN
1073  * bytes from INP before EOF is returned), NULL is returned and an
1074  * error message is logged.  */
1075 static void *
1076 read_rest (IOBUF inp, size_t pktlen)
1077 {
1078   int c;
1079   byte *buf, *p;
1080
1081   buf = xtrymalloc (pktlen);
1082   if (!buf)
1083     {
1084       gpg_error_t err = gpg_error_from_syserror ();
1085       log_error ("error reading rest of packet: %s\n", gpg_strerror (err));
1086       return NULL;
1087     }
1088   for (p = buf; pktlen; pktlen--)
1089     {
1090       c = iobuf_get (inp);
1091       if (c == -1)
1092         {
1093           log_error ("premature eof while reading rest of packet\n");
1094           xfree (buf);
1095           return NULL;
1096         }
1097       *p++ = c;
1098     }
1099
1100   return buf;
1101 }
1102
1103
1104 /* Read a special size+body from INP.  On success store an opaque MPI
1105    with it at R_DATA.  On error return an error code and store NULL at
1106    R_DATA.  Even in the error case store the number of read bytes at
1107    R_NREAD.  The caller shall pass the remaining size of the packet in
1108    PKTLEN.  */
1109 static gpg_error_t
1110 read_size_body (iobuf_t inp, int pktlen, size_t *r_nread,
1111                 gcry_mpi_t *r_data)
1112 {
1113   char buffer[256];
1114   char *tmpbuf;
1115   int i, c, nbytes;
1116
1117   *r_nread = 0;
1118   *r_data = NULL;
1119
1120   if (!pktlen)
1121     return gpg_error (GPG_ERR_INV_PACKET);
1122   c = iobuf_readbyte (inp);
1123   if (c < 0)
1124     return gpg_error (GPG_ERR_INV_PACKET);
1125   pktlen--;
1126   ++*r_nread;
1127   nbytes = c;
1128   if (nbytes < 2 || nbytes > 254)
1129     return gpg_error (GPG_ERR_INV_PACKET);
1130   if (nbytes > pktlen)
1131     return gpg_error (GPG_ERR_INV_PACKET);
1132
1133   buffer[0] = nbytes;
1134
1135   for (i = 0; i < nbytes; i++)
1136     {
1137       c = iobuf_get (inp);
1138       if (c < 0)
1139         return gpg_error (GPG_ERR_INV_PACKET);
1140       ++*r_nread;
1141       buffer[1+i] = c;
1142     }
1143
1144   tmpbuf = xtrymalloc (1 + nbytes);
1145   if (!tmpbuf)
1146     return gpg_error_from_syserror ();
1147   memcpy (tmpbuf, buffer, 1 + nbytes);
1148   *r_data = gcry_mpi_set_opaque (NULL, tmpbuf, 8 * (1 + nbytes));
1149   if (!*r_data)
1150     {
1151       xfree (tmpbuf);
1152       return gpg_error_from_syserror ();
1153     }
1154   return 0;
1155 }
1156
1157
1158 /* Parse a marker packet.  */
1159 static int
1160 parse_marker (IOBUF inp, int pkttype, unsigned long pktlen)
1161 {
1162   (void) pkttype;
1163
1164   if (pktlen != 3)
1165     goto fail;
1166
1167   if (iobuf_get (inp) != 'P')
1168     {
1169       pktlen--;
1170       goto fail;
1171     }
1172
1173   if (iobuf_get (inp) != 'G')
1174     {
1175       pktlen--;
1176       goto fail;
1177     }
1178
1179   if (iobuf_get (inp) != 'P')
1180     {
1181       pktlen--;
1182       goto fail;
1183     }
1184
1185   if (list_mode)
1186     es_fputs (":marker packet: PGP\n", listfp);
1187
1188   return 0;
1189
1190  fail:
1191   log_error ("invalid marker packet\n");
1192   if (list_mode)
1193     es_fputs (":marker packet: [invalid]\n", listfp);
1194   iobuf_skip_rest (inp, pktlen, 0);
1195   return GPG_ERR_INV_PACKET;
1196 }
1197
1198
1199 static int
1200 parse_symkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
1201                  PACKET * packet)
1202 {
1203   PKT_symkey_enc *k;
1204   int rc = 0;
1205   int i, version, s2kmode, cipher_algo, aead_algo, hash_algo, seskeylen, minlen;
1206
1207   if (pktlen < 4)
1208     goto too_short;
1209   version = iobuf_get_noeof (inp);
1210   pktlen--;
1211   if (version == 4)
1212     ;
1213   else if (version == 5)
1214     ;
1215   else
1216     {
1217       log_error ("packet(%d) with unknown version %d\n", pkttype, version);
1218       if (list_mode)
1219         es_fprintf (listfp, ":symkey enc packet: [unknown version]\n");
1220       rc = gpg_error (GPG_ERR_INV_PACKET);
1221       goto leave;
1222     }
1223   if (pktlen > 200)
1224     {                           /* (we encode the seskeylen in a byte) */
1225       log_error ("packet(%d) too large\n", pkttype);
1226       if (list_mode)
1227         es_fprintf (listfp, ":symkey enc packet: [too large]\n");
1228       rc = gpg_error (GPG_ERR_INV_PACKET);
1229       goto leave;
1230     }
1231   cipher_algo = iobuf_get_noeof (inp);
1232   pktlen--;
1233   if (version == 5)
1234     {
1235       aead_algo = iobuf_get_noeof (inp);
1236       pktlen--;
1237     }
1238   else
1239     aead_algo = 0;
1240   if (pktlen < 2)
1241     goto too_short;
1242   s2kmode = iobuf_get_noeof (inp);
1243   pktlen--;
1244   hash_algo = iobuf_get_noeof (inp);
1245   pktlen--;
1246   switch (s2kmode)
1247     {
1248     case 0: /* Simple S2K.  */
1249       minlen = 0;
1250       break;
1251     case 1: /* Salted S2K.  */
1252       minlen = 8;
1253       break;
1254     case 3: /* Iterated+salted S2K.  */
1255       minlen = 9;
1256       break;
1257     default:
1258       log_error ("unknown S2K mode %d\n", s2kmode);
1259       if (list_mode)
1260         es_fprintf (listfp, ":symkey enc packet: [unknown S2K mode]\n");
1261       goto leave;
1262     }
1263   if (minlen > pktlen)
1264     {
1265       log_error ("packet with S2K %d too short\n", s2kmode);
1266       if (list_mode)
1267         es_fprintf (listfp, ":symkey enc packet: [too short]\n");
1268       rc = gpg_error (GPG_ERR_INV_PACKET);
1269       goto leave;
1270     }
1271   seskeylen = pktlen - minlen;
1272   k = packet->pkt.symkey_enc = xmalloc_clear (sizeof *packet->pkt.symkey_enc
1273                                               + seskeylen - 1);
1274   k->version = version;
1275   k->cipher_algo = cipher_algo;
1276   k->aead_algo = aead_algo;
1277   k->s2k.mode = s2kmode;
1278   k->s2k.hash_algo = hash_algo;
1279   if (s2kmode == 1 || s2kmode == 3)
1280     {
1281       for (i = 0; i < 8 && pktlen; i++, pktlen--)
1282         k->s2k.salt[i] = iobuf_get_noeof (inp);
1283     }
1284   if (s2kmode == 3)
1285     {
1286       k->s2k.count = iobuf_get_noeof (inp);
1287       pktlen--;
1288     }
1289   k->seskeylen = seskeylen;
1290   if (k->seskeylen)
1291     {
1292       for (i = 0; i < seskeylen && pktlen; i++, pktlen--)
1293         k->seskey[i] = iobuf_get_noeof (inp);
1294
1295       /* What we're watching out for here is a session key decryptor
1296          with no salt.  The RFC says that using salt for this is a
1297          MUST. */
1298       if (s2kmode != 1 && s2kmode != 3)
1299         log_info (_("WARNING: potentially insecure symmetrically"
1300                     " encrypted session key\n"));
1301     }
1302   log_assert (!pktlen);
1303
1304   if (list_mode)
1305     {
1306       es_fprintf (listfp,
1307                   ":symkey enc packet: version %d, cipher %d, aead %d,"
1308                   " s2k %d, hash %d",
1309                   version, cipher_algo, aead_algo, s2kmode, hash_algo);
1310       if (seskeylen)
1311         {
1312           /* To compute the size of the session key we need to know
1313            * the size of the AEAD nonce which we may not know.  Thus
1314            * we show only the size of the entire encrypted session
1315            * key.  */
1316           if (aead_algo)
1317             es_fprintf (listfp, ", encrypted seskey %d bytes", seskeylen);
1318           else
1319             es_fprintf (listfp, ", seskey %d bits", (seskeylen - 1) * 8);
1320         }
1321       es_fprintf (listfp, "\n");
1322       if (s2kmode == 1 || s2kmode == 3)
1323         {
1324           es_fprintf (listfp, "\tsalt ");
1325           es_write_hexstring (listfp, k->s2k.salt, 8, 0, NULL);
1326           if (s2kmode == 3)
1327             es_fprintf (listfp, ", count %lu (%lu)",
1328                         S2K_DECODE_COUNT ((ulong) k->s2k.count),
1329                         (ulong) k->s2k.count);
1330           es_fprintf (listfp, "\n");
1331         }
1332     }
1333
1334  leave:
1335   iobuf_skip_rest (inp, pktlen, 0);
1336   return rc;
1337
1338  too_short:
1339   log_error ("packet(%d) too short\n", pkttype);
1340   if (list_mode)
1341     es_fprintf (listfp, ":symkey enc packet: [too short]\n");
1342   rc = gpg_error (GPG_ERR_INV_PACKET);
1343   goto leave;
1344 }
1345
1346
1347 static int
1348 parse_pubkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
1349                  PACKET * packet)
1350 {
1351   int rc = 0;
1352   int i, ndata;
1353   PKT_pubkey_enc *k;
1354
1355   k = packet->pkt.pubkey_enc = xmalloc_clear (sizeof *packet->pkt.pubkey_enc);
1356   if (pktlen < 12)
1357     {
1358       log_error ("packet(%d) too short\n", pkttype);
1359       if (list_mode)
1360         es_fputs (":pubkey enc packet: [too short]\n", listfp);
1361       rc = gpg_error (GPG_ERR_INV_PACKET);
1362       goto leave;
1363     }
1364   k->version = iobuf_get_noeof (inp);
1365   pktlen--;
1366   if (k->version != 2 && k->version != 3)
1367     {
1368       log_error ("packet(%d) with unknown version %d\n", pkttype, k->version);
1369       if (list_mode)
1370         es_fputs (":pubkey enc packet: [unknown version]\n", listfp);
1371       rc = gpg_error (GPG_ERR_INV_PACKET);
1372       goto leave;
1373     }
1374   k->keyid[0] = read_32 (inp);
1375   pktlen -= 4;
1376   k->keyid[1] = read_32 (inp);
1377   pktlen -= 4;
1378   k->pubkey_algo = iobuf_get_noeof (inp);
1379   pktlen--;
1380   k->throw_keyid = 0;  /* Only used as flag for build_packet.  */
1381   if (list_mode)
1382     es_fprintf (listfp,
1383                 ":pubkey enc packet: version %d, algo %d, keyid %08lX%08lX\n",
1384                 k->version, k->pubkey_algo, (ulong) k->keyid[0],
1385                 (ulong) k->keyid[1]);
1386
1387   ndata = pubkey_get_nenc (k->pubkey_algo);
1388   if (!ndata)
1389     {
1390       if (list_mode)
1391         es_fprintf (listfp, "\tunsupported algorithm %d\n", k->pubkey_algo);
1392       unknown_pubkey_warning (k->pubkey_algo);
1393       k->data[0] = NULL; /* No need to store the encrypted data.  */
1394     }
1395   else
1396     {
1397       for (i = 0; i < ndata; i++)
1398         {
1399           if (k->pubkey_algo == PUBKEY_ALGO_ECDH)
1400             {
1401               if (i == 1)
1402                 {
1403                   size_t n;
1404                   rc = read_size_body (inp, pktlen, &n, k->data+i);
1405                   pktlen -= n;
1406                 }
1407               else
1408                 {
1409                   int n = pktlen;
1410                   k->data[i] = sos_read (inp, &n, 0);
1411                   pktlen -= n;
1412                   if (!k->data[i])
1413                     rc = gpg_error (GPG_ERR_INV_PACKET);
1414                 }
1415             }
1416           else
1417             {
1418               int n = pktlen;
1419               k->data[i] = mpi_read (inp, &n, 0);
1420               pktlen -= n;
1421               if (!k->data[i])
1422                 rc = gpg_error (GPG_ERR_INV_PACKET);
1423             }
1424           if (rc)
1425             goto leave;
1426           if (list_mode)
1427             {
1428               es_fprintf (listfp, "\tdata: ");
1429               mpi_print (listfp, k->data[i], mpi_print_mode);
1430               es_putc ('\n', listfp);
1431             }
1432         }
1433     }
1434
1435  leave:
1436   iobuf_skip_rest (inp, pktlen, 0);
1437   return rc;
1438 }
1439
1440
1441 /* Dump a subpacket to LISTFP.  BUFFER contains the subpacket in
1442  * question and points to the type field in the subpacket header (not
1443  * the start of the header).  TYPE is the subpacket's type with the
1444  * critical bit cleared.  CRITICAL is the value of the CRITICAL bit.
1445  * BUFLEN is the length of the buffer and LENGTH is the length of the
1446  * subpacket according to the subpacket's header.  DIGEST_ALGO is the
1447  * digest algo of the signature.  */
1448 static void
1449 dump_sig_subpkt (int hashed, int type, int critical,
1450                  const byte * buffer, size_t buflen, size_t length,
1451                  int digest_algo)
1452 {
1453   const char *p = NULL;
1454   int i;
1455   int nprinted;
1456
1457   /* The CERT has warning out with explains how to use GNUPG to detect
1458    * the ARRs - we print our old message here when it is a faked ARR
1459    * and add an additional notice.  */
1460   if (type == SIGSUBPKT_ARR && !hashed)
1461     {
1462       es_fprintf (listfp,
1463                   "\tsubpkt %d len %u (additional recipient request)\n"
1464                   "WARNING: PGP versions > 5.0 and < 6.5.8 will automagically "
1465                   "encrypt to this key and thereby reveal the plaintext to "
1466                   "the owner of this ARR key. Detailed info follows:\n",
1467                   type, (unsigned) length);
1468     }
1469
1470   buffer++;
1471   length--;
1472
1473   nprinted = es_fprintf (listfp, "\t%s%ssubpkt %d len %u (",    /*) */
1474                          critical ? "critical " : "",
1475                          hashed ? "hashed " : "", type, (unsigned) length);
1476   if (nprinted < 1)
1477     nprinted = 1; /*(we use (nprinted-1) later.)*/
1478   if (length > buflen)
1479     {
1480       es_fprintf (listfp, "too short: buffer is only %u)\n", (unsigned) buflen);
1481       return;
1482     }
1483   switch (type)
1484     {
1485     case SIGSUBPKT_SIG_CREATED:
1486       if (length >= 4)
1487         es_fprintf (listfp, "sig created %s",
1488                     strtimestamp (buf32_to_u32 (buffer)));
1489       break;
1490     case SIGSUBPKT_SIG_EXPIRE:
1491       if (length >= 4)
1492         {
1493           if (buf32_to_u32 (buffer))
1494             es_fprintf (listfp, "sig expires after %s",
1495                         strtimevalue (buf32_to_u32 (buffer)));
1496           else
1497             es_fprintf (listfp, "sig does not expire");
1498         }
1499       break;
1500     case SIGSUBPKT_EXPORTABLE:
1501       if (length)
1502         es_fprintf (listfp, "%sexportable", *buffer ? "" : "not ");
1503       break;
1504     case SIGSUBPKT_TRUST:
1505       if (length != 2)
1506         p = "[invalid trust subpacket]";
1507       else
1508         es_fprintf (listfp, "trust signature of depth %d, value %d", buffer[0],
1509                     buffer[1]);
1510       break;
1511     case SIGSUBPKT_REGEXP:
1512       if (!length)
1513         p = "[invalid regexp subpacket]";
1514       else
1515         {
1516           es_fprintf (listfp, "regular expression: \"");
1517           es_write_sanitized (listfp, buffer, length, "\"", NULL);
1518           p = "\"";
1519         }
1520       break;
1521     case SIGSUBPKT_REVOCABLE:
1522       if (length)
1523         es_fprintf (listfp, "%srevocable", *buffer ? "" : "not ");
1524       break;
1525     case SIGSUBPKT_KEY_EXPIRE:
1526       if (length >= 4)
1527         {
1528           if (buf32_to_u32 (buffer))
1529             es_fprintf (listfp, "key expires after %s",
1530                         strtimevalue (buf32_to_u32 (buffer)));
1531           else
1532             es_fprintf (listfp, "key does not expire");
1533         }
1534       break;
1535     case SIGSUBPKT_PREF_SYM:
1536       es_fputs ("pref-sym-algos:", listfp);
1537       for (i = 0; i < length; i++)
1538         es_fprintf (listfp, " %d", buffer[i]);
1539       break;
1540     case SIGSUBPKT_PREF_AEAD:
1541       es_fputs ("pref-aead-algos:", listfp);
1542       for (i = 0; i < length; i++)
1543         es_fprintf (listfp, " %d", buffer[i]);
1544       break;
1545     case SIGSUBPKT_REV_KEY:
1546       es_fputs ("revocation key: ", listfp);
1547       if (length < 22)
1548         p = "[too short]";
1549       else
1550         {
1551           es_fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]);
1552           for (i = 2; i < length; i++)
1553             es_fprintf (listfp, "%02X", buffer[i]);
1554         }
1555       break;
1556     case SIGSUBPKT_ISSUER:
1557       if (length >= 8)
1558         es_fprintf (listfp, "issuer key ID %08lX%08lX",
1559                     (ulong) buf32_to_u32 (buffer),
1560                     (ulong) buf32_to_u32 (buffer + 4));
1561       break;
1562     case SIGSUBPKT_ISSUER_FPR:
1563       if (length >= 21)
1564         {
1565           char *tmp;
1566           es_fprintf (listfp, "issuer fpr v%d ", buffer[0]);
1567           tmp = bin2hex (buffer+1, length-1, NULL);
1568           if (tmp)
1569             {
1570               es_fputs (tmp, listfp);
1571               xfree (tmp);
1572             }
1573         }
1574       break;
1575     case SIGSUBPKT_NOTATION:
1576       {
1577         es_fputs ("notation: ", listfp);
1578         if (length < 8)
1579           p = "[too short]";
1580         else
1581           {
1582             const byte *s = buffer;
1583             size_t n1, n2;
1584
1585             n1 = (s[4] << 8) | s[5];
1586             n2 = (s[6] << 8) | s[7];
1587             s += 8;
1588             if (8 + n1 + n2 != length)
1589               p = "[error]";
1590             else
1591               {
1592                 es_write_sanitized (listfp, s, n1, ")", NULL);
1593                 es_putc ('=', listfp);
1594
1595                 if (*buffer & 0x80)
1596                   es_write_sanitized (listfp, s + n1, n2, ")", NULL);
1597                 else
1598                   p = "[not human readable]";
1599               }
1600           }
1601       }
1602       break;
1603     case SIGSUBPKT_PREF_HASH:
1604       es_fputs ("pref-hash-algos:", listfp);
1605       for (i = 0; i < length; i++)
1606         es_fprintf (listfp, " %d", buffer[i]);
1607       break;
1608     case SIGSUBPKT_PREF_COMPR:
1609       es_fputs ("pref-zip-algos:", listfp);
1610       for (i = 0; i < length; i++)
1611         es_fprintf (listfp, " %d", buffer[i]);
1612       break;
1613     case SIGSUBPKT_KS_FLAGS:
1614       es_fputs ("keyserver preferences:", listfp);
1615       for (i = 0; i < length; i++)
1616         es_fprintf (listfp, " %02X", buffer[i]);
1617       break;
1618     case SIGSUBPKT_PREF_KS:
1619       es_fputs ("preferred keyserver: ", listfp);
1620       es_write_sanitized (listfp, buffer, length, ")", NULL);
1621       break;
1622     case SIGSUBPKT_PRIMARY_UID:
1623       p = "primary user ID";
1624       break;
1625     case SIGSUBPKT_POLICY:
1626       es_fputs ("policy: ", listfp);
1627       es_write_sanitized (listfp, buffer, length, ")", NULL);
1628       break;
1629     case SIGSUBPKT_KEY_FLAGS:
1630       es_fputs ("key flags:", listfp);
1631       for (i = 0; i < length; i++)
1632         es_fprintf (listfp, " %02X", buffer[i]);
1633       break;
1634     case SIGSUBPKT_SIGNERS_UID:
1635       p = "signer's user ID";
1636       break;
1637     case SIGSUBPKT_REVOC_REASON:
1638       if (length)
1639         {
1640           es_fprintf (listfp, "revocation reason 0x%02x (", *buffer);
1641           es_write_sanitized (listfp, buffer + 1, length - 1, ")", NULL);
1642           p = ")";
1643         }
1644       break;
1645     case SIGSUBPKT_ARR:
1646       es_fputs ("Big Brother's key (ignored): ", listfp);
1647       if (length < 22)
1648         p = "[too short]";
1649       else
1650         {
1651           es_fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]);
1652           if (length > 2)
1653             es_write_hexstring (listfp, buffer+2, length-2, 0, NULL);
1654         }
1655       break;
1656     case SIGSUBPKT_FEATURES:
1657       es_fputs ("features:", listfp);
1658       for (i = 0; i < length; i++)
1659         es_fprintf (listfp, " %02x", buffer[i]);
1660       break;
1661     case SIGSUBPKT_SIGNATURE:
1662       es_fputs ("signature: ", listfp);
1663       if (length < 17)
1664         p = "[too short]";
1665       else
1666         es_fprintf (listfp, "v%d, class 0x%02X, algo %d, digest algo %d",
1667                     buffer[0],
1668                     buffer[0] == 3 ? buffer[2] : buffer[1],
1669                     buffer[0] == 3 ? buffer[15] : buffer[2],
1670                     buffer[0] == 3 ? buffer[16] : buffer[3]);
1671       break;
1672
1673     case SIGSUBPKT_ATTST_SIGS:
1674       {
1675         unsigned int hlen;
1676
1677         es_fputs ("attst-sigs: ", listfp);
1678         hlen = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (digest_algo));
1679         if (!hlen)
1680           p = "[unknown digest algo]";
1681         else if ((length % hlen))
1682           p = "[invalid length]";
1683         else
1684           {
1685             es_fprintf (listfp, "%u", (unsigned int)length/hlen);
1686             while (length)
1687               {
1688                 es_fprintf (listfp, "\n\t%*s", nprinted-1, "");
1689                 es_write_hexstring (listfp, buffer, hlen, 0, NULL);
1690                 buffer += hlen;
1691                 length -= hlen;
1692               }
1693           }
1694       }
1695       break;
1696
1697     case SIGSUBPKT_KEY_BLOCK:
1698       es_fputs ("key-block: ", listfp);
1699       if (length && buffer[0])
1700         p = "[unknown reserved octet]";
1701       else if (length < 50)  /* 50 is an arbitrary min. length.  */
1702         p = "[invalid subpacket]";
1703       else
1704         {
1705           /* estream_t fp; */
1706           /* fp = es_fopen ("a.key-block", "wb"); */
1707           /* log_assert (fp); */
1708           /* es_fwrite ( buffer+1, length-1, 1, fp); */
1709           /* es_fclose (fp); */
1710           es_fprintf (listfp, "[%u octets]", (unsigned int)length-1);
1711         }
1712       break;
1713
1714
1715     default:
1716       if (type >= 100 && type <= 110)
1717         p = "experimental / private subpacket";
1718       else
1719         p = "?";
1720       break;
1721     }
1722
1723   es_fprintf (listfp, "%s)\n", p ? p : "");
1724 }
1725
1726
1727 /*
1728  * Returns: >= 0 use this offset into buffer
1729  *          -1 explicitly reject returning this type
1730  *          -2 subpacket too short
1731  */
1732 int
1733 parse_one_sig_subpkt (const byte * buffer, size_t n, int type)
1734 {
1735   switch (type)
1736     {
1737     case SIGSUBPKT_REV_KEY:
1738       if (n < 22)
1739         break;
1740       return 0;
1741     case SIGSUBPKT_SIG_CREATED:
1742     case SIGSUBPKT_SIG_EXPIRE:
1743     case SIGSUBPKT_KEY_EXPIRE:
1744       if (n < 4)
1745         break;
1746       return 0;
1747     case SIGSUBPKT_KEY_FLAGS:
1748     case SIGSUBPKT_KS_FLAGS:
1749     case SIGSUBPKT_PREF_SYM:
1750     case SIGSUBPKT_PREF_AEAD:
1751     case SIGSUBPKT_PREF_HASH:
1752     case SIGSUBPKT_PREF_COMPR:
1753     case SIGSUBPKT_POLICY:
1754     case SIGSUBPKT_PREF_KS:
1755     case SIGSUBPKT_FEATURES:
1756     case SIGSUBPKT_REGEXP:
1757     case SIGSUBPKT_ATTST_SIGS:
1758       return 0;
1759     case SIGSUBPKT_SIGNATURE:
1760     case SIGSUBPKT_EXPORTABLE:
1761     case SIGSUBPKT_REVOCABLE:
1762     case SIGSUBPKT_REVOC_REASON:
1763       if (!n)
1764         break;
1765       return 0;
1766     case SIGSUBPKT_ISSUER:      /* issuer key ID */
1767       if (n < 8)
1768         break;
1769       return 0;
1770     case SIGSUBPKT_ISSUER_FPR:  /* issuer key fingerprint */
1771       if (n < 21)
1772         break;
1773       return 0;
1774     case SIGSUBPKT_NOTATION:
1775       /* minimum length needed, and the subpacket must be well-formed
1776          where the name length and value length all fit inside the
1777          packet. */
1778       if (n < 8
1779           || 8 + ((buffer[4] << 8) | buffer[5]) +
1780           ((buffer[6] << 8) | buffer[7]) != n)
1781         break;
1782       return 0;
1783     case SIGSUBPKT_PRIMARY_UID:
1784       if (n != 1)
1785         break;
1786       return 0;
1787     case SIGSUBPKT_TRUST:
1788       if (n != 2)
1789         break;
1790       return 0;
1791     case SIGSUBPKT_KEY_BLOCK:
1792       if (n && buffer[0])
1793         return -1; /* Unknown version - ignore.  */
1794       if (n < 50)
1795         break;  /* Definitely too short to carry a key block.  */
1796       return 0;
1797     default:
1798       return 0;
1799     }
1800   return -2;
1801 }
1802
1803
1804 /* Return true if we understand the critical notation.  */
1805 static int
1806 can_handle_critical_notation (const byte *name, size_t len)
1807 {
1808   strlist_t sl;
1809
1810   register_known_notation (NULL); /* Make sure it is initialized.  */
1811
1812   for (sl = known_notations_list; sl; sl = sl->next)
1813     if (sl->flags == len && !memcmp (sl->d, name, len))
1814       return 1; /* Known */
1815
1816   if (opt.verbose && !glo_ctrl.silence_parse_warnings)
1817     {
1818       log_info(_("Unknown critical signature notation: ") );
1819       print_utf8_buffer (log_get_stream(), name, len);
1820       log_printf ("\n");
1821     }
1822
1823   return 0; /* Unknown.  */
1824 }
1825
1826
1827 static int
1828 can_handle_critical (const byte * buffer, size_t n, int type)
1829 {
1830   switch (type)
1831     {
1832     case SIGSUBPKT_NOTATION:
1833       if (n >= 8)
1834         {
1835           size_t notation_len = ((buffer[4] << 8) | buffer[5]);
1836           if (n - 8 >= notation_len)
1837             return can_handle_critical_notation (buffer + 8, notation_len);
1838         }
1839       return 0;
1840     case SIGSUBPKT_SIGNATURE:
1841     case SIGSUBPKT_SIG_CREATED:
1842     case SIGSUBPKT_SIG_EXPIRE:
1843     case SIGSUBPKT_KEY_EXPIRE:
1844     case SIGSUBPKT_EXPORTABLE:
1845     case SIGSUBPKT_REVOCABLE:
1846     case SIGSUBPKT_REV_KEY:
1847     case SIGSUBPKT_ISSUER:      /* issuer key ID */
1848     case SIGSUBPKT_ISSUER_FPR:  /* issuer fingerprint */
1849     case SIGSUBPKT_PREF_SYM:
1850     case SIGSUBPKT_PREF_AEAD:
1851     case SIGSUBPKT_PREF_HASH:
1852     case SIGSUBPKT_PREF_COMPR:
1853     case SIGSUBPKT_KEY_FLAGS:
1854     case SIGSUBPKT_PRIMARY_UID:
1855     case SIGSUBPKT_FEATURES:
1856     case SIGSUBPKT_TRUST:
1857     case SIGSUBPKT_REGEXP:
1858     case SIGSUBPKT_ATTST_SIGS:
1859       /* Is it enough to show the policy or keyserver? */
1860     case SIGSUBPKT_POLICY:
1861     case SIGSUBPKT_PREF_KS:
1862     case SIGSUBPKT_REVOC_REASON: /* At least we know about it.  */
1863       return 1;
1864
1865     case SIGSUBPKT_KEY_BLOCK:
1866       if (n && !buffer[0])
1867         return 1;
1868       else
1869         return 0;
1870
1871     default:
1872       return 0;
1873     }
1874 }
1875
1876
1877 const byte *
1878 enum_sig_subpkt (PKT_signature *sig, int want_hashed, sigsubpkttype_t reqtype,
1879                  size_t *ret_n, int *start, int *critical)
1880 {
1881   const byte *buffer;
1882   int buflen;
1883   int type;
1884   int critical_dummy;
1885   int offset;
1886   size_t n;
1887   const subpktarea_t *pktbuf = want_hashed? sig->hashed : sig->unhashed;
1888   int seq = 0;
1889   int reqseq = start ? *start : 0;
1890
1891   if (!critical)
1892     critical = &critical_dummy;
1893
1894   if (!pktbuf || reqseq == -1)
1895     {
1896       static char dummy[] = "x";
1897       /* Return a value different from NULL to indicate that
1898        * there is no critical bit we do not understand.  */
1899       return reqtype == SIGSUBPKT_TEST_CRITICAL ? dummy : NULL;
1900     }
1901   buffer = pktbuf->data;
1902   buflen = pktbuf->len;
1903   while (buflen)
1904     {
1905       n = *buffer++;
1906       buflen--;
1907       if (n == 255) /* 4 byte length header.  */
1908         {
1909           if (buflen < 4)
1910             goto too_short;
1911           n = buf32_to_size_t (buffer);
1912           buffer += 4;
1913           buflen -= 4;
1914         }
1915       else if (n >= 192) /* 4 byte special encoded length header.  */
1916         {
1917           if (buflen < 2)
1918             goto too_short;
1919           n = ((n - 192) << 8) + *buffer + 192;
1920           buffer++;
1921           buflen--;
1922         }
1923       if (buflen < n)
1924         goto too_short;
1925       if (!buflen)
1926         goto no_type_byte;
1927       type = *buffer;
1928       if (type & 0x80)
1929         {
1930           type &= 0x7f;
1931           *critical = 1;
1932         }
1933       else
1934         *critical = 0;
1935       if (!(++seq > reqseq))
1936         ;
1937       else if (reqtype == SIGSUBPKT_TEST_CRITICAL)
1938         {
1939           if (*critical)
1940             {
1941               if (n - 1 > buflen + 1)
1942                 goto too_short;
1943               if (!can_handle_critical (buffer + 1, n - 1, type))
1944                 {
1945                   if (opt.verbose && !glo_ctrl.silence_parse_warnings)
1946                     log_info (_("subpacket of type %d has "
1947                                 "critical bit set\n"), type);
1948                   if (start)
1949                     *start = seq;
1950                   return NULL;  /* This is an error.  */
1951                 }
1952             }
1953         }
1954       else if (reqtype < 0) /* List packets.  */
1955         dump_sig_subpkt (reqtype == SIGSUBPKT_LIST_HASHED,
1956                          type, *critical, buffer, buflen, n, sig->digest_algo);
1957       else if (type == reqtype) /* Found.  */
1958         {
1959           buffer++;
1960           n--;
1961           if (n > buflen)
1962             goto too_short;
1963           if (ret_n)
1964             *ret_n = n;
1965           offset = parse_one_sig_subpkt (buffer, n, type);
1966           switch (offset)
1967             {
1968             case -2:
1969               log_error ("subpacket of type %d too short\n", type);
1970               return NULL;
1971             case -1:
1972               return NULL;
1973             default:
1974               break;
1975             }
1976           if (start)
1977             *start = seq;
1978           return buffer + offset;
1979         }
1980       buffer += n;
1981       buflen -= n;
1982     }
1983   if (reqtype == SIGSUBPKT_TEST_CRITICAL)
1984     /* Returning NULL means we found a subpacket with the critical bit
1985        set that we don't grok.  We've iterated over all the subpackets
1986        and haven't found such a packet so we need to return a non-NULL
1987        value.  */
1988     return buffer;
1989
1990   /* Critical bit we don't understand. */
1991   if (start)
1992     *start = -1;
1993   return NULL;  /* End of packets; not found.  */
1994
1995  too_short:
1996   if (opt.debug && !glo_ctrl.silence_parse_warnings)
1997     {
1998       es_fflush (es_stdout);
1999       log_printhex (pktbuf->data, pktbuf->len > 16? 16 : pktbuf->len,
2000                     "buffer shorter than subpacket (%zu/%d/%zu); dump:",
2001                     pktbuf->len, buflen, n);
2002     }
2003
2004   if (start)
2005     *start = -1;
2006   return NULL;
2007
2008  no_type_byte:
2009   if (opt.verbose && !glo_ctrl.silence_parse_warnings)
2010     log_info ("type octet missing in subpacket\n");
2011   if (start)
2012     *start = -1;
2013   return NULL;
2014 }
2015
2016
2017 const byte *
2018 parse_sig_subpkt (PKT_signature *sig, int want_hashed, sigsubpkttype_t reqtype,
2019                   size_t *ret_n)
2020 {
2021   return enum_sig_subpkt (sig, want_hashed, reqtype, ret_n, NULL, NULL);
2022 }
2023
2024
2025 const byte *
2026 parse_sig_subpkt2 (PKT_signature *sig, sigsubpkttype_t reqtype)
2027 {
2028   const byte *p;
2029
2030   p = parse_sig_subpkt (sig, 1, reqtype, NULL);
2031   if (!p)
2032     p = parse_sig_subpkt (sig, 0, reqtype, NULL);
2033   return p;
2034 }
2035
2036
2037 /* Find all revocation keys.  Look in hashed area only.  */
2038 void
2039 parse_revkeys (PKT_signature * sig)
2040 {
2041   const byte *revkey;
2042   int seq = 0;
2043   size_t len;
2044
2045   if (sig->sig_class != 0x1F)
2046     return;
2047
2048   while ((revkey = enum_sig_subpkt (sig, 1, SIGSUBPKT_REV_KEY,
2049                                     &len, &seq, NULL)))
2050     {
2051       /* Consider only valid packets.  They must have a length of
2052        * either 2+20 or 2+32 octets and bit 7 of the class octet must
2053        * be set.  */
2054       if ((len == 22 || len == 34)
2055           && (revkey[0] & 0x80))
2056         {
2057           sig->revkey = xrealloc (sig->revkey,
2058                                   sizeof (struct revocation_key) *
2059                                   (sig->numrevkeys + 1));
2060
2061           sig->revkey[sig->numrevkeys].class = revkey[0];
2062           sig->revkey[sig->numrevkeys].algid = revkey[1];
2063           len -= 2;
2064           sig->revkey[sig->numrevkeys].fprlen = len;
2065           memcpy (sig->revkey[sig->numrevkeys].fpr, revkey+2, len);
2066           memset (sig->revkey[sig->numrevkeys].fpr+len, 0,
2067                   sizeof (sig->revkey[sig->numrevkeys].fpr) - len);
2068           sig->numrevkeys++;
2069         }
2070     }
2071 }
2072
2073
2074 int
2075 parse_signature (IOBUF inp, int pkttype, unsigned long pktlen,
2076                  PKT_signature * sig)
2077 {
2078   int md5_len = 0;
2079   unsigned n;
2080   int is_v4or5 = 0;
2081   int rc = 0;
2082   int i, ndata;
2083
2084   if (pktlen < 16)
2085     {
2086       log_error ("packet(%d) too short\n", pkttype);
2087       if (list_mode)
2088         es_fputs (":signature packet: [too short]\n", listfp);
2089       goto leave;
2090     }
2091   sig->version = iobuf_get_noeof (inp);
2092   pktlen--;
2093   if (sig->version == 4 || sig->version == 5)
2094     is_v4or5 = 1;
2095   else if (sig->version != 2 && sig->version != 3)
2096     {
2097       log_error ("packet(%d) with unknown version %d\n",
2098                  pkttype, sig->version);
2099       if (list_mode)
2100         es_fputs (":signature packet: [unknown version]\n", listfp);
2101       rc = gpg_error (GPG_ERR_INV_PACKET);
2102       goto leave;
2103     }
2104
2105   if (!is_v4or5)
2106     {
2107       if (pktlen == 0)
2108         goto underflow;
2109       md5_len = iobuf_get_noeof (inp);
2110       pktlen--;
2111     }
2112   if (pktlen == 0)
2113     goto underflow;
2114   sig->sig_class = iobuf_get_noeof (inp);
2115   pktlen--;
2116   if (!is_v4or5)
2117     {
2118       if (pktlen < 12)
2119         goto underflow;
2120       sig->timestamp = read_32 (inp);
2121       pktlen -= 4;
2122       sig->keyid[0] = read_32 (inp);
2123       pktlen -= 4;
2124       sig->keyid[1] = read_32 (inp);
2125       pktlen -= 4;
2126     }
2127   if (pktlen < 2)
2128     goto underflow;
2129   sig->pubkey_algo = iobuf_get_noeof (inp);
2130   pktlen--;
2131   sig->digest_algo = iobuf_get_noeof (inp);
2132   pktlen--;
2133   sig->flags.exportable = 1;
2134   sig->flags.revocable = 1;
2135   if (is_v4or5) /* Read subpackets.  */
2136     {
2137       if (pktlen < 2)
2138         goto underflow;
2139       n = read_16 (inp);
2140       pktlen -= 2;  /* Length of hashed data. */
2141       if (pktlen < n)
2142         goto underflow;
2143       if (n > 10000)
2144         {
2145           log_error ("signature packet: hashed data too long\n");
2146           if (list_mode)
2147             es_fputs (":signature packet: [hashed data too long]\n", listfp);
2148           rc = GPG_ERR_INV_PACKET;
2149           goto leave;
2150         }
2151       if (n)
2152         {
2153           sig->hashed = xmalloc (sizeof (*sig->hashed) + n - 1);
2154           sig->hashed->size = n;
2155           sig->hashed->len = n;
2156           if (iobuf_read (inp, sig->hashed->data, n) != n)
2157             {
2158               log_error ("premature eof while reading "
2159                          "hashed signature data\n");
2160               if (list_mode)
2161                 es_fputs (":signature packet: [premature eof]\n", listfp);
2162               rc = -1;
2163               goto leave;
2164             }
2165           pktlen -= n;
2166         }
2167       if (pktlen < 2)
2168         goto underflow;
2169       n = read_16 (inp);
2170       pktlen -= 2;  /* Length of unhashed data.  */
2171       if (pktlen < n)
2172         goto underflow;
2173       if (n > 10000)
2174         {
2175           log_error ("signature packet: unhashed data too long\n");
2176           if (list_mode)
2177             es_fputs (":signature packet: [unhashed data too long]\n", listfp);
2178           rc = GPG_ERR_INV_PACKET;
2179           goto leave;
2180         }
2181       if (n)
2182         {
2183           sig->unhashed = xmalloc (sizeof (*sig->unhashed) + n - 1);
2184           sig->unhashed->size = n;
2185           sig->unhashed->len = n;
2186           if (iobuf_read (inp, sig->unhashed->data, n) != n)
2187             {
2188               log_error ("premature eof while reading "
2189                          "unhashed signature data\n");
2190               if (list_mode)
2191                 es_fputs (":signature packet: [premature eof]\n", listfp);
2192               rc = -1;
2193               goto leave;
2194             }
2195           pktlen -= n;
2196         }
2197     }
2198
2199   if (pktlen < 2)
2200     goto underflow;
2201   sig->digest_start[0] = iobuf_get_noeof (inp);
2202   pktlen--;
2203   sig->digest_start[1] = iobuf_get_noeof (inp);
2204   pktlen--;
2205
2206   if (is_v4or5 && sig->pubkey_algo)  /* Extract required information.  */
2207     {
2208       const byte *p;
2209       size_t len;
2210
2211       /* Set sig->flags.unknown_critical if there is a critical bit
2212        * set for packets which we do not understand.  */
2213       if (!parse_sig_subpkt (sig, 1, SIGSUBPKT_TEST_CRITICAL, NULL)
2214           || !parse_sig_subpkt (sig, 0, SIGSUBPKT_TEST_CRITICAL, NULL))
2215         sig->flags.unknown_critical = 1;
2216
2217       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_SIG_CREATED, NULL);
2218       if (p)
2219         sig->timestamp = buf32_to_u32 (p);
2220       else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110)
2221                && opt.verbose > 1 && !glo_ctrl.silence_parse_warnings)
2222         log_info ("signature packet without timestamp\n");
2223
2224       /* Set the key id.  We first try the issuer fingerprint and if
2225        * it is a v4 signature the fallback to the issuer.  Note that
2226        * only the issuer packet is also searched in the unhashed area.  */
2227       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_ISSUER_FPR, &len);
2228       if (p && len == 21 && p[0] == 4)
2229         {
2230           sig->keyid[0] = buf32_to_u32 (p + 1 + 12);
2231           sig->keyid[1] = buf32_to_u32 (p + 1 + 16);
2232         }
2233       else if (p && len == 33 && p[0] == 5)
2234         {
2235           sig->keyid[0] = buf32_to_u32 (p + 1 );
2236           sig->keyid[1] = buf32_to_u32 (p + 1 + 4);
2237         }
2238       else if ((p = parse_sig_subpkt2 (sig, SIGSUBPKT_ISSUER)))
2239         {
2240           sig->keyid[0] = buf32_to_u32 (p);
2241           sig->keyid[1] = buf32_to_u32 (p + 4);
2242         }
2243       else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110)
2244                && opt.verbose > 1 && !glo_ctrl.silence_parse_warnings)
2245         log_info ("signature packet without keyid\n");
2246
2247       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_SIG_EXPIRE, NULL);
2248       if (p && buf32_to_u32 (p))
2249         sig->expiredate = sig->timestamp + buf32_to_u32 (p);
2250       if (sig->expiredate && sig->expiredate <= make_timestamp ())
2251         sig->flags.expired = 1;
2252
2253       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_POLICY, NULL);
2254       if (p)
2255         sig->flags.policy_url = 1;
2256
2257       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_KS, NULL);
2258       if (p)
2259         sig->flags.pref_ks = 1;
2260
2261       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_SIGNERS_UID, &len);
2262       if (p && len)
2263         {
2264           char *mbox;
2265
2266           sig->signers_uid = try_make_printable_string (p, len, 0);
2267           if (!sig->signers_uid)
2268             {
2269               rc = gpg_error_from_syserror ();
2270               goto leave;
2271             }
2272           mbox = mailbox_from_userid (sig->signers_uid, 0);
2273           if (mbox)
2274             {
2275               xfree (sig->signers_uid);
2276               sig->signers_uid = mbox;
2277             }
2278         }
2279
2280       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_BLOCK, NULL);
2281       if (p)
2282         sig->flags.key_block = 1;
2283
2284       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_NOTATION, NULL);
2285       if (p)
2286         sig->flags.notation = 1;
2287
2288       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_REVOCABLE, NULL);
2289       if (p && *p == 0)
2290         sig->flags.revocable = 0;
2291
2292       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_TRUST, &len);
2293       if (p && len == 2)
2294         {
2295           sig->trust_depth = p[0];
2296           sig->trust_value = p[1];
2297
2298           /* Only look for a regexp if there is also a trust
2299              subpacket. */
2300           sig->trust_regexp =
2301             parse_sig_subpkt (sig, 1, SIGSUBPKT_REGEXP, &len);
2302
2303           /* If the regular expression is of 0 length, there is no
2304              regular expression. */
2305           if (len == 0)
2306             sig->trust_regexp = NULL;
2307         }
2308
2309       /* We accept the exportable subpacket from either the hashed or
2310          unhashed areas as older versions of gpg put it in the
2311          unhashed area.  In theory, anyway, we should never see this
2312          packet off of a local keyring. */
2313
2314       p = parse_sig_subpkt2 (sig, SIGSUBPKT_EXPORTABLE);
2315       if (p && *p == 0)
2316         sig->flags.exportable = 0;
2317
2318       /* Find all revocation keys.  */
2319       if (sig->sig_class == 0x1F)
2320         parse_revkeys (sig);
2321     }
2322
2323   if (list_mode)
2324     {
2325       es_fprintf (listfp, ":signature packet: algo %d, keyid %08lX%08lX\n"
2326                   "\tversion %d, created %lu, md5len %d, sigclass 0x%02x\n"
2327                   "\tdigest algo %d, begin of digest %02x %02x\n",
2328                   sig->pubkey_algo,
2329                   (ulong) sig->keyid[0], (ulong) sig->keyid[1],
2330                   sig->version, (ulong) sig->timestamp, md5_len, sig->sig_class,
2331                   sig->digest_algo, sig->digest_start[0], sig->digest_start[1]);
2332       if (is_v4or5)
2333         {
2334           parse_sig_subpkt (sig, 1, SIGSUBPKT_LIST_HASHED, NULL);
2335           parse_sig_subpkt (sig, 0, SIGSUBPKT_LIST_UNHASHED, NULL);
2336         }
2337     }
2338
2339   ndata = pubkey_get_nsig (sig->pubkey_algo);
2340   if (!ndata)
2341     {
2342       if (list_mode)
2343         es_fprintf (listfp, "\tunknown algorithm %d\n", sig->pubkey_algo);
2344       unknown_pubkey_warning (sig->pubkey_algo);
2345
2346       /* We store the plain material in data[0], so that we are able
2347        * to write it back with build_packet().  */
2348       if (pktlen > (5 * MAX_EXTERN_MPI_BITS / 8))
2349         {
2350           /* We include a limit to avoid too trivial DoS attacks by
2351              having gpg allocate too much memory.  */
2352           log_error ("signature packet: too much data\n");
2353           rc = GPG_ERR_INV_PACKET;
2354         }
2355       else
2356         {
2357           void *tmpp;
2358
2359           tmpp = read_rest (inp, pktlen);
2360           sig->data[0] = gcry_mpi_set_opaque (NULL, tmpp, tmpp? pktlen * 8 : 0);
2361           pktlen = 0;
2362         }
2363     }
2364   else
2365     {
2366       for (i = 0; i < ndata; i++)
2367         {
2368           n = pktlen;
2369           if (sig->pubkey_algo == PUBKEY_ALGO_ECDSA
2370               || sig->pubkey_algo == PUBKEY_ALGO_EDDSA)
2371             sig->data[i] = sos_read (inp, &n, 0);
2372           else
2373             sig->data[i] = mpi_read (inp, &n, 0);
2374           pktlen -= n;
2375           if (list_mode)
2376             {
2377               es_fprintf (listfp, "\tdata: ");
2378               mpi_print (listfp, sig->data[i], mpi_print_mode);
2379               es_putc ('\n', listfp);
2380             }
2381           if (!sig->data[i])
2382             rc = GPG_ERR_INV_PACKET;
2383         }
2384     }
2385
2386  leave:
2387   iobuf_skip_rest (inp, pktlen, 0);
2388   return rc;
2389
2390  underflow:
2391   log_error ("packet(%d) too short\n", pkttype);
2392   if (list_mode)
2393     es_fputs (":signature packet: [too short]\n", listfp);
2394
2395   iobuf_skip_rest (inp, pktlen, 0);
2396
2397   return GPG_ERR_INV_PACKET;
2398 }
2399
2400
2401 static int
2402 parse_onepass_sig (IOBUF inp, int pkttype, unsigned long pktlen,
2403                    PKT_onepass_sig * ops)
2404 {
2405   int version;
2406   int rc = 0;
2407
2408   if (pktlen < 13)
2409     {
2410       log_error ("packet(%d) too short\n", pkttype);
2411       if (list_mode)
2412         es_fputs (":onepass_sig packet: [too short]\n", listfp);
2413       rc = gpg_error (GPG_ERR_INV_PACKET);
2414       goto leave;
2415     }
2416   version = iobuf_get_noeof (inp);
2417   pktlen--;
2418   if (version != 3)
2419     {
2420       log_error ("onepass_sig with unknown version %d\n", version);
2421       if (list_mode)
2422         es_fputs (":onepass_sig packet: [unknown version]\n", listfp);
2423       rc = gpg_error (GPG_ERR_INV_PACKET);
2424       goto leave;
2425     }
2426   ops->sig_class = iobuf_get_noeof (inp);
2427   pktlen--;
2428   ops->digest_algo = iobuf_get_noeof (inp);
2429   pktlen--;
2430   ops->pubkey_algo = iobuf_get_noeof (inp);
2431   pktlen--;
2432   ops->keyid[0] = read_32 (inp);
2433   pktlen -= 4;
2434   ops->keyid[1] = read_32 (inp);
2435   pktlen -= 4;
2436   ops->last = iobuf_get_noeof (inp);
2437   pktlen--;
2438   if (list_mode)
2439     es_fprintf (listfp,
2440                 ":onepass_sig packet: keyid %08lX%08lX\n"
2441                 "\tversion %d, sigclass 0x%02x, digest %d, pubkey %d, "
2442                 "last=%d\n",
2443                 (ulong) ops->keyid[0], (ulong) ops->keyid[1],
2444                 version, ops->sig_class,
2445                 ops->digest_algo, ops->pubkey_algo, ops->last);
2446
2447
2448  leave:
2449   iobuf_skip_rest (inp, pktlen, 0);
2450   return rc;
2451 }
2452
2453
2454 static int
2455 parse_key (IOBUF inp, int pkttype, unsigned long pktlen,
2456            byte * hdr, int hdrlen, PACKET * pkt)
2457 {
2458   gpg_error_t err = 0;
2459   int i, version, algorithm;
2460   unsigned long timestamp, expiredate, max_expiredate;
2461   int npkey, nskey;
2462   u32 keyid[2];
2463   PKT_public_key *pk;
2464   int is_v5;
2465   unsigned int pkbytes; /* For v5 keys: Number of bytes in the public
2466                          * key material.  For v4 keys: 0.  */
2467
2468   (void) hdr;
2469
2470   pk = pkt->pkt.public_key; /* PK has been cleared. */
2471
2472   version = iobuf_get_noeof (inp);
2473   pktlen--;
2474   if (pkttype == PKT_PUBLIC_SUBKEY && version == '#')
2475     {
2476       /* Early versions of G10 used the old PGP comments packets;
2477        * luckily all those comments are started by a hash.  */
2478       if (list_mode)
2479         {
2480           es_fprintf (listfp, ":rfc1991 comment packet: \"");
2481           for (; pktlen; pktlen--)
2482             {
2483               int c;
2484               c = iobuf_get (inp);
2485               if (c == -1)
2486                 break; /* Ooops: shorter than indicated.  */
2487               if (c >= ' ' && c <= 'z')
2488                 es_putc (c, listfp);
2489               else
2490                 es_fprintf (listfp, "\\x%02x", c);
2491             }
2492           es_fprintf (listfp, "\"\n");
2493         }
2494       iobuf_skip_rest (inp, pktlen, 0);
2495       return 0;
2496     }
2497   else if (version == 4)
2498     is_v5 = 0;
2499   else if (version == 5)
2500     is_v5 = 1;
2501   else if (version == 2 || version == 3)
2502     {
2503       /* Not anymore supported since 2.1.  Use an older gpg version
2504        * (i.e. gpg 1.4) to parse v3 packets.  */
2505       if (opt.verbose > 1 && !glo_ctrl.silence_parse_warnings)
2506         log_info ("packet(%d) with obsolete version %d\n", pkttype, version);
2507       if (list_mode)
2508         es_fprintf (listfp, ":key packet: [obsolete version %d]\n", version);
2509       pk->version = version;
2510       err = gpg_error (GPG_ERR_LEGACY_KEY);
2511       goto leave;
2512     }
2513   else
2514     {
2515       log_error ("packet(%d) with unknown version %d\n", pkttype, version);
2516       if (list_mode)
2517         es_fputs (":key packet: [unknown version]\n", listfp);
2518       err = gpg_error (GPG_ERR_INV_PACKET);
2519       goto leave;
2520     }
2521
2522   if (pktlen < (is_v5? 15:11))
2523     {
2524       log_error ("packet(%d) too short\n", pkttype);
2525       if (list_mode)
2526         es_fputs (":key packet: [too short]\n", listfp);
2527       err = gpg_error (GPG_ERR_INV_PACKET);
2528       goto leave;
2529     }
2530   else if (pktlen > MAX_KEY_PACKET_LENGTH)
2531     {
2532       log_error ("packet(%d) too large\n", pkttype);
2533       if (list_mode)
2534         es_fputs (":key packet: [too large]\n", listfp);
2535       err = gpg_error (GPG_ERR_INV_PACKET);
2536       goto leave;
2537     }
2538
2539   timestamp = read_32 (inp);
2540   pktlen -= 4;
2541   expiredate = 0;               /* have to get it from the selfsignature */
2542   max_expiredate = 0;
2543   algorithm = iobuf_get_noeof (inp);
2544   pktlen--;
2545   if (is_v5)
2546     {
2547       pkbytes = read_32 (inp);
2548       pktlen -= 4;
2549     }
2550   else
2551     pkbytes = 0;
2552
2553   if (list_mode)
2554     {
2555       es_fprintf (listfp, ":%s key packet:\n"
2556                   "\tversion %d, algo %d, created %lu, expires %lu",
2557                   pkttype == PKT_PUBLIC_KEY ? "public" :
2558                   pkttype == PKT_SECRET_KEY ? "secret" :
2559                   pkttype == PKT_PUBLIC_SUBKEY ? "public sub" :
2560                   pkttype == PKT_SECRET_SUBKEY ? "secret sub" : "??",
2561                   version, algorithm, timestamp, expiredate);
2562       if (is_v5)
2563         es_fprintf (listfp, ", pkbytes %u\n", pkbytes);
2564       else
2565         es_fprintf (listfp, "\n");
2566     }
2567
2568   pk->timestamp = timestamp;
2569   pk->expiredate = expiredate;
2570   pk->max_expiredate = max_expiredate;
2571   pk->hdrbytes = hdrlen;
2572   pk->version = version;
2573   pk->flags.primary = (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY);
2574   pk->pubkey_algo = algorithm;
2575
2576   nskey = pubkey_get_nskey (algorithm);
2577   npkey = pubkey_get_npkey (algorithm);
2578   if (!npkey)
2579     {
2580       if (list_mode)
2581         es_fprintf (listfp, "\tunknown algorithm %d\n", algorithm);
2582       unknown_pubkey_warning (algorithm);
2583     }
2584
2585   if (!npkey)
2586     {
2587       /* Unknown algorithm - put data into an opaque MPI.  */
2588       void *tmpp = read_rest (inp, pktlen);
2589       /* Current gcry_mpi_cmp does not handle a (NULL,n>0) nicely and
2590        * thus we avoid to create such an MPI.  */
2591       pk->pkey[0] = gcry_mpi_set_opaque (NULL, tmpp, tmpp? pktlen * 8 : 0);
2592       pktlen = 0;
2593       goto leave;
2594     }
2595   else
2596     {
2597       for (i = 0; i < npkey; i++)
2598         {
2599           if (    (algorithm == PUBKEY_ALGO_ECDSA && (i == 0))
2600                || (algorithm == PUBKEY_ALGO_EDDSA && (i == 0))
2601                || (algorithm == PUBKEY_ALGO_ECDH  && (i == 0 || i == 2)))
2602             {
2603               /* Read the OID (i==0) or the KDF params (i==2).  */
2604               size_t n;
2605               err = read_size_body (inp, pktlen, &n, pk->pkey+i);
2606               pktlen -= n;
2607             }
2608           else
2609             {
2610               unsigned int n = pktlen;
2611               if (algorithm == PUBKEY_ALGO_ECDSA
2612                   || algorithm == PUBKEY_ALGO_EDDSA
2613                   || algorithm == PUBKEY_ALGO_ECDH)
2614                 pk->pkey[i] = sos_read (inp, &n, 0);
2615               else
2616                 pk->pkey[i] = mpi_read (inp, &n, 0);
2617               pktlen -= n;
2618               if (!pk->pkey[i])
2619                 err = gpg_error (GPG_ERR_INV_PACKET);
2620             }
2621           if (err)
2622             goto leave;
2623           if (list_mode)
2624             {
2625               es_fprintf (listfp, "\tpkey[%d]: ", i);
2626               mpi_print (listfp, pk->pkey[i], mpi_print_mode);
2627               if ((algorithm == PUBKEY_ALGO_ECDSA
2628                    || algorithm == PUBKEY_ALGO_EDDSA
2629                    || algorithm == PUBKEY_ALGO_ECDH) && i==0)
2630                 {
2631                   char *curve = openpgp_oid_to_str (pk->pkey[0]);
2632                   const char *name = openpgp_oid_to_curve (curve, 0);
2633                   es_fprintf (listfp, " %s (%s)", name?name:"", curve);
2634                   xfree (curve);
2635                 }
2636               es_putc ('\n', listfp);
2637             }
2638         }
2639     }
2640   if (list_mode)
2641     keyid_from_pk (pk, keyid);
2642
2643   if (pkttype == PKT_SECRET_KEY || pkttype == PKT_SECRET_SUBKEY)
2644     {
2645       struct seckey_info *ski;
2646       byte temp[16];
2647       size_t snlen = 0;
2648       unsigned int skbytes;
2649
2650       if (pktlen < 1)
2651         {
2652           err = gpg_error (GPG_ERR_INV_PACKET);
2653           goto leave;
2654         }
2655
2656       pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
2657       if (!pk->seckey_info)
2658         {
2659           err = gpg_error_from_syserror ();
2660           goto leave;
2661         }
2662
2663       ski->algo = iobuf_get_noeof (inp);
2664       pktlen--;
2665
2666       if (is_v5)
2667         {
2668           unsigned int protcount = 0;
2669
2670           /* Read the one octet count of the following key-protection
2671            * material.  Only required in case of unknown values. */
2672           if (!pktlen)
2673             {
2674               err = gpg_error (GPG_ERR_INV_PACKET);
2675               goto leave;
2676             }
2677           protcount = iobuf_get_noeof (inp);
2678           pktlen--;
2679           if (list_mode)
2680             es_fprintf (listfp, "\tprotbytes: %u\n", protcount);
2681         }
2682
2683       if (ski->algo)
2684         {
2685           ski->is_protected = 1;
2686           ski->s2k.count = 0;
2687           if (ski->algo == 254 || ski->algo == 255)
2688             {
2689               if (pktlen < 3)
2690                 {
2691                   err = gpg_error (GPG_ERR_INV_PACKET);
2692                   goto leave;
2693                 }
2694
2695               ski->sha1chk = (ski->algo == 254);
2696               ski->algo = iobuf_get_noeof (inp);
2697               pktlen--;
2698               /* Note that a ski->algo > 110 is illegal, but I'm not
2699                * erroring out here as otherwise there would be no way
2700                * to delete such a key.  */
2701               ski->s2k.mode = iobuf_get_noeof (inp);
2702               pktlen--;
2703               ski->s2k.hash_algo = iobuf_get_noeof (inp);
2704               pktlen--;
2705               /* Check for the special GNU extension.  */
2706               if (ski->s2k.mode == 101)
2707                 {
2708                   for (i = 0; i < 4 && pktlen; i++, pktlen--)
2709                     temp[i] = iobuf_get_noeof (inp);
2710                   if (i < 4 || memcmp (temp, "GNU", 3))
2711                     {
2712                       if (list_mode)
2713                         es_fprintf (listfp, "\tunknown S2K %d\n",
2714                                     ski->s2k.mode);
2715                       err = gpg_error (GPG_ERR_INV_PACKET);
2716                       goto leave;
2717                     }
2718                   /* Here we know that it is a GNU extension.  What
2719                    * follows is the GNU protection mode: All values
2720                    * have special meanings and they are mapped to MODE
2721                    * with a base of 1000.  */
2722                   ski->s2k.mode = 1000 + temp[3];
2723                 }
2724
2725               /* Read the salt.  */
2726               if (ski->s2k.mode == 3 || ski->s2k.mode == 1)
2727                 {
2728                   for (i = 0; i < 8 && pktlen; i++, pktlen--)
2729                     temp[i] = iobuf_get_noeof (inp);
2730                   if (i < 8)
2731                     {
2732                       err = gpg_error (GPG_ERR_INV_PACKET);
2733                       goto leave;
2734                     }
2735                   memcpy (ski->s2k.salt, temp, 8);
2736                 }
2737
2738               /* Check the mode.  */
2739               switch (ski->s2k.mode)
2740                 {
2741                 case 0:
2742                   if (list_mode)
2743                     es_fprintf (listfp, "\tsimple S2K");
2744                   break;
2745                 case 1:
2746                   if (list_mode)
2747                     es_fprintf (listfp, "\tsalted S2K");
2748                   break;
2749                 case 3:
2750                   if (list_mode)
2751                     es_fprintf (listfp, "\titer+salt S2K");
2752                   break;
2753                 case 1001:
2754                   if (list_mode)
2755                     es_fprintf (listfp, "\tgnu-dummy");
2756                   break;
2757                 case 1002:
2758                   if (list_mode)
2759                     es_fprintf (listfp, "\tgnu-divert-to-card");
2760                   break;
2761                 case 1003:
2762                   if (list_mode)
2763                     es_fprintf (listfp, "\tgnu-mode1003");
2764                   break;
2765                 default:
2766                   if (list_mode)
2767                     es_fprintf (listfp, "\tunknown %sS2K %d\n",
2768                                 ski->s2k.mode < 1000 ? "" : "GNU ",
2769                                 ski->s2k.mode);
2770                   err = gpg_error (GPG_ERR_INV_PACKET);
2771                   goto leave;
2772                 }
2773
2774               /* Print some info.  */
2775               if (list_mode && ski->s2k.mode != 1003)
2776                 {
2777                   es_fprintf (listfp, ", algo: %d,%s hash: %d",
2778                               ski->algo,
2779                               ski->sha1chk ? " SHA1 protection,"
2780                               : " simple checksum,", ski->s2k.hash_algo);
2781                   if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
2782                     {
2783                       es_fprintf (listfp, ", salt: ");
2784                       es_write_hexstring (listfp, ski->s2k.salt, 8, 0, NULL);
2785                     }
2786                 }
2787               if (list_mode)
2788                 es_putc ('\n', listfp);
2789
2790               /* Read remaining protection parameters.  */
2791               if (ski->s2k.mode == 3)
2792                 {
2793                   if (pktlen < 1)
2794                     {
2795                       err = gpg_error (GPG_ERR_INV_PACKET);
2796                       goto leave;
2797                     }
2798                   ski->s2k.count = iobuf_get_noeof (inp);
2799                   pktlen--;
2800                   if (list_mode)
2801                     es_fprintf (listfp, "\tprotect count: %lu (%lu)\n",
2802                                 (ulong)S2K_DECODE_COUNT ((ulong)ski->s2k.count),
2803                                 (ulong) ski->s2k.count);
2804                 }
2805               else if (ski->s2k.mode == 1002)
2806                 {
2807                   /* Read the serial number. */
2808                   if (pktlen < 1)
2809                     {
2810                       err = gpg_error (GPG_ERR_INV_PACKET);
2811                       goto leave;
2812                     }
2813                   snlen = iobuf_get (inp);
2814                   pktlen--;
2815                   if (pktlen < snlen || snlen == (size_t)(-1))
2816                     {
2817                       err = gpg_error (GPG_ERR_INV_PACKET);
2818                       goto leave;
2819                     }
2820                 }
2821             }
2822           else /* Old version; no S2K, so we set mode to 0, hash MD5.  */
2823             {
2824               /* Note that a ski->algo > 110 is illegal, but I'm not
2825                  erroring on it here as otherwise there would be no
2826                  way to delete such a key.  */
2827               ski->s2k.mode = 0;
2828               ski->s2k.hash_algo = DIGEST_ALGO_MD5;
2829               if (list_mode)
2830                 es_fprintf (listfp, "\tprotect algo: %d  (hash algo: %d)\n",
2831                             ski->algo, ski->s2k.hash_algo);
2832             }
2833
2834           /* It is really ugly that we don't know the size
2835            * of the IV here in cases we are not aware of the algorithm.
2836            * so a
2837            *   ski->ivlen = cipher_get_blocksize (ski->algo);
2838            * won't work.  The only solution I see is to hardwire it.
2839            * NOTE: if you change the ivlen above 16, don't forget to
2840            * enlarge temp.
2841            * FIXME: For v5 keys we can deduce this info!
2842            */
2843           ski->ivlen = openpgp_cipher_blocklen (ski->algo);
2844           log_assert (ski->ivlen <= sizeof (temp));
2845
2846           if (ski->s2k.mode == 1001 || ski->s2k.mode == 1003)
2847             ski->ivlen = 0;
2848           else if (ski->s2k.mode == 1002)
2849             ski->ivlen = snlen < 16 ? snlen : 16;
2850
2851           if (pktlen < ski->ivlen)
2852             {
2853               err = gpg_error (GPG_ERR_INV_PACKET);
2854               goto leave;
2855             }
2856           for (i = 0; i < ski->ivlen; i++, pktlen--)
2857             temp[i] = iobuf_get_noeof (inp);
2858           if (list_mode && ski->s2k.mode != 1003)
2859             {
2860               es_fprintf (listfp,
2861                           ski->s2k.mode == 1002 ? "\tserial-number: "
2862                           : "\tprotect IV: ");
2863               for (i = 0; i < ski->ivlen; i++)
2864                 es_fprintf (listfp, " %02x", temp[i]);
2865               es_putc ('\n', listfp);
2866             }
2867           memcpy (ski->iv, temp, ski->ivlen);
2868         }
2869
2870       /* Skip count of secret key material.  */
2871       if (is_v5)
2872         {
2873           if (pktlen < 4)
2874             {
2875               err = gpg_error (GPG_ERR_INV_PACKET);
2876               goto leave;
2877             }
2878           skbytes = read_32 (inp);
2879           pktlen -= 4;
2880           if (list_mode)
2881             es_fprintf (listfp, "\tskbytes: %u\n", skbytes);
2882         }
2883
2884       /* It does not make sense to read it into secure memory.
2885        * If the user is so careless, not to protect his secret key,
2886        * we can assume, that he operates an open system :=(.
2887        * So we put the key into secure memory when we unprotect it. */
2888       if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
2889         {
2890           /* Better set some dummy stuff here.  */
2891           pk->pkey[npkey] = gcry_mpi_set_opaque (NULL,
2892                                                  xstrdup ("dummydata"),
2893                                                  10 * 8);
2894           pktlen = 0;
2895         }
2896       else if (ski->s2k.mode == 1003)
2897         {
2898           void *tmpp;
2899
2900           if (pktlen < 2) /* At least two bytes for parenthesis.  */
2901             {
2902               err = gpg_error (GPG_ERR_INV_PACKET);
2903               goto leave;
2904             }
2905
2906           tmpp = read_rest (inp, pktlen);
2907           if (list_mode)
2908             {
2909               if (mpi_print_mode)
2910                 {
2911                   char *tmpsxp = canon_sexp_to_string (tmpp, pktlen);
2912                   es_fprintf (listfp, "\tskey[%d]: %s\n", npkey,
2913                               tmpsxp? trim_trailing_spaces (tmpsxp)
2914                               /*  */: "[invalid S-expression]");
2915                   xfree (tmpsxp);
2916                 }
2917               else
2918                 es_fprintf (listfp, "\tskey[%d]: [s-expression %lu octets]\n",
2919                             npkey, pktlen);
2920             }
2921           pk->pkey[npkey] = gcry_mpi_set_opaque (NULL,
2922                                                  tmpp, tmpp? pktlen * 8 : 0);
2923           pktlen = 0;
2924         }
2925       else if (ski->is_protected)
2926         {
2927           void *tmpp;
2928
2929           if (pktlen < 2) /* At least two bytes for the length.  */
2930             {
2931               err = gpg_error (GPG_ERR_INV_PACKET);
2932               goto leave;
2933             }
2934
2935           /* Ugly: The length is encrypted too, so we read all stuff
2936            * up to the end of the packet into the first SKEY
2937            * element.
2938            * FIXME: We can do better for v5 keys.  */
2939
2940           tmpp = read_rest (inp, pktlen);
2941           pk->pkey[npkey] = gcry_mpi_set_opaque (NULL,
2942                                                  tmpp, tmpp? pktlen * 8 : 0);
2943           /* Mark that MPI as protected - we need this information for
2944            * importing a key.  The OPAQUE flag can't be used because
2945            * we also store public EdDSA values in opaque MPIs.  */
2946           if (pk->pkey[npkey])
2947             gcry_mpi_set_flag (pk->pkey[npkey], GCRYMPI_FLAG_USER1);
2948           pktlen = 0;
2949           if (list_mode)
2950             es_fprintf (listfp, "\tskey[%d]: [v4 protected]\n", npkey);
2951         }
2952       else
2953         {
2954           /* Not encrypted.  */
2955           for (i = npkey; i < nskey; i++)
2956             {
2957               unsigned int n;
2958
2959               if (pktlen < 2) /* At least two bytes for the length.  */
2960                 {
2961                   err = gpg_error (GPG_ERR_INV_PACKET);
2962                   goto leave;
2963                 }
2964               n = pktlen;
2965               if (algorithm == PUBKEY_ALGO_ECDSA
2966                   || algorithm == PUBKEY_ALGO_EDDSA
2967                   || algorithm == PUBKEY_ALGO_ECDH)
2968                 pk->pkey[i] = sos_read (inp, &n, 0);
2969               else
2970                 pk->pkey[i] = mpi_read (inp, &n, 0);
2971               pktlen -= n;
2972               if (list_mode)
2973                 {
2974                   es_fprintf (listfp, "\tskey[%d]: ", i);
2975                   mpi_print (listfp, pk->pkey[i], mpi_print_mode);
2976                   es_putc ('\n', listfp);
2977                 }
2978
2979               if (!pk->pkey[i])
2980                 err = gpg_error (GPG_ERR_INV_PACKET);
2981             }
2982           if (err)
2983             goto leave;
2984
2985           if (pktlen < 2)
2986             {
2987               err = gpg_error (GPG_ERR_INV_PACKET);
2988               goto leave;
2989             }
2990           ski->csum = read_16 (inp);
2991           pktlen -= 2;
2992           if (list_mode)
2993             es_fprintf (listfp, "\tchecksum: %04hx\n", ski->csum);
2994         }
2995     }
2996
2997   /* Note that KEYID below has been initialized above in list_mode.  */
2998   if (list_mode)
2999     es_fprintf (listfp, "\tkeyid: %08lX%08lX\n",
3000                 (ulong) keyid[0], (ulong) keyid[1]);
3001
3002  leave:
3003   iobuf_skip_rest (inp, pktlen, 0);
3004   return err;
3005 }
3006
3007
3008 /* Attribute subpackets have the same format as v4 signature
3009    subpackets.  This is not part of OpenPGP, but is done in several
3010    versions of PGP nevertheless.  */
3011 int
3012 parse_attribute_subpkts (PKT_user_id * uid)
3013 {
3014   size_t n;
3015   int count = 0;
3016   struct user_attribute *attribs = NULL;
3017   const byte *buffer = uid->attrib_data;
3018   int buflen = uid->attrib_len;
3019   byte type;
3020
3021   xfree (uid->attribs);
3022
3023   while (buflen)
3024     {
3025       n = *buffer++;
3026       buflen--;
3027       if (n == 255)  /* 4 byte length header.  */
3028         {
3029           if (buflen < 4)
3030             goto too_short;
3031           n = buf32_to_size_t (buffer);
3032           buffer += 4;
3033           buflen -= 4;
3034         }
3035       else if (n >= 192)  /* 2 byte special encoded length header.  */
3036         {
3037           if (buflen < 2)
3038             goto too_short;
3039           n = ((n - 192) << 8) + *buffer + 192;
3040           buffer++;
3041           buflen--;
3042         }
3043       if (buflen < n)
3044         goto too_short;
3045
3046       if (!n)
3047         {
3048           /* Too short to encode the subpacket type.  */
3049           if (opt.verbose)
3050             log_info ("attribute subpacket too short\n");
3051           break;
3052         }
3053
3054       attribs = xrealloc (attribs,
3055                           (count + 1) * sizeof (struct user_attribute));
3056       memset (&attribs[count], 0, sizeof (struct user_attribute));
3057
3058       type = *buffer;
3059       buffer++;
3060       buflen--;
3061       n--;
3062
3063       attribs[count].type = type;
3064       attribs[count].data = buffer;
3065       attribs[count].len = n;
3066       buffer += n;
3067       buflen -= n;
3068       count++;
3069     }
3070
3071   uid->attribs = attribs;
3072   uid->numattribs = count;
3073   return count;
3074
3075  too_short:
3076   if (opt.verbose && !glo_ctrl.silence_parse_warnings)
3077     log_info ("buffer shorter than attribute subpacket\n");
3078   uid->attribs = attribs;
3079   uid->numattribs = count;
3080   return count;
3081 }
3082
3083
3084 static int
3085 parse_user_id (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet)
3086 {
3087   byte *p;
3088
3089   /* Cap the size of a user ID at 2k: a value absurdly large enough
3090      that there is no sane user ID string (which is printable text
3091      as of RFC2440bis) that won't fit in it, but yet small enough to
3092      avoid allocation problems.  A large pktlen may not be
3093      allocatable, and a very large pktlen could actually cause our
3094      allocation to wrap around in xmalloc to a small number. */
3095
3096   if (pktlen > MAX_UID_PACKET_LENGTH)
3097     {
3098       log_error ("packet(%d) too large\n", pkttype);
3099       if (list_mode)
3100         es_fprintf (listfp, ":user ID packet: [too large]\n");
3101       iobuf_skip_rest (inp, pktlen, 0);
3102       return GPG_ERR_INV_PACKET;
3103     }
3104
3105   packet->pkt.user_id = xmalloc_clear (sizeof *packet->pkt.user_id + pktlen);
3106   packet->pkt.user_id->len = pktlen;
3107   packet->pkt.user_id->ref = 1;
3108
3109   p = packet->pkt.user_id->name;
3110   for (; pktlen; pktlen--, p++)
3111     *p = iobuf_get_noeof (inp);
3112   *p = 0;
3113
3114   if (list_mode)
3115     {
3116       int n = packet->pkt.user_id->len;
3117       es_fprintf (listfp, ":user ID packet: \"");
3118       /* fixme: Hey why don't we replace this with es_write_sanitized?? */
3119       for (p = packet->pkt.user_id->name; n; p++, n--)
3120         {
3121           if (*p >= ' ' && *p <= 'z')
3122             es_putc (*p, listfp);
3123           else
3124             es_fprintf (listfp, "\\x%02x", *p);
3125         }
3126       es_fprintf (listfp, "\"\n");
3127     }
3128   return 0;
3129 }
3130
3131
3132 void
3133 make_attribute_uidname (PKT_user_id * uid, size_t max_namelen)
3134 {
3135   log_assert (max_namelen > 70);
3136   if (uid->numattribs <= 0)
3137     sprintf (uid->name, "[bad attribute packet of size %lu]",
3138              uid->attrib_len);
3139   else if (uid->numattribs > 1)
3140     sprintf (uid->name, "[%d attributes of size %lu]",
3141              uid->numattribs, uid->attrib_len);
3142   else
3143     {
3144       /* Only one attribute, so list it as the "user id" */
3145
3146       if (uid->attribs->type == ATTRIB_IMAGE)
3147         {
3148           u32 len;
3149           byte type;
3150
3151           if (parse_image_header (uid->attribs, &type, &len))
3152             sprintf (uid->name, "[%.20s image of size %lu]",
3153                      image_type_to_string (type, 1), (ulong) len);
3154           else
3155             sprintf (uid->name, "[invalid image]");
3156         }
3157       else
3158         sprintf (uid->name, "[unknown attribute of size %lu]",
3159                  (ulong) uid->attribs->len);
3160     }
3161
3162   uid->len = strlen (uid->name);
3163 }
3164
3165
3166 static int
3167 parse_attribute (IOBUF inp, int pkttype, unsigned long pktlen,
3168                  PACKET * packet)
3169 {
3170   byte *p;
3171
3172   (void) pkttype;
3173
3174   /* We better cap the size of an attribute packet to make DoS not too
3175      easy.  16MB should be more then enough for one attribute packet
3176      (ie. a photo).  */
3177   if (pktlen > MAX_ATTR_PACKET_LENGTH)
3178     {
3179       log_error ("packet(%d) too large\n", pkttype);
3180       if (list_mode)
3181         es_fprintf (listfp, ":attribute packet: [too large]\n");
3182       iobuf_skip_rest (inp, pktlen, 0);
3183       return GPG_ERR_INV_PACKET;
3184     }
3185
3186 #define EXTRA_UID_NAME_SPACE 71
3187   packet->pkt.user_id = xmalloc_clear (sizeof *packet->pkt.user_id
3188                                        + EXTRA_UID_NAME_SPACE);
3189   packet->pkt.user_id->ref = 1;
3190   packet->pkt.user_id->attrib_data = xmalloc (pktlen? pktlen:1);
3191   packet->pkt.user_id->attrib_len = pktlen;
3192
3193   p = packet->pkt.user_id->attrib_data;
3194   for (; pktlen; pktlen--, p++)
3195     *p = iobuf_get_noeof (inp);
3196
3197   /* Now parse out the individual attribute subpackets.  This is
3198      somewhat pointless since there is only one currently defined
3199      attribute type (jpeg), but it is correct by the spec. */
3200   parse_attribute_subpkts (packet->pkt.user_id);
3201
3202   make_attribute_uidname (packet->pkt.user_id, EXTRA_UID_NAME_SPACE);
3203
3204   if (list_mode)
3205     {
3206       es_fprintf (listfp, ":attribute packet: %s\n", packet->pkt.user_id->name);
3207     }
3208   return 0;
3209 }
3210
3211
3212 static int
3213 parse_comment (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet)
3214 {
3215   byte *p;
3216
3217   /* Cap comment packet at a reasonable value to avoid an integer
3218      overflow in the malloc below.  Comment packets are actually not
3219      anymore define my OpenPGP and we even stopped to use our
3220      private comment packet.  */
3221   if (pktlen > MAX_COMMENT_PACKET_LENGTH)
3222     {
3223       log_error ("packet(%d) too large\n", pkttype);
3224       if (list_mode)
3225         es_fprintf (listfp, ":%scomment packet: [too large]\n",
3226                     pkttype == PKT_OLD_COMMENT ? "OpenPGP draft " : "");
3227       iobuf_skip_rest (inp, pktlen, 0);
3228       return GPG_ERR_INV_PACKET;
3229     }
3230   packet->pkt.comment = xmalloc (sizeof *packet->pkt.comment + pktlen - 1);
3231   packet->pkt.comment->len = pktlen;
3232   p = packet->pkt.comment->data;
3233   for (; pktlen; pktlen--, p++)
3234     *p = iobuf_get_noeof (inp);
3235
3236   if (list_mode)
3237     {
3238       int n = packet->pkt.comment->len;
3239       es_fprintf (listfp, ":%scomment packet: \"", pkttype == PKT_OLD_COMMENT ?
3240                   "OpenPGP draft " : "");
3241       for (p = packet->pkt.comment->data; n; p++, n--)
3242         {
3243           if (*p >= ' ' && *p <= 'z')
3244             es_putc (*p, listfp);
3245           else
3246             es_fprintf (listfp, "\\x%02x", *p);
3247         }
3248       es_fprintf (listfp, "\"\n");
3249     }
3250   return 0;
3251 }
3252
3253
3254 /* Parse a ring trust packet RFC4880 (5.10).
3255  *
3256  * This parser is special in that the packet is not stored as a packet
3257  * but its content is merged into the previous packet.  */
3258 static gpg_error_t
3259 parse_ring_trust (parse_packet_ctx_t ctx, unsigned long pktlen)
3260 {
3261   gpg_error_t err;
3262   iobuf_t inp = ctx->inp;
3263   PKT_ring_trust rt = {0};
3264   int c;
3265   int not_gpg = 0;
3266
3267   if (!pktlen)
3268     {
3269       if (list_mode)
3270         es_fprintf (listfp, ":trust packet: empty\n");
3271       err = 0;
3272       goto leave;
3273     }
3274
3275   c = iobuf_get_noeof (inp);
3276   pktlen--;
3277   rt.trustval = c;
3278   if (pktlen)
3279     {
3280       if (!c)
3281         {
3282           c = iobuf_get_noeof (inp);
3283           /* We require that bit 7 of the sigcache is 0 (easier
3284            * eof handling).  */
3285           if (!(c & 0x80))
3286             rt.sigcache = c;
3287         }
3288       else
3289         iobuf_get_noeof (inp);  /* Dummy read.  */
3290       pktlen--;
3291     }
3292
3293   /* Next is the optional subtype.  */
3294   if (pktlen > 3)
3295     {
3296       char tmp[4];
3297       tmp[0] = iobuf_get_noeof (inp);
3298       tmp[1] = iobuf_get_noeof (inp);
3299       tmp[2] = iobuf_get_noeof (inp);
3300       tmp[3] = iobuf_get_noeof (inp);
3301       pktlen -= 4;
3302       if (!memcmp (tmp, "gpg", 3))
3303         rt.subtype = tmp[3];
3304       else
3305         not_gpg = 1;
3306     }
3307   /* If it is a key or uid subtype read the remaining data.  */
3308   if ((rt.subtype == RING_TRUST_KEY || rt.subtype == RING_TRUST_UID)
3309       && pktlen >= 6 )
3310     {
3311       int i;
3312       unsigned int namelen;
3313
3314       rt.keyorg = iobuf_get_noeof (inp);
3315       pktlen--;
3316       rt.keyupdate = read_32 (inp);
3317       pktlen -= 4;
3318       namelen = iobuf_get_noeof (inp);
3319       pktlen--;
3320       if (namelen && pktlen)
3321         {
3322           rt.url = xtrymalloc (namelen + 1);
3323           if (!rt.url)
3324             {
3325               err = gpg_error_from_syserror ();
3326               goto leave;
3327             }
3328           for (i = 0; pktlen && i < namelen; pktlen--, i++)
3329             rt.url[i] = iobuf_get_noeof (inp);
3330           rt.url[i] = 0;
3331         }
3332     }
3333
3334   if (list_mode)
3335     {
3336       if (rt.subtype == RING_TRUST_SIG)
3337         es_fprintf (listfp, ":trust packet: sig flag=%02x sigcache=%02x\n",
3338                     rt.trustval, rt.sigcache);
3339       else if (rt.subtype == RING_TRUST_UID || rt.subtype == RING_TRUST_KEY)
3340         {
3341           unsigned char *p;
3342
3343           es_fprintf (listfp, ":trust packet: %s upd=%lu src=%d%s",
3344                       (rt.subtype == RING_TRUST_UID? "uid" : "key"),
3345                       (unsigned long)rt.keyupdate,
3346                       rt.keyorg,
3347                       (rt.url? " url=":""));
3348           if (rt.url)
3349             {
3350               for (p = rt.url; *p; p++)
3351                 {
3352                   if (*p >= ' ' && *p <= 'z')
3353                     es_putc (*p, listfp);
3354                   else
3355                     es_fprintf (listfp, "\\x%02x", *p);
3356                 }
3357             }
3358           es_putc ('\n', listfp);
3359         }
3360       else if (not_gpg)
3361         es_fprintf (listfp, ":trust packet: not created by gpg\n");
3362       else
3363         es_fprintf (listfp, ":trust packet: subtype=%02x\n",
3364                     rt.subtype);
3365     }
3366
3367   /* Now transfer the data to the respective packet.  Do not do this
3368    * if SKIP_META is set.  */
3369   if (!ctx->last_pkt.pkt.generic || ctx->skip_meta)
3370     ;
3371   else if (rt.subtype == RING_TRUST_SIG
3372            && ctx->last_pkt.pkttype == PKT_SIGNATURE)
3373     {
3374       PKT_signature *sig = ctx->last_pkt.pkt.signature;
3375
3376       if ((rt.sigcache & 1))
3377         {
3378           sig->flags.checked = 1;
3379           sig->flags.valid = !!(rt.sigcache & 2);
3380         }
3381     }
3382   else if (rt.subtype == RING_TRUST_UID
3383            && (ctx->last_pkt.pkttype == PKT_USER_ID
3384                || ctx->last_pkt.pkttype == PKT_ATTRIBUTE))
3385     {
3386       PKT_user_id *uid = ctx->last_pkt.pkt.user_id;
3387
3388       uid->keyorg = rt.keyorg;
3389       uid->keyupdate = rt.keyupdate;
3390       uid->updateurl = rt.url;
3391       rt.url = NULL;
3392     }
3393   else if (rt.subtype == RING_TRUST_KEY
3394            && (ctx->last_pkt.pkttype == PKT_PUBLIC_KEY
3395                || ctx->last_pkt.pkttype == PKT_SECRET_KEY))
3396     {
3397       PKT_public_key *pk = ctx->last_pkt.pkt.public_key;
3398
3399       pk->keyorg = rt.keyorg;
3400       pk->keyupdate = rt.keyupdate;
3401       pk->updateurl = rt.url;
3402       rt.url = NULL;
3403     }
3404
3405   err = 0;
3406
3407  leave:
3408   xfree (rt.url);
3409   free_packet (NULL, ctx); /* This sets ctx->last_pkt to NULL.  */
3410   iobuf_skip_rest (inp, pktlen, 0);
3411   return err;
3412 }
3413
3414
3415 static int
3416 parse_plaintext (IOBUF inp, int pkttype, unsigned long pktlen,
3417                  PACKET * pkt, int new_ctb, int partial)
3418 {
3419   int rc = 0;
3420   int mode, namelen;
3421   PKT_plaintext *pt;
3422   byte *p;
3423   int c, i;
3424
3425   if (!partial && pktlen < 6)
3426     {
3427       log_error ("packet(%d) too short (%lu)\n", pkttype, (ulong) pktlen);
3428       if (list_mode)
3429         es_fputs (":literal data packet: [too short]\n", listfp);
3430       rc = gpg_error (GPG_ERR_INV_PACKET);
3431       goto leave;
3432     }
3433   mode = iobuf_get_noeof (inp);
3434   if (pktlen)
3435     pktlen--;
3436   namelen = iobuf_get_noeof (inp);
3437   if (pktlen)
3438     pktlen--;
3439   /* Note that namelen will never exceed 255 bytes. */
3440   pt = pkt->pkt.plaintext =
3441     xmalloc (sizeof *pkt->pkt.plaintext + namelen - 1);
3442   pt->new_ctb = new_ctb;
3443   pt->mode = mode;
3444   pt->namelen = namelen;
3445   pt->is_partial = partial;
3446   if (pktlen)
3447     {
3448       for (i = 0; pktlen > 4 && i < namelen; pktlen--, i++)
3449         pt->name[i] = iobuf_get_noeof (inp);
3450     }
3451   else
3452     {
3453       for (i = 0; i < namelen; i++)
3454         if ((c = iobuf_get (inp)) == -1)
3455           break;
3456         else
3457           pt->name[i] = c;
3458     }
3459   /* Fill up NAME so that a check with valgrind won't complain about
3460    * reading from uninitialized memory.  This case may be triggred by
3461    * corrupted packets.  */
3462   for (; i < namelen; i++)
3463     pt->name[i] = 0;
3464
3465   pt->timestamp = read_32 (inp);
3466   if (pktlen)
3467     pktlen -= 4;
3468   pt->len = pktlen;
3469   pt->buf = inp;
3470
3471   if (list_mode)
3472     {
3473       es_fprintf (listfp, ":literal data packet:\n"
3474                   "\tmode %c (%X), created %lu, name=\"",
3475                   mode >= ' ' && mode < 'z' ? mode : '?', mode,
3476                   (ulong) pt->timestamp);
3477       for (p = pt->name, i = 0; i < namelen; p++, i++)
3478         {
3479           if (*p >= ' ' && *p <= 'z')
3480             es_putc (*p, listfp);
3481           else
3482             es_fprintf (listfp, "\\x%02x", *p);
3483         }
3484       es_fprintf (listfp, "\",\n\traw data: ");
3485       if (partial)
3486         es_fprintf (listfp, "unknown length\n");
3487       else
3488         es_fprintf (listfp, "%lu bytes\n", (ulong) pt->len);
3489     }
3490
3491  leave:
3492   return rc;
3493 }
3494
3495
3496 static int
3497 parse_compressed (IOBUF inp, int pkttype, unsigned long pktlen,
3498                   PACKET * pkt, int new_ctb)
3499 {
3500   PKT_compressed *zd;
3501
3502   /* PKTLEN is here 0, but data follows (this should be the last
3503      object in a file or the compress algorithm should know the
3504      length).  */
3505   (void) pkttype;
3506   (void) pktlen;
3507
3508   zd = pkt->pkt.compressed = xmalloc (sizeof *pkt->pkt.compressed);
3509   zd->algorithm = iobuf_get_noeof (inp);
3510   zd->len = 0;                  /* not used */
3511   zd->new_ctb = new_ctb;
3512   zd->buf = inp;
3513   if (list_mode)
3514     es_fprintf (listfp, ":compressed packet: algo=%d\n", zd->algorithm);
3515   return 0;
3516 }
3517
3518
3519 static int
3520 parse_encrypted (IOBUF inp, int pkttype, unsigned long pktlen,
3521                  PACKET * pkt, int new_ctb, int partial)
3522 {
3523   int rc = 0;
3524   PKT_encrypted *ed;
3525   unsigned long orig_pktlen = pktlen;
3526
3527   ed = pkt->pkt.encrypted = xmalloc (sizeof *pkt->pkt.encrypted);
3528   /* ed->len is set below.  */
3529   ed->extralen = 0;  /* Unknown here; only used in build_packet.  */
3530   ed->buf = NULL;
3531   ed->new_ctb = new_ctb;
3532   ed->is_partial = partial;
3533   ed->aead_algo = 0;
3534   ed->cipher_algo = 0; /* Only used with AEAD.  */
3535   ed->chunkbyte = 0;   /* Only used with AEAD.  */
3536   if (pkttype == PKT_ENCRYPTED_MDC)
3537     {
3538       /* Fixme: add some pktlen sanity checks.  */
3539       int version;
3540
3541       version = iobuf_get_noeof (inp);
3542       if (orig_pktlen)
3543         pktlen--;
3544       if (version != 1)
3545         {
3546           log_error ("encrypted_mdc packet with unknown version %d\n",
3547                      version);
3548           if (list_mode)
3549             es_fputs (":encrypted data packet: [unknown version]\n", listfp);
3550           /*skip_rest(inp, pktlen); should we really do this? */
3551           rc = gpg_error (GPG_ERR_INV_PACKET);
3552           goto leave;
3553         }
3554       ed->mdc_method = DIGEST_ALGO_SHA1;
3555     }
3556   else
3557     ed->mdc_method = 0;
3558
3559   /* A basic sanity check.  We need at least an 8 byte IV plus the 2
3560      detection bytes.  Note that we don't known the algorithm and thus
3561      we may only check against the minimum blocksize.  */
3562   if (orig_pktlen && pktlen < 10)
3563     {
3564       /* Actually this is blocksize+2.  */
3565       log_error ("packet(%d) too short\n", pkttype);
3566       if (list_mode)
3567         es_fputs (":encrypted data packet: [too short]\n", listfp);
3568       rc = GPG_ERR_INV_PACKET;
3569       iobuf_skip_rest (inp, pktlen, partial);
3570       goto leave;
3571     }
3572
3573   /* Store the remaining length of the encrypted data (i.e. without
3574      the MDC version number but with the IV etc.).  This value is
3575      required during decryption.  */
3576   ed->len = pktlen;
3577
3578   if (list_mode)
3579     {
3580       if (orig_pktlen)
3581         es_fprintf (listfp, ":encrypted data packet:\n\tlength: %lu\n",
3582                     orig_pktlen);
3583       else
3584         es_fprintf (listfp, ":encrypted data packet:\n\tlength: unknown\n");
3585       if (ed->mdc_method)
3586         es_fprintf (listfp, "\tmdc_method: %d\n", ed->mdc_method);
3587     }
3588
3589   ed->buf = inp;
3590
3591  leave:
3592   return rc;
3593 }
3594
3595
3596 /* Note, that this code is not anymore used in real life because the
3597    MDC checking is now done right after the decryption in
3598    decrypt_data.  */
3599 static int
3600 parse_mdc (IOBUF inp, int pkttype, unsigned long pktlen,
3601            PACKET * pkt, int new_ctb)
3602 {
3603   int rc = 0;
3604   PKT_mdc *mdc;
3605   byte *p;
3606
3607   (void) pkttype;
3608
3609   mdc = pkt->pkt.mdc = xmalloc (sizeof *pkt->pkt.mdc);
3610   if (list_mode)
3611     es_fprintf (listfp, ":mdc packet: length=%lu\n", pktlen);
3612   if (!new_ctb || pktlen != 20)
3613     {
3614       log_error ("mdc_packet with invalid encoding\n");
3615       rc = gpg_error (GPG_ERR_INV_PACKET);
3616       goto leave;
3617     }
3618   p = mdc->hash;
3619   for (; pktlen; pktlen--, p++)
3620     *p = iobuf_get_noeof (inp);
3621
3622  leave:
3623   return rc;
3624 }
3625
3626
3627 static gpg_error_t
3628 parse_encrypted_aead (iobuf_t inp, int pkttype, unsigned long pktlen,
3629                       PACKET *pkt, int partial)
3630 {
3631   int rc = 0;
3632   PKT_encrypted *ed;
3633   unsigned long orig_pktlen = pktlen;
3634   int version;
3635
3636   ed = pkt->pkt.encrypted = xtrymalloc (sizeof *pkt->pkt.encrypted);
3637   if (!ed)
3638     return gpg_error_from_syserror ();
3639   ed->len = 0;
3640   ed->extralen = 0;  /* (only used in build_packet.)  */
3641   ed->buf = NULL;
3642   ed->new_ctb = 1;   /* (packet number requires a new CTB anyway.)  */
3643   ed->is_partial = partial;
3644   ed->mdc_method = 0;
3645   /* A basic sanity check.  We need one version byte, one algo byte,
3646    * one aead algo byte, one chunkbyte, at least 15 byte IV.  */
3647   if (orig_pktlen && pktlen < 19)
3648     {
3649       log_error ("packet(%d) too short\n", pkttype);
3650       if (list_mode)
3651         es_fputs (":aead encrypted packet: [too short]\n", listfp);
3652       rc = gpg_error (GPG_ERR_INV_PACKET);
3653       iobuf_skip_rest (inp, pktlen, partial);
3654       goto leave;
3655     }
3656
3657   version = iobuf_get_noeof (inp);
3658   if (orig_pktlen)
3659     pktlen--;
3660   if (version != 1)
3661     {
3662       log_error ("aead encrypted packet with unknown version %d\n",
3663                  version);
3664       if (list_mode)
3665         es_fputs (":aead encrypted packet: [unknown version]\n", listfp);
3666       /*skip_rest(inp, pktlen); should we really do this? */
3667       rc = gpg_error (GPG_ERR_INV_PACKET);
3668       goto leave;
3669     }
3670
3671   ed->cipher_algo = iobuf_get_noeof (inp);
3672   if (orig_pktlen)
3673     pktlen--;
3674   ed->aead_algo = iobuf_get_noeof (inp);
3675   if (orig_pktlen)
3676     pktlen--;
3677   ed->chunkbyte = iobuf_get_noeof (inp);
3678   if (orig_pktlen)
3679     pktlen--;
3680
3681   /* Store the remaining length of the encrypted data.  We read the
3682    * rest during decryption.  */
3683   ed->len = pktlen;
3684
3685   if (list_mode)
3686     {
3687       es_fprintf (listfp, ":aead encrypted packet: cipher=%u aead=%u cb=%u\n",
3688                   ed->cipher_algo, ed->aead_algo, ed->chunkbyte);
3689       if (orig_pktlen)
3690         es_fprintf (listfp, "\tlength: %lu\n", orig_pktlen);
3691       else
3692         es_fprintf (listfp, "\tlength: unknown\n");
3693     }
3694
3695   ed->buf = inp;
3696
3697  leave:
3698   return rc;
3699 }
3700
3701
3702 /*
3703  * This packet is internally generated by us (in armor.c) to transfer
3704  * some information to the lower layer.  To make sure that this packet
3705  * is really a GPG faked one and not one coming from outside, we
3706  * first check that there is a unique tag in it.
3707  *
3708  * The format of such a control packet is:
3709  *   n byte  session marker
3710  *   1 byte  control type CTRLPKT_xxxxx
3711  *   m byte  control data
3712  */
3713 static int
3714 parse_gpg_control (IOBUF inp, int pkttype, unsigned long pktlen,
3715                    PACKET * packet, int partial)
3716 {
3717   byte *p;
3718   const byte *sesmark;
3719   size_t sesmarklen;
3720   int i;
3721
3722   (void) pkttype;
3723
3724   if (list_mode)
3725     es_fprintf (listfp, ":packet 63: length %lu ", pktlen);
3726
3727   sesmark = get_session_marker (&sesmarklen);
3728   if (pktlen < sesmarklen + 1)  /* 1 is for the control bytes */
3729     goto skipit;
3730   for (i = 0; i < sesmarklen; i++, pktlen--)
3731     {
3732       if (sesmark[i] != iobuf_get_noeof (inp))
3733         goto skipit;
3734     }
3735   if (pktlen > 4096)
3736     goto skipit;  /* Definitely too large.  We skip it to avoid an
3737                      overflow in the malloc.  */
3738   if (list_mode)
3739     es_fputs ("- gpg control packet", listfp);
3740
3741   packet->pkt.gpg_control = xmalloc (sizeof *packet->pkt.gpg_control
3742                                      + pktlen - 1);
3743   packet->pkt.gpg_control->control = iobuf_get_noeof (inp);
3744   pktlen--;
3745   packet->pkt.gpg_control->datalen = pktlen;
3746   p = packet->pkt.gpg_control->data;
3747   for (; pktlen; pktlen--, p++)
3748     *p = iobuf_get_noeof (inp);
3749
3750   return 0;
3751
3752  skipit:
3753   if (list_mode)
3754     {
3755       int c;
3756
3757       i = 0;
3758       es_fprintf (listfp, "- private (rest length %lu)\n", pktlen);
3759       if (partial)
3760         {
3761           while ((c = iobuf_get (inp)) != -1)
3762             dump_hex_line (c, &i);
3763         }
3764       else
3765         {
3766           for (; pktlen; pktlen--)
3767             {
3768               dump_hex_line ((c = iobuf_get (inp)), &i);
3769               if (c == -1)
3770                 break;
3771             }
3772         }
3773       es_putc ('\n', listfp);
3774     }
3775   iobuf_skip_rest (inp, pktlen, 0);
3776   return gpg_error (GPG_ERR_INV_PACKET);
3777 }
3778
3779
3780 /* Create a GPG control packet to be used internally as a placeholder.  */
3781 PACKET *
3782 create_gpg_control (ctrlpkttype_t type, const byte * data, size_t datalen)
3783 {
3784   PACKET *packet;
3785   byte *p;
3786
3787   if (!data)
3788     datalen = 0;
3789
3790   packet = xmalloc (sizeof *packet);
3791   init_packet (packet);
3792   packet->pkttype = PKT_GPG_CONTROL;
3793   packet->pkt.gpg_control = xmalloc (sizeof *packet->pkt.gpg_control + datalen);
3794   packet->pkt.gpg_control->control = type;
3795   packet->pkt.gpg_control->datalen = datalen;
3796   p = packet->pkt.gpg_control->data;
3797   for (; datalen; datalen--, p++)
3798     *p = *data++;
3799
3800   return packet;
3801 }