root/openpgpsdk/trunk/src/packet-parse.c

Revision 282 (checked in by rachel, 8 years ago)

initial stab at stacked error handling

  • Property svn:keywords set to Id
Line 
1 /** \file
2  * \brief Parser for OpenPGP packets
3  */
4
5
6 #include <openpgpsdk/packet.h>
7 #include <openpgpsdk/packet-parse.h>
8 #include <openpgpsdk/util.h>
9 #include <openpgpsdk/compress.h>
10 #include <openpgpsdk/errors.h>
11
12 #include <assert.h>
13 #include <stdarg.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <errno.h>
18
19 /**
20  * limited_read_data reads the specified amount of the subregion's data
21  * into a data_t structure
22  *
23  * \param data  Empty structure which will be filled with data
24  * \param len   Number of octets to read
25  * \param subregion
26  * \param parse_info    How to parse
27  *
28  * \return 1 on success, 0 on failure
29  */
30 static int limited_read_data(ops_data_t *data,unsigned int len,
31                              ops_region_t *subregion,ops_parse_info_t *parse_info)
32     {
33     data->len = len;
34
35     assert(subregion->length-subregion->length_read >= len);
36
37     data->contents=malloc(data->len);
38     if (!data->contents)
39         return 0;
40
41     if (!ops_limited_read(data->contents, data->len,subregion,parse_info))
42         return 0;
43    
44     return 1;
45     }
46
47 /**
48  * read_data reads the remainder of the subregion's data
49  * into a data_t structure
50  *
51  * \param data
52  * \param subregion
53  * \param parse_info
54  *
55  * \return 1 on success, 0 on failure
56  */
57 static int read_data(ops_data_t *data,ops_region_t *subregion,
58                      ops_parse_info_t *parse_info)
59     {
60     int len;
61
62     len=subregion->length-subregion->length_read;
63
64     return(limited_read_data(data,len,subregion,parse_info));
65     }
66
67 /**
68  * Reads the remainder of the subregion as a string.
69  * It is the user's responsibility to free the memory allocated here.
70  */
71
72 static int read_unsigned_string(unsigned char **str, ops_region_t *subregion, ops_parse_info_t *parse_info)
73     {
74     int len=0;
75
76     len=subregion->length-subregion->length_read;
77
78     *str=malloc(len+1);
79     if(!(*str))
80         return 0;
81
82     if(len && !ops_limited_read(*str,len,subregion,parse_info))
83         return 0;
84
85     /*! ensure the string is NULL-terminated */
86
87     (*str)[len]=(char) NULL;
88
89     return 1;
90     }
91
92 static int read_string(char **str, ops_region_t *subregion, ops_parse_info_t *parse_info)
93     {
94     return (read_unsigned_string((unsigned char **)str, subregion, parse_info));
95     }
96
97 void ops_init_subregion(ops_region_t *subregion,ops_region_t *region)
98     {
99     memset(subregion,'\0',sizeof *subregion);
100     subregion->parent=region;
101     }
102
103 /*! \todo descr for CB macro */
104 #define CB(t,pc)        do { (pc)->tag=(t); if(parse_info->cb(pc,parse_info->cb_arg) == OPS_RELEASE_MEMORY) ops_parser_content_free(pc); } while(0)
105 /*! macro to save typing */
106 #define C               content.content
107 /*! macro to run CallBack function specifying a parser error has occurred */
108 #define E               CB(OPS_PARSER_ERROR,&content); return 0
109 /*! set error code in content and run CallBack to handle error */
110 #define ERRCODE(err)    do { C.errcode.errcode=err; CB(OPS_PARSER_ERRCODE,&content); } while(0)
111 /*! set error text in content and run CallBack to handle error, then return */
112 #define ERR(err)        do { C.error.error=err; E; } while(0)
113 /*! set error text in content and run CallBack to handle warning, do not return */
114 #define WARN(warn)      do { C.error.error=warn; CB(OPS_PARSER_ERROR,&content);; } while(0)
115 /*! \todo descr ERR1 macro */
116 #define ERR1(fmt,x)     do { format_error(&content,(fmt),(x)); E; } while(0)
117
118 /* XXX: replace ops_ptag_t with something more appropriate for limiting
119    reads */
120
121 /* Note that this makes the parser non-reentrant, in a limited way */
122 /* It is the caller's responsibility to avoid overflow in the buffer */
123 static void format_error(ops_parser_content_t *content,
124                          const char *const fmt,...)
125     {
126     va_list va;
127     static char buf[8192];
128
129     va_start(va,fmt);
130     vsnprintf(buf,sizeof buf,fmt,va);
131     va_end(va);
132     content->content.error.error=buf;
133     }
134
135 /**
136  * low-level function to read data from reader function
137  *
138  * Use this function, rather than calling the reader directly.
139  *
140  * If the accumulate flag is set in *parse_info, the function
141  * adds the read data to the accumulated data, and updates
142  * the accumulated length. This is useful if, for example,
143  * the application wants access to the raw data as well as the
144  * parsed data.
145  *
146  * \param *dest
147  * \param *plength
148  * \param flags
149  * \param *parse_info
150  *
151  * \return OPS_R_OK
152  * \return OPS_R_PARTIAL_READ
153  * \return OPS_R_EOF
154  * \return OPS_R_EARLY_EOF
155  *
156  * \sa #ops_reader_ret_t, ops_reader_fd() for details of return codes
157  */
158
159 static ops_reader_ret_t base_read(unsigned char *dest,unsigned *plength,
160                                   ops_reader_flags_t flags,
161                                   ops_parse_info_t *parse_info)
162     {
163     ops_reader_ret_t ret=parse_info->reader(dest,plength,flags,parse_info);
164     if(ret != OPS_R_OK && ret != OPS_R_PARTIAL_READ)
165         return ret;
166
167     if(parse_info->accumulate)
168         {
169         assert(parse_info->asize >= parse_info->alength);
170         if(parse_info->alength+*plength > parse_info->asize)
171             {
172             parse_info->asize=parse_info->asize*2+*plength;
173             parse_info->accumulated=realloc(parse_info->accumulated,parse_info->asize);
174             }
175         assert(parse_info->asize >= parse_info->alength+*plength);
176         memcpy(parse_info->accumulated+parse_info->alength,dest,*plength);
177         }
178     // we track length anyway, because it is used for packet offsets
179     parse_info->alength+=*plength;
180     // and also the position
181     parse_info->position+=*plength;
182
183     return ret;
184     }
185
186 /** Read a scalar value of selected length from reader.
187  *
188  * Read an unsigned scalar value from reader in Big Endian representation.
189  *
190  * This function does not know or care about packet boundaries.
191  *
192  * \param *result       The scalar value is stored here
193  * \param *reader       Our reader
194  * \param length        How many bytes to read
195  * \return              OPS_R_OK on success, reader's return value otherwise
196  *
197  * \sa #ops_reader_ret_t for possible return codes
198  */
199 static ops_reader_ret_t read_scalar(unsigned *result,unsigned length,
200                                     ops_parse_info_t *parse_info)
201     {
202     unsigned t=0;
203     ops_reader_ret_t ret;
204
205     assert (length <= sizeof(*result));
206
207     while(length--)
208         {
209         unsigned char c[1];
210         unsigned one=1;
211
212         ret=base_read(c,&one,0,parse_info);
213         if(ret != OPS_R_OK)
214             return ret;
215         t=(t << 8)+c[0];
216         }
217     *result=t;
218     return OPS_R_OK;
219     }
220
221 /** Read bytes from a region within the packet.
222  *
223  * Read length bytes into the buffer pointed to by *dest.  Make sure
224  * we do not read over the packet boundary.  Updates the Packet Tag's
225  * ops_ptag_t::length_read.
226  *
227  * If length would make us read over the packet boundary, or if
228  * reading fails, we call the callback with an OPS_PARSER_ERROR.
229  *
230  * This function makes sure to respect packet boundaries.
231  *
232  * \param *dest         The destination buffer
233  * \param length        How many bytes to read
234  * \param *region       Pointer to packet region
235  * \param *parse_info   How to parse, including callback function
236  * \return              1 on success, 0 on error
237  */
238 int ops_limited_read(unsigned char *dest,unsigned length,
239                      ops_region_t *region,ops_parse_info_t *parse_info)
240     {
241     ops_parser_content_t content;
242     ops_reader_ret_t ret;
243
244     if(!region->indeterminate && region->length_read+length > region->length)
245         {
246         ERRCODE(OPS_E_P_NOT_ENOUGH_DATA);
247         return 0;
248         }
249
250     ret=base_read(dest,&length,region->indeterminate ? OPS_RETURN_LENGTH : 0,
251                   parse_info);
252
253     if(ret != OPS_R_OK && ret != OPS_R_PARTIAL_READ)
254         {
255         ERRCODE(OPS_E_R_READ_FAILED);
256         return 0;
257         }
258
259     region->last_read=length;
260     do
261         {
262         region->length_read+=length;
263         assert(!region->parent || region->length <= region->parent->length);
264         }
265     while((region=region->parent));
266
267     return 1;
268     }
269
270 /** Skip over length bytes of this packet.
271  *
272  * Calls limited_read() to skip over some data.
273  *
274  * This function makes sure to respect packet boundaries.
275  *
276  * \param length        How many bytes to skip
277  * \param *region       Pointer to packet region
278  * \param *parse_info   How to parse
279  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
280  */
281 static int limited_skip(unsigned length,ops_region_t *region,
282                         ops_parse_info_t *parse_info)
283     {
284     unsigned char buf[8192];
285
286     while(length)
287         {
288         int n=length%8192;
289         if(!ops_limited_read(buf,n,region,parse_info))
290             return 0;
291         length-=n;
292         }
293     return 1;
294     }
295
296 /** Read a scalar.
297  *
298  * Read a big-endian scalar of length bytes, respecting packet
299  * boundaries (by calling limited_read() to read the raw data).
300  *
301  * This function makes sure to respect packet boundaries.
302  *
303  * \param *dest         The scalar value is stored here
304  * \param length        How many bytes make up this scalar (at most 4)
305  * \param *region       Pointer to current packet region
306  * \param *parse_info   How to parse
307  * \param *cb           The callback
308  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
309  *
310  * \see RFC2440bis-12 3.1
311  */
312 static int limited_read_scalar(unsigned *dest,unsigned length,
313                                ops_region_t *region,
314                                ops_parse_info_t *parse_info)
315     {
316     unsigned char c[4];
317     unsigned t;
318     unsigned n;
319
320     assert(length <= 4);
321     assert(sizeof(*dest) >= 4);
322     if(!ops_limited_read(c,length,region,parse_info))
323         return 0;
324
325     for(t=0,n=0 ; n < length ; ++n)
326         t=(t << 8)+c[n];
327     *dest=t;
328
329     return 1;
330     }
331
332 /** Read a scalar.
333  *
334  * Read a big-endian scalar of length bytes, respecting packet
335  * boundaries (by calling limited_read() to read the raw data).
336  *
337  * The value read is stored in a size_t, which is a different size
338  * from an unsigned on some platforms.
339  *
340  * This function makes sure to respect packet boundaries.
341  *
342  * \param *dest         The scalar value is stored here
343  * \param length        How many bytes make up this scalar (at most 4)
344  * \param *region       Pointer to current packet region
345  * \param *parse_info   How to parse
346  * \param *cb           The callback
347  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
348  *
349  * \see RFC2440bis-12 3.1
350  */
351 static int limited_read_size_t_scalar(size_t *dest,unsigned length,
352                                       ops_region_t *region,
353                                       ops_parse_info_t *parse_info)
354     {
355     unsigned tmp;
356
357     assert(sizeof(*dest) >= 4);
358
359     /* Note that because the scalar is at most 4 bytes, we don't care
360        if size_t is bigger than usigned */
361     if(!limited_read_scalar(&tmp,length,region,parse_info))
362         return 0;
363
364     *dest=tmp;
365     return 1;
366     }
367
368 /** Read a timestamp.
369  *
370  * Timestamps in OpenPGP are unix time, i.e. seconds since The Epoch (1.1.1970).  They are stored in an unsigned scalar
371  * of 4 bytes.
372  *
373  * This function reads the timestamp using limited_read_scalar().
374  *
375  * This function makes sure to respect packet boundaries.
376  *
377  * \param *dest         The timestamp is stored here
378  * \param *ptag         Pointer to current packet's Packet Tag.
379  * \param *reader       Our reader
380  * \param *cb           The callback
381  * \return              see limited_read_scalar()
382  *
383  * \see RFC2440bis-12 3.5
384  */
385 static int limited_read_time(time_t *dest,ops_region_t *region,
386                              ops_parse_info_t *parse_info)
387     {
388     return limited_read_scalar((unsigned *)dest,4,region,parse_info);
389     }
390
391 /** Read a multiprecision integer.
392  *
393  * Large numbers (multiprecision integers, MPI) are stored in OpenPGP in two parts.  First there is a 2 byte scalar
394  * indicating the length of the following MPI in Bits.  Then follow the bits that make up the actual number, most
395  * significant bits first (Big Endian).  The most significant bit in the MPI is supposed to be 1 (unless the MPI is
396  * encrypted - then it may be different as the bit count refers to the plain text but the bits are encrypted).
397  *
398  * Unused bits (i.e. those filling up the most significant byte from the left to the first bits that counts) are
399  * supposed to be cleared - I guess. XXX - does anything actually say so?
400  *
401  * This function makes sure to respect packet boundaries.
402  *
403  * \param **pgn         return the integer there - the BIGNUM is created by BN_bin2bn() and probably needs to be freed
404  *                              by the caller XXX right ben?
405  * \param *ptag         Pointer to current packet's Packet Tag.
406  * \param *reader       Our reader
407  * \param *cb           The callback
408  * \return              1 on success, 0 on error (by limited_read_scalar() or limited_read() or if the MPI is not properly formed (XXX
409  *                               see comment below - the callback is called with a OPS_PARSER_ERROR in case of an error)
410  *
411  * \see RFC2440bis-12 3.2
412  */
413 static int limited_read_mpi(BIGNUM **pbn,ops_region_t *region,
414                             ops_parse_info_t *parse_info)
415     {
416     unsigned length;
417     unsigned nonzero;
418     unsigned char buf[8192]; /* an MPI has a 2 byte length part.  Length
419                                 is given in bits, so the largest we should
420                                 ever need for the buffer is 8192 bytes. */
421     ops_parser_content_t content;
422
423     if(!limited_read_scalar(&length,2,region,parse_info))
424         return 0;
425
426     nonzero=length&7; /* there should be this many zero bits in the MS byte */
427     if(!nonzero)
428         nonzero=8;
429     length=(length+7)/8;
430
431     assert(length <= 8192);
432     if(!ops_limited_read(buf,length,region,parse_info))
433         return 0;
434
435     if((buf[0] >> nonzero) != 0 || !(buf[0]&(1 << (nonzero-1))))
436         ERR("MPI format error");  /* XXX: Ben, one part of this constraint does not apply to encrypted MPIs the draft says. -- peter */
437
438     *pbn=BN_bin2bn(buf,length,NULL);
439     return 1;
440     }
441
442 /** Read some data with a New-Format length from reader.
443  *
444  * \sa Internet-Draft RFC2440bis-13.txt Section 4.2.2
445  *
446  * \param *length       Where the decoded length will be put
447  * \param *parse_info   How to parse
448  * \return              1 if OK, else 0
449  *
450  */
451
452 static int read_new_length(unsigned *length,ops_parse_info_t *parse_info)
453     {
454     unsigned char c[1];
455     unsigned one=1;
456
457     if(base_read(c,&one,0,parse_info) != OPS_R_OK)
458         return 0;
459     if(c[0] < 192)
460         {
461         *length=c[0];
462         return 1;
463         }
464     if(c[0] < 255)
465         {
466         unsigned t=(c[0]-192) << 8;
467
468         if(base_read(c,&one,0,parse_info) != OPS_R_OK)
469             return 0;
470         *length=t+c[0]+192;
471         return 1;
472         }
473     return (read_scalar(length,4,parse_info) == OPS_R_OK ? 1 : 0);
474     }
475
476 /** Read the length information for a new format Packet Tag.
477  *
478  * New style Packet Tags encode the length in one to five octets.  This function reads the right amount of bytes and
479  * decodes it to the proper length information.
480  *
481  * This function makes sure to respect packet boundaries.
482  *
483  * \param *length       return the length here
484  * \param *ptag         Pointer to current packet's Packet Tag.
485  * \param *reader       Our reader
486  * \param *cb           The callback
487  * \return              1 on success, 0 on error (by limited_read_scalar() or limited_read() or if the MPI is not properly formed (XXX
488  *                               see comment below)
489  *
490  * \see RFC2440bis-12 4.2.2
491  * \see ops_ptag_t
492  */
493 static int limited_read_new_length(unsigned *length,ops_region_t *region,
494                                    ops_parse_info_t *parse_info)
495     {
496     unsigned char c[1];
497
498     if(!ops_limited_read(c,1,region,parse_info))
499         return 0;
500     if(c[0] < 192)
501         {
502         *length=c[0];
503         return 1;
504         }
505     if(c[0] < 255)
506         {
507         unsigned t=(c[0]-192) << 8;
508
509         if(!ops_limited_read(c,1,region,parse_info))
510             return 0;
511         *length=t+c[0]+192;
512         return 1;
513         }
514     return limited_read_scalar(length,4,region,parse_info);
515     }
516
517 static void data_free(ops_data_t *data)
518     {
519     free(data->contents);
520     data->contents=NULL;
521     data->len=0;
522     }
523
524 static void string_free(char **str)
525     {
526     free(*str);
527     *str=NULL;
528     }
529
530 /*! Free packet memory, set pointer to NULL */
531 void ops_packet_free(ops_packet_t *packet)
532     {
533     free(packet->raw);
534     packet->raw=NULL;
535     }
536
537 void ops_headers_free(ops_headers_t *headers)
538     {
539     unsigned n;
540
541     for(n=0 ; n < headers->nheaders ; ++n)
542         {
543         free(headers->headers[n].key);
544         free(headers->headers[n].value);
545         }
546     free(headers->headers);
547     headers->headers=NULL;
548     }
549
550 void ops_signed_cleartext_trailer_free(ops_signed_cleartext_trailer_t *trailer)
551     {
552     free(trailer->hash);
553     trailer->hash=NULL;
554     }
555
556 /*! Free any memory allocated when parsing the packet content */
557 void ops_parser_content_free(ops_parser_content_t *c)
558     {
559     switch(c->tag)
560         {
561     case OPS_PARSER_PTAG:
562     case OPS_PTAG_CT_COMPRESSED:
563     case OPS_PTAG_SS_CREATION_TIME:
564     case OPS_PTAG_SS_EXPIRATION_TIME:
565     case OPS_PTAG_SS_KEY_EXPIRATION_TIME:
566     case OPS_PTAG_SS_TRUST:
567     case OPS_PTAG_SS_ISSUER_KEY_ID:
568     case OPS_PTAG_CT_ONE_PASS_SIGNATURE:
569     case OPS_PTAG_SS_PRIMARY_USER_ID:
570     case OPS_PTAG_SS_REVOCABLE:
571     case OPS_PTAG_SS_REVOCATION_KEY:
572     case OPS_PTAG_CT_LITERAL_DATA_HEADER:
573     case OPS_PTAG_CT_LITERAL_DATA_BODY:
574     case OPS_PTAG_CT_SIGNED_CLEARTEXT_BODY:
575     case OPS_PTAG_CT_UNARMOURED_TEXT:
576     case OPS_PTAG_CT_ARMOUR_TRAILER:
577     case OPS_PTAG_CT_SIGNATURE_HEADER:
578         break;
579
580     case OPS_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
581         ops_headers_free(&c->content.signed_cleartext_header.headers);
582         break;
583
584     case OPS_PTAG_CT_ARMOUR_HEADER:
585         ops_headers_free(&c->content.armour_header.headers);
586         break;
587
588     case OPS_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
589         ops_signed_cleartext_trailer_free(&c->content.signed_cleartext_trailer);
590         break;
591
592     case OPS_PTAG_CT_TRUST:
593         ops_trust_free(&c->content.trust);
594         break;
595
596     case OPS_PTAG_CT_SIGNATURE:
597     case OPS_PTAG_CT_SIGNATURE_FOOTER:
598         ops_signature_free(&c->content.signature);
599         break;
600
601     case OPS_PTAG_CT_PUBLIC_KEY:
602     case OPS_PTAG_CT_PUBLIC_SUBKEY:
603         ops_public_key_free(&c->content.public_key);
604         break;
605
606     case OPS_PTAG_CT_USER_ID:
607         ops_user_id_free(&c->content.user_id);
608         break;
609
610     case OPS_PTAG_SS_SIGNERS_USER_ID:
611         ops_user_id_free(&c->content.ss_signers_user_id);
612         break;
613
614     case OPS_PTAG_CT_USER_ATTRIBUTE:
615         ops_user_attribute_free(&c->content.user_attribute);
616         break;
617
618     case OPS_PTAG_SS_PREFERRED_SKA:
619         ops_ss_preferred_ska_free(&c->content.ss_preferred_ska);
620         break;
621
622     case OPS_PTAG_SS_PREFERRED_HASH:
623         ops_ss_preferred_hash_free(&c->content.ss_preferred_hash);
624         break;
625
626     case OPS_PTAG_SS_PREFERRED_COMPRESSION:
627         ops_ss_preferred_compression_free(&c->content.ss_preferred_compression);
628         break;
629
630     case OPS_PTAG_SS_KEY_FLAGS:
631         ops_ss_key_flags_free(&c->content.ss_key_flags);
632         break;
633
634     case OPS_PTAG_SS_KEY_SERVER_PREFS:
635         ops_ss_key_server_prefs_free(&c->content.ss_key_server_prefs);
636         break;
637
638     case OPS_PTAG_SS_FEATURES:
639         ops_ss_features_free(&c->content.ss_features);
640         break;
641
642     case OPS_PTAG_SS_NOTATION_DATA:
643         ops_ss_notation_data_free(&c->content.ss_notation_data);
644         break;
645
646     case OPS_PTAG_SS_REGEXP:
647         ops_ss_regexp_free(&c->content.ss_regexp);
648         break;
649
650     case OPS_PTAG_SS_POLICY_URL:
651         ops_ss_policy_url_free(&c->content.ss_policy_url);
652         break;
653
654     case OPS_PTAG_SS_PREFERRED_KEY_SERVER:
655         ops_ss_preferred_key_server_free(&c->content.ss_preferred_key_server);
656         break;
657
658     case OPS_PTAG_SS_USERDEFINED00:
659     case OPS_PTAG_SS_USERDEFINED01:
660     case OPS_PTAG_SS_USERDEFINED02:
661     case OPS_PTAG_SS_USERDEFINED03:
662     case OPS_PTAG_SS_USERDEFINED04:
663     case OPS_PTAG_SS_USERDEFINED05:
664     case OPS_PTAG_SS_USERDEFINED06:
665     case OPS_PTAG_SS_USERDEFINED07:
666     case OPS_PTAG_SS_USERDEFINED08:
667     case OPS_PTAG_SS_USERDEFINED09:
668     case OPS_PTAG_SS_USERDEFINED10:
669         ops_ss_userdefined_free(&c->content.ss_userdefined);
670         break;
671
672     case OPS_PTAG_SS_RESERVED:
673         ops_ss_reserved_free(&c->content.ss_unknown);
674         break;
675
676     case OPS_PTAG_SS_REVOCATION_REASON:
677         ops_ss_revocation_reason_free(&c->content.ss_revocation_reason);
678         break;
679
680     case OPS_PARSER_PACKET_END:
681         ops_packet_free(&c->content.packet);
682         break;
683
684     case OPS_PARSER_ERROR:
685     case OPS_PARSER_ERRCODE:
686         break;
687
688     case OPS_PTAG_CT_SECRET_KEY:
689         ops_secret_key_free(&c->content.secret_key);
690         break;
691
692     default:
693         fprintf(stderr,"Can't free %d (0x%x)\n",c->tag,c->tag);
694         assert(0);
695         }
696     }
697
698 static void free_BN(BIGNUM **pp)
699     {
700     BN_free(*pp);
701     *pp=NULL;
702     }
703
704 /*! Free the memory used when parsing a public key */
705 void ops_public_key_free(ops_public_key_t *p)
706     {
707     switch(p->algorithm)
708         {
709     case OPS_PKA_RSA:
710     case OPS_PKA_RSA_ENCRYPT_ONLY:
711     case OPS_PKA_RSA_SIGN_ONLY:
712         free_BN(&p->key.rsa.n);
713         free_BN(&p->key.rsa.e);
714         break;
715
716     case OPS_PKA_DSA:
717         free_BN(&p->key.dsa.p);
718         free_BN(&p->key.dsa.q);
719         free_BN(&p->key.dsa.g);
720         free_BN(&p->key.dsa.y);
721         break;
722
723     case OPS_PKA_ELGAMAL:
724     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
725         free_BN(&p->key.elgamal.p);
726         free_BN(&p->key.elgamal.g);
727         free_BN(&p->key.elgamal.y);
728         break;
729
730     default:
731         assert(0);
732         }
733     }
734
735 static int parse_public_key_data(ops_public_key_t *key,ops_region_t *region,
736                                  ops_parse_info_t *parse_info)
737     {
738     ops_parser_content_t content;
739     unsigned char c[1];
740
741     assert (region->length_read == 0);  /* We should not have read anything so far */
742
743     if(!ops_limited_read(c,1,region,parse_info))
744         return 0;
745     key->version=c[0];
746     if(key->version < 2 || key->version > 4)
747         ERR1("Bad public key version (0x%02x)",key->version);
748
749     if(!limited_read_time(&key->creation_time,region,parse_info))
750         return 0;
751
752     key->days_valid=0;
753     if((key->version == 2 || key->version == 3)
754        && !limited_read_scalar(&key->days_valid,2,region,parse_info))
755         return 0;
756
757     if(!ops_limited_read(c,1,region,parse_info))
758         return 0;
759
760     key->algorithm=c[0];
761
762     switch(key->algorithm)
763         {
764     case OPS_PKA_DSA:
765         if(!limited_read_mpi(&key->key.dsa.p,region,parse_info)
766            || !limited_read_mpi(&key->key.dsa.q,region,parse_info)
767            || !limited_read_mpi(&key->key.dsa.g,region,parse_info)
768            || !limited_read_mpi(&key->key.dsa.y,region,parse_info))
769             return 0;
770         break;
771
772     case OPS_PKA_RSA:
773     case OPS_PKA_RSA_ENCRYPT_ONLY:
774     case OPS_PKA_RSA_SIGN_ONLY:
775         if(!limited_read_mpi(&key->key.rsa.n,region,parse_info)
776            || !limited_read_mpi(&key->key.rsa.e,region,parse_info))
777             return 0;
778         break;
779
780     case OPS_PKA_ELGAMAL:
781     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
782         if(!limited_read_mpi(&key->key.elgamal.p,region,parse_info)
783            || !limited_read_mpi(&key->key.elgamal.g,region,parse_info)
784            || !limited_read_mpi(&key->key.elgamal.y,region,parse_info))
785             return 0;
786         break;
787
788     default:
789         ERR1("Unknown public key algorithm (%d)",key->algorithm);
790         }
791
792     return 1;
793     }
794
795
796 /** Parse a public key packet.
797  *
798  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
799  *
800  * Once the key has been parsed successfully, it is passed to the callback.
801  *
802  * \param *ptag         Pointer to the current Packet Tag.  This function should consume the entire packet.
803  * \param *reader       Our reader
804  * \param *cb           The callback
805  * \return              1 on success, 0 on error
806  *
807  * \see RFC2440bis-12 5.5.2
808  */
809 static int parse_public_key(ops_content_tag_t tag,ops_region_t *region,
810                             ops_parse_info_t *parse_info)
811     {
812     ops_parser_content_t content;
813
814     if(!parse_public_key_data(&C.public_key,region,parse_info))
815         return 0;
816
817     // XXX: this test should be done for all packets, surely?
818     if(region->length_read != region->length)
819         ERR1("Unconsumed data (%d)",region->length-region->length_read);
820
821     CB(tag,&content);
822
823     return 1;
824     }
825
826
827 /*! Free the memory used when parsing this signature sub-packet type */
828 void ops_ss_regexp_free(ops_ss_regexp_t *regexp)
829     {
830     string_free(&regexp->text);
831     }
832
833 /*! Free the memory used when parsing this signature sub-packet type */
834 void ops_ss_policy_url_free(ops_ss_policy_url_t *policy_url)
835     {
836     string_free(&policy_url->text);
837     }
838
839 /*! Free the memory used when parsing this signature sub-packet type */
840 void ops_ss_preferred_key_server_free(ops_ss_preferred_key_server_t *preferred_key_server)
841     {
842     string_free(&preferred_key_server->text);
843     }
844
845 /*! Free the memory used when parsing this packet type */
846 void ops_user_attribute_free(ops_user_attribute_t *user_att)
847     {
848     data_free(&user_att->data);
849     }
850
851 /** Parse one user attribute packet.
852  *
853  * User attribute packets contain one or more attribute subpackets.
854  * For now, handle the whole packet as raw data.
855  */
856
857 static int parse_user_attribute(ops_region_t *region, ops_parse_info_t *parse_info)
858     {
859
860     ops_parser_content_t content;
861
862     /* xxx- treat as raw data for now. Could break down further
863        into attribute sub-packets later - rachel */
864
865     assert(region->length_read == 0);  /* We should not have read anything so far */
866
867     if(!read_data(&C.user_attribute.data,region,parse_info))
868         return 0;
869
870     CB(OPS_PTAG_CT_USER_ATTRIBUTE,&content);
871
872     return 1;
873     }
874
875 /*! Free the memory used when parsing this packet type */
876 void ops_user_id_free(ops_user_id_t *id)
877     {
878     free(id->user_id);
879     id->user_id=NULL;
880     }
881
882 /** Parse a user id.
883  *
884  * This function parses an user id packet, which is basically just a char array the size of the packet.
885  *
886  * The char array is to be treated as an UTF-8 string.
887  *
888  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
889  *
890  * Once the userid has been parsed successfully, it is passed to the callback.
891  *
892  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire packet.
893  * \param *reader       Our reader
894  * \param *cb           The callback
895  * \return              1 on success, 0 on error
896  *
897  * \see RFC2440bis-12 5.11
898  */
899 static int parse_user_id(ops_region_t *region,ops_parse_info_t *parse_info)
900     {
901     ops_parser_content_t content;
902
903     assert(region->length_read == 0);  /* We should not have read anything so far */
904
905     C.user_id.user_id=malloc(region->length+1);  /* XXX should we not like check malloc's return value? */
906
907     if(region->length && !ops_limited_read(C.user_id.user_id,region->length,
908                                            region,parse_info))
909         return 0;
910
911     C.user_id.user_id[region->length]='\0'; /* terminate the string */
912
913     CB(OPS_PTAG_CT_USER_ID,&content);
914
915     return 1;
916     }
917
918 /**
919  * \ingroup Memory
920  *
921  * Free the memory used when parsing a private/experimental PKA signature
922  *
923  * \param unknown_sig
924  */
925 void free_unknown_sig_pka(ops_unknown_signature_t *unknown_sig)
926     {
927     data_free(&unknown_sig->data);
928     }
929
930 /**
931  * \ingroup Memory
932  *
933  * Free the memory used when parsing a signature
934  *
935  * \param sig
936  */
937 void ops_signature_free(ops_signature_t *sig)
938     {
939     switch(sig->key_algorithm)
940         {
941     case OPS_PKA_RSA:
942         free_BN(&sig->signature.rsa.sig);
943         break;
944
945     case OPS_PKA_DSA:
946         free_BN(&sig->signature.dsa.r);
947         free_BN(&sig->signature.dsa.s);
948         break;
949
950     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
951         free_BN(&sig->signature.elgamal.r);
952         free_BN(&sig->signature.elgamal.s);
953         break;
954
955     case OPS_PKA_PRIVATE00:
956     case OPS_PKA_PRIVATE01:
957     case OPS_PKA_PRIVATE02:
958     case OPS_PKA_PRIVATE03:
959     case OPS_PKA_PRIVATE04:
960     case OPS_PKA_PRIVATE05:
961     case OPS_PKA_PRIVATE06:
962     case OPS_PKA_PRIVATE07:
963     case OPS_PKA_PRIVATE08:
964     case OPS_PKA_PRIVATE09:
965     case OPS_PKA_PRIVATE10:
966         free_unknown_sig_pka(&sig->signature.unknown);
967         break;
968
969     default:
970         assert(0);
971         }
972     }
973
974 /** Parse a version 3 signature.
975  *
976  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
977  *
978  * Once the signature has been parsed successfully, it is passed to the callback.
979  *
980  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire packet.
981  * \param *reader       Our reader
982  * \param *cb           The callback
983  * \return              1 on success, 0 on error
984  *
985  * \see RFC2440bis-12 5.2.2
986  */
987 static int parse_v3_signature(ops_region_t *region,ops_parse_info_t *parse_info)
988     {
989     unsigned char c[1];
990     ops_parser_content_t content;
991
992     C.signature.version=OPS_SIG_V3;
993
994     /* hash info length */
995     if(!ops_limited_read(c,1,region,parse_info))
996         return 0;
997     if(c[0] != 5)
998         ERR("bad hash info length");
999
1000     if(!ops_limited_read(c,1,region,parse_info))
1001         return 0;
1002     C.signature.type=c[0];
1003     /* XXX: check signature type */
1004
1005     if(!limited_read_time(&C.signature.creation_time,region,parse_info))
1006         return 0;
1007     C.signature.creation_time_set=ops_true;
1008
1009     if(!ops_limited_read(C.signature.signer_id,OPS_KEY_ID_SIZE,region,parse_info))
1010         return 0;
1011     C.signature.signer_id_set=ops_true;
1012
1013     if(!ops_limited_read(c,1,region,parse_info))
1014         return 0;
1015     C.signature.key_algorithm=c[0];
1016     /* XXX: check algorithm */
1017
1018     if(!ops_limited_read(c,1,region,parse_info))
1019         return 0;
1020     C.signature.hash_algorithm=c[0];
1021     /* XXX: check algorithm */
1022    
1023     if(!ops_limited_read(C.signature.hash2,2,region,parse_info))
1024         return 0;
1025
1026     switch(C.signature.key_algorithm)
1027         {
1028     case OPS_PKA_RSA:
1029         if(!limited_read_mpi(&C.signature.signature.rsa.sig,region,parse_info))
1030             return 0;
1031         break;
1032
1033     case OPS_PKA_DSA:
1034         if(!limited_read_mpi(&C.signature.signature.dsa.r,region,parse_info)
1035            || !limited_read_mpi(&C.signature.signature.dsa.s,region,parse_info))
1036             return 0;
1037         break;
1038
1039     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1040         if(!limited_read_mpi(&C.signature.signature.elgamal.r,region,parse_info)
1041            || !limited_read_mpi(&C.signature.signature.elgamal.s,region,parse_info))
1042             return 0;
1043         break;
1044
1045     default:
1046         ERR1("Bad signature key algorithm (%d)",C.signature.key_algorithm);
1047         }
1048
1049     if(region->length_read != region->length)
1050         ERR1("Unconsumed data (%d)",region->length-region->length_read);
1051
1052     CB(OPS_PTAG_CT_SIGNATURE,&content);
1053
1054     return 1;
1055     }
1056
1057 /** Parse one signature sub-packet.
1058  *
1059  * Version 4 signatures can have an arbitrary amount of (hashed and unhashed) subpackets.  Subpackets are used to hold
1060  * optional attributes of subpackets.
1061  *
1062  * This function parses one such signature subpacket.
1063  *
1064  * Once the subpacket has been parsed successfully, it is passed to the callback.
1065  *
1066  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire subpacket.
1067  * \param *reader       Our reader
1068  * \param *cb           The callback
1069  * \return              1 on success, 0 on error
1070  *
1071  * \see RFC2440bis-12 5.2.3
1072  */
1073 static int parse_one_signature_subpacket(ops_signature_t *sig,
1074                                          ops_region_t *region,
1075                                          ops_parse_info_t *parse_info)
1076     {
1077     ops_region_t subregion;
1078     unsigned char c[1];
1079     ops_parser_content_t content;
1080     unsigned t8,t7;
1081     ops_boolean_t read=ops_true;
1082     unsigned char bool[1];
1083
1084     ops_init_subregion(&subregion,region);
1085     if(!limited_read_new_length(&subregion.length,region,parse_info))
1086         return 0;
1087
1088     if(subregion.length > region->length)
1089         ERR("Subpacket too long");
1090
1091     if(!ops_limited_read(c,1,&subregion,parse_info))
1092         return 0;
1093
1094     t8=(c[0]&0x7f)/8;
1095     t7=1 << (c[0]&7);
1096
1097     content.critical=c[0] >> 7;
1098     content.tag=OPS_PTAG_SIGNATURE_SUBPACKET_BASE+(c[0]&0x7f);
1099
1100     /* Application wants it delivered raw */
1101     if(parse_info->ss_raw[t8]&t7)
1102         {
1103         C.ss_raw.tag=content.tag;
1104         C.ss_raw.length=subregion.length-1;
1105         C.ss_raw.raw=malloc(C.ss_raw.length);
1106         if(!ops_limited_read(C.ss_raw.raw,C.ss_raw.length,&subregion,parse_info))
1107             return 0;
1108         CB(OPS_PTAG_RAW_SS,&content);
1109         return 1;
1110         }
1111
1112     switch(content.tag)
1113         {
1114     case OPS_PTAG_SS_CREATION_TIME:
1115     case OPS_PTAG_SS_EXPIRATION_TIME:
1116     case OPS_PTAG_SS_KEY_EXPIRATION_TIME:
1117         if(!limited_read_time(&C.ss_time.time,&subregion,parse_info))
1118             return 0;
1119         if(content.tag == OPS_PTAG_SS_CREATION_TIME)
1120             {
1121             sig->creation_time=C.ss_time.time;
1122             sig->creation_time_set=ops_true;
1123             }
1124         break;
1125
1126     case OPS_PTAG_SS_TRUST:
1127         if(!ops_limited_read(&C.ss_trust.level,1,&subregion,parse_info)
1128            || !ops_limited_read(&C.ss_trust.amount,1,&subregion,parse_info))
1129             return 0;
1130         break;
1131
1132     case OPS_PTAG_SS_REVOCABLE:
1133         if(!ops_limited_read(bool,1,&subregion,parse_info))
1134             return 0;
1135         C.ss_revocable.revocable=!!bool;
1136         break;
1137
1138     case OPS_PTAG_SS_ISSUER_KEY_ID:
1139         if(!ops_limited_read(C.ss_issuer_key_id.key_id,OPS_KEY_ID_SIZE,
1140                              &subregion,parse_info))
1141             return 0;
1142         memcpy(sig->signer_id,C.ss_issuer_key_id.key_id,OPS_KEY_ID_SIZE);
1143         sig->signer_id_set=ops_true;
1144         break;
1145
1146     case OPS_PTAG_SS_PREFERRED_SKA:
1147         if(!read_data(&C.ss_preferred_ska.data,&subregion,parse_info))
1148             return 0;
1149         break;
1150                                
1151     case OPS_PTAG_SS_PREFERRED_HASH:
1152         if(!read_data(&C.ss_preferred_hash.data,&subregion,parse_info))
1153             return 0;
1154         break;
1155                                
1156     case OPS_PTAG_SS_PREFERRED_COMPRESSION:
1157         if(!read_data(&C.ss_preferred_compression.data,&subregion,parse_info))
1158             return 0;
1159         break;
1160                                
1161     case OPS_PTAG_SS_PRIMARY_USER_ID:
1162         if(!ops_limited_read (bool,1,&subregion,parse_info))
1163             return 0;
1164         C.ss_primary_user_id.primary_user_id = !!bool;
1165         break;
1166  
1167     case OPS_PTAG_SS_KEY_FLAGS:
1168         if(!read_data(&C.ss_key_flags.data,&subregion,parse_info))
1169             return 0;
1170         break;
1171
1172     case OPS_PTAG_SS_KEY_SERVER_PREFS:
1173         if(!read_data(&C.ss_key_server_prefs.data,&subregion,parse_info))
1174             return 0;
1175         break;
1176
1177     case OPS_PTAG_SS_FEATURES:
1178         if(!read_data(&C.ss_features.data,&subregion,parse_info))
1179             return 0;
1180         break;
1181
1182     case OPS_PTAG_SS_SIGNERS_USER_ID:
1183         if(!read_unsigned_string(&C.ss_signers_user_id.user_id,&subregion,parse_info))
1184             return 0;
1185         break;
1186
1187     case OPS_PTAG_SS_NOTATION_DATA:
1188         if(!limited_read_data(&C.ss_notation_data.flags,4,&subregion,parse_info))
1189             return 0;
1190         if(!limited_read_size_t_scalar(&C.ss_notation_data.name.len,2,
1191                                        &subregion,parse_info))
1192             return 0;
1193         if(!limited_read_size_t_scalar(&C.ss_notation_data.value.len,2,
1194                                        &subregion,parse_info))
1195             return 0;
1196         if(!limited_read_data(&C.ss_notation_data.name,
1197                               C.ss_notation_data.name.len,&subregion,parse_info))
1198             return 0;
1199         if(!limited_read_data(&C.ss_notation_data.value,
1200                               C.ss_notation_data.value.len,&subregion,parse_info))
1201             return 0;
1202         break;
1203
1204     case OPS_PTAG_SS_POLICY_URL:
1205         if(!read_string(&C.ss_policy_url.text,&subregion,parse_info))
1206             return 0;
1207         break;
1208
1209     case OPS_PTAG_SS_REGEXP:
1210         if(!read_string(&C.ss_regexp.text,&subregion, parse_info))
1211             return 0;
1212         break;
1213
1214     case OPS_PTAG_SS_PREFERRED_KEY_SERVER:
1215         if(!read_string(&C.ss_preferred_key_server.text,&subregion,parse_info))
1216             return 0;
1217         break;
1218
1219     case OPS_PTAG_SS_USERDEFINED00:
1220     case OPS_PTAG_SS_USERDEFINED01:
1221     case OPS_PTAG_SS_USERDEFINED02:
1222     case OPS_PTAG_SS_USERDEFINED03:
1223     case OPS_PTAG_SS_USERDEFINED04:
1224     case OPS_PTAG_SS_USERDEFINED05:
1225     case OPS_PTAG_SS_USERDEFINED06:
1226     case OPS_PTAG_SS_USERDEFINED07:
1227     case OPS_PTAG_SS_USERDEFINED08:
1228     case OPS_PTAG_SS_USERDEFINED09:
1229     case OPS_PTAG_SS_USERDEFINED10:
1230         if(!read_data(&C.ss_userdefined.data,&subregion,parse_info))
1231             return 0;
1232         break;
1233
1234     case OPS_PTAG_SS_RESERVED:
1235         if(!read_data(&C.ss_unknown.data,&subregion,parse_info))
1236             return 0;
1237         break;
1238
1239     case OPS_PTAG_SS_REVOCATION_REASON:
1240         /* first byte is the machine-readable code */
1241         if(!ops_limited_read(&C.ss_revocation_reason.code,1,&subregion,parse_info))
1242             return 0;
1243
1244         /* the rest is a human-readable UTF-8 string */
1245         if(!read_string(&C.ss_revocation_reason.text,&subregion,parse_info))
1246             return 0;
1247         break;
1248
1249     case OPS_PTAG_SS_REVOCATION_KEY:
1250         /* octet 0 = class. Bit 0x80 must be set */
1251         if(!ops_limited_read (&C.ss_revocation_key.class,1,&subregion,parse_info))
1252             return 0;
1253         if(!(C.ss_revocation_key.class&0x80))
1254             {
1255             printf("Warning: OPS_PTAG_SS_REVOCATION_KEY class: "
1256                    "Bit 0x80 should be set\n");
1257             return 0;
1258             }
1259  
1260         /* octet 1 = algid */
1261         if(!ops_limited_read(&C.ss_revocation_key.algid,1,&subregion,parse_info))
1262             return 0;
1263  
1264         /* octets 2-21 = fingerprint */
1265         if(!ops_limited_read(&C.ss_revocation_key.fingerprint[0],20,&subregion,
1266                              parse_info))
1267             return 0;
1268         break;
1269  
1270     default:
1271         if(parse_info->ss_parsed[t8]&t7)
1272             ERR1("Unknown signature subpacket type (%d)",c[0]&0x7f);
1273         read=ops_false;
1274         break;
1275         }
1276
1277     /* Application doesn't want it delivered parsed */
1278     if(!(parse_info->ss_parsed[t8]&t7))
1279         {
1280         if(content.critical)
1281             ERR1("Critical signature subpacket ignored (%d)",c[0]&0x7f);
1282         if(!read && !limited_skip(subregion.length-1,&subregion,parse_info))
1283             return 0;
1284         //      printf("skipped %d length %d\n",c[0]&0x7f,subregion.length);
1285         if(read)
1286             ops_parser_content_free(&content);
1287         return 1;
1288         }
1289
1290     if(read && subregion.length_read != subregion.length)
1291         ERR1("Unconsumed data (%d)", subregion.length-subregion.length_read);
1292  
1293     CB(content.tag,&content);
1294
1295     return 1;
1296     }
1297
1298 /*! Free the memory used when parsing this signature sub-packet type */
1299 void ops_ss_preferred_ska_free(ops_ss_preferred_ska_t *ss_preferred_ska)
1300     {
1301     data_free(&ss_preferred_ska->data);
1302     }
1303
1304 /*! Free the memory used when parsing this signature sub-packet type */
1305 void ops_ss_preferred_hash_free(ops_ss_preferred_hash_t *ss_preferred_hash)
1306     {
1307     data_free(&ss_preferred_hash->data);
1308     }
1309
1310 /*! Free the memory used when parsing this signature sub-packet type */
1311 void ops_ss_preferred_compression_free(ops_ss_preferred_compression_t *ss_preferred_compression)
1312     {
1313     data_free(&ss_preferred_compression->data);
1314     }
1315
1316 /*! Free the memory used when parsing this signature sub-packet type */
1317 void ops_ss_key_flags_free(ops_ss_key_flags_t *ss_key_flags)
1318     {
1319     data_free(&ss_key_flags->data);
1320     }
1321
1322 /*! Free the memory used when parsing this signature sub-packet type */
1323 void ops_ss_features_free(ops_ss_features_t *ss_features)
1324     {
1325     data_free(&ss_features->data);
1326     }
1327
1328 /*! Free the memory used when parsing this signature sub-packet type */
1329 void ops_ss_key_server_prefs_free(ops_ss_key_server_prefs_t *ss_key_server_prefs)
1330     {
1331     data_free(&ss_key_server_prefs->data);
1332     }
1333
1334 /** Parse several signature subpackets.
1335  *
1336  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1337  * This function parses this length and then calls parse_one_signature_subpacket() for each subpacket until the
1338  * entire set is consumed.
1339  *
1340  * This function does not call the callback directly, parse_one_signature_subpacket() does for each subpacket.
1341  *
1342  * \param *ptag         Pointer to the Packet Tag.
1343  * \param *reader       Our reader
1344  * \param *cb           The callback
1345  * \return              1 on success, 0 on error
1346  *
1347  * \see RFC2440bis-12 5.2.3
1348  */
1349 static int parse_signature_subpackets(ops_signature_t *sig,
1350                                       ops_region_t *region,
1351                                       ops_parse_info_t *parse_info)
1352     {
1353     ops_region_t subregion;
1354     ops_parser_content_t content;
1355
1356     ops_init_subregion(&subregion,region);
1357     if(!limited_read_scalar(&subregion.length,2,region,parse_info))
1358         return 0;
1359
1360     if(subregion.length > region->length)
1361         ERR("Subpacket set too long");
1362
1363     while(subregion.length_read < subregion.length)
1364         if(!parse_one_signature_subpacket(sig,&subregion,parse_info))
1365             return 0;
1366
1367     if(subregion.length_read != subregion.length)
1368         {
1369         if(!limited_skip(subregion.length-subregion.length_read,&subregion,
1370                          parse_info))
1371             ERR("Read failed while recovering from subpacket length mismatch");
1372         ERR("Subpacket length mismatch");
1373         }
1374
1375     return 1;
1376     }
1377
1378 /** Parse a version 4 signature.
1379  *
1380  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
1381  *
1382  * Once the signature packet has been parsed successfully, it is passed to the callback.
1383  *
1384  * \param *ptag         Pointer to the Packet Tag.
1385  * \param *reader       Our reader
1386  * \param *cb           The callback
1387  * \return              1 on success, 0 on error
1388  *
1389  * \see RFC2440bis-12 5.2.3
1390  */
1391 static int parse_v4_signature(ops_region_t *region,ops_parse_info_t *parse_info,
1392                               size_t v4_hashed_data_start)
1393     {
1394     unsigned char c[1];
1395     ops_parser_content_t content;
1396
1397     memset(&C.signature,'\0',sizeof C.signature);
1398     C.signature.version=OPS_SIG_V4;
1399     C.signature.v4_hashed_data_start=v4_hashed_data_start;
1400
1401     if(!ops_limited_read(c,1,region,parse_info))
1402         return 0;
1403     C.signature.type=c[0];
1404     /* XXX: check signature type */
1405
1406     if(!ops_limited_read(c,1,region,parse_info))
1407         return 0;
1408     C.signature.key_algorithm=c[0];
1409     /* XXX: check algorithm */
1410
1411     if(!ops_limited_read(c,1,region,parse_info))
1412         return 0;
1413     C.signature.hash_algorithm=c[0];
1414     /* XXX: check algorithm */
1415
1416     CB(OPS_PTAG_CT_SIGNATURE_HEADER,&content);
1417
1418     if(!parse_signature_subpackets(&C.signature,region,parse_info))
1419         return 0;
1420     C.signature.v4_hashed_data_length=parse_info->alength
1421         -C.signature.v4_hashed_data_start;
1422
1423     if(!parse_signature_subpackets(&C.signature,region,parse_info))
1424         return 0;
1425    
1426     if(!ops_limited_read(C.signature.hash2,2,region,parse_info))
1427         return 0;
1428
1429     switch(C.signature.key_algorithm)
1430         {
1431     case OPS_PKA_RSA:
1432         if(!limited_read_mpi(&C.signature.signature.rsa.sig,region,parse_info))
1433             return 0;
1434         break;
1435
1436     case OPS_PKA_DSA:
1437         if(!limited_read_mpi(&C.signature.signature.dsa.r,region,parse_info))
1438             ERR("Error reading DSA r field in signature");
1439         if (!limited_read_mpi(&C.signature.signature.dsa.s,region,parse_info))
1440             ERR("Error reading DSA s field in signature");
1441         break;
1442
1443     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1444         if(!limited_read_mpi(&C.signature.signature.elgamal.r,region,parse_info)
1445            || !limited_read_mpi(&C.signature.signature.elgamal.s,region,parse_info))
1446             return 0;
1447         break;
1448
1449     case OPS_PKA_PRIVATE00:
1450     case OPS_PKA_PRIVATE01:
1451     case OPS_PKA_PRIVATE02:
1452     case OPS_PKA_PRIVATE03:
1453     case OPS_PKA_PRIVATE04:
1454     case OPS_PKA_PRIVATE05:
1455     case OPS_PKA_PRIVATE06:
1456     case OPS_PKA_PRIVATE07:
1457     case OPS_PKA_PRIVATE08:
1458     case OPS_PKA_PRIVATE09:
1459     case OPS_PKA_PRIVATE10:
1460         if (!read_data(&C.signature.signature.unknown.data,region,parse_info))
1461             return 0;
1462         break;
1463
1464     default:
1465         ERR1("Bad v4 signature key algorithm (%d)",C.signature.key_algorithm);
1466         }
1467
1468     if(region->length_read != region->length)
1469         ERR1("Unconsumed data (%d)",region->length-region->length_read);
1470
1471     CB(OPS_PTAG_CT_SIGNATURE_FOOTER,&content);
1472
1473     return 1;
1474     }
1475
1476 /** Parse a signature subpacket.
1477  *
1478  * This function calls the appropriate function to handle v3 or v4 signatures.
1479  *
1480  * Once the signature packet has been parsed successfully, it is passed to the callback.
1481  *
1482  * \param *ptag         Pointer to the Packet Tag.
1483  * \param *reader       Our reader
1484  * \param *cb           The callback
1485  * \return              1 on success, 0 on error
1486  */
1487 static int parse_signature(ops_region_t *region,ops_parse_info_t *parse_info)
1488     {
1489     unsigned char c[1];
1490     ops_parser_content_t content;
1491     size_t v4_hashed_data_start;
1492
1493     assert(region->length_read == 0);  /* We should not have read anything so far */
1494
1495     memset(&content,'\0',sizeof content);
1496
1497     v4_hashed_data_start=parse_info->alength;
1498     if(!ops_limited_read(c,1,region,parse_info))
1499         return 0;
1500
1501     /* XXX: More V2 issues!  - Ben*/
1502     /* XXX: are there v2 signatures? - Peter */
1503     if(c[0] == 2 || c[0] == 3)
1504         return parse_v3_signature(region,parse_info);
1505     else if(c[0] == 4)
1506         return parse_v4_signature(region,parse_info,v4_hashed_data_start);
1507     ERR1("Bad signature version (%d)",c[0]);
1508     }
1509
1510 static int parse_compressed(ops_region_t *region,ops_parse_info_t *parse_info)
1511     {
1512     unsigned char c[1];
1513     ops_parser_content_t content;
1514
1515     if(!ops_limited_read(c,1,region,parse_info))
1516         return 0;
1517
1518     C.compressed.type=c[0];
1519
1520     CB(OPS_PTAG_CT_COMPRESSED,&content);
1521
1522     /* The content of a compressed data packet is more OpenPGP packets
1523        once decompressed, so recursively handle them */
1524
1525     return ops_decompress(region,parse_info);
1526     }
1527
1528 static int parse_one_pass(ops_region_t *region,ops_parse_info_t *parse_info)
1529     {
1530     unsigned char c[1];
1531     ops_parser_content_t content;
1532
1533     if(!ops_limited_read(&C.one_pass_signature.version,1,region,parse_info))
1534         return 0;
1535     if(C.one_pass_signature.version != 3)
1536         ERR1("Bad one-pass signature version (%d)",
1537              C.one_pass_signature.version);
1538
1539     if(!ops_limited_read(c,1,region,parse_info))
1540         return 0;
1541     C.one_pass_signature.sig_type=c[0];
1542
1543     if(!ops_limited_read(c,1,region,parse_info))
1544         return 0;
1545     C.one_pass_signature.hash_algorithm=c[0];
1546
1547     if(!ops_limited_read(c,1,region,parse_info))
1548         return 0;
1549     C.one_pass_signature.key_algorithm=c[0];
1550
1551     if(!ops_limited_read(C.one_pass_signature.keyid,
1552                          sizeof C.one_pass_signature.keyid,region,parse_info))
1553         return 0;
1554
1555     if(!ops_limited_read(c,1,region,parse_info))
1556         return 0;
1557     C.one_pass_signature.nested=!!c[0];
1558
1559     CB(OPS_PTAG_CT_ONE_PASS_SIGNATURE,&content);
1560
1561     return 1;
1562     }
1563
1564 /*! Free the memory used when parsing this signature sub-packet type */
1565 void ops_ss_userdefined_free(ops_ss_userdefined_t *ss_userdefined)
1566     {
1567     data_free(&ss_userdefined->data);
1568     }
1569
1570 /*! Free the memory used when parsing this signature sub-packet type */
1571 void ops_ss_reserved_free(ops_ss_unknown_t *ss_unknown)
1572     {
1573     data_free(&ss_unknown->data);
1574     }
1575
1576 /*! Free the memory used when parsing this signature sub-packet type */
1577 void ops_ss_notation_data_free(ops_ss_notation_data_t *ss_notation_data)
1578      {
1579      data_free(&ss_notation_data->name);
1580      data_free(&ss_notation_data->value);
1581      }
1582
1583 /*! Free the memory used when parsing this signature sub-packet type */
1584 void ops_ss_revocation_reason_free(ops_ss_revocation_reason_t *ss_revocation_reason)
1585     {
1586     string_free(&ss_revocation_reason->text);
1587     }
1588
1589 /*! Free the memory used when parsing this packet type */
1590 void ops_trust_free(ops_trust_t *trust)
1591     {
1592     data_free(&trust->data);
1593     }
1594
1595 static int
1596 parse_trust (ops_region_t *region, ops_parse_info_t *parse_info)
1597     {
1598     ops_parser_content_t content;
1599
1600     if(!read_data(&C.trust.data,region,parse_info))
1601             return 0;
1602
1603     CB(OPS_PTAG_CT_TRUST, &content);
1604
1605     return 1;
1606     }
1607
1608 static int parse_literal_data(ops_region_t *region,ops_parse_info_t *parse_info)
1609     {
1610     ops_parser_content_t content;
1611     unsigned char c[1];
1612
1613     if(!ops_limited_read(c,1,region,parse_info))
1614         return 0;
1615     C.literal_data_header.format=c[0];
1616
1617     if(!ops_limited_read(c,1,region,parse_info))
1618         return 0;
1619     if(!ops_limited_read((unsigned char *)C.literal_data_header.filename,c[0],region,parse_info))
1620         return 0;
1621     C.literal_data_header.filename[c[0]]='\0';
1622
1623     if(!limited_read_time(&C.literal_data_header.modification_time,region,parse_info))
1624         return 0;
1625
1626     CB(OPS_PTAG_CT_LITERAL_DATA_HEADER,&content);
1627
1628     while(region->length_read < region->length)
1629         {
1630         unsigned l=region->length-region->length_read;
1631
1632         if(l > sizeof C.literal_data_body.data)
1633             l=sizeof C.literal_data_body.data;
1634
1635         if(!ops_limited_read(C.literal_data_body.data,l,region,parse_info))
1636             return 0;
1637
1638         C.literal_data_body.length=l;
1639
1640         CB(OPS_PTAG_CT_LITERAL_DATA_BODY,&content);
1641         }
1642
1643     return 1;
1644     }
1645
1646 /**
1647  * \ingroup Memory
1648  *
1649  * ops_secret_key_free() frees the memory associated with "key". Note that
1650  * the key itself is not freed.
1651  *
1652  * \param key
1653  */
1654
1655 void ops_secret_key_free(ops_secret_key_t *key)
1656     {
1657     switch(key->public_key.algorithm)
1658         {
1659     case OPS_PKA_RSA:
1660     case OPS_PKA_RSA_ENCRYPT_ONLY:
1661     case OPS_PKA_RSA_SIGN_ONLY:
1662         free_BN(&key->key.rsa.d);
1663         free_BN(&key->key.rsa.p);
1664         free_BN(&key->key.rsa.q);
1665         free_BN(&key->key.rsa.u);
1666         break;
1667
1668     default:
1669         assert(0);
1670         }
1671
1672     ops_public_key_free(&key->public_key);
1673     }
1674
1675 static int parse_secret_key(ops_region_t *region,ops_parse_info_t *parse_info)
1676     {
1677     ops_parser_content_t content;
1678     unsigned char c[1];
1679
1680     if(!parse_public_key_data(&C.secret_key.public_key,region,parse_info))
1681         return 0;
1682     if(!ops_limited_read(c,1,region,parse_info))
1683         return 0;
1684     C.secret_key.s2k_usage=c[0];
1685     assert(C.secret_key.s2k_usage == 0);
1686
1687     switch(C.secret_key.public_key.algorithm)
1688         {
1689     case OPS_PKA_RSA:
1690     case OPS_PKA_RSA_ENCRYPT_ONLY:
1691     case OPS_PKA_RSA_SIGN_ONLY:
1692         if(!limited_read_mpi(&C.secret_key.key.rsa.d,region,parse_info)
1693            || !limited_read_mpi(&C.secret_key.key.rsa.p,region,parse_info)
1694            || !limited_read_mpi(&C.secret_key.key.rsa.q,region,parse_info)
1695            || !limited_read_mpi(&C.secret_key.key.rsa.u,region,parse_info))
1696             return 0;
1697         break;
1698
1699     default:
1700         assert(0);
1701         }
1702
1703     if(!limited_read_scalar(&C.secret_key.checksum,2,region,parse_info))
1704         return 0;
1705     // XXX: check the checksum
1706
1707     CB(OPS_PTAG_CT_SECRET_KEY,&content);
1708
1709     return 1;
1710     }
1711
1712 /** Parse one packet.
1713  *
1714  * This function parses the packet tag.  It computes the value of the
1715  * content tag and then calls the appropriate function to handle the
1716  * content.
1717  *
1718  * \param *parse_info   How to parse
1719  * \param *pktlen       On return, will contain number of bytes in packet
1720  * \return 1 on success, 0 on error, -1 on EOF */
1721 static int ops_parse_one_packet(ops_parse_info_t *parse_info,unsigned long *pktlen)
1722     {
1723     unsigned char ptag[1];
1724     ops_reader_ret_t ret;
1725     ops_parser_content_t content;
1726     int r;
1727     ops_region_t region;
1728     unsigned one=1;
1729     ops_boolean_t indeterminate=ops_false;
1730
1731     C.ptag.position=parse_info->position;
1732
1733     ret=base_read(ptag,&one,0,parse_info);
1734     if(ret == OPS_R_EOF || ret == OPS_R_EARLY_EOF)
1735         return -1;
1736
1737     *pktlen=0;
1738
1739     assert(ret == OPS_R_OK);
1740     if(!(*ptag&OPS_PTAG_ALWAYS_SET))
1741         {
1742         C.error.error="Format error (ptag bit not set)";
1743         CB(OPS_PARSER_ERROR,&content);
1744         return 0;
1745         }
1746     C.ptag.new_format=!!(*ptag&OPS_PTAG_NEW_FORMAT);
1747     if(C.ptag.new_format)
1748         {
1749         C.ptag.content_tag=*ptag&OPS_PTAG_NF_CONTENT_TAG_MASK;
1750         C.ptag.length_type=0;
1751         if(!read_new_length(&C.ptag.length,parse_info))
1752             return 0;
1753
1754         }
1755     else
1756         {
1757         C.ptag.content_tag=(*ptag&OPS_PTAG_OF_CONTENT_TAG_MASK)
1758             >> OPS_PTAG_OF_CONTENT_TAG_SHIFT;
1759         C.ptag.length_type=*ptag&OPS_PTAG_OF_LENGTH_TYPE_MASK;
1760         switch(C.ptag.length_type)
1761             {
1762         case OPS_PTAG_OF_LT_ONE_BYTE:
1763             ret=read_scalar(&C.ptag.length,1,parse_info);
1764             break;
1765
1766         case OPS_PTAG_OF_LT_TWO_BYTE:
1767             ret=read_scalar(&C.ptag.length,2,parse_info);
1768             break;
1769
1770         case OPS_PTAG_OF_LT_FOUR_BYTE:
1771             ret=read_scalar(&C.ptag.length,4,parse_info);
1772             break;
1773
1774         case OPS_PTAG_OF_LT_INDETERMINATE:
1775             C.ptag.length=0;
1776             indeterminate=ops_true;
1777             ret=OPS_R_OK;
1778             break;
1779             }
1780         if(ret == OPS_R_EOF || ret == OPS_R_EARLY_EOF)
1781             return -1;
1782         }
1783
1784     CB(OPS_PARSER_PTAG,&content);
1785
1786     ops_init_subregion(&region,NULL);
1787     region.length=C.ptag.length;
1788     region.indeterminate=indeterminate;
1789     switch(C.ptag.content_tag)
1790         {
1791     case OPS_PTAG_CT_SIGNATURE:
1792         r=parse_signature(&region,parse_info);
1793         break;
1794
1795     case OPS_PTAG_CT_PUBLIC_KEY:
1796     case OPS_PTAG_CT_PUBLIC_SUBKEY:
1797         r=parse_public_key(C.ptag.content_tag,&region,parse_info);
1798         break;
1799
1800     case OPS_PTAG_CT_TRUST:
1801         r=parse_trust(&region, parse_info);
1802         break;
1803      
1804     case OPS_PTAG_CT_USER_ID:
1805         r=parse_user_id(&region,parse_info);
1806         break;
1807
1808     case OPS_PTAG_CT_COMPRESSED:
1809         r=parse_compressed(&region,parse_info);
1810         break;
1811
1812     case OPS_PTAG_CT_ONE_PASS_SIGNATURE:
1813         r=parse_one_pass(&region,parse_info);
1814         break;
1815
1816     case OPS_PTAG_CT_LITERAL_DATA:
1817         r=parse_literal_data(&region,parse_info);
1818         break;
1819
1820     case OPS_PTAG_CT_USER_ATTRIBUTE:
1821         r=parse_user_attribute(&region,parse_info);
1822         break;
1823
1824     case OPS_PTAG_CT_SECRET_KEY:
1825         r=parse_secret_key(&region,parse_info);
1826         break;
1827
1828     default:
1829         format_error(&content,"Format error (unknown content tag %d)",
1830                      C.ptag.content_tag);
1831         CB(OPS_PARSER_ERROR,&content);
1832         r=0;
1833         }
1834
1835     /* Ensure that the entire packet has been consumed (so long as
1836        there haven't been errors) */
1837
1838     if(region.length != region.length_read && r)
1839         {
1840         ops_data_t remainder;
1841
1842         if (read_data(&remainder,&region,parse_info))
1843             {
1844             /* now throw it away */
1845             data_free(&remainder);
1846             WARN("Remainder of packet consumed and discarded.");
1847             }
1848         else
1849             WARN("Problem consuming remainder of error packet.");
1850         }
1851
1852     /* set pktlen */
1853
1854     *pktlen=parse_info->alength;
1855
1856     /* do callback on entire packet, if desired */
1857
1858     if(parse_info->accumulate)
1859         {
1860         C.packet.length=parse_info->alength;
1861         C.packet.raw=parse_info->accumulated;
1862         parse_info->accumulated=NULL;
1863         parse_info->asize=0;
1864         CB(OPS_PARSER_PACKET_END,&content);
1865         }
1866     parse_info->alength=0;
1867        
1868     return r ? 1 : 0;
1869     }
1870
1871 /**
1872  * \ingroup Parse
1873  *
1874  * ops_parse() parses packets from an input stream until EOF or error.
1875  *
1876  * All the necessary information for parsing should have been set up by the
1877  * calling function in "*parse_info" beforehand.
1878  *
1879  * That information includes :
1880  *
1881  * - a "reader" function to be used to get the data to be parsed
1882  *
1883  * - a "callback" function to be called when this library has identified
1884  * a parseable object within the data
1885  *
1886  * - whether the calling function wants the signature subpackets returned raw, parsed or not at all.
1887  *
1888  * \sa See Detailed Description for usage.
1889  *
1890  * \param *parse_info   How to parse
1891  * \return              1 on success in all packets, 0 on error in any packet
1892  * \todo Add some error checking to make sure *parse_info contains a sensible setup?
1893  */
1894
1895 int ops_parse(ops_parse_info_t *parse_info)
1896     {
1897     int rtn;
1898     ops_ulong_list_t errors;
1899
1900     ops_ulong_list_init(&errors);
1901     rtn=ops_parse_and_save_errs(parse_info,&errors);
1902     ops_ulong_list_free(&errors);
1903     return rtn;
1904     }
1905
1906 int ops_parse_and_save_errs(ops_parse_info_t *parse_info, ops_ulong_list_t *errors)
1907     {
1908     int r;
1909     unsigned long pktlen;
1910     unsigned long offset=0;
1911
1912     do
1913         {
1914         r=ops_parse_one_packet(parse_info,&pktlen);
1915         if (!r)
1916             ops_ulong_list_add(errors,&offset);
1917         offset+=pktlen;
1918         } while (r!=-1);
1919
1920     return errors->used ? 0 : 1;
1921     }
1922
1923 /**
1924  *
1925  * \return 1 if success, 0 otherwise
1926  */
1927
1928 int ops_parse_errs(ops_parse_info_t *parse_info, ops_ulong_list_t *errs)
1929     {
1930     unsigned err;
1931     int r;
1932     unsigned long pktlen;
1933     ops_reader_fd_arg_t *arg;
1934     int orig_acc;
1935
1936     /* can only handle ops_reader_fd for now */
1937
1938     if (parse_info->reader != ops_reader_fd)
1939         {
1940         fprintf(stderr,"ops_parse_errs: can only handle ops_reader_fd\n");
1941         return 0;
1942         }
1943
1944     arg=parse_info->reader_arg;
1945
1946     /* store current state of accumulate flag */
1947
1948     orig_acc=parse_info->accumulate;
1949
1950     /* set accumulate flag */
1951
1952     parse_info->accumulate=1;
1953
1954     /* now parse each error in turn. */
1955
1956     for(err=0; err < errs->used ; err++)
1957         {
1958
1959         //      printf("\n***\n*** Error at offset %lu \n***\n",errs->ulongs[err]);
1960
1961         /* move stream to offset of error */
1962
1963         r=lseek(arg->fd,errs->ulongs[err],SEEK_SET);
1964         if (r==-1)
1965             {
1966             printf("error %d in first lseek to offset\n", errno);
1967             return 0;
1968             }
1969
1970         /* parse packet */
1971
1972         ops_parse_one_packet(parse_info,&pktlen);
1973
1974         }
1975
1976     /* restore accumulate flag original value */
1977     parse_info->accumulate=orig_acc;
1978
1979     return 1;
1980     }
1981
1982 /**
1983  * \ingroup Parse
1984  *
1985  * ops_parse_options() specifies whether one or more signature
1986  * subpacket types should be returned parsed or raw or ignored.
1987  *
1988  * \param       parse_info      Pointer to previously allocated structure
1989  * \param       tag     Packet tag. OPS_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
1990  * \param       type    Parse type
1991  * \todo XXX: Make all packet types optional, not just subpackets */
1992 void ops_parse_options(ops_parse_info_t *parse_info,
1993                        ops_content_tag_t tag,
1994                        ops_parse_type_t type)
1995     {
1996     int t8,t7;
1997
1998     if(tag == OPS_PTAG_SS_ALL)
1999         {
2000         int n;
2001
2002         for(n=0 ; n < 256 ; ++n)
2003             ops_parse_options(parse_info,OPS_PTAG_SIGNATURE_SUBPACKET_BASE+n,
2004                               type);
2005         return;
2006         }
2007
2008     assert(tag >= OPS_PTAG_SIGNATURE_SUBPACKET_BASE
2009            && tag <= OPS_PTAG_SIGNATURE_SUBPACKET_BASE+255);
2010     t8=(tag-OPS_PTAG_SIGNATURE_SUBPACKET_BASE)/8;
2011     t7=1 << ((tag-OPS_PTAG_SIGNATURE_SUBPACKET_BASE)&7);
2012     switch(type)
2013         {
2014     case OPS_PARSE_RAW:
2015         parse_info->ss_raw[t8] |= t7;
2016         parse_info->ss_parsed[t8] &= ~t7;
2017         break;
2018
2019     case OPS_PARSE_PARSED:
2020         parse_info->ss_raw[t8] &= ~t7;
2021         parse_info->ss_parsed[t8] |= t7;
2022         break;
2023
2024     case OPS_PARSE_IGNORE:
2025         parse_info->ss_raw[t8] &= ~t7;
2026         parse_info->ss_parsed[t8] &= ~t7;
2027         break;
2028         }
2029     }
2030
2031
2032 /* vim:set textwidth=120: */
2033 /* vim:set ts=8: */
Note: See TracBrowser for help on using the browser.