~ubuntu-branches/ubuntu/oneiric/gnupg2/oneiric-updates

« back to all changes in this revision

Viewing changes to g10/encode.c

  • Committer: Bazaar Package Importer
  • Author(s): Thomas Viehmann
  • Date: 2008-10-04 10:25:53 UTC
  • mfrom: (5.1.15 intrepid)
  • Revision ID: james.westby@ubuntu.com-20081004102553-fv62pp8dsitxli47
Tags: 2.0.9-3.1
* Non-maintainer upload.
* agent/gpg-agent.c: Deinit the threading library before exec'ing
  the command to run in --daemon mode. And because that still doesn't
  restore the sigprocmask, do that manually. Closes: #499569

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* encode.c - encode data
2
 
 * Copyright (C) 1998, 1999, 2000, 2001, 2002,
3
 
 *               2003 Free Software Foundation, Inc.
 
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
 
3
 *               2006 Free Software Foundation, Inc.
4
4
 *
5
5
 * This file is part of GnuPG.
6
6
 *
7
7
 * GnuPG is free software; you can redistribute it and/or modify
8
8
 * it under the terms of the GNU General Public License as published by
9
 
 * the Free Software Foundation; either version 2 of the License, or
 
9
 * the Free Software Foundation; either version 3 of the License, or
10
10
 * (at your option) any later version.
11
11
 *
12
12
 * GnuPG is distributed in the hope that it will be useful,
15
15
 * GNU General Public License for more details.
16
16
 *
17
17
 * You should have received a copy of the GNU General Public License
18
 
 * along with this program; if not, write to the Free Software
19
 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
18
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20
19
 */
21
20
 
22
21
#include <config.h>
29
28
#include "gpg.h"
30
29
#include "options.h"
31
30
#include "packet.h"
32
 
#include "errors.h"
 
31
#include "status.h"
33
32
#include "iobuf.h"
34
33
#include "keydb.h"
35
 
#include "memory.h"
36
34
#include "util.h"
37
35
#include "main.h"
38
36
#include "filter.h"
42
40
#include "pkglue.h"
43
41
 
44
42
 
45
 
static int encode_simple( const char *filename, int mode, int compat );
46
 
static int write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, iobuf_t out );
47
 
 
48
 
 
 
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 );
49
45
 
50
46
/****************
51
47
 * Encode FILENAME with only the symmetric cipher.  Take input from
54
50
int
55
51
encode_symmetric( const char *filename )
56
52
{
57
 
    int compat = 1;
58
 
 
59
 
#if 0    
60
 
    /* We don't want to use it because older gnupg version can't
61
 
       handle it and we can presume that a lot of scripts are running
62
 
       with the expert mode set.  Some time in the future we might
63
 
       want to allow for it. */
64
 
    if ( opt.expert )
65
 
        compat = 0; /* PGP knows how to handle this mode. */
66
 
#endif
67
 
    return encode_simple( filename, 1, compat );
 
53
    return encode_simple( filename, 1, 0 );
68
54
}
69
55
 
70
56
/****************
74
60
int
75
61
encode_store( const char *filename )
76
62
{
77
 
    return encode_simple( filename, 0, 1 );
 
63
    return encode_simple( filename, 0, 0 );
78
64
}
79
65
 
 
66
 
80
67
static void
81
 
encode_sesskey (DEK * dek, DEK ** ret_dek, byte * enckey)
 
68
encode_seskey( DEK *dek, DEK **seskey, byte *enckey )
82
69
{
83
 
  CIPHER_HANDLE hd;
84
 
  DEK * c;
85
 
  byte buf[33];
86
 
 
87
 
  assert (dek->keylen < 32);
88
 
    
89
 
  c = xcalloc (1, sizeof *c);
90
 
  c->keylen = dek->keylen;
91
 
  c->algo = dek->algo;
92
 
  make_session_key (c);
93
 
  /*log_hexdump ("thekey", c->key, c->keylen);*/
94
 
 
95
 
  /* the encrypted session key is prefixed with a one-octet algorithm id */
96
 
  buf[0] = c->algo;
97
 
  memcpy (buf + 1, c->key, c->keylen);
98
 
    
99
 
  /* due to the fact that we use only checked values, consider each
100
 
     failure as fatal. */
101
 
  if (gcry_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
102
 
    BUG();
103
 
  if (gcry_cipher_setkey (hd, dek->key, dek->keylen))
104
 
    BUG();
105
 
  gcry_cipher_setiv (hd, NULL, 0);
106
 
  gcry_cipher_encrypt (hd, buf, c->keylen + 1, NULL, 0);
107
 
  gcry_cipher_close (hd);
108
 
 
109
 
  memcpy (enckey, buf, c->keylen + 1);
110
 
  wipememory (buf, sizeof buf); /* burn key */
111
 
  *ret_dek = c;
 
70
    gcry_cipher_hd_t hd;
 
71
    byte buf[33];
 
72
 
 
73
    assert ( dek->keylen <= 32 );
 
74
    if(!*seskey)
 
75
      {
 
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 );*/
 
81
      }
 
