Replace a call to BUG by an error return.
[gnupg.git] / g10 / encode.c
blob92aa9b27d158f5590d961d05afbd5972fca3476e
1 /* encode.c - encode data
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006 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 encode_simple( const char *filename, int mode, int use_seskey );
44 static int write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, IOBUF out );
46 /****************
47 * Encode FILENAME with only the symmetric cipher. Take input from
48 * stdin if FILENAME is NULL.
50 int
51 encode_symmetric( const char *filename )
53 return encode_simple( filename, 1, 0 );
56 /****************
57 * Encode FILENAME as a literal data packet only. Take input from
58 * stdin if FILENAME is NULL.
60 int
61 encode_store( const char *filename )
63 return encode_simple( filename, 0, 0 );
67 static void
68 encode_seskey( DEK *dek, DEK **seskey, byte *enckey )
70 gcry_cipher_hd_t hd;
71 byte buf[33];
73 assert ( dek->keylen <= 32 );
74 if(!*seskey)
76 *seskey=xmalloc_clear(sizeof(DEK));
77 (*seskey)->keylen=dek->keylen;
78 (*seskey)->algo=dek->algo;
79 make_session_key(*seskey);
80 /*log_hexdump( "thekey", c->key, c->keylen );*/
83 /* The encrypted session key is prefixed with a one-octet algorithm id. */
84 buf[0] = (*seskey)->algo;
85 memcpy( buf + 1, (*seskey)->key, (*seskey)->keylen );
87 /* We only pass already checked values to the following fucntion,
88 thus we consider any failure as fatal. */
89 if (gcry_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
90 BUG ();
91 if (gcry_cipher_setkey (hd, dek->key, dek->keylen))
92 BUG ();
93 gcry_cipher_setiv (hd, NULL, 0);
94 gcry_cipher_encrypt (hd, buf, (*seskey)->keylen + 1, NULL, 0);
95 gcry_cipher_close (hd);
97 memcpy( enckey, buf, (*seskey)->keylen + 1 );
98 wipememory( buf, sizeof buf ); /* burn key */
101 /* We try very hard to use a MDC */
102 static int
103 use_mdc(PK_LIST pk_list,int algo)
105 /* RFC-1991 and 2440 don't have MDC */
106 if(RFC1991 || RFC2440)
107 return 0;
109 /* --force-mdc overrides --disable-mdc */
110 if(opt.force_mdc)
111 return 1;
113 if(opt.disable_mdc)
114 return 0;
116 /* Do the keys really support MDC? */
118 if(select_mdc_from_pklist(pk_list))
119 return 1;
121 /* The keys don't support MDC, so now we do a bit of a hack - if any
122 of the AESes or TWOFISH are in the prefs, we assume that the user
123 can handle a MDC. This is valid for PGP 7, which can handle MDCs
124 though it will not generate them. 2440bis allows this, by the
125 way. */
127 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
128 CIPHER_ALGO_AES,NULL)==CIPHER_ALGO_AES)
129 return 1;
131 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
132 CIPHER_ALGO_AES192,NULL)==CIPHER_ALGO_AES192)
133 return 1;
135 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
136 CIPHER_ALGO_AES256,NULL)==CIPHER_ALGO_AES256)
137 return 1;
139 if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
140 CIPHER_ALGO_TWOFISH,NULL)==CIPHER_ALGO_TWOFISH)
141 return 1;
143 /* Last try. Use MDC for the modern ciphers. */
145 if (gcry_cipher_get_algo_blklen (algo) != 8)
146 return 1;
148 if (opt.verbose)
149 warn_missing_mdc_from_pklist (pk_list);
151 return 0; /* No MDC */
154 /* We don't want to use use_seskey yet because older gnupg versions
155 can't handle it, and there isn't really any point unless we're
156 making a message that can be decrypted by a public key or
157 passphrase. */
158 static int
159 encode_simple( const char *filename, int mode, int use_seskey )
161 IOBUF inp, out;
162 PACKET pkt;
163 PKT_plaintext *pt = NULL;
164 STRING2KEY *s2k = NULL;
165 byte enckey[33];
166 int rc = 0;
167 int seskeylen = 0;
168 u32 filesize;
169 cipher_filter_context_t cfx;
170 armor_filter_context_t *afx = NULL;
171 compress_filter_context_t zfx;
172 text_filter_context_t tfx;
173 progress_filter_context_t *pfx;
174 int do_compress = !RFC1991 && default_compress_algo();
176 pfx = new_progress_context ();
177 memset( &cfx, 0, sizeof cfx);
178 memset( &zfx, 0, sizeof zfx);
179 memset( &tfx, 0, sizeof tfx);
180 init_packet(&pkt);
182 /* prepare iobufs */
183 inp = iobuf_open(filename);
184 if (inp)
185 iobuf_ioctl (inp,3,1,NULL); /* disable fd caching */
186 if (inp && is_secured_file (iobuf_get_fd (inp)))
188 iobuf_close (inp);
189 inp = NULL;
190 errno = EPERM;
192 if( !inp ) {
193 rc = gpg_error_from_syserror ();
194 log_error(_("can't open `%s': %s\n"), filename? filename: "[stdin]",
195 strerror(errno) );
196 release_progress_context (pfx);
197 return rc;
200 handle_progress (pfx, inp, filename);
202 if( opt.textmode )
203 iobuf_push_filter( inp, text_filter, &tfx );
205 /* Due the the fact that we use don't use an IV to encrypt the
206 session key we can't use the new mode with RFC1991 because
207 it has no S2K salt. RFC1991 always uses simple S2K. */
208 if ( RFC1991 && use_seskey )
209 use_seskey = 0;
211 cfx.dek = NULL;
212 if( mode ) {
213 int canceled;
215 s2k = xmalloc_clear( sizeof *s2k );
216 s2k->mode = RFC1991? 0:opt.s2k_mode;
217 s2k->hash_algo=S2K_DIGEST_ALGO;
218 cfx.dek = passphrase_to_dek( NULL, 0,
219 default_cipher_algo(), s2k, 2,
220 NULL, &canceled);
221 if( !cfx.dek || !cfx.dek->keylen ) {
222 rc = gpg_error (canceled? GPG_ERR_CANCELED:GPG_ERR_INV_PASSPHRASE);
223 xfree(cfx.dek);
224 xfree(s2k);
225 iobuf_close(inp);
226 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc));
227 release_progress_context (pfx);
228 return rc;
230 if (use_seskey && s2k->mode != 1 && s2k->mode != 3) {
231 use_seskey = 0;
232 log_info (_("can't use a symmetric ESK packet "
233 "due to the S2K mode\n"));
236 if ( use_seskey )
238 DEK *dek = NULL;
240 seskeylen = gcry_cipher_get_algo_keylen (default_cipher_algo ());
241 encode_seskey( cfx.dek, &dek, enckey );
242 xfree( cfx.dek ); cfx.dek = dek;
245 if(opt.verbose)
246 log_info(_("using cipher %s\n"),
247 openpgp_cipher_algo_name (cfx.dek->algo));
249 cfx.dek->use_mdc=use_mdc(NULL,cfx.dek->algo);
252 if (do_compress && cfx.dek && cfx.dek->use_mdc
253 && is_file_compressed(filename, &rc))
255 if (opt.verbose)
256 log_info(_("`%s' already compressed\n"), filename);
257 do_compress = 0;
260 if( rc || (rc = open_outfile( filename, opt.armor? 1:0, &out )) ) {
261 iobuf_cancel(inp);
262 xfree(cfx.dek);
263 xfree(s2k);
264 release_progress_context (pfx);
265 return rc;
268 if ( opt.armor )
270 afx = new_armor_context ();
271 push_armor_filter (afx, out);
274 if( s2k && !RFC1991 ) {
275 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc + seskeylen + 1 );
276 enc->version = 4;
277 enc->cipher_algo = cfx.dek->algo;
278 enc->s2k = *s2k;
279 if ( use_seskey && seskeylen ) {
280 enc->seskeylen = seskeylen + 1; /* algo id */
281 memcpy( enc->seskey, enckey, seskeylen + 1 );
283 pkt.pkttype = PKT_SYMKEY_ENC;
284 pkt.pkt.symkey_enc = enc;
285 if( (rc = build_packet( out, &pkt )) )
286 log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
287 xfree(enc);
290 if (!opt.no_literal)
291 pt=setup_plaintext_name(filename,inp);
293 /* Note that PGP 5 has problems decrypting symmetrically encrypted
294 data if the file length is in the inner packet. It works when
295 only partial length headers are use. In the past, we always
296 used partial body length here, but since PGP 2, PGP 6, and PGP
297 7 need the file length, and nobody should be using PGP 5
298 nowadays anyway, this is now set to the file length. Note also
299 that this only applies to the RFC-1991 style symmetric
300 messages, and not the RFC-2440 style. PGP 6 and 7 work with
301 either partial length or fixed length with the new style
302 messages. */
304 if ( !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
306 off_t tmpsize;
307 int overflow;
309 if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
310 && !overflow )
311 log_info(_("WARNING: `%s' is an empty file\n"), filename );
312 /* We can't encode the length of very large files because
313 OpenPGP uses only 32 bit for file sizes. So if the the
314 size of a file is larger than 2^32 minus some bytes for
315 packet headers, we switch to partial length encoding. */
316 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
317 filesize = tmpsize;
318 else
319 filesize = 0;
321 else
322 filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
324 if (!opt.no_literal) {
325 pt->timestamp = make_timestamp();
326 pt->mode = opt.textmode? 't' : 'b';
327 pt->len = filesize;
328 pt->new_ctb = !pt->len && !RFC1991;
329 pt->buf = inp;
330 pkt.pkttype = PKT_PLAINTEXT;
331 pkt.pkt.plaintext = pt;
332 cfx.datalen = filesize && !do_compress ? calc_packet_length( &pkt ) : 0;
334 else
336 cfx.datalen = filesize && !do_compress ? filesize : 0;
337 pkt.pkttype = 0;
338 pkt.pkt.generic = NULL;
341 /* register the cipher filter */
342 if( mode )
343 iobuf_push_filter( out, cipher_filter, &cfx );
344 /* register the compress filter */
345 if( do_compress )
347 if (cfx.dek && cfx.dek->use_mdc)
348 zfx.new_ctb = 1;
349 push_compress_filter(out,&zfx,default_compress_algo());
352 /* do the work */
353 if (!opt.no_literal) {
354 if( (rc = build_packet( out, &pkt )) )
355 log_error("build_packet failed: %s\n", g10_errstr(rc) );
357 else {
358 /* user requested not to create a literal packet,
359 * so we copy the plain data */
360 byte copy_buffer[4096];
361 int bytes_copied;
362 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
363 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
364 log_error ("copying input to output failed: %s\n",
365 gpg_strerror (rc) );
366 break;
368 wipememory(copy_buffer, 4096); /* burn buffer */
371 /* finish the stuff */
372 iobuf_close(inp);
373 if (rc)
374 iobuf_cancel(out);
375 else {
376 iobuf_close(out); /* fixme: check returncode */
377 if (mode)
378 write_status( STATUS_END_ENCRYPTION );
380 if (pt)
381 pt->buf = NULL;
382 free_packet(&pkt);
383 xfree(cfx.dek);
384 xfree(s2k);
385 release_armor_context (afx);
386 release_progress_context (pfx);
387 return rc;
391 setup_symkey(STRING2KEY **symkey_s2k,DEK **symkey_dek)
393 int canceled;
395 *symkey_s2k=xmalloc_clear(sizeof(STRING2KEY));
396 (*symkey_s2k)->mode = opt.s2k_mode;
397 (*symkey_s2k)->hash_algo = S2K_DIGEST_ALGO;
399 *symkey_dek=passphrase_to_dek(NULL,0,opt.s2k_cipher_algo,
400 *symkey_s2k,2,NULL, &canceled);
401 if(!*symkey_dek || !(*symkey_dek)->keylen)
403 xfree(*symkey_dek);
404 xfree(*symkey_s2k);
405 return gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
408 return 0;
411 static int
412 write_symkey_enc(STRING2KEY *symkey_s2k,DEK *symkey_dek,DEK *dek,IOBUF out)
414 int rc, seskeylen = gcry_cipher_get_algo_keylen (dek->algo);
416 PKT_symkey_enc *enc;
417 byte enckey[33];
418 PACKET pkt;
420 enc=xmalloc_clear(sizeof(PKT_symkey_enc)+seskeylen+1);
421 encode_seskey(symkey_dek,&dek,enckey);
423 enc->version = 4;
424 enc->cipher_algo = opt.s2k_cipher_algo;
425 enc->s2k = *symkey_s2k;
426 enc->seskeylen = seskeylen + 1; /* algo id */
427 memcpy( enc->seskey, enckey, seskeylen + 1 );
429 pkt.pkttype = PKT_SYMKEY_ENC;
430 pkt.pkt.symkey_enc = enc;
432 if((rc=build_packet(out,&pkt)))
433 log_error("build symkey_enc packet failed: %s\n",g10_errstr(rc));
435 xfree(enc);
436 return rc;
439 /****************
440 * Encrypt the file with the given userids (or ask if none
441 * is supplied).
444 encode_crypt( const char *filename, strlist_t remusr, int use_symkey )
446 IOBUF inp = NULL, out = NULL;
447 PACKET pkt;
448 PKT_plaintext *pt = NULL;
449 DEK *symkey_dek = NULL;
450 STRING2KEY *symkey_s2k = NULL;
451 int rc = 0, rc2 = 0;
452 u32 filesize;
453 cipher_filter_context_t cfx;
454 armor_filter_context_t *afx = NULL;
455 compress_filter_context_t zfx;
456 text_filter_context_t tfx;
457 progress_filter_context_t *pfx;
458 PK_LIST pk_list,work_list;
459 int do_compress = opt.compress_algo && !RFC1991;
461 pfx = new_progress_context ();
462 memset( &cfx, 0, sizeof cfx);
463 memset( &zfx, 0, sizeof zfx);
464 memset( &tfx, 0, sizeof tfx);
465 init_packet(&pkt);
467 if(use_symkey
468 && (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
470 release_progress_context (pfx);
471 return rc;
474 if( (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC)) )
476 release_progress_context (pfx);
477 return rc;
480 if(PGP2) {
481 for(work_list=pk_list; work_list; work_list=work_list->next)
482 if(!(is_RSA(work_list->pk->pubkey_algo) &&
483 nbits_from_pk(work_list->pk)<=2048))
485 log_info(_("you can only encrypt to RSA keys of 2048 bits or "
486 "less in --pgp2 mode\n"));
487 compliance_failure();
488 break;
492 /* prepare iobufs */
493 inp = iobuf_open(filename);
494 if (inp)
495 iobuf_ioctl (inp,3,1,NULL); /* disable fd caching */
496 if (inp && is_secured_file (iobuf_get_fd (inp)))
498 iobuf_close (inp);
499 inp = NULL;
500 errno = EPERM;
502 if( !inp ) {
503 rc = gpg_error_from_syserror ();
504 log_error(_("can't open `%s': %s\n"),
505 filename? filename: "[stdin]",
506 gpg_strerror (rc) );
507 goto leave;
509 else if( opt.verbose )
510 log_info(_("reading from `%s'\n"), filename? filename: "[stdin]");
512 handle_progress (pfx, inp, filename);
514 if( opt.textmode )
515 iobuf_push_filter( inp, text_filter, &tfx );
517 if( (rc = open_outfile( filename, opt.armor? 1:0, &out )) )
518 goto leave;
520 if ( opt.armor )
522 afx = new_armor_context ();
523 push_armor_filter (afx, out);
526 /* create a session key */
527 cfx.dek = xmalloc_secure_clear (sizeof *cfx.dek);
528 if( !opt.def_cipher_algo ) { /* try to get it from the prefs */
529 cfx.dek->algo = select_algo_from_prefs(pk_list,PREFTYPE_SYM,-1,NULL);
530 /* The only way select_algo_from_prefs can fail here is when
531 mixing v3 and v4 keys, as v4 keys have an implicit
532 preference entry for 3DES, and the pk_list cannot be empty.
533 In this case, use 3DES anyway as it's the safest choice -
534 perhaps the v3 key is being used in an OpenPGP
535 implementation and we know that the implementation behind
536 any v4 key can handle 3DES. */
537 if( cfx.dek->algo == -1 ) {
538 cfx.dek->algo = CIPHER_ALGO_3DES;
540 if( PGP2 ) {
541 log_info(_("unable to use the IDEA cipher for all of the keys "
542 "you are encrypting to.\n"));
543 compliance_failure();
547 /* In case 3DES has been selected, print a warning if
548 any key does not have a preference for AES. This
549 should help to indentify why encrypting to several
550 recipients falls back to 3DES. */
551 if (opt.verbose
552 && cfx.dek->algo == CIPHER_ALGO_3DES)
553 warn_missing_aes_from_pklist (pk_list);
555 else {
556 if(!opt.expert &&
557 select_algo_from_prefs(pk_list,PREFTYPE_SYM,
558 opt.def_cipher_algo,NULL)!=opt.def_cipher_algo)
559 log_info(_("WARNING: forcing symmetric cipher %s (%d)"
560 " violates recipient preferences\n"),
561 openpgp_cipher_algo_name (opt.def_cipher_algo),
562 opt.def_cipher_algo);
564 cfx.dek->algo = opt.def_cipher_algo;
567 cfx.dek->use_mdc=use_mdc(pk_list,cfx.dek->algo);
569 /* Only do the is-file-already-compressed check if we are using a
570 MDC. This forces compressed files to be re-compressed if we do
571 not have a MDC to give some protection against chosen
572 ciphertext attacks. */
574 if (do_compress && cfx.dek->use_mdc && is_file_compressed(filename, &rc2) )
576 if (opt.verbose)
577 log_info(_("`%s' already compressed\n"), filename);
578 do_compress = 0;
580 if (rc2)
582 rc = rc2;
583 goto leave;
586 make_session_key( cfx.dek );
587 if( DBG_CIPHER )
588 log_printhex ("DEK is: ", cfx.dek->key, cfx.dek->keylen );
590 rc = write_pubkey_enc_from_list( pk_list, cfx.dek, out );
591 if( rc )
592 goto leave;
594 /* We put the passphrase (if any) after any public keys as this
595 seems to be the most useful on the recipient side - there is no
596 point in prompting a user for a passphrase if they have the
597 secret key needed to decrypt. */
598 if(use_symkey && (rc=write_symkey_enc(symkey_s2k,symkey_dek,cfx.dek,out)))
599 goto leave;
601 if (!opt.no_literal)
602 pt=setup_plaintext_name(filename,inp);
604 if (!iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
606 off_t tmpsize;
607 int overflow;
609 if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
610 && !overflow )
611 log_info(_("WARNING: `%s' is an empty file\n"), filename );
612 /* We can't encode the length of very large files because
613 OpenPGP uses only 32 bit for file sizes. So if the the
614 size of a file is larger than 2^32 minus some bytes for
615 packet headers, we switch to partial length encoding. */
616 if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
617 filesize = tmpsize;
618 else
619 filesize = 0;
621 else
622 filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
624 if (!opt.no_literal) {
625 pt->timestamp = make_timestamp();
626 pt->mode = opt.textmode ? 't' : 'b';
627 pt->len = filesize;
628 pt->new_ctb = !pt->len && !RFC1991;
629 pt->buf = inp;
630 pkt.pkttype = PKT_PLAINTEXT;
631 pkt.pkt.plaintext = pt;
632 cfx.datalen = filesize && !do_compress? calc_packet_length( &pkt ) : 0;
634 else
635 cfx.datalen = filesize && !do_compress ? filesize : 0;
637 /* register the cipher filter */
638 iobuf_push_filter( out, cipher_filter, &cfx );
640 /* register the compress filter */
641 if( do_compress ) {
642 int compr_algo = opt.compress_algo;
644 if(compr_algo==-1)
646 if((compr_algo=
647 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
648 compr_algo=DEFAULT_COMPRESS_ALGO;
649 /* Theoretically impossible to get here since uncompressed
650 is implicit. */
652 else if(!opt.expert &&
653 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
654 compr_algo,NULL)!=compr_algo)
655 log_info(_("WARNING: forcing compression algorithm %s (%d)"
656 " violates recipient preferences\n"),
657 compress_algo_to_string(compr_algo),compr_algo);
659 /* algo 0 means no compression */
660 if( compr_algo )
662 if (cfx.dek && cfx.dek->use_mdc)
663 zfx.new_ctb = 1;
664 push_compress_filter(out,&zfx,compr_algo);
668 /* do the work */
669 if (!opt.no_literal) {
670 if( (rc = build_packet( out, &pkt )) )
671 log_error("build_packet failed: %s\n", g10_errstr(rc) );
673 else {
674 /* user requested not to create a literal packet, so we copy
675 the plain data */
676 byte copy_buffer[4096];
677 int bytes_copied;
678 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
679 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
680 log_error ("copying input to output failed: %s\n",
681 gpg_strerror (rc));
682 break;
684 wipememory(copy_buffer, 4096); /* burn buffer */
687 /* finish the stuff */
688 leave:
689 iobuf_close(inp);
690 if( rc )
691 iobuf_cancel(out);
692 else {
693 iobuf_close(out); /* fixme: check returncode */
694 write_status( STATUS_END_ENCRYPTION );
696 if( pt )
697 pt->buf = NULL;
698 free_packet(&pkt);
699 xfree(cfx.dek);
700 xfree(symkey_dek);
701 xfree(symkey_s2k);
702 release_pk_list( pk_list );
703 release_armor_context (afx);
704 release_progress_context (pfx);
705 return rc;
711 /****************
712 * Filter to do a complete public key encryption.
715 encrypt_filter( void *opaque, int control,
716 IOBUF a, byte *buf, size_t *ret_len)
718 size_t size = *ret_len;
719 encrypt_filter_context_t *efx = opaque;
720 int rc=0;
722 if( control == IOBUFCTRL_UNDERFLOW ) { /* decrypt */
723 BUG(); /* not used */
725 else if( control == IOBUFCTRL_FLUSH ) { /* encrypt */
726 if( !efx->header_okay ) {
727 efx->cfx.dek = xmalloc_secure_clear( sizeof *efx->cfx.dek );
729 if( !opt.def_cipher_algo ) { /* try to get it from the prefs */
730 efx->cfx.dek->algo =
731 select_algo_from_prefs(efx->pk_list,PREFTYPE_SYM,-1,NULL);
732 if( efx->cfx.dek->algo == -1 ) {
733 /* because 3DES is implicitly in the prefs, this can only
734 * happen if we do not have any public keys in the list */
735 efx->cfx.dek->algo = DEFAULT_CIPHER_ALGO;
738 /* In case 3DES has been selected, print a warning if
739 any key does not have a preference for AES. This
740 should help to indentify why encrypting to several
741 recipients falls back to 3DES. */
742 if (opt.verbose
743 && efx->cfx.dek->algo == CIPHER_ALGO_3DES)
744 warn_missing_aes_from_pklist (efx->pk_list);
746 else {
747 if(!opt.expert &&
748 select_algo_from_prefs(efx->pk_list,PREFTYPE_SYM,
749 opt.def_cipher_algo,
750 NULL)!=opt.def_cipher_algo)
751 log_info(_("forcing symmetric cipher %s (%d) "
752 "violates recipient preferences\n"),
753 openpgp_cipher_algo_name (opt.def_cipher_algo),
754 opt.def_cipher_algo);
756 efx->cfx.dek->algo = opt.def_cipher_algo;
759 efx->cfx.dek->use_mdc = use_mdc(efx->pk_list,efx->cfx.dek->algo);
761 make_session_key( efx->cfx.dek );
762 if( DBG_CIPHER )
763 log_printhex ("DEK is: ",
764 efx->cfx.dek->key, efx->cfx.dek->keylen );
766 rc = write_pubkey_enc_from_list( efx->pk_list, efx->cfx.dek, a );
767 if( rc )
768 return rc;
770 if(efx->symkey_s2k && efx->symkey_dek)
772 rc=write_symkey_enc(efx->symkey_s2k,efx->symkey_dek,
773 efx->cfx.dek,a);
774 if(rc)
775 return rc;
778 iobuf_push_filter( a, cipher_filter, &efx->cfx );
780 efx->header_okay = 1;
782 rc = iobuf_write( a, buf, size );
785 else if( control == IOBUFCTRL_FREE )
787 xfree(efx->symkey_dek);
788 xfree(efx->symkey_s2k);
790 else if( control == IOBUFCTRL_DESC ) {
791 *(char**)buf = "encrypt_filter";
793 return rc;
797 /****************
798 * Write pubkey-enc packets from the list of PKs to OUT.
800 static int
801 write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, IOBUF out )
803 PACKET pkt;
804 PKT_public_key *pk;
805 PKT_pubkey_enc *enc;
806 int rc;
808 for( ; pk_list; pk_list = pk_list->next ) {
809 gcry_mpi_t frame;
811 pk = pk_list->pk;
813 print_pubkey_algo_note( pk->pubkey_algo );
814 enc = xmalloc_clear( sizeof *enc );
815 enc->pubkey_algo = pk->pubkey_algo;
816 keyid_from_pk( pk, enc->keyid );
817 enc->throw_keyid = (opt.throw_keyid || (pk_list->flags&1));
819 if(opt.throw_keyid && (PGP2 || PGP6 || PGP7 || PGP8))
821 log_info(_("you may not use %s while in %s mode\n"),
822 "--throw-keyid",compliance_option_string());
823 compliance_failure();
826 /* Okay, what's going on: We have the session key somewhere in
827 * the structure DEK and want to encode this session key in
828 * an integer value of n bits. pubkey_nbits gives us the
829 * number of bits we have to use. We then encode the session
830 * key in some way and we get it back in the big intger value
831 * FRAME. Then we use FRAME, the public key PK->PKEY and the
832 * algorithm number PK->PUBKEY_ALGO and pass it to pubkey_encrypt
833 * which returns the encrypted value in the array ENC->DATA.
834 * This array has a size which depends on the used algorithm
835 * (e.g. 2 for Elgamal). We don't need frame anymore because we
836 * have everything now in enc->data which is the passed to
837 * build_packet()
839 frame = encode_session_key (dek, pubkey_nbits (pk->pubkey_algo,
840 pk->pkey) );
841 rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, pk->pkey);
842 gcry_mpi_release (frame);
843 if( rc )
844 log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
845 else {
846 if( opt.verbose ) {
847 char *ustr = get_user_id_string_native (enc->keyid);
848 log_info(_("%s/%s encrypted for: \"%s\"\n"),
849 gcry_pk_algo_name (enc->pubkey_algo),
850 openpgp_cipher_algo_name (dek->algo),
851 ustr );
852 xfree(ustr);
854 /* and write it */
855 init_packet(&pkt);
856 pkt.pkttype = PKT_PUBKEY_ENC;
857 pkt.pkt.pubkey_enc = enc;
858 rc = build_packet( out, &pkt );
859 if( rc )
860 log_error("build_packet(pubkey_enc) failed: %s\n", g10_errstr(rc));
862 free_pubkey_enc(enc);
863 if( rc )
864 return rc;
866 return 0;
869 void
870 encode_crypt_files(int nfiles, char **files, strlist_t remusr)
872 int rc = 0;
874 if (opt.outfile)
876 log_error(_("--output doesn't work for this command\n"));
877 return;
880 if (!nfiles)
882 char line[2048];
883 unsigned int lno = 0;
884 while ( fgets(line, DIM(line), stdin) )
886 lno++;
887 if (!*line || line[strlen(line)-1] != '\n')
889 log_error("input line %u too long or missing LF\n", lno);
890 return;
892 line[strlen(line)-1] = '\0';
893 print_file_status(STATUS_FILE_START, line, 2);
894 if ( (rc = encode_crypt(line, remusr, 0)) )
895 log_error("encryption of `%s' failed: %s\n",
896 print_fname_stdin(line), g10_errstr(rc) );
897 write_status( STATUS_FILE_DONE );
900 else
902 while (nfiles--)
904 print_file_status(STATUS_FILE_START, *files, 2);
905 if ( (rc = encode_crypt(*files, remusr, 0)) )
906 log_error("encryption of `%s' failed: %s\n",
907 print_fname_stdin(*files), g10_errstr(rc) );
908 write_status( STATUS_FILE_DONE );
909 files++;