Coverage Report

Created: 2026-01-10 07:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/packet.h
Line
Count
Source
1
/* packet.h - OpenPGP packet definitions
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3
 *               2007 Free Software Foundation, Inc.
4
 * Copyright (C) 2015 g10 Code GmbH
5
 *
6
 * This file is part of GnuPG.
7
 *
8
 * GnuPG is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * GnuPG is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
#ifndef G10_PACKET_H
23
#define G10_PACKET_H
24
25
#include "../common/types.h"
26
#include "../common/iobuf.h"
27
#include "../common/strlist.h"
28
#include "dek.h"
29
#include "filter.h"
30
#include "../common/openpgpdefs.h"
31
#include "../common/userids.h"
32
#include "../common/util.h"
33
34
#define DEBUG_PARSE_PACKET 1
35
36
/* Maximum length of packets to avoid excessive memory allocation.  */
37
960k
#define MAX_KEY_PACKET_LENGTH     (256 * 1024)
38
50.5k
#define MAX_UID_PACKET_LENGTH     (  2 * 1024)
39
6.66k
#define MAX_COMMENT_PACKET_LENGTH ( 64 * 1024)
40
12.0k
#define MAX_ATTR_PACKET_LENGTH    ( 16 * 1024*1024)
41
42
/* Constants to allocate static MPI arrays.  */
43
#define PUBKEY_MAX_NPKEY  OPENPGP_MAX_NPKEY
44
40.0k
#define PUBKEY_MAX_NSKEY  OPENPGP_MAX_NSKEY
45
#define PUBKEY_MAX_NSIG   OPENPGP_MAX_NSIG
46
0
#define PUBKEY_MAX_NENC   OPENPGP_MAX_NENC
47
48
/* Usage flags */
49
288k
#define PUBKEY_USAGE_SIG     GCRY_PK_USAGE_SIGN  /* Good for signatures. */
50
509k
#define PUBKEY_USAGE_ENC     GCRY_PK_USAGE_ENCR  /* Good for encryption. */
51
298k
#define PUBKEY_USAGE_CERT    GCRY_PK_USAGE_CERT  /* Also good to certify keys.*/
52
8.60k
#define PUBKEY_USAGE_AUTH    GCRY_PK_USAGE_AUTH  /* Good for authentication. */
53
0
#define PUBKEY_USAGE_UNKNOWN GCRY_PK_USAGE_UNKN  /* Unknown usage flag. */
54
0
#define PUBKEY_USAGE_NONE    256                 /* No usage given. */
55
#if  (GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR | GCRY_PK_USAGE_CERT \
56
      | GCRY_PK_USAGE_AUTH | GCRY_PK_USAGE_UNKN) >= 256
57
# error Please choose another value for PUBKEY_USAGE_NONE
58
#endif
59
251k
#define PUBKEY_USAGE_GROUP   512                 /* Group flag.  */
60
253k
#define PUBKEY_USAGE_RENC    1024                /* Restricted encryption.  */
61
0
#define PUBKEY_USAGE_TIME    2048                /* Timestamp use.  */
62
63
4.57k
#define PUBKEY_USAGE_VERIFY  16384               /* Verify only modifier.  */
64
65
/* The usage bits which can be derived from the algo.  */
66
3.38k
#define PUBKEY_USAGE_BASIC_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC\
67
3.38k
                                  |PUBKEY_USAGE_CERT|PUBKEY_USAGE_AUTH)
68
69
/* The usage bits which define encryption.  */
70
0
#define PUBKEY_USAGE_XENC_MASK  (PUBKEY_USAGE_ENC | PUBKEY_USAGE_RENC)
71
72
/* The signature classes.  */
73
#define SIGCLASS_DATA    0x00   /* Signature on a binary document.       */
74
#define SIGCLASS_TEXT    0x01   /* Signature on a text document.         */
75
#define SIGCLASS_SALONE  0x02   /* Standalone signature.                 */
76
3.01M
#define SIGCLASS_CERT    0x10   /* User ID certification signature.      */
77
#define SIGCLASS_CERT11  0x11   /* User ID certification signature.      */
78
#define SIGCLASS_CERT12  0x12   /* User ID certification signature.      */
79
#define SIGCLASS_CERT13  0x13   /* User ID certification signature.      */
80
976k
#define SIGCLASS_SUBKEY  0x18   /* Key binding signature.                */
81
636k
#define SIGCLASS_BACKSIG 0x19   /* Primary key binding signature.        */
82
560k
#define SIGCLASS_KEY     0x1f   /* Direct key signature (on primary key) */
83
465k
#define SIGCLASS_KEYREV  0x20   /* Key revoction signature.              */
84
757k
#define SIGCLASS_SUBREV  0x28   /* Subkey revocation signature.          */
85
187k
#define SIGCLASS_CERTREV 0x30   /* Certification revocation signature.   */
86
87
/* Bitflags to convey hints on what kind of signature is created.  */
88
0
#define SIGNHINT_KEYSIG  1
89
0
#define SIGNHINT_SELFSIG 2
90
0
#define SIGNHINT_ADSK    4
91
92
93
/* Helper macros.  */
94
12.7M
#define is_RSA(a)     ((a)==PUBKEY_ALGO_RSA || (a)==PUBKEY_ALGO_RSA_E \
95
12.7M
           || (a)==PUBKEY_ALGO_RSA_S )
96
0
#define is_ELGAMAL(a) ((a)==PUBKEY_ALGO_ELGAMAL_E)
97
0
#define is_DSA(a)     ((a)==PUBKEY_ALGO_DSA)
98
99
/* A pointer to the packet object.  */
100
typedef struct packet_struct PACKET;
101
102
/* PKT_GPG_CONTROL types */
103
typedef enum {
104
    CTRLPKT_CLEARSIGN_START = 1,
105
    CTRLPKT_PIPEMODE = 2,
106
    CTRLPKT_PLAINTEXT_MARK =3
107
} ctrlpkttype_t;
108
109
typedef enum {
110
    PREFTYPE_NONE = 0,
111
    PREFTYPE_SYM = 1,
112
    PREFTYPE_HASH = 2,
113
    PREFTYPE_ZIP = 3,
114
    PREFTYPE_AEAD = 4
115
} preftype_t;
116
117
typedef struct {
118
    byte type;
119
    byte value;
120
} prefitem_t;
121
122
/* A string-to-key specifier as defined in RFC 4880, Section 3.7.  */
123
typedef struct
124
{
125
  int  mode;      /* Must be an integer due to the GNU modes 1001 et al.  */
126
  byte hash_algo;
127
  byte salt[8];
128
  /* The *coded* (i.e., the serialized version) iteration count.  */
129
  u32  count;
130
} STRING2KEY;
131
132
/* A symmetric-key encrypted session key packet as defined in RFC
133
   4880, Section 5.3.  All fields are serialized.  */