82
 
 
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 );
 
86
    
 
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);
 
96
 
 
97
    memcpy( enckey, buf, (*seskey)->keylen + 1 );
 
98
    wipememory( buf, sizeof buf ); /* burn key */
112
99
}
113
100
 
114
101
/* We try very hard to use a MDC */
115
102
static int
116
 
use_mdc (PK_LIST pk_list,int algo)
 
103
use_mdc(PK_LIST pk_list,int algo)
117
104
{
118
 
  byte cipher_algid[4] = {
119
 
    CIPHER_ALGO_AES,
120
 
    CIPHER_ALGO_AES192,
121
 
    CIPHER_ALGO_AES256,
122
 
    CIPHER_ALGO_TWOFISH
123
 
  };
124
 
  int i;
125
 
 
126
105
  /* RFC-1991 and 2440 don't have MDC */
127
106
  if(RFC1991 || RFC2440)
128
107
    return 0;
129
 
  
 
108
 
130
109
  /* --force-mdc overrides --disable-mdc */
131
 
  if (opt.force_mdc)
 
110
  if(opt.force_mdc)
132
111
    return 1;
133
112
 
134
 
  if (opt.disable_mdc)
 
113
  if(opt.disable_mdc)
135
114
    return 0;
136
115
 
137
116
  /* Do the keys really support MDC? */
138
117
 
139
 
  if (select_mdc_from_pklist (pk_list))
 
118
  if(select_mdc_from_pklist(pk_list))
140
119
    return 1;
141
120
  
142
121
  /* The keys don't support MDC, so now we do a bit of a hack - if any
144
123
     can handle a MDC.  This is valid for PGP 7, which can handle MDCs
145
124
     though it will not generate them.  2440bis allows this, by the
146
125
     way. */
147
 
  for (i=0; i < DIM (cipher_algid); i++)
148
 
    {
149
 
      if (select_algo_from_prefs (pk_list, PREFTYPE_SYM, cipher_algid[i],
150
 
                                  NULL) == cipher_algid[i])
151
 
        return 1;
152
 
    }
 
126
 
 
127
  if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
 
128
                            CIPHER_ALGO_AES,NULL)==CIPHER_ALGO_AES)
 
129
    return 1;
 
130
 
 
131
  if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
 
132
                            CIPHER_ALGO_AES192,NULL)==CIPHER_ALGO_AES192)
 
133
    return 1;
 
134
 
 
135
  if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
 
136
                            CIPHER_ALGO_AES256,NULL)==CIPHER_ALGO_AES256)
 
137
    return 1;
 
138
 
 
139
  if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
 
140
                            CIPHER_ALGO_TWOFISH,NULL)==CIPHER_ALGO_TWOFISH)
 
141
    return 1;
153
142
 
154
143
  /* Last try.  Use MDC for the modern ciphers. */
 
144
 
155
145
  if (gcry_cipher_get_algo_blklen (algo) != 8)
156
146
    return 1;
157
147
 
 
148
  if (opt.verbose)
 
149
    warn_missing_mdc_from_pklist (pk_list);
 
150
 
158
151
  return 0; /* No MDC */
159
152
}
160
153
 
 
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. */
161
158
static int
162
 
encode_simple( const char *filename, int mode, int compat )
 
159
encode_simple( const char *filename, int mode, int use_seskey )
163
160
{
164
 
    iobuf_t inp, out;
 
161
    IOBUF inp, out;
165
162
    PACKET pkt;
166
 
    DEK *dek = NULL;
167
163
    PKT_plaintext *pt = NULL;
168
164
    STRING2KEY *s2k = NULL;
169
165
    byte enckey[33];
171
167
    int seskeylen = 0;
172
168
    u32 filesize;
173
169
    cipher_filter_context_t cfx;
174
 
    armor_filter_context_t afx;
 
170
    armor_filter_context_t  *afx = NULL;
175
171
    compress_filter_context_t zfx;
176
172
    text_filter_context_t tfx;
177
 
    progress_filter_context_t pfx;
178
 
    int do_compress = opt.compress && !RFC1991;
 
173
    progress_filter_context_t *pfx;
 
174
    int do_compress = !RFC1991 && default_compress_algo();
179
175
 
 
176
    pfx = new_progress_context ();
180
177
    memset( &cfx, 0, sizeof cfx);
181
 
    memset( &afx, 0, sizeof afx);
182
178
    memset( &zfx, 0, sizeof zfx);
183
179
    memset( &tfx, 0, sizeof tfx);
184
180
    init_packet(&pkt);
185
181
    
186
182
    /* prepare iobufs */
187
 
    if( !(inp = iobuf_open(filename)) ) {
188
 
        rc = gpg_error_from_errno (errno);
189
 
        log_error(_("%s: can't open: %s\n"), filename? filename: "[stdin]",
190
 
                                        strerror(errno) );
 
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)))
 
