~ubuntu-branches/ubuntu/jaunty/gnupg2/jaunty

« back to all changes in this revision

Viewing changes to g10/sign.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Mueller
  • Date: 2005-03-29 10:30:32 UTC
  • Revision ID: james.westby@ubuntu.com-20050329103032-sj42n2ain3ipx310
Tags: upstream-1.9.15
ImportĀ upstreamĀ versionĀ 1.9.15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* sign.c - sign data
 
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002,
 
3
 *               2003 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 2 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, write to the Free Software
 
19
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
20
 */
 
21
 
 
22
#include <config.h>
 
23
#include <stdio.h>
 
24
#include <stdlib.h>
 
25
#include <string.h>
 
26
#include <errno.h>
 
27
#include <assert.h>
 
28
#include <unistd.h> /* need sleep() */
 
29
 
 
30
#include "options.h"
 
31
#include "packet.h"
 
32
#include "errors.h"
 
33
#include "iobuf.h"
 
34
#include "keydb.h"
 
35
#include "memory.h"
 
36
#include "util.h"
 
37
#include "main.h"
 
38
#include "filter.h"
 
39
#include "ttyio.h"
 
40
#include "trustdb.h"
 
41
#include "status.h"
 
42
#include "i18n.h"
 
43
#include "pkglue.h"
 
44
#include "call-agent.h"
 
45
 
 
46
 
 
47
#ifdef HAVE_DOSISH_SYSTEM
 
48
#define LF "\r\n"
 
49
void __stdcall Sleep(ulong);
 
50
#define sleep(a)  Sleep((a)*1000)
 
51
#else
 
52
#define LF "\n"
 
53
#endif
 
54
 
 
55
static int recipient_digest_algo=0;
 
56
 
 
57
/****************
 
58
 * Create a notation.  We assume thIt is assumed that the strings in
 
59
 * the STRLISTs of the opt struct are already checked to contain only
 
60
 * printable data and have a valid NAME=VALUE format.
 
61
 */
 
62
static void
 
63
mk_notation_policy_etc( PKT_signature *sig,
 
64
                        PKT_public_key *pk, PKT_secret_key *sk )
 
65
{
 
66
    const char *string;
 
67
    char *s=NULL;
 
68
    byte *buf;
 
69
    unsigned n1, n2;
 
70
    STRLIST nd=NULL,pu=NULL;
 
71
    struct expando_args args;
 
72
 
 
73
    memset(&args,0,sizeof(args));
 
74
    args.pk=pk;
 
75
    args.sk=sk;
 
76
 
 
77
    /* It is actually impossible to get here when making a v3 key
 
78
       signature since keyedit.c:sign_uids will automatically bump a
 
79
       signature with a notation or policy url up to v4, but it is
 
80
       good to do these checks anyway. */
 
81
 
 
82
    /* notation data */
 
83
    if(IS_SIG(sig) && opt.sig_notation_data)
 
84
      {
 
85
        if(sig->version<4)
 
86
          log_error(_("can't put notation data into v3 (PGP 2.x style) "
 
87
                      "signatures\n"));
 
88
        else
 
89
          nd=opt.sig_notation_data;
 
90
      }
 
91
    else if( IS_CERT(sig) && opt.cert_notation_data )
 
92
      {
 
93
        if(sig->version<4)
 
94
          log_error(_("can't put notation data into v3 (PGP 2.x style) "
 
95
                      "key signatures\n"));
 
96
        else
 
97
          nd=opt.cert_notation_data;
 
98
      }
 
99
 
 
100
    for( ; nd; nd = nd->next ) {
 
101
        char *expanded;
 
102
 
 
103
        string = nd->d;
 
104
        s = strchr( string, '=' );
 
105
        if( !s )
 
106
          BUG(); /* we have already parsed this */
 
107
        n1 = s - string;
 
108
        s++;
 
109
 
 
110
        expanded=pct_expando(s,&args);
 
111
        if(!expanded)
 
112
          {
 
113
            log_error(_("WARNING: unable to %%-expand notation "
 
114
                        "(too large).  Using unexpanded.\n"));
 
115
            expanded=xstrdup (s);
 
116
          }
 
117
 
 
118
        n2 = strlen(expanded);
 
119
        buf = xmalloc ( 8 + n1 + n2 );
 
120
        buf[0] = 0x80; /* human readable */
 
121
        buf[1] = buf[2] = buf[3] = 0;
 
122
        buf[4] = n1 >> 8;
 
123
        buf[5] = n1;
 
124
        buf[6] = n2 >> 8;
 
125
        buf[7] = n2;
 
126
        memcpy(buf+8, string, n1 );
 
127
        memcpy(buf+8+n1, expanded, n2 );
 
128
        build_sig_subpkt( sig, SIGSUBPKT_NOTATION
 
129
                          | ((nd->flags & 1)? SIGSUBPKT_FLAG_CRITICAL:0),
 
130
                          buf, 8+n1+n2 );
 
131
        xfree (expanded);
 
132
        xfree (buf);
 
133
    }
 
134
 
 
135
    /* set policy URL */
 
136
    if( IS_SIG(sig) && opt.sig_policy_url )
 
137
      {
 
138
        if(sig->version<4)
 
139
          log_error(_("can't put a policy URL into v3 (PGP 2.x style) "
 
140
                      "signatures\n"));
 
141
        else
 
142
          pu=opt.sig_policy_url;
 
143
      }
 
144
    else if( IS_CERT(sig) && opt.cert_policy_url )
 
145
      {
 
146
        if(sig->version<4)
 
147
          log_error(_("can't put a policy URL into v3 key (PGP 2.x style) "
 
148
                      "signatures\n"));
 
149
        else
 
150
          pu=opt.cert_policy_url;
 
151
      }
 
152
 
 
153
    for(;pu;pu=pu->next)
 
154
      {
 
155
        string = pu->d;
 
156
 
 
157
        s=pct_expando(string,&args);
 
158
        if(!s)
 
159
          {
 
160
            log_error(_("WARNING: unable to %%-expand policy url "
 
161
                        "(too large).  Using unexpanded.\n"));
 
162
            s=xstrdup (string);
 
163
          }
 
164
 
 
165
        build_sig_subpkt(sig,SIGSUBPKT_POLICY|
 
166
                         ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
 
167
                         s,strlen(s));
 
168
 
 
169
        xfree (s);
 
170
      }
 
171
 
 
172
    /* preferred keyserver URL */
 
173
    if( IS_SIG(sig) && opt.sig_keyserver_url )
 
174
      {
 
175
        if(sig->version<4)
 
176
          log_info (_("can't put a preferred keyserver URL "
 
177
                      "into v3 signatures\n"));
 
178
        else
 
179
          pu=opt.sig_keyserver_url;
 
180
      }
 
181
 
 
182
    for(;pu;pu=pu->next)
 
183
      {
 
184
        string = pu->d;
 
185
 
 
186
        s=pct_expando(string,&args);
 
187
        if(!s)
 
188
          {
 
189
            log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
 
190
                        " (too large).  Using unexpanded.\n"));
 
191
            s=xstrdup(string);
 
192
          }
 
193
 
 
194
        build_sig_subpkt(sig,SIGSUBPKT_PREF_KS|
 
195
                         ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
 
196
                         s,strlen(s));
 
197
 
 
198
        xfree(s);
 
199
      }
 
