Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/sign.c
Line
Count
Source
1
/* sign.c - sign data
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3
 *               2007, 2010, 2012 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 <errno.h>
26
27
#include "gpg.h"
28
#include "options.h"
29
#include "packet.h"
30
#include "../common/status.h"
31
#include "../common/iobuf.h"
32
#include "keydb.h"
33
#include "../common/util.h"
34
#include "main.h"
35
#include "filter.h"
36
#include "../common/ttyio.h"
37
#include "trustdb.h"
38
#include "../common/status.h"
39
#include "../common/i18n.h"
40
#include "pkglue.h"
41
#include "../common/sysutils.h"
42
#include "call-agent.h"
43
#include "../common/mbox-util.h"
44
#include "../common/compliance.h"
45
46
#ifdef HAVE_DOSISH_SYSTEM
47
#define LF "\r\n"
48
#else
49
0
#define LF "\n"
50
#endif
51
52
53
/* Hack */
54
static int recipient_digest_algo;
55
56
57
/* A type for the extra data we hash into v5 signature packets.  */
58
struct pt_extra_hash_data_s
59
{
60
  unsigned char mode;
61
  u32 timestamp;
62
  unsigned char namelen;
63
  char name[1];
64
};
65
typedef struct pt_extra_hash_data_s *pt_extra_hash_data_t;
66
67
68
/*
69
 * Create notations and other stuff.  It is assumed that the strings
70
 * in STRLIST are already checked to contain only printable data and
71
 * have a valid NAME=VALUE format.  If with_manu is set a "manu"
72
 * notation is also added: a value of 1 includes it in the standard
73
 * way and a value of 23 assumes that the data is de-vs compliant.
74
 */
75
static void
76
mk_notation_policy_etc (ctrl_t ctrl, PKT_signature *sig,
77
      PKT_public_key *pk, PKT_public_key *pksk, int with_manu)
78
0
{
79
0
  const char *string;
80
0
  char *p = NULL;
81
0
  strlist_t pu = NULL;
82
0
  struct notation *nd = NULL;
83
0
  struct notation *ndmanu = NULL;
84
0
  struct expando_args args;
85
86
0
  log_assert (sig->version >= 4);
87
88
0
  memset (&args, 0, sizeof(args));
89
0
  args.pk = pk;
90
0
  args.pksk = pksk;
91
92
  /* Notation data. */
93
0
  if (IS_ATTST_SIGS(sig))
94
0
    ;
95
0
  else if (IS_SIG(sig) && opt.sig_notations)
96
0
    nd = opt.sig_notations;
97
0
  else if (IS_CERT(sig) && opt.cert_notations)
98
0
    nd = opt.cert_notations;
99
100
0
  if (with_manu)
101
0
    {
102
      /* Modifiying ND (i.e. opt.cert_notations) to temporary store
103
       * the manu is obviously not thread-save.  */
104
0
      ndmanu = name_value_to_notation
105
0
        ("manu",
106
0
         gnupg_manu_notation_value (with_manu == 23? CO_DE_VS :
107
0
                                    with_manu == 140? CO_FIPS : CO_GNUPG));
108
0
      ndmanu->next = nd;
109
0
      nd = ndmanu;
110
0
    }
111
112
0
  if (nd)
113
0
    {
114
0
      struct notation *item;
115
116
0
      for (item = nd; item; item = item->next)
117
0
        {
118
0
          item->altvalue = pct_expando (ctrl, item->value,&args);
119
0
          if (!item->altvalue)
120
0
            log_error (_("WARNING: unable to %%-expand notation "
121
0
                         "(too large).  Using unexpanded.\n"));
122
0
        }
123
124
0
      keygen_add_notations (sig, nd);
125
126
0
      for (item = nd; item; item = item->next)
127
0
        {
128
0
          xfree (item->altvalue);
129
0
          item->altvalue = NULL;
130
0
        }
131
0
      if (with_manu)
132
0
        {
133
          /* Restore the original nd and release ndmanu.  */
134
0
          nd = ndmanu->next;
135
0
          ndmanu->next = NULL;
136
0
          free_notation (ndmanu);
137
          /* ND is now again opt.sig_notations or opt.cert_notations. */
138
0
        }
139
0
    }
140
141
  /* Set policy URL. */
142
0
  if (IS_ATTST_SIGS(sig))
143
0
    ;
144
0
  else if (IS_SIG(sig) && opt.sig_policy_url)
145
0
    pu = opt.sig_policy_url;
146
0
  else if (IS_CERT(sig) && opt.cert_policy_url)
147
0
    pu = opt.cert_policy_url;
148
149
0
  for (; pu; pu = pu->next)
150
0
    {
151
0
      string = pu->d;
152
153
0
      p = pct_expando (ctrl, string, &args);
154
0
      if (!p)
155
0
        {
156
0
          log_error(_("WARNING: unable to %%-expand policy URL "
157
0
                      "(too large).  Using unexpanded.\n"));
158
0
          p = xstrdup(string);
159
0
        }
160
161
0
      build_sig_subpkt (sig, (SIGSUBPKT_POLICY
162
0
                              | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
163
0
                        p, strlen (p));
164
165
0
      xfree (p);
166
0
    }
167
168
  /* Preferred keyserver URL. */
169
0
  if (IS_SIG(sig) && opt.sig_keyserver_url)
170
0
    pu = opt.sig_keyserver_url;
171
172
0
  for (; pu; pu = pu->next)
173
0
    {
174
0
      string = pu->d;
175
176
0
      p = pct_expando (ctrl, string, &args);
177
0
      if (!p)
178
0
        {
179
0
          log_error (_("WARNING: unable to %%-expand preferred keyserver URL"
180
0
                       " (too large).  Using unexpanded.\n"));
181
0
          p = xstrdup (string);
182
0
        }
183
184
0
      build_sig_subpkt (sig, (SIGSUBPKT_PREF_KS
185
0
                              | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
186
0
                        p, strlen (p));
187
0
      xfree (p);
188
0
    }
189
190
  /* Set signer's user id.  */
191
0
  if (IS_SIG (sig) && !opt.flags.disable_signer_uid)
192
0
    {
193
0
      char *mbox;
194
195
      /* For now we use the uid which was used to locate the key.  */
196
0
      if (pksk->user_id
197
0
          && (mbox = mailbox_from_userid (pksk->user_id->name, 0)))
198
0
        {
199
0
          if (DBG_LOOKUP)
200
0
            log_debug ("setting Signer's UID to '%s'\n", mbox);
201
0
          build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, mbox, strlen (mbox));
202
0
          xfree (mbox);
203
0
        }
204
0
      else if (opt.sender_list)
205
0
        {
206
          /* If a list of --sender was given we scan that list and use
207
           * the first one matching a user id of the current key.  */
208
209
          /* FIXME: We need to get the list of user ids for the PKSK
210
           * packet.  That requires either a function to look it up
211
           * again or we need to extend the key packet struct to link
212
           * to the primary key which in turn could link to the user
213
           * ids.  Too much of a change right now.  Let's take just
214
           * one from the supplied list and hope that the caller
215
           * passed a matching one.  */
216
0
          build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
217
0
                            opt.sender_list->d, strlen (opt.sender_list->d));
218
0
        }
219
0
    }
220
0
}
221
222
223
224
/*
225
 * Put the Key Block subpacket into SIG for key PKSK.  Returns an
226
 * error code on failure.
227
 */
228
static gpg_error_t
229
mk_sig_subpkt_key_block (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pksk)
230
0
{
231
0
  gpg_error_t err;
232
0
  char *mbox;
233
0
  char *filterexp = NULL;
234
0
  int save_opt_armor = opt.armor;
235
0
  int save_opt_verbose = opt.verbose;
236
0
  char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
237
0
  void *data = NULL;
238
0
  size_t datalen;
239
0
  kbnode_t keyblock = NULL;
240
241
0
  push_export_filters ();
242
0
  opt.armor = 0;
243
244
0
  hexfingerprint (pksk, hexfpr, sizeof hexfpr);
245
246
  /* Get the user id so that we know which one to insert into the
247
   * key.  */
248
0
  if (pksk->user_id
249
0
      && (mbox = mailbox_from_userid (pksk->user_id->name, 0)))
250
0
    {
251
0
      if (DBG_LOOKUP)
252
0
        log_debug ("including key with UID '%s' (specified)\n", mbox);
253
0
      filterexp = xasprintf ("keep-uid= -- mbox = %s", mbox);
254
0
      xfree (mbox);
255
0
    }
256
0
  else if (opt.sender_list)
257
0
    {
258
      /* If --sender was given we use the first one from that list.  */
259
0
      if (DBG_LOOKUP)
260
0
        log_debug ("including key with UID '%s' (--sender)\n",
261
0
                   opt.sender_list->d);
262
0
      filterexp = xasprintf ("keep-uid= -- mbox = %s", opt.sender_list->d);
263
0
    }
264
0
  else  /* Use the primary user id.  */
265
0
    {
266
0
      if (DBG_LOOKUP)
267
0
        log_debug ("including key with primary UID\n");
268
0
      filterexp = xstrdup ("keep-uid= primary -t");
269
0
    }
270
271
0
  if (DBG_LOOKUP)
272
0
    log_debug ("export filter expression: %s\n", filterexp);
273
0
  err = parse_and_set_export_filter (filterexp);
274
0
  if (err)
275
0
    goto leave;
276
0
  xfree (filterexp);
277
0
  filterexp = xasprintf ("drop-subkey= fpr <> %s && usage !~ e", hexfpr);
278
0
  if (DBG_LOOKUP)
279
0
    log_debug ("export filter expression: %s\n", filterexp);
280
0
  err = parse_and_set_export_filter (filterexp);
281
0
  if (err)
282
0
    goto leave;
283
284
285
0
  opt.verbose = 0;
286
0
  err = export_pubkey_buffer (ctrl, hexfpr, EXPORT_MINIMAL|EXPORT_CLEAN,
287
0
                              "", 1, /* Prefix with the reserved byte. */
288
0
                              NULL, &keyblock, &data, &datalen);
289
0
  opt.verbose = save_opt_verbose;
290
0
  if (err)
291
0
    {
292
0
      log_error ("failed to get to be included key: %s\n", gpg_strerror (err));
293
0
      goto leave;
294
0
    }
295
296
0
  build_sig_subpkt (sig, SIGSUBPKT_KEY_BLOCK, data, datalen);
297
298
0
 leave:
299
0
  xfree (data);
300
0
  release_kbnode (keyblock);
301
0
  xfree (filterexp);
302
0
  opt.armor = save_opt_armor;
303
0
  pop_export_filters ();
304
0
  return err;
305
0
}
306
307
308
/*
309
 * Helper to hash a user ID packet.
310
 */