187
      {
 
188
        iobuf_close (inp);
 
189
        inp = NULL;
 
190
        errno = EPERM;
 
191
      }
 
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);
191
197
        return rc;
192
198
    }
193
199
 
194
 
    handle_progress (&pfx, inp, filename);
 
200
    handle_progress (pfx, inp, filename);
195
201
 
196
202
    if( opt.textmode )
197
203
        iobuf_push_filter( inp, text_filter, &tfx );
199
205
    /* Due the the fact that we use don't use an IV to encrypt the
200
206
       session key we can't use the new mode with RFC1991 because
201
207
       it has no S2K salt. RFC1991 always uses simple S2K. */
202
 
    if ( RFC1991 && !compat )
203
 
        compat = 1;
 
208
    if ( RFC1991 && use_seskey )
 
209
        use_seskey = 0;
204
210
    
205
211
    cfx.dek = NULL;
206
212
    if( mode ) {
207
 
        s2k = xcalloc (1, sizeof *s2k );
 
213
        int canceled;
 
214
 
 
215
        s2k = xmalloc_clear( sizeof *s2k );
208
216
        s2k->mode = RFC1991? 0:opt.s2k_mode;
209
 
        s2k->hash_algo = opt.s2k_digest_algo;
 
217
        s2k->hash_algo=S2K_DIGEST_ALGO;
210
218
        cfx.dek = passphrase_to_dek( NULL, 0,
211
219
                                     default_cipher_algo(), s2k, 2,
212
 
                                     NULL, NULL);
 
220
                                     NULL, &canceled);
213
221
        if( !cfx.dek || !cfx.dek->keylen ) {
214
 
            rc = gpg_error (GPG_ERR_INV_PASSPHRASE);
215
 
            xfree (cfx.dek);
216
 
            xfree (s2k);
 
222
            rc = gpg_error (canceled? GPG_ERR_CANCELED:GPG_ERR_INV_PASSPHRASE);
 
223
            xfree(cfx.dek);
 
224
            xfree(s2k);
217
225
            iobuf_close(inp);
218
 
            log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
 
226
            log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc));
 
227
            release_progress_context (pfx);
219
228
            return rc;
220
229
        }
221
 
        if (!compat && s2k->mode != 1 && s2k->mode != 3) {
222
 
            compat = 1;
 
230
        if (use_seskey && s2k->mode != 1 && s2k->mode != 3) {
 
231
            use_seskey = 0;
223
232
            log_info (_("can't use a symmetric ESK packet "
224
233
                        "due to the S2K mode\n"));
225
234
        }
226
235
 
227
 
        if ( !compat ) {            
228
 
            seskeylen = gcry_cipher_get_algo_keylen (default_cipher_algo());
229
 
            encode_sesskey( cfx.dek, &dek, enckey );
230
 
            xfree (cfx.dek); cfx.dek = dek;
231
 
        }
 
236
        if ( use_seskey )
 
237
          {
 
238
            DEK *dek = NULL;
 
239
 
 
240
            seskeylen = gcry_cipher_get_algo_keylen (default_cipher_algo ());
 
241
            encode_seskey( cfx.dek, &dek, enckey );
 
242
            xfree( cfx.dek ); cfx.dek = dek;
 
243
          }
 
244
 
 
245
        if(opt.verbose)
 
246
          log_info(_("using cipher %s\n"),
 
247
                   openpgp_cipher_algo_name (cfx.dek->algo));
232
248
 
233
249
        cfx.dek->use_mdc=use_mdc(NULL,cfx.dek->algo);
234
250
    }
235
251
 
236
 
    if (opt.compress == -1 && cfx.dek && cfx.dek->use_mdc &&
237
 
        is_file_compressed(filename, &rc))
 
252
    if (do_compress && cfx.dek && cfx.dek->use_mdc
 
253
        && is_file_compressed(filename, &rc))