200
}
 
201
 
 
202
 
 
203
/*
 
204
 * Helper to hash a user ID packet.  
 
205
 */
 
206
static void
 
207
hash_uid (MD_HANDLE md, int sigversion, const PKT_user_id *uid)
 
208
{
 
209
    if ( sigversion >= 4 ) {
 
210
        byte buf[5];
 
211
 
 
212
        if(uid->attrib_data) {
 
213
          buf[0] = 0xd1;                   /* indicates an attribute packet */
 
214
          buf[1] = uid->attrib_len >> 24;  /* always use 4 length bytes */
 
215
          buf[2] = uid->attrib_len >> 16;
 
216
          buf[3] = uid->attrib_len >>  8;
 
217
          buf[4] = uid->attrib_len;
 
218
        }
 
219
        else {
 
220
          buf[0] = 0xb4;            /* indicates a userid packet */
 
221
          buf[1] = uid->len >> 24;  /* always use 4 length bytes */
 
222
          buf[2] = uid->len >> 16;
 
223
          buf[3] = uid->len >>  8;
 
224
          buf[4] = uid->len;
 
225
        }
 
226
        gcry_md_write( md, buf, 5 );
 
227
    }
 
228
 
 
229
    if(uid->attrib_data)
 
230
      gcry_md_write (md, uid->attrib_data, uid->attrib_len );
 
231
    else
 
232
      gcry_md_write (md, uid->name, uid->len );
 
233
}
 
234
 
 
235
 
 
236
/*
 
237
 * Helper to hash some parts from the signature
 
238
 */
 
239
static void
 
240
hash_sigversion_to_magic (MD_HANDLE md, const PKT_signature *sig)
 
241
{
 
242
    if (sig->version >= 4) 
 
243
        gcry_md_putc (md, sig->version);
 
244
    gcry_md_putc (md, sig->sig_class);
 
245
    if (sig->version < 4) {
 
246
        u32 a = sig->timestamp;
 
247
        gcry_md_putc (md, (a >> 24) & 0xff );
 
248
        gcry_md_putc (md, (a >> 16) & 0xff );
 
249
        gcry_md_putc (md, (a >>  8) & 0xff );
 
250
        gcry_md_putc (md,  a           & 0xff );
 
251
    }
 
252
    else {
 
253
        byte buf[6];
 
254
        size_t n;
 
255
        
 
256
        gcry_md_putc (md, sig->pubkey_algo);
 
257
        gcry_md_putc (md, sig->digest_algo);
 
258
        if (sig->hashed) {
 
259
            n = sig->hashed->len;
 
260
            gcry_md_putc (md, (n >> 8) );
 
261
            gcry_md_putc (md,  n       );
 
262
            gcry_md_write (md, sig->hashed->data, n );
 
263
            n += 6;
 
264
        }
 
265
        else {
 
266
            gcry_md_putc (md, 0);  /* always hash the length of the subpacket*/
 
267
            gcry_md_putc (md, 0);
 
268
            n = 6;
 
269
        }
 
270
        /* add some magic */
 
271
        buf[0] = sig->version;
 
272
        buf[1] = 0xff;
 
273
        buf[2] = n >> 24; /* hmmm, n is only 16 bit, so this is always 0 */
 
274
        buf[3] = n >> 16;
 
275
        buf[4] = n >>  8;
 
276
        buf[5] = n;
 
277
        gcry_md_write (md, buf, 6);
 
278
    }
 
279
}
 
280
 
 
281
 
 
282
static int
 
283
do_sign( PKT_secret_key *sk, PKT_signature *sig,
 
284
         MD_HANDLE md, int digest_algo )
 
285
{
 
286
  gcry_mpi_t frame;
 
287
  byte *dp;
 
288
  int rc;
 
289
 
 
290
  if( sk->timestamp > sig->timestamp ) {
 
291
    ulong d = sk->timestamp - sig->timestamp;
 
292
    log_info( d==1 ? _("key has been created %lu second "
 
293
                       "in future (time warp or clock problem)\n")
 
294
              : _("key has been created %lu seconds "
 
295
                  "in future (time warp or clock problem)\n"), d );
 
296
    if( !opt.ignore_time_conflict )
 
297
      return GPG_ERR_TIME_CONFLICT;
 
298
  }
 
299
 
 
300
  print_pubkey_algo_note(sk->pubkey_algo);
 
301
 
 
302
  if( !digest_algo )
 
303
    digest_algo = gcry_md_get_algo(md);
 
304
 
 
305
  print_digest_algo_note( digest_algo );
 
306
  dp = gcry_md_read ( md, digest_algo );
 
307
  sig->digest_algo = digest_algo;
 
308
  sig->digest_start[0] = dp[0];
 
309
  sig->digest_start[1] = dp[1];
 
310
  if (sk->is_protected && sk->protect.s2k.mode == 1002)
 
311
    { /* FIXME: Note that we do only support RSA for now. */
 
312
      char *rbuf;
 
313
      size_t rbuflen;
 
314
      char *snbuf;
 
315
 
 
316
      snbuf = serialno_and_fpr_from_sk (sk->protect.iv, sk->protect.ivlen, sk);
 
317
      rc = agent_scd_pksign (snbuf, digest_algo,
 
318
                             gcry_md_read (md, digest_algo),
 
319
                             gcry_md_get_algo_dlen (digest_algo),
 
320
                             &rbuf, &rbuflen);
 
321
      xfree (snbuf);
 
322
      if (!rc)
 
323
        {
 
324
          if (gcry_mpi_scan (&sig->data[0], GCRYMPI_FMT_USG,
 
325
                             rbuf, rbuflen, NULL))
 
326
            BUG ();
 
327
        }
 
328
    }
 
329
  else
 
330
    {
 
331
      frame = encode_md_value( sk->pubkey_algo, md,
 
332
                               digest_algo, mpi_get_nbits(sk->skey[0]), 0 );
 
333
      if (!frame)
 
334
        return GPG_ERR_GENERAL;
 
335
      rc = pk_sign( sk->pubkey_algo, sig->data, frame, sk->skey );
 
336
      gcry_mpi_release (frame);
 
337
    }
 
338
  if (!rc && !opt.no_sig_create_check) {
 
339
    /* check that the signature verification worked and nothing is
 
340
     * fooling us e.g. by a bug in the signature create
 
341
     * code or by deliberately introduced faults. */
 
342
    PKT_public_key *pk = xcalloc (1,sizeof *pk);
 
343
 
 
344
    if( get_pubkey( pk, sig->keyid ) )
 
345
      rc = GPG_ERR_NO_PUBKEY;
 
346
    else {
 
347
      frame = encode_md_value (pk->pubkey_algo, md,
 
348
                               sig->digest_algo,
 
349
                               mpi_get_nbits(pk->pkey[0]), 0);
 
350
      if (!frame)
 
351
        rc = GPG_ERR_GENERAL;
 
352
      else
 
353
        rc = pk_verify (pk->pubkey_algo, frame,
 
354
                        sig->data, pk->pkey);
 
355
      gcry_mpi_release (frame);
 
356
    }
 
357
    if (rc)
 
358
      log_error (_("checking created signature failed: %s\n"),
 
359
                 gpg_strerror (rc));
 
360
    free_public_key (pk);
 
361
  }
 
362
  if( rc )
 
363
    log_error(_("signing failed: %s\n"), gpg_strerror (rc) );
 
364
  else {
 
365
    if( opt.verbose ) {
 
366
      char *ustr = get_user_id_string_printable (sig->keyid);
 
367
      log_info(_("%s/%s signature from: \"%s\"\n"),
 
368
               gcry_pk_algo_name (sk->pubkey_algo),
 
369
               gcry_md_algo_name (sig->digest_algo),
 
370
               ustr );
 
371
      xfree (ustr);
 
372
    }
 
373
  }
 
374
  return rc;
 
375
}
 
