Coverage Report

Created: 2026-07-30 06:13

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
16.5M
{
63
  /* Bit 7 must always be set.  */
64
16.5M
  log_assert ((ctb & (1 << 7)));
65
  /* Bit 6 indicates whether the packet is a new format packet.  */
66
16.5M
  return (ctb & (1 << 6));
67
16.5M
}
68
69
/* Extract the packet type from a CTB.  */
70
static int
71
ctb_pkttype (int ctb)
72
5.82M
{
73
5.82M
  if (ctb_new_format_p (ctb))
74
    /* Bits 0 through 5 are the packet type.  */
75
0
    return (ctb & ((1 << 6) - 1));
76
5.82M
  else
77
    /* Bits 2 through 5 are the packet type.  */
78
5.82M
    return (ctb & ((1 << 6) - 1)) >> 2;
79
5.82M
}
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.49k
{
89
2.49k
  gpg_error_t err;
90
2.49k
  iobuf_t iobuf;
91
2.49k
  kbnode_t kbctx, node;
92
93
2.49k
  *r_iobuf = NULL;
94
95
2.49k
  iobuf = iobuf_temp ();
96
5.51M
  for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
97
5.51M
    {
98
      /* Make sure to use only packets valid on a keyblock.  */
99
5.51M
      switch (node->pkt->pkttype)
100
5.51M
        {
101
2.49k
        case PKT_PUBLIC_KEY:
102
316k
        case PKT_PUBLIC_SUBKEY:
103
5.50M
        case PKT_SIGNATURE:
104
5.51M
        case PKT_USER_ID:
105
5.51M
        case PKT_ATTRIBUTE:
106
5.51M
        case PKT_RING_TRUST:
107
5.51M
          break;
108
0
        default:
109
0
          continue;
110
5.51M
        }
111
112
5.51M
      err = build_packet_and_meta (iobuf, node->pkt);
113
5.51M
      if (err)
114
0
        {
115
0
          iobuf_close (iobuf);
116
0
          return err;
117
0
        }
118
5.51M
    }
119
120
2.49k
  *r_iobuf = iobuf;
121
2.49k
  return 0;
122
2.49k
}
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
5.51M
{
130
5.51M
  int rc = 0;
131
5.51M
  int new_ctb = 0;
132
5.51M
  int ctb, pkttype;
133
134
5.51M
  if (DBG_PACKET)
135
5.51M
    log_debug ("build_packet() type=%d\n", pkt->pkttype);
136
5.51M
  log_assert (pkt->pkt.generic);
137
138
5.51M
  switch ((pkttype = pkt->pkttype))
139
5.51M
    {
140
2.49k
    case PKT_PUBLIC_KEY:
141
2.49k
      if (pkt->pkt.public_key->seckey_info)
142
0
        pkttype = PKT_SECRET_KEY;
143
2.49k
      break;
144
314k
    case PKT_PUBLIC_SUBKEY:
145
314k
      if (pkt->pkt.public_key->seckey_info)
146
0
        pkttype = PKT_SECRET_SUBKEY;
147
314k
      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
4.73k
    case PKT_USER_ID:
160
4.73k
      if (pkt->pkt.user_id->attrib_data)
161
0
        pkttype = PKT_ATTRIBUTE;
162
4.73k
      break;
163
5.18M
    default:
164
5.18M
      break;
165
5.51M
    }
166
167
5.51M
  if (new_ctb || pkttype > 15) /* new format */
168
0
    ctb = (0xc0 | (pkttype & 0x3f));
169
5.51M
  else
170
5.51M
    ctb = (0x80 | ((pkttype & 15)<<2));
171
5.51M
  switch (pkttype)
172
5.51M
    {
173
0
    case PKT_ATTRIBUTE:
174
4.73k
    case PKT_USER_ID:
175
4.73k
      rc = do_user_id (out, ctb, pkt->pkt.user_id);
176
4.73k
      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
314k
    case PKT_PUBLIC_SUBKEY:
186
316k
    case PKT_PUBLIC_KEY:
187
316k
    case PKT_SECRET_SUBKEY:
188
316k
    case PKT_SECRET_KEY:
189
316k
      rc = do_key (out, ctb, pkt->pkt.public_key);
190
316k
      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
5.18M
    case PKT_SIGNATURE:
213
5.18M
      rc = do_signature (out, ctb, pkt->pkt.signature);
214
5.18M
      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
5.51M
    }
227
228
5.51M
  return rc;
229
5.51M
}
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
5.51M
{
238
5.51M
  gpg_error_t err;
239
5.51M
  PKT_ring_trust rt = {0};
240
241
5.51M
  err = build_packet (out, pkt);
242
5.51M
  if (err)
243
0
    ;
244
5.51M
  else if (pkt->pkttype == PKT_SIGNATURE)
245
5.18M
    {
246
5.18M
      PKT_signature *sig = pkt->pkt.signature;
247
248
5.18M
      rt.subtype = RING_TRUST_SIG;
249
      /* Note: trustval is not yet used.  */
250
5.18M
      if (sig->flags.checked)
251
2.97M
        {
252
2.97M
          rt.sigcache = 1;
253
2.97M
          if (sig->flags.valid)
254
2.80M
            rt.sigcache |= 2;
255
2.97M
        }
256
5.18M
      err = do_ring_trust (out, &rt);
257
5.18M
    }
258
321k
  else if (pkt->pkttype == PKT_USER_ID
259
316k
           || pkt->pkttype == PKT_ATTRIBUTE)
260
4.73k
    {
261
4.73k
      PKT_user_id *uid = pkt->pkt.user_id;
262
263
4.73k
      rt.subtype = RING_TRUST_UID;
264
4.73k
      rt.keyorg = uid->keyorg;
265
4.73k
      rt.keyupdate = uid->keyupdate;
266
4.73k
      rt.url = uid->updateurl;
267
4.73k
      err = do_ring_trust (out, &rt);
268
4.73k
      rt.url = NULL;
269
4.73k
    }
270
316k
  else if (pkt->pkttype == PKT_PUBLIC_KEY
271
314k
           || pkt->pkttype == PKT_SECRET_KEY)
272
2.49k
    {
273
2.49k
      PKT_public_key *pk = pkt->pkt.public_key;
274
275
2.49k
      rt.subtype = RING_TRUST_KEY;
276
2.49k
      rt.keyorg = pk->keyorg;
277
2.49k
      rt.keyupdate = pk->keyupdate;
278
2.49k
      rt.url = pk->updateurl;
279
2.49k
      err = do_ring_trust (out, &rt);
280
2.49k
      rt.url = NULL;
281
282
2.49k
    }
283
284
5.51M
  return err;
285
5.51M
}
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
52.4k
{
296
52.4k
  gpg_error_t err;
297
52.4k
  unsigned int nwritten = 0;
298
299
52.4k
  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
52.4k
  else
341
52.4k
    {
342
52.4k
      char buffer[(MAX_EXTERN_MPI_BITS+7)/8+2]; /* 2 is for the mpi length. */
343
52.4k
      size_t nbytes;
344
345
52.4k
      nbytes = DIM(buffer);
346
52.4k
      err = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
347
52.4k
      if (!err)
348
52.4k
        {
349
52.4k
          err = out? iobuf_write (out, buffer, nbytes) : 0;
350
52.4k
          if (!err)
351
52.4k
            nwritten += nbytes;
352
52.4k
        }
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
52.4k
    }
361
362
52.4k
  if (r_nwritten)
363
0
    *r_nwritten = nwritten;
364
52.4k
  return err;
365
52.4k
}
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
10.5M
{
377
10.5M
  gpg_error_t err;
378
10.5M
  unsigned int nwritten = 0;
379
380
10.5M
  if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
381
10.5M
    {
382
10.5M
      unsigned int nbits;
383
10.5M
      const unsigned char *p;
384
10.5M
      unsigned char lenhdr[2];
385
386
      /* gcry_log_debugmpi ("a", a); */
387
10.5M
      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
10.5M
      if (p && *p)
392
10.5M
        {
393
10.5M
          nbits = ((nbits + 7) / 8) * 8;
394
395
10.5M
          if (nbits >= 8 && !(*p & 0x80))
396
8.64M
            if (--nbits >= 7 && !(*p & 0x40))
397
2.47M
              if (--nbits >= 6 && !(*p & 0x20))
398
2.06M
                if (--nbits >= 5 && !(*p & 0x10))
399
123k
                  if (--nbits >= 4 && !(*p & 0x08))
400
36.5k
                    if (--nbits >= 3 && !(*p & 0x04))
401
36.2k
                      if (--nbits >= 2 && !(*p & 0x02))
402
25.8k
                        if (--nbits >= 1 && !(*p & 0x01))
403
0
                          --nbits;
404
10.5M
        }
405
406
10.5M
      lenhdr[0] = nbits >> 8;
407
10.5M
      lenhdr[1] = nbits;
408
10.5M
      err = out? iobuf_write (out, lenhdr, 2) : 0;
409
10.5M
      if (!err)
410
10.5M
        {
411
10.5M
          nwritten += 2;
412
10.5M
          if (p)
413
10.5M
            {
414
10.5M
              err = out? iobuf_write (out, p, (nbits+7)/8) : 0;
415
10.5M
              if (!err)
416
10.5M
                nwritten += (nbits+7)/8;
417
10.5M
            }
418
10.5M
        }
419
10.5M
    }
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
10.5M
  if (r_nwritten)
427
0
    *r_nwritten = nwritten;
428
10.5M
  return err;
429
10.5M
}
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
630k
{
438
630k
  int rc;
439
440
630k
  if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
441
630k
    {
442
630k
      unsigned int nbits;
443
630k
      const void *p;
444
445
630k
      p = gcry_mpi_get_opaque (a, &nbits);
446
630k
      rc = p ? iobuf_write (out, p, (nbits+7)/8) : 0;
447
630k
    }
448
0
  else
449
0
    rc = gpg_error (GPG_ERR_BAD_MPI);
450
451
630k
  return rc;
452
630k
}
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
42.1k
{
533
42.1k
  unsigned int n;
534
42.1k
  void *p;
535
536
42.1k
  if (!a)
537
80
    return 0;
538
42.0k
  if (!gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
539
0
    return 0; /* e.g. due to generating a key with wrong usage.  */
540
42.0k
  p = gcry_mpi_get_opaque ( a, &n);
541
42.0k
  if (!p)
542
41.5k
    return 0; /* For example due to a read error in
543
                 parse-packet.c:read_rest.  */
544
484
  return iobuf_write (out, p, (n+7)/8 );
545
42.0k
}
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
5.19M
{
552
5.19M
  unsigned int namelen = 0;
553
5.19M
  unsigned int pktlen = 6;
554
555
5.19M
  if (rt->subtype == RING_TRUST_KEY || rt->subtype == RING_TRUST_UID)
556
7.23k
    {
557
7.23k
      if (rt->url)
558
0
        namelen = strlen (rt->url);
559
7.23k
      pktlen += 1 + 4 + 1 + namelen;
560
7.23k
    }
561
562
5.19M
  write_header (out, (0x80 | ((PKT_RING_TRUST & 15)<<2)), pktlen);
563
5.19M
  iobuf_put (out, rt->trustval);
564
5.19M
  iobuf_put (out, rt->sigcache);
565
5.19M
  iobuf_write (out, "gpg", 3);
566
5.19M
  iobuf_put (out, rt->subtype);
567
5.19M
  if (rt->subtype == RING_TRUST_KEY || rt->subtype == RING_TRUST_UID)
568
7.23k
    {
569
7.23k
      iobuf_put (out, rt->keyorg);
570
7.23k
      write_32 (out, rt->keyupdate);
571
7.23k
      iobuf_put (out, namelen);
572
7.23k
      if (namelen)
573
0
        iobuf_write (out, rt->url, namelen);
574
7.23k
    }
575
576
5.19M
  return 0;
577
5.19M
}
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
4.73k
{
588
4.73k
  int rc;
589
4.73k
  int hdrlen;
590
591
4.73k
  log_assert (ctb_pkttype (ctb) == PKT_USER_ID
592
4.73k
              || 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
4.73k
  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
4.73k
  else
610
4.73k
    {
611
4.73k
      if (uid->len > MAX_UID_PACKET_LENGTH - 10)
612
0
        return gpg_error (GPG_ERR_TOO_LARGE);
613
4.73k
      hdrlen = uid->len? 0 : 2;
614
4.73k
      write_header2 (out, ctb, uid->len, hdrlen);
615
4.73k
      rc = iobuf_write( out, uid->name, uid->len );
616
4.73k
    }
617
4.73k
  return rc;
618
4.73k
}
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
316k
{
637
316k
  gpg_error_t err = 0;
638
316k
  iobuf_t a;
639
316k
  int i, nskey, npkey;
640
316k
  u32 pkbytes = 0;
641
316k
  int is_v5;
642
643
316k
  log_assert (pk->version == 0 || pk->version == 4 || pk->version == 5);
644
316k
  log_assert (ctb_pkttype (ctb) == PKT_PUBLIC_KEY
645
316k
              || ctb_pkttype (ctb) == PKT_PUBLIC_SUBKEY
646
316k
              || ctb_pkttype (ctb) == PKT_SECRET_KEY
647
316k
              || 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
316k
  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
316k
  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
316k
  nskey = pubkey_get_nskey (pk->pubkey_algo);
665
316k
  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
316k
  if (!npkey)
671
0
    {
672
0
      write_fake_data (a, pk->pkey[0]);
673
0
      goto leave;
674
0
    }
675
316k
  log_assert (npkey < nskey);
676
677
1.26M
  for (i=0; i < npkey; i++ )
678
948k
    {
679
948k
      if (   (pk->pubkey_algo == PUBKEY_ALGO_ECDSA && (i == 0))
680
948k
          || (pk->pubkey_algo == PUBKEY_ALGO_EDDSA && (i == 0))
681
945k
          || (pk->pubkey_algo == PUBKEY_ALGO_ECDH  && (i == 0 || i == 2))
682
317k
          || (pk->pubkey_algo == PUBKEY_ALGO_KYBER && (i == 0)))
683
630k
        err = gpg_mpi_write_opaque_nohdr (a, pk->pkey[i]);
684
317k
      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
317k
      else if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
690
317k
               || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
691
314k
               || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
692
316k
        err = sos_write (a, pk->pkey[i], NULL);
693
500
      else
694
500
        err = gpg_mpi_write (a, pk->pkey[i], NULL);
695
948k
      if (err)
696
0
        goto leave;
697
948k
    }
698
699
  /* Record the length of the public key part.  */
700
316k
  pkbytes = iobuf_get_temp_length (a);
701
702
316k
  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
316k
 leave:
878
316k
  if (!err)
879
316k
    {
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
316k
      u32 len = iobuf_get_temp_length (a);
884
316k
      len += 1; /* version number  */
885
316k
      len += 4; /* timestamp  */
886
316k
      len += 1; /* algo  */
887
316k
      if (is_v5)
888
2
        len += 4; /* public key material count  */
889
890
316k
      write_header2 (out, ctb, len, 0);
891
       /* And finally write it out to the real stream. */
892
316k
      iobuf_put (out, pk->version? pk->version : 4); /* version number  */
893
316k
      write_32 (out, pk->timestamp );
894
316k
      iobuf_put (out, pk->pubkey_algo);  /* algo */
895
316k
      if (is_v5)
896
2
        write_32 (out, pkbytes);        /* public key material count  */
897
316k
      err = iobuf_write_temp (out, a);  /* pub and sec key material */
898
316k
    }
899
900
316k
  iobuf_close (a); /* Close the temporary buffer */
901
316k
  return err;
902
316k
}
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
1504
    /* Add fpr of the to-be-revoked key in an intended recipient fpr subpacket. */
1505
0
    if (IS_KEY_REV (sig))
1506
0
      {
1507
0
        log_assert (sizeof buf >= sig->rev_subject_info->fprlen + 1);
1508
1509
0
        buf[0] = sig->rev_subject_info->fprlen == 20? 4:
1510
0
          sig->rev_subject_info->fprlen == 32? 5 : 0;
1511
1512
0
        if (buf[0] == 4 || buf[0] == 5)
1513
0
          {
1514
0
            memcpy (buf+1, sig->rev_subject_info->fpr,
1515
0
                    sig->rev_subject_info->fprlen);
1516
0
            build_sig_subpkt (sig, SIGSUBPKT_INT_RCP_FPR,
1517
0
                              buf, sig->rev_subject_info->fprlen + 1);
1518
0
          }
1519
0
      }
1520
0
}
1521
1522
void
1523
build_attribute_subpkt(PKT_user_id *uid,byte type,
1524
           const void *buf,u32 buflen,
1525
           const void *header,u32 headerlen)
1526
0
{
1527
0
  byte *attrib;
1528
0
  int idx;
1529
1530
0
  if(1+headerlen+buflen>8383)
1531
0
    idx=5;
1532
0
  else if(1+headerlen+buflen>191)
1533
0
    idx=2;
1534
0
  else
1535
0
    idx=1;
1536
1537
  /* realloc uid->attrib_data to the right size */
1538
1539
0
  uid->attrib_data=xrealloc(uid->attrib_data,
1540
0
           uid->attrib_len+idx+1+headerlen+buflen);
1541
1542
0
  attrib=&uid->attrib_data[uid->attrib_len];
1543
1544
0
  if(idx==5)
1545
0
    {
1546
0
      attrib[0]=255;
1547
0
      attrib[1]=(1+headerlen+buflen) >> 24;
1548
0
      attrib[2]=(1+headerlen+buflen) >> 16;
1549
0
      attrib[3]=(1+headerlen+buflen) >> 8;
1550
0
      attrib[4]=1+headerlen+buflen;
1551
0
    }
1552
0
  else if(idx==2)
1553
0
    {
1554
0
      attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
1555
0
      attrib[1]=(1+headerlen+buflen-192) % 256;
1556
0
    }
1557
0
  else
1558
0
    attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
1559
1560
0
  attrib[idx++]=type;
1561
1562
  /* Tack on our data at the end */
1563
1564
0
  if(headerlen>0)
1565
0
    memcpy(&attrib[idx],header,headerlen);
1566
0
  memcpy(&attrib[idx+headerlen],buf,buflen);
1567
0
  uid->attrib_len+=idx+headerlen+buflen;
1568
0
}
1569
1570
/* Returns a human-readable string corresponding to the notation.
1571
   This ignores notation->value.  The caller must free the result.  */
1572
static char *
1573
notation_value_to_human_readable_string (struct notation *notation)
1574
0
{
1575
0
  if(notation->bdat)
1576
    /* Binary data.  */
1577
0
    {
1578
0
      size_t len = notation->blen;
1579
0
      int i;
1580
0
      char preview[20];
1581
1582
0
      for (i = 0; i < len && i < sizeof (preview) - 1; i ++)
1583
0
        if (isprint (notation->bdat[i]))
1584
0
          preview[i] = notation->bdat[i];
1585
0
        else
1586
0
          preview[i] = '?';
1587
0
      preview[i] = 0;
1588
1589
0
      return xasprintf (_("[ not human readable (%zu bytes: %s%s) ]"),
1590
0
                        len, preview, i < len ? "..." : "");
1591
0
    }
1592
0
  else
1593
    /* The value is human-readable.  */
1594
0
    return xstrdup (notation->value);
1595
0
}
1596
1597
1598
/* Turn the notation described by the string STRING into a notation.
1599
 *
1600
 * STRING has the form:
1601
 *
1602
 *   - -name - Delete the notation.
1603
 *   - name@domain.name=value - Normal notation
1604
 *   - !name@domain.name=value - Notation with critical bit set.
1605
 *
1606
 * The caller must free the result using free_notation().  */
1607
struct notation *
1608
string_to_notation (const char *string, int is_utf8)
1609
0
{
1610
0
  const char *s;
1611
0
  int saw_at=0;
1612
0
  struct notation *notation;
1613
1614
0
  notation=xmalloc_clear(sizeof(*notation));
1615
1616
0
  if(*string=='-')
1617
0
    {
1618
0
      notation->flags.ignore=1;
1619
0
      string++;
1620
0
    }
1621
1622
0
  if(*string=='!')
1623
0
    {
1624
0
      notation->flags.critical=1;
1625
0
      string++;
1626
0
    }
1627
1628
  /* If and when the IETF assigns some official name tags, we'll have
1629
     to add them here. */
1630
1631
0
  for( s=string ; *s != '='; s++ )
1632
0
    {
1633
0
      if( *s=='@')
1634
0
  saw_at++;
1635
1636
      /* -notationname is legal without an = sign */
1637
0
      if(!*s && notation->flags.ignore)
1638
0
  break;
1639
1640
0
      if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
1641
0
  {
1642
0
    log_error(_("a notation name must have only printable characters"
1643
0
          " or spaces, and end with an '='\n") );
1644
0
    goto fail;
1645
0
  }
1646
0
    }
1647
1648
0
  notation->name=xmalloc((s-string)+1);
1649
0
  memcpy(notation->name,string,s-string);
1650
0
  notation->name[s-string]='\0';
1651
1652
0
  if(!saw_at && !opt.expert)
1653
0
    {
1654
0
      log_error(_("a user notation name must contain the '@' character\n"));
1655
0
      goto fail;
1656
0
    }
1657
1658
0
  if (saw_at > 1)
1659
0
    {
1660
0
      log_error(_("a notation name must not contain more than"
1661
0
      " one '@' character\n"));
1662
0
      goto fail;
1663
0
    }
1664
1665
0
  if(*s)
1666
0
    {
1667
0
      const char *i=s+1;
1668
0
      int highbit=0;
1669
1670
      /* we only support printable text - therefore we enforce the use
1671
   of only printable characters (an empty value is valid) */
1672
0
      for(s++; *s ; s++ )
1673
0
  {
1674
0
    if ( !isascii (*s) )
1675
0
      highbit=1;
1676
0
    else if (iscntrl(*s))
1677
0
      {
1678
0
        log_error(_("a notation value must not use any"
1679
0
        " control characters\n"));
1680
0
        goto fail;
1681
0
      }
1682
0
  }
1683
1684
0
      if(!highbit || is_utf8)
1685
0
  notation->value=xstrdup(i);
1686
0
      else
1687
0
  notation->value=native_to_utf8(i);
1688
0
    }
1689
1690
0
  return notation;
1691
1692
0
 fail:
1693
0
  free_notation(notation);
1694
0
  return NULL;
1695
0
}
1696
1697
1698
/* Turn the notation described by NAME and VALUE into a notation.
1699
 * This will be a human readble non-critical notation.
1700
 * The caller must free the result using free_notation().  */
1701
struct notation *
1702
name_value_to_notation (const char *name, const char *value)
1703
0
{
1704
0
  struct notation *notation;
1705
1706
0
  notation = xcalloc (1, sizeof *notation);
1707
0
  notation->name = xstrdup (name);
1708
0
  notation->value = xstrdup (value);
1709
0
  return notation;
1710
0
}
1711
1712
1713
/* Like string_to_notation, but store opaque data rather than human
1714
   readable data.  */
1715
struct notation *
1716
blob_to_notation(const char *name, const char *data, size_t len)
1717
0
{
1718
0
  const char *s;
1719
0
  int saw_at=0;
1720
0
  struct notation *notation;
1721
1722
0
  notation=xmalloc_clear(sizeof(*notation));
1723
1724
0
  if(*name=='-')
1725
0
    {
1726
0
      notation->flags.ignore=1;
1727
0
      name++;
1728
0
    }
1729
1730
0
  if(*name=='!')
1731
0
    {
1732
0
      notation->flags.critical=1;
1733
0
      name++;
1734
0
    }
1735
1736
  /* If and when the IETF assigns some official name tags, we'll have
1737
     to add them here. */
1738
1739
0
  for( s=name ; *s; s++ )
1740
0
    {
1741
0
      if( *s=='@')
1742
0
  saw_at++;
1743
1744
      /* -notationname is legal without an = sign */
1745
0
      if(!*s && notation->flags.ignore)
1746
0
  break;
1747
1748
0
      if (*s == '=')
1749
0
        {
1750
0
          log_error(_("a notation name may not contain an '=' character\n"));
1751
0
          goto fail;
1752
0
        }
1753
1754
0
      if (!isascii (*s) || (!isgraph(*s) && !isspace(*s)))
1755
0
  {
1756
0
    log_error(_("a notation name must have only printable characters"
1757
0
          " or spaces\n") );
1758
0
    goto fail;
1759
0
  }
1760
0
    }
1761
1762
0
  notation->name=xstrdup (name);
1763
1764
0
  if(!saw_at && !opt.expert)
1765
0
    {
1766
0
      log_error(_("a user notation name must contain the '@' character\n"));
1767
0
      goto fail;
1768
0
    }
1769
1770
0
  if (saw_at > 1)
1771
0
    {
1772
0
      log_error(_("a notation name must not contain more than"
1773
0
      " one '@' character\n"));
1774
0
      goto fail;
1775
0
    }
1776
1777
0
  notation->bdat = xmalloc (len);
1778
0
  memcpy (notation->bdat, data, len);
1779
0
  notation->blen = len;
1780
1781
0
  notation->value = notation_value_to_human_readable_string (notation);
1782
1783
0
  return notation;
1784
1785
0
 fail:
1786
0
  free_notation(notation);
1787
0
  return NULL;
1788
0
}
1789
1790
struct notation *
1791
sig_to_notation(PKT_signature *sig)
1792
0
{
1793
0
  const byte *p;
1794
0
  size_t len;
1795
0
  int seq = 0;
1796
0
  int crit;
1797
0
  notation_t list = NULL;
1798
1799
  /* See RFC 4880, 5.2.3.16 for the format of notation data.  In
1800
     short, a notation has:
1801
1802
       - 4 bytes of flags
1803
       - 2 byte name length (n1)
1804
       - 2 byte value length (n2)
1805
       - n1 bytes of name data
1806
       - n2 bytes of value data
1807
   */
1808
0
  while((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_NOTATION, &len, &seq, &crit)))
1809
0
    {
1810
0
      int n1,n2;
1811
0
      struct notation *n=NULL;
1812
1813
0
      if(len<8)
1814
0
  {
1815
0
    log_info(_("WARNING: invalid notation data found\n"));
1816
0
    continue;
1817
0
  }
1818
1819
      /* name length.  */
1820
0
      n1=(p[4]<<8)|p[5];
1821
      /* value length.  */
1822
0
      n2=(p[6]<<8)|p[7];
1823
1824
0
      if(8+n1+n2!=len)
1825
0
  {
1826
0
    log_info(_("WARNING: invalid notation data found\n"));
1827
0
    continue;
1828
0
  }
1829
1830
0
      n=xmalloc_clear(sizeof(*n));
1831
0
      n->name=xmalloc(n1+1);
1832
1833
0
      memcpy(n->name,&p[8],n1);
1834
0
      n->name[n1]='\0';
1835
1836
0
      if(p[0]&0x80)
1837
        /* The value is human-readable.  */
1838
0
  {
1839
0
    n->value=xmalloc(n2+1);
1840
0
    memcpy(n->value,&p[8+n1],n2);
1841
0
    n->value[n2]='\0';
1842
0
          n->flags.human = 1;
1843
0
  }
1844
0
      else
1845
        /* Binary data.  */
1846
0
  {
1847
0
    n->bdat=xmalloc(n2);
1848
0
    n->blen=n2;
1849
0
    memcpy(n->bdat,&p[8+n1],n2);
1850
1851
0
          n->value = notation_value_to_human_readable_string (n);
1852
0
  }
1853
1854
0
      n->flags.critical=crit;
1855
1856
0
      n->next=list;
1857
0
      list=n;
1858
0
    }
1859
1860
0
  return list;
1861
0
}
1862
1863
1864
/* Return a list of notation data matching NAME.  The caller needs to
1865
 * to free the list using free_notation.  Other than sig_to_notation
1866
 * this function does not return the notation in human readable format
1867
 * but always returns the raw data.  The human readable flag is set
1868
 * anyway set but .value is always NULL.  */
1869
struct notation *
1870
search_sig_notations (PKT_signature *sig, const char *name)
1871
0
{
1872
0
  const byte *p;
1873
0
  size_t len;
1874
0
  int seq = 0;
1875
0
  int crit;
1876
0
  notation_t list = NULL;
1877
1878
0
  while((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_NOTATION, &len, &seq, &crit)))
1879
0
    {
1880
0
      int n1,n2;
1881
0
      struct notation *n=NULL;
1882
1883
0
      if (len < 8)
1884
0
  {
1885
0
    log_info (_("WARNING: invalid notation data found\n"));
1886
0
    continue;
1887
0
  }
1888
1889
      /* name length.  */
1890
0
      n1=(p[4]<<8)|p[5];
1891
      /* value length.  */
1892
0
      n2=(p[6]<<8)|p[7];
1893
1894
0
      if (8 + n1 + n2 != len)
1895
0
  {
1896
0
    log_info (_("WARNING: invalid notation data found\n"));
1897
0
    continue;
1898
0
  }
1899
1900
0
      if (!name)
1901
0
        ; /* Return everything.  */
1902
0
      else if (n1 != strlen (name) || memcmp (p+8, name, n1))
1903
0
        continue; /* Not the requested name.  */
1904
1905
1906
0
      n = xmalloc_clear (sizeof *n);
1907
0
      n->name = xmalloc (n1+1);
1908
1909
0
      memcpy (n->name,p + 8, n1);
1910
0
      n->name[n1]='\0';
1911
1912
      /* In any case append a Nul. */
1913
0
      n->bdat = xmalloc (n2+1);
1914
0
      memcpy (n->bdat, p + 8 + n1, n2);
1915
0
      n->bdat[n2] = '\0';
1916
0
      n->blen = n2;
1917
0
      n->flags.human = !!(p[0] & 0x80);
1918
1919
0
      n->flags.critical = crit;
1920
1921
0
      n->next = list;
1922
0
      list = n;
1923
0
    }
1924
1925
0
  return list;
1926
0
}
1927
1928
1929
/* Release the resources associated with the *list* of notations.  To
1930
   release a single notation, make sure that notation->next is
1931
   NULL.  */