311
static void
312
hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
313
0
{
314
0
  byte buf[5];
315
316
0
  (void)sigversion;
317
318
0
  if (uid->attrib_data)
319
0
    {
320
0
      buf[0] = 0xd1;                 /* Indicates an attribute packet.  */
321
0
      buf[1] = uid->attrib_len >> 24;  /* Always use 4 length bytes.  */
322
0
      buf[2] = uid->attrib_len >> 16;
323
0
      buf[3] = uid->attrib_len >>  8;
324
0
      buf[4] = uid->attrib_len;
325
0
    }
326
0
  else
327
0
    {
328
0
      buf[0] = 0xb4;                 /* Indicates a userid packet.  */
329
0
      buf[1] = uid->len >> 24;         /* Always use 4 length bytes.  */
330
0
      buf[2] = uid->len >> 16;
331
0
      buf[3] = uid->len >>  8;
332
0
      buf[4] = uid->len;
333
0
    }
334
0
  gcry_md_write( md, buf, 5 );
335
336
0
  if (uid->attrib_data)
337
0
    gcry_md_write (md, uid->attrib_data, uid->attrib_len );
338
0
  else
339
0
    gcry_md_write (md, uid->name, uid->len );
340
0
}
341
342
343
/*
344
 * Helper to hash some parts from the signature.  EXTRAHASH gives the
345
 * extra data to be hashed into v5 signatures; it may by NULL for
346
 * detached signatures.
347
 */
348
static void
349
hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig,
350
                          pt_extra_hash_data_t extrahash)
351
0
{
352
0
  byte buf[10];
353
0
  int i;
354
0
  size_t n;
355
356
0
  gcry_md_putc (md, sig->version);
357
0
  gcry_md_putc (md, sig->sig_class);
358
0
  gcry_md_putc (md, sig->pubkey_algo);
359
0
  gcry_md_putc (md, sig->digest_algo);
360
0
  if (sig->hashed)
361
0
    {
362
0
      n = sig->hashed->len;
363
0
      if (sig->version >= 6)
364
0
        {
365
0
          gcry_md_putc (md, (n >> 24) );
366
0
          gcry_md_putc (md, (n >> 16) );
367
0
        }
368
0
      gcry_md_putc (md, (n >> 8) );
369
0
      gcry_md_putc (md,  n       );
370
0
      gcry_md_write (md, sig->hashed->data, n );
371
0
      n += 6;
372
0
    }
373
0
  else
374
0
    {
375
0
      if (sig->version >= 6)
376
0
        {
377
0
          gcry_md_putc (md, 0);
378
0
          gcry_md_putc (md, 0);
379
0
        }
380
0
      gcry_md_putc (md, 0);  /* Always hash the length of the subpacket.  */
381
0
      gcry_md_putc (md, 0);
382
0
      n = 6;
383
0
    }
384
0
  if (sig->version >= 6)
385
0
    n += 2; /* Fixup for the two extra octets hashed.  */
386
387
  /* Hash data from the literal data packet.  */
388
0
  if (sig->version >= 5 && (sig->sig_class == 0x00 || sig->sig_class == 0x01))
389
0
    {
390
      /* - One octet content format
391
       * - File name (one octet length followed by the name)
392
       * - Four octet timestamp */
393
0
      if (extrahash)
394
0
        {
395
0
          buf[0] = extrahash->mode;
396
0
          buf[1] = extrahash->namelen;
397
0
          gcry_md_write (md, buf, 2);
398
0
          if (extrahash->namelen)
399
0
            gcry_md_write (md, extrahash->name, extrahash->namelen);
400
0
          buf[0] = extrahash->timestamp >> 24;
401
0
          buf[1] = extrahash->timestamp >> 16;
402
0
          buf[2] = extrahash->timestamp >>  8;
403
0
          buf[3] = extrahash->timestamp;
404
0
          gcry_md_write (md, buf, 4);
405
0
        }
406
0
      else /* Detached signatures */
407
0
        {
408
0
          memset (buf, 0, 6);
409
0
          gcry_md_write (md, buf, 6);
410
0
        }
411
0
    }
412
  /* Add some magic aka known as postscript.  The idea was to make it
413
   * impossible to make up a document with a v3 signature and then
414
   * turn this into a v4 signature for another document.  The last
415
   * hashed 5 bytes of a v4 signature should never look like a the
416
   * last 5 bytes of a v3 signature.  The length can be used to parse
417
   * from the end. */
418
0
  i = 0;
419
0
  buf[i++] = sig->version;  /* Hash convention version.  */
420
0
  buf[i++] = 0xff;          /* Not any sig type value.   */
421
0
  if (sig->version >= 5 && sig->version != 6)
422
0
    {
423
      /* Note: We don't hashed any data larger than 2^32 and thus we
424
       * can always use 0 here.  See also note below.  */
425
0
      buf[i++] = 0;
426
0
      buf[i++] = 0;
427
0
      buf[i++] = 0;
428
0
      buf[i++] = 0;
429
0
    }
430
0
  buf[i++] = n >> 24;         /* (n is only 16 bit, so this is always 0) */
431
0
  buf[i++] = n >> 16;
432
0
  buf[i++] = n >>  8;
433
0
  buf[i++] = n;
434
0
  gcry_md_write (md, buf, i);
435
0
}
436
437
438
/* Perform the sign operation.  If CACHE_NONCE is given the agent is
439
 * advised to use that cached passphrase for the key.  SIGNHINTS has
440
 * hints so that we can do some additional checks. */
441
static int
442
do_sign (ctrl_t ctrl, PKT_public_key *pksk, PKT_signature *sig,
443
   gcry_md_hd_t md, int mdalgo,
444
         const char *cache_nonce, unsigned int signhints)
445
0
{
446
0
  gpg_error_t err;
447
0
  byte *dp;
448
0
  char *hexgrip;
449
450
  /* An ADSK key commonly has a creation date older than the primary
451
   * key.  For example because the ADSK is used as an archive key for
452
   * a group of users.  */
453
0
  if (pksk->timestamp > sig->timestamp && !(signhints & SIGNHINT_ADSK))
454
0
    {
455
0
      ulong d = pksk->timestamp - sig->timestamp;
456
0
      log_info (ngettext("key %s was created %lu second"
457
0
                         " in the future (time warp or clock problem)\n",
458
0
                         "key %s was created %lu seconds"
459
0
                         " in the future (time warp or clock problem)\n",
460
0
                         d), keystr_from_pk (pksk), d);
461
0
      if (!opt.ignore_time_conflict)
462
0
        return gpg_error (GPG_ERR_TIME_CONFLICT);
463
0
    }
464
465
0
  print_pubkey_algo_note (pksk->pubkey_algo);
466
467
0
  if (!mdalgo)
468
0
    mdalgo = gcry_md_get_algo (md);
469
470
0
  if ((signhints & SIGNHINT_KEYSIG) && !(signhints & SIGNHINT_SELFSIG)
471
0
      && mdalgo == GCRY_MD_SHA1
472
0
      && !opt.flags.allow_weak_key_signatures)
473
0
    {
474
      /* We do not allow the creation of third-party key signatures
475
       * using SHA-1 because we also reject them when verifying.  Note
476
       * that this will render dsa1024 keys unsuitable for such
477
       * keysigs and in turn the WoT. */
478
0
      print_sha1_keysig_rejected_note ();
479
0
      err = gpg_error (GPG_ERR_DIGEST_ALGO);
480
0
      goto leave;
481
0
    }
482
483
  /* Check compliance but always allow for key revocations. */
484
0
  if (!IS_KEY_REV (sig)
485
0
      && ! gnupg_digest_is_allowed (opt.compliance, 1, mdalgo))
486
0
    {
487
0
      log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
488
0
     gcry_md_algo_name (mdalgo),
489
0
     gnupg_compliance_option_string (opt.compliance));
490
0
      err = gpg_error (GPG_ERR_DIGEST_ALGO);
491
0
      goto leave;
492
0
    }
493
494
0
  if (!IS_KEY_REV (sig)
495
0
      && ! gnupg_pk_is_allowed (opt.compliance, PK_USE_SIGNING,
496
0
                                pksk->pubkey_algo, 0,
497
0
                                pksk->pkey, nbits_from_pk (pksk), NULL))
498
0
    {
499
0
      log_error (_("key %s may not be used for signing in %s mode\n"),
500
0
                 keystr_from_pk (pksk),
501
0
                 gnupg_compliance_option_string (opt.compliance));
502
0
      err = gpg_error (GPG_ERR_PUBKEY_ALGO);
503
0
      goto leave;
504
0
    }
505
506
0
  if (!gnupg_rng_is_compliant (opt.compliance))
507
0
    {
508
0
      err = gpg_error (GPG_ERR_FORBIDDEN);
509
0
      log_error (_("%s is not compliant with %s mode\n"),
510
0
                 "RNG",
511
0
                 gnupg_compliance_option_string (opt.compliance));
512
0
      write_status_error ("random-compliance", err);
513
0
      goto leave;
514
0
    }
515
516
0
  print_digest_algo_note (mdalgo);
517
0
  dp = gcry_md_read  (md, mdalgo);
518
0
  sig->digest_algo = mdalgo;
519
0
  sig->digest_start[0] = dp[0];
520
0
  sig->digest_start[1] = dp[1];
521
0
  mpi_release (sig->data[0]);
522
0
  sig->data[0] = NULL;
523
0
  mpi_release (sig->data[1]);
524
0
  sig->data[1] = NULL;
525
526
527
0
  err = hexkeygrip_from_pk (pksk, &hexgrip);
528
0
  if (!err)
529
0
    {
530
0
      char *desc;
531
0
      gcry_sexp_t s_sigval;
532
533
0
      desc = gpg_format_keydesc (ctrl, pksk, FORMAT_KEYDESC_NORMAL, 1);
534
      /* FIXME: Eventually support composite keys.  */
535
0
      err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
536
0
                          pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
537
0
                          dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
538
0
                          &s_sigval);
539
0
      xfree (desc);
540
541
0
      if (err)
542
0
        ;
543
0
      else if (pksk->pubkey_algo == GCRY_PK_RSA
544
0
               || pksk->pubkey_algo == GCRY_PK_RSA_S)
545
0
        sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
546
0
      else if (pksk->pubkey_algo == PUBKEY_ALGO_EDDSA
547
0
               && openpgp_oid_is_ed25519 (pksk->pkey[0]))
548
0
        {
549
0
          err = sexp_extract_param_sos_nlz (s_sigval, "r", &sig->data[0]);
550
0
          if (!err)
551
0
            err = sexp_extract_param_sos_nlz (s_sigval, "s", &sig->data[1]);
552
0
        }
553
0
      else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
554
0
               || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
555
0
        {
556
0
          err = sexp_extract_param_sos (s_sigval, "r", &sig->data[0]);
557
0
          if (!err)
558
0
            err = sexp_extract_param_sos (s_sigval, "s", &sig->data[1]);
559
0
        }