134
typedef struct {
135
  /* We support version 4 (rfc4880) and 5 (rfc4880bis).  */
136
  byte version;
137
  /* The cipher algorithm used to encrypt the session key.  Note that
138
   * this may be different from the algorithm that is used to encrypt
139
   * bulk data.  */
140
  byte cipher_algo;
141
  /* The AEAD algorithm or 0 for CFB encryption.  */
142
  byte aead_algo;
143
  /* The string-to-key specifier.  */
144
  STRING2KEY s2k;
145
  /* The length of SESKEY in bytes or 0 if this packet does not
146
     encrypt a session key.  (In the latter case, the results of the
147
     S2K function on the password is the session key. See RFC 4880,
148
     Section 5.3.)  */
149
  byte seskeylen;
150
  /* The malloced session key as encrypted by the S2K specifier.  For
151
   * AEAD this includes the nonce and the authentication tag.  */
152
  byte *seskey;
153
} PKT_symkey_enc;
154
155
/* A public-key encrypted session key packet as defined in RFC 4880,
156
   Section 5.1.  All fields are serialized.  */
157
typedef struct {
158
  /* The 64-bit keyid.  */
159
  u32     keyid[2];
160
  /* The packet's version.  Currently, only version 3 is defined.  */
161
  byte    version;
162
  /* The algorithm used for the public key encryption scheme.  */
163
  byte    pubkey_algo;
164
  /* The session key algorithm used by some pubkey algos.  */
165
  byte    seskey_algo;
166
  /* Whether to hide the key id.  This value is not directly
167
     serialized.  */
168
  byte    throw_keyid;
169
  /* The encrypted session key.  */
170
  gcry_mpi_t     data[PUBKEY_MAX_NENC];
171
} PKT_pubkey_enc;
172
173
174
/* An object to build a list of public-key and symkey encrypted
175
 * session key.  Note that we use a dedicated union here instead of
176
 * the usual PACKET type to avoid the need for extra allocations. */
177
struct seskey_enc_list
178
{
179
  struct seskey_enc_list *next;
180
  int result; /* The error code decrypting the session key.  */
181
  int u_sym;  /* Use the sym member.  */
182
  union {
183
    PKT_pubkey_enc pub;
184
    PKT_symkey_enc sym;
185
  } u;
186
};
187
188
189
/* An object to record some properties of a PKT_pubkey_enc packet.  */
190
struct pubkey_enc_info_item
191
{
192
  struct pubkey_enc_info_item *next;
193
  /* 3 fields copied from a PKT_pubkey_enc:  */
194
  u32     keyid[2];
195
  byte    version;
196
  byte    pubkey_algo;
197
};
198
199
200
/* A one-pass signature packet as defined in RFC 4880, Section
201
   5.4.  All fields are serialized.  */
202
typedef struct {
203
    u32     keyid[2];     /* The 64-bit keyid */
204
    /* The signature's classification (RFC 4880, Section 5.2.1).  */
205
    byte    sig_class;
206
    byte    digest_algo;    /* algorithm used for digest */
207
    byte    pubkey_algo;    /* algorithm used for public key scheme */
208
    /* A message can be signed by multiple keys.  In this case, there
209
       are n one-pass signature packets before the message to sign and
210
       n signatures packets after the message.  It is conceivable that
211
       someone wants to not only sign the message, but all of the
212
       signatures.  Now we need to distinguish between signing the
213
       message and signing the message plus the surrounding
214
       signatures.  This is the point of this flag.  If set, it means:
215
       I sign all of the data starting at the next packet.  */
216
    byte    last;
217
} PKT_onepass_sig;
218
219
220
/* A v4 OpenPGP signature has a hashed and unhashed area containing
221
   co-called signature subpackets (RFC 4880, Section 5.2.3).  These
222
   areas are described by this data structure.  Use enum_sig_subpkt to
223
   parse this area.  */
224
typedef struct {
225
    size_t size;  /* allocated */
226
    size_t len;   /* used (serialized) */
227
    byte data[1]; /* the serialized subpackes (serialized) */
228
} subpktarea_t;
229
230
/* The in-memory representation of a designated revoker signature
231
   subpacket (RFC 4880, Section 5.2.3.15).  */
232
struct revocation_key {
233
  /* A bit field.  0x80 must be set.  0x40 means this information is
234
     sensitive (and should not be uploaded to a keyserver by
235
     default).  */
236
  byte class;
237
  /* The public-key algorithm ID.  */
238
  byte algid;
239
  /* The length of the fingerprint.  */
240
  byte fprlen;
241
  /* The fingerprint of the authorized key.  */
242
  byte fpr[MAX_FINGERPRINT_LEN];
243
};
244
245
246
/* A signature packet (RFC 4880, Section 5.2).  Only a subset of these
247
   fields are directly serialized (these are marked as such); the rest
248
   are read from the subpackets, which are not synthesized when
249
   serializing this data structure (i.e., when using build_packet()).
250
   Instead, the subpackets must be created by hand.  */