376
 
 
377
 
 
378
 
 
379
int
 
380
complete_sig( PKT_signature *sig, PKT_secret_key *sk, MD_HANDLE md )
 
381
{
 
382
    int rc=0;
 
383
 
 
384
    if( !(rc=check_secret_key( sk, 0 )) )
 
385
        rc = do_sign( sk, sig, md, 0 );
 
386
    return rc;
 
387
}
 
388
 
 
389
static int
 
390
hash_for(int pubkey_algo, int packet_version )
 
391
{
 
392
  if( opt.def_digest_algo )
 
393
    return opt.def_digest_algo;
 
394
  else if( recipient_digest_algo )
 
395
    return recipient_digest_algo;
 
396
  else if(PGP2 && pubkey_algo == PUBKEY_ALGO_RSA && packet_version < 4 )
 
397
    {
 
398
      /* Old-style PGP only understands MD5 */
 
399
      return DIGEST_ALGO_MD5;
 
400
    }
 
401
  else if( pubkey_algo == PUBKEY_ALGO_DSA )
 
402
    {
 
403
      /* We need a 160-bit hash for DSA, so we can't just take the first
 
404
         in the pref list */
 
405
 
 
406
      if(opt.personal_digest_prefs)
 
407
        {
 
408
          prefitem_t *prefs;
 
409
 
 
410
          for(prefs=opt.personal_digest_prefs;prefs->type;prefs++)
 
411
            if(gcry_md_get_algo_dlen (prefs->value) == 20)
 
412
              return prefs->value;
 
413
        }
 
414
 
 
415
      return DIGEST_ALGO_SHA1;
 
416
    }
 
417
  else if( opt.personal_digest_prefs )
 
418
    {
 
419
      /* It's not DSA, so we can use whatever the first hash algorithm
 
420
         is in the pref list */
 
421
      return opt.personal_digest_prefs[0].value;
 
422
    }
 
423
  else
 
424
    return DEFAULT_DIGEST_ALGO;
 
425
}
 
426
 
 
427
static int
 
428
only_old_style( SK_LIST sk_list )
 
429
{
 
430
    SK_LIST sk_rover = NULL;
 
431
    int old_style = 0;
 
432
 
 
433
    /* if there are only old style capable key we use the old sytle */
 
434
    for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
 
435
        PKT_secret_key *sk = sk_rover->sk;
 
436
        if( sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
 
437
            old_style = 1;
 
438
        else
 
439
            return 0;
 
440
    }
 
441
    return old_style;
 
442
}
 
443
 
 
444
 
 
445
static void
 
446
print_status_sig_created ( PKT_secret_key *sk, PKT_signature *sig, int what )
 
447
{
 
448
    byte array[MAX_FINGERPRINT_LEN], *p;
 
449
    char buf[100+MAX_FINGERPRINT_LEN*2];
 
450
    size_t i, n;
 
451
 
 
452
    sprintf(buf, "%c %d %d %02x %lu ",
 
453
            what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
 
454
            (ulong)sig->timestamp );
 
455
 
 
456
    fingerprint_from_sk( sk, array, &n );
 
457
    p = buf + strlen(buf);
 
458
    for(i=0; i < n ; i++ )
 
459
        sprintf(p+2*i, "%02X", array[i] );
 
460
 
 
461
    write_status_text( STATUS_SIG_CREATED, buf );
 
462
}
 
463
 
 
464
 
 
465
/*
 
466
 * Loop over the secret certificates in SK_LIST and build the one pass
 
467
 * signature packets.  OpenPGP says that the data should be bracket by
 
468
 * the onepass-sig and signature-packet; so we build these onepass
 
469
 * packet here in reverse order 
 
470
 */
 
471
static int
 
472
write_onepass_sig_packets (SK_LIST sk_list, iobuf_t out, int sigclass )
 
473
{
 
474
    int skcount;
 
475
    SK_LIST sk_rover;
 
476
 
 
477
    for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
 
478
        skcount++;
 
479
 
 
480
    for (; skcount; skcount--) {
 
481
        PKT_secret_key *sk;
 
482
        PKT_onepass_sig *ops;
 
483
        PACKET pkt;
 
484
        int i, rc;
 
485
        
 
486
        for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
 
487
            if (++i == skcount)
 
488
                break;
 
489
        }
 
490
 
 
491
        sk = sk_rover->sk;
 
492
        ops = xcalloc (1,sizeof *ops);
 
493
        ops->sig_class = sigclass;
 
494
        ops->digest_algo = hash_for (sk->pubkey_algo, sk->version);
 
495
        ops->pubkey_algo = sk->pubkey_algo;
 
496
        keyid_from_sk (sk, ops->keyid);
 
497
        ops->last = (skcount == 1);
 
498
        
 
499
        init_packet(&pkt);
 
500
        pkt.pkttype = PKT_ONEPASS_SIG;
 
501
        pkt.pkt.onepass_sig = ops;
 
502
        rc = build_packet (out, &pkt);
 
503
        free_packet (&pkt);
 
504
        if (rc) {
 
505
            log_error ("build onepass_sig packet failed: %s\n",
 
506
                       gpg_strerror (rc));
 
507
            return rc;
 
508
        }
 
509
    }
 
510
 
 
511
    return 0;
 
512
}
 
513
 
 
514
/*
 
515
 * Helper to write the plaintext (literal data) packet
 
516
 */
 
517
static int
 
518
write_plaintext_packet (iobuf_t out, iobuf_t inp, const char *fname, int ptmode)
 