560
0
      else if (pksk->pubkey_algo == PUBKEY_ALGO_ED25519)
561
0
        {
562
0
          sig->data[0] = get_r_s_mpi_from_sexp (s_sigval);
563
0
          if (!sig->data[0])
564
0
            err = gpg_error (GPG_ERR_NO_OBJ);
565
0
        }
566
0
      else
567
0
        {
568
0
          sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
569
0
          sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
570
0
        }
571
572
0
      gcry_sexp_release (s_sigval);
573
0
    }
574
0
  xfree (hexgrip);
575
576
0
 leave:
577
0
  if (err)
578
0
    log_error (_("signing failed: %s\n"), gpg_strerror (err));
579
0
  else
580
0
    {
581
0
      if (opt.verbose)
582
0
        {
583
0
          char *ustr = get_user_id_string_native (ctrl, sig->keyid);
584
0
          log_info (_("%s/%s signature from: \"%s\"\n"),
585
0
                    openpgp_pk_algo_name (pksk->pubkey_algo),
586
0
                    openpgp_md_algo_name (sig->digest_algo),
587
0
                    ustr);
588
0
          xfree (ustr);
589
0
  }
590
0
    }
591
0
  return err;
592
0
}
593
594
595
static int
596
complete_sig (ctrl_t ctrl,
597
              PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
598
              const char *cache_nonce, unsigned int signhints)
599
0
{
600
0
  int rc;
601
602
  /* if (!(rc = check_secret_key (pksk, 0))) */
603
0
  rc = do_sign (ctrl, pksk, sig, md, 0, cache_nonce, signhints);
604
0
  return rc;
605
0
}
606
607
608
/* Return true if the key seems to be on a version 1 OpenPGP card.
609
   This works by asking the agent and may fail if the card has not yet
610
   been used with the agent.  */
611
static int
612
openpgp_card_v1_p (PKT_public_key *pk)
613
0
{
614
0
  gpg_error_t err;
615
0
  int result;
616
617
  /* Shortcut if we are not using RSA: The v1 cards only support RSA
618
     thus there is no point in looking any further.  */
619
0
  if (!is_RSA (pk->pubkey_algo))
620
0
    return 0;
621
622
0
  if (!pk->flags.serialno_valid)
623
0
    {
624
0
      char *hexgrip;
625
626
      /* Note: No need to care about composite keys for non-RSA keys.  */
627
0
      err = hexkeygrip_from_pk (pk, &hexgrip);
628
0
      if (err)
629
0
        {
630
0
          log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
631
0
          return 0; /* Ooops.  */
632
0
        }
633
634
0
      xfree (pk->serialno);
635
0
      agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL);
636
0
      xfree (hexgrip);
637
0
      pk->flags.serialno_valid = 1;
638
0
    }
639
640
0
  if (!pk->serialno)
641
0
    result = 0; /* Error from a past agent_get_keyinfo or no card.  */
642
0
  else
643
0
    {
644
      /* The version number of the card is included in the serialno.  */
645
0
      result = !strncmp (pk->serialno, "D2760001240101", 14);
646
0
    }
647
0
  return result;
648
0
}
649
650
651
/* Get a matching hash algorithm for DSA and ECDSA.  */
652
static int
653
match_dsa_hash (unsigned int qbytes)
654
0
{
655
0
  if (qbytes <= 20)
656
0
    return DIGEST_ALGO_SHA1;
657
658
0
  if (qbytes <= 28)
659
0
    return DIGEST_ALGO_SHA224;
660
661
0
  if (qbytes <= 32)
662
0
    return DIGEST_ALGO_SHA256;
663
664
0
  if (qbytes <= 48)
665
0
    return DIGEST_ALGO_SHA384;
666
667
0
  if (qbytes <= 66 )  /* 66 corresponds to 521 (64 to 512) */
668
0
    return DIGEST_ALGO_SHA512;
669
670
0
  return DEFAULT_DIGEST_ALGO;
671
  /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
672
     answer we have if a digest larger than 512 bits is requested.  */
673
0
}
674
675
676
/*
677
  First try --digest-algo.  If that isn't set, see if the recipient
678
  has a preferred algorithm (which is also filtered through
679
  --personal-digest-prefs).  If we're making a signature without a
680
  particular recipient (i.e. signing, rather than signing+encrypting)
681
  then take the first algorithm in --personal-digest-prefs that is
682
  usable for the pubkey algorithm.  If --personal-digest-prefs isn't
683
  set, then take the OpenPGP default (i.e. SHA-1).
684
685
  Note that EdDSA takes an input of arbitrary length and thus
686
  we don't enforce any particular algorithm like we do for standard
687
  ECDSA. However, we use SHA256 as the default algorithm.
688
689
  Possible improvement: Use the highest-ranked usable algorithm from
690
  the signing key prefs either before or after using the personal
691
  list?
692
*/
693
static int
694
hash_for (PKT_public_key *pk)
695
0
{
696
0
  if (opt.def_digest_algo)
697
0
    {
698
0
      return opt.def_digest_algo;
699
0
    }
700
0
  else if (recipient_digest_algo && !is_weak_digest (recipient_digest_algo))
701
0
    {
702
0
      return recipient_digest_algo;
703
0
    }
704
0
  else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
705
0
    {
706
0
      if (opt.personal_digest_prefs)
707
0
        return opt.personal_digest_prefs[0].value;
708
0
      else
709
0
        if (gcry_mpi_get_nbits (pk->pkey[1]) > 256)
710
0
          return DIGEST_ALGO_SHA512;
711
0
        else
712
0
          return DIGEST_ALGO_SHA256;
713
0
    }
714
0
  else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
715
0
           || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
716
0
    {
717
0
      unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
718
719
0
      if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
720
0
        qbytes = ecdsa_qbits_from_Q (qbytes);
721
0
      qbytes = qbytes/8;
722
723
      /* It's a DSA key, so find a hash that is the same size as q or
724
   larger.  If q is 160, assume it is an old DSA key and use a
725
   160-bit hash unless --enable-dsa2 is set, in which case act
726
   like a new DSA key that just happens to have a 160-bit q
727
   (i.e. allow truncation).  If q is not 160, by definition it
728
   must be a new DSA key.  We ignore the personal_digest_prefs
729
   for ECDSA because they should always match the curve and
730
   truncated hashes are not useful either.  Even worse,
731
   smartcards may reject non matching hash lengths for curves
732
   (e.g. using SHA-512 with brainpooolP385r1 on a Yubikey).  */
733
734
0
      if (pk->pubkey_algo == PUBKEY_ALGO_DSA && opt.personal_digest_prefs)
735
0
  {
736
0
    prefitem_t *prefs;
737
738
0
    if (qbytes != 20 || opt.flags.dsa2)
739
0
      {
740
0
        for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
741
0
    if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
742
0
      return prefs->value;
743
0
      }
744
0
    else
745
0
      {
746
0
        for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
747
0
    if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
748
0
      return prefs->value;
749
0
      }
750
0
  }
751
752
0
      return match_dsa_hash(qbytes);
753
0
    }
754
0
  else if (openpgp_card_v1_p (pk))
755
0
    {
756
      /* The sk lives on a smartcard, and old smartcards only handle
757
   SHA-1 and RIPEMD/160.  Newer smartcards (v2.0) don't have
758
   this restriction anymore.  Fortunately the serial number
759
   encodes the version of the card and thus we know that this
760
   key is on a v1 card. */
761
0
      if(opt.personal_digest_prefs)
762
0
  {
763
0
    prefitem_t *prefs;
764
765
0
    for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
766
0
      if (prefs->value==DIGEST_ALGO_SHA1
767
0
                || prefs->value==DIGEST_ALGO_RMD160)
768
0
        return prefs->value;
769
0
  }
770
771
0
      return DIGEST_ALGO_SHA1;
772
0
    }
773
0
  else if (opt.personal_digest_prefs)
774
0
    {
775
      /* It's not DSA, so we can use whatever the first hash algorithm
776
   is in the pref list */
777
0
      return opt.personal_digest_prefs[0].value;
778
0
    }
779
0
  else
780
0
    return DEFAULT_DIGEST_ALGO;
781
0
}
782
783
784
static void
785
print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
786
0
{
787
0
  byte array[MAX_FINGERPRINT_LEN];
788
0
  char buf[100+MAX_FINGERPRINT_LEN*2];
789
0
  size_t n;
790
791
0
  snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
792
0
            what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
793
0
            (ulong)sig->timestamp );
794
0
  fingerprint_from_pk (pk, array, &n);
795
0
  bin2hex (array, n, buf + strlen (buf));
796
797
0
  write_status_text( STATUS_SIG_CREATED, buf );
798
0
}
799
800
801
/*
802
 * Loop over the secret certificates in SK_LIST and build the one pass
803
 * signature packets.  OpenPGP says that the data should be bracket by
804
 * the onepass-sig and signature-packet; so we build these onepass
805
 * packet here in reverse order.
806
 */
807
static int
808
write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
809
0
{
810
0
  int skcount;
811
0
  SK_LIST sk_rover;
812
813
0
  for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
814
0
    skcount++;
815
816
0
  for (; skcount; skcount--)
817
0
    {
818
0
      PKT_public_key *pk;
819
0
      PKT_onepass_sig *ops;
820
0
      PACKET pkt;
821
0
      int i, rc;
822
823
0
      for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
824
0
        if (++i == skcount)
825
0
          break;
826
827
0
      pk = sk_rover->pk;
828
0
      ops = xmalloc_clear (sizeof *ops);
829
0
      ops->sig_class = sigclass;
830
0
      ops->digest_algo = hash_for (pk);
831
0
      ops->pubkey_algo = pk->pubkey_algo;
832
0
      keyid_from_pk (pk, ops->keyid);
833
0
      ops->last = (skcount == 1);
834
835
0
      init_packet (&pkt);
836
0
      pkt.pkttype = PKT_ONEPASS_SIG;
837
0
      pkt.pkt.onepass_sig = ops;
838
0
      rc = build_packet (out, &pkt);
839
0
      free_packet (&pkt, NULL);
840
0
      if (rc)
841
0
        {
842
0
          log_error ("build onepass_sig packet failed: %s\n",
843
0
                     gpg_strerror (rc));
844
0
          return rc;
845
0
        }
846
0
    }
847
848
0
  return 0;
849
0
}
850
851
852
/*
853
 * Helper to write the plaintext (literal data) packet.  At
854
 * R_EXTRAHASH a malloced object with the extra data hashed
855
 * into v5 signatures is stored.
856
 */
857
static int
858
write_plaintext_packet (iobuf_t out, iobuf_t inp,
859
                        const char *fname, int ptmode,
860
                        pt_extra_hash_data_t *r_extrahash)
