Coverage Report

Created: 2026-06-07 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/encrypt.c
Line
Count
Source
1
/* encrypt.c - Main encryption driver
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3
 *               2006, 2009 Free Software Foundation, Inc.
4
 * Copyright (C) 2016, 2023 g10 Code GmbH
5
 *
6
 * This file is part of GnuPG.
7
 *
8
 * GnuPG is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * GnuPG is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20
 * SPDX-License-Identifier: GPL-3.0-or-later
21
 */
22
23
#include <config.h>
24
#include <stdio.h>
25
#include <stdlib.h>
26
#include <string.h>
27
#include <errno.h>
28
29
#include "gpg.h"
30
#include "options.h"
31
#include "packet.h"
32
#include "../common/status.h"
33
#include "../common/iobuf.h"
34
#include "keydb.h"
35
#include "../common/util.h"
36
#include "main.h"
37
#include "filter.h"
38
#include "trustdb.h"
39
#include "../common/i18n.h"
40
#include "../common/status.h"
41
#include "pkglue.h"
42
#include "../common/compliance.h"
43
44
45
static int encrypt_simple( const char *filename, int mode, int use_seskey );
46
static int write_pubkey_enc_from_list (ctrl_t ctrl, pk_list_t pk_list,
47
                                       DEK *dek, iobuf_t out,
48
                                       struct pubkey_enc_info_item *restrct);
49
50
51
52
/* Helper for show the "encrypted for USER" during encryption.
53
 * PUBKEY_USAGE is used to figure out whether this is an ADSK key.  */
54
static void
55
show_encrypted_for_user_info (ctrl_t ctrl, unsigned int pubkey_usage,
56
                              PKT_pubkey_enc *enc, DEK *dek)
57
0
{
58
0
  char *ustr = get_user_id_string_native (ctrl, enc->keyid);
59
0
  if ((pubkey_usage & PUBKEY_USAGE_RENC))
60
0
    {
61
0
      char *tmpustr = xstrconcat (ustr, " [ADSK]", NULL);
62
0
      xfree (ustr);
63
0
      ustr = tmpustr;
64
0
    }
65
0
  log_info (_("%s/%s.%s encrypted for: \"%s\"\n"),
66
0
            openpgp_pk_algo_name (enc->pubkey_algo),
67
0
            openpgp_cipher_algo_name (dek->algo),
68
0
            dek->use_aead? openpgp_aead_algo_name (dek->use_aead)
69
0
            /**/         : "CFB",
70
0
            ustr );
71
0
  xfree (ustr);
72
0
}
73
74
75
/*
76
 * Encrypt FILENAME with only the symmetric cipher.  Take input from
77
 * stdin if FILENAME is NULL.  If --force-ocb or --use-ocb-sym is used
78
 * we use an SKESK.
79
 */
80
int
81
encrypt_symmetric (const char *filename)
82
0
{
83
0
  return encrypt_simple (filename, 1, opt.force_ocb || opt.use_ocb_sym);
84
0
}
85
86
87
/****************
88
 * Encrypt FILENAME as a literal data packet only. Take input from
89
 * stdin if FILENAME is NULL.
90
 */
91
int
92
encrypt_store (const char *filename)
93
0
{
94
0
  return encrypt_simple( filename, 0, 0 );
95
0
}
96
97
98
/* Create and setup a DEK structure and print appropriate warnings.
99
 * PK_LIST gives the list of public keys.  Always returns a DEK.  The
100
 * actual session needs to be added later.  */
101
static DEK *
102
create_dek_with_warnings (pk_list_t pk_list)
103
0
{
104
0
  DEK *dek;
105
106
0
  dek = xmalloc_secure_clear (sizeof *dek);
107
0
  if (!opt.def_cipher_algo)
108
0
    {
109
      /* Try to get it from the prefs.  */
110
0
      dek->algo = select_algo_from_prefs (pk_list, PREFTYPE_SYM, -1, NULL);
111
0
      if (dek->algo == -1)
112
0
        {
113
          /* If does not make sense to fallback to the rfc4880
114
           * required 3DES if we will reject that algo later.  Thus we
115
           * fallback to AES anticipating RFC4880bis rules.  */
116
0
          if (opt.flags.allow_old_cipher_algos)
117
0
            dek->algo = CIPHER_ALGO_3DES;
118
0
          else
119
0
            dek->algo = CIPHER_ALGO_AES;
120
0
        }
121
122
      /* In case 3DES has been selected, print a warning if any key
123
       * does not have a preference for AES.  This should help to
124
       * identify why encrypting to several recipients falls back to
125
       * 3DES. */
126
0
      if (opt.verbose && dek->algo == CIPHER_ALGO_3DES)
127
0
        warn_missing_aes_from_pklist (pk_list);
128
0
    }
129
0
  else
130
0
    {
131
0
      if (!opt.expert
132
0
          && (select_algo_from_prefs (pk_list, PREFTYPE_SYM,
133
0
                                      opt.def_cipher_algo, NULL)
134
0
              != opt.def_cipher_algo))
135
0
        {
136
0
          log_info(_("WARNING: forcing symmetric cipher %s (%d)"
137
0
                     " violates recipient preferences\n"),
138
0
                   openpgp_cipher_algo_name (opt.def_cipher_algo),
139
0
                   opt.def_cipher_algo);
140
0
        }
141
142
0
      dek->algo = opt.def_cipher_algo;
143
0
    }
144
145
0
  if (dek->algo != CIPHER_ALGO_AES256)
146
0
    {
147
      /* If quantum resistance was explicitly required, we force the
148
       * use of AES256 no matter what. Otherwise, we force AES256 if we
149
       * encrypt to Kyber keys only and the user did not explicity
150
       * request another another algo. */
151
0
      if (opt.flags.require_pqc_encryption)
152
0
        dek->algo = CIPHER_ALGO_AES256;
153
0
      else if (!opt.def_cipher_algo)
154
0
        {
155
0
          int non_kyber_pk = 0;
156
0
          for ( ; pk_list; pk_list = pk_list->next)
157
0
            if (pk_list->pk->pubkey_algo != PUBKEY_ALGO_KYBER)
158
0
              non_kyber_pk += 1;
159
0
          if (!non_kyber_pk)
160
0
            dek->algo = CIPHER_ALGO_AES256;
161
0
        }
162
0
    }
163
164
0
  return dek;
165
0
}
166
167
168
/* Check whether all encryption keys are compliant with the current
169
 * mode and issue respective status lines.  DEK has the info about the
170
 * session key and PK_LIST the list of public keys.  */
171
static gpg_error_t
172
check_encryption_compliance (DEK *dek, pk_list_t pk_list)
173
0
{
174
0
  gpg_error_t err = 0;
175
0
  pk_list_t pkr;
176
0
  int compliant;
177
178
  /* First check whether we should use the algo at all.  */
179
0
  if (openpgp_cipher_blocklen (dek->algo) < 16
180
0
      && !opt.flags.allow_old_cipher_algos)
181
0
    {
182
0
      log_error (_("cipher algorithm '%s' may not be used for encryption\n"),
183
0
     openpgp_cipher_algo_name (dek->algo));
184
0
      if (!opt.quiet)
185
0
        log_info (_("(use option \"%s\" to override)\n"),
186
0
                  "--allow-old-cipher-algos");
187
0
      err = gpg_error (GPG_ERR_CIPHER_ALGO);
188
0
      goto leave;
189
0
    }
190
191
  /* Now check the compliance.  */
192
0
  if (! gnupg_cipher_is_allowed (opt.compliance, 1, dek->algo,
193
0
                                 GCRY_CIPHER_MODE_CFB))
194
0
    {
195
0
      log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
196
0
     openpgp_cipher_algo_name (dek->algo),
197
0
     gnupg_compliance_option_string (opt.compliance));
198
0
      err = gpg_error (GPG_ERR_CIPHER_ALGO);
199
0
      goto leave;
200
0
    }