251
typedef struct
252
{
253
  struct
254
  {
255
    unsigned checked:1;         /* Signature has been checked. */
256
    unsigned valid:1;           /* Signature is good (if checked is set). */
257
    unsigned chosen_selfsig:1;  /* A selfsig that is the chosen one. */
258
    unsigned unknown_critical:1;
259
    unsigned exportable:1;
260
    unsigned revocable:1;
261
    unsigned policy_url:1;  /* At least one policy URL is present */
262
    unsigned notation:1;    /* At least one notation is present */
263
    unsigned pref_ks:1;     /* At least one preferred keyserver is present */
264
    unsigned key_block:1;   /* A key block subpacket is present.  */
265
    unsigned expired:1;
266
  } flags;
267
  /* The key that allegedly generated this signature.  (Directly
268
     serialized in v3 sigs; for v4 sigs, this must be explicitly added
269
     as an issuer subpacket (5.2.3.5.)  */
270
  u32     keyid[2];
271
  /* When the signature was made (seconds since the Epoch).  (Directly
272
     serialized in v3 sigs; for v4 sigs, this must be explicitly added
273
     as a signature creation time subpacket (5.2.3.4).)  */
274
  u32     timestamp;
275
  u32     expiredate;     /* Expires at this date or 0 if not at all. */
276
  /* The serialization format used / to use.  If 0, then defaults to
277
     version 3.  (Serialized.)  */
278
  byte    version;
279
  /* The signature type. (See RFC 4880, Section 5.2.1.)  */
280
  byte    sig_class;
281
  /* Algorithm used for public key scheme (e.g., PUBKEY_ALGO_RSA).
282
     (Serialized.)  */
283
  byte    pubkey_algo;
284
  /* Algorithm used for digest (e.g., DIGEST_ALGO_SHA1).
285
     (Serialized.)  */
286
  byte    digest_algo;
287
  byte    trust_depth;
288
  byte    trust_value;
289
  const byte *trust_regexp;
290
  struct revocation_key *revkey;
291
  int numrevkeys;
292
  int help_counter;          /* Used internally by some functions.  */
293
  char *signers_uid;         /* Malloced value of the SIGNERS_UID
294
                              * subpacket or NULL.  This string has
295
                              * already been sanitized.  */
296
  subpktarea_t *hashed;      /* All subpackets with hashed data (v4 only). */
297
  subpktarea_t *unhashed;    /* Ditto for unhashed data. */
298
  /* First 2 bytes of the digest.  (Serialized.  Note: this is not
299
     automatically filled in when serializing a signature!)  */
300
  byte digest_start[2];
301
  /* The signature.  (Serialized.)  */
302
  gcry_mpi_t  data[PUBKEY_MAX_NSIG];
303
  /* The message digest and its length (in bytes).  Note the maximum
304
     digest length is 512 bits (64 bytes).  If DIGEST_LEN is 0, then
305
     the digest's value has not been saved here.  */
306
  byte digest[512 / 8];
307
  int digest_len;
308
} PKT_signature;
309
310
2.16k
#define ATTRIB_IMAGE 1
311
312
/* This is the cooked form of attributes.  */
313
struct user_attribute {
314
  byte type;
315
  const byte *data;
316
  u32 len;
317
};
318
319
320
/* A user id (RFC 4880, Section 5.11) or a user attribute packet (RFC
321
   4880, Section 5.12).  Only a subset of these fields are directly
322
   serialized (these are marked as such); the rest are read from the
323
   self-signatures in merge_keys_and_selfsig()).  */
324
typedef struct
325
{
326
  int ref;              /* reference counter */
327
  /* The length of NAME.  */
328
  int len;
329
  struct user_attribute *attribs;
330
  int numattribs;
331
  /* If this is not NULL, the packet is a user attribute rather than a
332
     user id (See RFC 4880 5.12).  (Serialized.)  */
333
  byte *attrib_data;
334
  /* The length of ATTRIB_DATA.  */
335
  unsigned long attrib_len;
336
  byte *namehash;
337
  u16 help_key_usage;
338
  u32 help_key_expire;
339
  int help_full_count;
340
  int help_marginal_count;
341
  u32 expiredate;       /* expires at this date or 0 if not at all */
342
  prefitem_t *prefs;    /* list of preferences (may be NULL)*/
343
  u32 created;          /* according to the self-signature */
344
  u32 keyupdate;        /* From the ring trust packet.  */
345
  char *updateurl;      /* NULL or the URL of the last update origin.  */
346
  byte keyorg;          /* From the ring trust packet.  */
347
  byte selfsigversion;
348
  struct
349
  {
350
    unsigned int mdc:1;
351
    unsigned int aead:1;
352
    unsigned int ks_modify:1;
353
    unsigned int compacted:1;
354
    unsigned int primary:2; /* 2 if set via the primary flag, 1 if calculated */
355
                            /* Note that this flag is set in a
356
                             * keyblock at max for one User ID and for
357
                             * one User Attribute per keyblock.  */
358
    unsigned int revoked:1;
359
    unsigned int expired:1;
360
  } flags;
361
362
  char *mbox;   /* NULL or the result of mailbox_from_userid.  */
363
364
  /* The text contained in the user id packet, which is normally the
365
   * name and email address of the key holder (See RFC 4880 5.11).
366
   * (Serialized.). For convenience an extra Nul is always appended.  */
367
  char name[1];
368
} PKT_user_id;
369
370
371
372
struct revoke_info
373
{
374
  /* Revoked at this date */
375
  u32 date;
376
  /* The keyid of the revoking key (selfsig or designated revoker) */
377
  u32 keyid[2];
378
  /* A malloced string of len reason_comment_len with the raw reason
379
   * string or NULL if not given.  */
380
  char *reason_comment;
381
  size_t reason_comment_len;
382
  /* The algo of the revoking key */
383
  byte algo;
384
  /* The reason code. */
385
  byte reason_code;
386
  /* Whether the above reason fields are valid. */
387
  byte got_reason;
388
};
389
390
391
/* Information pertaining to secret keys. */
392
struct seckey_info
393
{
394
  unsigned int is_protected:1; /* The secret info is protected and must */
395
      /* be decrypted before use, the protected */
396
      /* MPIs are simply (void*) pointers to memory */
397
      /* and should never be passed to a mpi_xxx() */
398
  unsigned int sha1chk:1; /* SHA1 is used instead of a 16 bit checksum */
399
  u16 csum;   /* Checksum for old protection modes.  */
400
  byte algo;            /* Cipher used to protect the secret information. */
401
  STRING2KEY s2k;       /* S2K parameter.  */
402
  byte ivlen;           /* Used length of the IV.  */
403
  byte iv[16];          /* Initialization vector for CFB mode.  */
404
};
405
406
407
/****************
408
 * The in-memory representation of a public key (RFC 4880, Section
409
 * 5.5).  Note: this structure contains significantly more information
410
 * than is contained in an OpenPGP public key packet.  This
411
 * information is derived from the self-signed signatures (by
412
 * merge_keys_and_selfsig()) and is ignored when serializing the
413
 * packet.  The fields that are actually written out when serializing
414
 * this packet are marked as accordingly.
415
 *
416
 * We assume that secret keys have the same number of parameters as
417
 * the public key and that the public parameters are the first items
418
 * in the PKEY array.  Thus NPKEY is always less than NSKEY and it is
419
 * possible to compare the secret and public keys by comparing the
420
 * first NPKEY elements of the PKEY array.  Note that since GnuPG 2.1
421
 * we don't use secret keys anymore directly because they are managed
422
 * by gpg-agent.  However for parsing OpenPGP key files we need a way
423
 * to temporary store those secret keys.  We do this by putting them
424
 * into the public key structure and extending the PKEY field to NSKEY
425
 * elements; the extra secret key information are stored in the
426
 * SECKEY_INFO field.
427
 */