238
254
      {
239
255
        if (opt.verbose)
240
256
          log_info(_("`%s' already compressed\n"), filename);
243
259
 
244
260
    if( rc || (rc = open_outfile( filename, opt.armor? 1:0, &out )) ) {
245
261
        iobuf_cancel(inp);
246
 
        xfree (cfx.dek);
247
 
        xfree (s2k);
 
262
        xfree(cfx.dek);
 
263
        xfree(s2k);
 
264
        release_progress_context (pfx);
248
265
        return rc;
249
266
    }
250
267
 
251
 
    if( opt.armor )
252
 
        iobuf_push_filter( out, armor_filter, &afx );
253
 
#ifdef ENABLE_COMMENT_PACKETS
254
 
    else {
255
 
        write_comment( out, "#created by GNUPG v" VERSION " ("
256
 
                                            PRINTABLE_OS_NAME ")");
257
 
        if( opt.comment_string )
258
 
            write_comment( out, opt.comment_string );
259
 
    }
260
 
#endif
 
268
    if ( opt.armor )
 
269
      {
 
270
        afx = new_armor_context ();
 
271
        push_armor_filter (afx, out);
 
272
      }
 
273
 
261
274
    if( s2k && !RFC1991 ) {
262
 
        PKT_symkey_enc *enc = xcalloc (1, sizeof *enc + seskeylen + 1 );
 
275
        PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc + seskeylen + 1 );
263
276
        enc->version = 4;
264
277
        enc->cipher_algo = cfx.dek->algo;
265
278
        enc->s2k = *s2k;
266
 
        if ( !compat && seskeylen ) {
 
279
        if ( use_seskey && seskeylen ) {
267
280
            enc->seskeylen = seskeylen + 1; /* algo id */
268
281
            memcpy( enc->seskey, enckey, seskeylen + 1 );
269
282
        }
270
283
        pkt.pkttype = PKT_SYMKEY_ENC;
271
284
        pkt.pkt.symkey_enc = enc;
272
285
        if( (rc = build_packet( out, &pkt )) )
273
 
            log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
274
 
        xfree (enc);
 
286
            log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
 
287
        xfree(enc);
275
288
    }
276
289
 
277
 
    if (!opt.no_literal) {
278
 
        /* setup the inner packet */
279
 
        if( filename || opt.set_filename ) {
280
 
            char *s = make_basename ( opt.set_filename ? opt.set_filename
281
 
                                                      : filename
282
 
                                      /* for riscos?
283
 
                                         .iobuf_get_real_fname( inp ) */
284
 
                                      );
285
 
            pt = xmalloc ( sizeof *pt + strlen(s) - 1 );
286
 
            pt->namelen = strlen(s);
287
 
            memcpy(pt->name, s, pt->namelen );
288
 
            xfree (s);
289
 
        }
290
 
        else { /* no filename */
291
 
            pt = xmalloc ( sizeof *pt - 1 );
292
 
            pt->namelen = 0;
293
 
        }
294
 
    }
 
290
    if (!opt.no_literal)
 
291
      pt=setup_plaintext_name(filename,inp);
295
292
 
296
293
    /* Note that PGP 5 has problems decrypting symmetrically encrypted
297
294
       data if the file length is in the inner packet. It works when
304
301
       either partial length or fixed length with the new style
305
302
       messages. */
306
303
 
307
 
    if (filename && *filename && !(*filename == '-' && !filename[1])
308
 
        && !opt.textmode ) {
 
304
    if ( !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
 
305
      {
309
306
        off_t tmpsize;
 
307
        int overflow;
310
308
 
311
 
        if ( !(tmpsize = iobuf_get_filelength(inp)) )
312
 
          log_info(_("%s: WARNING: empty file\n"), filename );
 
309
        if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
 
310
             && !overflow )
 
311
          log_info(_("WARNING: `%s' is an empty file\n"), filename );
313
312
        /* We can't encode the length of very large files because
314
313
           OpenPGP uses only 32 bit for file sizes.  So if the the
315
314
           size of a file is larger than 2^32 minus some bytes for
318
317
          filesize = tmpsize;
319
318
        else
320
319
          filesize = 0;
321
 
    }
 
320
      }
322
321
    else
323
 
        filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
 
322
      filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
324
323
 
325
324
    if (!opt.no_literal) {
326
325
        pt->timestamp = make_timestamp();
347
346
      {
348
347
        if (cfx.dek && cfx.dek->use_mdc)
349
348
          zfx.new_ctb = 1;
350
 
        zfx.algo=default_compress_algo();
351
 
        iobuf_push_filter( out, compress_filter, &zfx );
 
349
        push_compress_filter(out,&zfx,default_compress_algo());
352
350
      }
353
351
 
354
352
    /* do the work */
355
353
    if (!opt.no_literal) {
356
354
        if( (rc = build_packet( out, &pkt )) )
357
 
            log_error("build_packet failed: %s\n", gpg_strerror (rc) );
 
355
            log_error("build_packet failed: %s\n", g10_errstr(rc) );
358
356
    }
359
357
    else {
360
358
        /* user requested not to create a literal packet,
362
360
        byte copy_buffer[4096];
363
361
        int  bytes_copied;
364
362
        while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
365
 
            if ( (rc=iobuf_write(out, copy_buffer, bytes_copied))) {
366
 
                log_error("copying input to output failed: %s\n", gpg_strerror (rc) );
 
363
            if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
 
364
                log_error ("copying input to output failed: %s\n",
 
365
                           gpg_strerror (rc) );
367
366
                break;
368
367
            }
369
368
        wipememory(copy_buffer, 4096); /* burn buffer */
381
380
    if (pt)
382
381
        pt->buf = NULL;
383
382
    free_packet(&pkt);
384
 
    xfree (cfx.dek);
385
 
    xfree (s2k);
 
383
    xfree(cfx.dek);
 
384
    xfree(s2k);
 
385
    release_armor_context (afx);
 
386
    release_progress_context (pfx);
386
387
    return rc;
387
388
}
388
389
 
 
390
int
 
391
setup_symkey(STRING2KEY **symkey_s2k,DEK **symkey_dek)
 
392
{
 
393
  int canceled;
 
394
 
 
395
  *symkey_s2k=xmalloc_clear(sizeof(STRING2KEY));
 
396
  (*symkey_s2k)->mode = opt.s2k_mode;
 
397
  (*symkey_s2k)->hash_algo = S2K_DIGEST_ALGO;
 
398
 
 
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)
 
402
    {
 
403
      xfree(*symkey_dek);
 
404
      xfree(*symkey_s2k);
 
405
      return gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
 
406
    }
 
407
 
 
408
  return 0;
 
409
}
 
410
 
 
411
static int
 
412
write_symkey_enc(STRING2KEY *symkey_s2k,DEK *symkey_dek,DEK *dek,IOBUF out)
 
413
{
 
414
  int rc, seskeylen = gcry_cipher_get_algo_keylen (dek->algo);
 
415
 
 
416
  PKT_symkey_enc *enc;
 
417
  byte enckey[33];
 
418
  PACKET pkt;
 
419
 
 
420
  enc=xmalloc_clear(sizeof(PKT_symkey_enc)+seskeylen+1);
 
421
  encode_seskey(symkey_dek,&dek,enckey);
 
422
 
 
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 );
 
428
 
 
429
  pkt.pkttype = PKT_SYMKEY_ENC;
 
430
  pkt.pkt.symkey_enc = enc;
 
431
 
 
432
  if((rc=build_packet(out,&pkt)))
 
433
    log_error("build symkey_enc packet failed: %s\n",g10_errstr(rc));
 
434
 
 
435
  xfree(enc);
 
436
  return rc;
 
437
}
 
438
 
389
439
/****************
390
440
 * Encrypt the file with the given userids (or ask if none
391
441
 * is supplied).
392
442
 */
393
443
int
394
 
encode_crypt( const char *filename, STRLIST remusr )
 
444
encode_crypt( const char *filename, strlist_t remusr, int use_symkey )
395
445
{
396
 
    iobuf_t inp = NULL, out = NULL;
 
446
    IOBUF inp = NULL, out = NULL;
397
447
    PACKET pkt;
398
448
    PKT_plaintext *pt = NULL;
 
449
    DEK *symkey_dek = NULL;
 
450
    STRING2KEY *symkey_s2k = NULL;
399
451
    int rc = 0, rc2 = 0;
400
452
    u32 filesize;
401
453
    cipher_filter_context_t cfx;
402
 
    armor_filter_context_t afx;
 
454
    armor_filter_context_t *afx = NULL;
403
455
    compress_filter_context_t zfx;
404
456
    text_filter_context_t tfx;
405
 
    progress_filter_context_t pfx;
 
457
    progress_filter_context_t *pfx;
406
458
    PK_LIST pk_list,work_list;
407
 
    int do_compress = opt.compress && !RFC1991;
408
 
 
409
 
 
 
459
    int do_compress = opt.compress_algo && !RFC1991;
 
460
 
 
461
    pfx = new_progress_context ();
410
462
    memset( &cfx, 0, sizeof cfx);
411
 
    memset( &afx, 0, sizeof afx);
412
463
    memset( &zfx, 0, sizeof zfx);
413
464
    memset( &tfx, 0, sizeof tfx);
414
465
    init_packet(&pkt);
415
466
 
 
467
    if(use_symkey
 
468
       && (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
 
469
      {
 
470
        release_progress_context (pfx);
 
471
        return rc;
 
472
      }
 
473
 
416
474
    if( (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC)) )
 
475
      {
 
476
        release_progress_context (pfx);
417
477
        return rc;
 
478
      }
418
479
 
419
480
    if(PGP2) {
420
481
      for(work_list=pk_list; work_list; work_list=work_list->next)
429
490
    }
430
491
 
431
492
    /* prepare iobufs */
432
 
    if( !(inp = iobuf_open(filename)) ) {
433
 
        rc = gpg_error_from_errno (errno);
434
 
        log_error(_("can't open %s: %s\n"), filename? filename: "[stdin]",
435
 
                                        strerror(errno) );
 
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)))
 
497
      {
 
498
        iobuf_close (inp);
 
499
        inp = NULL;
 
500
        errno = EPERM;
 
501
      }
 
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) );
436
507
        goto leave;