201
202
0
  if (!gnupg_rng_is_compliant (opt.compliance))
203
0
    {
204
0
      err = gpg_error (GPG_ERR_FORBIDDEN);
205
0
      log_error (_("%s is not compliant with %s mode\n"),
206
0
                 "RNG",
207
0
                 gnupg_compliance_option_string (opt.compliance));
208
0
      write_status_error ("random-compliance", err);
209
0
      goto leave;
210
0
    }
211
212
  /* From here on we only test for CO_DE_VS - if we ever want to
213
   * return other compliance mode values we need to change this to
214
   * loop over all those values.  */
215
0
  compliant = gnupg_gcrypt_is_compliant (CO_DE_VS);
216
217
0
  if (!gnupg_cipher_is_compliant (CO_DE_VS, dek->algo, GCRY_CIPHER_MODE_CFB))
218
0
    compliant = 0;
219
220
0
  for (pkr = pk_list; pkr; pkr = pkr->next)
221
0
    {
222
0
      PKT_public_key *pk = pkr->pk;
223
0
      unsigned int nbits = nbits_from_pk (pk);
224
225
0
      if (!gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0,
226
0
                                  pk->pkey, nbits, NULL))
227
0
        log_info (_("WARNING: key %s is not suitable for encryption"
228
0
                    " in %s mode\n"),
229
0
                  keystr_from_pk (pk),
230
0
                  gnupg_compliance_option_string (opt.compliance));
231
232
0
      if (compliant
233
0
          && !gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
234
0
                                     nbits, NULL))
235
0
        compliant = 0; /* Not compliant - reset flag.  */
236
0
    }
237
238
  /* If we are compliant print the status for de-vs compliance.  */
239
0
  if (compliant)
240
0
    write_status_strings (STATUS_ENCRYPTION_COMPLIANCE_MODE,
241
0
                          gnupg_status_compliance_flag (CO_DE_VS),
242
0
                          NULL);
243
244
  /* Check whether we should fail the operation.  */
245
0
  if (opt.flags.require_compliance
246
0
      && opt.compliance == CO_DE_VS
247
0
      && !compliant)
248
0
    {
249
0
      compliance_failure ();
250
0
      err = gpg_error (GPG_ERR_FORBIDDEN);
251
0
      goto leave;
252
0
    }
253
254
0
 leave:
255
0
  return err;
256
0
}
257
258
259
/* Encrypt a session key using DEK and store a pointer to the result
260
 * at R_ENCKEY and its length at R_ENCKEYLEN.
261
 *
262
 * R_SESKEY points to the unencrypted session key (.KEY, .KEYLEN) and
263
 * the algorithm that will be used to encrypt the contents of the
264
 * SKESK packet (.ALGO).  If R_SESKEY points to NULL, then a random
265
 * session key that is appropriate for DEK->ALGO is generated and
266
 * stored at R_SESKEY.  If AEAD_ALGO is not 0 the given AEAD algorithm
267
 * is used for encryption.
268
 */
269
static gpg_error_t
270
encrypt_seskey (DEK *dek, aead_algo_t aead_algo,
271
                DEK **r_seskey, void **r_enckey, size_t *r_enckeylen)
272
0
{
273
0
  gpg_error_t err;
274
0
  gcry_cipher_hd_t hd = NULL;
275
0
  byte *buf = NULL;
276
0
  DEK *seskey;
277
278
0
  *r_enckey = NULL;
279
0
  *r_enckeylen = 0;
280
281
0
  if (*r_seskey)
282
0
    seskey = *r_seskey;
283
0
  else
284
0
    {
285
0
      seskey = xtrycalloc (1, sizeof(DEK));
286
0
      if (!seskey)
287
0
        {
288
0
          err = gpg_error_from_syserror ();
289
0
          goto leave;
290
0
        }
291
0
      seskey->algo = dek->algo;
292
0
      make_session_key (seskey);
293
      /*log_hexdump( "thekey", c->key, c->keylen );*/
294
0
    }
295
296
297
0
  if (aead_algo)
298
0
    {
299
0
      unsigned int noncelen;
300
0
      enum gcry_cipher_modes ciphermode;
301
0
      byte ad[4];
302
303
0
      err = openpgp_aead_algo_info (aead_algo, &ciphermode, &noncelen);
304
0
      if (err)
305
0
        goto leave;
306
307
      /* Allocate space for the nonce, the key, and the authentication
308
       * tag (16).  */
309
0
      buf = xtrymalloc_secure (noncelen + seskey->keylen + 16);
310
0
      if (!buf)
311
0
        {
312
0
          err = gpg_error_from_syserror ();
313
0
          goto leave;
314
0
        }
315
316
0
      gcry_randomize (buf, noncelen, GCRY_STRONG_RANDOM);
317
318
0
      err = openpgp_cipher_open (&hd, dek->algo,
319
0
                                 ciphermode, GCRY_CIPHER_SECURE);
320
0
      if (!err)
321
0
        err = gcry_cipher_setkey (hd, dek->key, dek->keylen);
322
0
      if (!err)
323
0
        err = gcry_cipher_setiv (hd, buf, noncelen);
324
0
      if (err)
325
0
        goto leave;
326
327
0
      ad[0] = (0xc0 | PKT_SYMKEY_ENC);
328
0
      ad[1] = 5;
329
0
      ad[2] = dek->algo;
330
0
      ad[3] = aead_algo;
331
0
      err = gcry_cipher_authenticate (hd, ad, 4);
332
0
      if (err)
333
0
        goto leave;
334
335
0
      memcpy (buf + noncelen, seskey->key, seskey->keylen);
336
0
      gcry_cipher_final (hd);
337
0
      err = gcry_cipher_encrypt (hd, buf + noncelen, seskey->keylen, NULL,0);
338
0
      if (err)
339
0
        goto leave;
340
0
      err = gcry_cipher_gettag (hd, buf + noncelen + seskey->keylen, 16);
341
0
      if (err)
342
0
        goto leave;
343
0
      *r_enckeylen = noncelen + seskey->keylen + 16;
344
0
      *r_enckey = buf;
345
0
      buf = NULL;
346
0
    }
347
0
  else
348
0
    {
349
      /* In the old version 4 SKESK the encrypted session key is
350
       * prefixed with a one-octet algorithm id.  */
351
0
      buf = xtrymalloc_secure (1 + seskey->keylen);
352
0
      if (!buf)
353
0
        {
354
0
          err = gpg_error_from_syserror ();
355
0
          goto leave;
356
0
        }
357
0
      buf[0] = seskey->algo;
358
0
      memcpy (buf + 1, seskey->key, seskey->keylen);
359
360
0
      err = openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1);
361
0
      if (!err)
362
0
        err = gcry_cipher_setkey (hd, dek->key, dek->keylen);
363
0
      if (!err)
364
0
        err = gcry_cipher_setiv (hd, NULL, 0);
365
0
      if (!err)
366
0
        err = gcry_cipher_encrypt (hd, buf, seskey->keylen + 1, NULL, 0);
367
0
      if (err)
368
0
        goto leave;
369
0
      *r_enckeylen = seskey->keylen + 1;
370
0
      *r_enckey = buf;
371
0
      buf = NULL;
372
0
    }
