Coverage Report

Created: 2026-01-10 07:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/build-packet.c
Line
Count
Source
1
/* build-packet.c - assemble packets and write them
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3
 *               2006, 2010, 2011  Free Software Foundation, Inc.
4
 *
5
 * This file is part of GnuPG.
6
 *
7
 * GnuPG is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * GnuPG is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
#include <config.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
#include <ctype.h>
26
27
#include "gpg.h"
28
#include "../common/util.h"
29
#include "packet.h"
30
#include "../common/status.h"
31
#include "../common/iobuf.h"
32
#include "../common/i18n.h"
33
#include "options.h"
34
#include "../common/host2net.h"
35
36
static gpg_error_t do_ring_trust (iobuf_t out, PKT_ring_trust *rt);
37
static int do_user_id( IOBUF out, int ctb, PKT_user_id *uid );
38
static int do_key (iobuf_t out, int ctb, PKT_public_key *pk);
39
static int do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc );
40
static int do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc );
41
static u32 calc_plaintext( PKT_plaintext *pt );
42
static int do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt );
43
static int do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed );
44
static int do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed );
45
static int do_encrypted_aead (iobuf_t out, int ctb, PKT_encrypted *ed);
46
static int do_compressed( IOBUF out, int ctb, PKT_compressed *cd );
47
static int do_signature( IOBUF out, int ctb, PKT_signature *sig );
48
static int do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops );
49
50
static int calc_header_length( u32 len, int new_ctb );
51
static int write_16(IOBUF inp, u16 a);
52
static int write_32(IOBUF inp, u32 a);
53
static int write_header( IOBUF out, int ctb, u32 len );
54
static int write_sign_packet_header( IOBUF out, int ctb, u32 len );
55
static int write_header2( IOBUF out, int ctb, u32 len, int hdrlen );
56
static int write_new_header( IOBUF out, int ctb, u32 len, int hdrlen );
57
58
/* Returns 1 if CTB is a new format ctb and 0 if CTB is an old format
59
   ctb.  */
60
static int
61
ctb_new_format_p (int ctb)
62
20.0M
{
63
  /* Bit 7 must always be set.  */
64
20.0M
  log_assert ((ctb & (1 << 7)));
65
  /* Bit 6 indicates whether the packet is a new format packet.  */
66
20.0M
  return (ctb & (1 << 6));
67
20.0M
}
68
69
/* Extract the packet type from a CTB.  */
70
static int
71
ctb_pkttype (int ctb)
72
6.97M
{
73
6.97M
  if (ctb_new_format_p (ctb))
74
    /* Bits 0 through 5 are the packet type.  */
75
0
    return (ctb & ((1 << 6) - 1));
76
6.97M
  else
77
    /* Bits 2 through 5 are the packet type.  */
78
6.97M
    return (ctb & ((1 << 6) - 1)) >> 2;
79
6.97M
}
80
81
82
/* Build a keyblock image from KEYBLOCK.  Returns 0 on success and
83
 * only then stores a new iobuf object at R_IOBUF; the returned iobuf
84
 * can be access with the iobuf_get_temp_buffer and
85
 * iobuf_get_temp_length macros.  */
86
gpg_error_t
87
build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf)
88
2.93k
{
89
2.93k
  gpg_error_t err;
90
2.93k
  iobuf_t iobuf;
91
2.93k
  kbnode_t kbctx, node;
92
93
2.93k
  *r_iobuf = NULL;
94
95
2.93k
  iobuf = iobuf_temp ();
96
6.68M
  for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
97
6.68M
    {
98
      /* Make sure to use only packets valid on a keyblock.  */
99
6.68M
      switch (node->pkt->pkttype)
100
6.68M
        {
101
2.93k
        case PKT_PUBLIC_KEY:
102
297k
        case PKT_PUBLIC_SUBKEY:
103
6.67M
        case PKT_SIGNATURE:
104
6.68M
        case PKT_USER_ID:
105
6.68M
        case PKT_ATTRIBUTE:
106
6.68M
        case PKT_RING_TRUST:
107
6.68M
          break;
108
0
        default:
109
0
          continue;
110
6.68M
        }
111
112
6.68M
      err = build_packet_and_meta (iobuf, node->pkt);
113
6.68M
      if (err)
114
0
        {
115
0
          iobuf_close (iobuf);
116
0
          return err;
117
0
        }
118
6.68M
    }
119
120
2.93k
  *r_iobuf = iobuf;
121
2.93k
  return 0;
122
2.93k
}
123
124
125
/* Build a packet and write it to the stream OUT.
126
 * Returns: 0 on success or on an error code.  */
127
int
128
build_packet (IOBUF out, PACKET *pkt)
129
6.68M
{
130
6.68M
  int rc = 0;
131
6.68M
  int new_ctb = 0;
132
6.68M
  int ctb, pkttype;
133
134
6.68M
  if (DBG_PACKET)
135
6.68M
    log_debug ("build_packet() type=%d\n", pkt->pkttype);
136
6.68M
  log_assert (pkt->pkt.generic);
137
138
6.68M
  switch ((pkttype = pkt->pkttype))
139
6.68M
    {
140
2.93k
    case PKT_PUBLIC_KEY:
141
2.93k
      if (pkt->pkt.public_key->seckey_info)
142
0
        pkttype = PKT_SECRET_KEY;
143
2.93k
      break;
144
294k
    case PKT_PUBLIC_SUBKEY:
145
294k
      if (pkt->pkt.public_key->seckey_info)
146
0
        pkttype = PKT_SECRET_SUBKEY;
147
294k
      break;
148
0
    case PKT_PLAINTEXT:
149
0
      new_ctb = pkt->pkt.plaintext->new_ctb;
150
0
      break;
151
0
    case PKT_ENCRYPTED:
152
0
    case PKT_ENCRYPTED_MDC:
153
0
    case PKT_ENCRYPTED_AEAD:
154
0
      new_ctb = pkt->pkt.encrypted->new_ctb;
155
0
      break;
156
0
    case PKT_COMPRESSED:
157
0
      new_ctb = pkt->pkt.compressed->new_ctb;
158
0
      break;
159
5.66k
    case PKT_USER_ID:
160
5.66k
      if (pkt->pkt.user_id->attrib_data)
161
0
        pkttype = PKT_ATTRIBUTE;
162
5.66k
      break;
163
6.37M
    default:
164
6.37M
      break;
165
6.68M
    }
166
167
6.68M
  if (new_ctb || pkttype > 15) /* new format */
168
0
    ctb = (0xc0 | (pkttype & 0x3f));
169
6.68M
  else
170
6.68M
    ctb = (0x80 | ((pkttype & 15)<<2));
171
6.68M
  switch (pkttype)
172
6.68M
    {
173
0
    case PKT_ATTRIBUTE:
174
5.66k
    case PKT_USER_ID:
175
5.66k
      rc = do_user_id (out, ctb, pkt->pkt.user_id);
176
5.66k
      break;
177
0
    case PKT_OLD_COMMENT:
178
0
    case PKT_COMMENT:
179
      /* Ignore these.  Theoretically, this will never be called as we
180
       * have no way to output comment packets any longer, but just in
181
       * case there is some code path that would end up outputting a
182
       * comment that was written before comments were dropped (in the
183
       * public key?) this is a no-op.  */
184
0
      break;
185
294k
    case PKT_PUBLIC_SUBKEY:
186
297k
    case PKT_PUBLIC_KEY:
187
297k
    case PKT_SECRET_SUBKEY:
188
297k
    case PKT_SECRET_KEY:
189
297k
      rc = do_key (out, ctb, pkt->pkt.public_key);
190
297k
      break;
191
0
    case PKT_SYMKEY_ENC:
192
0
      rc = do_symkey_enc (out, ctb, pkt->pkt.symkey_enc);
193
0
      break;
194
0
    case PKT_PUBKEY_ENC:
195
0
      rc = do_pubkey_enc (out, ctb, pkt->pkt.pubkey_enc);
196
0
      break;
197
0
    case PKT_PLAINTEXT:
198
0
      rc = do_plaintext (out, ctb, pkt->pkt.plaintext);
199
0
      break;
200
0
    case PKT_ENCRYPTED:
201
0
      rc = do_encrypted (out, ctb, pkt->pkt.encrypted);
202
0
      break;
203
0
    case PKT_ENCRYPTED_MDC:
204
0
      rc = do_encrypted_mdc (out, ctb, pkt->pkt.encrypted);
205
0
      break;
206
0
    case PKT_ENCRYPTED_AEAD:
207
0
      rc = do_encrypted_aead (out, ctb, pkt->pkt.encrypted);
208
0
      break;
209
0
    case PKT_COMPRESSED:
210
0
      rc = do_compressed (out, ctb, pkt->pkt.compressed);
211
0
      break;
212
6.37M
    case PKT_SIGNATURE:
213
6.37M
      rc = do_signature (out, ctb, pkt->pkt.signature);
214
6.37M
      break;
215
0
    case PKT_ONEPASS_SIG:
216
0
      rc = do_onepass_sig (out, ctb, pkt->pkt.onepass_sig);
217
0
      break;
218
0
    case PKT_RING_TRUST:
219
      /* Ignore it (only written by build_packet_and_meta)  */
220
0
      break;
221
0
    case PKT_MDC:
222
      /* We write it directly, so we should never see it here. */
223
0
    default:
224
0
      log_bug ("invalid packet type in build_packet()\n");
225
0
      break;
226
6.68M
    }
227
228
6.68M
  return rc;
229
6.68M
}
230
231
232
/* Build a packet and write it to the stream OUT.  This variant also
233
 * writes the meta data using ring trust packets.  Returns: 0 on
234
 * success or on error code.  */
235
gpg_error_t
236
build_packet_and_meta (iobuf_t out, PACKET *pkt)
237
6.68M
{
238
6.68M
  gpg_error_t err;
239
6.68M
  PKT_ring_trust rt = {0};
240
241
6.68M
  err = build_packet (out, pkt);
242
6.68M
  if (err)
243
0
    ;
244
6.68M
  else if (pkt->pkttype == PKT_SIGNATURE)
245
6.37M
    {
246
6.37M
      PKT_signature *sig = pkt->pkt.signature;
247
248
6.37M
      rt.subtype = RING_TRUST_SIG;
249
      /* Note: trustval is not yet used.  */
250
6.37M
      if (sig->flags.checked)
251
4.04M
        {
252
4.04M
          rt.sigcache = 1;
253
4.04M
          if (sig->flags.valid)
254
3.85M
            rt.sigcache |= 2;
255
4.04M
        }
256
6.37M
      err = do_ring_trust (out, &rt);
257
6.37M
    }
258
302k
  else if (pkt->pkttype == PKT_USER_ID
259
297k
           || pkt->pkttype == PKT_ATTRIBUTE)
260
5.66k
    {
261
5.66k
      PKT_user_id *uid = pkt->pkt.user_id;
262
263
5.66k
      rt.subtype = RING_TRUST_UID;
264
5.66k
      rt.keyorg = uid->keyorg;
265
5.66k
      rt.keyupdate = uid->keyupdate;
266
5.66k
      rt.url = uid->updateurl;
267
5.66k
      err = do_ring_trust (out, &rt);
268
5.66k
      rt.url = NULL;
269
5.66k
    }
270
297k
  else if (pkt->pkttype == PKT_PUBLIC_KEY
271
294k
           || pkt->pkttype == PKT_SECRET_KEY)
272
2.93k
    {
273
2.93k
      PKT_public_key *pk = pkt->pkt.public_key;
274
275
2.93k
      rt.subtype = RING_TRUST_KEY;
276
2.93k
      rt.keyorg = pk->keyorg;
277
2.93k
      rt.keyupdate = pk->keyupdate;
278
2.93k
      rt.url = pk->updateurl;
279
2.93k
      err = do_ring_trust (out, &rt);
280
2.93k
      rt.url = NULL;
281
282
2.93k
    }
283
284
6.68M
  return err;
285
6.68M
}
286
287
288
/*
289
 * Write the mpi A to OUT.  If R_NWRITTEN is not NULL the number of
290
 * bytes written is stored there.  To only get the number of bytes
291
 * which would be written NULL may be passed for OUT.
292
 */
