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