Implement the server comamnd DECRYPT.
[gnupg.git] / g10 / encrypt.c
blob649ea337f9fe137b19ad5a5b0c7f0028c9c2860c
1 /* encrypt.c - Main encryption driver
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "iobuf.h"
33 #include "keydb.h"
34 #include "util.h"
35 #include "main.h"
36 #include "filter.h"
37 #include "trustdb.h"
38 #include "i18n.h"
39 #include "status.h"
40 #include "pkglue.h"
43 static int encrypt_simple( const char *filename, int mode, int use_seskey );
44 static int write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, iobuf_t out );
46 /****************
47 * Encrypt FILENAME with only the symmetric cipher. Take input from
48 * stdin if FILENAME is NULL.
50 int
51 encrypt_symmetric (const char *filename)
53 return encrypt_simple( filename, 1, 0 );
57 /****************
58 * Encrypt FILENAME as a literal data packet only. Take input from
59 * stdin if FILENAME is NULL.
61 int
62 encrypt_store (const char *filename)
64 return encrypt_simple( filename, 0, 0 );
68 static void
69 encrypt_seskey (DEK *dek, DEK **seskey, byte *enckey)
71 gcry_cipher_hd_t hd;
72 byte buf[33];
74 assert ( dek->keylen <= 32 );
75 if (!*seskey)
77 *seskey=xmalloc_clear(sizeof(DEK));
78 (*seskey)->keylen=dek->keylen;
79 (*seskey)->algo=dek->algo;
80 make_session_key(*seskey);
81 /*log_hexdump( "thekey", c->key, c->keylen );*/
84 /* The encrypted session key is prefixed with a one-octet algorithm id. */
85 buf[0] = (*seskey)->algo;
86 memcpy( buf + 1, (*seskey)->key, (*seskey)->keylen );
88 /* We only pass already checked values to the following fucntion,
89 thus we consider any failure as fatal. */
90 if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
91 BUG ();
92 if (gcry_cipher_setkey (hd, dek->key, dek->keylen))
93 BUG ();
94 gcry_cipher_setiv (hd, NULL, 0);
95 gcry_cipher_encrypt (hd, buf, (*seskey)->keylen + 1, NULL, 0);
96 gcry_cipher_close (hd);
98 memcpy( enckey, buf, (*seskey)->keylen + 1 );
99 wipememory( buf, sizeof buf ); /* burn key */
103 /* We try very hard to use a MDC */
104 static int
105 use_mdc(PK_LIST pk_list,int algo)
107 /* RFC-1991 and 2440 don't have MDC */
108 if(RFC1991 || RFC2440)
109 return 0;
111 /* --force-mdc overrides --disable-mdc */
112 if(opt.force_mdc)
113 return 1;
115 if(opt.disable_mdc)
116 return 0;
118 /* Do the keys really support MDC? */
120 if(select_mdc_from_pklist(pk_list))
121 return 1;
123 /* The keys don't support MDC, so now we do a bit of a hack - if any
124 of the AESes or TWOFISH are in the prefs, we assume that the user
125 can handle a MDC. This is valid for PGP 7, which can handle MDCs
126 though it will not generate them. 2440bis allows this, by the
127 way. */
129 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
130 CIPHER_ALGO_AES,NULL)==CIPHER_ALGO_AES)
131 return 1;
133 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
134 CIPHER_ALGO_AES192,NULL)==CIPHER_ALGO_AES192)
135 return 1;
137 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
138 CIPHER_ALGO_AES256,NULL)==CIPHER_ALGO_AES256)
139 return 1;
141 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
142 CIPHER_ALGO_TWOFISH,NULL)==CIPHER_ALGO_TWOFISH)
143 return 1;
145 /* Last try. Use MDC for the modern ciphers. */
147 if (openpgp_cipher_get_algo_blklen (algo) != 8)
148 return 1;
150 if (opt.verbose)
151 warn_missing_mdc_from_pklist (pk_list);
153 return 0; /* No MDC */
157 /* We don't want to use use_seskey yet because older gnupg versions
158 can't handle it, and there isn't really any point unless we're
159 making a message that can be decrypted by a public key or
160 passphrase. */
161 static int
162 encrypt_simple (const char *filename, int mode, int use_seskey)
164 iobuf_t inp, out;
165 PACKET pkt;
166 PKT_plaintext *pt = NULL;
167 STRING2KEY *s2k = NULL;
168 byte enckey[33];
169 int rc = 0;
170 int seskeylen = 0;
171 u32 filesize;
172 cipher_filter_context_t cfx;
173 armor_filter_context_t *afx = NULL;
174 compress_filter_context_t zfx;
175 text_filter_context_t tfx;
176 progress_filter_context_t *pfx;
177 int do_compress = !RFC1991 && default_compress_algo();
179 pfx = new_progress_context ();
180 memset( &cfx, 0, sizeof cfx);
181 memset( &zfx, 0, sizeof zfx);
182 memset( &tfx, 0, sizeof tfx);
183 init_packet(&pkt);
185 /* Prepare iobufs. */
186 inp = iobuf_open(filename);
187 if (inp)
188 iobuf_ioctl (inp,3,1,NULL); /* disable fd caching */
189 if (inp && is_secured_file (iobuf_get_fd (inp)))
191 iobuf_close (inp);
192 inp = NULL;
193 errno = EPERM;
195 if (!inp)
197 rc = gpg_error_from_syserror ();
198 log_error(_("can't open `%s': %s\n"), filename? filename: "[stdin]",
199 strerror(errno) );
200 release_progress_context (pfx);
201 return rc;
204 handle_progress (pfx, inp, filename);
206 if (opt.textmode)
207 iobuf_push_filter( inp, text_filter, &tfx );
209 /* Due the the fact that we use don't use an IV to encrypt the
210 session key we can't use the new mode with RFC1991 because it has
211 no S2K salt. RFC1991 always uses simple S2K. */
212 if ( RFC1991 && use_seskey )
213 use_seskey = 0;
215 cfx.dek = NULL;
216 if ( mode )
218 int canceled;
220 s2k = xmalloc_clear( sizeof *s2k );
221 s2k->mode = RFC1991? 0:opt.s2k_mode;
222 s2k->hash_algo = S2K_DIGEST_ALGO;
223 cfx.dek = passphrase_to_dek (NULL, 0,
224 default_cipher_algo(), s2k, 4,
225 NULL, &canceled);
226 if ( !cfx.dek || !cfx.dek->keylen )
228 rc = gpg_error (canceled? GPG_ERR_CANCELED:GPG_ERR_INV_PASSPHRASE);
229 xfree (cfx.dek);
230 xfree (s2k);
231 iobuf_close (inp);
232 log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
233 release_progress_context (pfx);
234 return rc;
236 if (use_seskey && s2k->mode != 1 && s2k->mode != 3)
238 use_seskey = 0;
239 log_info (_("can't use a symmetric ESK packet "
240 "due to the S2K mode\n"));
243 if ( use_seskey )
245 DEK *dek = NULL;
247 seskeylen = openpgp_cipher_get_algo_keylen (default_cipher_algo ());
248 encrypt_seskey( cfx.dek, &dek, enckey );
249 xfree( cfx.dek ); cfx.dek = dek;
252 if (opt.verbose)
253 log_info(_("using cipher %s\n"),
254 openpgp_cipher_algo_name (cfx.dek->algo));
256 cfx.dek->use_mdc=use_mdc(NULL,cfx.dek->algo);
259 if (do_compress && cfx.dek && cfx.dek->use_mdc
260 && is_file_compressed(filename, &rc))
262 if (opt.verbose)
263 log_info(_("`%s' already compressed\n"), filename);
264 do_compress = 0;
267 if ( rc || (rc = open_outfile (-1, filename, opt.armor? 1:0, &out )))
269 iobuf_cancel (inp);
270 xfree (cfx.dek);
271 xfree (s2k);
272 release_progress_context (pfx);
273 return rc;
276 if ( opt.armor )
278 afx = new_armor_context ();
279 push_armor_filter (afx, out);
282 if ( s2k && !RFC1991 )
284 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc + seskeylen + 1 );
285 enc->version = 4;
286 enc->cipher_algo = cfx.dek->algo;
287 enc->s2k = *s2k;
288 if ( use_seskey && seskeylen )
290 enc->seskeylen = seskeylen + 1; /* algo id */
291 memcpy (enc->seskey, enckey, seskeylen + 1 );
293 pkt.pkttype = PKT_SYMKEY_ENC;
294 pkt.pkt.symkey_enc = enc;
295 if ((rc = build_packet( out, &pkt )))
296 log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
297 xfree (enc);
300 if (!opt.no_literal)
301 pt = setup_plaintext_name (filename, inp);
303 /* Note that PGP 5 has problems decrypting symmetrically encrypted
304 data if the file length is in the inner packet. It works when
305 only partial length headers are use. In the past, we always used
306 partial body length here, but since PGP 2, PGP 6, and PGP 7 need
307 the file length, and nobody should be using PGP 5 nowadays
308 anyway, this is now set to the file length. Note also that this
309 only applies to the RFC-1991 style symmetric messages, and not
310 the RFC-2440 style. PGP 6 and 7 work with either partial length
311 or fixed length with the new style messages. */
313 if ( !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
315 off_t tmpsize;
316 int overflow;
318 if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
319 && !overflow && opt.verbose)
320 log_info(_("WARNING: `%s' is an empty file\n"), filename );
321 /* We can't encode the length of very large files because
322 OpenPGP uses only 32 bit for file sizes. So if the the
323 size of a file is larger than 2^32 minus some bytes for
324 packet headers, we switch to partial length encoding. */
325 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
326 filesize = tmpsize;
327 else
328 filesize = 0;
330 else
331 filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
333 if (!opt.no_literal)
335 pt->timestamp = make_timestamp();
336 pt->mode = opt.textmode? 't' : 'b';
337 pt->len = filesize;
338 pt->new_ctb = !pt->len && !RFC1991;
339 pt->buf = inp;
340 pkt.pkttype = PKT_PLAINTEXT;
341 pkt.pkt.plaintext = pt;
342 cfx.datalen = filesize && !do_compress ? calc_packet_length( &pkt ) : 0;
344 else
346 cfx.datalen = filesize && !do_compress ? filesize : 0;
347 pkt.pkttype = 0;
348 pkt.pkt.generic = NULL;
351 /* Register the cipher filter. */
352 if (mode)
353 iobuf_push_filter ( out, cipher_filter, &cfx );
355 /* Register the compress filter. */
356 if ( do_compress )
358 if (cfx.dek && cfx.dek->use_mdc)
359 zfx.new_ctb = 1;
360 push_compress_filter (out, &zfx, default_compress_algo());
363 /* Do the work. */
364 if (!opt.no_literal)
366 if ( (rc = build_packet( out, &pkt )) )
367 log_error("build_packet failed: %s\n", g10_errstr(rc) );
369 else
371 /* User requested not to create a literal packet, so we copy the
372 plain data. */
373 byte copy_buffer[4096];
374 int bytes_copied;
375 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
376 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
377 log_error ("copying input to output failed: %s\n",
378 gpg_strerror (rc) );
379 break;
381 wipememory (copy_buffer, 4096); /* burn buffer */
384 /* Finish the stuff. */
385 iobuf_close (inp);
386 if (rc)
387 iobuf_cancel(out);
388 else
390 iobuf_close (out); /* fixme: check returncode */
391 if (mode)
392 write_status ( STATUS_END_ENCRYPTION );
394 if (pt)
395 pt->buf = NULL;
396 free_packet (&pkt);
397 xfree (cfx.dek);
398 xfree (s2k);
399 release_armor_context (afx);
400 release_progress_context (pfx);
401 return rc;
406 setup_symkey (STRING2KEY **symkey_s2k,DEK **symkey_dek)
408 int canceled;
410 *symkey_s2k=xmalloc_clear(sizeof(STRING2KEY));
411 (*symkey_s2k)->mode = opt.s2k_mode;
412 (*symkey_s2k)->hash_algo = S2K_DIGEST_ALGO;
414 *symkey_dek=passphrase_to_dek(NULL,0,opt.s2k_cipher_algo,
415 *symkey_s2k, 4, NULL, &canceled);
416 if(!*symkey_dek || !(*symkey_dek)->keylen)
418 xfree(*symkey_dek);
419 xfree(*symkey_s2k);
420 return gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
423 return 0;
427 static int
428 write_symkey_enc (STRING2KEY *symkey_s2k, DEK *symkey_dek, DEK *dek,
429 iobuf_t out)
431 int rc, seskeylen = openpgp_cipher_get_algo_keylen (dek->algo);
433 PKT_symkey_enc *enc;
434 byte enckey[33];
435 PACKET pkt;
437 enc=xmalloc_clear(sizeof(PKT_symkey_enc)+seskeylen+1);
438 encrypt_seskey(symkey_dek,&dek,enckey);
440 enc->version = 4;
441 enc->cipher_algo = opt.s2k_cipher_algo;
442 enc->s2k = *symkey_s2k;
443 enc->seskeylen = seskeylen + 1; /* algo id */
444 memcpy( enc->seskey, enckey, seskeylen + 1 );
446 pkt.pkttype = PKT_SYMKEY_ENC;
447 pkt.pkt.symkey_enc = enc;
449 if ((rc=build_packet(out,&pkt)))
450 log_error("build symkey_enc packet failed: %s\n",g10_errstr(rc));
452 xfree(enc);
453 return rc;
458 * Encrypt the file with the given userids (or ask if none is
459 * supplied). Either FILENAME or FILEFD must be given, but not both.
460 * The caller may provide a checked list of public keys in
461 * PROVIDED_PKS; if not the function builds a list of keys on its own.
464 encrypt_crypt (int filefd, const char *filename,
465 strlist_t remusr, int use_symkey, pk_list_t provided_keys,
466 int outputfd)
468 iobuf_t inp = NULL;
469 iobuf_t out = NULL;
470 PACKET pkt;
471 PKT_plaintext *pt = NULL;
472 DEK *symkey_dek = NULL;
473 STRING2KEY *symkey_s2k = NULL;
474 int rc = 0, rc2 = 0;
475 u32 filesize;
476 cipher_filter_context_t cfx;
477 armor_filter_context_t *afx = NULL;
478 compress_filter_context_t zfx;
479 text_filter_context_t tfx;
480 progress_filter_context_t *pfx;
481 PK_LIST pk_list, work_list;
482 int do_compress;
484 if (filefd != -1 && filename)
485 return gpg_error (GPG_ERR_INV_ARG);
487 do_compress = opt.compress_algo && !RFC1991;
489 pfx = new_progress_context ();
490 memset( &cfx, 0, sizeof cfx);
491 memset( &zfx, 0, sizeof zfx);
492 memset( &tfx, 0, sizeof tfx);
493 init_packet(&pkt);
495 if (use_symkey
496 && (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
498 release_progress_context (pfx);
499 return rc;
502 if (provided_keys)
503 pk_list = provided_keys;
504 else
506 if ((rc = build_pk_list (remusr, &pk_list, PUBKEY_USAGE_ENC)))
508 release_progress_context (pfx);
509 return rc;
513 if(PGP2)
515 for (work_list=pk_list; work_list; work_list=work_list->next)
516 if (!(is_RSA (work_list->pk->pubkey_algo)
517 && nbits_from_pk (work_list->pk) <= 2048))
519 log_info(_("you can only encrypt to RSA keys of 2048 bits or "
520 "less in --pgp2 mode\n"));
521 compliance_failure();
522 break;
526 /* Prepare iobufs. */
527 inp = iobuf_open_fd_or_name (filefd, filename, "rb");
528 if (inp)
529 iobuf_ioctl (inp, 3, 1, NULL); /* Disable fd caching. */
530 if (inp && is_secured_file (iobuf_get_fd (inp)))
532 iobuf_close (inp);
533 inp = NULL;
534 errno = EPERM;
536 if (!inp)
538 char xname[64];
540 rc = gpg_error_from_syserror ();
541 if (filefd != -1)
542 snprintf (xname, sizeof xname, "[fd %d]", filefd);
543 else if (!filename)
544 strcpy (xname, "[stdin]");
545 else
546 *xname = 0;
547 log_error (_("can't open `%s': %s\n"),
548 *xname? xname : filename, gpg_strerror (rc) );
549 goto leave;
552 if (opt.verbose)
553 log_info (_("reading from `%s'\n"), iobuf_get_fname_nonnull (inp));
555 handle_progress (pfx, inp, filename);
557 if (opt.textmode)
558 iobuf_push_filter (inp, text_filter, &tfx);
560 rc = open_outfile (outputfd, filename, opt.armor? 1:0, &out);
561 if (rc)
562 goto leave;
564 if (opt.armor)
566 afx = new_armor_context ();
567 push_armor_filter (afx, out);
570 /* Create a session key. */
571 cfx.dek = xmalloc_secure_clear (sizeof *cfx.dek);
572 if (!opt.def_cipher_algo)
574 /* Try to get it from the prefs. */
575 cfx.dek->algo = select_algo_from_prefs (pk_list, PREFTYPE_SYM, -1, NULL);
576 /* The only way select_algo_from_prefs can fail here is when
577 mixing v3 and v4 keys, as v4 keys have an implicit preference
578 entry for 3DES, and the pk_list cannot be empty. In this
579 case, use 3DES anyway as it's the safest choice - perhaps the
580 v3 key is being used in an OpenPGP implementation and we know
581 that the implementation behind any v4 key can handle 3DES. */
582 if (cfx.dek->algo == -1)
584 cfx.dek->algo = CIPHER_ALGO_3DES;
586 if (PGP2)
588 log_info(_("unable to use the IDEA cipher for all of the keys "
589 "you are encrypting to.\n"));
590 compliance_failure();
594 /* In case 3DES has been selected, print a warning if any key
595 does not have a preference for AES. This should help to
596 indentify why encrypting to several recipients falls back to
597 3DES. */
598 if (opt.verbose && cfx.dek->algo == CIPHER_ALGO_3DES)
599 warn_missing_aes_from_pklist (pk_list);
601 else
603 if (!opt.expert
604 && (select_algo_from_prefs (pk_list, PREFTYPE_SYM,
605 opt.def_cipher_algo, NULL)
606 != opt.def_cipher_algo))
608 log_info(_("WARNING: forcing symmetric cipher %s (%d)"
609 " violates recipient preferences\n"),
610 openpgp_cipher_algo_name (opt.def_cipher_algo),
611 opt.def_cipher_algo);
614 cfx.dek->algo = opt.def_cipher_algo;
617 cfx.dek->use_mdc = use_mdc (pk_list,cfx.dek->algo);
619 /* Only do the is-file-already-compressed check if we are using a
620 MDC. This forces compressed files to be re-compressed if we do
621 not have a MDC to give some protection against chosen ciphertext
622 attacks. */
624 if (do_compress && cfx.dek->use_mdc && is_file_compressed(filename, &rc2))
626 if (opt.verbose)
627 log_info(_("`%s' already compressed\n"), filename);
628 do_compress = 0;
630 if (rc2)
632 rc = rc2;
633 goto leave;
636 make_session_key (cfx.dek);
637 if (DBG_CIPHER)
638 log_printhex ("DEK is: ", cfx.dek->key, cfx.dek->keylen );
640 rc = write_pubkey_enc_from_list (pk_list, cfx.dek, out);
641 if (rc)
642 goto leave;
644 /* We put the passphrase (if any) after any public keys as this
645 seems to be the most useful on the recipient side - there is no
646 point in prompting a user for a passphrase if they have the
647 secret key needed to decrypt. */
648 if(use_symkey && (rc = write_symkey_enc(symkey_s2k,symkey_dek,cfx.dek,out)))
649 goto leave;
651 if (!opt.no_literal)
652 pt = setup_plaintext_name (filename, inp);
654 if (filefd != -1
655 && !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
657 off_t tmpsize;
658 int overflow;
660 if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
661 && !overflow && opt.verbose)
662 log_info(_("WARNING: `%s' is an empty file\n"), filename );
663 /* We can't encode the length of very large files because
664 OpenPGP uses only 32 bit for file sizes. So if the the size
665 of a file is larger than 2^32 minus some bytes for packet
666 headers, we switch to partial length encoding. */
667 if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
668 filesize = tmpsize;
669 else
670 filesize = 0;
672 else
673 filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
675 if (!opt.no_literal)
677 pt->timestamp = make_timestamp();
678 pt->mode = opt.textmode ? 't' : 'b';
679 pt->len = filesize;
680 pt->new_ctb = !pt->len && !RFC1991;
681 pt->buf = inp;
682 pkt.pkttype = PKT_PLAINTEXT;
683 pkt.pkt.plaintext = pt;
684 cfx.datalen = filesize && !do_compress? calc_packet_length( &pkt ) : 0;
686 else
687 cfx.datalen = filesize && !do_compress ? filesize : 0;
689 /* Register the cipher filter. */
690 iobuf_push_filter (out, cipher_filter, &cfx);
692 /* Register the compress filter. */
693 if (do_compress)
695 int compr_algo = opt.compress_algo;
697 if (compr_algo == -1)
699 compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP, -1, NULL);
700 if (compr_algo == -1)
701 compr_algo = DEFAULT_COMPRESS_ALGO;
702 /* Theoretically impossible to get here since uncompressed
703 is implicit. */
705 else if (!opt.expert
706 && select_algo_from_prefs(pk_list, PREFTYPE_ZIP,
707 compr_algo, NULL) != compr_algo)
709 log_info (_("WARNING: forcing compression algorithm %s (%d)"
710 " violates recipient preferences\n"),
711 compress_algo_to_string(compr_algo), compr_algo);
714 /* Algo 0 means no compression. */
715 if (compr_algo)
717 if (cfx.dek && cfx.dek->use_mdc)
718 zfx.new_ctb = 1;
719 push_compress_filter (out,&zfx,compr_algo);
723 /* Do the work. */
724 if (!opt.no_literal)
726 if ((rc = build_packet( out, &pkt )))
727 log_error ("build_packet failed: %s\n", g10_errstr(rc));
729 else
731 /* User requested not to create a literal packet, so we copy the
732 plain data. */
733 byte copy_buffer[4096];
734 int bytes_copied;
735 while ((bytes_copied = iobuf_read (inp, copy_buffer, 4096)) != -1)
737 rc = iobuf_write (out, copy_buffer, bytes_copied);
738 if (rc)
740 log_error ("copying input to output failed: %s\n",
741 gpg_strerror (rc));
742 break;
745 wipememory (copy_buffer, 4096); /* Burn the buffer. */
748 /* Finish the stuff. */
749 leave:
750 iobuf_close (inp);
751 if (rc)
752 iobuf_cancel (out);
753 else
755 iobuf_close (out); /* fixme: check returncode */
756 write_status (STATUS_END_ENCRYPTION);
758 if (pt)
759 pt->buf = NULL;
760 free_packet (&pkt);
761 xfree (cfx.dek);
762 xfree (symkey_dek);
763 xfree (symkey_s2k);
764 if (!provided_keys)
765 release_pk_list (pk_list);
766 release_armor_context (afx);
767 release_progress_context (pfx);
768 return rc;
773 * Filter to do a complete public key encryption.
776 encrypt_filter (void *opaque, int control,
777 iobuf_t a, byte *buf, size_t *ret_len)
779 size_t size = *ret_len;
780 encrypt_filter_context_t *efx = opaque;
781 int rc = 0;
783 if (control == IOBUFCTRL_UNDERFLOW) /* decrypt */
785 BUG(); /* not used */
787 else if ( control == IOBUFCTRL_FLUSH ) /* encrypt */
789 if ( !efx->header_okay )
791 efx->cfx.dek = xmalloc_secure_clear ( sizeof *efx->cfx.dek );
792 if ( !opt.def_cipher_algo )
794 /* Try to get it from the prefs. */
795 efx->cfx.dek->algo =
796 select_algo_from_prefs (efx->pk_list, PREFTYPE_SYM, -1, NULL);
797 if (efx->cfx.dek->algo == -1 )
799 /* Because 3DES is implicitly in the prefs, this can
800 only happen if we do not have any public keys in
801 the list. */
802 efx->cfx.dek->algo = DEFAULT_CIPHER_ALGO;
805 /* In case 3DES has been selected, print a warning if
806 any key does not have a preference for AES. This
807 should help to indentify why encrypting to several
808 recipients falls back to 3DES. */
809 if (opt.verbose
810 && efx->cfx.dek->algo == CIPHER_ALGO_3DES)
811 warn_missing_aes_from_pklist (efx->pk_list);
813 else
815 if (!opt.expert
816 && select_algo_from_prefs (efx->pk_list,PREFTYPE_SYM,
817 opt.def_cipher_algo,
818 NULL) != opt.def_cipher_algo)
819 log_info(_("forcing symmetric cipher %s (%d) "
820 "violates recipient preferences\n"),
821 openpgp_cipher_algo_name (opt.def_cipher_algo),
822 opt.def_cipher_algo);
824 efx->cfx.dek->algo = opt.def_cipher_algo;
827 efx->cfx.dek->use_mdc = use_mdc (efx->pk_list,efx->cfx.dek->algo);
829 make_session_key ( efx->cfx.dek );
830 if (DBG_CIPHER)
831 log_printhex ("DEK is: ", efx->cfx.dek->key, efx->cfx.dek->keylen);
833 rc = write_pubkey_enc_from_list (efx->pk_list, efx->cfx.dek, a);
834 if (rc)
835 return rc;
837 if(efx->symkey_s2k && efx->symkey_dek)
839 rc=write_symkey_enc(efx->symkey_s2k,efx->symkey_dek,
840 efx->cfx.dek,a);
841 if(rc)
842 return rc;
845 iobuf_push_filter (a, cipher_filter, &efx->cfx);
847 efx->header_okay = 1;
849 rc = iobuf_write (a, buf, size);
852 else if (control == IOBUFCTRL_FREE)
854 xfree (efx->symkey_dek);
855 xfree (efx->symkey_s2k);
857 else if ( control == IOBUFCTRL_DESC )
859 *(char**)buf = "encrypt_filter";
861 return rc;
866 * Write pubkey-enc packets from the list of PKs to OUT.
868 static int
869 write_pubkey_enc_from_list (PK_LIST pk_list, DEK *dek, iobuf_t out)
871 PACKET pkt;
872 PKT_public_key *pk;
873 PKT_pubkey_enc *enc;
874 int rc;
876 for ( ; pk_list; pk_list = pk_list->next )
878 gcry_mpi_t frame;
880 pk = pk_list->pk;
882 print_pubkey_algo_note ( pk->pubkey_algo );
883 enc = xmalloc_clear ( sizeof *enc );
884 enc->pubkey_algo = pk->pubkey_algo;
885 keyid_from_pk( pk, enc->keyid );
886 enc->throw_keyid = (opt.throw_keyid || (pk_list->flags&1));
888 if (opt.throw_keyid && (PGP2 || PGP6 || PGP7 || PGP8))
890 log_info(_("you may not use %s while in %s mode\n"),
891 "--throw-keyid",compliance_option_string());
892 compliance_failure();
895 /* Okay, what's going on: We have the session key somewhere in
896 * the structure DEK and want to encode this session key in an
897 * integer value of n bits. pubkey_nbits gives us the number of
898 * bits we have to use. We then encode the session key in some
899 * way and we get it back in the big intger value FRAME. Then
900 * we use FRAME, the public key PK->PKEY and the algorithm
901 * number PK->PUBKEY_ALGO and pass it to pubkey_encrypt which
902 * returns the encrypted value in the array ENC->DATA. This
903 * array has a size which depends on the used algorithm (e.g. 2
904 * for Elgamal). We don't need frame anymore because we have
905 * everything now in enc->data which is the passed to
906 * build_packet(). */
907 frame = encode_session_key (dek,
908 pubkey_nbits (pk->pubkey_algo, pk->pkey));
909 rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, pk->pkey);
910 gcry_mpi_release (frame);
911 if (rc)
912 log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
913 else
915 if ( opt.verbose )
917 char *ustr = get_user_id_string_native (enc->keyid);
918 log_info (_("%s/%s encrypted for: \"%s\"\n"),
919 gcry_pk_algo_name (enc->pubkey_algo),
920 openpgp_cipher_algo_name (dek->algo),
921 ustr );
922 xfree (ustr);
924 /* And write it. */
925 init_packet (&pkt);
926 pkt.pkttype = PKT_PUBKEY_ENC;
927 pkt.pkt.pubkey_enc = enc;
928 rc = build_packet (out, &pkt);
929 if (rc)
930 log_error ("build_packet(pubkey_enc) failed: %s\n",
931 g10_errstr (rc));
933 free_pubkey_enc(enc);
934 if (rc)
935 return rc;
937 return 0;
941 void
942 encrypt_crypt_files (int nfiles, char **files, strlist_t remusr)
944 int rc = 0;
946 if (opt.outfile)
948 log_error(_("--output doesn't work for this command\n"));
949 return;
952 if (!nfiles)
954 char line[2048];
955 unsigned int lno = 0;
956 while ( fgets(line, DIM(line), stdin) )
958 lno++;
959 if (!*line || line[strlen(line)-1] != '\n')
961 log_error("input line %u too long or missing LF\n", lno);
962 return;
964 line[strlen(line)-1] = '\0';
965 print_file_status(STATUS_FILE_START, line, 2);
966 rc = encrypt_crypt (-1, line, remusr, 0, NULL, -1);
967 if (rc)
968 log_error ("encryption of `%s' failed: %s\n",
969 print_fname_stdin(line), g10_errstr(rc) );
970 write_status( STATUS_FILE_DONE );
973 else
975 while (nfiles--)
977 print_file_status(STATUS_FILE_START, *files, 2);
978 if ( (rc = encrypt_crypt (-1, *files, remusr, 0, NULL, -1)) )
979 log_error("encryption of `%s' failed: %s\n",
980 print_fname_stdin(*files), g10_errstr(rc) );
981 write_status( STATUS_FILE_DONE );
982 files++;