861
0
{
862
0
  PKT_plaintext *pt = NULL;
863
0
  u32 filesize;
864
0
  int rc = 0;
865
866
0
  if (!opt.no_literal)
867
0
    pt = setup_plaintext_name (fname, inp);
868
869
  /* Try to calculate the length of the data. */
870
0
  if ( !iobuf_is_pipe_filename (fname) && *fname)
871
0
    {
872
0
      uint64_t tmpsize;
873
874
0
      tmpsize = iobuf_get_filelength (inp);
875
0
      if (!tmpsize && opt.verbose)
876
0
        log_info (_("WARNING: '%s' is an empty file\n"), fname);
877
878
      /* We can't encode the length of very large files because
879
       * OpenPGP uses only 32 bit for file sizes.  So if the size of a
880
       * file is larger than 2^32 minus some bytes for packet headers,
881
       * we switch to partial length encoding. */
882
0
      if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536))
883
0
        filesize = tmpsize;
884
0
      else
885
0
        filesize = 0;
886
887
      /* Because the text_filter modifies the length of the
888
       * data, it is not possible to know the used length
889
       * without a double read of the file - to avoid that
890
       * we simple use partial length packets. */
891
0
      if (ptmode == 't' || ptmode == 'u' || ptmode == 'm')
892
0
        filesize = 0;
893
0
    }
894
0
  else
895
0
    filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
896
897
0
  if (!opt.no_literal)
898
0
    {
899
0
      PACKET pkt;
900
901
      /* Note that PT has been initialized above in no_literal mode.  */
902
0
      pt->timestamp = make_timestamp ();
903
0
      pt->mode = ptmode;
904
0
      pt->len = filesize;
905
0
      pt->new_ctb = !pt->len;
906
0
      pt->buf = inp;
907
0
      init_packet (&pkt);
908
0
      pkt.pkttype = PKT_PLAINTEXT;
909
0
      pkt.pkt.plaintext = pt;
910
      /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
911
0
      if ((rc = build_packet (out, &pkt)))
912
0
        log_error ("build_packet(PLAINTEXT) failed: %s\n",
913
0
                   gpg_strerror (rc) );
914
915
0
      *r_extrahash = xtrymalloc (sizeof **r_extrahash + pt->namelen);
916
0
      if (!*r_extrahash)
917
0
        rc = gpg_error_from_syserror ();
918
0
      else
919
0
        {
920
0
          (*r_extrahash)->mode = pt->mode;
921
0
          (*r_extrahash)->timestamp = pt->timestamp;
922
0
          (*r_extrahash)->namelen = pt->namelen;
923
          /* Note that the last byte of NAME won't be initialized
924
           * because we don't need it.  */
925
0
          memcpy ((*r_extrahash)->name, pt->name, pt->namelen);
926
0
        }
927
0
      pt->buf = NULL;
928
0
      free_packet (&pkt, NULL);
929
0
    }
930
0
  else
931
0
    {
932
0
      byte copy_buffer[4096];
933
0
      int  bytes_copied;
934
935
0
      *r_extrahash = xtrymalloc (sizeof **r_extrahash);
936
0
      if (!*r_extrahash)
937
0
        {
938
0
          rc = gpg_error_from_syserror ();
939
0
          goto leave;
940
0
        }
941
      /* FIXME: We need to parse INP to get the to be hashed data from
942
       * it.  */
943
0
      (*r_extrahash)->mode = 0;
944
0
      (*r_extrahash)->timestamp = 0;
945
0
      (*r_extrahash)->namelen = 0;
946
947
0
      while ((bytes_copied = iobuf_read (inp, copy_buffer, 4096)) != -1)
948
0
        if ((rc = iobuf_write (out, copy_buffer, bytes_copied)))
949
0
          {
950
0
            log_error ("copying input to output failed: %s\n",
951
0
                       gpg_strerror (rc));
952
0
            break;
953
0
          }
954
0
      wipememory (copy_buffer, 4096); /* burn buffer */
955
0
    }
956
957
0
 leave:
958
0
  return rc;
959
0
}
960
961
962
/*
963
 * Write the signatures from the SK_LIST to OUT. HASH must be a
964
 * non-finalized hash which will not be changes here.  EXTRAHASH is
965
 * either NULL or the extra data to be hashed into v5 signatures.
966
 */
967
static int
968
write_signature_packets (ctrl_t ctrl,
969
                         SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
970
                         pt_extra_hash_data_t extrahash,
971
                         int sigclass, u32 timestamp, u32 duration,
972
       int status_letter, const char *cache_nonce)
973
0
{
974
0
  SK_LIST sk_rover;
975
0
  int with_manu;
976
977
  /* Loop over the certificates with secret keys. */
978
0
  for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
979
0
    {
980
0
      PKT_public_key *pk;
981
0
      PKT_signature *sig;
982
0
      gcry_md_hd_t md;
983
0
      gpg_error_t err;
984
985
0
      pk = sk_rover->pk;
986
987
      /* Build the signature packet.  */
988
0
      sig = xtrycalloc (1, sizeof *sig);
989
0
      if (!sig)
990
0
        return gpg_error_from_syserror ();
991
992
0
      if (pk->version >= 5)
993
0
        sig->version = 5;  /* Required for v5 keys.  */
994
0
      else
995
0
        sig->version = 4;  /* Required.  */
996
997
0
      keyid_from_pk (pk, sig->keyid);
998
0
      sig->digest_algo = hash_for (pk);
999
0
      sig->pubkey_algo = pk->pubkey_algo;
1000
0
      if (timestamp)
1001
0
        sig->timestamp = timestamp;
1002
0
      else
1003
0
        sig->timestamp = make_timestamp();
1004
0
      if (duration)
1005
0
        sig->expiredate = sig->timestamp + duration;
1006
0
      sig->sig_class = sigclass;
1007
1008
0
      if (gcry_md_copy (&md, hash))
1009
0
        BUG ();
1010
1011
0
      build_sig_subpkt_from_sig (sig, pk, 0);
1012
1013
0
      if (opt.compliance == CO_DE_VS
1014
0
          && gnupg_rng_is_compliant (CO_DE_VS))
1015
0
        with_manu = 23;  /* FIXME: Also check that the algos are compliant?*/
1016
0
      else if (opt.compliance == CO_FIPS
1017
0
          && gnupg_rng_is_compliant (CO_FIPS))
1018
0
        with_manu = 140;
1019
0
      else if (!(opt.compat_flags & COMPAT_NO_MANU))
1020
0
        with_manu = 1;
1021
0
      else
1022
0
        with_manu = 0;
1023
1024
0
      mk_notation_policy_etc (ctrl, sig, NULL, pk, with_manu);
1025
0
      if (opt.flags.include_key_block && IS_SIG (sig))
1026
0
        err = mk_sig_subpkt_key_block (ctrl, sig, pk);
1027
0
      else
1028
0
        err = 0;
1029
0
      hash_sigversion_to_magic (md, sig, extrahash);
1030
0
      gcry_md_final (md);
1031
1032
0
      if (!err)
1033
0
        err = do_sign (ctrl, pk, sig, md, hash_for (pk), cache_nonce, 0);
1034
0
      gcry_md_close (md);
1035
0
      if (!err)
1036
0
        {
1037
          /* Write the packet.  */
1038
0
          PACKET pkt;
1039
1040
0
          init_packet (&pkt);
1041
0
          pkt.pkttype = PKT_SIGNATURE;
1042
0
          pkt.pkt.signature = sig;
1043
0
          err = build_packet (out, &pkt);
1044
0
          if (!err && is_status_enabled())
1045
0
            print_status_sig_created (pk, sig, status_letter);
1046
0
          free_packet (&pkt, NULL);
1047
0
          if (err)
1048
0
            log_error ("build signature packet failed: %s\n",
1049
0
                       gpg_strerror (err));
1050
0
  }
1051
0
      else
1052
0
        free_seckey_enc (sig);
1053
1054
0
      if (err)
1055
0
        return err;
1056
0
    }
1057
1058
0
  return 0;
1059
0
}
1060
1061
1062
/*
1063
 * Sign the files whose names are in FILENAME using all secret keys
1064
 * which can be taken from LOCUSR, if this is NULL, use the default
1065
 * secret key.
1066
 * If DETACHED has the value true, make a detached signature.
1067
 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
1068
 * signed data for these users.  If ENCRYPTFLAG is 2 symmetric encryption
1069
 * is also used.
1070
 * If FILENAMES->d is NULL read from stdin and ignore the detached mode.
1071
 * If OUTFILE is not NULL; this file is used for output and the function
1072
 * does not ask for overwrite permission; output is then always
1073
 * uncompressed, non-armored and in binary mode.
1074
 */
1075
int
1076
sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
1077
     int encryptflag, strlist_t remusr, const char *outfile )
1078
0
{
1079
0
  const char *fname;
1080
0
  armor_filter_context_t *afx;
1081
0
  compress_filter_context_t zfx;
1082
0
  gcry_md_hd_t md = NULL;
1083
0
  md_filter_context_t mfx;
1084
0
  md_thd_filter_context_t mfx2 = NULL;
1085
0
  text_filter_context_t tfx;
1086
0
  progress_filter_context_t *pfx;
1087
0
  encrypt_filter_context_t efx;
1088
0
  iobuf_t inp = NULL;
1089
0
  iobuf_t out = NULL;
1090
0
  PACKET pkt;
1091
0
  int rc = 0;
1092
0
  PK_LIST pk_list = NULL;
1093
0
  SK_LIST sk_list = NULL;
1094
0
  SK_LIST sk_rover = NULL;
1095
0
  int multifile = 0;
1096
0
  u32 duration=0;
1097
0
  pt_extra_hash_data_t extrahash = NULL;
1098
1099
0
  pfx = new_progress_context ();
1100
0
  afx = new_armor_context ();
1101
0
  memset (&zfx, 0, sizeof zfx);
1102
0
  memset (&mfx, 0, sizeof mfx);
1103
0
  memset (&efx, 0, sizeof efx);
1104
0
  efx.ctrl = ctrl;
1105
0
  init_packet (&pkt);
1106
1107
0
  if (filenames)
1108
0
    {
1109
0
      fname = filenames->d;
1110
0
      multifile = !!filenames->next;
1111
0
    }
1112
0
  else
1113
0
    fname = NULL;
1114
1115
0
  if (fname && filenames->next && (!detached || encryptflag))
1116
0
    log_bug ("multiple files can only be detached signed");
1117
1118
0
  if (encryptflag == 2
1119
0
      && (rc = setup_symkey (&efx.symkey_s2k, &efx.symkey_dek)))
1120
0
    goto leave;
1121
1122
0
  if (opt.ask_sig_expire && !opt.batch)
1123
0
    duration = ask_expire_interval(1,opt.def_sig_expire);
1124
0
  else
1125
0
    duration = parse_expire_string(opt.def_sig_expire);
1126
1127
  /* Note: In the old non-agent version the following call used to
1128
   * unprotect the secret key.  This is now done on demand by the agent.  */
1129
0
  if ((rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )))