373
374
  /* Return the session key in case we allocated it.  */
375
0
  *r_seskey = seskey;
376
0
  seskey = NULL;
377
378
0
 leave:
379
0
  gcry_cipher_close (hd);
380
0
  if (seskey != *r_seskey)
381
0
    xfree (seskey);
382
0
  xfree (buf);
383
0
  return err;
384
0
}
385
386
387
/* Return the AEAD algo if we shall use AEAD mode.  Returns 0 if AEAD
388
 * shall not be used.  */
389
aead_algo_t
390
use_aead (pk_list_t pk_list, int algo)
391
0
{
392
0
  int can_use;
393
394
0
  can_use = openpgp_cipher_get_algo_blklen (algo) == 16;
395
396
  /* With --force-aead we want OCB. We also use OCB in symmetric mode
397
   * with --use-ocb-sym which is detected by an empty PK_LIST. */
398
0
  if (opt.force_ocb || (!pk_list && opt.use_ocb_sym))
399
0
    {
400
0
      if (!can_use)
401
0
        {
402
0
          log_info ("Warning: request to use OCB ignored for cipher '%s'\n",
403
0
                    openpgp_cipher_algo_name (algo));
404
0
          return 0;
405
0
        }
406
0
      return AEAD_ALGO_OCB;
407
0
    }
408
409
  /* AEAD does only work with 128 bit cipher blocklength.  */
410
0
  if (!can_use)
411
0
    return 0;
412
413
  /* Note the user which keys have no AEAD feature flag set.  */
414
0
  if (opt.verbose)
415
0
    warn_missing_aead_from_pklist (pk_list);
416
417
  /* If all keys support AEAD we can use it.  */
418
0
  return select_aead_from_pklist (pk_list);
419
0
}
420
421
422
/* Shall we use the MDC?  Yes - unless rfc-2440 compatibility is
423
 * requested. */
424
int
425
use_mdc (pk_list_t pk_list,int algo)
426
0
{
427
0
  (void)pk_list;
428
0
  (void)algo;
429
430
  /* RFC-2440 don't has MDC - this is the only way to create a legacy
431
   * non-MDC encryption packet.  */
432
0
  if (RFC2440)
433
0
    return 0;
434
435
0
  return 1; /* In all other cases we use the MDC */
436
0
}
437
438
439
/* This function handles the --symmetric only (MODE true) and --store
440
 * (MODE false) cases.  We don't want to use USE_SESKEY by default
441
 * very old gnupg versions can't handle it, and there isn't really any
442
 * point unless we're making a message that can be decrypted by a
443
 * public key or passphrase.  */
