Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / g10 / encrypt.c
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 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "../common/status.h"
32 #include "../common/iobuf.h"
33 #include "keydb.h"
34 #include "../common/util.h"
35 #include "main.h"
36 #include "filter.h"
37 #include "trustdb.h"
38 #include "../common/i18n.h"
39 #include "../common/status.h"
40 #include "pkglue.h"
41 #include "../common/compliance.h"
42
43
44 static int encrypt_simple( const char *filename, int mode, int use_seskey );
45 static int write_pubkey_enc_from_list (ctrl_t ctrl,
46                                        PK_LIST pk_list, DEK *dek, iobuf_t out);
47
48 /****************
49  * Encrypt FILENAME with only the symmetric cipher.  Take input from
50  * stdin if FILENAME is NULL.
51  */
52 int
53 encrypt_symmetric (const char *filename)
54 {
55   return encrypt_simple( filename, 1, 0 );
56 }
57
58
59 /****************
60  * Encrypt FILENAME as a literal data packet only. Take input from
61  * stdin if FILENAME is NULL.
62  */
63 int
64 encrypt_store (const char *filename)
65 {
66   return encrypt_simple( filename, 0, 0 );
67 }
68
69
70 /* *SESKEY contains the unencrypted session key ((*SESKEY)->KEY) and
71    the algorithm that will be used to encrypt the contents of the SED
72    packet ((*SESKEY)->ALGO).  If *SESKEY is NULL, then a random
73    session key that is appropriate for DEK->ALGO is generated and
74    stored there.
75
76    Encrypt that session key using DEK and store the result in ENCKEY,
77    which must be large enough to hold (*SESKEY)->KEYLEN + 1 bytes.  */
78 void
79 encrypt_seskey (DEK *dek, DEK **seskey, byte *enckey)
80 {
81   gcry_cipher_hd_t hd;
82   byte buf[33];
83
84   log_assert ( dek->keylen <= 32 );
85   if (!*seskey)
86     {
87       *seskey=xmalloc_clear(sizeof(DEK));
88       (*seskey)->algo=dek->algo;
89       make_session_key(*seskey);
90       /*log_hexdump( "thekey", c->key, c->keylen );*/
91     }
92
93   /* The encrypted session key is prefixed with a one-octet algorithm id.  */
94   buf[0] = (*seskey)->algo;
95   memcpy( buf + 1, (*seskey)->key, (*seskey)->keylen );
96
97   /* We only pass already checked values to the following function,
98      thus we consider any failure as fatal.  */
99   if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
100     BUG ();
101   if (gcry_cipher_setkey (hd, dek->key, dek->keylen))
102     BUG ();
103   gcry_cipher_setiv (hd, NULL, 0);
104   gcry_cipher_encrypt (hd, buf, (*seskey)->keylen + 1, NULL, 0);
105   gcry_cipher_close (hd);
106
107   memcpy( enckey, buf, (*seskey)->keylen + 1 );
108   wipememory( buf, sizeof buf ); /* burn key */
109 }
110
111
112 /* Shall we use the MDC?  Yes - unless rfc-2440 compatibility is
113  * requested.  Must return 1 or 0. */
114 int
115 use_mdc (pk_list_t pk_list,int algo)
116 {
117   (void)pk_list;
118   (void)algo;
119
120   /* RFC-2440 don't has MDC - this is the only way to create a legacy
121    * non-MDC encryption packet.  */
122   if (RFC2440)
123     return 0;
124
125   return 1; /* In all other cases we use the MDC */
126 }
127
128
129 /* We don't want to use use_seskey yet because older gnupg versions
130    can't handle it, and there isn't really any point unless we're
131    making a message that can be decrypted by a public key or
132    passphrase. */
133 static int
134 encrypt_simple (const char *filename, int mode, int use_seskey)
135 {
136   iobuf_t inp, out;
137   PACKET pkt;
138   PKT_plaintext *pt = NULL;
139   STRING2KEY *s2k = NULL;
140   byte enckey[33];
141   int rc = 0;
142   int seskeylen = 0;
143   u32 filesize;
144   cipher_filter_context_t cfx;
145   armor_filter_context_t  *afx = NULL;
146   compress_filter_context_t zfx;
147   text_filter_context_t tfx;
148   progress_filter_context_t *pfx;
149   int do_compress = !!default_compress_algo();
150
151   if (!gnupg_rng_is_compliant (opt.compliance))
152     {
153       rc = gpg_error (GPG_ERR_FORBIDDEN);
154       log_error (_("%s is not compliant with %s mode\n"),
155                  "RNG",
156                  gnupg_compliance_option_string (opt.compliance));
157       write_status_error ("random-compliance", rc);
158       return rc;
159     }
160
161   pfx = new_progress_context ();
162   memset( &cfx, 0, sizeof cfx);
163   memset( &zfx, 0, sizeof zfx);
164   memset( &tfx, 0, sizeof tfx);
165   init_packet(&pkt);
166
167   /* Prepare iobufs. */
168   inp = iobuf_open(filename);
169   if (inp)
170     iobuf_ioctl (inp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
171   if (inp && is_secured_file (iobuf_get_fd (inp)))
172     {
173       iobuf_close (inp);
174       inp = NULL;
175       gpg_err_set_errno (EPERM);
176     }
177   if (!inp)
178     {
179       rc = gpg_error_from_syserror ();
180       log_error(_("can't open '%s': %s\n"), filename? filename: "[stdin]",
181                 strerror(errno) );
182       release_progress_context (pfx);
183       return rc;
184     }
185
186   handle_progress (pfx, inp, filename);
187
188   if (opt.textmode)
189     iobuf_push_filter( inp, text_filter, &tfx );
190
191   cfx.dek = NULL;
192   if ( mode )
193     {
194       rc = setup_symkey (&s2k, &cfx.dek);
195       if (rc)
196         {
197           iobuf_close (inp);
198           if (gpg_err_code (rc) == GPG_ERR_CIPHER_ALGO
199               || gpg_err_code (rc) == GPG_ERR_DIGEST_ALGO)
200             ; /* Error has already been printed.  */
201           else
202             log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
203           release_progress_context (pfx);
204           return rc;
205         }
206       if (use_seskey && s2k->mode != 1 && s2k->mode != 3)
207         {
208           use_seskey = 0;
209           log_info (_("can't use a symmetric ESK packet "
210                       "due to the S2K mode\n"));
211         }
212
213       if ( use_seskey )
214         {
215           DEK *dek = NULL;
216
217           seskeylen = openpgp_cipher_get_algo_keylen (default_cipher_algo ());
218           encrypt_seskey( cfx.dek, &dek, enckey );
219           xfree( cfx.dek ); cfx.dek = dek;
220         }
221
222       if (opt.verbose)
223         log_info(_("using cipher %s\n"),
224                  openpgp_cipher_algo_name (cfx.dek->algo));
225
226       cfx.dek->use_mdc=use_mdc(NULL,cfx.dek->algo);
227     }
228
229   if (do_compress && cfx.dek && cfx.dek->use_mdc
230       && is_file_compressed(filename, &rc))
231     {
232       if (opt.verbose)
233         log_info(_("'%s' already compressed\n"), filename);
234       do_compress = 0;
235     }
236
237   if ( rc || (rc = open_outfile (-1, filename, opt.armor? 1:0, 0, &out )))
238     {
239       iobuf_cancel (inp);
240       xfree (cfx.dek);
241       xfree (s2k);
242       release_progress_context (pfx);
243       return rc;
244     }
245
246   if ( opt.armor )
247     {
248       afx = new_armor_context ();
249       push_armor_filter (afx, out);
250     }
251
252   if ( s2k )
253     {
254       PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc + seskeylen + 1 );
255       enc->version = 4;
256       enc->cipher_algo = cfx.dek->algo;
257       enc->s2k = *s2k;
258       if ( use_seskey && seskeylen )
259         {
260           enc->seskeylen = seskeylen + 1; /* algo id */
261           memcpy (enc->seskey, enckey, seskeylen + 1 );
262         }
263       pkt.pkttype = PKT_SYMKEY_ENC;
264       pkt.pkt.symkey_enc = enc;
265       if ((rc = build_packet( out, &pkt )))
266         log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
267       xfree (enc);
268     }
269
270   if (!opt.no_literal)
271     pt = setup_plaintext_name (filename, inp);
272
273   /* Note that PGP 5 has problems decrypting symmetrically encrypted
274      data if the file length is in the inner packet. It works when
275      only partial length headers are use.  In the past, we always used
276      partial body length here, but since PGP 2, PGP 6, and PGP 7 need
277      the file length, and nobody should be using PGP 5 nowadays
278      anyway, this is now set to the file length.  Note also that this
279      only applies to the RFC-1991 style symmetric messages, and not
280      the RFC-2440 style.  PGP 6 and 7 work with either partial length
281      or fixed length with the new style messages. */
282
283   if ( !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
284     {
285       off_t tmpsize;
286       int overflow;
287
288       if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
289            && !overflow && opt.verbose)
290         log_info(_("WARNING: '%s' is an empty file\n"), filename );
291       /* We can't encode the length of very large files because
292          OpenPGP uses only 32 bit for file sizes.  So if the
293          size of a file is larger than 2^32 minus some bytes for
294          packet headers, we switch to partial length encoding. */
295       if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
296         filesize = tmpsize;
297       else
298         filesize = 0;
299     }
300   else
301     filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
302
303   if (!opt.no_literal)
304     {
305       /* Note that PT has been initialized above in !no_literal mode.  */
306       pt->timestamp = make_timestamp();
307       pt->mode = opt.mimemode? 'm' : opt.textmode? 't' : 'b';
308       pt->len = filesize;
309       pt->new_ctb = !pt->len;
310       pt->buf = inp;
311       pkt.pkttype = PKT_PLAINTEXT;
312       pkt.pkt.plaintext = pt;
313       cfx.datalen = filesize && !do_compress ? calc_packet_length( &pkt ) : 0;
314     }
315   else
316     {
317       cfx.datalen = filesize && !do_compress ? filesize : 0;
318       pkt.pkttype = 0;
319       pkt.pkt.generic = NULL;
320     }
321
322   /* Register the cipher filter. */
323   if (mode)
324     iobuf_push_filter ( out, cipher_filter, &cfx );
325
326   /* Register the compress filter. */
327   if ( do_compress )
328     {
329       if (cfx.dek && cfx.dek->use_mdc)
330         zfx.new_ctb = 1;
331       push_compress_filter (out, &zfx, default_compress_algo());
332     }
333
334   /* Do the work. */
335   if (!opt.no_literal)
336     {
337       if ( (rc = build_packet( out, &pkt )) )
338         log_error("build_packet failed: %s\n", gpg_strerror (rc) );
339     }
340   else
341     {
342       /* User requested not to create a literal packet, so we copy the
343          plain data.  */
344     byte copy_buffer[4096];
345     int  bytes_copied;
346     while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
347       if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
348         log_error ("copying input to output failed: %s\n",
349                    gpg_strerror (rc) );
350         break;
351       }
352     wipememory (copy_buffer, 4096); /* burn buffer */
353     }
354
355   /* Finish the stuff.  */
356   iobuf_close (inp);
357   if (rc)
358     iobuf_cancel(out);
359   else
360     {
361       iobuf_close (out); /* fixme: check returncode */
362       if (mode)
363         write_status ( STATUS_END_ENCRYPTION );
364     }
365   if (pt)
366     pt->buf = NULL;
367   free_packet (&pkt, NULL);
368   xfree (cfx.dek);
369   xfree (s2k);
370   release_armor_context (afx);
371   release_progress_context (pfx);
372   return rc;
373 }
374
375
376 gpg_error_t
377 setup_symkey (STRING2KEY **symkey_s2k, DEK **symkey_dek)
378 {
379   int canceled;
380   int defcipher;
381   int s2kdigest;
382
383   defcipher = default_cipher_algo ();
384   if (!gnupg_cipher_is_allowed (opt.compliance, 1, defcipher,
385                                 GCRY_CIPHER_MODE_CFB))
386     {
387       log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
388                  openpgp_cipher_algo_name (defcipher),
389                  gnupg_compliance_option_string (opt.compliance));
390       return gpg_error (GPG_ERR_CIPHER_ALGO);
391     }
392
393   s2kdigest = S2K_DIGEST_ALGO;
394   if (!gnupg_digest_is_allowed (opt.compliance, 1, s2kdigest))
395     {
396       log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
397                  gcry_md_algo_name (s2kdigest),
398                  gnupg_compliance_option_string (opt.compliance));
399       return gpg_error (GPG_ERR_DIGEST_ALGO);
400     }
401
402   *symkey_s2k = xmalloc_clear (sizeof **symkey_s2k);
403   (*symkey_s2k)->mode = opt.s2k_mode;
404   (*symkey_s2k)->hash_algo = s2kdigest;
405
406   *symkey_dek = passphrase_to_dek (defcipher,
407                                    *symkey_s2k, 1, 0, NULL, 0, &canceled);
408   if (!*symkey_dek || !(*symkey_dek)->keylen)
409     {
410       xfree(*symkey_dek);
411       xfree(*symkey_s2k);
412       return gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_INV_PASSPHRASE);
413     }
414
415   return 0;
416 }
417
418
419 static int
420 write_symkey_enc (STRING2KEY *symkey_s2k, DEK *symkey_dek, DEK *dek,
421                   iobuf_t out)
422 {
423   int rc, seskeylen = openpgp_cipher_get_algo_keylen (dek->algo);
424
425   PKT_symkey_enc *enc;
426   byte enckey[33];
427   PACKET pkt;
428
429   enc=xmalloc_clear(sizeof(PKT_symkey_enc)+seskeylen+1);
430   encrypt_seskey(symkey_dek,&dek,enckey);
431
432   enc->version = 4;
433   enc->cipher_algo = opt.s2k_cipher_algo;
434   enc->s2k = *symkey_s2k;
435   enc->seskeylen = seskeylen + 1; /* algo id */
436   memcpy( enc->seskey, enckey, seskeylen + 1 );
437
438   pkt.pkttype = PKT_SYMKEY_ENC;
439   pkt.pkt.symkey_enc = enc;
440
441   if ((rc=build_packet(out,&pkt)))
442     log_error("build symkey_enc packet failed: %s\n",gpg_strerror (rc));
443
444   xfree(enc);
445   return rc;
446 }
447
448
449 /*
450  * Encrypt the file with the given userids (or ask if none is
451  * supplied).  Either FILENAME or FILEFD must be given, but not both.
452  * The caller may provide a checked list of public keys in
453  * PROVIDED_PKS; if not the function builds a list of keys on its own.
454  *
455  * Note that FILEFD is currently only used by cmd_encrypt in the
456  * not yet finished server.c.
457  */
458 int
459 encrypt_crypt (ctrl_t ctrl, int filefd, const char *filename,
460                strlist_t remusr, int use_symkey, pk_list_t provided_keys,
461                int outputfd)
462 {
463   iobuf_t inp = NULL;
464   iobuf_t out = NULL;
465   PACKET pkt;
466   PKT_plaintext *pt = NULL;
467   DEK *symkey_dek = NULL;
468   STRING2KEY *symkey_s2k = NULL;
469   int rc = 0, rc2 = 0;
470   u32 filesize;
471   cipher_filter_context_t cfx;
472   armor_filter_context_t *afx = NULL;
473   compress_filter_context_t zfx;
474   text_filter_context_t tfx;
475   progress_filter_context_t *pfx;
476   PK_LIST pk_list;
477   int do_compress;
478   int compliant;
479
480   if (filefd != -1 && filename)
481     return gpg_error (GPG_ERR_INV_ARG);  /* Both given.  */
482
483   do_compress = !!opt.compress_algo;
484
485   pfx = new_progress_context ();
486   memset( &cfx, 0, sizeof cfx);
487   memset( &zfx, 0, sizeof zfx);
488   memset( &tfx, 0, sizeof tfx);
489   init_packet(&pkt);
490
491   if (use_symkey
492       && (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
493     {
494       release_progress_context (pfx);
495       return rc;
496     }
497
498   if (provided_keys)
499     pk_list = provided_keys;
500   else
501     {
502       if ((rc = build_pk_list (ctrl, remusr, &pk_list)))
503         {
504           release_progress_context (pfx);
505           return rc;
506         }
507     }
508
509   /* Prepare iobufs. */
510 #ifdef HAVE_W32_SYSTEM
511   if (filefd == -1)
512     inp = iobuf_open (filename);
513   else
514     {
515       inp = NULL;
516       gpg_err_set_errno (ENOSYS);
517     }
518 #else
519   if (filefd == GNUPG_INVALID_FD)
520     inp = iobuf_open (filename);
521   else
522     inp = iobuf_fdopen_nc (FD2INT(filefd), "rb");
523 #endif
524   if (inp)
525     iobuf_ioctl (inp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
526   if (inp && is_secured_file (iobuf_get_fd (inp)))
527     {
528       iobuf_close (inp);
529       inp = NULL;
530       gpg_err_set_errno (EPERM);
531     }
532   if (!inp)
533     {
534       char xname[64];
535
536       rc = gpg_error_from_syserror ();
537       if (filefd != -1)
538         snprintf (xname, sizeof xname, "[fd %d]", filefd);
539       else if (!filename)
540         strcpy (xname, "[stdin]");
541       else
542         *xname = 0;
543       log_error (_("can't open '%s': %s\n"),
544                  *xname? xname : filename, gpg_strerror (rc) );
545       goto leave;
546     }
547
548   if (opt.verbose)
549     log_info (_("reading from '%s'\n"), iobuf_get_fname_nonnull (inp));
550
551   handle_progress (pfx, inp, filename);
552
553   if (opt.textmode)
554     iobuf_push_filter (inp, text_filter, &tfx);
555
556   rc = open_outfile (outputfd, filename, opt.armor? 1:0, 0, &out);
557   if (rc)
558     goto leave;
559
560   if (opt.armor)
561     {
562       afx = new_armor_context ();
563       push_armor_filter (afx, out);
564     }
565
566   /* Create a session key. */
567   cfx.dek = xmalloc_secure_clear (sizeof *cfx.dek);
568   if (!opt.def_cipher_algo)
569     {
570       /* Try to get it from the prefs.  */
571       cfx.dek->algo = select_algo_from_prefs (pk_list, PREFTYPE_SYM, -1, NULL);
572       /* The only way select_algo_from_prefs can fail here is when
573          mixing v3 and v4 keys, as v4 keys have an implicit preference
574          entry for 3DES, and the pk_list cannot be empty.  In this
575          case, use 3DES anyway as it's the safest choice - perhaps the
576          v3 key is being used in an OpenPGP implementation and we know
577          that the implementation behind any v4 key can handle 3DES. */
578       if (cfx.dek->algo == -1)
579         {
580           cfx.dek->algo = CIPHER_ALGO_3DES;
581         }
582
583       /* In case 3DES has been selected, print a warning if any key
584          does not have a preference for AES.  This should help to
585          indentify why encrypting to several recipients falls back to
586          3DES. */
587       if (opt.verbose && cfx.dek->algo == CIPHER_ALGO_3DES)
588         warn_missing_aes_from_pklist (pk_list);
589     }
590   else
591     {
592       if (!opt.expert
593           && (select_algo_from_prefs (pk_list, PREFTYPE_SYM,
594                                       opt.def_cipher_algo, NULL)
595               != opt.def_cipher_algo))
596         {
597           log_info(_("WARNING: forcing symmetric cipher %s (%d)"
598                      " violates recipient preferences\n"),
599                    openpgp_cipher_algo_name (opt.def_cipher_algo),
600                    opt.def_cipher_algo);
601         }
602
603       cfx.dek->algo = opt.def_cipher_algo;
604     }
605
606   /* Check compliance.  */
607   if (! gnupg_cipher_is_allowed (opt.compliance, 1, cfx.dek->algo,
608                                  GCRY_CIPHER_MODE_CFB))
609     {
610       log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
611                  openpgp_cipher_algo_name (cfx.dek->algo),
612                  gnupg_compliance_option_string (opt.compliance));
613       rc = gpg_error (GPG_ERR_CIPHER_ALGO);
614       goto leave;
615     }
616
617   if (!gnupg_rng_is_compliant (opt.compliance))
618     {
619       rc = gpg_error (GPG_ERR_FORBIDDEN);
620       log_error (_("%s is not compliant with %s mode\n"),
621                  "RNG",
622                  gnupg_compliance_option_string (opt.compliance));
623       write_status_error ("random-compliance", rc);
624       goto leave;
625     }
626
627   compliant = gnupg_cipher_is_compliant (CO_DE_VS, cfx.dek->algo,
628                                          GCRY_CIPHER_MODE_CFB);
629
630   {
631     pk_list_t pkr;
632
633     for (pkr = pk_list; pkr; pkr = pkr->next)
634       {
635         PKT_public_key *pk = pkr->pk;
636         unsigned int nbits = nbits_from_pk (pk);
637
638         if (!gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0,
639                                     pk->pkey, nbits, NULL))
640           log_info (_("WARNING: key %s is not suitable for encryption"
641                       " in %s mode\n"),
642                     keystr_from_pk (pk),
643                     gnupg_compliance_option_string (opt.compliance));
644
645         if (compliant
646             && !gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
647                                        nbits, NULL))
648           compliant = 0;
649       }
650
651   }
652
653   if (compliant)
654     write_status_strings (STATUS_ENCRYPTION_COMPLIANCE_MODE,
655                           gnupg_status_compliance_flag (CO_DE_VS),
656                           NULL);
657
658   if (opt.flags.require_compliance
659       && opt.compliance == CO_DE_VS
660       && !compliant)
661     {
662       log_error (_("operation forced to fail due to"
663                    " unfulfilled compliance rules\n"));
664       rc = gpg_error (GPG_ERR_FORBIDDEN);
665       g10_errors_seen = 1;
666       goto leave;
667     }
668
669
670   cfx.dek->use_mdc = use_mdc (pk_list,cfx.dek->algo);
671
672   /* Only do the is-file-already-compressed check if we are using a
673      MDC.  This forces compressed files to be re-compressed if we do
674      not have a MDC to give some protection against chosen ciphertext
675      attacks. */
676
677   if (do_compress && cfx.dek->use_mdc && is_file_compressed(filename, &rc2))
678     {
679       if (opt.verbose)
680         log_info(_("'%s' already compressed\n"), filename);
681       do_compress = 0;
682     }
683   if (rc2)
684     {
685       rc = rc2;
686       goto leave;
687     }
688
689   make_session_key (cfx.dek);
690   if (DBG_CRYPTO)
691     log_printhex (cfx.dek->key, cfx.dek->keylen, "DEK is: ");
692
693   rc = write_pubkey_enc_from_list (ctrl, pk_list, cfx.dek, out);
694   if (rc)
695     goto leave;
696
697   /* We put the passphrase (if any) after any public keys as this
698      seems to be the most useful on the recipient side - there is no
699      point in prompting a user for a passphrase if they have the
700      secret key needed to decrypt.  */
701   if(use_symkey && (rc = write_symkey_enc(symkey_s2k,symkey_dek,cfx.dek,out)))
702     goto leave;
703
704   if (!opt.no_literal)
705     pt = setup_plaintext_name (filename, inp);
706
707   /* Get the size of the file if possible, i.e., if it is a real file.  */
708   if (filename && *filename
709       && !iobuf_is_pipe_filename (filename) && !opt.textmode )
710     {
711       off_t tmpsize;
712       int overflow;
713
714       if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
715            && !overflow && opt.verbose)
716         log_info(_("WARNING: '%s' is an empty file\n"), filename );
717       /* We can't encode the length of very large files because
718          OpenPGP uses only 32 bit for file sizes.  So if the size
719          of a file is larger than 2^32 minus some bytes for packet
720          headers, we switch to partial length encoding. */
721       if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
722         filesize = tmpsize;
723       else
724         filesize = 0;
725     }
726   else
727     filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
728
729   if (!opt.no_literal)
730     {
731       pt->timestamp = make_timestamp();
732       pt->mode = opt.mimemode? 'm' : opt.textmode ? 't' : 'b';
733       pt->len = filesize;
734       pt->new_ctb = !pt->len;
735       pt->buf = inp;
736       pkt.pkttype = PKT_PLAINTEXT;
737       pkt.pkt.plaintext = pt;
738       cfx.datalen = filesize && !do_compress? calc_packet_length( &pkt ) : 0;
739     }
740   else
741     cfx.datalen = filesize && !do_compress ? filesize : 0;
742
743   /* Register the cipher filter. */
744   iobuf_push_filter (out, cipher_filter, &cfx);
745
746   /* Register the compress filter. */
747   if (do_compress)
748     {
749       int compr_algo = opt.compress_algo;
750
751       if (compr_algo == -1)
752         {
753           compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP, -1, NULL);
754           if (compr_algo == -1)
755             compr_algo = DEFAULT_COMPRESS_ALGO;
756           /* Theoretically impossible to get here since uncompressed
757              is implicit.  */
758         }
759       else if (!opt.expert
760                && select_algo_from_prefs(pk_list, PREFTYPE_ZIP,
761                                          compr_algo, NULL) != compr_algo)
762         {
763           log_info (_("WARNING: forcing compression algorithm %s (%d)"
764                       " violates recipient preferences\n"),
765                     compress_algo_to_string(compr_algo), compr_algo);
766         }
767
768       /* Algo 0 means no compression. */
769       if (compr_algo)
770         {
771           if (cfx.dek && cfx.dek->use_mdc)
772             zfx.new_ctb = 1;
773           push_compress_filter (out,&zfx,compr_algo);
774         }
775     }
776
777   /* Do the work. */
778   if (!opt.no_literal)
779     {
780       if ((rc = build_packet( out, &pkt )))
781         log_error ("build_packet failed: %s\n", gpg_strerror (rc));
782     }
783   else
784     {
785       /* User requested not to create a literal packet, so we copy the
786          plain data. */
787       byte copy_buffer[4096];
788       int  bytes_copied;
789       while ((bytes_copied = iobuf_read (inp, copy_buffer, 4096)) != -1)
790         {
791           rc = iobuf_write (out, copy_buffer, bytes_copied);
792           if (rc)
793             {
794               log_error ("copying input to output failed: %s\n",
795                          gpg_strerror (rc));
796               break;
797             }
798         }
799       wipememory (copy_buffer, 4096); /* Burn the buffer. */
800     }
801
802   /* Finish the stuff. */
803  leave:
804   iobuf_close (inp);
805   if (rc)
806     iobuf_cancel (out);
807   else
808     {
809       iobuf_close (out); /* fixme: check returncode */
810       write_status (STATUS_END_ENCRYPTION);
811     }
812   if (pt)
813     pt->buf = NULL;
814   free_packet (&pkt, NULL);
815   xfree (cfx.dek);
816   xfree (symkey_dek);
817   xfree (symkey_s2k);
818   if (!provided_keys)
819     release_pk_list (pk_list);
820   release_armor_context (afx);
821   release_progress_context (pfx);
822   return rc;
823 }
824
825
826 /*
827  * Filter to do a complete public key encryption.
828  */
829 int
830 encrypt_filter (void *opaque, int control,
831                 iobuf_t a, byte *buf, size_t *ret_len)
832 {
833   size_t size = *ret_len;
834   encrypt_filter_context_t *efx = opaque;
835   int rc = 0;
836
837   if (control == IOBUFCTRL_UNDERFLOW) /* decrypt */
838     {
839       BUG(); /* not used */
840     }
841   else if ( control == IOBUFCTRL_FLUSH ) /* encrypt */
842     {
843       if ( !efx->header_okay )
844         {
845           efx->cfx.dek = xmalloc_secure_clear ( sizeof *efx->cfx.dek );
846           if ( !opt.def_cipher_algo  )
847             {
848               /* Try to get it from the prefs. */
849               efx->cfx.dek->algo =
850                 select_algo_from_prefs (efx->pk_list, PREFTYPE_SYM, -1, NULL);
851               if (efx->cfx.dek->algo == -1 )
852                 {
853                   /* Because 3DES is implicitly in the prefs, this can
854                      only happen if we do not have any public keys in
855                      the list.  */
856                   efx->cfx.dek->algo = DEFAULT_CIPHER_ALGO;
857                 }
858
859               /* In case 3DES has been selected, print a warning if
860                  any key does not have a preference for AES.  This
861                  should help to indentify why encrypting to several
862                  recipients falls back to 3DES. */
863               if (opt.verbose
864                   && efx->cfx.dek->algo == CIPHER_ALGO_3DES)
865                 warn_missing_aes_from_pklist (efx->pk_list);
866             }
867           else
868             {
869               if (!opt.expert
870                   && select_algo_from_prefs (efx->pk_list,PREFTYPE_SYM,
871                                              opt.def_cipher_algo,
872                                              NULL) != opt.def_cipher_algo)
873                 log_info(_("forcing symmetric cipher %s (%d) "
874                            "violates recipient preferences\n"),
875                          openpgp_cipher_algo_name (opt.def_cipher_algo),
876                          opt.def_cipher_algo);
877
878               efx->cfx.dek->algo = opt.def_cipher_algo;
879             }
880
881           efx->cfx.dek->use_mdc = use_mdc (efx->pk_list,efx->cfx.dek->algo);
882
883           make_session_key ( efx->cfx.dek );
884           if (DBG_CRYPTO)
885             log_printhex (efx->cfx.dek->key, efx->cfx.dek->keylen, "DEK is: ");
886
887           rc = write_pubkey_enc_from_list (efx->ctrl,
888                                            efx->pk_list, efx->cfx.dek, a);
889           if (rc)
890             return rc;
891
892           if(efx->symkey_s2k && efx->symkey_dek)
893             {
894               rc=write_symkey_enc(efx->symkey_s2k,efx->symkey_dek,
895                                   efx->cfx.dek,a);
896               if(rc)
897                 return rc;
898             }
899
900           iobuf_push_filter (a, cipher_filter, &efx->cfx);
901
902           efx->header_okay = 1;
903         }
904       rc = iobuf_write (a, buf, size);
905
906     }
907   else if (control == IOBUFCTRL_FREE)
908     {
909       xfree (efx->symkey_dek);
910       xfree (efx->symkey_s2k);
911     }
912   else if ( control == IOBUFCTRL_DESC )
913     {
914       mem2str (buf, "encrypt_filter", *ret_len);
915     }
916   return rc;
917 }
918
919
920 /*
921  * Write a pubkey-enc packet for the public key PK to OUT.
922  */
923 int
924 write_pubkey_enc (ctrl_t ctrl,
925                   PKT_public_key *pk, int throw_keyid, DEK *dek, iobuf_t out)
926 {
927   PACKET pkt;
928   PKT_pubkey_enc *enc;
929   int rc;
930   gcry_mpi_t frame;
931
932   print_pubkey_algo_note ( pk->pubkey_algo );
933   enc = xmalloc_clear ( sizeof *enc );
934   enc->pubkey_algo = pk->pubkey_algo;
935   keyid_from_pk( pk, enc->keyid );
936   enc->throw_keyid = throw_keyid;
937
938   /* Okay, what's going on: We have the session key somewhere in
939    * the structure DEK and want to encode this session key in an
940    * integer value of n bits. pubkey_nbits gives us the number of
941    * bits we have to use.  We then encode the session key in some
942    * way and we get it back in the big intger value FRAME.  Then
943    * we use FRAME, the public key PK->PKEY and the algorithm
944    * number PK->PUBKEY_ALGO and pass it to pubkey_encrypt which
945    * returns the encrypted value in the array ENC->DATA.  This
946    * array has a size which depends on the used algorithm (e.g. 2
947    * for Elgamal).  We don't need frame anymore because we have
948    * everything now in enc->data which is the passed to
949    * build_packet().  */
950   frame = encode_session_key (pk->pubkey_algo, dek,
951                               pubkey_nbits (pk->pubkey_algo, pk->pkey));
952   rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, pk, pk->pkey);
953   gcry_mpi_release (frame);
954   if (rc)
955     log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
956   else
957     {
958       if ( opt.verbose )
959         {
960           char *ustr = get_user_id_string_native (ctrl, enc->keyid);
961           log_info (_("%s/%s encrypted for: \"%s\"\n"),
962                     openpgp_pk_algo_name (enc->pubkey_algo),
963                     openpgp_cipher_algo_name (dek->algo),
964                     ustr );
965           xfree (ustr);
966         }
967       /* And write it. */
968       init_packet (&pkt);
969       pkt.pkttype = PKT_PUBKEY_ENC;
970       pkt.pkt.pubkey_enc = enc;
971       rc = build_packet (out, &pkt);
972       if (rc)
973         log_error ("build_packet(pubkey_enc) failed: %s\n",
974                    gpg_strerror (rc));
975     }
976   free_pubkey_enc(enc);
977   return rc;
978 }
979
980
981 /*
982  * Write pubkey-enc packets from the list of PKs to OUT.
983  */
984 static int
985 write_pubkey_enc_from_list (ctrl_t ctrl, PK_LIST pk_list, DEK *dek, iobuf_t out)
986 {
987   if (opt.throw_keyids && (PGP6 || PGP7 || PGP8))
988     {
989       log_info(_("option '%s' may not be used in %s mode\n"),
990                "--throw-keyids",
991                gnupg_compliance_option_string (opt.compliance));
992       compliance_failure();
993     }
994
995   for ( ; pk_list; pk_list = pk_list->next )
996     {
997       PKT_public_key *pk = pk_list->pk;
998       int throw_keyid = (opt.throw_keyids || (pk_list->flags&1));
999       int rc = write_pubkey_enc (ctrl, pk, throw_keyid, dek, out);
1000       if (rc)
1001         return rc;
1002     }
1003
1004   return 0;
1005 }
1006
1007 void
1008 encrypt_crypt_files (ctrl_t ctrl, int nfiles, char **files, strlist_t remusr)
1009 {
1010   int rc = 0;
1011
1012   if (opt.outfile)
1013     {
1014       log_error(_("--output doesn't work for this command\n"));
1015       return;
1016     }
1017
1018   if (!nfiles)
1019     {
1020       char line[2048];
1021       unsigned int lno = 0;
1022       while ( fgets(line, DIM(line), stdin) )
1023         {
1024           lno++;
1025           if (!*line || line[strlen(line)-1] != '\n')
1026             {
1027               log_error("input line %u too long or missing LF\n", lno);
1028               return;
1029             }
1030           line[strlen(line)-1] = '\0';
1031           print_file_status(STATUS_FILE_START, line, 2);
1032           rc = encrypt_crypt (ctrl, -1, line, remusr, 0, NULL, -1);
1033           if (rc)
1034             log_error ("encryption of '%s' failed: %s\n",
1035                        print_fname_stdin(line), gpg_strerror (rc) );
1036           write_status( STATUS_FILE_DONE );
1037         }
1038     }
1039   else
1040     {
1041       while (nfiles--)
1042         {
1043           print_file_status(STATUS_FILE_START, *files, 2);
1044           if ( (rc = encrypt_crypt (ctrl, -1, *files, remusr, 0, NULL, -1)) )
1045             log_error("encryption of '%s' failed: %s\n",
1046                       print_fname_stdin(*files), gpg_strerror (rc) );
1047           write_status( STATUS_FILE_DONE );
1048           files++;
1049         }
1050     }
1051 }