1 /* encode.c - encode data
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3  *               2006 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
27 
28 #include "options.h"
29 #include "packet.h"
30 #include "errors.h"
31 #include "iobuf.h"
32 #include "keydb.h"
33 #include "memory.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 
41 static int encode_simple( const char *filename, int mode, int use_seskey );
42 static int write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, IOBUF out );
43 
44 /****************
45  * Encode FILENAME with only the symmetric cipher.  Take input from
46  * stdin if FILENAME is NULL.
47  */
48 int
encode_symmetric(const char * filename)49 encode_symmetric( const char *filename )
50 {
51     return encode_simple( filename, 1, 0 );
52 }
53 
54 /****************
55  * Encode FILENAME as a literal data packet only. Take input from
56  * stdin if FILENAME is NULL.
57  */
58 int
encode_store(const char * filename)59 encode_store( const char *filename )
60 {
61     return encode_simple( filename, 0, 0 );
62 }
63 
64 static void
encode_seskey(DEK * dek,DEK ** seskey,byte * enckey)65 encode_seskey( DEK *dek, DEK **seskey, byte *enckey )
66 {
67     CIPHER_HANDLE hd;
68     byte buf[33];
69 
70     assert ( dek->keylen <= 32 );
71     if(!*seskey)
72       {
73 	*seskey=xmalloc_clear(sizeof(DEK));
74 	(*seskey)->keylen=dek->keylen;
75 	(*seskey)->algo=dek->algo;
76 	make_session_key(*seskey);
77 	/*log_hexdump( "thekey", c->key, c->keylen );*/
78       }
79 
80     buf[0] = (*seskey)->algo;
81     memcpy( buf + 1, (*seskey)->key, (*seskey)->keylen );
82 
83     hd = cipher_open( dek->algo, CIPHER_MODE_CFB, 1 );
84     cipher_setkey( hd, dek->key, dek->keylen );
85     cipher_setiv( hd, NULL, 0 );
86     cipher_encrypt( hd, buf, buf, (*seskey)->keylen + 1 );
87     cipher_close( hd );
88 
89     memcpy( enckey, buf, (*seskey)->keylen + 1 );
90     wipememory( buf, sizeof buf ); /* burn key */
91 }
92 
93 /* We try very hard to use a MDC */
94 static int
use_mdc(PK_LIST pk_list,int algo)95 use_mdc(PK_LIST pk_list,int algo)
96 {
97   /* RFC-1991 and 2440 don't have MDC */
98   if(RFC1991 || RFC2440)
99     return 0;
100 
101   /* --force-mdc overrides --disable-mdc */
102   if(opt.force_mdc)
103     return 1;
104 
105   if(opt.disable_mdc)
106     return 0;
107 
108   /* Do the keys really support MDC? */
109 
110   if(select_mdc_from_pklist(pk_list))
111     return 1;
112 
113   /* The keys don't support MDC, so now we do a bit of a hack - if any
114      of the AESes or TWOFISH are in the prefs, we assume that the user
115      can handle a MDC.  This is valid for PGP 7, which can handle MDCs
116      though it will not generate them.  2440bis allows this, by the
117      way. */
118 
119   if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
120 			    CIPHER_ALGO_AES,NULL)==CIPHER_ALGO_AES)
121     return 1;
122 
123   if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
124 			    CIPHER_ALGO_AES192,NULL)==CIPHER_ALGO_AES192)
125     return 1;
126 
127   if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
128 			    CIPHER_ALGO_AES256,NULL)==CIPHER_ALGO_AES256)
129     return 1;
130 
131   if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
132 			    CIPHER_ALGO_TWOFISH,NULL)==CIPHER_ALGO_TWOFISH)
133     return 1;
134 
135   /* Last try.  Use MDC for the modern ciphers. */
136 
137   if(cipher_get_blocksize(algo)!=8)
138     return 1;
139 
140   return 0; /* No MDC */
141 }
142 
143 /* We don't want to use use_seskey yet because older gnupg versions
144    can't handle it, and there isn't really any point unless we're
145    making a message that can be decrypted by a public key or
146    passphrase. */
147 static int
encode_simple(const char * filename,int mode,int use_seskey)148 encode_simple( const char *filename, int mode, int use_seskey )
149 {
150     IOBUF inp, out;
151     PACKET pkt;
152     PKT_plaintext *pt = NULL;
153     STRING2KEY *s2k = NULL;
154     byte enckey[33];
155     int rc = 0;
156     int seskeylen = 0;
157     u32 filesize;
158     cipher_filter_context_t cfx;
159     armor_filter_context_t afx;
160     compress_filter_context_t zfx;
161     text_filter_context_t tfx;
162     progress_filter_context_t pfx;
163     int do_compress = !RFC1991 && default_compress_algo();
164 
165     memset( &cfx, 0, sizeof cfx);
166     memset( &afx, 0, sizeof afx);
167     memset( &zfx, 0, sizeof zfx);
168     memset( &tfx, 0, sizeof tfx);
169     init_packet(&pkt);
170 
171     /* prepare iobufs */
172     inp = iobuf_open(filename);
173     if (inp)
174       iobuf_ioctl (inp,3,1,NULL); /* disable fd caching */
175     if (inp && is_secured_file (iobuf_get_fd (inp)))
176       {
177         iobuf_close (inp);
178         inp = NULL;
179         errno = EPERM;
180       }
181     if( !inp ) {
182 	log_error(_("can't open `%s': %s\n"), filename? filename: "[stdin]",
183                   strerror(errno) );
184 	return G10ERR_OPEN_FILE;
185     }
186 
187     handle_progress (&pfx, inp, filename);
188 
189     if( opt.textmode )
190 	iobuf_push_filter( inp, text_filter, &tfx );
191 
192     /* Due the the fact that we use don't use an IV to encrypt the
193        session key we can't use the new mode with RFC1991 because
194        it has no S2K salt. RFC1991 always uses simple S2K. */
195     if ( RFC1991 && use_seskey )
196         use_seskey = 0;
197 
198     cfx.dek = NULL;
199     if( mode ) {
200 	s2k = xmalloc_clear( sizeof *s2k );
201 	s2k->mode = RFC1991? 0:opt.s2k_mode;
202 	s2k->hash_algo=S2K_DIGEST_ALGO;
203 	cfx.dek = passphrase_to_dek( NULL, 0,
204 				     default_cipher_algo(), s2k, 2,
205                                      NULL, NULL);
206 	if( !cfx.dek || !cfx.dek->keylen ) {
207 	    rc = G10ERR_PASSPHRASE;
208 	    xfree(cfx.dek);
209 	    xfree(s2k);
210 	    iobuf_close(inp);
211 	    log_error(_("error creating passphrase: %s\n"), g10_errstr(rc) );
212 	    return rc;
213 	}
214         if (use_seskey && s2k->mode != 1 && s2k->mode != 3) {
215             use_seskey = 0;
216             log_info (_("can't use a symmetric ESK packet "
217                         "due to the S2K mode\n"));
218         }
219 
220         if ( use_seskey )
221 	  {
222 	    DEK *dek = NULL;
223             seskeylen = cipher_get_keylen( default_cipher_algo() ) / 8;
224             encode_seskey( cfx.dek, &dek, enckey );
225             xfree( cfx.dek ); cfx.dek = dek;
226 	  }
227 
228 	if(opt.verbose)
229 	  log_info(_("using cipher %s\n"),
230 		   cipher_algo_to_string(cfx.dek->algo));
231 
232 	cfx.dek->use_mdc=use_mdc(NULL,cfx.dek->algo);
233     }
234 
235     if (do_compress && cfx.dek && cfx.dek->use_mdc
236 	&& is_file_compressed(filename, &rc))
237       {
238         if (opt.verbose)
239           log_info(_("`%s' already compressed\n"), filename);
240         do_compress = 0;
241       }
242 
243     if( rc || (rc = open_outfile( filename, opt.armor? 1:0, &out )) ) {
244 	iobuf_cancel(inp);
245 	xfree(cfx.dek);
246 	xfree(s2k);
247 	return rc;
248     }
249 
250     if( opt.armor )
251 	iobuf_push_filter( out, armor_filter, &afx );
252 
253     if( s2k && !RFC1991 ) {
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             enc->seskeylen = seskeylen + 1; /* algo id */
260             memcpy( enc->seskey, enckey, seskeylen + 1 );
261         }
262 	pkt.pkttype = PKT_SYMKEY_ENC;
263 	pkt.pkt.symkey_enc = enc;
264 	if( (rc = build_packet( out, &pkt )) )
265 	    log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
266 	xfree(enc);
267     }
268 
269     if (!opt.no_literal)
270       pt=setup_plaintext_name(filename,inp);
271 
272     /* Note that PGP 5 has problems decrypting symmetrically encrypted
273        data if the file length is in the inner packet. It works when
274        only partial length headers are use.  In the past, we always
275        used partial body length here, but since PGP 2, PGP 6, and PGP
276        7 need the file length, and nobody should be using PGP 5
277        nowadays anyway, this is now set to the file length.  Note also
278        that this only applies to the RFC-1991 style symmetric
279        messages, and not the RFC-2440 style.  PGP 6 and 7 work with
280        either partial length or fixed length with the new style
281        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 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 	pt->timestamp = make_timestamp();
305 	pt->mode = opt.textmode? 't' : 'b';
306 	pt->len = filesize;
307 	pt->new_ctb = !pt->len && !RFC1991;
308 	pt->buf = inp;
309 	pkt.pkttype = PKT_PLAINTEXT;
310 	pkt.pkt.plaintext = pt;
311 	cfx.datalen = filesize && !do_compress ? calc_packet_length( &pkt ) : 0;
312     }
313     else
314       {
315         cfx.datalen = filesize && !do_compress ? filesize : 0;
316         pkt.pkttype = 0;
317         pkt.pkt.generic = NULL;
318       }
319 
320     /* register the cipher filter */
321     if( mode )
322 	iobuf_push_filter( out, cipher_filter, &cfx );
323     /* register the compress filter */
324     if( do_compress )
325       {
326         if (cfx.dek && cfx.dek->use_mdc)
327           zfx.new_ctb = 1;
328 	push_compress_filter(out,&zfx,default_compress_algo());
329       }
330 
331     /* do the work */
332     if (!opt.no_literal) {
333 	if( (rc = build_packet( out, &pkt )) )
334 	    log_error("build_packet failed: %s\n", g10_errstr(rc) );
335     }
336     else {
337 	/* user requested not to create a literal packet,
338 	 * so we copy the plain data */
339 	byte copy_buffer[4096];
340 	int  bytes_copied;
341 	while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
342 	    if (iobuf_write(out, copy_buffer, bytes_copied) == -1) {
343 		rc = G10ERR_WRITE_FILE;
344 		log_error("copying input to output failed: %s\n", g10_errstr(rc) );
345 		break;
346 	    }
347 	wipememory(copy_buffer, 4096); /* burn buffer */
348     }
349 
350     /* finish the stuff */
351     iobuf_close(inp);
352     if (rc)
353 	iobuf_cancel(out);
354     else {
355 	iobuf_close(out); /* fixme: check returncode */
356         if (mode)
357             write_status( STATUS_END_ENCRYPTION );
358     }
359     if (pt)
360 	pt->buf = NULL;
361     free_packet(&pkt);
362     xfree(cfx.dek);
363     xfree(s2k);
364     return rc;
365 }
366 
367 int
setup_symkey(STRING2KEY ** symkey_s2k,DEK ** symkey_dek)368 setup_symkey(STRING2KEY **symkey_s2k,DEK **symkey_dek)
369 {
370   *symkey_s2k=xmalloc_clear(sizeof(STRING2KEY));
371   (*symkey_s2k)->mode = opt.s2k_mode;
372   (*symkey_s2k)->hash_algo = S2K_DIGEST_ALGO;
373 
374   *symkey_dek=passphrase_to_dek(NULL,0,opt.s2k_cipher_algo,
375 				*symkey_s2k,2,NULL,NULL);
376   if(!*symkey_dek || !(*symkey_dek)->keylen)
377     {
378       xfree(*symkey_dek);
379       xfree(*symkey_s2k);
380       return G10ERR_PASSPHRASE;
381     }
382 
383   return 0;
384 }
385 
386 static int
write_symkey_enc(STRING2KEY * symkey_s2k,DEK * symkey_dek,DEK * dek,IOBUF out)387 write_symkey_enc(STRING2KEY *symkey_s2k,DEK *symkey_dek,DEK *dek,IOBUF out)
388 {
389   int rc,seskeylen=cipher_get_keylen(dek->algo)/8;
390 
391   PKT_symkey_enc *enc;
392   byte enckey[33];
393   PACKET pkt;
394 
395   enc=xmalloc_clear(sizeof(PKT_symkey_enc)+seskeylen+1);
396   encode_seskey(symkey_dek,&dek,enckey);
397 
398   enc->version = 4;
399   enc->cipher_algo = opt.s2k_cipher_algo;
400   enc->s2k = *symkey_s2k;
401   enc->seskeylen = seskeylen + 1; /* algo id */
402   memcpy( enc->seskey, enckey, seskeylen + 1 );
403 
404   pkt.pkttype = PKT_SYMKEY_ENC;
405   pkt.pkt.symkey_enc = enc;
406 
407   if((rc=build_packet(out,&pkt)))
408     log_error("build symkey_enc packet failed: %s\n",g10_errstr(rc));
409 
410   xfree(enc);
411   return rc;
412 }
413 
414 /****************
415  * Encrypt the file with the given userids (or ask if none
416  * is supplied).
417  */
418 int
encode_crypt(const char * filename,STRLIST remusr,int use_symkey)419 encode_crypt( const char *filename, STRLIST remusr, int use_symkey )
420 {
421     IOBUF inp = NULL, out = NULL;
422     PACKET pkt;
423     PKT_plaintext *pt = NULL;
424     DEK *symkey_dek = NULL;
425     STRING2KEY *symkey_s2k = NULL;
426     int rc = 0, rc2 = 0;
427     u32 filesize;
428     cipher_filter_context_t cfx;
429     armor_filter_context_t afx;
430     compress_filter_context_t zfx;
431     text_filter_context_t tfx;
432     progress_filter_context_t pfx;
433     PK_LIST pk_list,work_list;
434     int do_compress = opt.compress_algo && !RFC1991;
435 
436     memset( &cfx, 0, sizeof cfx);
437     memset( &afx, 0, sizeof afx);
438     memset( &zfx, 0, sizeof zfx);
439     memset( &tfx, 0, sizeof tfx);
440     init_packet(&pkt);
441 
442     if(use_symkey
443        && (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
444       return rc;
445 
446     if( (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC)) )
447 	return rc;
448 
449     if(PGP2) {
450       for(work_list=pk_list; work_list; work_list=work_list->next)
451 	if(!(is_RSA(work_list->pk->pubkey_algo) &&
452 	     nbits_from_pk(work_list->pk)<=2048))
453 	  {
454 	    log_info(_("you can only encrypt to RSA keys of 2048 bits or "
455 		       "less in --pgp2 mode\n"));
456 	    compliance_failure();
457 	    break;
458 	  }
459     }
460 
461     /* prepare iobufs */
462     inp = iobuf_open(filename);
463     if (inp)
464       iobuf_ioctl (inp,3,1,NULL); /* disable fd caching */
465     if (inp && is_secured_file (iobuf_get_fd (inp)))
466       {
467         iobuf_close (inp);
468         inp = NULL;
469         errno = EPERM;
470       }
471     if( !inp ) {
472 	log_error(_("can't open `%s': %s\n"), filename? filename: "[stdin]",
473 					strerror(errno) );
474 	rc = G10ERR_OPEN_FILE;
475 	goto leave;
476     }
477     else if( opt.verbose )
478 	log_info(_("reading from `%s'\n"), filename? filename: "[stdin]");
479 
480     handle_progress (&pfx, inp, filename);
481 
482     if( opt.textmode )
483 	iobuf_push_filter( inp, text_filter, &tfx );
484 
485     if( (rc = open_outfile( filename, opt.armor? 1:0, &out )) )
486 	goto leave;
487 
488     if( opt.armor )
489 	iobuf_push_filter( out, armor_filter, &afx );
490 
491     /* create a session key */
492     cfx.dek = xmalloc_secure_clear (sizeof *cfx.dek);
493     if( !opt.def_cipher_algo ) { /* try to get it from the prefs */
494 	cfx.dek->algo = select_algo_from_prefs(pk_list,PREFTYPE_SYM,-1,NULL);
495 	/* The only way select_algo_from_prefs can fail here is when
496            mixing v3 and v4 keys, as v4 keys have an implicit
497            preference entry for 3DES, and the pk_list cannot be empty.
498            In this case, use 3DES anyway as it's the safest choice -
499            perhaps the v3 key is being used in an OpenPGP
500            implementation and we know that the implementation behind
501            any v4 key can handle 3DES. */
502 	if( cfx.dek->algo == -1 ) {
503 	    cfx.dek->algo = CIPHER_ALGO_3DES;
504 
505 	    if( PGP2 ) {
506 	      log_info(_("unable to use the IDEA cipher for all of the keys "
507 			 "you are encrypting to.\n"));
508 	      compliance_failure();
509 	    }
510 	}
511     }
512     else {
513       if(!opt.expert &&
514 	 select_algo_from_prefs(pk_list,PREFTYPE_SYM,
515 				opt.def_cipher_algo,NULL)!=opt.def_cipher_algo)
516 	log_info(_("WARNING: forcing symmetric cipher %s (%d)"
517 		   " violates recipient preferences\n"),
518 		 cipher_algo_to_string(opt.def_cipher_algo),
519 		 opt.def_cipher_algo);
520 
521       cfx.dek->algo = opt.def_cipher_algo;
522     }
523 
524     cfx.dek->use_mdc=use_mdc(pk_list,cfx.dek->algo);
525 
526     /* Only do the is-file-already-compressed check if we are using a
527        MDC.  This forces compressed files to be re-compressed if we do
528        not have a MDC to give some protection against chosen
529        ciphertext attacks. */
530 
531     if (do_compress && cfx.dek->use_mdc && is_file_compressed(filename, &rc2) )
532       {
533         if (opt.verbose)
534           log_info(_("`%s' already compressed\n"), filename);
535         do_compress = 0;
536       }
537     if (rc2)
538       {
539         rc = rc2;
540         goto leave;
541       }
542 
543     make_session_key( cfx.dek );
544     if( DBG_CIPHER )
545 	log_hexdump("DEK is: ", cfx.dek->key, cfx.dek->keylen );
546 
547     rc = write_pubkey_enc_from_list( pk_list, cfx.dek, out );
548     if( rc  )
549 	goto leave;
550 
551     /* We put the passphrase (if any) after any public keys as this
552        seems to be the most useful on the recipient side - there is no
553        point in prompting a user for a passphrase if they have the
554        secret key needed to decrypt. */
555     if(use_symkey && (rc=write_symkey_enc(symkey_s2k,symkey_dek,cfx.dek,out)))
556       goto leave;
557 
558     if (!opt.no_literal)
559       pt=setup_plaintext_name(filename,inp);
560 
561     if (!iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
562       {
563         off_t tmpsize;
564         int overflow;
565 
566 	if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
567              && !overflow && opt.verbose)
568           log_info(_("WARNING: `%s' is an empty file\n"), filename );
569         /* We can't encode the length of very large files because
570            OpenPGP uses only 32 bit for file sizes.  So if the the
571            size of a file is larger than 2^32 minus some bytes for
572            packet headers, we switch to partial length encoding. */
573         if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
574           filesize = tmpsize;
575         else
576           filesize = 0;
577       }
578     else
579       filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
580 
581     if (!opt.no_literal) {
582 	pt->timestamp = make_timestamp();
583 	pt->mode = opt.textmode ? 't' : 'b';
584 	pt->len = filesize;
585 	pt->new_ctb = !pt->len && !RFC1991;
586 	pt->buf = inp;
587 	pkt.pkttype = PKT_PLAINTEXT;
588 	pkt.pkt.plaintext = pt;
589 	cfx.datalen = filesize && !do_compress? calc_packet_length( &pkt ) : 0;
590     }
591     else
592 	cfx.datalen = filesize && !do_compress ? filesize : 0;
593 
594     /* register the cipher filter */
595     iobuf_push_filter( out, cipher_filter, &cfx );
596 
597     /* register the compress filter */
598     if( do_compress ) {
599 	int compr_algo = opt.compress_algo;
600 
601 	if(compr_algo==-1)
602 	  {
603 	    if((compr_algo=
604 		select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
605 	      compr_algo=DEFAULT_COMPRESS_ALGO;
606 	    /* Theoretically impossible to get here since uncompressed
607 	       is implicit. */
608 	  }
609 	else if(!opt.expert &&
610 		select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
611 				       compr_algo,NULL)!=compr_algo)
612 	  log_info(_("WARNING: forcing compression algorithm %s (%d)"
613 		     " violates recipient preferences\n"),
614 		   compress_algo_to_string(compr_algo),compr_algo);
615 
616 	/* algo 0 means no compression */
617 	if( compr_algo )
618 	  {
619             if (cfx.dek && cfx.dek->use_mdc)
620               zfx.new_ctb = 1;
621 	    push_compress_filter(out,&zfx,compr_algo);
622 	  }
623     }
624 
625     /* do the work */
626     if (!opt.no_literal) {
627 	if( (rc = build_packet( out, &pkt )) )
628 	    log_error("build_packet failed: %s\n", g10_errstr(rc) );
629     }
630     else {
631 	/* user requested not to create a literal packet, so we copy
632            the plain data */
633 	byte copy_buffer[4096];
634 	int  bytes_copied;
635 	while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
636 	    if (iobuf_write(out, copy_buffer, bytes_copied) == -1) {
637 		rc = G10ERR_WRITE_FILE;
638 		log_error("copying input to output failed: %s\n",
639                           g10_errstr(rc) );
640 		break;
641 	    }
642 	wipememory(copy_buffer, 4096); /* burn buffer */
643     }
644 
645     /* finish the stuff */
646   leave:
647     iobuf_close(inp);
648     if( rc )
649 	iobuf_cancel(out);
650     else {
651 	iobuf_close(out); /* fixme: check returncode */
652         write_status( STATUS_END_ENCRYPTION );
653     }
654     if( pt )
655 	pt->buf = NULL;
656     free_packet(&pkt);
657     xfree(cfx.dek);
658     xfree(symkey_dek);
659     xfree(symkey_s2k);
660     release_pk_list( pk_list );
661     return rc;
662 }
663 
664 
665 
666 
667 /****************
668  * Filter to do a complete public key encryption.
669  */
670 int
encrypt_filter(void * opaque,int control,IOBUF a,byte * buf,size_t * ret_len)671 encrypt_filter( void *opaque, int control,
672 	       IOBUF a, byte *buf, size_t *ret_len)
673 {
674     size_t size = *ret_len;
675     encrypt_filter_context_t *efx = opaque;
676     int rc=0;
677 
678     if( control == IOBUFCTRL_UNDERFLOW ) { /* decrypt */
679 	BUG(); /* not used */
680     }
681     else if( control == IOBUFCTRL_FLUSH ) { /* encrypt */
682 	if( !efx->header_okay ) {
683 	    efx->cfx.dek = xmalloc_secure_clear( sizeof *efx->cfx.dek );
684 
685 	    if( !opt.def_cipher_algo  ) { /* try to get it from the prefs */
686 		efx->cfx.dek->algo =
687 		  select_algo_from_prefs(efx->pk_list,PREFTYPE_SYM,-1,NULL);
688 		if( efx->cfx.dek->algo == -1 ) {
689                     /* because 3DES is implicitly in the prefs, this can only
690                      * happen if we do not have any public keys in the list */
691 		    efx->cfx.dek->algo = DEFAULT_CIPHER_ALGO;
692                 }
693 	    }
694 	    else {
695 	      if(!opt.expert &&
696 		 select_algo_from_prefs(efx->pk_list,PREFTYPE_SYM,
697 					opt.def_cipher_algo,
698 					NULL)!=opt.def_cipher_algo)
699 		log_info(_("forcing symmetric cipher %s (%d) "
700 			   "violates recipient preferences\n"),
701 			 cipher_algo_to_string(opt.def_cipher_algo),
702 			 opt.def_cipher_algo);
703 
704 	      efx->cfx.dek->algo = opt.def_cipher_algo;
705 	    }
706 
707             efx->cfx.dek->use_mdc = use_mdc(efx->pk_list,efx->cfx.dek->algo);
708 
709 	    make_session_key( efx->cfx.dek );
710 	    if( DBG_CIPHER )
711 		log_hexdump("DEK is: ",
712 			     efx->cfx.dek->key, efx->cfx.dek->keylen );
713 
714 	    rc = write_pubkey_enc_from_list( efx->pk_list, efx->cfx.dek, a );
715 	    if( rc )
716 		return rc;
717 
718 	    if(efx->symkey_s2k && efx->symkey_dek)
719 	      {
720 		rc=write_symkey_enc(efx->symkey_s2k,efx->symkey_dek,
721 				    efx->cfx.dek,a);
722 		if(rc)
723 		  return rc;
724 	      }
725 
726 	    iobuf_push_filter( a, cipher_filter, &efx->cfx );
727 
728 	    efx->header_okay = 1;
729 	}
730 	rc = iobuf_write( a, buf, size );
731 
732     }
733     else if( control == IOBUFCTRL_FREE )
734       {
735 	xfree(efx->symkey_dek);
736 	xfree(efx->symkey_s2k);
737       }
738     else if( control == IOBUFCTRL_DESC ) {
739         mem2str (buf, "encrypt_filter", *ret_len);
740     }
741     return rc;
742 }
743 
744 
745 /****************
746  * Write pubkey-enc packets from the list of PKs to OUT.
747  */
748 static int
write_pubkey_enc_from_list(PK_LIST pk_list,DEK * dek,IOBUF out)749 write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, IOBUF out )
750 {
751     PACKET pkt;
752     PKT_public_key *pk;
753     PKT_pubkey_enc  *enc;
754     int rc;
755 
756     for( ; pk_list; pk_list = pk_list->next ) {
757 	MPI frame;
758 
759 	pk = pk_list->pk;
760 
761 	print_pubkey_algo_note( pk->pubkey_algo );
762 	enc = xmalloc_clear( sizeof *enc );
763 	enc->pubkey_algo = pk->pubkey_algo;
764 	keyid_from_pk( pk, enc->keyid );
765 	enc->throw_keyid = (opt.throw_keyid || (pk_list->flags&1));
766 
767 	if(opt.throw_keyid && (PGP2 || PGP6 || PGP7 || PGP8))
768 	  {
769 	    log_info(_("you may not use %s while in %s mode\n"),
770 		     "--throw-keyid",compliance_option_string());
771 	    compliance_failure();
772 	  }
773 
774 	/* Okay, what's going on: We have the session key somewhere in
775 	 * the structure DEK and want to encode this session key in
776 	 * an integer value of n bits.	pubkey_nbits gives us the
777 	 * number of bits we have to use.  We then encode the session
778 	 * key in some way and we get it back in the big intger value
779 	 * FRAME.  Then we use FRAME, the public key PK->PKEY and the
780 	 * algorithm number PK->PUBKEY_ALGO and pass it to pubkey_encrypt
781 	 * which returns the encrypted value in the array ENC->DATA.
782 	 * This array has a size which depends on the used algorithm
783 	 * (e.g. 2 for Elgamal).  We don't need frame anymore because we
784 	 * have everything now in enc->data which is the passed to
785 	 * build_packet()
786 	 */
787 	frame = encode_session_key( dek, pubkey_nbits( pk->pubkey_algo,
788 							  pk->pkey ) );
789 	rc = pubkey_encrypt( pk->pubkey_algo, enc->data, frame, pk->pkey );
790 	mpi_free( frame );
791 	if( rc )
792 	    log_error("pubkey_encrypt failed: %s\n", g10_errstr(rc) );
793 	else {
794 	    if( opt.verbose ) {
795 		char *ustr = get_user_id_string_native (enc->keyid);
796 		log_info(_("%s/%s encrypted for: \"%s\"\n"),
797 		    pubkey_algo_to_string(enc->pubkey_algo),
798 		    cipher_algo_to_string(dek->algo), ustr );
799 		xfree(ustr);
800 	    }
801 	    /* and write it */
802 	    init_packet(&pkt);
803 	    pkt.pkttype = PKT_PUBKEY_ENC;
804 	    pkt.pkt.pubkey_enc = enc;
805 	    rc = build_packet( out, &pkt );
806 	    if( rc )
807 	       log_error("build_packet(pubkey_enc) failed: %s\n", g10_errstr(rc));
808 	}
809 	free_pubkey_enc(enc);
810 	if( rc )
811 	    return rc;
812     }
813     return 0;
814 }
815 
816 void
encode_crypt_files(int nfiles,char ** files,STRLIST remusr)817 encode_crypt_files(int nfiles, char **files, STRLIST remusr)
818 {
819   int rc = 0;
820 
821   if (opt.outfile)
822     {
823       log_error(_("--output doesn't work for this command\n"));
824       return;
825     }
826 
827   if (!nfiles)
828     {
829       char line[2048];
830       unsigned int lno = 0;
831       while ( fgets(line, DIM(line), stdin) )
832         {
833           lno++;
834           if (!*line || line[strlen(line)-1] != '\n')
835             {
836               log_error("input line %u too long or missing LF\n", lno);
837               return;
838             }
839           line[strlen(line)-1] = '\0';
840           print_file_status(STATUS_FILE_START, line, 2);
841           if ( (rc = encode_crypt(line, remusr, 0)) )
842             log_error("encryption of `%s' failed: %s\n",
843                       print_fname_stdin(line), g10_errstr(rc) );
844           write_status( STATUS_FILE_DONE );
845           iobuf_ioctl( NULL, 2, 0, NULL); /* Invalidate entire cache. */
846         }
847     }
848   else
849     {
850       while (nfiles--)
851         {
852           print_file_status(STATUS_FILE_START, *files, 2);
853           if ( (rc = encode_crypt(*files, remusr, 0)) )
854             log_error("encryption of `%s' failed: %s\n",
855                       print_fname_stdin(*files), g10_errstr(rc) );
856           write_status( STATUS_FILE_DONE );
857           iobuf_ioctl( NULL, 2, 0, NULL); /* Invalidate entire cache. */
858           files++;
859         }
860     }
861 }
862