444
static int
445
encrypt_simple (const char *filename, int mode, int use_seskey)
446
0
{
447
0
  iobuf_t inp, out;
448
0
  PACKET pkt;
449
0
  PKT_plaintext *pt = NULL;
450
0
  STRING2KEY *s2k = NULL;
451
0
  void *enckey = NULL;
452
0
  size_t enckeylen = 0;
453
0
  int rc = 0;
454
0
  u32 filesize;
455
0
  cipher_filter_context_t cfx;
456
0
  armor_filter_context_t  *afx = NULL;
457
0
  compress_filter_context_t zfx;
458
0
  text_filter_context_t tfx;
459
0
  progress_filter_context_t *pfx;
460
0
  int do_compress = !!default_compress_algo();
461
462
0
  if (!gnupg_rng_is_compliant (opt.compliance))
463
0
    {
464
0
      rc = gpg_error (GPG_ERR_FORBIDDEN);
465
0
      log_error (_("%s is not compliant with %s mode\n"),
466
0
                 "RNG",
467
0
                 gnupg_compliance_option_string (opt.compliance));
468
0
      write_status_error ("random-compliance", rc);
469
0
      return rc;
470
0
    }
471
472
0
  pfx = new_progress_context ();
473
0
  memset( &cfx, 0, sizeof cfx);
474
0
  memset( &zfx, 0, sizeof zfx);
475
0
  memset( &tfx, 0, sizeof tfx);
476
0
  init_packet(&pkt);
477
478
  /* Prepare iobufs. */
479
0
  inp = iobuf_open(filename);
480
0
  if (inp)
481
0
    iobuf_ioctl (inp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
482
0
  if (inp && is_secured_file (iobuf_get_fd (inp)))
483
0
    {
484
0
      iobuf_close (inp);
485
0
      inp = NULL;
486
0
      gpg_err_set_errno (EPERM);
487
0
    }
488
0
  if (!inp)
489
0
    {
490
0
      rc = gpg_error_from_syserror ();
491
0
      log_error(_("can't open '%s': %s\n"), filename? filename: "[stdin]",
492
0
                strerror(errno) );
493
0
      release_progress_context (pfx);
494
0
      return rc;
495
0
    }
496
497
0
  handle_progress (pfx, inp, filename);
498
499
0
  if (opt.textmode)
500
0
    iobuf_push_filter( inp, text_filter, &tfx );
501
502
0
  cfx.dek = NULL;
503
0
  if ( mode )
504
0
    {
505
0
      aead_algo_t aead_algo;
506
507
0
      rc = setup_symkey (&s2k, &cfx.dek);
508
0
      if (rc)
509
0
        {
510
0
          iobuf_close (inp);
511
0
          if (gpg_err_code (rc) == GPG_ERR_CIPHER_ALGO
512
0
              || gpg_err_code (rc) == GPG_ERR_DIGEST_ALGO)
513
0
            ; /* Error has already been printed.  */
514
0
          else
515
0
            log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
516
0
          release_progress_context (pfx);
517
0
          return rc;
518
0
        }
519
0
      if (use_seskey && s2k->mode != 1 && s2k->mode != 3)
520
0
        {
521
0
          use_seskey = 0;
522
0
          log_info (_("can't use a SKESK packet due to the S2K mode\n"));
523
0
        }
524
525
      /* See whether we want to use AEAD.  */
526
0
      aead_algo = use_aead (NULL, cfx.dek->algo);
527
528
0
      if ( use_seskey )
529
0
        {
530
0
          DEK *dek = NULL;
531
532
0
          rc = encrypt_seskey (cfx.dek, aead_algo, &dek, &enckey, &enckeylen);
533
0
          if (rc)
534
0
            {
535
0
              xfree (cfx.dek);
536
0
              xfree (s2k);
537
0
              iobuf_close (inp);
538
0
              release_progress_context (pfx);
539
0
              return rc;
540
0
            }
541
          /* Replace key in DEK.  */
542
0
          xfree (cfx.dek);
543
0
          cfx.dek = dek;
544
0
        }
545
546
0
      if (aead_algo)
547
0
        cfx.dek->use_aead = aead_algo;
548
0
      else
549
0
        cfx.dek->use_mdc = !!use_mdc (NULL, cfx.dek->algo);
550
551
0
      if (opt.verbose)
552
0
        log_info(_("using cipher %s.%s\n"),
553
0
                 openpgp_cipher_algo_name (cfx.dek->algo),
554
0
                 cfx.dek->use_aead? openpgp_aead_algo_name (cfx.dek->use_aead)
555
0
                 /**/             : "CFB");
556
0
    }
557
558
0
  if (rc || (rc = open_outfile (GNUPG_INVALID_FD, filename, opt.armor? 1:0,
559
0
                                0, &out )))
560
0
    {
561
0
      iobuf_cancel (inp);
562
0
      xfree (cfx.dek);
563
0
      xfree (s2k);
564
0
      release_progress_context (pfx);
565
0
      return rc;
566
0
    }
567
568
0
  if ( opt.armor )
569
0
    {
570
0
      afx = new_armor_context ();
571
0
      push_armor_filter (afx, out);
572
0
    }
573
574
0
  if ( s2k )
575
0
    {
576
      /* Fixme: This is quite similar to write_symkey_enc.  */
577
0
      PKT_symkey_enc *enc = xmalloc_clear (sizeof *enc);
578
0
      enc->version = cfx.dek->use_aead ? 5 : 4;
579
0
      enc->cipher_algo = cfx.dek->algo;
580
0
      enc->aead_algo = cfx.dek->use_aead;
581
0
      enc->s2k = *s2k;
582
0
      if (enckeylen)
583
0
        {
584
0
          enc->seskeylen = enckeylen;
585
0
          enc->seskey = xmalloc (enckeylen);
586
0
          memcpy (enc->seskey, enckey, enckeylen);
587
0
        }
588
0
      pkt.pkttype = PKT_SYMKEY_ENC;
589
0
      pkt.pkt.symkey_enc = enc;
590
0
      if ((rc = build_packet( out, &pkt )))
591
0
        log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
592
0
      free_symkey_enc (enc);
593
0
      xfree (enckey);
594
0
      enckey = NULL;
595
0
    }
596
597
0
  if (!opt.no_literal)
598
0
    pt = setup_plaintext_name (filename, inp);
599
600
  /* Note that PGP 5 has problems decrypting symmetrically encrypted
601
     data if the file length is in the inner packet. It works when
602
     only partial length headers are use.  In the past, we always used
603
     partial body length here, but since PGP 2, PGP 6, and PGP 7 need
604
     the file length, and nobody should be using PGP 5 nowadays
605
     anyway, this is now set to the file length.  Note also that this
606
     only applies to the RFC-1991 style symmetric messages, and not
607
     the RFC-2440 style.  PGP 6 and 7 work with either partial length
608
     or fixed length with the new style messages. */
609
610
0
  if ( !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
611
0
    {
612
0
      uint64_t tmpsize;
613
614
0
      tmpsize = iobuf_get_filelength(inp);
615
0
      if (!tmpsize && opt.verbose)
616
0
        log_info(_("WARNING: '%s' is an empty file\n"), filename );
617
618
      /* We can't encode the length of very large files because
619
         OpenPGP uses only 32 bit for file sizes.  So if the
620
         size of a file is larger than 2^32 minus some bytes for
621
         packet headers, we switch to partial length encoding. */
622
0
      if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
623
0
        filesize = tmpsize;
624
0
      else
625
0
        filesize = 0;
626
0
    }
627
0
  else
628
0
    filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
629
630
  /* Register the cipher filter. */
631
0
  if (mode)
632
0
    iobuf_push_filter (out,
633
0
                       cfx.dek->use_aead? cipher_filter_aead
634
0
                       /**/             : cipher_filter_cfb,
635
0
                       &cfx );
636
637
0
  if (do_compress
638
0
      && cfx.dek
639
0
      && (cfx.dek->use_mdc || cfx.dek->use_aead)
640
0
      && !opt.explicit_compress_option
641
0
      && is_file_compressed (inp))
642
0
    {
643
0
      if (opt.verbose)
644
0
        log_info(_("'%s' already compressed\n"), filename? filename: "[stdin]");
645
0
      do_compress = 0;
646
0
    }
647
648
0
  if (!opt.no_literal)
649
0
    {
650
      /* Note that PT has been initialized above in !no_literal mode.  */
651
0
      pt->timestamp = make_timestamp();
652
0
      pt->mode = opt.mimemode? 'm' : opt.textmode? 't' : 'b';
653
0
      pt->len = filesize;
654
0
      pt->new_ctb = !pt->len;
655
0
      pt->buf = inp;
656
0
      pkt.pkttype = PKT_PLAINTEXT;
657
0
      pkt.pkt.plaintext = pt;
658
0
      cfx.datalen = filesize && !do_compress ? calc_packet_length( &pkt ) : 0;
659
0
    }
660
0
  else
661
0
    {
662
0
      cfx.datalen = filesize && !do_compress ? filesize : 0;
663
0
      pkt.pkttype = 0;
664
0
      pkt.pkt.generic = NULL;
665
0
    }
666
667
  /* Register the compress filter. */
668
0
  if ( do_compress )
669
0
    {
670
0
      if (cfx.dek && (cfx.dek->use_mdc || cfx.dek->use_aead))
671
0
        zfx.new_ctb = 1;
672
0
      push_compress_filter (out, &zfx, default_compress_algo());
673
0
    }
674
675
  /* Do the work. */
676
0
  if (!opt.no_literal)
677
0
    {
678
0
      if ( (rc = build_packet( out, &pkt )) )
679
0
        log_error("build_packet failed: %s\n", gpg_strerror (rc) );
680
0
    }
681
0
  else
682
0
    {
683
      /* User requested not to create a literal packet, so we copy the
684
         plain data.  */
685
0
      iobuf_copy (out, inp);
686
0
      if ((rc = iobuf_error (inp)))
687
0
        log_error (_("error reading '%s': %s\n"),
688
0
                   iobuf_get_fname_nonnull (inp), gpg_strerror (rc));
689
0
      else if ((rc = iobuf_error (out)))
690
0
        log_error (_("error writing '%s': %s\n"),
691
0
                   iobuf_get_fname_nonnull (out), gpg_strerror (rc));
692
0
    }
693
694
  /* Finish the stuff.  */
695
0
  iobuf_close (inp);
696
0
  if (rc)
697
0
    iobuf_cancel(out);
698
0
  else
699
0
    {
700
0
      iobuf_close (out); /* fixme: check returncode */
701
0
      if (mode)
702
0
        write_status ( STATUS_END_ENCRYPTION );
703
0
    }
704
0
  if (pt)
705
0
    pt->buf = NULL;
706
0
  free_packet (&pkt, NULL);
707
0
  xfree (enckey);
708
0
  xfree (cfx.dek);
709
0
  xfree (s2k);
710
0
  release_armor_context (afx);
711
0
  release_progress_context (pfx);
712
0
  return rc;
713
0
}
714
715
716
gpg_error_t
717
setup_symkey (STRING2KEY **symkey_s2k, DEK **symkey_dek)
718
0
{
719
0
  int canceled;
720
0
  int defcipher;
721
0
  int s2kdigest;
722
723
0
  defcipher = default_cipher_algo ();
724
0
  if (openpgp_cipher_blocklen (defcipher) < 16
725
0
      && !opt.flags.allow_old_cipher_algos)
726
0
    {
727
0
      log_error (_("cipher algorithm '%s' may not be used for encryption\n"),
728
0
     openpgp_cipher_algo_name (defcipher));
729
0
      if (!opt.quiet)
730
0
        log_info (_("(use option \"%s\" to override)\n"),
731
0
                  "--allow-old-cipher-algos");
732
0
      return gpg_error (GPG_ERR_CIPHER_ALGO);
733
0
    }
734
735
0
  if (!gnupg_cipher_is_allowed (opt.compliance, 1, defcipher,
736
0
                                GCRY_CIPHER_MODE_CFB))
737
0
    {
738
0
      log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
739
0
     openpgp_cipher_algo_name (defcipher),
740
0
     gnupg_compliance_option_string (opt.compliance));
741
0
      return gpg_error (GPG_ERR_CIPHER_ALGO);
742
0
    }
743
744
0
  s2kdigest = S2K_DIGEST_ALGO;
745
0
  if (!gnupg_digest_is_allowed (opt.compliance, 1, s2kdigest))
746
0
    {
747
0
      log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
748
0
     gcry_md_algo_name (s2kdigest),
749
0
     gnupg_compliance_option_string (opt.compliance));
750
0
      return gpg_error (GPG_ERR_DIGEST_ALGO);
751
0
    }
752
753
0
  *symkey_s2k = xmalloc_clear (sizeof **symkey_s2k);
754
0
  (*symkey_s2k)->mode = opt.s2k_mode;
755
0
  (*symkey_s2k)->hash_algo = s2kdigest;
756
757
0
  *symkey_dek = passphrase_to_dek (defcipher,
758
0
                                   *symkey_s2k, 1, 0, NULL, 0, &canceled);
759
0
  if (!*symkey_dek || !(*symkey_dek)->keylen)
760
0
    {
761
0
      xfree(*symkey_dek);
762
0
      xfree(*symkey_s2k);
763
0
      return gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_INV_PASSPHRASE);
764
0
    }