1932
void
1933
free_notation(struct notation *notation)
1934
0
{
1935
0
  while(notation)
1936
0
    {
1937
0
      struct notation *n=notation;
1938
1939
0
      xfree(n->name);
1940
0
      xfree(n->value);
1941
0
      xfree(n->altvalue);
1942
0
      xfree(n->bdat);
1943
0
      notation=n->next;
1944
0
      xfree(n);
1945
0
    }
1946
0
}
1947
1948
/* Serialize the signature packet (RFC 4880, Section 5.2) described by
1949
   SIG and write it to OUT.  */
1950
static int
1951
do_signature( IOBUF out, int ctb, PKT_signature *sig )
1952
5.18M
{
1953
5.18M
  int rc = 0;
1954
5.18M
  int n, i;
1955
5.18M
  IOBUF a = iobuf_temp();
1956
1957
5.18M
  log_assert (ctb_pkttype (ctb) == PKT_SIGNATURE);
1958
1959
5.18M
  if ( !sig->version || sig->version == 3)
1960
4.46k
    {
1961
4.46k
      iobuf_put( a, 3 );
1962
1963
      /* Version 3 packets don't support subpackets.  Actually we
1964
       * should never get to here but real life is different and thus
1965
       * we now use a log_fatal instead of a log_assert here. */
1966
4.46k
      if (sig->hashed || sig->unhashed)
1967
4.46k
        log_fatal ("trying to write a subpacket to a v3 signature (%d,%d)\n",
1968
0
                   !!sig->hashed, !!sig->unhashed);
1969
4.46k
    }
1970
5.18M
  else
1971
5.18M
    iobuf_put( a, sig->version );
1972
5.18M
  if ( sig->version < 4 )
1973
4.46k
    iobuf_put (a, 5 ); /* Constant used by pre-v4 signatures. */
1974
5.18M
  iobuf_put (a, sig->sig_class );
1975
5.18M
  if ( sig->version < 4 )
1976
4.46k
    {
1977
4.46k
      write_32(a, sig->timestamp );
1978
4.46k
      write_32(a, sig->keyid[0] );
1979
4.46k
      write_32(a, sig->keyid[1] );
1980
4.46k
    }
1981
5.18M
  iobuf_put(a, sig->pubkey_algo );
1982
5.18M
  iobuf_put(a, sig->digest_algo );
1983
5.18M
  if ( sig->version >= 4 )
1984
5.18M
    {
1985
5.18M
      size_t nn;
1986
      /* Timestamp and keyid must have been packed into the subpackets
1987
   prior to the call of this function, because these subpackets
1988
   are hashed. */
1989
5.18M
      nn = sig->hashed? sig->hashed->len : 0;
1990
5.18M
      write_16(a, nn);
1991
5.18M
      if (nn)
1992
5.18M
        iobuf_write( a, sig->hashed->data, nn );
1993
5.18M
      nn = sig->unhashed? sig->unhashed->len : 0;
1994
5.18M
      write_16(a, nn);
1995
5.18M
      if (nn)
1996
5.17M
        iobuf_write( a, sig->unhashed->data, nn );
1997
5.18M
    }
1998
5.18M
  iobuf_put(a, sig->digest_start[0] );
1999
5.18M
  iobuf_put(a, sig->digest_start[1] );
2000
5.18M
  n = pubkey_get_nsig( sig->pubkey_algo );
2001
5.18M
  if ( !n )
2002
42.1k
    write_fake_data( a, sig->data[0] );
2003
5.18M
  if (sig->pubkey_algo == PUBKEY_ALGO_ECDSA
2004
5.06M
      || sig->pubkey_algo == PUBKEY_ALGO_EDDSA)
2005
15.2M
    for (i=0; i < n && !rc ; i++ )
2006
10.1M
      rc = sos_write (a, sig->data[i], NULL);
2007
94.0k
  else
2008
146k
    for (i=0; i < n && !rc ; i++ )
2009
51.9k
      rc = gpg_mpi_write (a, sig->data[i], NULL);
2010
2011
5.18M
  if (!rc)
2012
5.18M
    {
2013
5.18M
      if ( is_RSA(sig->pubkey_algo) && sig->version < 4 )
2014
810
        write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
2015
5.18M
      else
2016
5.18M
        write_header(out, ctb, iobuf_get_temp_length(a) );
2017
5.18M
      rc = iobuf_write_temp( out, a );
2018
5.18M
    }
2019
2020
5.18M
  iobuf_close(a);
2021
5.18M
  return rc;
2022
5.18M
}
2023
2024
2025
/* Serialize the one-pass signature packet (RFC 4880, Section 5.4)
2026
   described by OPS and write it to OUT.  */