519
{
 
520
    PKT_plaintext *pt = NULL;
 
521
    u32 filesize;
 
522
    int rc = 0;
 
523
 
 
524
    if (!opt.no_literal) {
 
525
        if (fname || opt.set_filename) {
 
526
            char *s = make_basename (opt.set_filename? opt.set_filename
 
527
                                                     : fname
 
528
                                     /*, iobuf_get_real_fname(inp)*/);
 
529
            pt = xmalloc (sizeof *pt + strlen(s) - 1);
 
530
            pt->namelen = strlen (s);
 
531
            memcpy (pt->name, s, pt->namelen);
 
532
            xfree (s);
 
533
        }
 
534
        else { /* no filename */
 
535
            pt = xmalloc (sizeof *pt - 1);
 
536
            pt->namelen = 0;
 
537
        }
 
538
    }
 
539
 
 
540
    /* try to calculate the length of the data */
 
541
    if (fname && *fname && !(*fname=='-' && !fname[1])) {
 
542
        if( !(filesize = iobuf_get_filelength(inp)) )
 
543
            log_info (_("WARNING: `%s' is an empty file\n"), fname);
 
544
 
 
545
        /* we can't yet encode the length of very large files,
 
546
         * so we switch to partial length encoding in this case */
 
547
        if (filesize >= IOBUF_FILELENGTH_LIMIT)
 
548
            filesize = 0;
 
549
 
 
550
        /* because the text_filter modifies the length of the
 
551
         * data, it is not possible to know the used length
 
552
         * without a double read of the file - to avoid that
 
553
         * we simple use partial length packets.
 
554
         */
 
555
        if ( ptmode == 't' )
 
556
            filesize = 0;
 
557
    }
 
558
    else {
 
559
        filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
 
560
    }
 
561
 
 
562
    if (!opt.no_literal) {
 
563
        PACKET pkt;
 
564
 
 
565
        pt->timestamp = make_timestamp ();
 
566
        pt->mode = ptmode;
 
567
        pt->len = filesize;
 
568
        pt->new_ctb = !pt->len && !RFC1991;
 
569
        pt->buf = inp;
 
570
        init_packet(&pkt);
 
571
        pkt.pkttype = PKT_PLAINTEXT;
 
572
        pkt.pkt.plaintext = pt;
 
573
        /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
 
574
        if( (rc = build_packet (out, &pkt)) )
 
575
            log_error ("build_packet(PLAINTEXT) failed: %s\n",
 
576
                       gpg_strerror (rc) );
 
577
        pt->buf = NULL;
 
578
    }
 
579
    else {
 
580
        byte copy_buffer[4096];
 
581
        int  bytes_copied;
 
582
 
 
583
        while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
 
584
            if ( (rc=iobuf_write(out, copy_buffer, bytes_copied) )) {
 
585
                log_error ("copying input to output failed: %s\n",
 
586
                           gpg_strerror (rc));
 
587
                break;
 
588
            }
 
589
        wipememory(copy_buffer,4096); /* burn buffer */
 
590
    }
 
591
    /* fixme: it seems that we never freed pt/pkt */
 
592
    
 
593
    return rc;
 
594
}
 
595
 
 
596
/*
 
597
 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
 
598
 * hash which will not be changes here.
 
599
 */
 
600
static int
 
601
write_signature_packets (SK_LIST sk_list, iobuf_t out, MD_HANDLE hash,
 
602
                         int sigclass, u32 timestamp, u32 duration,
 
603
                         int status_letter)
 
604
{
 
605
    SK_LIST sk_rover;
 
606
 
 
607
    /* loop over the secret certificates */
 
608
    for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
 
609
        PKT_secret_key *sk;
 
610
        PKT_signature *sig;
 
611
        MD_HANDLE md;
 
612
        int rc;
 
613
 
 
614
        sk = sk_rover->sk;
 
615
 
 
616
        /* build the signature packet */
 
617
        sig = xcalloc (1,sizeof *sig);
 
618
        if(opt.force_v3_sigs || RFC1991)
 
619
          sig->version=3;
 
620
        else if(duration || opt.sig_policy_url
 
621
                || opt.sig_notation_data || opt.sig_keyserver_url)
 
622
          sig->version=4;
 
623
        else
 
624
          sig->version=sk->version;
 
625
        keyid_from_sk (sk, sig->keyid);
 
626
        sig->digest_algo = hash_for (sk->pubkey_algo, sk->version);
 
627
        sig->pubkey_algo = sk->pubkey_algo;
 
628
        if(timestamp)
 
629
          sig->timestamp = timestamp;
 
630
        else
 
631
          sig->timestamp = make_timestamp();
 
632
        if(duration)
 
633
          sig->expiredate = sig->timestamp+duration;
 
634
        sig->sig_class = sigclass;
 
635
 
 
636
        gcry_md_copy (&md, hash);
 
637
 
 
638
        if (sig->version >= 4)
 
639
            build_sig_subpkt_from_sig (sig);
 
640
        mk_notation_policy_etc (sig, NULL, sk);
 
641
 
 
642
        hash_sigversion_to_magic (md, sig);
 
643
        gcry_md_final (md);
 
644
 
 
645
        rc = do_sign( sk, sig, md, hash_for (sig->pubkey_algo, sk->version) );
 
646
        gcry_md_close (md);
 
647
 
 
648
        if( !rc ) { /* and write it */
 
649
            PACKET pkt;
 
650
 
 
651
            init_packet(&pkt);
 
652
            pkt.pkttype = PKT_SIGNATURE;
 
653
            pkt.pkt.signature = sig;
 
654
            rc = build_packet (out, &pkt);
 
655
            if (!rc && is_status_enabled()) {
 
656
                print_status_sig_created ( sk, sig, status_letter);
 
657
            }
 
658
            free_packet (&pkt);
 
659
            if (rc)
 
660
                log_error ("build signature packet failed: %s\n",
 
661
                           gpg_strerror (rc) );
 
662
        }
 
663
        if( rc )
 
664
            return rc;;
 
665
    }
 
666
 
 
667
    return 0;
 
668
}
 
669
 
 
670
/****************
 
671
 * Sign the files whose names are in FILENAME.
 
672
 * If DETACHED has the value true,
 
673
 * make a detached signature.  If FILENAMES->d is NULL read from stdin
 
674
 * and ignore the detached mode.  Sign the file with all secret keys
 
675
 * which can be taken from LOCUSR, if this is NULL, use the default one
 
676
 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
 
677
 * signed data for these users.
 
678
 * If OUTFILE is not NULL; this file is used for output and the function
 
679
 * does not ask for overwrite permission; output is then always
 
680
 * uncompressed, non-armored and in binary mode.
 
681
 */
 
682
int
 
683
sign_file( STRLIST filenames, int detached, STRLIST locusr,
 
684
           int encryptflag, STRLIST remusr, const char *outfile )
 
685
{
 
686
    const char *fname;
 
687
    armor_filter_context_t afx;
 
688
    compress_filter_context_t zfx;
 
689
    md_filter_context_t mfx;
 
690
    text_filter_context_t tfx;
 
691
    progress_filter_context_t pfx;
 
692
    encrypt_filter_context_t efx;
 
693
    iobuf_t inp = NULL, out = NULL;
 
694
    PACKET pkt;
 
695
    int rc = 0;
 
696
    PK_LIST pk_list = NULL;
 
697
    SK_LIST sk_list = NULL;
 
698
    SK_LIST sk_rover = NULL;
 
699
    int multifile = 0;
 
700
    u32 duration=0;
 
701
 
 
702
    memset( &afx, 0, sizeof afx);
 
703
    memset( &zfx, 0, sizeof zfx);
 
704
    memset( &mfx, 0, sizeof mfx);
 
705
    memset( &efx, 0, sizeof efx);
 
706
    init_packet( &pkt );
 
707
 
 
708
    if( filenames ) {
 
709
        fname = filenames->d;
 
710
        multifile = !!filenames->next;
 
711
    }
 
712
    else
 
713
        fname = NULL;
 
714
 
 
715
    if( fname && filenames->next && (!detached || encryptflag) )
 
716
        log_bug("multiple files can only be detached signed");
 
717
 
 
718
    if(opt.ask_sig_expire && !opt.force_v3_sigs && !opt.batch && !RFC1991)
 
719
      duration=ask_expire_interval(1);
 
720
 
 
721
    if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
 
722
        goto leave;
 
723
 
 
724
    if(PGP2 && !only_old_style(sk_list))
 
725
      {
 
726
        log_info(_("you can only detach-sign with PGP 2.x style keys "
 
727
                   "while in --pgp2 mode\n"));
 
728
        compliance_failure();
 
729
      }
 
730
 
 
731
    if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC )))
 