293
gpg_error_t
294
gpg_mpi_write (iobuf_t out, gcry_mpi_t a, unsigned int *r_nwritten)
295
41.0k
{
296
41.0k
  gpg_error_t err;
297
41.0k
  unsigned int nwritten = 0;
298
299
41.0k
  if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
300
0
    {
301
0
      unsigned int nbits;
302
0
      const unsigned char *p;
303
0
      unsigned char lenhdr[2];
304
305
      /* gcry_log_debugmpi ("a", a); */
306
0
      p = gcry_mpi_get_opaque (a, &nbits);
307
0
      if (p)
308
0
        {
309
          /* First get nbits back to full bytes.  */
310
0
          nbits = ((nbits + 7) / 8) * 8;
311
          /* Then strip leading zero bits.  */
312
0
          for (; nbits >= 8 && !*p; p++, nbits -= 8)
313
0
            ;
314
0
          if (nbits >= 8 && !(*p & 0x80))
315
0
            if (--nbits >= 7 && !(*p & 0x40))
316
0
              if (--nbits >= 6 && !(*p & 0x20))
317
0
                if (--nbits >= 5 && !(*p & 0x10))
318
0
                  if (--nbits >= 4 && !(*p & 0x08))
319
0
                    if (--nbits >= 3 && !(*p & 0x04))
320
0
                      if (--nbits >= 2 && !(*p & 0x02))
321
0
                        if (--nbits >= 1 && !(*p & 0x01))
322
0
                          --nbits;
323
0
        }
324
      /* gcry_log_debug ("   [%u bit]\n", nbits); */
325
      /* gcry_log_debughex (" ", p, (nbits+7)/8); */
326
0
      lenhdr[0] = nbits >> 8;
327
0
      lenhdr[1] = nbits;
328
0
      err = out? iobuf_write (out, lenhdr, 2) : 0;
329
0
      if (!err)
330
0
        {
331
0
          nwritten += 2;
332
0
          if (p)
333
0
            {
334
0
              err = out? iobuf_write (out, p, (nbits+7)/8) : 0;
335
0
              if (!err)
336
0
                nwritten += (nbits+7)/8;
337
0
            }
338
0
        }
339
0
    }
340
41.0k
  else
341
41.0k
    {
342
41.0k
      char buffer[(MAX_EXTERN_MPI_BITS+7)/8+2]; /* 2 is for the mpi length. */
343
41.0k
      size_t nbytes;
344
345
41.0k
      nbytes = DIM(buffer);
346
41.0k
      err = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
347
41.0k
      if (!err)
348
41.0k
        {
349
41.0k
          err = out? iobuf_write (out, buffer, nbytes) : 0;
350
41.0k
          if (!err)
351
41.0k
            nwritten += nbytes;
352
41.0k
        }
353
0
      else if (gpg_err_code (err) == GPG_ERR_TOO_SHORT )
354
0
        {
355
0
          log_info ("mpi too large (%u bits)\n", gcry_mpi_get_nbits (a));
356
          /* The buffer was too small.  We better tell the user about
357
           * the MPI. */
358
0
          err = gpg_error (GPG_ERR_TOO_LARGE);
359
0
        }
360
41.0k
    }
361
362
41.0k
  if (r_nwritten)
363
0
    *r_nwritten = nwritten;
364
41.0k
  return err;
365
41.0k
}
366
367
368
/*
369
 * Write the mpi A to the output stream OUT as "SOS" (Strange Octet
370
 * String).  If R_NWRITTEN is not NULL the number of bytes written is
371
 * stored there.  To only get the number of bytes which would be
372
 * written, NULL may be passed for OUT.
373
 */
374
static gpg_error_t
375
sos_write (iobuf_t out, gcry_mpi_t a, unsigned int *r_nwritten)
376
12.8M
{
377
12.8M
  gpg_error_t err;
378
12.8M
  unsigned int nwritten = 0;
379
380
12.8M
  if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
381
12.8M
    {
382
12.8M
      unsigned int nbits;
383
12.8M
      const unsigned char *p;
384
12.8M
      unsigned char lenhdr[2];
385
386
      /* gcry_log_debugmpi ("a", a); */
387
12.8M
      p = gcry_mpi_get_opaque (a, &nbits);
388
      /* gcry_log_debug ("   [%u bit]\n", nbits); */
389
      /* gcry_log_debughex (" ", p, (nbits+7)/8); */
390
391
12.8M
      if (p && *p)
392
12.8M
        {
393
12.8M
          nbits = ((nbits + 7) / 8) * 8;
394
395
12.8M
          if (nbits >= 8 && !(*p & 0x80))
396
10.9M
            if (--nbits >= 7 && !(*p & 0x40))
397
2.46M
              if (--nbits >= 6 && !(*p & 0x20))
398
2.09M
                if (--nbits >= 5 && !(*p & 0x10))
399
148k
                  if (--nbits >= 4 && !(*p & 0x08))
400
78.3k
                    if (--nbits >= 3 && !(*p & 0x04))
401
77.7k
                      if (--nbits >= 2 && !(*p & 0x02))
402
62.7k
                        if (--nbits >= 1 && !(*p & 0x01))
403
0
                          --nbits;
404
12.8M
        }
405
406
12.8M
      lenhdr[0] = nbits >> 8;
407
12.8M
      lenhdr[1] = nbits;
408
12.8M
      err = out? iobuf_write (out, lenhdr, 2) : 0;
409
12.8M
      if (!err)
410
12.8M
        {
411
12.8M
          nwritten += 2;
412
12.8M
          if (p)
413
12.8M
            {
414
12.8M
              err = out? iobuf_write (out, p, (nbits+7)/8) : 0;
415
12.8M
              if (!err)
416
12.8M
                nwritten += (nbits+7)/8;
417
12.8M
            }
418
12.8M
        }
419
12.8M
    }
420
0
  else
421
0
    {
422
0
      log_info ("non-opaque MPI (%u bits) for SOS\n", gcry_mpi_get_nbits (a));
423
0
      err = gpg_error (GPG_ERR_INV_DATA);
424
0
    }
425
426
12.8M
  if (r_nwritten)
427
0
    *r_nwritten = nwritten;
428
12.8M
  return err;
429
12.8M
}
430
431
432
/*
433
 * Write an opaque string to the output stream without length info.
434
 */
435
gpg_error_t
436
gpg_mpi_write_opaque_nohdr (iobuf_t out, gcry_mpi_t a)
437
591k
{
438
591k
  int rc;
439
440
591k
  if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
441
591k
    {
442
591k
      unsigned int nbits;
443
591k
      const void *p;
444
445
591k
      p = gcry_mpi_get_opaque (a, &nbits);
446
591k
      rc = p ? iobuf_write (out, p, (nbits+7)/8) : 0;
447
591k
    }
448
0
  else
449
0
    rc = gpg_error (GPG_ERR_BAD_MPI);
450
451
591k
  return rc;
452
591k
}
453
454
455
/*
456
 * Write an opaque MPI string with a four-byte octet count to the
457
 * output stream.  If R_NWRITTEN is not NULL the number of written
458
 * bytes is stored there.  OUT may be NULL in which case only
459
 * R_NWRITTEN is updated and error checking is done.
460
 */