765
766
0
  return 0;
767
0
}
768
769
770
static int
771
write_symkey_enc (STRING2KEY *symkey_s2k, aead_algo_t aead_algo,
772
                  DEK *symkey_dek, DEK *dek, iobuf_t out)
773
0
{
774
0
  int rc;
775
0
  void *enckey;
776
0
  size_t enckeylen;
777
0
  PKT_symkey_enc *enc;
778
0
  PACKET pkt;
779
780
0
  rc = encrypt_seskey (symkey_dek, aead_algo, &dek, &enckey, &enckeylen);
781
0
  if (rc)
782
0
    return rc;
783
0
  enc = xtrycalloc (1, sizeof (PKT_symkey_enc));
784
0
  if (!enc)
785
0
    {
786
0
      rc = gpg_error_from_syserror ();
787
0
      xfree (enckey);
788
0
      return rc;
789
0
    }
790
791
0
  enc->version = aead_algo? 5 : 4;
792
0
  enc->cipher_algo = opt.s2k_cipher_algo;
793
0
  enc->aead_algo = aead_algo;
794
0
  enc->s2k = *symkey_s2k;
795
0
  enc->seskeylen = enckeylen;
796
0
  enc->seskey = xtrymalloc (enckeylen);
797
0
  if (!enc->seskey)
798
0
    {
799
0
      rc = gpg_error_from_syserror ();
800
0
      xfree (enc);
801
0
      xfree (enckey);
802
0
      return rc;
803
0
    }
804
0
  memcpy (enc->seskey, enckey, enckeylen);
805
0
  xfree (enckey);
806
807
0
  pkt.pkttype = PKT_SYMKEY_ENC;
808
0
  pkt.pkt.symkey_enc = enc;
809
810
0
  if ((rc=build_packet(out,&pkt)))
811
0
    log_error("build symkey_enc packet failed: %s\n",gpg_strerror (rc));
812
813
0
  free_symkey_enc (enc);
814
0
  return rc;
815
0
}
816
817
818
/*
819
 * Encrypt the file with the given userids (or ask if none is
820
 * supplied).  Either FILENAME or FILEFD must be given, but not both.
821
 * The caller may provide a checked list of public keys in
822
 * PROVIDED_KEYS; if not the function builds a list of keys on its own.
823
 *
824
 * Note that FILEFD and OUTPUTFD are currently only used by
825
 * cmd_encrypt in the not yet finished server.c.
826
 */
827
int
828
encrypt_crypt (ctrl_t ctrl, gnupg_fd_t filefd, const char *filename,
829
               strlist_t remusr, int use_symkey, pk_list_t provided_keys,
830
               gnupg_fd_t outputfd)