732
      goto leave;
 
733
 
 
734
    /* prepare iobufs */
 
735
    if( multifile )  /* have list of filenames */
 
736
        inp = NULL; /* we do it later */
 
737
    else {
 
738
        if( !(inp = iobuf_open(fname)) ) {
 
739
            rc = gpg_error_from_errno (errno);
 
740
            log_error("can't open %s: %s\n", fname? fname: "[stdin]",
 
741
                      strerror(errno) );
 
742
            goto leave;
 
743
        }
 
744
 
 
745
        handle_progress (&pfx, inp, fname);
 
746
    }
 
747
 
 
748
    if( outfile ) {
 
749
        if( !(out = iobuf_create( outfile )) ) {
 
750
            rc = gpg_error_from_errno (errno);
 
751
            log_error(_("can't create %s: %s\n"), outfile, strerror(errno) );
 
752
            goto leave;
 
753
        }
 
754
        else if( opt.verbose )
 
755
            log_info(_("writing to `%s'\n"), outfile );
 
756
    }
 
757
    else if( (rc = open_outfile( fname, opt.armor? 1: detached? 2:0, &out )))
 
758
        goto leave;
 
759
 
 
760
    /* prepare to calculate the MD over the input */
 
761
    if( opt.textmode && !outfile && !multifile )
 
762
      {
 
763
        memset( &tfx, 0, sizeof tfx);
 
764
        iobuf_push_filter( inp, text_filter, &tfx );
 
765
      }
 
766
 
 
767
    gcry_md_open (&mfx.md, 0, 0);
 
768
 
 
769
   /* If we're encrypting and signing, it is reasonable to pick the
 
770
       hash algorithm to use out of the recepient key prefs. */
 
771
    if(pk_list)
 
772
      {
 
773
        if(opt.def_digest_algo)
 
774
          {
 
775
            if(!opt.expert &&
 
776
               select_algo_from_prefs(pk_list,PREFTYPE_HASH,
 
777
                                      opt.def_digest_algo,
 
778
                                      NULL)!=opt.def_digest_algo)
 
779
          log_info(_("forcing digest algorithm %s (%d) "
 
780
                     "violates recipient preferences\n"),
 
781
                   gcry_md_algo_name (opt.def_digest_algo),
 
782
                   opt.def_digest_algo);
 
783
          }
 
784
        else
 
785
          {
 
786
            int hashlen=0,algo;
 
787
 
 
788
            /* Of course, if the recipient asks for something
 
789
               unreasonable (like a non-160-bit hash for DSA, for
 
790
               example), then don't do it.  Check all sk's - if any
 
791
               are DSA, then the hash must be 160-bit.  In the future
 
792
               this can be more complex with different hashes for each
 
793
               sk, but so long as there is only one signing algorithm
 
794
               with hash restrictions, this is ok. -dms */
 
795
 
 
796
            for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
 
797
              if(sk_rover->sk->pubkey_algo==PUBKEY_ALGO_DSA)
 
798
                hashlen=20;
 
799
 
 
800
            if((algo=
 
801
                select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,
 
802
                                       hashlen?&hashlen:NULL))>0)
 
803
              recipient_digest_algo=algo;
 
804
          }
 
805
      }
 
806
 
 
807
    for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
 
808
        PKT_secret_key *sk = sk_rover->sk;
 
809
        gcry_md_enable (mfx.md, hash_for(sk->pubkey_algo, sk->version ));
 
810
    }
 
811
 
 
812
    if( !multifile )
 
813
        iobuf_push_filter( inp, md_filter, &mfx );
 
814
 
 
815
    if( detached && !encryptflag && !RFC1991 )
 
816
        afx.what = 2;
 
817
 
 
818
    if( opt.armor && !outfile  )
 
819
        iobuf_push_filter( out, armor_filter, &afx );
 
820
 
 
821
    if( encryptflag ) {
 
822
        efx.pk_list = pk_list;
 
823
        /* fixme: set efx.cfx.datalen if known */
 
824
        iobuf_push_filter( out, encrypt_filter, &efx );
 
825
    }
 
826
 
 
827
    if( opt.compress && !outfile && ( !detached || opt.compress_sigs) )
 
828
      {
 
829
        int compr_algo=opt.def_compress_algo;
 
830
 
 
831
        /* If not forced by user */
 
832
        if(compr_algo==-1)
 
833
          {
 
834
            /* If we're not encrypting, then select_algo_from_prefs
 
835
               will fail and we'll end up with the default.  If we are
 
836
               encrypting, select_algo_from_prefs cannot fail since
 
837
               there is an assumed preference for uncompressed data.
 
838
               Still, if it did fail, we'll also end up with the
 
839
               default. */
 
840
 
 
841
            if((compr_algo=
 
842
                select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
 
843
              compr_algo=default_compress_algo();
 
844
          }
 
845
        else if(!opt.expert && pk_list
 
846
                && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
 
847
                                          compr_algo,NULL)!=compr_algo)
 
848
          log_info(_("forcing compression algorithm %s (%d) "
 
849
                     "violates recipient preferences\n"),
 
850
                   compress_algo_to_string(compr_algo),compr_algo);
 
851
 
 
852
        /* algo 0 means no compression */
 
853
        if( compr_algo )
 
854
          {
 
855
            zfx.algo = compr_algo;
 
856
            iobuf_push_filter( out, compress_filter, &zfx );
 
857
          }
 
858
      }
 
859
 
 
860
    /* Write the one-pass signature packets if needed */
 
861
    if (!detached && !RFC1991) {
 
862
        rc = write_onepass_sig_packets (sk_list, out,
 
863
                                        opt.textmode && !outfile ? 0x01:0x00);
 
864
        if (rc)
 
865
            goto leave;
 
866
    }
 
867
 
 
868
    /* setup the inner packet */
 
869
    if( detached ) {
 
870
        if( multifile ) {
 
871
            STRLIST sl;
 
872
 
 
873
            if( opt.verbose )
 
874
                log_info(_("signing:") );
 
875
            /* must walk reverse trough this list */
 
876
            for( sl = strlist_last(filenames); sl;
 
877
                        sl = strlist_prev( filenames, sl ) ) {
 
878
                if( !(inp = iobuf_open(sl->d)) ) {
 
879
                    rc = gpg_error_from_errno (errno);
 
880
                    log_error(_("can't open %s: %s\n"),
 
881
                                            sl->d, strerror(errno) );
 
882
                    goto leave;
 
883
                }
 
884
                handle_progress (&pfx, inp, sl->d);
 
885
                if( opt.verbose )
 
886
                    fprintf(stderr, " `%s'", sl->d );
 
887
                if(opt.textmode)
 
888
                  {
 
889
                    memset( &tfx, 0, sizeof tfx);
 
890
                    iobuf_push_filter( inp, text_filter, &tfx );
 
891
                  }
 
892
                iobuf_push_filter( inp, md_filter, &mfx );
 
893
                while( iobuf_get(inp) != -1 )
 
894
                    ;
 
895
                iobuf_close(inp); inp = NULL;
 
896
            }
 
897
            if( opt.verbose )
 
898
                putc( '\n', stderr );
 
899
        }
 
900
        else {
 
901
            /* read, so that the filter can calculate the digest */
 
902
            while( iobuf_get(inp) != -1 )
 
903
                ;
 
904
        }
 
905
    }
 
906
    else {
 
907
        rc = write_plaintext_packet (out, inp, fname,
 
908
                                     opt.textmode && !outfile ? 't':'b');
 
909
    }
 
910
 
 
911
    /* catch errors from above */
 
912
    if (rc)
 
913
        goto leave;
 
914
 
 
915
    /* write the signatures */
 
916
    rc = write_signature_packets (sk_list, out, mfx.md,
 
917
                                  opt.textmode && !outfile? 0x01 : 0x00,
 
918
                                  0, duration, detached ? 'D':'S');
 
919
    if( rc )
 
920
        goto leave;
 
921
 
 
922
 
 
923
  leave:
 
924
    if( rc )
 
925
        iobuf_cancel(out);
 
926
    else {
 
927
        iobuf_close(out);
 
928
        if (encryptflag)
 
929
            write_status( STATUS_END_ENCRYPTION );
 
930
    }
 
931
    iobuf_close(inp);
 
932
    gcry_md_close ( mfx.md );
 
933
    release_sk_list( sk_list );
 
934
    release_pk_list( pk_list );
 
935
    recipient_digest_algo=0;
 
936
    return rc;
 
937
}
 