428
typedef struct
429
{
430
  /* When the key was created.  (Serialized.)  */
431
  u32     timestamp;
432
  u32     expiredate;     /* expires at this date or 0 if not at all */
433
  u32     max_expiredate; /* must not expire past this date */
434
  struct revoke_info revoked;
435
  /* An OpenPGP packet consists of a header and a body.  This is the
436
     size of the header.  If this is 0, an appropriate size is
437
     automatically chosen based on the size of the body.
438
     (Serialized.)  */
439
  byte    hdrbytes;
440
  /* The serialization format.  If 0, the default version (4) is used
441
     when serializing.  (Serialized.)  */
442
  byte    version;
443
  byte    selfsigversion; /* highest version of all of the self-sigs */
444
  byte    fprlen;         /* 0 or length of FPR.  */
445
  byte    pubkey_algo;    /* The public key algorithm.  (PGP format)  */
446
  u16     pubkey_usage;   /* carries the usage info.            */
447
  u16     req_usage;      /* hack to pass a request to getkey() */
448
  u32     has_expired;    /* set to the expiration date if expired */
449
  /* keyid of the primary key.  Never access this value directly.
450
     Instead, use pk_main_keyid().  */
451
  u32     main_keyid[2];
452
  /* keyid of this key.  Never access this value directly!  Instead,
453
     use pk_keyid().  */
454
  u32     keyid[2];
455
  /* Fingerprint of the key.  Only valid if FPRLEN is not 0.  */
456
  byte    fpr[MAX_FINGERPRINT_LEN];
457
  prefitem_t *prefs;      /* list of preferences (may be NULL) */
458
  struct
459
  {
460
    unsigned int mdc:1;           /* MDC feature set.  */
461
    unsigned int aead:1;          /* AEAD feature set.  */
462
    unsigned int disabled_valid:1;/* The next flag is valid.  */
463
    unsigned int disabled:1;      /* The key has been disabled.  */
464
    unsigned int primary:1;       /* This is a primary key.  */
465
    unsigned int revoked:2;       /* Key has been revoked.
466
                                     1 = revoked by the owner
467
                                     2 = revoked by designated revoker.  */
468
    unsigned int maybe_revoked:1; /* A designated revocation is
469
                                     present, but without the key to
470
                                     check it.  */
471
    unsigned int valid:1;         /* Key (especially subkey) is valid.  */
472
    unsigned int dont_cache:1;    /* Do not cache this key.  */
473
    unsigned int backsig:2;       /* 0=none, 1=bad, 2=good.  */
474
    unsigned int serialno_valid:1;/* SERIALNO below is valid.  */
475
    unsigned int exact:1;         /* Found via exact (!) search.  */
476
  } flags;
477
  PKT_user_id *user_id;   /* If != NULL: found by that uid. */
478
  struct revocation_key *revkey;
479
  int     numrevkeys;
480
  u32     trust_timestamp;
481
  byte    trust_depth;
482
  byte    trust_value;
483
  byte    keyorg;         /* From the ring trust packet.  */
484
  u32     keyupdate;      /* From the ring trust packet.  */
485
  char    *updateurl;     /* NULL or the URL of the last update origin.  */
486
  const byte *trust_regexp;
487
  char    *serialno;      /* Malloced hex string or NULL if it is
488
                             likely not on a card.  See also
489
                             flags.serialno_valid.  */
490
  /* If not NULL this malloced structure describes a secret key.
491
     (Serialized.)  */
492
  struct seckey_info *seckey_info;
493
  /* The public key.  Contains pubkey_get_npkey (pubkey_algo) +
494
     pubkey_get_nskey (pubkey_algo) MPIs.  (If pubkey_get_npkey
495
     returns 0, then the algorithm is not understood and the PKEY
496
     contains a single opaque MPI.)  (Serialized.)  */
497
  gcry_mpi_t  pkey[PUBKEY_MAX_NSKEY]; /* Right, NSKEY elements.  */
498
} PKT_public_key;
499
500
/* Evaluates as true if the pk is disabled, and false if it isn't.  If
501
   there is no disable value cached, fill one in. */
502
#define pk_is_disabled(a)                                       \
503
0
  (((a)->flags.disabled_valid)?                                 \
504
0
   ((a)->flags.disabled):(cache_disabled_value(ctrl,(a))))
505
506
507
typedef struct {
508
    int  len;     /* length of data */
509
    char data[1];
510
} PKT_comment;
511
512
/* A compression packet (RFC 4880, Section 5.6).  */
513
typedef struct {
514
  /* Not used.  */
515
  u32 len;
516
  /* Whether the serialized version of the packet used / should use
517
     the new format.  */
518
  byte  new_ctb;
519
  /* The compression algorithm.  */
520
  byte  algorithm;
521
  /* An iobuf holding the data to be decompressed.  (This is not used
522
     for compression!)  */
523
  iobuf_t buf;
524
} PKT_compressed;
525
526
/* A symmetrically encrypted data packet (RFC 4880, Section 5.7) or a
527
   symmetrically encrypted integrity protected data packet (Section
528
   5.13) */