2027
static int
2028
do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
2029
0
{
2030
0
    log_assert (ctb_pkttype (ctb) == PKT_ONEPASS_SIG);
2031
2032
0
    write_header(out, ctb, 4 + 8 + 1);
2033
2034
0
    iobuf_put (out, 3);  /* Version.  */
2035
0
    iobuf_put(out, ops->sig_class );
2036
0
    iobuf_put(out, ops->digest_algo );
2037
0
    iobuf_put(out, ops->pubkey_algo );
2038
0
    write_32(out, ops->keyid[0] );
2039
0
    write_32(out, ops->keyid[1] );
2040
0
    iobuf_put(out, ops->last );
2041
2042
0
    return 0;
2043
0
}
2044
2045
2046
/* Write a 16-bit quantity to OUT in big endian order.  */
2047
static int
2048
write_16(IOBUF out, u16 a)
2049
10.3M
{
2050
10.3M
    iobuf_put(out, a>>8);
2051
10.3M
    if( iobuf_put(out,a) )
2052
0
  return -1;
2053
10.3M
    return 0;
2054
10.3M
}
2055
2056
/* Write a 32-bit quantity to OUT in big endian order.  */
2057
static int
2058
write_32(IOBUF out, u32 a)
2059
337k
{
2060
337k
    iobuf_put(out, a>> 24);
2061
337k
    iobuf_put(out, a>> 16);
2062
337k
    iobuf_put(out, a>> 8);
2063
337k
    return iobuf_put(out, a);
2064
337k
}
2065
2066
2067
/****************
2068
 * calculate the length of a header.
2069
 *
2070
 * LEN is the length of the packet's body.  NEW_CTB is whether we are
2071
 * using a new or old format packet.
2072
 *
2073
 * This function does not handle indeterminate lengths or partial body
2074
 * lengths.  (If you pass LEN as 0, then this function assumes you
2075
 * really mean an empty body.)
2076
 */