938
 
 
939
 
 
940
 
 
941
/****************
 
942
 * make a clear signature. note that opt.armor is not needed
 
943
 */
 
944
int
 
945
clearsign_file( const char *fname, STRLIST locusr, const char *outfile )
 
946
{
 
947
    armor_filter_context_t afx;
 
948
    progress_filter_context_t pfx;
 
949
    MD_HANDLE textmd = NULL;
 
950
    iobuf_t inp = NULL, out = NULL;
 
951
    PACKET pkt;
 
952
    int rc = 0;
 
953
    SK_LIST sk_list = NULL;
 
954
    SK_LIST sk_rover = NULL;
 
955
    int old_style = RFC1991;
 
956
    int only_md5 = 0;
 
957
    u32 duration=0;
 
958
 
 
959
    memset( &afx, 0, sizeof afx);
 
960
    init_packet( &pkt );
 
961
 
 
962
    if(opt.ask_sig_expire && !opt.force_v3_sigs && !opt.batch && !RFC1991)
 
963
      duration=ask_expire_interval(1);
 
964
 
 
965
    if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
 
966
        goto leave;
 
967
 
 
968
    if( !old_style && !duration )
 
969
        old_style = only_old_style( sk_list );
 
970
 
 
971
    if(PGP2 && !only_old_style(sk_list))
 
972
      {
 
973
        log_info(_("you can only clearsign with PGP 2.x style keys "
 
974
                   "while in --pgp2 mode\n"));
 
975
        compliance_failure();
 
976
      }
 
977
 
 
978
    /* prepare iobufs */
 
979
    if( !(inp = iobuf_open(fname)) ) {
 
980
        rc = gpg_error_from_errno (errno);
 
981
        log_error("can't open %s: %s\n", fname? fname: "[stdin]",
 
982
                                        strerror(errno) );
 
983
        goto leave;
 
984
    }
 
985
    handle_progress (&pfx, inp, fname);
 
986
 
 
987
    if( outfile ) {
 
988
        if( !(out = iobuf_create( outfile )) ) {
 
989
            rc = gpg_error_from_errno (errno);
 
990
            log_error(_("can't create %s: %s\n"), outfile, strerror(errno) );
 
991
            goto leave;
 
992
        }
 
993
        else if( opt.verbose )
 
994
            log_info(_("writing to `%s'\n"), outfile );
 
995
    }
 
996
    else if( (rc = open_outfile( fname, 1, &out )) )
 
997
        goto leave;
 
998
 
 
999
    iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
 
1000
 
 
1001
    for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
 
1002
        PKT_secret_key *sk = sk_rover->sk;
 
1003
        if( hash_for(sk->pubkey_algo, sk->version) == DIGEST_ALGO_MD5 )
 
1004
            only_md5 = 1;
 
1005
        else {
 
1006
            only_md5 = 0;
 
1007
            break;
 
1008
        }
 
1009
    }
 
1010
 
 
1011
    if( !(old_style && only_md5) ) {
 
1012
        const char *s;
 
1013
        int any = 0;
 
1014
        byte hashs_seen[256];
 
1015
 
 
1016
        memset( hashs_seen, 0, sizeof hashs_seen );
 
1017
        iobuf_writestr(out, "Hash: " );
 
1018
        for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
 
1019
            PKT_secret_key *sk = sk_rover->sk;
 
1020
            int i = hash_for(sk->pubkey_algo, sk->version);
 
1021
 
 
1022
            if( !hashs_seen[ i & 0xff ] ) {
 
1023
                s = gcry_md_algo_name (i);
 
1024
                if( s ) {
 
1025
                    hashs_seen[ i & 0xff ] = 1;
 
1026
                    if( any )
 
1027
                        iobuf_put(out, ',' );
 
1028
                    iobuf_writestr(out, s );
 
1029
                    any = 1;
 
1030
                }
 
1031
            }
 
1032
        }
 
1033
        assert(any);
 
1034
        iobuf_writestr(out, LF );
 
1035
    }
 
1036
 
 
1037
    if( opt.not_dash_escaped )
 
1038
      iobuf_writestr( out,
 
1039
                  "NotDashEscaped: You need GnuPG to verify this message" LF );
 
1040
    iobuf_writestr(out, LF );
 
1041
 
 
1042
    gcry_md_open (&textmd, 0, 0);
 
1043
    for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
 
1044
        PKT_secret_key *sk = sk_rover->sk;
 
1045
        gcry_md_enable (textmd, hash_for(sk->pubkey_algo, sk->version));
 
1046
    }
 
1047
    if ( DBG_HASHING )
 
1048
        gcry_md_start_debug ( textmd, "clearsign" );
 
1049
    copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
 
1050
                        opt.escape_from, (old_style && only_md5) );
 
1051
    /* fixme: check for read errors */
 
1052
 
 
1053
    /* now write the armor */
 
1054
    afx.what = 2;
 
1055
    iobuf_push_filter( out, armor_filter, &afx );
 
1056
 
 
1057
    /* write the signatures */
 
1058
    rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
 
1059
    if( rc )
 
1060
        goto leave;
 
1061
 
 
1062
  leave:
 
1063
    if( rc )
 
1064
        iobuf_cancel(out);
 
1065
    else
 
1066
        iobuf_close(out);
 
1067
    iobuf_close(inp);
 
1068
    gcry_md_close ( textmd );
 
1069
    release_sk_list( sk_list );
 
1070
    return rc;
 
1071
}
 
1072
 
 
1073
/*
 
1074
 * Sign and conventionally encrypt the given file.
 
1075
 * FIXME: Far too much code is duplicated - revamp the whole file.
 
1076
 */
 
1077
int
 
1078
sign_symencrypt_file (const char *fname, STRLIST locusr)
 