461
gpg_error_t
462
gpg_mpi_write_opaque_32 (iobuf_t out, gcry_mpi_t a, unsigned int *r_nwritten)
463
0
{
464
0
  gpg_error_t err;
465
466
0
  if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
467
0
    {
468
0
      unsigned int nbits, nbytes;
469
0
      const void *p;
470
471
0
      p = gcry_mpi_get_opaque (a, &nbits);
472
0
      nbytes = (nbits + 7)/8;
473
0
      if (out)
474
0
        {
475
0
          write_32 (out, nbytes);
476
0
          err = p ? iobuf_write (out, p, nbytes) : 0;
477
0
        }
478
0
      else
479
0
        err = 0;
480
0
      if (r_nwritten)
481
0
        *r_nwritten = 4 + (p? nbytes : 0);
482
0
    }
483
0
  else
484
0
    {
485
0
      err = gpg_error (GPG_ERR_BAD_MPI);
486
0
      if (r_nwritten)
487
0
        *r_nwritten = 0;
488
0
    }
489
490
0
  return err;
491
0
}
492
493
494
/* Calculate the length of a packet described by PKT.  */
495
u32
496
calc_packet_length( PACKET *pkt )
497
0
{
498
0
  u32 n = 0;
499
0
  int new_ctb = 0;
500
501
0
  log_assert (pkt->pkt.generic);
502
0
  switch (pkt->pkttype)
503
0
    {
504
0
    case PKT_PLAINTEXT:
505
0
      n = calc_plaintext (pkt->pkt.plaintext);
506
0
      new_ctb = pkt->pkt.plaintext->new_ctb;
507
0
      break;
508
0
    case PKT_ATTRIBUTE:
509
0
    case PKT_USER_ID:
510
0
    case PKT_COMMENT:
511
0
    case PKT_PUBLIC_KEY:
512
0
    case PKT_SECRET_KEY:
513
0
    case PKT_SYMKEY_ENC:
514
0
    case PKT_PUBKEY_ENC:
515
0
    case PKT_ENCRYPTED:
516
0
    case PKT_SIGNATURE:
517
0
    case PKT_ONEPASS_SIG:
518
0
    case PKT_RING_TRUST:
519
0
    case PKT_COMPRESSED:
520
0
    default:
521
0
      log_bug ("invalid packet type in calc_packet_length()");
522
0
      break;
523
0
    }
524
525
0
  n += calc_header_length (n, new_ctb);
526
0
  return n;
527
0
}
528
529
530
static gpg_error_t
531
write_fake_data (IOBUF out, gcry_mpi_t a)
532
66.3k
{
533
66.3k
  unsigned int n;
534
66.3k
  void *p;
535
536
66.3k
  if (!a)
537
86
    return 0;
538
66.2k
  if (!gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
539
0
    return 0; /* e.g. due to generating a key with wrong usage.  */
540
66.2k
  p = gcry_mpi_get_opaque ( a, &n);
541
66.2k
  if (!p)
542
65.5k
    return 0; /* For example due to a read error in
543
                 parse-packet.c:read_rest.  */
544
660
  return iobuf_write (out, p, (n+7)/8 );
545
66.2k
}
546
547
548
/* Write a ring trust meta packet.  */
549
static gpg_error_t
550
do_ring_trust (iobuf_t out, PKT_ring_trust *rt)
551
6.38M
{
552
6.38M
  unsigned int namelen = 0;
553
6.38M
  unsigned int pktlen = 6;
554
555
6.38M
  if (rt->subtype == RING_TRUST_KEY || rt->subtype == RING_TRUST_UID)
556
8.59k
    {
557
8.59k
      if (rt->url)
558
0
        namelen = strlen (rt->url);
559
8.59k
      pktlen += 1 + 4 + 1 + namelen;
560
8.59k
    }
561
562
6.38M
  write_header (out, (0x80 | ((PKT_RING_TRUST & 15)<<2)), pktlen);
563
6.38M
  iobuf_put (out, rt->trustval);
564
6.38M
  iobuf_put (out, rt->sigcache);
565
6.38M
  iobuf_write (out, "gpg", 3);
566
6.38M
  iobuf_put (out, rt->subtype);
567
6.38M
  if (rt->subtype == RING_TRUST_KEY || rt->subtype == RING_TRUST_UID)
568
8.59k
    {
569
8.59k
      iobuf_put (out, rt->keyorg);
570
8.59k
      write_32 (out, rt->keyupdate);
571
8.59k
      iobuf_put (out, namelen);
572
8.59k
      if (namelen)
573
0
        iobuf_write (out, rt->url, namelen);
574
8.59k
    }
575
576
6.38M
  return 0;
577
6.38M
}
578
579
580
/* Serialize the user id (RFC 4880, Section 5.11) or the user
581
 * attribute UID (Section 5.12) and write it to OUT.
582
 *
583
 * CTB is the serialization's CTB.  It specifies the header format and
584
 * the packet's type.  The header length must not be set.  */
585
static int
586
do_user_id( IOBUF out, int ctb, PKT_user_id *uid )
587
5.66k
{
588
5.66k
  int rc;
589
5.66k
  int hdrlen;
590
591
5.66k
  log_assert (ctb_pkttype (ctb) == PKT_USER_ID
592
5.66k
              || ctb_pkttype (ctb) == PKT_ATTRIBUTE);
593
594
  /* We need to take special care of a user ID with a length of 0:
595
   * Without forcing HDRLEN to 2 in this case an indeterminate length
596
   * packet would be written which is not allowed.  Note that we are
597
   * always called with a CTB indicating an old packet header format,
598
   * so that forcing a 2 octet header works.  We also check for the
599
   * maximum allowed packet size by the parser using an arbitrary
600
   * extra 10 bytes for header data. */
601
5.66k
  if (uid->attrib_data)
602
0
    {
603
0
      if (uid->attrib_len > MAX_ATTR_PACKET_LENGTH - 10)
604
0
        return gpg_error (GPG_ERR_TOO_LARGE);
605
0
      hdrlen = uid->attrib_len? 0 : 2;
606
0
      write_header2 (out, ctb, uid->attrib_len, hdrlen);
607
0
      rc = iobuf_write( out, uid->attrib_data, uid->attrib_len );
608
0
    }
609
5.66k
  else
610
5.66k
    {
611
5.66k
      if (uid->len > MAX_UID_PACKET_LENGTH - 10)
612
0
        return gpg_error (GPG_ERR_TOO_LARGE);
613
5.66k
      hdrlen = uid->len? 0 : 2;
614
5.66k
      write_header2 (out, ctb, uid->len, hdrlen);
615
5.66k
      rc = iobuf_write( out, uid->name, uid->len );
616
5.66k
    }
617
5.66k
  return rc;
618
5.66k
}
619
620
621
/* Serialize the key (RFC 4880, Section 5.5) described by PK and write
622
 * it to OUT.
623
 *
624
 * This function serializes both primary keys and subkeys with or
625
 * without a secret part.
626
 *
627
 * CTB is the serialization's CTB.  It specifies the header format and
628
 * the packet's type.  The header length must not be set.
629
 *
630
 * PK->VERSION specifies the serialization format.  A value of 0 means
631
 * to use the default version.  Currently, only version 4 packets are
632
 * supported.
633
 */
634
static int
635
do_key (iobuf_t out, int ctb, PKT_public_key *pk)
636
297k
{
637
297k
  gpg_error_t err = 0;
638
297k
  iobuf_t a;
639
297k
  int i, nskey, npkey;
640
297k
  u32 pkbytes = 0;
641
297k
  int is_v5;
642
643
297k
  log_assert (pk->version == 0 || pk->version == 4 || pk->version == 5);
644
297k
  log_assert (ctb_pkttype (ctb) == PKT_PUBLIC_KEY
645
297k
              || ctb_pkttype (ctb) == PKT_PUBLIC_SUBKEY
646
297k
              || ctb_pkttype (ctb) == PKT_SECRET_KEY
647
297k
              || ctb_pkttype (ctb) == PKT_SECRET_SUBKEY);
648
649
  /* The length of the body is stored in the packet's header, which
650
   * occurs before the body.  Unfortunately, we don't know the length
651
   * of the packet's body until we've written all of the data!  To
652
   * work around this, we first write the data into this temporary
653
   * buffer, then generate the header, and finally copy the content
654
   * of this buffer to OUT.  */
655
297k
  a = iobuf_temp();
656
657
  /* Note that the Version number, Timestamp, Algo, and the v5 Key
658
   * material count are written at the end of the function. */
659
660
297k
  is_v5 = (pk->version == 5);
661
662
  /* Get number of secret and public parameters.  They are held in one
663
     array: the public ones followed by the secret ones.  */
664
297k
  nskey = pubkey_get_nskey (pk->pubkey_algo);
665
297k
  npkey = pubkey_get_npkey (pk->pubkey_algo);
666
667
  /* If we don't have any public parameters - which is for example the
668
     case if we don't know the algorithm used - the parameters are
669
     stored as one blob in a faked (opaque) MPI. */
670
297k
  if (!npkey)
671
0
    {
672
0
      write_fake_data (a, pk->pkey[0]);
673
0
      goto leave;
674
0
    }
675
297k
  log_assert (npkey < nskey);
676
677
1.18M
  for (i=0; i < npkey; i++ )
678
888k
    {
679
888k
      if (   (pk->pubkey_algo == PUBKEY_ALGO_ECDSA && (i == 0))
680
888k
          || (pk->pubkey_algo == PUBKEY_ALGO_EDDSA && (i == 0))
681
886k
          || (pk->pubkey_algo == PUBKEY_ALGO_ECDH  && (i == 0 || i == 2))
682
297k
          || (pk->pubkey_algo == PUBKEY_ALGO_KYBER && (i == 0)))
683
591k
        err = gpg_mpi_write_opaque_nohdr (a, pk->pkey[i]);
684
297k
      else if (pk->pubkey_algo == PUBKEY_ALGO_KYBER && i == 2)
685
0
        {
686
          /* Write a four-octet count prefixed Kyber public key.  */
687
0
          err = gpg_mpi_write_opaque_32 (a, pk->pkey[2], NULL);
688
0
        }
689
297k
      else if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
690
297k
               || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
691
294k
               || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
692
297k
        err = sos_write (a, pk->pkey[i], NULL);
693
575
      else
694
575
        err = gpg_mpi_write (a, pk->pkey[i], NULL);
695
888k
      if (err)
696
0
        goto leave;
697
888k
    }
698
699
  /* Record the length of the public key part.  */
700
297k
  pkbytes = iobuf_get_temp_length (a);
701
702
297k
  if (pk->seckey_info)
703
0
    {
704
      /* This is a secret key packet.  */
705
0
      struct seckey_info *ski = pk->seckey_info;
706
707
      /* Build the header for protected (encrypted) secret parameters.  */
708
0
      if (ski->is_protected)
709
0
        {
710
0
          iobuf_put (a, ski->sha1chk? 0xfe : 0xff); /* S2k usage.  */
711
0
          if (is_v5)
712
0
            {
713
              /* For a v5 key determine the count of the following
714
               * key-protection material and write it.  */
715
0
              int count = 1;  /* Pubkey algo octet. */
716
0
              if (ski->s2k.mode >= 1000)
717
0
                count += 6;   /* GNU specific mode descriptor.  */
718
0
              else
719
0
                count += 2;   /* Mode and hash algo.  */
720
0
              if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
721
0
                count += 8;   /* Salt.  */
722
0
              if (ski->s2k.mode == 3)
723
0
                count++;      /* S2K.COUNT */
724
0
              if (ski->s2k.mode != 1001 && ski->s2k.mode != 1002
725
0
                   && ski->s2k.mode != 1003)
726
0
                count += ski->ivlen;
727
728
0
              iobuf_put (a, count);
729
0
            }
730
0
          iobuf_put (a, ski->algo);  /* Pubkey algo octet.  */
731
0
          if (ski->s2k.mode >= 1000)
732
0
            {
733
              /* These modes are not possible in OpenPGP, we use them
734
                 to implement our extensions, 101 can be viewed as a
735
                 private/experimental extension (this is not specified
736
                 in rfc2440 but the same scheme is used for all other
737
                 algorithm identifiers). */
738
0
              iobuf_put (a, 101);
739
0
              iobuf_put (a, ski->s2k.hash_algo);
740
0
              iobuf_write (a, "GNU", 3 );
741
0
              iobuf_put (a, ski->s2k.mode - 1000);
742
0
            }
743
0
          else
744
0
            {
745
0
              iobuf_put (a, ski->s2k.mode);
746
0
              iobuf_put (a, ski->s2k.hash_algo);
747
0
            }
748
749
0
          if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
750
0
            iobuf_write (a, ski->s2k.salt, 8);
751
752
0
          if (ski->s2k.mode == 3)
753
0
            iobuf_put (a, ski->s2k.count);
754
755
          /* For our special modes 1001..1003 we do not need an IV. */
756
0
          if (ski->s2k.mode != 1001 && ski->s2k.mode != 1002
757
0
               && ski->s2k.mode != 1003)
758
0
            iobuf_write (a, ski->iv, ski->ivlen);
759
760
0
        }
761
0
      else /* Not protected. */
762
0
        {
763
0
          iobuf_put (a, 0 );  /* S2K usage = not protected.  */
764
0
          if (is_v5)
765
0
            iobuf_put (a, 0); /* Zero octets of key-protection
766
                               * material follows.  */
767
0
        }
768
769
0
      if (ski->s2k.mode == 1001)
770
0
        {
771
          /* GnuPG extension - don't write a secret key at all. */
772
0
          if (is_v5)
773
0
            write_32 (a, 0); /* Zero octets of key material.  */
774
0
        }
775
0
      else if (ski->s2k.mode == 1002)
776
0
        {
777
          /* GnuPG extension - divert to OpenPGP smartcard. */
778
0
          if (is_v5)
779
0
            write_32 (a, 1 + ski->ivlen);
780
          /* Length of the serial number or 0 for no serial number. */
781
0
          iobuf_put (a, ski->ivlen );
782
          /* The serial number gets stored in the IV field.  */
783
0
          iobuf_write (a, ski->iv, ski->ivlen);
784
0
        }
785
0
      else if (ski->s2k.mode == 1003)
786
0
        {
787
          /* GnuPG extension - Store raw s-expression. */
788
0
          byte *p;
789
0
          unsigned int ndatabits;
790
791
0
          log_assert (gcry_mpi_get_flag (pk->pkey[npkey], GCRYMPI_FLAG_OPAQUE));
792
793
0
          p = gcry_mpi_get_opaque (pk->pkey[npkey], &ndatabits);
794
          /* For v5 keys we first write the number of octets of the
795
           * following key material.  */
796
0
          if (is_v5)
797
0
            write_32 (a, p? (ndatabits+7)/8 : 0);
798
0
          if (p)
799
0
            iobuf_write (a, p, (ndatabits+7)/8 );
800
0
        }
801
0
      else if (ski->is_protected)
802
0
        {
803
          /* The secret key is protected - write it out as it is.  */
804
0
          byte *p;
805
0
          unsigned int ndatabits;
806
807
0
          log_assert (gcry_mpi_get_flag (pk->pkey[npkey], GCRYMPI_FLAG_OPAQUE));
808
0
          p = gcry_mpi_get_opaque (pk->pkey[npkey], &ndatabits);
809
          /* For v5 keys we first write the number of octets of the
810
           * following encrypted key material.  */
811
0
          if (is_v5)
812
0
            write_32 (a, p? (ndatabits+7)/8 : 0);
813
0
          if (p)
814
0
            iobuf_write (a, p, (ndatabits+7)/8 );
815
0
        }
816
0
      else
817
0
        {
818
          /* Non-protected key. */
819
0
          if (is_v5)
820
0
            {
821
0
              unsigned int skbytes = 0;
822
0
              unsigned int n;
823
0
              int j;
824
825
0
              for (j=i; j < nskey; j++ )
826
0
                {
827
0
                  if (pk->pubkey_algo == PUBKEY_ALGO_KYBER && j == 4)
828
0
                    {
829
0
                      if ((err=gpg_mpi_write_opaque_32 (NULL,pk->pkey[j], &n)))
830
0
                        goto leave;
831
0
                    }
832
0
                  else if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
833
0
                           || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
834
0
                           || pk->pubkey_algo == PUBKEY_ALGO_ECDH
835
0
                           || pk->pubkey_algo == PUBKEY_ALGO_KYBER)
836
0
                    {
837
0
                      if ((err = sos_write (NULL, pk->pkey[j], &n)))
838
0
                        goto leave;
839
0
                    }
840
0
                  else
841
0
                    {
842
0
                      if ( (err = gpg_mpi_write (a, pk->pkey[i], NULL)))
843
0
                        goto leave;
844
0
                    }
845
0
                  skbytes += n;
846
0
                }
847
848
0
              write_32 (a, skbytes);
849
0
            }
850
851
0
          for ( ; i < nskey; i++ )
852
0
            {
853
0
              if (pk->pubkey_algo == PUBKEY_ALGO_KYBER && i == 4)
854
0
                {
855
0
                  err = gpg_mpi_write_opaque_32 (a, pk->pkey[i], NULL);
856
0
                  if (err)
857
0
                    goto leave;
858
0
                }
859
0
              else if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
860
0
                       || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
861
0
                       || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
862
0
                {
863
0
                  if ((err = sos_write (a, pk->pkey[i], NULL)))
864
0
                    goto leave;
865
0
                }
866
0
              else
867
0
                {
868
0
                  if ((err = gpg_mpi_write (a, pk->pkey[i], NULL)))
869
0
                    goto leave;
870
0
                }
871
0
            }
872
873
0
          write_16 (a, ski->csum );
874
0
        }
875
0
    }
876
877
297k
 leave:
878
297k
  if (!err)
879
297k
    {
880
      /* Build the header of the packet - which we must do after
881
       * writing all the other stuff, so that we know the length of
882
       * the packet */
883
297k
      u32 len = iobuf_get_temp_length (a);
884
297k
      len += 1; /* version number  */
885
297k
      len += 4; /* timestamp  */
886
297k
      len += 1; /* algo  */
887
297k
      if (is_v5)
888
2
        len += 4; /* public key material count  */
889
890
297k
      write_header2 (out, ctb, len, 0);
891
       /* And finally write it out to the real stream. */
892
297k
      iobuf_put (out, pk->version? pk->version : 4); /* version number  */
893
297k
      write_32 (out, pk->timestamp );
894
297k
      iobuf_put (out, pk->pubkey_algo);  /* algo */
895
297k
      if (is_v5)
896
2
        write_32 (out, pkbytes);        /* public key material count  */
897
297k
      err = iobuf_write_temp (out, a);  /* pub and sec key material */
898
297k
    }
899
900
297k
  iobuf_close (a); /* Close the temporary buffer */
901
297k
  return err;
902
297k
}
903
904
905
/* Serialize the symmetric-key encrypted session key packet (RFC 4880,
906
 * 5.3) described by ENC and write it to OUT.
907
 *
908
 * CTB is the serialization's CTB.  It specifies the header format and
909
 * the packet's type.  The header length must not be set.  */