529
typedef struct {
530
  /* Remaining length of encrypted data. */
531
  u32  len;
532
  /* When encrypting in CFB mode, the first block size bytes of data
533
   * are random data and the following 2 bytes are copies of the last
534
   * two bytes of the random data (RFC 4880, Section 5.7).  This
535
   * provides a simple check that the key is correct.  EXTRALEN is the
536
   * size of this extra data or, in AEAD mode, the length of the
537
   * headers and the tags.  This is used by build_packet when writing
538
   * out the packet's header. */
539
  int  extralen;
540
  /* Whether the serialized version of the packet used / should use
541
     the new format.  */
542
  byte new_ctb;
543
  /* Whether the packet has an indeterminate length (old format) or
544
     was encoded using partial body length headers (new format).
545
     Note: this is ignored when encrypting.  */
546
  byte is_partial;
547
  /* If 0, MDC is disabled.  Otherwise, the MDC method that was used
548
     (only DIGEST_ALGO_SHA1 has ever been defined).  */
549
  byte mdc_method;
550
  /* If 0, AEAD is not used.  Otherwise, the used AEAD algorithm.
551
   * MDC_METHOD (above) shall be zero if AEAD is used.  */
552
  byte aead_algo;
553
  /* The cipher algo for/from the AEAD packet.  0 for other encryption
554
   * packets. */
555
  byte cipher_algo;
556
  /* The chunk byte from the AEAD packet.  */
557
  byte chunkbyte;
558
559
  /* An iobuf holding the data to be decrypted.  (This is not used for
560
     encryption!)  */
561
  iobuf_t buf;
562
} PKT_encrypted;
563
564
typedef struct {
565
    byte hash[20];
566
} PKT_mdc;
567
568
569
/* Subtypes for the ring trust packet.  */
570
46.2M
#define RING_TRUST_SIG 0  /* The classical signature cache.  */
571
65.4M
#define RING_TRUST_KEY 1  /* A KEYORG on a primary key.      */
572
32.7M
#define RING_TRUST_UID 2  /* A KEYORG on a user id.          */
573
574
/* The local only ring trust packet which OpenPGP declares as
575
 * implementation defined.  GnuPG uses this to cache signature
576
 * verification status and since 2.1.18 also to convey information
577
 * about the origin of a key.  Note that this packet is not part
578
 * struct packet_struct because we use it only local in the packet
579
 * parser and builder. */
580
typedef struct {
581
  unsigned int trustval;
582
  unsigned int sigcache;
583
  unsigned char subtype; /* The subtype of this ring trust packet.   */
584
  unsigned char keyorg;  /* The origin of the key (KEYORG_*).        */
585
  u32 keyupdate;         /* The wall time the key was last updated.  */
586
  char *url;             /* NULL or the URL of the source.           */
587
} PKT_ring_trust;
588
589
590
/* A plaintext packet (see RFC 4880, 5.9).  */
591
typedef struct {
592
  /* The length of data in BUF or 0 if unknown.  */
593
  u32  len;
594
  /* A buffer containing the data stored in the packet's body.  */
595
  iobuf_t buf;
596
  byte new_ctb;
597
  byte is_partial;      /* partial length encoded */
598
  /* The data's formatting.  This is either 'b', 't', 'u', 'l' or '1'
599
     (however, the last two are deprecated).  */
600
  int mode;
601
  u32 timestamp;
602
  /* The name of the file.  This can be at most 255 characters long,
603
     since namelen is just a byte in the serialized format.  */
604
  int  namelen;
605
  char name[1];
606
} PKT_plaintext;
607
608
typedef struct {
609
    int  control;
610
    size_t datalen;
611
    char data[1];
612
} PKT_gpg_control;
613
614
/* combine all packets into a union */
615
struct packet_struct {
616
    pkttype_t pkttype;
617
    union {
618
  void *generic;
619
  PKT_symkey_enc  *symkey_enc;  /* PKT_SYMKEY_ENC */
620
  PKT_pubkey_enc  *pubkey_enc;  /* PKT_PUBKEY_ENC */
621
  PKT_onepass_sig *onepass_sig; /* PKT_ONEPASS_SIG */
622
  PKT_signature *signature; /* PKT_SIGNATURE */
623
  PKT_public_key  *public_key;  /* PKT_PUBLIC_[SUB]KEY */
624
  PKT_public_key  *secret_key;  /* PKT_SECRET_[SUB]KEY */
625
  PKT_comment *comment; /* PKT_COMMENT */
626
  PKT_user_id *user_id; /* PKT_USER_ID */
627
  PKT_compressed  *compressed;  /* PKT_COMPRESSED */
628
  PKT_encrypted *encrypted; /* PKT_ENCRYPTED[_MDC|_AEAD] */
629
  PKT_mdc   *mdc;   /* PKT_MDC */
630
  PKT_plaintext *plaintext; /* PKT_PLAINTEXT */
631
        PKT_gpg_control *gpg_control;   /* PKT_GPG_CONTROL */
632
    } pkt;
633
};
634
635
21.0M
#define init_packet(a) do { (a)->pkttype = 0;   \
636
21.0M
          (a)->pkt.generic = NULL;  \
637
21.0M
           } while(0)
638
639
640
/* A notation.  See RFC 4880, Section 5.2.3.16.  */
641
struct notation
642
{
643
  /* The notation's name.  */
644
  char *name;
645
  /* If the notation is human readable, then the value is stored here
646
     as a NUL-terminated string.  If it is not human readable a human
647
     readable approximation of the binary value _may_ be stored
648
     here.  */
649
  char *value;
650
  /* Sometimes we want to %-expand the value.  In these cases, we save
651
     that transformed value here.  */
652
  char *altvalue;
653
  /* If the notation is not human readable or the function does not
654
     want to distinguish that, then the value is stored here.  */
655
  unsigned char *bdat;
656
  /* The amount of data stored in BDAT.
657
658
     Note: if this is 0 and BDAT is NULL, this does not necessarily
659
     mean that the value is human readable.  It could be that we have
660
     a 0-length value.  To determine whether the notation is human
661
     readable, always check if VALUE is not NULL.  This works, because
662
     if a human-readable value has a length of 0, we will still
663
     allocate space for the NUL byte.  */
664
  size_t blen;
665
  struct
666
  {
667
    /* The notation is critical.  */
668
    unsigned int critical:1;
669
    /* The notation is human readable.  */
670
    unsigned int human:1;
671
    /* The notation should be deleted.  */
672
    unsigned int ignore:1;
673
  } flags;
674
675
  /* A field to facilitate creating a list of notations.  */
676
  struct notation *next;
677
};
678
typedef struct notation *notation_t;
679
680
/*-- mainproc.c --*/
681
void reset_literals_seen(void);
682
int proc_packets (ctrl_t ctrl, void *ctx, iobuf_t a );
683
int proc_signature_packets (ctrl_t ctrl, void *ctx, iobuf_t a,
684
          strlist_t signedfiles, const char *sigfile );