437
508
    }
438
509
    else if( opt.verbose )
439
510
        log_info(_("reading from `%s'\n"), filename? filename: "[stdin]");
440
511
 
441
 
    handle_progress (&pfx, inp, filename);
 
512
    handle_progress (pfx, inp, filename);
442
513
 
443
514
    if( opt.textmode )
444
515
        iobuf_push_filter( inp, text_filter, &tfx );
446
517
    if( (rc = open_outfile( filename, opt.armor? 1:0, &out )) )
447
518
        goto leave;
448
519
 
 
520
    if ( opt.armor )
 
521
      {
 
522
        afx = new_armor_context ();
 
523
        push_armor_filter (afx, out);
 
524
      }
449
525
 
450
 
    if( opt.armor )
451
 
        iobuf_push_filter( out, armor_filter, &afx );
452
 
#ifdef ENABLE_COMMENT_PACKETS
453
 
    else {
454
 
        write_comment( out, "#created by GNUPG v" VERSION " ("
455
 
                                            PRINTABLE_OS_NAME ")");
456
 
        if( opt.comment_string )
457
 
            write_comment( out, opt.comment_string );
458
 
    }
459
 
#endif
460
526
    /* create a session key */
461
 
    cfx.dek = xcalloc_secure (1, sizeof *cfx.dek);
 