1079
{
 
1080
    armor_filter_context_t afx;
 
1081
    progress_filter_context_t pfx;
 
1082
    compress_filter_context_t zfx;
 
1083
    md_filter_context_t mfx;
 
1084
    text_filter_context_t tfx;
 
1085
    cipher_filter_context_t cfx;
 
1086
    iobuf_t inp = NULL, out = NULL;
 
1087
    PACKET pkt;
 
1088
    STRING2KEY *s2k = NULL;
 
1089
    int rc = 0;
 
1090
    SK_LIST sk_list = NULL;
 
1091
    SK_LIST sk_rover = NULL;
 
1092
    int algo;
 
1093
    u32 duration=0;
 
1094
 
 
1095
    memset( &afx, 0, sizeof afx);
 
1096
    memset( &zfx, 0, sizeof zfx);
 
1097
    memset( &mfx, 0, sizeof mfx);
 
1098
    memset( &tfx, 0, sizeof tfx);
 
1099
    memset( &cfx, 0, sizeof cfx);
 
1100
    init_packet( &pkt );
 
1101
 
 
1102
    if(opt.ask_sig_expire && !opt.force_v3_sigs && !opt.batch && !RFC1991)
 
1103
      duration=ask_expire_interval(1);
 
1104
 
 
1105
    rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
 
1106
    if (rc) 
 
1107
        goto leave;
 
1108
 
 
1109
    /* prepare iobufs */
 
1110
    inp = iobuf_open(fname);
 
1111
    if( !inp ) {
 
1112
        rc = gpg_error_from_errno (errno);
 
1113
        log_error("can't open %s: %s\n", fname? fname: "[stdin]",
 
1114
                                        strerror(errno) );
 
1115
        goto leave;
 
1116
    }
 
1117
    handle_progress (&pfx, inp, fname);
 
1118
 
 
1119
    /* prepare key */
 
1120
    s2k = xcalloc (1, sizeof *s2k );
 
1121
    s2k->mode = RFC1991? 0:opt.s2k_mode;
 
1122
    s2k->hash_algo = opt.s2k_digest_algo;
 
1123
 
 
1124
    algo = default_cipher_algo();
 
1125
    if (!opt.quiet || !opt.batch)
 
1126
        log_info (_("%s encryption will be used\n"),
 
1127
                    gcry_cipher_algo_name (algo) );
 
1128
    cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, NULL);
 
1129
 
 
1130
    if (!cfx.dek || !cfx.dek->keylen) {
 
1131
        rc = gpg_error (GPG_ERR_INV_PASSPHRASE);
 
1132
        log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
 
1133
        goto leave;
 
1134
    }
 
1135
 
 
1136
    /* now create the outfile */
 
1137
    rc = open_outfile (fname, opt.armor? 1:0, &out);
 
1138
    if (rc)
 
1139
        goto leave;
 
1140
 
 
1141
    /* prepare to calculate the MD over the input */
 
1142
    if (opt.textmode)
 
1143
        iobuf_push_filter (inp, text_filter, &tfx);
 
1144
    gcry_md_open (&mfx.md, 0, 0);
 
1145
 
 
1146
    for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
 
1147
        PKT_secret_key *sk = sk_rover->sk;
 
1148
        gcry_md_enable (mfx.md, hash_for (sk->pubkey_algo, sk->version ));
 
1149
    }
 
1150
 
 
1151
    iobuf_push_filter (inp, md_filter, &mfx);
 
1152
 
 
1153
    /* Push armor output filter */
 
1154
    if (opt.armor)
 
1155
        iobuf_push_filter (out, armor_filter, &afx);
 
1156
 
 
1157
    /* Write the symmetric key packet */
 
1158
    /*(current filters: armor)*/
 
1159
    if (!RFC1991) {
 
1160
        PKT_symkey_enc *enc = xcalloc (1, sizeof *enc );
 
1161
        enc->version = 4;
 
1162
        enc->cipher_algo = cfx.dek->algo;
 
1163
        enc->s2k = *s2k;
 
1164
        pkt.pkttype = PKT_SYMKEY_ENC;
 
1165
        pkt.pkt.symkey_enc = enc;
 
1166
        if( (rc = build_packet( out, &pkt )) )
 
1167
            log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
 
1168
        xfree (enc);
 
1169
    }
 
1170
 
 
1171
    /* Push the encryption filter */
 
1172
    iobuf_push_filter( out, cipher_filter, &cfx );
 
1173
 
 
1174
    /* Push the Zip filter */
 
1175
    if (opt.compress && default_compress_algo())
 
1176
      {
 
1177
        zfx.algo = default_compress_algo();
 
1178
        iobuf_push_filter( out, compress_filter, &zfx );
 
1179
      }
 
1180
 
 
1181
    /* Write the one-pass signature packets */
 
1182
    /*(current filters: zip - encrypt - armor)*/
 
1183
    if (!RFC1991) {
 
1184
        rc = write_onepass_sig_packets (sk_list, out,
 
1185
                                        opt.textmode? 0x01:0x00);
 
1186
        if (rc)
 
1187
            goto leave;
 
1188
    }
 
1189
 
 
1190
    /* Pipe data through all filters; i.e. write the signed stuff */
 
1191
    /*(current filters: zip - encrypt - armor)*/
 
1192
    rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
 
1193
    if (rc)
 
1194
        goto leave;
 
1195
    
 
1196
    /* Write the signatures */
 
1197
    /*(current filters: zip - encrypt - armor)*/
 
1198
    rc = write_signature_packets (sk_list, out, mfx.md,
 
1199
                                  opt.textmode? 0x01 : 0x00,
 
1200
                                  0, duration, 'S');
 
1201
    if( rc )
 
1202
        goto leave;
 
1203
 
 
1204
 
 
1205
  leave:
 
1206
    if( rc )
 
1207
        iobuf_cancel(out);
 
1208
    else {
 
1209
        iobuf_close(out);
 
1210
        write_status( STATUS_END_ENCRYPTION );
 
1211
    }
 
1212
    iobuf_close(inp);
 
1213
    release_sk_list( sk_list );
 
1214
    gcry_md_close ( mfx.md );
 
1215
    xfree (cfx.dek);
 
1216
    xfree (s2k);
 
1217
    return rc;
 
1218
}
 
1219
 
 
1220
 
 
1221
/****************
 
1222
 * Create a signature packet for the given public key certificate and
 
1223
 * the user id and return it in ret_sig. User signature class SIGCLASS
 
1224
 * user-id is not used (and may be NULL if sigclass is 0x20) If
 
1225
 * DIGEST_ALGO is 0 the function selects an appropriate one.
 
1226
 * SIGVERSION gives the minimal required signature packet version;
 
1227
 * this is needed so that special properties like local sign are not
 
1228
 * applied (actually: dropped) when a v3 key is used.  TIMESTAMP is
 
1229
 * the timestamp to use for the signature. 0 means "now". */
 
1230
int
 
1231
make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
 
1232
                    PKT_user_id *uid, PKT_public_key *subpk,
 
1233
                    PKT_secret_key *sk,
 
1234
                    int sigclass, int digest_algo,
 
1235
                    int sigversion, u32 timestamp, u32 duration,
 
1236
                    int (*mksubpkt)(PKT_signature *, void *), void *opaque
 
1237
                   )
 
1238
{
 
1239
    PKT_signature *sig;
 
1240
    int rc=0;
 
1241
    MD_HANDLE md;
 
1242
 
 
1243
    assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
 
1244
            || sigclass == 0x20 || sigclass == 0x18
 
1245
            || sigclass == 0x30 || sigclass == 0x28 );
 
1246
 
 
1247
    if (opt.force_v4_certs)
 
1248
        sigversion = 4;
 