2077
static int
2078
calc_header_length( u32 len, int new_ctb )
2079
0
{
2080
0
    if( new_ctb ) {
2081
0
  if( len < 192 )
2082
0
      return 2;
2083
0
  if( len < 8384 )
2084
0
      return 3;
2085
0
  else
2086
0
      return 6;
2087
0
    }
2088
0
    if( len < 256 )
2089
0
  return 2;
2090
0
    if( len < 65536 )
2091
0
  return 3;
2092
2093
0
    return 5;
2094
0
}
2095
2096
/****************
2097
 * Write the CTB and the packet length
2098
 */
2099
static int
2100
write_header( IOBUF out, int ctb, u32 len )
2101
10.3M
{
2102
10.3M
    return write_header2( out, ctb, len, 0 );
2103
10.3M
}
2104
2105
2106
static int
2107
write_sign_packet_header (IOBUF out, int ctb, u32 len)
2108
810
{
2109
810
  (void)ctb;
2110
2111
  /* Work around a bug in the pgp read function for signature packets,
2112
     which are not correctly coded and silently assume at some point 2
2113
     byte length headers.*/
2114
810
  iobuf_put (out, 0x89 );
2115
810
  iobuf_put (out, len >> 8 );
2116
810
  return iobuf_put (out, len) == -1 ? -1:0;
2117
810
}
2118
2119
/****************
2120
 * Write a packet header to OUT.
2121
 *
2122
 * CTB is the ctb.  It determines whether a new or old format packet
2123
 * header should be written.  The length field is adjusted, but the
2124
 * CTB is otherwise written out as is.
2125
 *
2126
 * LEN is the length of the packet's body.
2127
 *
2128
 * If HDRLEN is set, then we don't necessarily use the most efficient
2129
 * encoding to store LEN, but the specified length.  (If this is not
2130
 * possible, this is a bug.)  In this case, LEN=0 means a 0 length
2131
 * packet.  Note: setting HDRLEN is only supported for old format
2132
 * packets!
2133
 *
2134
 * If HDRLEN is not set, then the shortest encoding is used.  In this
2135
 * case, LEN=0 means the body has an indeterminate length and a
2136
 * partial body length header (if a new format packet) or an
2137
 * indeterminate length header (if an old format packet) is written
2138
 * out.  Further, if using partial body lengths, this enables partial
2139
 * body length mode on OUT.
2140
 */