527
    cfx.dek = xmalloc_secure_clear (sizeof *cfx.dek);
462
528
    if( !opt.def_cipher_algo ) { /* try to get it from the prefs */
463
529
        cfx.dek->algo = select_algo_from_prefs(pk_list,PREFTYPE_SYM,-1,NULL);
464
530
        /* The only way select_algo_from_prefs can fail here is when
477
543
              compliance_failure();
478
544
            }
479
545
        }
 
546
 
 
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);
480
554
    }
481
555
    else {
482
556
      if(!opt.expert &&
483
557
         select_algo_from_prefs(pk_list,PREFTYPE_SYM,
484
558
                                opt.def_cipher_algo,NULL)!=opt.def_cipher_algo)
485
 
        log_info(_("forcing symmetric cipher %s (%d) "
486
 
                   "violates recipient preferences\n"),
487
 
                 gcry_cipher_algo_name (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),
488
562
                 opt.def_cipher_algo);
489
563
 
490
564
      cfx.dek->algo = opt.def_cipher_algo;
491
565
    }
492
 
 
 
566
    
493
567
    cfx.dek->use_mdc=use_mdc(pk_list,cfx.dek->algo);
494
568
 
495
569
    /* Only do the is-file-already-compressed check if we are using a
497
571
       not have a MDC to give some protection against chosen
498
572
       ciphertext attacks. */
499
573
 
500
 
    if (opt.compress == -1 && cfx.dek->use_mdc &&
501
 
        is_file_compressed(filename, &rc2) )
 
574
    if (do_compress && cfx.dek->use_mdc && is_file_compressed(filename, &rc2) )
502
575
      {
503
576
        if (opt.verbose)
504
577
          log_info(_("`%s' already compressed\n"), filename);
518
591
    if( rc  )
519
592
        goto leave;
520
593
 
521
 
    if (!opt.no_literal) {
522
 
        /* setup the inner packet */
523
 
        if( filename || opt.set_filename ) {
524
 
            char *s = make_basename( opt.set_filename ? opt.set_filename
525
 
                                                      : filename
526
 
                                     /* ,iobuf_get_real_fname( inp )*/ );
527
 
            pt = xmalloc ( sizeof *pt + strlen(s) - 1 );
528
 
            pt->namelen = strlen(s);
529
 
            memcpy(pt->name, s, pt->namelen );
530
 
            xfree (s);
531
 
        }
532
 
        else { /* no filename */
533
 
            pt = xmalloc ( sizeof *pt - 1 );
534
 
            pt->namelen = 0;
535
 
        }
536
 
    }
537
 
 
538
 
    if (filename && *filename && !(*filename == '-' && !filename[1])
539
 
        && !opt.textmode ) {
 
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;
 
600
 
 
601
    if (!opt.no_literal)
 
602
      pt=setup_plaintext_name(filename,inp);
 
603
 
 
604
    if (!iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
 
605
      {
540
606
        off_t tmpsize;
 
607
        int overflow;
541
608
 
542
 
        if ( !(tmpsize = iobuf_get_filelength(inp)) )
543
 
          log_info(_("%s: WARNING: empty file\n"), filename );
 
609
        if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
 
610
             && !overflow )
 
611
          log_info(_("WARNING: `%s' is an empty file\n"), filename );
544
612
        /* We can't encode the length of very large files because
545
613
           OpenPGP uses only 32 bit for file sizes.  So if the the
546
614
           size of a file is larger than 2^32 minus some bytes for
547
615
           packet headers, we switch to partial length encoding. */
548
 
        if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
 
616
        if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
549
617
          filesize = tmpsize;
550
618
        else
551
619
          filesize = 0;
552
 
    }
 
620
      }
553
621
    else
554
 
        filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
 
622
      filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
555
623
 
556
624
    if (!opt.no_literal) {
557
625
        pt->timestamp = make_timestamp();
571
639
 
572
640
    /* register the compress filter */
573
641
    if( do_compress ) {
574
 
        int compr_algo = opt.def_compress_algo;
 
642
        int compr_algo = opt.compress_algo;
575
643
 
576
644
        if(compr_algo==-1)
577
645
          {
584
652
        else if(!opt.expert &&
585
653
                select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
586
654
                                       compr_algo,NULL)!=compr_algo)
587
 
          log_info(_("forcing compression algorithm %s (%d) "
588
 
                     "violates recipient preferences\n"),
 
655
          log_info(_("WARNING: forcing compression algorithm %s (%d)"
 
656
                     " violates recipient preferences\n"),
589
657
                   compress_algo_to_string(compr_algo),compr_algo);
590
658
 
591
659
        /* algo 0 means no compression */
593
661
          {
594
662
            if (cfx.dek && cfx.dek->use_mdc)
595
663
              zfx.new_ctb = 1;
596
 
            zfx.algo = compr_algo;
597
 
            iobuf_push_filter( out, compress_filter, &zfx );
 
664
            push_compress_filter(out,&zfx,compr_algo);
598
665
          }
599
666
    }
600
667
 
601
668
    /* do the work */
602
669
    if (!opt.no_literal) {
603
670
        if( (rc = build_packet( out, &pkt )) )
604
 
            log_error("build_packet failed: %s\n", gpg_strerror (rc) );
 
671
            log_error("build_packet failed: %s\n", g10_errstr(rc) );
605
672
    }
606
673
    else {
607
674
        /* user requested not to create a literal packet, so we copy
609
676
        byte copy_buffer[4096];
610
677
        int  bytes_copied;
611
678
        while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
612
 
            if ((rc=iobuf_write(out, copy_buffer, bytes_copied))) {
613
 
                log_error("copying input to output failed: %s\n",
614
 
                          gpg_strerror (rc) );
 
679
            if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
 
680
                log_error ("copying input to output failed: %s\n",
 
681
                           gpg_strerror (rc));
615
682
                break;
616
683
            }
617
684
        wipememory(copy_buffer, 4096); /* burn buffer */
629
696
    if( pt )
630
697
        pt->buf = NULL;
631
698
    free_packet(&pkt);
632
 
    xfree (cfx.dek);
 
699
    xfree(cfx.dek);
 
700
    xfree(symkey_dek);
 
701
    xfree(symkey_s2k);
633
702
    release_pk_list( pk_list );
 
703
    release_armor_context (afx);
 
704
    release_progress_context (pfx);
634
705
    return rc;
635
706
}
636
707
 
642
713
 */
643
714
int
644
715
encrypt_filter( void *opaque, int control,
645
 
               iobuf_t a, byte *buf, size_t *ret_len)
 
716
               IOBUF a, byte *buf, size_t *ret_len)
646
717
{
647
718
    size_t size = *ret_len;
648
719
    encrypt_filter_context_t *efx = opaque;
653
724
    }
654
725
    else if( control == IOBUFCTRL_FLUSH ) { /* encrypt */
655
726
        if( !efx->header_okay ) {
656
 
            efx->cfx.dek = xcalloc_secure (1, sizeof *efx->cfx.dek );
 
727
            efx->cfx.dek = xmalloc_secure_clear( sizeof *efx->cfx.dek );
657
728
 
658
729
            if( !opt.def_cipher_algo  ) { /* try to get it from the prefs */
659
730
                efx->cfx.dek->algo =
663
734
                     * happen if we do not have any public keys in the list */
664
735
                    efx->cfx.dek->algo = DEFAULT_CIPHER_ALGO;
665
736
                }
 
737
 
 
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);
666
745
            }
667
746
            else {
668
747
              if(!opt.expert &&
671
750
                                        NULL)!=opt.def_cipher_algo)
672
751
                log_info(_("forcing symmetric cipher %s (%d) "
673
752
                           "violates recipient preferences\n"),
674
 
                         gcry_cipher_algo_name (opt.def_cipher_algo),
 
753
                         openpgp_cipher_algo_name (opt.def_cipher_algo),
675
754
                         opt.def_cipher_algo);
676
755
 
677
756
              efx->cfx.dek->algo = opt.def_cipher_algo;
688
767
            if( rc )
689
768
                return rc;
690
769
 
 
770
            if(efx->symkey_s2k && efx->symkey_dek)
 
771
              {
 
772
                rc=write_symkey_enc(efx->symkey_s2k,efx->symkey_dek,
 
773
                                    efx->cfx.dek,a);
 
774
                if(rc)
 
775
                  return rc;
 
776
              }
 
777
 
691
778
            iobuf_push_filter( a, cipher_filter, &efx->cfx );
692
779
 
693
780
            efx->header_okay = 1;
695
782
        rc = iobuf_write( a, buf, size );
696
783
 
697
784
    }
698
 
    else if( control == IOBUFCTRL_FREE ) {
699
 
    }
 
785
    else if( control == IOBUFCTRL_FREE )
 
786
      {
 
787
        xfree(efx->symkey_dek);
 
788
        xfree(efx->symkey_s2k);
 
789
      }
700
790
    else if( control == IOBUFCTRL_DESC ) {
701
791
        *(char**)buf = "encrypt_filter";
702
792
    }
708
798
 * Write pubkey-enc packets from the list of PKs to OUT.
709
799
 */
710
800
static int
711
 
write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, iobuf_t out )
 
801
write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, IOBUF out )
712
802
{
713
803
    PACKET pkt;
714
804
    PKT_public_key *pk;
721
811
        pk = pk_list->pk;
722
812
 
723
813
        print_pubkey_algo_note( pk->pubkey_algo );
724
 
        enc = xcalloc (1, sizeof *enc );
 
814
        enc = xmalloc_clear( sizeof *enc );
725
815
        enc->pubkey_algo = pk->pubkey_algo;
726
816
        keyid_from_pk( pk, enc->keyid );
727
817
        enc->throw_keyid = (opt.throw_keyid || (pk_list->flags&1));
742
832
         * algorithm number PK->PUBKEY_ALGO and pass it to pubkey_encrypt
743
833
         * which returns the encrypted value in the array ENC->DATA.
744
834
         * This array has a size which depends on the used algorithm
745
 
         * (e.g. 2 for ElGamal).  We don't need frame anymore because we
 
835
         * (e.g. 2 for Elgamal).  We don't need frame anymore because we
746
836
         * have everything now in enc->data which is the passed to
747
837
         * build_packet()
748
838
         */
749
 
        frame = encode_session_key( dek, pubkey_nbits( pk->pubkey_algo,
750
 
                                                          pk->pkey ) );
751
 
        rc = pk_encrypt( pk->pubkey_algo, enc->data, frame, pk->pkey );
752
 
        gcry_mpi_release ( frame );
 
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);
753
843
        if( rc )