910
static int
911
do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc )
912
0
{
913
0
  int rc = 0;
914
0
  IOBUF a = iobuf_temp();
915
916
0
  log_assert (ctb_pkttype (ctb) == PKT_SYMKEY_ENC);
917
0
  log_assert (enc->version == 4 || enc->version == 5);
918
919
0
  switch (enc->s2k.mode)
920
0
    {
921
0
    case 0: /* Simple S2K.  */
922
0
    case 1: /* Salted S2K.  */
923
0
    case 3: /* Iterated and salted S2K.  */
924
0
      break; /* Reasonable values.  */
925
926
0
    default:
927
0
      log_bug ("do_symkey_enc: s2k=%d\n", enc->s2k.mode);
928
0
    }
929
0
  iobuf_put (a, enc->version);
930
0
  iobuf_put (a, enc->cipher_algo);
931
0
  if (enc->version == 5)
932
0
    iobuf_put (a, enc->aead_algo);
933
0
  iobuf_put (a, enc->s2k.mode);
934
0
  iobuf_put (a, enc->s2k.hash_algo);
935
0
  if (enc->s2k.mode == 1 || enc->s2k.mode == 3)
936
0
    {
937
0
      iobuf_write (a, enc->s2k.salt, 8);
938
0
      if (enc->s2k.mode == 3)
939
0
        iobuf_put (a, enc->s2k.count);
940
0
    }
941
0
  if (enc->seskeylen)
942
0
    iobuf_write (a, enc->seskey, enc->seskeylen);
943
944
0
  write_header (out, ctb, iobuf_get_temp_length(a));
945
0
  rc = iobuf_write_temp (out, a);
946
947
0
  iobuf_close (a);
948
0
  return rc;
949
0
}
950
951
952
/* Serialize the public-key encrypted session key packet (RFC 4880,
953
   5.1) described by ENC and write it to OUT.
954
955
   CTB is the serialization's CTB.  It specifies the header format and
956
   the packet's type.  The header length must not be set.  */
957
static int
958
do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc )
959
0
{
960
0
  int rc = 0;
961
0
  int n, i;
962
0
  IOBUF a = iobuf_temp();
963
964
0
  log_assert (ctb_pkttype (ctb) == PKT_PUBKEY_ENC);
965
966
0
  iobuf_put (a, 3); /* Version.  */
967
968
0
  if ( enc->throw_keyid )
969
0
    {
970
0
      write_32(a, 0 );  /* Don't tell Eve who can decrypt the message.  */
971
0
      write_32(a, 0 );
972
0
    }
973
0
  else
974
0
    {
975
0
      write_32(a, enc->keyid[0] );
976
0
      write_32(a, enc->keyid[1] );
977
0
    }
978
0
  iobuf_put(a,enc->pubkey_algo );
979
0
  n = pubkey_get_nenc( enc->pubkey_algo );
980
0
  if ( !n )
981
0
    write_fake_data( a, enc->data[0] );
982
983
0
  for (i=0; i < n && !rc ; i++ )
984
0
    {
985
      /* For Kyber we need to insert the algo before the final data
986
       * element because it is not stored in the data array.  */
987
0
      if (enc->pubkey_algo == PUBKEY_ALGO_KYBER && i == 2)
988
0
        iobuf_put (a, enc->seskey_algo);
989
990
0
      if (i == 1 && enc->pubkey_algo == PUBKEY_ALGO_ECDH)
991
0
        rc = gpg_mpi_write_opaque_nohdr (a, enc->data[i]);
992
0
      else if (i == 1 && enc->pubkey_algo == PUBKEY_ALGO_KYBER)
993
0
        rc = gpg_mpi_write_opaque_32 (a, enc->data[i], NULL);
994
0
      else if (i == 2 && enc->pubkey_algo == PUBKEY_ALGO_KYBER)
995
0
        rc = gpg_mpi_write_opaque_nohdr (a, enc->data[i]);
996
0
      else if (enc->pubkey_algo == PUBKEY_ALGO_ECDH
997
0
               || enc->pubkey_algo == PUBKEY_ALGO_KYBER)
998
0
        rc = sos_write (a, enc->data[i], NULL);
999
0
      else
1000
0
        rc = gpg_mpi_write (a, enc->data[i], NULL);
1001
0
    }
1002
1003
0
  if (!rc)
1004
0
    {
1005
0
      write_header (out, ctb, iobuf_get_temp_length(a) );
1006
0
      rc = iobuf_write_temp (out, a);
1007
0
    }
1008
0
  iobuf_close(a);
1009
0
  return rc;
1010
0
}
1011
1012
1013
/* Calculate the length of the serialized plaintext packet PT (RFC
1014
   4480, Section 5.9).  */
1015
static u32
1016
calc_plaintext( PKT_plaintext *pt )
1017
0
{
1018
  /* Truncate namelen to the maximum 255 characters.  Note this means
1019
     that a function that calls build_packet with an illegal literal
1020
     packet will get it back legalized. */
1021
1022
0
  if(pt->namelen>255)
1023
0
    pt->namelen=255;
1024
1025
0
  return pt->len? (1 + 1 + pt->namelen + 4 + pt->len) : 0;
1026
0
}
1027
1028
/* Serialize the plaintext packet (RFC 4880, 5.9) described by PT and
1029
   write it to OUT.
1030
1031
   The body of the message is stored in PT->BUF.  The amount of data
1032
   to write is PT->LEN.  (PT->BUF should be configured to return EOF
1033
   after this much data has been read.)  If PT->LEN is 0 and CTB
1034
   indicates that this is a new format packet, then partial block mode
1035
   is assumed to have been enabled on OUT.  On success, partial block
1036
   mode is disabled.
1037
1038
   If PT->BUF is NULL, the caller must write out the data.  In
1039
   this case, if PT->LEN was 0, then partial body length mode was
1040
   enabled and the caller must disable it by calling
1041
   iobuf_set_partial_body_length_mode (out, 0).  */