2141
static int
2142
write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
2143
10.7M
{
2144
10.7M
  if (ctb_new_format_p (ctb))
2145
0
    return write_new_header( out, ctb, len, hdrlen );
2146
2147
  /* An old format packet.  Refer to RFC 4880, Section 4.2.1 to
2148
     understand how lengths are encoded in this case.  */
2149
2150
  /* The length encoding is stored in the two least significant bits.
2151
     Make sure they are cleared.  */
2152
10.7M
  log_assert ((ctb & 3) == 0);
2153
2154
10.7M
  log_assert (hdrlen == 0 || hdrlen == 2 || hdrlen == 3 || hdrlen == 5);
2155
2156
10.7M
  if (hdrlen)
2157
    /* Header length is given.  */
2158
0
    {
2159
0
      if( hdrlen == 2 && len < 256 )
2160
        /* 00 => 1 byte length.  */
2161
0
  ;
2162
0
      else if( hdrlen == 3 && len < 65536 )
2163
        /* 01 => 2 byte length.  If len < 256, this is not the most
2164
           compact encoding, but it is a correct encoding.  */
2165
0
  ctb |= 1;
2166
0
      else if (hdrlen == 5)
2167
        /* 10 => 4 byte length.  If len < 65536, this is not the most
2168
           compact encoding, but it is a correct encoding.  */
2169
0
  ctb |= 2;
2170
0
      else
2171
0
        log_bug ("Can't encode length=%d in a %d byte header!\n",
2172
0
                 len, hdrlen);
2173
0
    }
2174
10.7M
  else
2175
10.7M
    {
2176
10.7M
      if( !len )
2177
        /* 11 => Indeterminate length.  */
2178
0
  ctb |= 3;
2179
10.7M
      else if( len < 256 )
2180
        /* 00 => 1 byte length.  */
2181
10.7M
  ;
2182
2.74k
      else if( len < 65536 )
2183
        /* 01 => 2 byte length.  */
2184
2.74k
  ctb |= 1;
2185
0
      else
2186
        /* 10 => 4 byte length.  */
2187
0
  ctb |= 2;
2188
10.7M
    }
2189
2190
10.7M
  if( iobuf_put(out, ctb ) )
2191
0
    return -1;
2192
2193
10.7M
  if( len || hdrlen )
2194
10.7M
    {
2195
10.7M
      if( ctb & 2 )
2196
0
  {
2197
0
    if(iobuf_put(out, len >> 24 ))
2198
0
      return -1;
2199
0
    if(iobuf_put(out, len >> 16 ))
2200
0
      return -1;
2201
0
  }
2202
2203
10.7M
      if( ctb & 3 )
2204
2.74k
  if(iobuf_put(out, len >> 8 ))
2205
0
    return -1;
2206
2207
10.7M
      if( iobuf_put(out, len ) )
2208
0
  return -1;
2209
10.7M
    }
2210
2211
10.7M
  return 0;
2212
10.7M
}
2213
2214
2215
/* Write a new format header to OUT.
2216
2217
   CTB is the ctb.
2218
2219
   LEN is the length of the packet's body.  If LEN is 0, then enables
2220
   partial body length mode (i.e., the body is of an indeterminant
2221
   length) on OUT.  Note: this function cannot be used to generate a
2222
   header for a zero length packet.
2223
2224
   HDRLEN is the length of the packet's header.  If HDRLEN is 0, the
2225
   shortest encoding is chosen based on the length of the packet's
2226
   body.  Currently, values other than 0 are not supported.
2227
2228
   Returns 0 on success.  */