754
 
            log_error("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
 
844
            log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
755
845
        else {
756
846
            if( opt.verbose ) {
757
 
                char *ustr = get_user_id_string_printable (enc->keyid);
 
847
                char *ustr = get_user_id_string_native (enc->keyid);
758
848
                log_info(_("%s/%s encrypted for: \"%s\"\n"),
759
 
                    gcry_pk_algo_name (enc->pubkey_algo),
760
 
                    gcry_cipher_algo_name (dek->algo), ustr );
761
 
                xfree (ustr);
 
849
                         gcry_pk_algo_name (enc->pubkey_algo),
 
850
                         openpgp_cipher_algo_name (dek->algo),
 
851
                         ustr );
 
852
                xfree(ustr);
762
853
            }
763
854
            /* and write it */
764
855
            init_packet(&pkt);
766
857
            pkt.pkt.pubkey_enc = enc;
767
858
            rc = build_packet( out, &pkt );
768
859
            if( rc )
769
 
               log_error("build_packet(pubkey_enc) failed: %s\n", gpg_strerror (rc));
 
860
               log_error("build_packet(pubkey_enc) failed: %s\n", g10_errstr(rc));
770
861
        }
771
862
        free_pubkey_enc(enc);
772
863
        if( rc )
776
867
}
777
868
 
778
869
void
779
 
encode_crypt_files(int nfiles, char **files, STRLIST remusr)
 
870
encode_crypt_files(int nfiles, char **files, strlist_t remusr)
780
871
{
781
872
  int rc = 0;
782
873
 
800
891
            }
801
892
          line[strlen(line)-1] = '\0';
802
893
          print_file_status(STATUS_FILE_START, line, 2);
803
 
          if ( (rc = encode_crypt(line, remusr)) )
804
 
            log_error("%s: encryption failed: %s\n",
805
 
                      print_fname_stdin(line), gpg_strerror (rc) );
 
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) );
806
897
          write_status( STATUS_FILE_DONE );
807
898
        }
808
899
    }
811
902
      while (nfiles--)
812
903
        {
813
904
          print_file_status(STATUS_FILE_START, *files, 2);
814
 
          if ( (rc = encode_crypt(*files, remusr)) )
815
 
            log_error("%s: encryption failed: %s\n",
816
 
                      print_fname_stdin(*files), gpg_strerror (rc) );
 
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) );
817
908
          write_status( STATUS_FILE_DONE );
818
909
          files++;
819
910
        }