1042
static int
1043
do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt )
1044
0
{
1045
0
    int rc = 0;
1046
0
    size_t nbytes;
1047
1048
0
    log_assert (ctb_pkttype (ctb) == PKT_PLAINTEXT);
1049
1050
0
    write_header(out, ctb, calc_plaintext( pt ) );
1051
0
    log_assert (pt->mode == 'b' || pt->mode == 't' || pt->mode == 'u'
1052
0
                || pt->mode == 'm'
1053
0
                || pt->mode == 'l' || pt->mode == '1');
1054
0
    iobuf_put(out, pt->mode );
1055
0
    iobuf_put(out, pt->namelen );
1056
0
    iobuf_write (out, pt->name, pt->namelen);
1057
0
    rc = write_32(out, pt->timestamp );
1058
0
    if (rc)
1059
0
      return rc;
1060
1061
0
    if (pt->buf)
1062
0
      {
1063
0
        nbytes = iobuf_copy (out, pt->buf);
1064
0
        if (nbytes == (size_t)(-1)
1065
0
            && (iobuf_error (out) || iobuf_error (pt->buf)))
1066
0
            return iobuf_error (out)? iobuf_error (out):iobuf_error (pt->buf);
1067
0
        else if (nbytes != (size_t)(-1) && iobuf_error (pt->buf))
1068
0
          rc = iobuf_error (pt->buf);  /* Read error.  */
1069
0
        else
1070
0
          {
1071
            /* Always get the iobuf error to catch write errors
1072
             * because iobuf_copy returns (-1) only if there was a
1073
             * errors in the output stream when entering that
1074
             * function.  */
1075
0
            rc = iobuf_error (out);
1076
0
          }
1077
0
        if(ctb_new_format_p (ctb) && !pt->len)
1078
          /* Turn off partial body length mode.  */
1079
0
          iobuf_set_partial_body_length_mode (out, 0);
1080
0
        if (pt->len && nbytes != pt->len)
1081
0
          {
1082
0
            log_error ("do_plaintext(): wrote %lu bytes"
1083
0
                       " but expected %lu bytes\n",
1084
0
                       (ulong)nbytes, (ulong)pt->len );
1085
0
            if (!rc) /* Just in case no error was set  */
1086
0
              rc = gpg_error (GPG_ERR_EIO);
1087
0
          }
1088
0
      }
1089
1090
0
    return rc;
1091
0
}
1092
1093
1094
1095
/* Serialize the symmetrically encrypted data packet (RFC 4880,
1096
   Section 5.7) described by ED and write it to OUT.
1097
1098
   Note: this only writes the packets header!  The call must then
1099
   follow up and write the initial random data and the body to OUT.
1100
   (If you use the encryption iobuf filter (cipher_filter), then this
1101
   is done automatically.)  */
1102
static int
1103
do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed )
1104
0
{
1105
0
    int rc = 0;
1106
0
    u32 n;
1107
1108
0
    log_assert (! ed->mdc_method);
1109
0
    log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED);
1110
1111
0
    n = ed->len ? (ed->len + ed->extralen) : 0;
1112
0
    write_header(out, ctb, n );
1113
1114
    /* This is all. The caller has to write the real data */
1115
1116
0
    return rc;
1117
0
}
1118
1119
/* Serialize the symmetrically encrypted integrity protected data
1120
   packet (RFC 4880, Section 5.13) described by ED and write it to
1121
   OUT.
1122
1123
   Note: this only writes the packet's header!  The caller must then
1124
   follow up and write the initial random data, the body and the MDC
1125
   packet to OUT.  (If you use the encryption iobuf filter
1126
   (cipher_filter), then this is done automatically.)  */
1127
static int
1128
do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed )
1129
0
{
1130
0
    int rc = 0;
1131
0
    u32 n;
1132
1133
0
    log_assert (ed->mdc_method);
1134
0
    log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED_MDC);
1135
1136
    /* Take version number and the following MDC packet in account. */
1137
0
    n = ed->len ? (ed->len + ed->extralen + 1 + 22) : 0;
1138
0
    write_header(out, ctb, n );
1139
0
    iobuf_put(out, 1 );  /* version */
1140
1141
    /* This is all. The caller has to write the real data */
1142
1143
0
    return rc;
1144
0
}
1145
1146
1147
/* Serialize the symmetrically AEAD encrypted data packet
1148
 * (rfc4880bis-03, Section 5.16) described by ED and write it to OUT.
1149
 *
1150
 * Note: this only writes only packet's header.  The caller must then
1151
 * follow up and write the actual encrypted data.  This should be done
1152
 * by pushing the the cipher_filter_aead.  */
1153
static int
1154
do_encrypted_aead (iobuf_t out, int ctb, PKT_encrypted *ed)
1155
0
{
1156
0
  u32 n;
1157
1158
0
  log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED_AEAD);
1159
1160
0
  n = ed->len ? (ed->len + ed->extralen + 4) : 0;
1161
0
  write_header (out, ctb, n );
1162
0
  iobuf_writebyte (out, 1); /* Version.  */
1163
0
  iobuf_writebyte (out, ed->cipher_algo);
1164
0
  iobuf_writebyte (out, ed->aead_algo);
1165
0
  iobuf_writebyte (out, ed->chunkbyte);
1166
1167
  /* This is all. The caller has to write the encrypted data */
1168
1169
0
  return 0;
1170
0
}
1171
1172
1173
/* Serialize the compressed packet (RFC 4880, Section 5.6) described
1174
   by CD and write it to OUT.
1175
1176
   Note: this only writes the packet's header!  The caller must then
1177
   follow up and write the body to OUT.  */
1178
static int
1179
do_compressed( IOBUF out, int ctb, PKT_compressed *cd )
1180
0
{
1181
0
    int rc = 0;
1182
1183
0
    log_assert (ctb_pkttype (ctb) == PKT_COMPRESSED);
1184
1185
    /* We must use the old convention and don't use blockmode for the
1186
       sake of PGP 2 compatibility.  However if the new_ctb flag was
1187
       set, CTB is already formatted as new style and write_header2
1188
       does create a partial length encoding using new the new
1189
       style. */
1190
0
    write_header2(out, ctb, 0, 0);
1191
0
    iobuf_put(out, cd->algorithm );
1192
1193
    /* This is all. The caller has to write the real data */
1194
1195
0
    return rc;
1196
0
}
1197
1198
1199
/****************
1200
 * Delete all subpackets of type REQTYPE and return a bool whether a packet
1201
 * was deleted.
1202
 */
1203
int
1204
delete_sig_subpkt (subpktarea_t *area, sigsubpkttype_t reqtype )
1205
0
{
1206
0
    int buflen;
1207
0
    sigsubpkttype_t type;
1208
0
    byte *buffer, *bufstart;
1209
0
    size_t n;
1210
0
    size_t unused = 0;
1211
0
    int okay = 0;
1212
1213
0
    if( !area )
1214
0
  return 0;
1215
0
    buflen = area->len;
1216
0
    buffer = area->data;
1217
0
    for(;;) {
1218
0
  if( !buflen ) {
1219
0
            okay = 1;
1220
0
            break;
1221
0
        }
1222
0
  bufstart = buffer;
1223
0
  n = *buffer++; buflen--;
1224
0
  if( n == 255 ) {
1225
0
      if( buflen < 4 )
1226
0
    break;
1227
0
      n = buf32_to_size_t (buffer);
1228
0
      buffer += 4;
1229
0
      buflen -= 4;
1230
0
  }
1231
0
  else if( n >= 192 ) {
1232
0
      if( buflen < 2 )
1233
0
    break;
1234
0
      n = (( n - 192 ) << 8) + *buffer + 192;
1235
0
      buffer++;
1236
0
      buflen--;
1237
0
  }
1238
0
  if( buflen < n )
1239
0
      break;
1240
1241
0
  type = *buffer & 0x7f;
1242
0
  if( type == reqtype ) {
1243
0
      buffer++;
1244
0
            buflen--;
1245
0
      n--;
1246
0
      if( n > buflen )
1247
0
    break;
1248
0
            buffer += n; /* point to next subpkt */
1249
0
            buflen -= n;
1250
0
            memmove (bufstart, buffer, buflen); /* shift */
1251
0
            unused +=  buffer - bufstart;
1252
0
            buffer = bufstart;
1253
0
  }
1254
0
        else {
1255
0
            buffer += n; buflen -=n;
1256
0
        }
1257
0
    }
1258
1259
0
    if (!okay)
1260
0
        log_error ("delete_subpkt: buffer shorter than subpacket\n");
1261
0
    log_assert (unused <= area->len);
1262
0
    area->len -= unused;
1263
0
    return !!unused;
1264
0
}
1265
1266
1267
/****************
1268
 * Create or update a signature subpacket for SIG of TYPE.  This
1269
 * functions knows where to put the data (hashed or unhashed).  The
1270
 * function may move data from the unhashed part to the hashed one.
1271
 * Note: All pointers into sig->[un]hashed (e.g. returned by
1272
 * parse_sig_subpkt) are not valid after a call to this function.  The
1273
 * data to put into the subpaket should be in a buffer with a length
1274
 * of buflen.
1275
 */
1276
void
1277
build_sig_subpkt (PKT_signature *sig, sigsubpkttype_t type,
1278
      const byte *buffer, size_t buflen )