2229
static int
2230
write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
2231
0
{
2232
0
    if( hdrlen )
2233
0
  log_bug("can't cope with hdrlen yet\n");
2234
2235
0
    if( iobuf_put(out, ctb ) )
2236
0
  return -1;
2237
0
    if( !len ) {
2238
0
  iobuf_set_partial_body_length_mode(out, 512 );
2239
0
    }
2240
0
    else {
2241
0
  if( len < 192 ) {
2242
0
      if( iobuf_put(out, len ) )
2243
0
    return -1;
2244
0
  }
2245
0
  else if( len < 8384 ) {
2246
0
      len -= 192;
2247
0
      if( iobuf_put( out, (len / 256) + 192) )
2248
0
    return -1;
2249
0
      if( iobuf_put( out, (len % 256) )  )
2250
0
    return -1;
2251
0
  }
2252
0
  else {
2253
0
      if( iobuf_put( out, 0xff ) )
2254
0
    return -1;
2255
0
      if( iobuf_put( out, (len >> 24)&0xff ) )
2256
0
    return -1;
2257
0
      if( iobuf_put( out, (len >> 16)&0xff ) )
2258
0
    return -1;
2259
0
      if( iobuf_put( out, (len >> 8)&0xff )  )
2260
0
    return -1;
2261
0
      if( iobuf_put( out, len & 0xff ) )
2262
0
    return -1;
2263
0
  }
2264
0
    }
2265
0
    return 0;
2266
0
}