685
int proc_signature_packets_by_fd (ctrl_t ctrl, void *anchor, IOBUF a,
686
                                  gnupg_fd_t signed_data_fd);
687
gpg_error_t proc_encryption_packets (ctrl_t ctrl, void *ctx, iobuf_t a,
688
                                     DEK **r_dek,
689
                                     struct seskey_enc_list **r_list);
690
691
int list_packets( iobuf_t a );
692
693
const byte *issuer_fpr_raw (PKT_signature *sig, size_t *r_len);
694
char *issuer_fpr_string (PKT_signature *sig);
695
696
/*-- parse-packet.c --*/
697
698
699
void register_known_notation (const char *string);
700
701
/* Sets the packet list mode to MODE (i.e., whether we are dumping a
702
   packet or not).  Returns the current mode.  This allows for
703
   temporarily suspending dumping by doing the following:
704
705
     int saved_mode = set_packet_list_mode (0);
706
     ...
707
     set_packet_list_mode (saved_mode);
708
*/
709
int set_packet_list_mode( int mode );
710
711
712
/* A context used with parse_packet.  */
713
struct parse_packet_ctx_s
714
{
715
  iobuf_t inp;       /* The input stream with the packets.  */
716
  struct packet_struct last_pkt; /* The last parsed packet.  */
717
  int free_last_pkt; /* Indicates that LAST_PKT must be freed.  */
718
  int skip_meta;     /* Skip ring trust packets.  */
719
  int only_fookey_enc;  /* Stop if the packet is not {sym,pub}key_enc. */
720
  unsigned int n_parsed_packets;  /* Number of parsed packets.  */
721
  int last_ctb;      /* The last CTB read.  */
722
};
723
typedef struct parse_packet_ctx_s *parse_packet_ctx_t;
724
725
37.0k
#define init_parse_packet(a,i) do { \
726
37.0k
    (a)->inp = (i);                 \
727
37.0k
    (a)->last_pkt.pkttype = 0;      \
728
37.0k
    (a)->last_pkt.pkt.generic= NULL;\
729
37.0k
    (a)->free_last_pkt = 0;         \
730
37.0k
    (a)->skip_meta = 0;             \
731
37.0k
    (a)->only_fookey_enc = 0;       \
732
37.0k
    (a)->n_parsed_packets = 0;      \
733
37.0k
    (a)->last_ctb = 1;              \
734
37.0k
  } while (0)
735
736
37.0k
#define deinit_parse_packet(a) do { \
737
37.0k
    if ((a)->free_last_pkt)         \
738
37.0k
      free_packet (NULL, (a));      \
739
37.0k
  } while (0)
740
741
742
#if DEBUG_PARSE_PACKET
743
/* There are debug functions and should not be used directly.  */
744
int dbg_search_packet (parse_packet_ctx_t ctx, PACKET *pkt,
745
                       off_t *retpos, int with_uid,
746
                       const char* file, int lineno  );
747
int dbg_parse_packet (parse_packet_ctx_t ctx, PACKET *ret_pkt,
748
                      const char *file, int lineno);
749
int dbg_copy_all_packets( iobuf_t inp, iobuf_t out,
750
                          const char* file, int lineno  );
751
int dbg_copy_some_packets( iobuf_t inp, iobuf_t out, off_t stopoff,
752
                           const char* file, int lineno  );
753
int dbg_skip_some_packets( iobuf_t inp, unsigned n,
754
                           const char* file, int lineno );
755
#define search_packet( a,b,c,d )   \
756
0
             dbg_search_packet( (a), (b), (c), (d), __FILE__, __LINE__ )
757
#define parse_packet( a, b )  \
758
21.0M
       dbg_parse_packet( (a), (b), __FILE__, __LINE__ )
759
#define copy_all_packets( a,b )  \
760
0
             dbg_copy_all_packets((a),(b), __FILE__, __LINE__ )
761
#define copy_some_packets( a,b,c ) \
762
0
             dbg_copy_some_packets((a),(b),(c), __FILE__, __LINE__ )
763
#define skip_some_packets( a,b ) \
764
0
             dbg_skip_some_packets((a),(b), __FILE__, __LINE__ )
765
#else
766
/* Return the next valid OpenPGP packet in *PKT.  (This function will
767
 * skip any packets whose type is 0.)  CTX must have been setup prior to
768
 * calling this function.
769
 *
770
 * Returns 0 on success, -1 if EOF is reached, and an error code
771
 * otherwise.  In the case of an error, the packet in *PKT may be
772
 * partially constructed.  As such, even if there is an error, it is
773
 * necessary to free *PKT to avoid a resource leak.  To detect what
774
 * has been allocated, clear *PKT before calling this function.  */
775
int parse_packet (parse_packet_ctx_t ctx, PACKET *pkt);
776
777
/* Return the first OpenPGP packet in *PKT that contains a key (either
778
 * a public subkey, a public key, a secret subkey or a secret key) or,
779
 * if WITH_UID is set, a user id.
780
 *
781
 * Saves the position in the pipeline of the start of the returned
782
 * packet (according to iobuf_tell) in RETPOS, if it is not NULL.
783
 *
784
 * The return semantics are the same as parse_packet.  */
785
int search_packet (parse_packet_ctx_t ctx, PACKET *pkt,
786
                   off_t *retpos, int with_uid);
787
788
/* Copy all packets (except invalid packets, i.e., those with a type
789
 * of 0) from INP to OUT until either an error occurs or EOF is
790
 * reached.
791
 *
792
 * Returns -1 when end of file is reached or an error code, if an
793
 * error occurred.  (Note: this function never returns 0, because it
794
 * effectively keeps going until it gets an EOF.)  */