1279
0
{
1280
0
    byte *p;
1281
0
    int critical, hashed;
1282
0
    subpktarea_t *oldarea, *newarea;
1283
0
    size_t nlen, n, n0;
1284
1285
0
    critical = (type & SIGSUBPKT_FLAG_CRITICAL);
1286
0
    type &= ~SIGSUBPKT_FLAG_CRITICAL;
1287
1288
    /* Sanity check buffer sizes */
1289
0
    if(parse_one_sig_subpkt(buffer,buflen,type)<0)
1290
0
      BUG();
1291
1292
0
    switch(type)
1293
0
      {
1294
0
      case SIGSUBPKT_NOTATION:
1295
0
      case SIGSUBPKT_POLICY:
1296
0
      case SIGSUBPKT_REV_KEY:
1297
0
      case SIGSUBPKT_SIGNATURE:
1298
  /* we do allow multiple subpackets */
1299
0
  break;
1300
1301
0
      default:
1302
  /* we don't allow multiple subpackets */
1303
0
  delete_sig_subpkt(sig->hashed,type);
1304
0
  delete_sig_subpkt(sig->unhashed,type);
1305
0
  break;
1306
0
      }
1307
1308
    /* Any special magic that needs to be done for this type so the
1309
       packet doesn't need to be reparsed? */
1310
0
    switch(type)
1311
0
      {
1312
0
      case SIGSUBPKT_NOTATION:
1313
0
  sig->flags.notation=1;
1314
0
  break;
1315
1316
0
      case SIGSUBPKT_POLICY:
1317
0
  sig->flags.policy_url=1;
1318
0
  break;
1319
1320
0
      case SIGSUBPKT_PREF_KS:
1321
0
  sig->flags.pref_ks=1;
1322
0
  break;
1323
1324
0
      case SIGSUBPKT_EXPORTABLE:
1325
0
  if(buffer[0])
1326
0
    sig->flags.exportable=1;
1327
0
  else
1328
0
    sig->flags.exportable=0;
1329
0
  break;
1330
1331
0
      case SIGSUBPKT_REVOCABLE:
1332
0
  if(buffer[0])
1333
0
    sig->flags.revocable=1;
1334
0
  else
1335
0
    sig->flags.revocable=0;
1336
0
  break;
1337
1338
0
      case SIGSUBPKT_TRUST:
1339
0
  sig->trust_depth=buffer[0];
1340
0
  sig->trust_value=buffer[1];
1341
0
  break;
1342
1343
0
      case SIGSUBPKT_REGEXP:
1344
0
  sig->trust_regexp=buffer;
1345
0
  break;
1346
1347
  /* This should never happen since we don't currently allow
1348
     creating such a subpacket, but just in case... */
1349
0
      case SIGSUBPKT_SIG_EXPIRE:
1350
0
  if(buf32_to_u32(buffer)+sig->timestamp<=make_timestamp())
1351
0
    sig->flags.expired=1;
1352
0
  else
1353
0
    sig->flags.expired=0;
1354
0
  break;
1355
1356
0
      default:
1357
0
  break;
1358
0
      }
1359
1360
0
    if( (buflen+1) >= 8384 )
1361
0
  nlen = 5; /* write 5 byte length header */
1362
0
    else if( (buflen+1) >= 192 )
1363
0
  nlen = 2; /* write 2 byte length header */
1364
0
    else
1365
0
  nlen = 1; /* just a 1 byte length header */
1366
1367
0
    switch( type )
1368
0
      {
1369
  /* The issuer being unhashed is a historical oddity.  It
1370
     should work equally as well hashed.  Of course, if even an
1371
     unhashed issuer is tampered with, it makes it awfully hard
1372
     to verify the sig... */
1373
0
      case SIGSUBPKT_ISSUER:
1374
0
      case SIGSUBPKT_SIGNATURE:
1375
0
        hashed = 0;
1376
0
        break;
1377
0
      default:
1378
0
        hashed = 1;
1379
0
        break;
1380
0
      }
1381
1382
0
    if( critical )
1383
0
  type |= SIGSUBPKT_FLAG_CRITICAL;
1384
1385
0
    oldarea = hashed? sig->hashed : sig->unhashed;
1386
1387
    /* Calculate new size of the area and allocate */
1388
0
    n0 = oldarea? oldarea->len : 0;
1389
0
    n = n0 + nlen + 1 + buflen; /* length, type, buffer */
1390
0
    if (oldarea && n <= oldarea->size) { /* fits into the unused space */
1391
0
        newarea = oldarea;
1392
        /*log_debug ("updating area for type %d\n", type );*/
1393
0
    }
1394
0
    else if (oldarea) {
1395
0
        newarea = xrealloc (oldarea, sizeof (*newarea) + n - 1);
1396
0
        newarea->size = n;
1397
        /*log_debug ("reallocating area for type %d\n", type );*/
1398
0
    }
1399
0
    else {
1400
0
        newarea = xmalloc (sizeof (*newarea) + n - 1);
1401
0
        newarea->size = n;
1402
        /*log_debug ("allocating area for type %d\n", type );*/
1403
0
    }
1404
0
    newarea->len = n;
1405
1406
0
    p = newarea->data + n0;
1407
0
    if (nlen == 5) {
1408
0
  *p++ = 255;
1409
0
  *p++ = (buflen+1) >> 24;
1410
0
  *p++ = (buflen+1) >> 16;
1411
0
  *p++ = (buflen+1) >>  8;
1412
0
  *p++ = (buflen+1);
1413
0
  *p++ = type;
1414
0
  memcpy (p, buffer, buflen);
1415
0
    }
1416
0
    else if (nlen == 2) {
1417
0
  *p++ = (buflen+1-192) / 256 + 192;
1418
0
  *p++ = (buflen+1-192) % 256;
1419
0
  *p++ = type;
1420
0
  memcpy (p, buffer, buflen);
1421
0
    }
1422
0
    else {
1423
0
  *p++ = buflen+1;
1424
0
  *p++ = type;
1425
0
  memcpy (p, buffer, buflen);
1426
0
    }
1427
1428
0
    if (hashed)
1429
0
  sig->hashed = newarea;
1430
0
    else
1431
0
  sig->unhashed = newarea;
1432
0
}
1433
1434
/*
1435
 * Put all the required stuff from SIG into subpackets of sig.
1436
 * PKSK is the signing key.  SIGNHINTS are various flags like
1437
 * SIGNHINT_ADSK.
1438
 * Hmmm, should we delete those subpackets which are in a wrong area?
1439
 */
1440
void
1441
build_sig_subpkt_from_sig (PKT_signature *sig, PKT_public_key *pksk,
1442
                           unsigned int signhints)
1443
0
{
1444
0
    u32  u;
1445
0
    byte buf[1+MAX_FINGERPRINT_LEN];
1446
0
    size_t fprlen;
1447
1448
    /* For v4 keys we need to write the ISSUER subpacket.  We do not
1449
     * want that for a future v5 format.  We also don't write it if
1450
     * only the new RENC keyflag is set (implementations with support
1451
     * for this key flag should understand the ISSUER_FPR).  */
1452
0
    if (pksk->version < 5 && !(signhints & SIGNHINT_ADSK))
1453
0
      {
1454
0
        u = sig->keyid[0];
1455
0
        buf[0] = (u >> 24) & 0xff;
1456
0
        buf[1] = (u >> 16) & 0xff;
1457
0
        buf[2] = (u >>  8) & 0xff;
1458
0
        buf[3] = u & 0xff;
1459
0
        u = sig->keyid[1];
1460
0
        buf[4] = (u >> 24) & 0xff;
1461
0
        buf[5] = (u >> 16) & 0xff;
1462
0
        buf[6] = (u >>  8) & 0xff;
1463
0
        buf[7] = u & 0xff;
1464
0
        build_sig_subpkt (sig, SIGSUBPKT_ISSUER, buf, 8);
1465
0
      }
1466
1467
    /* Write the new ISSUER_FPR subpacket.  */
1468
0
    fingerprint_from_pk (pksk, buf+1, &fprlen);
1469
0
    if (fprlen == 20 || fprlen == 32)
1470
0
      {
1471
0
        buf[0] = pksk->version;
1472
0
        build_sig_subpkt (sig, SIGSUBPKT_ISSUER_FPR, buf, fprlen + 1);
1473
0
      }
1474
1475
    /* Write the timestamp.  */
1476
0
    u = sig->timestamp;
1477
0
    buf[0] = (u >> 24) & 0xff;
1478
0
    buf[1] = (u >> 16) & 0xff;
1479
0
    buf[2] = (u >>  8) & 0xff;
1480
0
    buf[3] = u & 0xff;
1481
0
    build_sig_subpkt( sig, SIGSUBPKT_SIG_CREATED, buf, 4 );
1482
1483
0
    if(sig->expiredate)
1484
0
      {
1485
0
  if(sig->expiredate>sig->timestamp)
1486
0
    u=sig->expiredate-sig->timestamp;
1487
0
  else
1488
0
    u=1; /* A 1-second expiration time is the shortest one
1489
      OpenPGP has */
1490
1491
0
  buf[0] = (u >> 24) & 0xff;
1492
0
  buf[1] = (u >> 16) & 0xff;
1493
0
  buf[2] = (u >>  8) & 0xff;
1494
0
  buf[3] = u & 0xff;
1495
1496
  /* Mark this CRITICAL, so if any implementation doesn't
1497
           understand sigs that can expire, it'll just disregard this
1498
           sig altogether. */
1499
1500
0
  build_sig_subpkt( sig, SIGSUBPKT_SIG_EXPIRE | SIGSUBPKT_FLAG_CRITICAL,
1501
0
        buf, 4 );
1502
0
      }
1503
0
}
1504
1505
void
1506
build_attribute_subpkt(PKT_user_id *uid,byte type,
1507
           const void *buf,u32 buflen,
1508
           const void *header,u32 headerlen)
1509
0
{
1510
0
  byte *attrib;
1511
0
  int idx;
1512
1513
0
  if(1+headerlen+buflen>8383)
1514
0
    idx=5;
1515
0
  else if(1+headerlen+buflen>191)
1516
0
    idx=2;
1517
0
  else
1518
0
    idx=1;
1519
1520
  /* realloc uid->attrib_data to the right size */
1521
1522
0
  uid->attrib_data=xrealloc(uid->attrib_data,
1523
0
           uid->attrib_len+idx+1+headerlen+buflen);
1524
1525
0
  attrib=&uid->attrib_data[uid->attrib_len];
1526
1527
0
  if(idx==5)
1528
0
    {
1529
0
      attrib[0]=255;
1530
0
      attrib[1]=(1+headerlen+buflen) >> 24;
1531
0
      attrib[2]=(1+headerlen+buflen) >> 16;
1532
0
      attrib[3]=(1+headerlen+buflen) >> 8;
1533
0
      attrib[4]=1+headerlen+buflen;
1534
0
    }
1535
0
  else if(idx==2)
1536
0
    {
1537
0
      attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
1538
0
      attrib[1]=(1+headerlen+buflen-192) % 256;
1539
0
    }
1540
0
  else
1541
0
    attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
1542
1543
0
  attrib[idx++]=type;
1544
1545
  /* Tack on our data at the end */
1546
1547
0
  if(headerlen>0)
1548
0
    memcpy(&attrib[idx],header,headerlen);
1549
0
  memcpy(&attrib[idx+headerlen],buf,buflen);
1550
0
  uid->attrib_len+=idx+headerlen+buflen;
1551
0
}
1552
1553
/* Returns a human-readable string corresponding to the notation.
1554
   This ignores notation->value.  The caller must free the result.  */
1555
static char *
1556
notation_value_to_human_readable_string (struct notation *notation)
1557
0
{
1558
0
  if(notation->bdat)
1559
    /* Binary data.  */
1560
0
    {
1561
0
      size_t len = notation->blen;
1562
0
      int i;
1563
0
      char preview[20];
1564
1565
0
      for (i = 0; i < len && i < sizeof (preview) - 1; i ++)
1566
0
        if (isprint (notation->bdat[i]))
1567
0
          preview[i] = notation->bdat[i];
1568
0
        else
1569
0
          preview[i] = '?';
1570
0
      preview[i] = 0;
1571
1572
0
      return xasprintf (_("[ not human readable (%zu bytes: %s%s) ]"),
1573
0
                        len, preview, i < len ? "..." : "");
1574
0
    }
1575
0
  else
1576
    /* The value is human-readable.  */
1577
0
    return xstrdup (notation->value);
1578
0
}
1579
1580
1581
/* Turn the notation described by the string STRING into a notation.
1582
 *
1583
 * STRING has the form:
1584
 *
1585
 *   - -name - Delete the notation.
1586
 *   - name@domain.name=value - Normal notation
1587
 *   - !name@domain.name=value - Notation with critical bit set.
1588
 *
1589
 * The caller must free the result using free_notation().  */
1590
struct notation *
1591
string_to_notation (const char *string, int is_utf8)
1592
0
{
1593
0
  const char *s;
1594
0
  int saw_at=0;
1595
0
  struct notation *notation;
1596
1597
0
  notation=xmalloc_clear(sizeof(*notation));
1598
1599
0
  if(*string=='-')
1600
0
    {
1601
0
      notation->flags.ignore=1;
1602
0
      string++;
1603
0
    }
1604
1605
0
  if(*string=='!')
1606
0
    {
1607
0
      notation->flags.critical=1;
1608
0
      string++;
1609
0
    }
1610
1611
  /* If and when the IETF assigns some official name tags, we'll have
1612
     to add them here. */
1613
1614
0
  for( s=string ; *s != '='; s++ )
1615
0
    {
1616
0
      if( *s=='@')
1617
0
  saw_at++;
1618
1619
      /* -notationname is legal without an = sign */
1620
0
      if(!*s && notation->flags.ignore)
1621
0
  break;
1622
1623
0
      if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
1624
0
  {
1625
0
    log_error(_("a notation name must have only printable characters"
1626
0
          " or spaces, and end with an '='\n") );
1627
0
    goto fail;
1628
0
  }
1629
0
    }
1630
1631
0
  notation->name=xmalloc((s-string)+1);
1632
0
  memcpy(notation->name,string,s-string);
1633
0
  notation->name[s-string]='\0';
1634
1635
0
  if(!saw_at && !opt.expert)
1636
0
    {
1637
0
      log_error(_("a user notation name must contain the '@' character\n"));
1638
0
      goto fail;
1639
0
    }
1640
1641
0
  if (saw_at > 1)
1642
0
    {
1643
0
      log_error(_("a notation name must not contain more than"
1644
0
      " one '@' character\n"));
1645
0
      goto fail;
1646
0
    }
1647
1648
0
  if(*s)
1649
0
    {
1650
0
      const char *i=s+1;
1651
0
      int highbit=0;
1652
1653
      /* we only support printable text - therefore we enforce the use
1654
   of only printable characters (an empty value is valid) */
1655
0
      for(s++; *s ; s++ )
1656
0
  {
1657
0
    if ( !isascii (*s) )
1658
0
      highbit=1;
1659
0
    else if (iscntrl(*s))
1660
0
      {
1661
0
        log_error(_("a notation value must not use any"
1662
0
        " control characters\n"));
1663
0
        goto fail;
1664
0
      }
1665
0
  }
1666
1667
0
      if(!highbit || is_utf8)
1668
0
  notation->value=xstrdup(i);
1669
0
      else
1670
0
  notation->value=native_to_utf8(i);
1671
0
    }
1672
1673
0
  return notation;
1674
1675
0
 fail:
1676
0
  free_notation(notation);
1677
0
  return NULL;
1678
0
}
1679
1680
1681
/* Turn the notation described by NAME and VALUE into a notation.
1682
 * This will be a human readble non-critical notation.
1683
 * The caller must free the result using free_notation().  */