831
0
{
832
0
  iobuf_t inp = NULL;
833
0
  iobuf_t out = NULL;
834
0
  PACKET pkt;
835
0
  PKT_plaintext *pt = NULL;
836
0
  DEK *symkey_dek = NULL;
837
0
  STRING2KEY *symkey_s2k = NULL;
838
0
  int rc = 0;
839
0
  u32 filesize;
840
0
  cipher_filter_context_t cfx;
841
0
  armor_filter_context_t *afx = NULL;
842
0
  compress_filter_context_t zfx;
843
0
  text_filter_context_t tfx;
844
0
  progress_filter_context_t *pfx;
845
0
  PK_LIST pk_list;
846
0
  int do_compress;
847
848
0
  if (filefd != GNUPG_INVALID_FD && filename)
849
0
    return gpg_error (GPG_ERR_INV_ARG);  /* Both given.  */
850
851
0
  do_compress = !!opt.compress_algo;
852
853
0
  pfx = new_progress_context ();
854
0
  memset( &cfx, 0, sizeof cfx);
855
0
  memset( &zfx, 0, sizeof zfx);
856
0
  memset( &tfx, 0, sizeof tfx);
857
0
  init_packet(&pkt);
858
859
0
  if (use_symkey
860
0
      && (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
861
0
    {
862
0
      release_progress_context (pfx);
863
0
      return rc;
864
0
    }
865
866
0
  if (provided_keys)
867
0
    pk_list = provided_keys;
868
0
  else
869
0
    {
870
0
      if ((rc = build_pk_list (ctrl, remusr, &pk_list)))
871
0
        {
872
0
          release_progress_context (pfx);
873
0
          return rc;
874
0
        }
875
0
    }
876
877
  /* Prepare iobufs. */
878
#ifdef HAVE_W32_SYSTEM
879
  if (filefd == GNUPG_INVALID_FD)
880
    inp = iobuf_open (filename);
881
  else
882
    {
883
      inp = NULL;
884
      gpg_err_set_errno (ENOSYS);
885
    }
886
#else
887
0
  if (filefd == GNUPG_INVALID_FD)
888
0
    inp = iobuf_open (filename);
889
0
  else
890
0
    inp = iobuf_fdopen_nc (filefd, "rb");
891
0
#endif
892
0
  if (inp)
893
0
    iobuf_ioctl (inp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
894
0
  if (inp && is_secured_file (iobuf_get_fd (inp)))
895
0
    {
896
0
      iobuf_close (inp);
897
0
      inp = NULL;
898
0
      gpg_err_set_errno (EPERM);
899
0
    }
900
0
  if (!inp)
901
0
    {
902
0
      char xname[64];
903
904
0
      rc = gpg_error_from_syserror ();
905
0
      if (filefd != GNUPG_INVALID_FD)
906
0
        snprintf (xname, sizeof xname, "[fd %d]", FD_DBG (filefd));
907
0
      else if (!filename)
908
0
        strcpy (xname, "[stdin]");
909
0
      else
910
0
        *xname = 0;
911
0
      log_error (_("can't open '%s': %s\n"),
912
0
                 *xname? xname : filename, gpg_strerror (rc) );
913
0
      goto leave;
914
0
    }
915
916
0
  if (opt.verbose)
917
0
    log_info (_("reading from '%s'\n"), iobuf_get_fname_nonnull (inp));
918
919
0
  handle_progress (pfx, inp, filename);
920
921
0
  if (opt.textmode)
922
0
    iobuf_push_filter (inp, text_filter, &tfx);
923
924
0
  rc = open_outfile (outputfd, filename, opt.armor? 1:0, 0, &out);
925
0
  if (rc)
926
0
    goto leave;
927
928
0
  if (opt.armor)
929
0
    {
930
0
      afx = new_armor_context ();
931
0
      push_armor_filter (afx, out);
932
0
    }
933
934
  /* Create a session key. */
935
0
  cfx.dek = create_dek_with_warnings (pk_list);
936
937
0
  rc = check_encryption_compliance (cfx.dek, pk_list);
938
0
  if (rc)
939
0
    goto leave;
940
941
0
  cfx.dek->use_aead = use_aead (pk_list, cfx.dek->algo);
942
0
  if (!cfx.dek->use_aead)
943
0
    cfx.dek->use_mdc = !!use_mdc (pk_list, cfx.dek->algo);
944
945
0
  make_session_key (cfx.dek);
946
0
  if (DBG_CRYPTO)
947
0
    log_printhex (cfx.dek->key, cfx.dek->keylen, "DEK is: ");
948
949
0
  rc = write_pubkey_enc_from_list (ctrl, pk_list, cfx.dek, out, NULL);
950
0
  if (rc)
951
0
    goto leave;
952
953
  /* We put the passphrase (if any) after any public keys as this
954
   * seems to be the most useful on the recipient side - there is no
955
   * point in prompting a user for a passphrase if they have the
956
   * secret key needed to decrypt.  */
957
0
  if (use_symkey && (rc = write_symkey_enc (symkey_s2k, cfx.dek->use_aead,
958
0
                                            symkey_dek, cfx.dek, out)))
959
0
    goto leave;
960
961
0
  if (!opt.no_literal)
962
0
    pt = setup_plaintext_name (filename, inp);
963
964
  /* Get the size of the file if possible, i.e., if it is a real file.  */
965
0
  if (filename && *filename
966
0
      && !iobuf_is_pipe_filename (filename) && !opt.textmode )
967
0
    {
968
0
      uint64_t tmpsize;
969
970
0
      tmpsize = iobuf_get_filelength (inp);
971
0
      if (!tmpsize && opt.verbose)
972
0
        log_info(_("WARNING: '%s' is an empty file\n"), filename );
973
      /* We can't encode the length of very large files because
974
         OpenPGP uses only 32 bit for file sizes.  So if the size
975
         of a file is larger than 2^32 minus some bytes for packet
976
         headers, we switch to partial length encoding. */
977
0
      if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
978
0
        filesize = tmpsize;
979
0
      else
980
0
        filesize = 0;
981
0
    }
982
0
  else
983
0
    filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
984
985
  /* Register the cipher filter. */
986
0
  iobuf_push_filter (out,
987
0
                     cfx.dek->use_aead? cipher_filter_aead
988
0
                     /**/             : cipher_filter_cfb,
989
0
                     &cfx);
990
991
  /* Only do the is-file-already-compressed check if we are using a
992
   * MDC or AEAD.  This forces compressed files to be re-compressed if
993
   * we do not have a MDC to give some protection against chosen
994
   * ciphertext attacks. */
995
0
  if (do_compress
996
0
      && (cfx.dek->use_mdc || cfx.dek->use_aead)
997
0
      && !opt.explicit_compress_option
998
0
      && is_file_compressed (inp))
999
0
    {
1000
0
      if (opt.verbose)
1001
0
        log_info(_("'%s' already compressed\n"), filename? filename: "[stdin]");
1002
0
      do_compress = 0;
1003
0
    }
1004
1005
0
  if (!opt.no_literal)
1006
0
    {
1007
0
      pt->timestamp = make_timestamp();
1008
0
      pt->mode = opt.mimemode? 'm' : opt.textmode ? 't' : 'b';
1009
0
      pt->len = filesize;
1010
0
      pt->new_ctb = !pt->len;
1011
0
      pt->buf = inp;
1012
0
      pkt.pkttype = PKT_PLAINTEXT;
1013
0
      pkt.pkt.plaintext = pt;
1014
0
      cfx.datalen = filesize && !do_compress? calc_packet_length( &pkt ) : 0;
1015
0
    }
1016
0
  else
1017
0
    cfx.datalen = filesize && !do_compress ? filesize : 0;
1018
1019
  /* Register the compress filter. */
1020
0
  if (do_compress)
1021
0
    {
1022
0
      int compr_algo = opt.compress_algo;
1023
1024
0
      if (compr_algo == -1)
1025
0
        {
1026
0
          compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP, -1, NULL);
1027
0
          if (compr_algo == -1)
1028
0
            compr_algo = DEFAULT_COMPRESS_ALGO;
1029
          /* Theoretically impossible to get here since uncompressed
1030
             is implicit.  */
1031
0
        }
1032
0
      else if (!opt.expert
1033
0
               && select_algo_from_prefs(pk_list, PREFTYPE_ZIP,
1034
0
                                         compr_algo, NULL) != compr_algo)
1035
0
        {
1036
0
          log_info (_("WARNING: forcing compression algorithm %s (%d)"
1037
0
                      " violates recipient preferences\n"),
1038
0
                    compress_algo_to_string(compr_algo), compr_algo);
1039
0
        }
1040
1041
      /* Algo 0 means no compression. */
1042
0
      if (compr_algo)
1043
0
        {
1044
0
          if (cfx.dek && (cfx.dek->use_mdc || cfx.dek->use_aead))
1045
0
            zfx.new_ctb = 1;
1046
0
          push_compress_filter (out,&zfx,compr_algo);
1047
0
        }
1048
0
    }
1049
1050
  /* Do the work. */
1051
0
  if (!opt.no_literal)
1052
0
    {
1053
0
      if ((rc = build_packet( out, &pkt )))
1054
0
        log_error ("build_packet failed: %s\n", gpg_strerror (rc));
1055
0
    }
1056
0
  else
1057
0
    {
1058
      /* User requested not to create a literal packet, so we copy the
1059
         plain data. */
1060
0
      iobuf_copy (out, inp);
1061
0
      if ((rc = iobuf_error (inp)))
1062
0
        log_error (_("error reading '%s': %s\n"),
1063
0
                   iobuf_get_fname_nonnull (inp), gpg_strerror (rc));
1064
0
      else if ((rc = iobuf_error (out)))
1065
0
        log_error (_("error writing '%s': %s\n"),
1066
0
                   iobuf_get_fname_nonnull (out), gpg_strerror (rc));
1067
1068
0
    }
1069
1070
  /* Finish the stuff. */
1071
0
 leave:
1072
0
  iobuf_close (inp);
1073
0
  if (rc)
1074
0
    iobuf_cancel (out);
1075
0
  else
1076
0
    {
1077
0
      iobuf_close (out); /* fixme: check returncode */
1078
0
      write_status (STATUS_END_ENCRYPTION);
1079
0
    }
1080
0
  if (pt)
1081
0
    pt->buf = NULL;
1082
0
  free_packet (&pkt, NULL);
1083
0
  xfree (cfx.dek);
1084
0
  xfree (symkey_dek);
1085
0
  xfree (symkey_s2k);
1086
0
  if (!provided_keys)
1087
0
    release_pk_list (pk_list);
1088
0
  release_armor_context (afx);
1089
0
  release_progress_context (pfx);
1090
0
  return rc;
1091
0
}
1092
1093
1094
/* Re-encrypt files with a set of new recipients.  Note that this
1095
 * function is called by decrypt_message.  INFP is the iobuf from the
1096
 * input file which is positioned right after the pubkey_enc and
1097
 * symkey_enc packets.  */
1098
gpg_error_t
1099
reencrypt_to_new_recipients (ctrl_t ctrl, int armor, const char *filename,
1100
                             iobuf_t infp, strlist_t recipients,
1101
                             DEK *dek, struct seskey_enc_list *sesenc_list)
1102
0
{
1103
0
  gpg_error_t err;
1104
0
  int save_no_encrypt_to;
1105
0
  pk_list_t newpk_list = NULL;
1106
0
  struct pubkey_enc_info_item *restrict_pk_list = NULL;
1107
0
  struct pubkey_enc_info_item *pkei;  /* Iterator */
1108
0
  iobuf_t outfp = NULL;
1109
0
  armor_filter_context_t *outafx = NULL;
1110
0
  PACKET pkt;
1111
0
  struct seskey_enc_list *el;
1112
0
  unsigned int count;
1113
1114
  /* Unless we want to clear the recipients, record the pubkey encrypt
1115
   * infos so hat we can avoid to double encrypt to the same
1116
   * recipient.  We can't do that for wildcards, though.  */
1117
0
  if (!ctrl->clear_recipients)
1118
0
    {
1119
0
      for (el = sesenc_list; el; el = el->next)
1120
0
        {
1121
0
          if (el->u_sym)
1122
0
            continue;
1123
0
          if (!el->u.pub.keyid[0] && !el->u.pub.keyid[1])
1124
0
            continue;  /* Wildcard encrypt - no useful info.  */
1125
0
          pkei = xcalloc (1, sizeof *pkei);
1126
0
          pkei->keyid[0] = el->u.pub.keyid[0];
1127
0
          pkei->keyid[1] = el->u.pub.keyid[1];
1128
0
          pkei->version  = el->u.pub.version;
1129
0
          pkei->pubkey_algo  = el->u.pub.pubkey_algo;
1130
0
          pkei->next = restrict_pk_list;
1131
0
          restrict_pk_list = pkei;
1132
0
        }
1133
0
    }
1134
1135
  /* Get the keys for all additional recipients but do not encrypt to
1136
   * the encrypt-to keys. */
1137
0
  save_no_encrypt_to = opt.no_encrypt_to;
1138
0
  opt.no_encrypt_to = 1;
1139
0
  err = build_pk_list (ctrl, recipients, &newpk_list);
1140
0
  opt.no_encrypt_to = save_no_encrypt_to;
1141
0
  if (err)
1142
0
    goto leave;
1143
1144
  /* Note that we use by default the suffixes .gpg or .asc */
1145
0
  err = open_outfile (GNUPG_INVALID_FD, filename, armor? 1:0, 0, &outfp);
1146
0
  if (err)
1147
0
    goto leave;
1148
1149
0
  if (armor)
1150
0
    {
1151
0
      outafx = new_armor_context ();
1152
0
      push_armor_filter (outafx, outfp);
1153
0
    }
1154
1155
  /* Write the new recipients first.  */
1156
0
  err = write_pubkey_enc_from_list (ctrl, newpk_list, dek, outfp,
1157
0
                                    restrict_pk_list);
1158
0
  if (err)
1159
0
    goto leave;
1160
1161
  /* Write the old recipients in --add-recipients mode.  */
1162
0
  for (count=0, el = sesenc_list; el; el = el->next, count++)
1163
0
    if (!ctrl->clear_recipients && !el->u_sym)
1164
0
      {
1165
0
        if (opt.verbose)
1166
0
          show_encrypted_for_user_info (ctrl, 0, &el->u.pub, dek);
1167
0
        init_packet (&pkt);
1168
0
        pkt.pkttype = PKT_PUBKEY_ENC;
1169
0
        pkt.pkt.pubkey_enc = &el->u.pub;
1170
0
        err = build_packet (outfp, &pkt);
1171
0
        if (err)
1172
0
          log_error ("build_packet(pubkey_enc) failed: %s\n",
1173
0
                     gpg_strerror (err));
1174
0
      }
1175
0
  if (ctrl->clear_recipients && opt.verbose)
1176
0
    log_info (_("number of removed recipients: %u\n"), count);
1177
1178
0
  iobuf_put (outfp, ctrl->last_read_ctb);
1179
1180
  /* Finally copy the bulk of the message.  */
1181
0
  iobuf_copy (outfp, infp);
1182
0
  if ((err = iobuf_error (infp)))
1183
0
    log_error (_("error reading '%s': %s\n"),
1184
0
               iobuf_get_fname_nonnull (infp), gpg_strerror (err));
1185
0
  else if ((err = iobuf_error (outfp)))
1186
0
    log_error (_("error writing '%s': %s\n"),
1187
0
               iobuf_get_fname_nonnull (outfp), gpg_strerror (err));
1188
1189
1190
0
 leave:
1191
0
  if (err)
1192
0
    iobuf_cancel (outfp);
1193
0
  else
1194
0
    iobuf_close (outfp);
1195
0
  release_armor_context (outafx);
1196
0
  release_pk_list (newpk_list);
1197
0
  while (restrict_pk_list)
1198
0
    {
1199
0
      pkei = restrict_pk_list->next;
1200
0
      xfree (restrict_pk_list);
1201
0
      restrict_pk_list = pkei;
1202
0
    }
1203
0
  return err;
1204
0
}
1205
1206
1207

1208
/*
1209
 * Filter to do a complete public key encryption.
1210
 */
1211
int
1212
encrypt_filter (void *opaque, int control,
1213
                iobuf_t a, byte *buf, size_t *ret_len)
1214
0
{
1215
0
  size_t size = *ret_len;
1216
0
  encrypt_filter_context_t *efx = opaque;
1217
0
  int rc = 0;
1218
1219
0
  if (control == IOBUFCTRL_UNDERFLOW) /* decrypt */
1220
0
    {
1221
0
      BUG(); /* not used */
1222
0
    }
1223
0
  else if ( control == IOBUFCTRL_FLUSH ) /* encrypt */
1224
0
    {
1225
0
      if ( !efx->header_okay )
1226
0
        {
1227
0
          efx->header_okay = 1;
1228
1229
0
          efx->cfx.dek = create_dek_with_warnings (efx->pk_list);
1230
1231
0
          rc = check_encryption_compliance (efx->cfx.dek, efx->pk_list);
1232
0
          if (rc)
1233
0
            return rc;
1234
1235
0
          efx->cfx.dek->use_aead = use_aead (efx->pk_list, efx->cfx.dek->algo);
1236
0
          if (!efx->cfx.dek->use_aead)
1237
0
            efx->cfx.dek->use_mdc = !!use_mdc (efx->pk_list,efx->cfx.dek->algo);
1238
1239
0
          make_session_key ( efx->cfx.dek );
1240
0
          if (DBG_CRYPTO)
1241
0
            log_printhex (efx->cfx.dek->key, efx->cfx.dek->keylen, "DEK is: ");
1242
1243
0
          rc = write_pubkey_enc_from_list (efx->ctrl,
1244
0
                                           efx->pk_list, efx->cfx.dek, a, NULL);
1245
0
          if (rc)
1246
0
            return rc;
1247
1248
0
          if(efx->symkey_s2k && efx->symkey_dek)
1249
0
            {
1250
0
              rc = write_symkey_enc (efx->symkey_s2k, efx->cfx.dek->use_aead,
1251
0
                                     efx->symkey_dek, efx->cfx.dek, a);
1252
0
              if (rc)
1253
0
                return rc;
1254
0
            }
1255
1256
0
          iobuf_push_filter (a,
1257
0
                             efx->cfx.dek->use_aead? cipher_filter_aead
1258
0
                             /**/                  : cipher_filter_cfb,
1259
0
                             &efx->cfx);
1260
1261
0
        }
1262
0
      rc = iobuf_write (a, buf, size);
1263
1264
0
    }
1265
0
  else if (control == IOBUFCTRL_FREE)
1266
0
    {
1267
0
      xfree (efx->symkey_dek);
1268
0
      xfree (efx->symkey_s2k);
1269
0
    }
1270
0
  else if ( control == IOBUFCTRL_DESC )
1271
0
    {
1272
0
      mem2str (buf, "encrypt_filter", *ret_len);
1273
0
    }
1274
0
  return rc;
1275
0
}
1276
1277
1278
/*
1279
 * Write a pubkey-enc packet for the public key PK to OUT.
1280
 */
1281
int
1282
write_pubkey_enc (ctrl_t ctrl,
1283
                  PKT_public_key *pk, int throw_keyid, DEK *dek, iobuf_t out)
1284
0
{
1285
0
  PACKET pkt;
1286
0
  PKT_pubkey_enc *enc;
1287
0
  int rc;
1288
0
  gcry_mpi_t frame;
1289
1290
0
  print_pubkey_algo_note ( pk->pubkey_algo );
1291
0
  enc = xmalloc_clear ( sizeof *enc );
1292
0
  enc->pubkey_algo = pk->pubkey_algo;
1293
0
  keyid_from_pk( pk, enc->keyid );
1294
0
  enc->throw_keyid = throw_keyid;
1295
0
  enc->seskey_algo = dek->algo;  /* (Used only by PUBKEY_ALGO_KYBER.) */
1296
1297
  /* Okay, what's going on: We have the session key somewhere in
1298
   * the structure DEK and want to encode this session key in an
1299
   * integer value of n bits. pubkey_nbits gives us the number of
1300
   * bits we have to use.  We then encode the session key in some
1301
   * way and we get it back in the big integer value FRAME.  Then
1302
   * we use FRAME, the public key PK->PKEY and the algorithm
1303
   * number PK->PUBKEY_ALGO and pass it to pubkey_encrypt which
1304
   * returns the encrypted value in the array ENC->DATA.  This
1305
   * array has a size which depends on the used algorithm (e.g. 2
1306
   * for Elgamal).  We don't need frame anymore because we have
1307
   * everything now in enc->data which is the passed to
1308
   * build_packet().  */
1309
0
  frame = encode_session_key (pk->pubkey_algo, dek,
1310
0
                              pubkey_nbits (pk->pubkey_algo, pk->pkey));
1311
0
  rc = pk_encrypt (pk, frame, dek->algo, enc->data);
1312
0
  gcry_mpi_release (frame);
1313
0
  if (rc)
1314
0
    log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
1315
0
  else
1316
0
    {
1317
0
      if ( opt.verbose )
1318
0
        show_encrypted_for_user_info (ctrl, pk->pubkey_usage, enc, dek);
1319
      /* And write it. */
1320
0
      init_packet (&pkt);
1321
0
      pkt.pkttype = PKT_PUBKEY_ENC;
1322
0
      pkt.pkt.pubkey_enc = enc;
1323
0
      rc = build_packet (out, &pkt);
1324
0
      if (rc)
1325
0
        log_error ("build_packet(pubkey_enc) failed: %s\n",
1326
0
                   gpg_strerror (rc));
1327
0
    }
1328
0
  free_pubkey_enc(enc);
1329
0
  return rc;
1330
0
}
1331
1332
1333
/*
1334
 * Write pubkey-enc packets from the list of PKs PKLIST to OUT.  DEK
1335
 * has the session key.  If a packet with the same key is also found
1336
 * in RESTRICT_PK_LIST, it is not written.
1337
 */
1338
static int
1339
write_pubkey_enc_from_list (ctrl_t ctrl, pk_list_t pk_list, DEK *dek,
1340
                            iobuf_t out,
1341
                            struct pubkey_enc_info_item *restrict_pk_list)
1342
0
{
1343
0
  PKT_public_key *pk;
1344
0
  struct pubkey_enc_info_item *pkei;
1345
0
  int throw_keyid, rc;
1346
1347
0
  if (opt.throw_keyids && (PGP7 || PGP8))
1348
0
    {
1349
0
      log_info(_("option '%s' may not be used in %s mode\n"),
1350
0
               "--throw-keyids",
1351
0
               gnupg_compliance_option_string (opt.compliance));
1352
0
      compliance_failure();
1353
0
    }
1354
1355
0
  for ( ; pk_list; pk_list = pk_list->next )
1356
0
    {
1357
0
      pk = pk_list->pk;
1358
0
      for (pkei = restrict_pk_list; pkei; pkei = pkei->next)
1359
0
        if (pk->keyid[0] == pkei->keyid[0]
1360
0
            && pk->keyid[1] == pkei->keyid[1]
1361
0
            && pk->version == pkei->version
1362
0
            && pk->pubkey_algo == pkei->pubkey_algo)
1363
0
          break;
1364
0
      if (pkei)
1365
0
        {
1366
0
          if (opt.verbose)
1367
0
            log_info (_("already encrypted to %08lX\n"),
1368
0
                      (ulong) keyid_from_pk (pk, NULL));
1369
0
          continue;
1370
0
        }
1371
1372
0
      throw_keyid = (opt.throw_keyids || (pk_list->flags&1));
1373
0
      rc = write_pubkey_enc (ctrl, pk, throw_keyid, dek, out);
1374
0
      if (rc)
1375
0
        return rc;
1376
0
    }
1377
1378
0
  return 0;
1379
0
}
1380
1381
void
1382
encrypt_crypt_files (ctrl_t ctrl, int nfiles, char **files, strlist_t remusr)
1383
0
{
1384
0
  int rc = 0;
1385
1386
0
  if (opt.outfile)
1387
0
    {
1388
0
      log_error(_("--output doesn't work for this command\n"));
1389
0
      return;
1390
0
    }
1391
1392
0
  if (!nfiles)
1393
0
    {
1394
0
      char line[2048];
1395
0
      unsigned int lno = 0;
1396
0
      while ( fgets(line, DIM(line), stdin) )
1397
0
        {
1398
0
          lno++;
1399
0
          if (!*line || line[strlen(line)-1] != '\n')
1400
0
            {
1401
0
              log_error("input line %u too long or missing LF\n", lno);
1402
0
              return;
1403
0
            }
1404
0
          line[strlen(line)-1] = '\0';
1405
0
          print_file_status(STATUS_FILE_START, line, 2);
1406
0
          rc = encrypt_crypt (ctrl, GNUPG_INVALID_FD, line, remusr,
1407
0
                              0, NULL, GNUPG_INVALID_FD);
1408
0
          if (rc)
1409
0
            log_error ("encryption of '%s' failed: %s\n",
1410
0
                       print_fname_stdin(line), gpg_strerror (rc) );
1411
0
          write_status( STATUS_FILE_DONE );
1412
0
        }
1413
0
    }
1414
0
  else
1415
0
    {
1416
0
      while (nfiles--)
1417
0
        {
1418
0
          print_file_status(STATUS_FILE_START, *files, 2);
1419
0
          if ((rc = encrypt_crypt (ctrl, GNUPG_INVALID_FD, *files, remusr,
1420
0
                                   0, NULL, GNUPG_INVALID_FD)))
1421
0
            log_error("encryption of '%s' failed: %s\n",
1422
0
                      print_fname_stdin(*files), gpg_strerror (rc) );
1423
0
          write_status( STATUS_FILE_DONE );
1424
0
          files++;
1425
0
        }
1426
0
    }
1427
0
}