1130
0
    goto leave;
1131
1132
0
  if (encryptflag
1133
0
      && (rc = build_pk_list (ctrl, remusr, &pk_list)))
1134
0
    goto leave;
1135
1136
  /* Prepare iobufs. */
1137
0
  if (multifile)    /* have list of filenames */
1138
0
    inp = NULL;     /* we do it later */
1139
0
  else
1140
0
    {
1141
0
      inp = iobuf_open(fname);
1142
0
      if (inp && is_secured_file (iobuf_get_fd (inp)))
1143
0
        {
1144
0
          iobuf_close (inp);
1145
0
          inp = NULL;
1146
0
          gpg_err_set_errno (EPERM);
1147
0
        }
1148
0
      if (!inp)
1149
0
        {
1150
0
          rc = gpg_error_from_syserror ();
1151
0
          log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
1152
0
                     strerror (errno));
1153
0
          goto leave;
1154
0
  }
1155
1156
0
      handle_progress (pfx, inp, fname);
1157
0
    }
1158
1159
0
  if (outfile)
1160
0
    {
1161
0
      if (is_secured_filename (outfile))
1162
0
        {
1163
0
          out = NULL;
1164
0
          gpg_err_set_errno (EPERM);
1165
0
        }
1166
0
      else
1167
0
        out = iobuf_create (outfile, 0);
1168
0
      if (!out)
1169
0
        {
1170
0
          rc = gpg_error_from_syserror ();
1171
0
          log_error (_("can't create '%s': %s\n"), outfile, gpg_strerror (rc));
1172
0
          goto leave;
1173
0
        }
1174
0
      else if (opt.verbose)
1175
0
        log_info (_("writing to '%s'\n"), outfile);
1176
0
    }
1177
0
  else if ((rc = open_outfile (GNUPG_INVALID_FD, fname,
1178
0
                               opt.armor? 1 : detached? 2 : 0, 0, &out)))
1179
0
    {
1180
0
      goto leave;
1181
0
    }
1182
1183
  /* Prepare to calculate the MD over the input.  */
1184
0
  if (opt.textmode && !outfile && !multifile)
1185
0
    {
1186
0
      memset (&tfx, 0, sizeof tfx);
1187
0
      iobuf_push_filter (inp, text_filter, &tfx);
1188
0
    }
1189
1190
0
  if (gcry_md_open (&md, 0, 0))
1191
0
    BUG ();
1192
0
  if (DBG_HASHING)
1193
0
    gcry_md_debug (md, "sign");
1194
1195
  /* If we're encrypting and signing, it is reasonable to pick the
1196
   * hash algorithm to use out of the recipient key prefs.  This is
1197
   * best effort only, as in a DSA2 and smartcard world there are
1198
   * cases where we cannot please everyone with a single hash (DSA2
1199
   * wants >160 and smartcards want =160).  In the future this could
1200
   * be more complex with different hashes for each sk, but the
1201
   * current design requires a single hash for all SKs. */
1202
0
  if (pk_list)
1203
0
    {
1204
0
      if (opt.def_digest_algo)
1205
0
        {
1206
0
          if (!opt.expert
1207
0
              && select_algo_from_prefs (pk_list,PREFTYPE_HASH,
1208
0
                                         opt.def_digest_algo,
1209
0
                                         NULL) != opt.def_digest_algo)
1210
0
            {
1211
0
              log_info (_("WARNING: forcing digest algorithm %s (%d)"
1212
0
                          " violates recipient preferences\n"),
1213
0
                        gcry_md_algo_name (opt.def_digest_algo),
1214
0
                        opt.def_digest_algo);
1215
0
            }
1216
0
        }
1217
0
      else
1218
0
        {
1219
0
          int algo;
1220
0
          int conflict = 0;
1221
0
          struct pref_hint hint = { 0 };
1222
1223
0
          hint.digest_length = 0;
1224
1225
          /* Of course, if the recipient asks for something
1226
           * unreasonable (like the wrong hash for a DSA key) then
1227
           * don't do it.  Check all sk's - if any are DSA or live
1228
           * on a smartcard, then the hash has restrictions and we
1229
           * may not be able to give the recipient what they want.
1230
           * For DSA, pass a hint for the largest q we have.  Note
1231
           * that this means that a q>160 key will override a q=160
1232
           * key and force the use of truncation for the q=160 key.
1233
           * The alternative would be to ignore the recipient prefs
1234
           * completely and get a different hash for each DSA key in
1235
           * hash_for().  The override behavior here is more or less
1236
           * reasonable as it is under the control of the user which
1237
           * keys they sign with for a given message and the fact
1238
           * that the message with multiple signatures won't be
1239
           * usable on an implementation that doesn't understand
1240
           * DSA2 anyway. */
1241
0
          for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
1242
0
            {
1243
0
              if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
1244
0
                  || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1245
0
                {
1246
0
                  int temp_hashlen = gcry_mpi_get_nbits (sk_rover->pk->pkey[1]);
1247
1248
0
                  if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1249
0
                    {
1250
0
                      temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
1251
0
                      if (!temp_hashlen)
1252
0
                        conflict = 1;  /* Better don't use the prefs. */
1253
0
                      temp_hashlen = (temp_hashlen+7)/8;
1254
                      /* Fixup for that funny nistp521 (yes, 521) were
1255
                       * we need to use a 512 bit hash algo.  */
1256
0
                      if (temp_hashlen == 66)
1257
0
                        temp_hashlen = 64;
1258
0
                    }
1259
0
                  else
1260
0
                    temp_hashlen = (temp_hashlen+7)/8;
1261
1262
                  /* Pick a hash that is large enough for our largest
1263
       * Q or matches our Q.  If there are several of them
1264
       * we run into a conflict and don't use the
1265
       * preferences.  */
1266
0
                  if (hint.digest_length < temp_hashlen)
1267
0
                    {
1268
0
                      if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1269
0
                        {
1270
0
                          if (hint.exact)
1271
0
                            conflict = 1;
1272
0
                          hint.exact = 1;
1273
0
                        }
1274
0
                      hint.digest_length = temp_hashlen;
1275
0
                    }
1276
0
                }
1277
0
            }
1278
1279
0
          if (!conflict
1280
0
              && (algo = select_algo_from_prefs (pk_list, PREFTYPE_HASH,
1281
0
                                                  -1, &hint)) > 0)
1282
0
            {
1283
              /* Note that we later check that the algo is not weak.  */
1284
0
              recipient_digest_algo = algo;
1285
0
            }
1286
0
        }
1287
0
    }
1288
1289
0
  for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1290
0
    gcry_md_enable (md, hash_for (sk_rover->pk));
1291
1292
0
  if (!multifile)
1293
0
    {
1294
0
      if (encryptflag && (opt.compat_flags & COMPAT_PARALLELIZED))
1295
0
        {
1296
0
          iobuf_push_filter (inp, md_thd_filter, &mfx2);
1297
0
          md_thd_filter_set_md (mfx2, md);
1298
0
        }
1299
0
      else
1300
0
        {
1301
0
          iobuf_push_filter (inp, md_filter, &mfx);
1302
0
          mfx.md = md;
1303
0
        }
1304
0
    }
1305
1306
0
  if (detached && !encryptflag)
1307
0
    afx->what = 2;
1308
1309
0
  if (opt.armor && !outfile)
1310
0
    push_armor_filter (afx, out);
1311
1312
0
  if (encryptflag)
1313
0
    {
1314
0
      efx.pk_list = pk_list;
1315
      /* fixme: set efx.cfx.datalen if known */
1316
0
      iobuf_push_filter (out, encrypt_filter, &efx);
1317
0
    }
1318
1319
0
  if (opt.compress_algo && !outfile && !detached)
1320
0
    {
1321
0
      int compr_algo = opt.compress_algo;
1322
1323
0
      if (!opt.explicit_compress_option
1324
0
          && is_file_compressed (inp))
1325
0
        {
1326
0
          if (opt.verbose)
1327
0
            log_info(_("'%s' already compressed\n"), fname? fname: "[stdin]");
1328
0
          compr_algo = 0;
1329
0
        }
1330
0
      else if (compr_algo==-1)
1331
0
        {
1332
          /* If we're not encrypting, then select_algo_from_prefs
1333
           * will fail and we'll end up with the default.  If we are
1334
           * encrypting, select_algo_from_prefs cannot fail since
1335
           * there is an assumed preference for uncompressed data.
1336
           * Still, if it did fail, we'll also end up with the
1337
           * default. */
1338
0
          if ((compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP,
1339
0
                                                    -1, NULL)) == -1)
1340
0
            {
1341
0
              compr_algo = default_compress_algo();
1342
0
            }
1343
0
        }
1344
0
      else if (!opt.expert && pk_list
1345
0
               && select_algo_from_prefs (pk_list, PREFTYPE_ZIP,
1346
0
            compr_algo, NULL) != compr_algo)
1347
0
        {
1348
0
          log_info (_("WARNING: forcing compression algorithm %s (%d)"
1349
0
                      " violates recipient preferences\n"),
1350
0
                    compress_algo_to_string (compr_algo), compr_algo);
1351
0
        }
1352
1353
      /* Algo 0 means no compression. */
1354
0
      if (compr_algo)
1355
0
        push_compress_filter (out, &zfx, compr_algo);
1356
0
    }
1357
1358
  /* Write the one-pass signature packets if needed */
1359
0
  if (!detached)
1360
0
    {
1361
0
      rc = write_onepass_sig_packets (sk_list, out,
1362
0
                                      opt.textmode && !outfile ? 0x01:0x00);
1363
0
      if (rc)
1364
0
        goto leave;
1365
0
    }
1366
1367
0
  write_status_begin_signing (md);
1368
1369
  /* Setup the inner packet. */
1370
0
  if (detached)