1684
struct notation *
1685
name_value_to_notation (const char *name, const char *value)
1686
0
{
1687
0
  struct notation *notation;
1688
1689
0
  notation = xcalloc (1, sizeof *notation);
1690
0
  notation->name = xstrdup (name);
1691
0
  notation->value = xstrdup (value);
1692
0
  return notation;
1693
0
}
1694
1695
1696
/* Like string_to_notation, but store opaque data rather than human
1697
   readable data.  */
1698
struct notation *
1699
blob_to_notation(const char *name, const char *data, size_t len)
1700
0
{
1701
0
  const char *s;
1702
0
  int saw_at=0;
1703
0
  struct notation *notation;
1704
1705
0
  notation=xmalloc_clear(sizeof(*notation));
1706
1707
0
  if(*name=='-')
1708
0
    {
1709
0
      notation->flags.ignore=1;
1710
0
      name++;
1711
0
    }
1712
1713
0
  if(*name=='!')
1714
0
    {
1715
0
      notation->flags.critical=1;
1716
0
      name++;
1717
0
    }
1718
1719
  /* If and when the IETF assigns some official name tags, we'll have
1720
     to add them here. */
1721
1722
0
  for( s=name ; *s; s++ )
1723
0
    {
1724
0
      if( *s=='@')
1725
0
  saw_at++;
1726
1727
      /* -notationname is legal without an = sign */
1728
0
      if(!*s && notation->flags.ignore)
1729
0
  break;
1730
1731
0
      if (*s == '=')
1732
0
        {
1733
0
          log_error(_("a notation name may not contain an '=' character\n"));
1734
0
          goto fail;
1735
0
        }
1736
1737
0
      if (!isascii (*s) || (!isgraph(*s) && !isspace(*s)))
1738
0
  {
1739
0
    log_error(_("a notation name must have only printable characters"
1740
0
          " or spaces\n") );
1741
0
    goto fail;
1742
0
  }
1743
0
    }
1744
1745
0
  notation->name=xstrdup (name);
1746
1747
0
  if(!saw_at && !opt.expert)
1748
0
    {
1749
0
      log_error(_("a user notation name must contain the '@' character\n"));
1750
0
      goto fail;
1751
0
    }
1752
1753
0
  if (saw_at > 1)
1754
0
    {
1755
0
      log_error(_("a notation name must not contain more than"
1756
0
      " one '@' character\n"));
1757
0
      goto fail;
1758
0
    }
1759
1760
0
  notation->bdat = xmalloc (len);
1761
0
  memcpy (notation->bdat, data, len);
1762
0
  notation->blen = len;
1763
1764
0
  notation->value = notation_value_to_human_readable_string (notation);
1765
1766
0
  return notation;
1767
1768
0
 fail:
1769
0
  free_notation(notation);
1770
0
  return NULL;
1771
0
}
1772
1773
struct notation *
1774
sig_to_notation(PKT_signature *sig)
1775
0
{
1776
0
  const byte *p;
1777
0
  size_t len;
1778
0
  int seq = 0;
1779
0
  int crit;
1780
0
  notation_t list = NULL;
1781
1782
  /* See RFC 4880, 5.2.3.16 for the format of notation data.  In
1783
     short, a notation has:
1784
1785
       - 4 bytes of flags
1786
       - 2 byte name length (n1)
1787
       - 2 byte value length (n2)
1788
       - n1 bytes of name data
1789
       - n2 bytes of value data
1790
   */
1791
0
  while((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_NOTATION, &len, &seq, &crit)))
1792
0
    {
1793
0
      int n1,n2;
1794
0
      struct notation *n=NULL;
1795
1796
0
      if(len<8)
1797
0
  {
1798
0
    log_info(_("WARNING: invalid notation data found\n"));
1799
0
    continue;
1800
0
  }
1801
1802
      /* name length.  */
1803
0
      n1=(p[4]<<8)|p[5];
1804
      /* value length.  */
1805
0
      n2=(p[6]<<8)|p[7];
1806
1807
0
      if(8+n1+n2!=len)
1808
0
  {
1809
0
    log_info(_("WARNING: invalid notation data found\n"));
1810
0
    continue;
1811
0
  }
1812
1813
0
      n=xmalloc_clear(sizeof(*n));
1814
0
      n->name=xmalloc(n1+1);
1815
1816
0
      memcpy(n->name,&p[8],n1);
1817
0
      n->name[n1]='\0';
1818
1819
0
      if(p[0]&0x80)
1820
        /* The value is human-readable.  */
1821
0
  {
1822
0
    n->value=xmalloc(n2+1);
1823
0
    memcpy(n->value,&p[8+n1],n2);
1824
0
    n->value[n2]='\0';
1825
0
          n->flags.human = 1;
1826
0
  }
1827
0
      else
1828
        /* Binary data.  */
1829
0
  {
1830
0
    n->bdat=xmalloc(n2);
1831
0
    n->blen=n2;
1832
0
    memcpy(n->bdat,&p[8+n1],n2);
1833
1834
0
          n->value = notation_value_to_human_readable_string (n);
1835
0
  }
1836
1837
0
      n->flags.critical=crit;
1838
1839
0
      n->next=list;
1840
0
      list=n;
1841
0
    }
1842
1843
0
  return list;
1844
0
}
1845
1846
1847
/* Return a list of notation data matching NAME.  The caller needs to
1848
 * to free the list using free_notation.  Other than sig_to_notation
1849
 * this function does not return the notation in human readable format
1850
 * but always returns the raw data.  The human readable flag is set
1851
 * anyway set but .value is always NULL.  */
1852
struct notation *
1853
search_sig_notations (PKT_signature *sig, const char *name)
1854
0
{
1855
0
  const byte *p;
1856
0
  size_t len;
1857
0
  int seq = 0;
1858
0
  int crit;
1859
0
  notation_t list = NULL;
1860
1861
0
  while((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_NOTATION, &len, &seq, &crit)))
1862
0
    {
1863
0
      int n1,n2;
1864
0
      struct notation *n=NULL;
1865
1866
0
      if (len < 8)
1867
0
  {
1868
0
    log_info (_("WARNING: invalid notation data found\n"));
1869
0
    continue;
1870
0
  }
1871
1872
      /* name length.  */
1873
0
      n1=(p[4]<<8)|p[5];
1874
      /* value length.  */
1875
0
      n2=(p[6]<<8)|p[7];
1876
1877
0
      if (8 + n1 + n2 != len)
1878
0
  {
1879
0
    log_info (_("WARNING: invalid notation data found\n"));
1880
0
    continue;
1881
0
  }
1882
1883
0
      if (!name)
1884
0
        ; /* Return everything.  */
1885
0
      else if (n1 != strlen (name) || memcmp (p+8, name, n1))
1886
0
        continue; /* Not the requested name.  */
1887
1888
1889
0
      n = xmalloc_clear (sizeof *n);
1890
0
      n->name = xmalloc (n1+1);
1891
1892
0
      memcpy (n->name,p + 8, n1);
1893
0
      n->name[n1]='\0';
1894
1895
      /* In any case append a Nul. */
1896
0
      n->bdat = xmalloc (n2+1);
1897
0
      memcpy (n->bdat, p + 8 + n1, n2);
1898
0
      n->bdat[n2] = '\0';
1899
0
      n->blen = n2;
1900
0
      n->flags.human = !!(p[0] & 0x80);
1901
1902
0
      n->flags.critical = crit;
1903
1904
0
      n->next = list;
1905
0
      list = n;
1906
0
    }
1907
1908
0
  return list;
1909
0
}
1910
1911
1912
/* Release the resources associated with the *list* of notations.  To
1913
   release a single notation, make sure that notation->next is
1914
   NULL.  */
1915
void
1916
free_notation(struct notation *notation)
1917
0
{
1918
0
  while(notation)
1919
0
    {
1920
0
      struct notation *n=notation;
1921
1922
0
      xfree(n->name);
1923
0
      xfree(n->value);
1924
0
      xfree(n->altvalue);
1925
0
      xfree(n->bdat);
1926
0
      notation=n->next;
1927
0
      xfree(n);
1928
0
    }
1929
0
}
1930
1931
/* Serialize the signature packet (RFC 4880, Section 5.2) described by
1932
   SIG and write it to OUT.  */