795
int copy_all_packets (iobuf_t inp, iobuf_t out );
796
797
/* Like copy_all_packets, but stops at the first packet that starts at
798
 * or after STOPOFF (as indicated by iobuf_tell).
799
 *
800
 * Example: if STOPOFF is 100, the first packet in INP goes from
801
 * 0 to 110 and the next packet starts at offset 111, then the packet
802
 * starting at offset 0 will be completely processed (even though it
803
 * extends beyond STOPOFF) and the packet starting at offset 111 will
804
 * not be processed at all.  */
805
int copy_some_packets (iobuf_t inp, iobuf_t out, off_t stopoff);
806
807
/* Skips the next N packets from INP.
808
 *
809
 * If parsing a packet returns an error code, then the function stops
810
 * immediately and returns the error code.  Note: in the case of an
811
 * error, this function does not indicate how many packets were
812
 * successfully processed.  */
813
int skip_some_packets (iobuf_t inp, unsigned int n);
814
#endif
815
816
/* Parse a signature packet and store it in *SIG.
817
818
   The signature packet is read from INP.  The OpenPGP header (the tag
819
   and the packet's length) have already been read; the next byte read
820
   from INP should be the first byte of the packet's contents.  The
821
   packet's type (as extract from the tag) must be passed as PKTTYPE
822
   and the packet's length must be passed as PKTLEN.  This is used as
823
   the upper bound on the amount of data read from INP.  If the packet
824
   is shorter than PKTLEN, the data at the end will be silently
825
   skipped.  If an error occurs, an error code will be returned.  -1
826
   means the EOF was encountered.  0 means parsing was successful.  */
827
int parse_signature( iobuf_t inp, int pkttype, unsigned long pktlen,
828
         PKT_signature *sig );
829
830
/* Given a signature packet, either:
831
 *
832
 *   - test whether there are any subpackets with the critical bit set
833
 *     that we don't understand,
834
 *
835
 *   - list the subpackets, or,
836
 *
837
 *   - find a subpacket with a specific type.
838
 *
839
 * The WANT_HASHED flag indicates that the hashed area shall be
840
 * considered.
841
 *
842
 * REQTYPE indicates the type of operation.
843
 *
844
 * If REQTYPE is SIGSUBPKT_TEST_CRITICAL, then this function checks
845
 * whether there are any subpackets that have the critical bit and
846
 * which GnuPG cannot handle.  If GnuPG understands all subpackets
847
 * whose critical bit is set, then this function returns simply
848
 * returns SUBPKTS.  If there is a subpacket whose critical bit is set
849
 * and which GnuPG does not understand, then this function returns
850
 * NULL and, if START is not NULL, sets *START to the 1-based index of
851
 * the subpacket that violates the constraint.
852
 *
853
 * If REQTYPE is SIGSUBPKT_LIST_HASHED or SIGSUBPKT_LIST_UNHASHED, the
854
 * packets are dumped.  Note: if REQTYPE is SIGSUBPKT_LIST_HASHED,
855
 * this function does not check whether the hash is correct; this is
856
 * merely an indication of the section that the subpackets came from.
857
 *
858
 * If REQTYPE is anything else, then this function interprets the
859
 * values as a subpacket type and looks for the first subpacket with
860
 * that type.  If such a packet is found, *CRITICAL (if not NULL) is
861
 * set if the critical bit was set, *RET_N is set to the offset of the
862
 * subpacket's content within the SUBPKTS buffer, *START is set to the
863
 * 1-based index of the subpacket within the buffer, and returns
864
 * &SUBPKTS[*RET_N].
865
 *
866
 * *START is the number of initial subpackets to not consider.  Thus,
867
 * if *START is 2, then the first 2 subpackets are ignored.
868
 */
869
const byte *enum_sig_subpkt (PKT_signature *sig, int want_hashed,
870
                             sigsubpkttype_t reqtype,
871
                             size_t *ret_n, int *start, int *critical );
872
873
/* Shorthand for:
874
 *
875
 *    enum_sig_subpkt (sig, want_hashed, reqtype, ret_n, NULL, NULL);
876
 */
877
const byte *parse_sig_subpkt (PKT_signature *sig, int want_hashed,
878
                              sigsubpkttype_t reqtype,
879
                              size_t *ret_n );
880
881
/* This calls parse_sig_subpkt first on the hashed signature area in
882
 * SIG and then, if that returns NULL, calls parse_sig_subpkt on the
883
 * unhashed subpacket area in SIG.  */
884
const byte *parse_sig_subpkt2 (PKT_signature *sig, sigsubpkttype_t reqtype);
885
886
/* Returns whether the N byte large buffer BUFFER is sufficient to
887
   hold a subpacket of type TYPE.  Note: the buffer refers to the
888
   contents of the subpacket (not the header) and it must already be
889
   initialized: for some subpackets, it checks some internal
890
   constraints.
891
892
   Returns 0 if the size is acceptable.  Returns -2 if the buffer is
893
   definitely too short.  To check for an error, check whether the
894
   return value is less than 0.  */
895
int parse_one_sig_subpkt( const byte *buffer, size_t n, int type );
896
897
/* Looks for revocation key subpackets (see RFC 4880 5.2.3.15) in the
898
   hashed area of the signature packet.  Any that are found are added
899
   to SIG->REVKEY and SIG->NUMREVKEYS is updated appropriately.  */
900
void parse_revkeys(PKT_signature *sig);
901
902
/* Extract the attributes from the buffer at UID->ATTRIB_DATA and
903
   update UID->ATTRIBS and UID->NUMATTRIBS accordingly.  */
904
int parse_attribute_subpkts(PKT_user_id *uid);
905
906
/* Set the UID->NAME field according to the attributes.  MAX_NAMELEN
907
   must be at least 71.  */
908
void make_attribute_uidname(PKT_user_id *uid, size_t max_namelen);
909
910
/* Allocate and initialize a new GPG control packet.  DATA is the data
911
   to save in the packet.  */
912
PACKET *create_gpg_control ( ctrlpkttype_t type,
913
                             const byte *data,
914
                             size_t datalen );