1371
0
    {
1372
0
      size_t iobuf_size = iobuf_set_buffer_size(0) * 1024;
1373
1374
0
      if (multifile)
1375
0
        {
1376
0
          strlist_t sl;
1377
1378
0
          if (opt.verbose)
1379
0
            log_info (_("signing:") );
1380
          /* Must walk reverse through this list.  */
1381
0
          for (sl = strlist_last(filenames);
1382
0
               sl;
1383
0
               sl = strlist_prev( filenames, sl))
1384
0
            {
1385
0
              inp = iobuf_open (sl->d);
1386
0
              if (inp && is_secured_file (iobuf_get_fd (inp)))
1387
0
                {
1388
0
                  iobuf_close (inp);
1389
0
                  inp = NULL;
1390
0
                  gpg_err_set_errno (EPERM);
1391
0
                }
1392
0
              if (!inp)
1393
0
                {
1394
0
                  rc = gpg_error_from_syserror ();
1395
0
                  log_error (_("can't open '%s': %s\n"),
1396
0
                             sl->d, gpg_strerror (rc));
1397
0
                  goto leave;
1398
0
                }
1399
0
              handle_progress (pfx, inp, sl->d);
1400
0
              if (opt.verbose)
1401
0
                log_printf (" '%s'", sl->d );
1402
0
              if (opt.textmode)
1403
0
                {
1404
0
                  memset (&tfx, 0, sizeof tfx);
1405
0
                  iobuf_push_filter (inp, text_filter, &tfx);
1406
0
                }
1407
0
              if (encryptflag && (opt.compat_flags & COMPAT_PARALLELIZED))
1408
0
                {
1409
0
                  iobuf_push_filter (inp, md_thd_filter, &mfx2);
1410
0
                  md_thd_filter_set_md (mfx2, md);
1411
0
                }
1412
0
              else
1413
0
                {
1414
0
                  iobuf_push_filter (inp, md_filter, &mfx);
1415
0
                  mfx.md = md;
1416
0
                }
1417
0
              while (iobuf_read (inp, NULL, iobuf_size) != -1)
1418
0
                ;
1419
0
              iobuf_close (inp);
1420
0
              inp = NULL;
1421
0
      }
1422
0
          if (opt.verbose)
1423
0
            log_printf ("\n");
1424
0
  }
1425
0
      else
1426
0
        {
1427
          /* Read, so that the filter can calculate the digest. */
1428
0
          while (iobuf_read (inp, NULL, iobuf_size) != -1)
1429
0
            ;
1430
0
  }
1431
0
    }
1432
0
  else
1433
0
    {
1434
0
      rc = write_plaintext_packet (out, inp, fname,
1435
0
                                   (opt.textmode && !outfile) ?
1436
0
                                   (opt.mimemode? 'm' : 't') : 'b',
1437
0
                                   &extrahash);
1438
0
    }
1439
1440
  /* Catch errors from above. */
1441
0
  if (rc)
1442
0
    goto leave;
1443
1444
  /* Write the signatures. */
1445
0
  rc = write_signature_packets (ctrl, sk_list, out, md, extrahash,
1446
0
                                opt.textmode && !outfile? 0x01 : 0x00,
1447
0
                                0, duration, detached ? 'D':'S', NULL);
1448
0
  if (rc)
1449
0
    goto leave;
1450
1451
1452
0
 leave:
1453
0
  if (rc)
1454
0
    iobuf_cancel (out);
1455
0
  else
1456
0
    {
1457
0
      iobuf_close (out);
1458
0
      if (encryptflag)
1459
0
        write_status (STATUS_END_ENCRYPTION);
1460
0
    }
1461
0
  iobuf_close (inp);
1462
0
  gcry_md_close (md);
1463
0
  release_sk_list (sk_list);
1464
0
  release_pk_list (pk_list);
1465
0
  recipient_digest_algo = 0;
1466
0
  release_progress_context (pfx);
1467
0
  release_armor_context (afx);
1468
0
  xfree (extrahash);
1469
0
  return rc;
1470
0
}
1471
1472
1473
/*
1474
 * Make a clear signature.  Note that opt.armor is not needed.
1475
 */
1476
int
1477
clearsign_file (ctrl_t ctrl,
1478
                const char *fname, strlist_t locusr, const char *outfile)
1479
0
{
1480
0
  armor_filter_context_t *afx;
1481
0
  progress_filter_context_t *pfx;
1482
0
  gcry_md_hd_t textmd = NULL;
1483
0
  iobuf_t inp = NULL;
1484
0
  iobuf_t out = NULL;
1485
0
  PACKET pkt;
1486
0
  int rc = 0;
1487
0
  SK_LIST sk_list = NULL;
1488
0
  SK_LIST sk_rover = NULL;
1489
0
  u32 duration = 0;
1490
0
  pt_extra_hash_data_t extrahash = NULL;
1491
1492
0
  pfx = new_progress_context ();
1493
0
  afx = new_armor_context ();
1494
0
  init_packet( &pkt );
1495
1496
0
  if (opt.ask_sig_expire && !opt.batch)
1497
0
    duration = ask_expire_interval (1, opt.def_sig_expire);
1498
0
  else
1499
0
    duration = parse_expire_string (opt.def_sig_expire);
1500
1501
  /* Note: In the old non-agent version the following call used to
1502
   * unprotect the secret key.  This is now done on demand by the agent.  */
1503
0
  if ((rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG)))
1504
0
    goto leave;
1505
1506
  /* Prepare iobufs.  */
1507
0
  inp = iobuf_open (fname);
1508
0
  if (inp && is_secured_file (iobuf_get_fd (inp)))
1509
0
    {
1510
0
      iobuf_close (inp);
1511
0
      inp = NULL;
1512
0
      gpg_err_set_errno (EPERM);
1513
0
    }
1514
0
  if (!inp)
1515
0
    {
1516
0
      rc = gpg_error_from_syserror ();
1517
0
      log_error (_("can't open '%s': %s\n"),
1518
0
                 fname? fname: "[stdin]", gpg_strerror (rc));
1519
0
      goto leave;
1520
0
    }
1521
0
  handle_progress (pfx, inp, fname);
1522
1523
0
  if (outfile)
1524
0
    {
1525
0
      if (is_secured_filename (outfile))
1526
0
        {
1527
0
          outfile = NULL;
1528
0
          gpg_err_set_errno (EPERM);
1529
0
        }
1530
0
      else
1531
0
        out = iobuf_create (outfile, 0);
1532
1533
0
      if (!out)
1534
0
        {
1535
0
          rc = gpg_error_from_syserror ();
1536
0
          log_error (_("can't create '%s': %s\n"), outfile, gpg_strerror (rc));
1537
0
          goto leave;
1538
0
        }
1539
0
      else if (opt.verbose)
1540
0
        log_info (_("writing to '%s'\n"), outfile);
1541
1542
0
    }
1543
0
  else if ((rc = open_outfile (GNUPG_INVALID_FD, fname, 1, 0, &out)))
1544
0
    {
1545
0
      goto leave;
1546
0
    }
1547
1548
0
  iobuf_writestr (out, "-----BEGIN PGP SIGNED MESSAGE-----" LF);
1549
1550
0
  {
1551
0
    const char *s;
1552
0
    int any = 0;
1553
0
    byte hashs_seen[256];
1554
1555
0
    memset (hashs_seen, 0, sizeof hashs_seen);
1556
0
    iobuf_writestr (out, "Hash: " );
1557
0
    for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1558
0
      {
1559
0
        int i = hash_for (sk_rover->pk);
1560
1561
0
        if (!hashs_seen[ i & 0xff ])
1562
0
          {
1563
0
            s = gcry_md_algo_name (i);
1564
0
            if (s)
1565
0
              {
1566
0
                hashs_seen[ i & 0xff ] = 1;
1567
0
                if (any)
1568
0
                  iobuf_put (out, ',');
1569
0
                iobuf_writestr (out, s);
1570
0
                any = 1;
1571
0
              }
1572
0
          }
1573
0
      }
1574
0
    log_assert (any);
1575
0
    iobuf_writestr (out, LF);
1576
0
  }
1577
1578
0
  if (opt.not_dash_escaped)
1579
0
    iobuf_writestr (out,
1580
0
                    "NotDashEscaped: You need "GPG_NAME
1581
0
                    " to verify this message" LF);
1582
0
  iobuf_writestr (out, LF );
1583
1584
0
  if (gcry_md_open (&textmd, 0, 0))
1585
0
    BUG ();
1586
0
  for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1587
0
    gcry_md_enable (textmd, hash_for(sk_rover->pk));
1588
1589
0
  if (DBG_HASHING)
1590
0
    gcry_md_debug (textmd, "clearsign");
1591
1592
0
  copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped, opt.escape_from);
1593
  /* fixme: check for read errors */
1594
1595
  /* Now write the armor. */
1596
0
  afx->what = 2;
1597
0
  push_armor_filter (afx, out);
1598
1599
  /* Prepare EXTRAHASH, so that it can be used for v5 signature.  */
1600
0
  extrahash = xtrymalloc (sizeof *extrahash);
1601
0
  if (!extrahash)
1602
0
    {
1603
0
      rc = gpg_error_from_syserror ();
1604
0
      goto leave;
1605
0
    }
1606
0
  else
1607
0
    {
1608
0
      extrahash->mode = 't';
1609
0
      extrahash->timestamp = 0;
1610
0
      extrahash->namelen = 0;
1611
0
    }
1612
1613
  /* Write the signatures.  */
1614
0
  rc = write_signature_packets (ctrl, sk_list, out, textmd, extrahash,
1615
0
                                0x01, 0, duration, 'C', NULL);
1616
0
  if (rc)
1617
0
    goto leave;
1618
1619
0
 leave:
1620
0
  if (rc)
1621
0
    iobuf_cancel (out);
1622
0
  else
1623
0
    iobuf_close (out);
1624
0
  iobuf_close (inp);
1625
0
  gcry_md_close (textmd);
1626
0
  release_sk_list (sk_list);
1627
0
  release_progress_context (pfx);
1628
0
  release_armor_context (afx);
1629
0
  xfree (extrahash);
1630
0
  return rc;
1631
0
}
1632
1633
1634
/*
1635
 * Sign and conventionally encrypt the given file.
1636
 * FIXME: Far too much code is duplicated - revamp the whole file.
1637
 */