1933
static int
1934
do_signature( IOBUF out, int ctb, PKT_signature *sig )
1935
6.37M
{
1936
6.37M
  int rc = 0;
1937
6.37M
  int n, i;
1938
6.37M
  IOBUF a = iobuf_temp();
1939
1940
6.37M
  log_assert (ctb_pkttype (ctb) == PKT_SIGNATURE);
1941
1942
6.37M
  if ( !sig->version || sig->version == 3)
1943
4.54k
    {
1944
4.54k
      iobuf_put( a, 3 );
1945
1946
      /* Version 3 packets don't support subpackets.  Actually we
1947
       * should never get to here but real life is different and thus
1948
       * we now use a log_fatal instead of a log_assert here. */
1949
4.54k
      if (sig->hashed || sig->unhashed)
1950
4.54k
        log_fatal ("trying to write a subpacket to a v3 signature (%d,%d)\n",
1951
0
                   !!sig->hashed, !!sig->unhashed);
1952
4.54k
    }
1953
6.37M
  else
1954
6.37M
    iobuf_put( a, sig->version );
1955
6.37M
  if ( sig->version < 4 )
1956
4.54k
    iobuf_put (a, 5 ); /* Constant used by pre-v4 signatures. */
1957
6.37M
  iobuf_put (a, sig->sig_class );
1958
6.37M
  if ( sig->version < 4 )
1959
4.54k
    {
1960
4.54k
      write_32(a, sig->timestamp );
1961
4.54k
      write_32(a, sig->keyid[0] );
1962
4.54k
      write_32(a, sig->keyid[1] );
1963
4.54k
    }
1964
6.37M
  iobuf_put(a, sig->pubkey_algo );
1965
6.37M
  iobuf_put(a, sig->digest_algo );
1966
6.37M
  if ( sig->version >= 4 )
1967
6.37M
    {
1968
6.37M
      size_t nn;
1969
      /* Timestamp and keyid must have been packed into the subpackets
1970
   prior to the call of this function, because these subpackets
1971
   are hashed. */
1972
6.37M
      nn = sig->hashed? sig->hashed->len : 0;
1973
6.37M
      write_16(a, nn);
1974
6.37M
      if (nn)
1975
6.37M
        iobuf_write( a, sig->hashed->data, nn );
1976
6.37M
      nn = sig->unhashed? sig->unhashed->len : 0;
1977
6.37M
      write_16(a, nn);
1978
6.37M
      if (nn)
1979
6.34M
        iobuf_write( a, sig->unhashed->data, nn );
1980
6.37M
    }
1981
6.37M
  iobuf_put(a, sig->digest_start[0] );
1982
6.37M
  iobuf_put(a, sig->digest_start[1] );
1983
6.37M
  n = pubkey_get_nsig( sig->pubkey_algo );
1984
6.37M
  if ( !n )
1985
66.3k
    write_fake_data( a, sig->data[0] );
1986
6.37M
  if (sig->pubkey_algo == PUBKEY_ALGO_ECDSA
1987
6.37M
      || sig->pubkey_algo == PUBKEY_ALGO_EDDSA)
1988
18.8M
    for (i=0; i < n && !rc ; i++ )
1989
12.5M
      rc = sos_write (a, sig->data[i], NULL);
1990
106k
  else
1991
147k
    for (i=0; i < n && !rc ; i++ )
1992
40.4k
      rc = gpg_mpi_write (a, sig->data[i], NULL);
1993
1994
6.37M
  if (!rc)
1995
6.37M
    {
1996
6.37M
      if ( is_RSA(sig->pubkey_algo) && sig->version < 4 )
1997
1.14k
        write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
1998
6.37M
      else
1999
6.37M
        write_header(out, ctb, iobuf_get_temp_length(a) );
2000
6.37M
      rc = iobuf_write_temp( out, a );
2001
6.37M
    }
2002
2003
6.37M
  iobuf_close(a);
2004
6.37M
  return rc;
2005
6.37M
}
2006
2007
2008
/* Serialize the one-pass signature packet (RFC 4880, Section 5.4)
2009
   described by OPS and write it to OUT.  */
2010
static int
2011
do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
2012
0
{
2013
0
    log_assert (ctb_pkttype (ctb) == PKT_ONEPASS_SIG);
2014
2015
0
    write_header(out, ctb, 4 + 8 + 1);
2016
2017
0
    iobuf_put (out, 3);  /* Version.  */
2018
0
    iobuf_put(out, ops->sig_class );
2019
0
    iobuf_put(out, ops->digest_algo );
2020
0
    iobuf_put(out, ops->pubkey_algo );
2021
0
    write_32(out, ops->keyid[0] );
2022
0
    write_32(out, ops->keyid[1] );
2023
0
    iobuf_put(out, ops->last );
2024
2025
0
    return 0;
2026
0
}
2027
2028
2029
/* Write a 16-bit quantity to OUT in big endian order.  */
2030
static int
2031
write_16(IOBUF out, u16 a)
2032
12.7M
{
2033
12.7M
    iobuf_put(out, a>>8);
2034
12.7M
    if( iobuf_put(out,a) )
2035
0
  return -1;
2036
12.7M
    return 0;
2037
12.7M
}
2038
2039
/* Write a 32-bit quantity to OUT in big endian order.  */
2040
static int
2041
write_32(IOBUF out, u32 a)
2042
319k
{
2043
319k
    iobuf_put(out, a>> 24);
2044
319k
    iobuf_put(out, a>> 16);
2045
319k
    iobuf_put(out, a>> 8);
2046
319k
    return iobuf_put(out, a);
2047
319k
}
2048
2049
2050
/****************
2051
 * calculate the length of a header.
2052
 *
2053
 * LEN is the length of the packet's body.  NEW_CTB is whether we are
2054
 * using a new or old format packet.
2055
 *
2056
 * This function does not handle indeterminate lengths or partial body
2057
 * lengths.  (If you pass LEN as 0, then this function assumes you
2058
 * really mean an empty body.)
2059
 */
2060
static int
2061
calc_header_length( u32 len, int new_ctb )
2062
0
{
2063
0
    if( new_ctb ) {
2064
0
  if( len < 192 )
2065
0
      return 2;
2066
0
  if( len < 8384 )
2067
0
      return 3;
2068
0
  else
2069
0
      return 6;
2070
0
    }
2071
0
    if( len < 256 )
2072
0
  return 2;
2073
0
    if( len < 65536 )
2074
0
  return 3;
2075
2076
0
    return 5;
2077
0
}
2078
2079
/****************
2080
 * Write the CTB and the packet length
2081
 */
2082
static int
2083
write_header( IOBUF out, int ctb, u32 len )
2084
12.7M
{
2085
12.7M
    return write_header2( out, ctb, len, 0 );
2086
12.7M
}
2087
2088
2089
static int
2090
write_sign_packet_header (IOBUF out, int ctb, u32 len)
2091
1.14k
{
2092
1.14k
  (void)ctb;
2093
2094
  /* Work around a bug in the pgp read function for signature packets,
2095
     which are not correctly coded and silently assume at some point 2
2096
     byte length headers.*/
2097
1.14k
  iobuf_put (out, 0x89 );
2098
1.14k
  iobuf_put (out, len >> 8 );
2099
1.14k
  return iobuf_put (out, len) == -1 ? -1:0;
2100
1.14k
}
2101
2102
/****************
2103
 * Write a packet header to OUT.
2104
 *
2105
 * CTB is the ctb.  It determines whether a new or old format packet
2106
 * header should be written.  The length field is adjusted, but the
2107
 * CTB is otherwise written out as is.
2108
 *
2109
 * LEN is the length of the packet's body.
2110
 *
2111
 * If HDRLEN is set, then we don't necessarily use the most efficient
2112
 * encoding to store LEN, but the specified length.  (If this is not
2113
 * possible, this is a bug.)  In this case, LEN=0 means a 0 length
2114
 * packet.  Note: setting HDRLEN is only supported for old format
2115
 * packets!
2116
 *
2117
 * If HDRLEN is not set, then the shortest encoding is used.  In this
2118
 * case, LEN=0 means the body has an indeterminate length and a
2119
 * partial body length header (if a new format packet) or an
2120
 * indeterminate length header (if an old format packet) is written
2121
 * out.  Further, if using partial body lengths, this enables partial
2122
 * body length mode on OUT.
2123
 */
2124
static int
2125
write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
2126
13.0M
{
2127
13.0M
  if (ctb_new_format_p (ctb))
2128
0
    return write_new_header( out, ctb, len, hdrlen );
2129
2130
  /* An old format packet.  Refer to RFC 4880, Section 4.2.1 to
2131
     understand how lengths are encoded in this case.  */
2132
2133
  /* The length encoding is stored in the two least significant bits.
2134
     Make sure they are cleared.  */
2135
13.0M
  log_assert ((ctb & 3) == 0);
2136
2137
13.0M
  log_assert (hdrlen == 0 || hdrlen == 2 || hdrlen == 3 || hdrlen == 5);
2138
2139
13.0M
  if (hdrlen)
2140
    /* Header length is given.  */
2141
0
    {
2142
0
      if( hdrlen == 2 && len < 256 )
2143
        /* 00 => 1 byte length.  */
2144
0
  ;
2145
0
      else if( hdrlen == 3 && len < 65536 )
2146
        /* 01 => 2 byte length.  If len < 256, this is not the most
2147
           compact encoding, but it is a correct encoding.  */
2148
0
  ctb |= 1;
2149
0
      else if (hdrlen == 5)
2150
        /* 10 => 4 byte length.  If len < 65536, this is not the most
2151
           compact encoding, but it is a correct encoding.  */
2152
0
  ctb |= 2;
2153
0
      else
2154
0
        log_bug ("Can't encode length=%d in a %d byte header!\n",
2155
0
                 len, hdrlen);
2156
0
    }
2157
13.0M
  else
2158
13.0M
    {
2159
13.0M
      if( !len )
2160
        /* 11 => Indeterminate length.  */
2161
0
  ctb |= 3;
2162
13.0M
      else if( len < 256 )
2163
        /* 00 => 1 byte length.  */
2164
13.0M
  ;
2165
4.40k
      else if( len < 65536 )
2166
        /* 01 => 2 byte length.  */
2167
4.40k
  ctb |= 1;
2168
0
      else
2169
        /* 10 => 4 byte length.  */
2170
0
  ctb |= 2;
2171
13.0M
    }
2172
2173
13.0M
  if( iobuf_put(out, ctb ) )
2174
0
    return -1;
2175
2176
13.0M
  if( len || hdrlen )
2177
13.0M
    {
2178
13.0M
      if( ctb & 2 )
2179
0
  {
2180
0
    if(iobuf_put(out, len >> 24 ))
2181
0
      return -1;
2182
0
    if(iobuf_put(out, len >> 16 ))
2183
0
      return -1;
2184
0
  }
2185
2186
13.0M
      if( ctb & 3 )
2187
4.40k
  if(iobuf_put(out, len >> 8 ))
2188
0
    return -1;
2189
2190
13.0M
      if( iobuf_put(out, len ) )
2191
0
  return -1;
2192
13.0M
    }
2193
2194
13.0M
  return 0;
2195
13.0M
}
2196
2197
2198
/* Write a new format header to OUT.
2199
2200
   CTB is the ctb.
2201
2202
   LEN is the length of the packet's body.  If LEN is 0, then enables
2203
   partial body length mode (i.e., the body is of an indeterminant
2204
   length) on OUT.  Note: this function cannot be used to generate a
2205
   header for a zero length packet.
2206
2207
   HDRLEN is the length of the packet's header.  If HDRLEN is 0, the
2208
   shortest encoding is chosen based on the length of the packet's
2209
   body.  Currently, values other than 0 are not supported.
2210
2211
   Returns 0 on success.  */
2212
static int
2213
write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
2214
0
{
2215
0
    if( hdrlen )
2216
0
  log_bug("can't cope with hdrlen yet\n");
2217
2218
0
    if( iobuf_put(out, ctb ) )
2219
0
  return -1;
2220
0
    if( !len ) {
2221
0
  iobuf_set_partial_body_length_mode(out, 512 );
2222
0
    }
2223
0
    else {
2224
0
  if( len < 192 ) {
2225
0
      if( iobuf_put(out, len ) )
2226
0
    return -1;
2227
0
  }
2228
0
  else if( len < 8384 ) {
2229
0
      len -= 192;
2230
0
      if( iobuf_put( out, (len / 256) + 192) )
2231
0
    return -1;
2232
0
      if( iobuf_put( out, (len % 256) )  )
2233
0
    return -1;
2234
0
  }
2235
0
  else {
2236
0
      if( iobuf_put( out, 0xff ) )
2237
0
    return -1;
2238
0
      if( iobuf_put( out, (len >> 24)&0xff ) )
2239
0
    return -1;
2240
0
      if( iobuf_put( out, (len >> 16)&0xff ) )
2241
0
    return -1;
2242
0
      if( iobuf_put( out, (len >> 8)&0xff )  )
2243
0
    return -1;
2244
0
      if( iobuf_put( out, len & 0xff ) )
2245
0
    return -1;
2246
0
  }
2247
0
    }
2248
0
    return 0;
2249
0
}