915
916
/*-- build-packet.c --*/
917
gpg_error_t build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf);
918
int build_packet (iobuf_t out, PACKET *pkt);
919
gpg_error_t build_packet_and_meta (iobuf_t out, PACKET *pkt);
920
gpg_error_t gpg_mpi_write (iobuf_t out, gcry_mpi_t a, unsigned int *t_nwritten);
921
gpg_error_t gpg_mpi_write_opaque_nohdr (iobuf_t out, gcry_mpi_t a);
922
gpg_error_t gpg_mpi_write_opaque_32 (iobuf_t out, gcry_mpi_t a,
923
                                     unsigned int *r_nwritten);
924
u32 calc_packet_length( PACKET *pkt );
925
void build_sig_subpkt( PKT_signature *sig, sigsubpkttype_t type,
926
      const byte *buffer, size_t buflen );
927
void build_sig_subpkt_from_sig (PKT_signature *sig, PKT_public_key *pksk,
928
                                unsigned int signhints);
929
int  delete_sig_subpkt(subpktarea_t *buffer, sigsubpkttype_t type );
930
void build_attribute_subpkt(PKT_user_id *uid,byte type,
931
          const void *buf,u32 buflen,
932
          const void *header,u32 headerlen);
933
struct notation *string_to_notation(const char *string,int is_utf8);
934
struct notation *name_value_to_notation (const char *name, const char *value);
935
struct notation *blob_to_notation(const char *name,
936
                                  const char *data, size_t len);
937
struct notation *sig_to_notation(PKT_signature *sig);
938
struct notation *search_sig_notations (PKT_signature *sig, const char *name);
939
void free_notation (struct notation *notation);
940
941
/*-- free-packet.c --*/
942
void free_symkey_enc( PKT_symkey_enc *enc );
943
944
void release_pubkey_enc_parts (PKT_pubkey_enc *enc);
945
void free_pubkey_enc( PKT_pubkey_enc *enc );
946
void copy_pubkey_enc_parts (PKT_pubkey_enc *dst, PKT_pubkey_enc *src);
947
948
void free_seckey_enc( PKT_signature *enc );
949
950
void release_public_key_parts( PKT_public_key *pk );
951
void free_public_key( PKT_public_key *key );
952
953
void free_attributes(PKT_user_id *uid);
954
void free_user_id( PKT_user_id *uid );
955
void free_comment( PKT_comment *rem );
956
void free_packet (PACKET *pkt, parse_packet_ctx_t parsectx);
957
prefitem_t *copy_prefs (const prefitem_t *prefs);
958
959
PKT_public_key *copy_public_key_basics (PKT_public_key *d, PKT_public_key *s);
960
PKT_public_key *copy_public_key( PKT_public_key *d, PKT_public_key *s );
961
962
PKT_signature *copy_signature( PKT_signature *d, PKT_signature *s );
963
PKT_user_id *scopy_user_id (PKT_user_id *sd );
964
965
void free_seskey_enc_list (struct seskey_enc_list *sesenc_list);
966
967
int cmp_public_keys( PKT_public_key *a, PKT_public_key *b );
968
int cmp_signatures( PKT_signature *a, PKT_signature *b );
969
int cmp_user_ids( PKT_user_id *a, PKT_user_id *b );
970
971
972
/*-- sig-check.c --*/
973
/* Check a signature.  Looks up the public key from the key db.  (If
974
 * R_PK is not NULL, it is stored at RET_PK.)  DIGEST contains a
975
 * valid hash context that already includes the signed data.  This
976
 * function adds the relevant meta-data to the hash before finalizing
977
 * it and verifying the signature.  FOCRED_PK is usually NULL. */
978
gpg_error_t check_signature (ctrl_t ctrl,
979
                              PKT_signature *sig, gcry_md_hd_t digest,
980
                              const void *extrahash, size_t extrahashlen,
981
                              PKT_public_key *forced_pk,
982
                              u32 *r_expiredate, int *r_expired, int *r_revoked,
983
                             PKT_public_key **r_pk, kbnode_t *r_keyblock);
984
985
986
/*-- pubkey-enc.c --*/
987
gpg_error_t get_session_key (ctrl_t ctrl, struct seskey_enc_list *k, DEK *dek);
988
gpg_error_t get_override_session_key (DEK *dek, const char *string);
989
990
/*-- compress.c --*/
991
int handle_compressed (ctrl_t ctrl, void *ctx, PKT_compressed *cd,
992
           int (*callback)(iobuf_t, void *), void *passthru );
993
994
/*-- decrypt-data.c --*/
995
int decrypt_data (ctrl_t ctrl, void *ctx, PKT_encrypted *ed, DEK *dek,
996
                  int *compliance_error);
997
998
/*-- plaintext.c --*/
999
gpg_error_t get_output_file (const byte *embedded_name, int embedded_namelen,
1000
                             iobuf_t data, char **fnamep, estream_t *fpp);
1001
int handle_plaintext( PKT_plaintext *pt, md_filter_context_t *mfx,
1002
          int nooutput, int clearsig );
1003
int ask_for_detached_datafile( gcry_md_hd_t md, gcry_md_hd_t md2,
1004
             const char *inname, int textmode );
1005
1006
/*-- sign.c --*/
1007
int make_keysig_packet (ctrl_t ctrl,
1008
                        PKT_signature **ret_sig, PKT_public_key *pk,
1009
      PKT_user_id *uid, PKT_public_key *subpk,
1010
      PKT_public_key *pksk, int sigclass,
1011
      u32 timestamp, u32 duration,
1012
      int (*mksubpkt)(PKT_signature *, void *),
1013
      void *opaque,
1014
                        const char *cache_nonce);
1015
gpg_error_t update_keysig_packet (ctrl_t ctrl,
1016
                      PKT_signature **ret_sig,
1017
                      PKT_signature *orig_sig,
1018
                      PKT_public_key *pk,
1019
                      PKT_user_id *uid,
1020
                      PKT_public_key *subpk,
1021
                      PKT_public_key *pksk,
1022
                      int (*mksubpkt)(PKT_signature *, void *),
1023
                      void *opaque   );
1024
1025
/*-- keygen.c --*/
1026
PKT_user_id *generate_user_id (kbnode_t keyblock, const char *uidstr);
1027
1028
#endif /*G10_PACKET_H*/