1638
int
1639
sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
1640
0
{
1641
0
  armor_filter_context_t *afx;
1642
0
  progress_filter_context_t *pfx;
1643
0
  compress_filter_context_t zfx;
1644
0
  md_filter_context_t mfx;
1645
0
  md_thd_filter_context_t mfx2 = NULL;
1646
0
  gcry_md_hd_t md = NULL;
1647
0
  text_filter_context_t tfx;
1648
0
  cipher_filter_context_t cfx;
1649
0
  iobuf_t inp = NULL;
1650
0
  iobuf_t out = NULL;
1651
0
  PACKET pkt;
1652
0
  STRING2KEY *s2k = NULL;
1653
0
  int rc = 0;
1654
0
  SK_LIST sk_list = NULL;
1655
0
  SK_LIST sk_rover = NULL;
1656
0
  int algo;
1657
0
  u32 duration = 0;
1658
0
  int canceled;
1659
0
  pt_extra_hash_data_t extrahash = NULL;
1660
1661
0
  pfx = new_progress_context ();
1662
0
  afx = new_armor_context ();
1663
0
  memset (&zfx, 0, sizeof zfx);
1664
0
  memset (&mfx, 0, sizeof mfx);
1665
0
  memset (&tfx, 0, sizeof tfx);
1666
0
  memset (&cfx, 0, sizeof cfx);
1667
0
  init_packet (&pkt);
1668
1669
0
  if (opt.ask_sig_expire && !opt.batch)
1670
0
    duration = ask_expire_interval (1, opt.def_sig_expire);
1671
0
  else
1672
0
    duration = parse_expire_string (opt.def_sig_expire);
1673
1674
  /* Note: In the old non-agent version the following call used to
1675
   * unprotect the secret key.  This is now done on demand by the agent.  */
1676
0
  rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
1677
0
  if (rc)
1678
0
    goto leave;
1679
1680
  /* Prepare iobufs.  */
1681
0
  inp = iobuf_open (fname);
1682
0
  if (inp && is_secured_file (iobuf_get_fd (inp)))
1683
0
    {
1684
0
      iobuf_close (inp);
1685
0
      inp = NULL;
1686
0
      gpg_err_set_errno (EPERM);
1687
0
    }
1688
0
  if (!inp)
1689
0
    {
1690
0
      rc = gpg_error_from_syserror ();
1691
0
      log_error (_("can't open '%s': %s\n"),
1692
0
                 fname? fname: "[stdin]", gpg_strerror (rc));
1693
0
      goto leave;
1694
0
    }
1695
0
  handle_progress (pfx, inp, fname);
1696
1697
  /* Prepare key.  */
1698
0
  s2k = xmalloc_clear (sizeof *s2k);
1699
0
  s2k->mode = opt.s2k_mode;
1700
0
  s2k->hash_algo = S2K_DIGEST_ALGO;
1701
1702
0
  algo = default_cipher_algo ();
1703
0
  cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, 0, &canceled);
1704
1705
0
  if (!cfx.dek || !cfx.dek->keylen)
1706
0
    {
1707
0
      rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1708
0
      log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
1709
0
      goto leave;
1710
0
    }
1711
1712
0
  cfx.dek->use_aead = use_aead (NULL, cfx.dek->algo);
1713
0
  if (!cfx.dek->use_aead)
1714
0
    cfx.dek->use_mdc = !!use_mdc (NULL, cfx.dek->algo);
1715
1716
0
  if (!opt.quiet || !opt.batch)
1717
0
    log_info (_("%s.%s encryption will be used\n"),
1718
0
              openpgp_cipher_algo_name (algo),
1719
0
              cfx.dek->use_aead? openpgp_aead_algo_name (cfx.dek->use_aead)
1720
0
              /**/             : "CFB");
1721
1722
  /* Now create the outfile.  */
1723
0
  rc = open_outfile (GNUPG_INVALID_FD, fname, opt.armor? 1:0, 0, &out);
1724
0
  if (rc)
1725
0
    goto leave;
1726
1727
  /* Prepare to calculate the MD over the input.  */
1728
0
  if (opt.textmode)
1729
0
    iobuf_push_filter (inp, text_filter, &tfx);
1730
0
  if (gcry_md_open (&md, 0, 0))
1731
0
    BUG ();
1732
0
  if  (DBG_HASHING)
1733
0
    gcry_md_debug (md, "symc-sign");
1734
1735
0
  for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1736
0
    gcry_md_enable (md, hash_for (sk_rover->pk));
1737
1738
0
  if ((opt.compat_flags & COMPAT_PARALLELIZED))
1739
0
    {
1740
0
      iobuf_push_filter (inp, md_thd_filter, &mfx2);
1741
0
      md_thd_filter_set_md (mfx2, md);
1742
0
    }
1743
0
  else
1744
0
    {
1745
0
      iobuf_push_filter (inp, md_filter, &mfx);
1746
0
      mfx.md = md;
1747
0
    }
1748
1749
1750
  /* Push armor output filter */
1751
0
  if (opt.armor)
1752
0
    push_armor_filter (afx, out);
1753
1754
  /* Write the symmetric key packet */
1755
  /* (current filters: armor)*/
1756
0
  {
1757
0
    PKT_symkey_enc *enc = xmalloc_clear (sizeof *enc);
1758
1759
    /* FIXME: seskeylen is 0, thus we directly encrypt the session key:
1760
     *
1761
     *     ...then the S2K algorithm applied to the passphrase produces
1762
     *    the session key for decrypting the file, using the symmetric
1763
     *    cipher algorithm from the Symmetric-Key Encrypted Session Key
1764
     *    packet.
1765
     *
1766
     * The problem is that this does not allow us to add additional
1767
     * encrypted session keys.
1768
     */
1769
1770
0
    enc->version = cfx.dek->use_aead ? 5 : 4;
1771
0
    enc->cipher_algo = cfx.dek->algo;
1772
0
    enc->aead_algo = cfx.dek->use_aead;
1773
0
    enc->s2k = *s2k;
1774
0
    pkt.pkttype = PKT_SYMKEY_ENC;
1775
0
    pkt.pkt.symkey_enc = enc;
1776
0
    if ((rc = build_packet (out, &pkt)))
1777
0
      log_error ("build symkey packet failed: %s\n", gpg_strerror (rc));
1778
0
    xfree (enc);
1779
0
  }
1780
1781
  /* Push the encryption filter */
1782
0
  iobuf_push_filter (out,
1783
0
                     cfx.dek->use_aead? cipher_filter_aead
1784
0
                     /**/             : cipher_filter_cfb,
1785
0
                     &cfx);
1786
1787
  /* Push the compress filter */
1788
0
  if (default_compress_algo())
1789
0
    {
1790
0
      if (cfx.dek && (cfx.dek->use_mdc || cfx.dek->use_aead))
1791
0
        zfx.new_ctb = 1;
1792
0
      push_compress_filter (out, &zfx,default_compress_algo() );
1793
0
    }
1794
1795
  /* Write the one-pass signature packets */
1796
  /* (current filters: zip - encrypt - armor) */
1797
0
  rc = write_onepass_sig_packets (sk_list, out, opt.textmode? 0x01:0x00);
1798
0
  if (rc)
1799
0
    goto leave;
1800
1801
0
  write_status_begin_signing (md);
1802
1803
  /* Pipe data through all filters; i.e. write the signed stuff.  */
1804
  /* (current filters: zip - encrypt - armor) */
1805
0
  rc = write_plaintext_packet (out, inp, fname,
1806
0
                               opt.textmode ? (opt.mimemode?'m':'t'):'b',
1807
0
                               &extrahash);
1808
0
  if (rc)
1809
0
    goto leave;
1810
1811
  /* Write the signatures.  */
1812
  /* (current filters: zip - encrypt - armor) */
1813
0
  rc = write_signature_packets (ctrl, sk_list, out, md, extrahash,
1814
0
                                opt.textmode? 0x01 : 0x00,
1815
0
                                0, duration, 'S', NULL);
1816
0
  if (rc)
1817
0
    goto leave;
1818
1819
1820
0
 leave:
1821
0
  if (rc)
1822
0
    iobuf_cancel (out);
1823
0
  else
1824
0
    {
1825
0
      iobuf_close (out);
1826
0
      write_status (STATUS_END_ENCRYPTION);
1827
0
    }
1828
0
  iobuf_close (inp);
1829
0
  release_sk_list (sk_list);
1830
0
  gcry_md_close (md);
1831
0
  xfree (cfx.dek);
1832
0
  xfree (s2k);
1833
0
  release_progress_context (pfx);
1834
0
  release_armor_context (afx);
1835
0
  xfree (extrahash);
1836
0
  return rc;
1837
0
}
1838
1839
1840
/*
1841
 * Create a v4/v5 signature in *RET_SIG.
1842
 *
1843
 * PK is the primary key to sign (required for all sigs)
1844
 * UID is the user id to sign (required for 0x10..0x13, 0x30)
1845
 * SUBPK is subkey to sign (required for 0x18, 0x19, 0x28)
1846
 *
1847
 * PKSK is the signing key
1848
 *
1849
 * SIGCLASS is the type of signature to create.
1850
 *
1851
 * TIMESTAMP is the timestamp to use for the signature. 0 means "now"
1852
 *
1853
 * DURATION is the amount of time (in seconds) until the signature
1854
 * expires.
1855
 *
1856
 * If CACHED_NONCE is not NULL the agent may use it to avoid
1857
 * additional Pinentry popups for the same keyblock.
1858
 *
1859
 * This function creates the following subpackets: issuer, created,
1860
 * and expire (if duration is not 0). For revocation signatures the
1861
 * intended recipient fingerprint subpacket is created.
1862
 * Additional subpackets can be added using MKSUBPKT, which is called
1863
 * after these subpackets are added and before the signature is generated.
1864
 * OPAQUE is passed to MKSUBPKT.
1865
 */
1866
int
1867
make_keysig_packet (ctrl_t ctrl,
1868
                    PKT_signature **ret_sig, PKT_public_key *pk,
1869
        PKT_user_id *uid, PKT_public_key *subpk,
1870
        PKT_public_key *pksk,
1871
        int sigclass,
1872
                    u32 timestamp, u32 duration,
1873
        int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1874
                    const char *cache_nonce)
1875
0
{
1876
0
  PKT_signature *sig;
1877
0
  int rc = 0;
1878
0
  int sigversion;
1879
0
  int digest_algo;
1880
0
  gcry_md_hd_t md;
1881
0
  u32 pk_keyid[2], pksk_keyid[2];
1882
0
  unsigned int signhints;
1883
0
  int with_manu;
1884
1885
0
  log_assert ((sigclass&~3) == SIGCLASS_CERT
1886
0
              || sigclass == SIGCLASS_KEY
1887
0
              || sigclass == SIGCLASS_KEYREV
1888
0
              || sigclass == SIGCLASS_SUBKEY
1889
0
              || sigclass == SIGCLASS_BACKSIG
1890
0
              || sigclass == SIGCLASS_CERTREV
1891
0
              || sigclass == SIGCLASS_SUBREV );
1892
1893
0
  if (pksk->version == 6 && RFC9980)
1894
0
    sigversion = 6;
1895
0
  else if (pksk->version >= 5)
1896
0
    sigversion = 5;
1897
0
  else
1898
0
    sigversion = 4;
1899
1900
  /* Select the digest algo to use. */
1901
0
  if (opt.cert_digest_algo)     /* Forceful override by the user.  */
1902
0
    digest_algo = opt.cert_digest_algo;
1903
0
  else if (pksk->pubkey_algo == PUBKEY_ALGO_DSA) /* Meet DSA requirements.  */
1904
0
    digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1905
0
  else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA) /* Meet ECDSA requirements. */
1906
0
    digest_algo = match_dsa_hash