1249
 
 
1250
    if (sigversion < sk->version)
 
1251
        sigversion = sk->version;
 
1252
 
 
1253
    /* If you are making a signature on a v4 key using your v3 key, it
 
1254
       doesn't make sense to generate a v3 sig.  After all, no v3-only
 
1255
       PGP implementation could understand the v4 key in the first
 
1256
       place.  Note that this implies that a signature on an attribute
 
1257
       uid is usually going to be v4 as well, since they are not
 
1258
       generally found on v3 keys. */
 
1259
    if (sigversion < pk->version)
 
1260
        sigversion = pk->version;
 
1261
 
 
1262
    if( !digest_algo )
 
1263
      {
 
1264
        /* Basically, this means use SHA1 always unless it's a v3 RSA
 
1265
           key making a v3 cert (use MD5), or the user specified
 
1266
           something (use whatever they said).  They still must use a
 
1267
           160-bit hash with DSA, or the signature will fail.  Note
 
1268
           that this still allows the caller of make_keysig_packet to
 
1269
           override the user setting if it must. */
 
1270
 
 
1271
        if(opt.cert_digest_algo)
 
1272
          digest_algo=opt.cert_digest_algo;
 
1273
        else if((sk->pubkey_algo==PUBKEY_ALGO_RSA ||
 
1274
                 sk->pubkey_algo==PUBKEY_ALGO_RSA_S) &&
 
1275
                pk->version<4 && sigversion < 4)
 
1276
          digest_algo = DIGEST_ALGO_MD5;
 
1277
        else
 
1278
          digest_algo = DIGEST_ALGO_SHA1;
 
1279
      }
 
1280
 
 
1281
    gcry_md_open (&md, digest_algo, 0 );
 
1282
 
 
1283
    /* hash the public key certificate and the user id */
 
1284
    hash_public_key( md, pk );
 
1285
    if( sigclass == 0x18 || sigclass == 0x28 ) { /* subkey binding/revocation*/
 
1286
        hash_public_key( md, subpk );
 
1287
    }
 
1288
    else if( sigclass != 0x1F && sigclass != 0x20 ) {
 
1289
        hash_uid (md, sigversion, uid);
 
1290
    }
 
1291
    /* and make the signature packet */
 
1292
    sig = xcalloc (1, sizeof *sig );
 
1293
    sig->version = sigversion;
 
1294
    sig->flags.exportable=1;
 
1295
    sig->flags.revocable=1;
 
1296
    keyid_from_sk( sk, sig->keyid );
 
1297
    sig->pubkey_algo = sk->pubkey_algo;
 
1298
    sig->digest_algo = digest_algo;
 
1299
    if(timestamp)
 
1300
      sig->timestamp=timestamp;
 
1301
    else
 
1302
      sig->timestamp=make_timestamp();
 
1303
    if(duration)
 
1304
      sig->expiredate=sig->timestamp+duration;
 
1305
    sig->sig_class = sigclass;
 
1306
    if( sig->version >= 4 )
 
1307
        build_sig_subpkt_from_sig( sig );
 
1308
    mk_notation_policy_etc ( sig, pk, sk );
 
1309
 
 
1310
    /* Crucial that the call to mksubpkt comes LAST before the calls
 
1311
       to finalize the sig as that makes it possible for the mksubpkt
 
1312
       function to get a reliable pointer to the subpacket area. */
 
1313
    if( sig->version >= 4 && mksubpkt )
 
1314
        rc = (*mksubpkt)( sig, opaque );
 
1315
 
 
1316
    if( !rc ) {
 
1317
        hash_sigversion_to_magic (md, sig);
 
1318
        gcry_md_final (md);
 
1319
 
 
1320
        rc = complete_sig( sig, sk, md );
 
1321
    }
 
1322
 
 
1323
    gcry_md_close ( md );
 
1324
    if( rc )
 
1325
        free_seckey_enc( sig );
 
1326
    else
 
1327
        *ret_sig = sig;
 
1328
    return rc;
 
1329
}
 
1330
 
 
1331
 
 
1332
 
 
1333
/****************
 
1334
 * Create a new signature packet based on an existing one.
 
1335
 * Only user ID signatures are supported for now.
 
1336
 * TODO: Merge this with make_keysig_packet.
 
1337
 */
 
1338
int
 
1339
update_keysig_packet( PKT_signature **ret_sig,
 
1340
                      PKT_signature *orig_sig,
 
1341
                      PKT_public_key *pk,
 
1342
                      PKT_user_id *uid, 
 
1343
                      PKT_public_key *subpk,
 
1344
                      PKT_secret_key *sk,
 
1345
                      int (*mksubpkt)(PKT_signature *, void *),
 
1346
                      void *opaque
 
1347
                   )
 
1348
{
 
1349
    PKT_signature *sig;
 
1350
    int rc=0;
 
1351
    MD_HANDLE md;
 
1352
 
 
1353
    if ((!orig_sig || !pk || !sk)
 
1354
        || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
 
1355
        || (orig_sig->sig_class == 0x18 && !subpk))
 
1356
      return GPG_ERR_GENERAL;
 
1357
 
 
1358
    gcry_md_open (&md, orig_sig->digest_algo, 0);
 
1359
 
 
1360
    /* hash the public key certificate and the user id */
 
1361
    hash_public_key( md, pk );
 
1362
 
 
1363
    if( orig_sig->sig_class == 0x18 )
 
1364
      hash_public_key( md, subpk );
 
1365
    else
 
1366
      hash_uid (md, orig_sig->version, uid);
 
1367
 
 
1368
    /* create a new signature packet */
 
1369
    sig = copy_signature (NULL, orig_sig);
 
1370
 
 
1371
    /* We need to create a new timestamp so that new sig expiration
 
1372
       calculations are done correctly... */
 
1373
    sig->timestamp=make_timestamp();
 
1374
 
 
1375
    /* ... but we won't make a timestamp earlier than the existing
 
1376
       one. */
 
1377
    while(sig->timestamp<=orig_sig->timestamp)
 
1378
      {
 
1379
        sleep(1);
 
1380
        sig->timestamp=make_timestamp();
 
1381
      }
 
1382
 
 
1383
    /* Note that already expired sigs will remain expired (with a
 
1384
       duration of 0) since build-packet.c:build_sig_subpkt_from_sig
 
1385
       detects this case. */
 
1386
 
 
1387
    if( sig->version >= 4 )
 
1388
      {
 
1389
        /* Put the updated timestamp into the sig.  Note that this
 
1390
           will automagically lower any sig expiration dates to
 
1391
           correctly correspond to the differences in the timestamps
 
1392
           (i.e. the duration will shrink). */
 
1393
        build_sig_subpkt_from_sig( sig );
 
1394
 
 
1395
        if (mksubpkt)
 
1396
          rc = (*mksubpkt)(sig, opaque);
 
1397
      }
 
1398
 
 
1399
    if (!rc) {
 
1400
        hash_sigversion_to_magic (md, sig);
 
1401
        gcry_md_final (md);
 
1402
 
 
1403
        rc = complete_sig( sig, sk, md );
 
1404
    }
 
1405
 
 
1406
    gcry_md_close (md);
 
1407
    if( rc )
 
1408
        free_seckey_enc (sig);
 
1409
    else
 
1410
        *ret_sig = sig;
 
1411
    return rc;
 
1412
}