1907
0
      (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1908
0
  else if (pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1909
0
    {
1910
0
      if (gcry_mpi_get_nbits (pksk->pkey[1]) > 256)
1911
0
        digest_algo = DIGEST_ALGO_SHA512;
1912
0
      else
1913
0
        digest_algo = DIGEST_ALGO_SHA256;
1914
0
    }
1915
0
  else if (pksk->pubkey_algo == PUBKEY_ALGO_ED25519)
1916
0
    {
1917
0
      digest_algo = DIGEST_ALGO_SHA256;
1918
0
    }
1919
0
  else /* Use the default.  */
1920
0
    digest_algo = DEFAULT_DIGEST_ALGO;
1921
1922
0
  signhints = SIGNHINT_KEYSIG;
1923
0
  keyid_from_pk (pk, pk_keyid);
1924
0
  keyid_from_pk (pksk, pksk_keyid);
1925
0
  if (pk_keyid[0] == pksk_keyid[0] && pk_keyid[1] == pksk_keyid[1])
1926
0
    signhints |= SIGNHINT_SELFSIG;
1927
1928
0
  if (gcry_md_open (&md, digest_algo, 0))
1929
0
    BUG ();
1930
0
  if  (DBG_HASHING)
1931
0
    gcry_md_debug (md, "mkkeysig");
1932
1933
  /* Hash the public key certificate. */
1934
0
  hash_public_key (md, pk, NULL);
1935
1936
0
  if (sigclass == SIGCLASS_SUBKEY || sigclass == SIGCLASS_BACKSIG
1937
0
      || sigclass == SIGCLASS_SUBREV)
1938
0
    {
1939
      /* Hash the subkey binding/backsig/revocation.  */
1940
0
      hash_public_key (md, subpk, NULL);
1941
0
      if ((subpk->pubkey_usage & PUBKEY_USAGE_RENC))
1942
0
        signhints |= SIGNHINT_ADSK;
1943
0
    }
1944
0
  else if (sigclass != SIGCLASS_KEY && sigclass != SIGCLASS_KEYREV)
1945
0
    {
1946
      /* Hash the user id. */
1947
0
      hash_uid (md, sigversion, uid);
1948
0
    }
1949
  /* Make the signature packet.  */
1950
0
  sig = xmalloc_clear (sizeof *sig);
1951
0
  sig->version = sigversion;
1952
0
  sig->flags.exportable = 1;
1953
0
  sig->flags.revocable = 1;
1954
0
  keyid_from_pk (pksk, sig->keyid);
1955
0
  sig->pubkey_algo = pksk->pubkey_algo;
1956
0
  sig->digest_algo = digest_algo;
1957
0
  sig->timestamp = timestamp? timestamp : make_timestamp ();
1958
0
  if (duration)
1959
0
    sig->expiredate = sig->timestamp + duration;
1960
0
  sig->sig_class = sigclass;
1961
  /* Get the fpr of the subject of the revocation signature. */
1962
0
  if (IS_KEY_REV (sig))
1963
0
    {
1964
0
      size_t rs_fprlen = 0;
1965
1966
0
      sig->rev_subject_info = xmalloc_clear (sizeof *sig->rev_subject_info);
1967
1968
0
      fingerprint_from_pk (pk, sig->rev_subject_info->fpr,
1969
0
                           &rs_fprlen);
1970
0
      sig->rev_subject_info->fprlen = rs_fprlen;
1971
0
    }
1972
1973
0
  build_sig_subpkt_from_sig (sig, pksk, signhints);
1974
1975
0
  with_manu = 0;
1976
0
  if ((signhints & SIGNHINT_SELFSIG)       /* Only for self-signatures.  */
1977
0
      && ((sigclass&~3) == SIGCLASS_CERT   /* on UIDs and subkeys.       */
1978
0
          || sigclass == SIGCLASS_SUBKEY))
1979
0
    {
1980
0
      if (opt.compliance == CO_DE_VS
1981
0
          && gnupg_rng_is_compliant (CO_DE_VS))
1982
0
        with_manu = 23;  /* Always in de-vs mode.  */
1983
0
      else if (opt.compliance == CO_FIPS
1984
0
               && gnupg_rng_is_compliant (CO_FIPS))
1985
0
        with_manu = 140;
1986
0
      else if (!(opt.compat_flags & COMPAT_NO_MANU))
1987
0
        with_manu = 1;
1988
0
    }
1989
1990
0
  mk_notation_policy_etc (ctrl, sig, pk, pksk, with_manu);
1991
1992
  /* Crucial that the call to mksubpkt comes LAST before the calls
1993
   * to finalize the sig as that makes it possible for the mksubpkt
1994
   * function to get a reliable pointer to the subpacket area. */
1995
0
  if (mksubpkt)
1996
0
    rc = (*mksubpkt)(sig, opaque);
1997
1998
0
  if (!rc)
1999
0
    {
2000
0
      hash_sigversion_to_magic (md, sig, NULL);
2001
0
      gcry_md_final (md);
2002
0
      rc = complete_sig (ctrl, sig, pksk, md, cache_nonce, signhints);
2003
0
    }
2004
2005
0
  gcry_md_close (md);
2006
0
  if (rc)
2007
0
    free_seckey_enc (sig);
2008
0
  else
2009
0
    *ret_sig = sig;
2010
0
  return rc;
2011
0
}
2012
2013
2014
2015
/*
2016
 * Create a new signature packet based on an existing one.
2017
 * Only user ID signatures are supported for now.
2018
 * PK is the public key to work on.
2019
 * PKSK is the key used to make the signature.
2020
 *
2021
 * TODO: Merge this with make_keysig_packet.
2022
 */
2023
gpg_error_t
2024
update_keysig_packet (ctrl_t ctrl,
2025
                      PKT_signature **ret_sig,
2026
                      PKT_signature *orig_sig,
2027
                      PKT_public_key *pk,
2028
                      PKT_user_id *uid,
2029
                      PKT_public_key *subpk,
2030
                      PKT_public_key *pksk,
2031
                      int (*mksubpkt)(PKT_signature *, void *),
2032
                      void *opaque)
2033
0
{
2034
0
  PKT_signature *sig;
2035
0
  gpg_error_t rc = 0;
2036
0
  int digest_algo;
2037
0
  gcry_md_hd_t md;
2038
0
  u32 pk_keyid[2], pksk_keyid[2];
2039
0
  unsigned int signhints = 0;
2040
2041
0
  if ((!orig_sig || !pk || !pksk)
2042
0
      || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
2043
0
      || (orig_sig->sig_class == 0x18 && !subpk))
2044
0
    return GPG_ERR_GENERAL;
2045
2046
  /* Either use the override digest algo or in the normal case the
2047
   * original digest algorithm.  However, iff the original digest
2048
   * algorithms is SHA-1 and we are in gnupg or de-vs compliance mode
2049
   * we switch to SHA-256 (done by the macro).  */
2050
0
  if  (opt.cert_digest_algo)
2051
0
    digest_algo = opt.cert_digest_algo;
2052
0
  else if (pksk->pubkey_algo == PUBKEY_ALGO_DSA
2053
0
           || pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
2054
0
           || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
2055
0
    digest_algo = orig_sig->digest_algo;
2056
0
  else if (orig_sig->digest_algo == DIGEST_ALGO_SHA1
2057
0
           || orig_sig->digest_algo == DIGEST_ALGO_RMD160)
2058
0
    digest_algo = DEFAULT_DIGEST_ALGO;
2059
0
  else
2060
0
    digest_algo = orig_sig->digest_algo;
2061
2062
0
  signhints = SIGNHINT_KEYSIG;
2063
0
  keyid_from_pk (pk, pk_keyid);
2064
0
  keyid_from_pk (pksk, pksk_keyid);
2065
0
  if (pk_keyid[0] == pksk_keyid[0] && pk_keyid[1] == pksk_keyid[1])
2066
0
    signhints |= SIGNHINT_SELFSIG;
2067
2068
0
  if (gcry_md_open (&md, digest_algo, 0))
2069
0
    BUG ();
2070
2071
  /* Hash the public key certificate and the user id. */
2072
0
  hash_public_key (md, pk, NULL);
2073
2074
0
  if (orig_sig->sig_class == 0x18)
2075
0
    hash_public_key (md, subpk, orig_sig);
2076
0
  else
2077
0
    hash_uid (md, orig_sig->version, uid);
2078
2079
  /* Create a new signature packet.  */
2080
0
  sig = copy_signature (NULL, orig_sig);
2081
2082
  /* Don't generate version 3 signature, but newer.  */
2083
0
  if (sig->version == 3)
2084
0
    {
2085
0
      if (pk->version > 3)
2086
0
        sig->version = pk->version;
2087
0
      else
2088
0
        sig->version = 4;
2089
0
    }
2090
2091
0
  sig->digest_algo = digest_algo;
2092
2093
  /* We need to create a new timestamp so that new sig expiration
2094
   * calculations are done correctly... */
2095
0
  sig->timestamp = make_timestamp();
2096
2097
  /* ... but we won't make a timestamp earlier than the existing
2098
   * one. */
2099
0
  {
2100
0
    int tmout = 0;
2101
0
    while (sig->timestamp <= orig_sig->timestamp)
2102
0
      {
2103
0
        if (++tmout > 5 && !opt.ignore_time_conflict)
2104
0
          {
2105
0
            rc = gpg_error (GPG_ERR_TIME_CONFLICT);
2106
0
            goto leave;
2107
0
          }
2108
0
        gnupg_sleep (1);
2109
0
        sig->timestamp = make_timestamp();
2110
0
      }
2111
0
  }
2112
2113
  /* Detect an ADSK key binding signature.  */
2114
0
  if ((sig->sig_class == 0x18
2115
0
       || sig->sig_class == 0x19 || sig->sig_class == 0x28)
2116
0
      && (pk->pubkey_usage & PUBKEY_USAGE_RENC))
2117
0
    signhints |= SIGNHINT_ADSK;
2118
2119
  /* Note that already expired sigs will remain expired (with a
2120
   * duration of 1) since build-packet.c:build_sig_subpkt_from_sig
2121
   * detects this case. */
2122
2123
  /* Put the updated timestamp into the sig.  Note that this will
2124
   * automagically lower any sig expiration dates to correctly
2125
   * correspond to the differences in the timestamps (i.e. the
2126
   * duration will shrink).  */
2127
0
  build_sig_subpkt_from_sig (sig, pksk, signhints);
2128
2129
0
  if (mksubpkt)
2130
0
    rc = (*mksubpkt)(sig, opaque);
2131
2132
0
  if (!rc)
2133
0
    {
2134
0
      hash_sigversion_to_magic (md, sig, NULL);
2135
0
      gcry_md_final (md);
2136
0
      rc = complete_sig (ctrl, sig, pksk, md, NULL, signhints);
2137
0
    }
2138
2139
0
 leave:
2140
0
  gcry_md_close (md);
2141
0
  if (rc)
2142
0
    free_seckey_enc (sig);
2143
0
  else
2144
0
    *ret_sig = sig;
2145
0
  return rc;
2146
0
}