Imported Upstream version 2.1.8
[platform/upstream/gpg2.git] / g10 / sign.c
1 /* sign.c - sign data
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2007, 2010, 2012 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 "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "iobuf.h"
33 #include "keydb.h"
34 #include "util.h"
35 #include "main.h"
36 #include "filter.h"
37 #include "ttyio.h"
38 #include "trustdb.h"
39 #include "status.h"
40 #include "i18n.h"
41 #include "pkglue.h"
42 #include "sysutils.h"
43 #include "call-agent.h"
44
45
46 #ifdef HAVE_DOSISH_SYSTEM
47 #define LF "\r\n"
48 #else
49 #define LF "\n"
50 #endif
51
52 static int recipient_digest_algo=0;
53
54 /****************
55  * Create notations and other stuff.  It is assumed that the stings in
56  * STRLIST are already checked to contain only printable data and have
57  * a valid NAME=VALUE format.
58  */
59 static void
60 mk_notation_policy_etc (PKT_signature *sig,
61                         PKT_public_key *pk, PKT_public_key *pksk)
62 {
63     const char *string;
64     char *s=NULL;
65     strlist_t pu=NULL;
66     struct notation *nd=NULL;
67     struct expando_args args;
68
69     assert(sig->version>=4);
70
71     memset(&args,0,sizeof(args));
72     args.pk=pk;
73     args.pksk=pksk;
74
75     /* notation data */
76     if(IS_SIG(sig) && opt.sig_notations)
77       nd=opt.sig_notations;
78     else if( IS_CERT(sig) && opt.cert_notations )
79       nd=opt.cert_notations;
80
81     if(nd)
82       {
83         struct notation *i;
84
85         for(i=nd;i;i=i->next)
86           {
87             i->altvalue=pct_expando(i->value,&args);
88             if(!i->altvalue)
89               log_error(_("WARNING: unable to %%-expand notation "
90                           "(too large).  Using unexpanded.\n"));
91           }
92
93         keygen_add_notations(sig,nd);
94
95         for(i=nd;i;i=i->next)
96           {
97             xfree(i->altvalue);
98             i->altvalue=NULL;
99           }
100       }
101
102     /* set policy URL */
103     if( IS_SIG(sig) && opt.sig_policy_url )
104       pu=opt.sig_policy_url;
105     else if( IS_CERT(sig) && opt.cert_policy_url )
106       pu=opt.cert_policy_url;
107
108     for(;pu;pu=pu->next)
109       {
110         string = pu->d;
111
112         s=pct_expando(string,&args);
113         if(!s)
114           {
115             log_error(_("WARNING: unable to %%-expand policy URL "
116                         "(too large).  Using unexpanded.\n"));
117             s=xstrdup(string);
118           }
119
120         build_sig_subpkt(sig,SIGSUBPKT_POLICY|
121                          ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
122                          s,strlen(s));
123
124         xfree(s);
125       }
126
127     /* preferred keyserver URL */
128     if( IS_SIG(sig) && opt.sig_keyserver_url )
129       pu=opt.sig_keyserver_url;
130
131     for(;pu;pu=pu->next)
132       {
133         string = pu->d;
134
135         s=pct_expando(string,&args);
136         if(!s)
137           {
138             log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
139                         " (too large).  Using unexpanded.\n"));
140             s=xstrdup(string);
141           }
142
143         build_sig_subpkt(sig,SIGSUBPKT_PREF_KS|
144                          ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
145                          s,strlen(s));
146
147         xfree(s);
148       }
149 }
150
151
152 /*
153  * Helper to hash a user ID packet.
154  */
155 static void
156 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
157 {
158   byte buf[5];
159
160   (void)sigversion;
161
162   if (uid->attrib_data)
163     {
164       buf[0] = 0xd1;                   /* Indicates an attribute packet.  */
165       buf[1] = uid->attrib_len >> 24;  /* Always use 4 length bytes.  */
166       buf[2] = uid->attrib_len >> 16;
167       buf[3] = uid->attrib_len >>  8;
168       buf[4] = uid->attrib_len;
169     }
170   else
171     {
172       buf[0] = 0xb4;                   /* Indicates a userid packet.  */
173       buf[1] = uid->len >> 24;         /* Always use 4 length bytes.  */
174       buf[2] = uid->len >> 16;
175       buf[3] = uid->len >>  8;
176       buf[4] = uid->len;
177     }
178   gcry_md_write( md, buf, 5 );
179
180   if (uid->attrib_data)
181     gcry_md_write (md, uid->attrib_data, uid->attrib_len );
182   else
183     gcry_md_write (md, uid->name, uid->len );
184 }
185
186
187 /*
188  * Helper to hash some parts from the signature
189  */
190 static void
191 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
192 {
193   byte buf[6];
194   size_t n;
195
196   gcry_md_putc (md, sig->version);
197   gcry_md_putc (md, sig->sig_class);
198   gcry_md_putc (md, sig->pubkey_algo);
199   gcry_md_putc (md, sig->digest_algo);
200   if (sig->hashed)
201     {
202       n = sig->hashed->len;
203       gcry_md_putc (md, (n >> 8) );
204       gcry_md_putc (md,  n       );
205       gcry_md_write (md, sig->hashed->data, n );
206       n += 6;
207     }
208   else
209     {
210       gcry_md_putc (md, 0);  /* Always hash the length of the subpacket.  */
211       gcry_md_putc (md, 0);
212       n = 6;
213     }
214   /* Add some magic.  */
215   buf[0] = sig->version;
216   buf[1] = 0xff;
217   buf[2] = n >> 24;         /* (n is only 16 bit, so this is always 0) */
218   buf[3] = n >> 16;
219   buf[4] = n >>  8;
220   buf[5] = n;
221   gcry_md_write (md, buf, 6);
222 }
223
224
225 /* Perform the sign operation.  If CACHE_NONCE is given the agent is
226    advised to use that cached passphrase fro the key.  */
227 static int
228 do_sign (PKT_public_key *pksk, PKT_signature *sig,
229          gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
230 {
231   gpg_error_t err;
232   gcry_mpi_t frame;
233   byte *dp;
234   char *hexgrip;
235
236   if (pksk->timestamp > sig->timestamp )
237     {
238       ulong d = pksk->timestamp - sig->timestamp;
239       log_info (d==1 ? _("key has been created %lu second "
240                          "in future (time warp or clock problem)\n")
241                 : _("key has been created %lu seconds "
242                     "in future (time warp or clock problem)\n"), d );
243       if (!opt.ignore_time_conflict)
244         return gpg_error (GPG_ERR_TIME_CONFLICT);
245     }
246
247
248   print_pubkey_algo_note (pksk->pubkey_algo);
249
250   if (!mdalgo)
251     mdalgo = gcry_md_get_algo (md);
252
253   print_digest_algo_note (mdalgo);
254   dp = gcry_md_read  (md, mdalgo);
255   sig->digest_algo = mdalgo;
256   sig->digest_start[0] = dp[0];
257   sig->digest_start[1] = dp[1];
258   sig->data[0] = NULL;
259   sig->data[1] = NULL;
260
261
262   err = hexkeygrip_from_pk (pksk, &hexgrip);
263   if (!err)
264     {
265       char *desc;
266       gcry_sexp_t s_sigval;
267
268       desc = gpg_format_keydesc (pksk, FORMAT_KEYDESC_NORMAL, 1);
269       err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
270                           pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
271                           dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
272                           &s_sigval);
273       xfree (desc);
274
275       if (err)
276         ;
277       else if (pksk->pubkey_algo == GCRY_PK_RSA
278                || pksk->pubkey_algo == GCRY_PK_RSA_S)
279         sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
280       else if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
281         {
282           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE);
283           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE);
284         }
285       else
286         {
287           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
288           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
289         }
290
291       gcry_sexp_release (s_sigval);
292     }
293   xfree (hexgrip);
294
295   /* Check that the signature verification worked and nothing is
296    * fooling us e.g. by a bug in the signature create code or by
297    * deliberately introduced faults.  Because Libgcrypt 1.7 does this
298    * for RSA internally there is no need to do it here again.  */
299   if (!err
300 #if GCRYPT_VERSION_NUMBER >= 0x010700 /* Libgcrypt >= 1.7 */
301         && !is_RSA (pksk->pubkey_algo)
302 #endif /* Libgcrypt >= 1.7 */
303       )
304     {
305       PKT_public_key *pk = xmalloc_clear (sizeof *pk);
306
307       if (get_pubkey (pk, sig->keyid ))
308         err = gpg_error (GPG_ERR_NO_PUBKEY);
309       else
310         {
311           frame = encode_md_value (pk, md, sig->digest_algo );
312           if (!frame)
313             err = gpg_error (GPG_ERR_GENERAL);
314           else
315             err = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey);
316           gcry_mpi_release (frame);
317         }
318       if (err)
319         log_error (_("checking created signature failed: %s\n"),
320                    gpg_strerror (err));
321       free_public_key (pk);
322     }
323
324   if (err)
325     log_error (_("signing failed: %s\n"), gpg_strerror (err));
326   else
327     {
328       if (opt.verbose)
329         {
330           char *ustr = get_user_id_string_native (sig->keyid);
331           log_info (_("%s/%s signature from: \"%s\"\n"),
332                     openpgp_pk_algo_name (pksk->pubkey_algo),
333                     openpgp_md_algo_name (sig->digest_algo),
334                     ustr);
335           xfree (ustr);
336         }
337     }
338   return err;
339 }
340
341
342 int
343 complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
344               const char *cache_nonce)
345 {
346   int rc;
347
348   /* if (!(rc = check_secret_key (pksk, 0))) */
349   rc = do_sign (pksk, sig, md, 0, cache_nonce);
350   return rc;
351 }
352
353
354 /* Return true if the key seems to be on a version 1 OpenPGP card.
355    This works by asking the agent and may fail if the card has not yet
356    been used with the agent.  */
357 static int
358 openpgp_card_v1_p (PKT_public_key *pk)
359 {
360   gpg_error_t err;
361   int result;
362
363   /* Shortcut if we are not using RSA: The v1 cards only support RSA
364      thus there is no point in looking any further.  */
365   if (!is_RSA (pk->pubkey_algo))
366     return 0;
367
368   if (!pk->flags.serialno_valid)
369     {
370       char *hexgrip;
371
372       err = hexkeygrip_from_pk (pk, &hexgrip);
373       if (err)
374         {
375           log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
376           return 0; /* Ooops.  */
377         }
378
379       xfree (pk->serialno);
380       agent_get_keyinfo (NULL, hexgrip, &pk->serialno);
381       xfree (hexgrip);
382       pk->flags.serialno_valid = 1;
383     }
384
385   if (!pk->serialno)
386     result = 0; /* Error from a past agent_get_keyinfo or no card.  */
387   else
388     {
389       /* The version number of the card is included in the serialno.  */
390       result = !strncmp (pk->serialno, "D2760001240101", 14);
391     }
392   return result;
393 }
394
395
396
397 static int
398 match_dsa_hash (unsigned int qbytes)
399 {
400   if (qbytes <= 20)
401     return DIGEST_ALGO_SHA1;
402
403   if (qbytes <= 28)
404     return DIGEST_ALGO_SHA224;
405
406   if (qbytes <= 32)
407     return DIGEST_ALGO_SHA256;
408
409   if (qbytes <= 48)
410     return DIGEST_ALGO_SHA384;
411
412   if (qbytes <= 66 )    /* 66 corresponds to 521 (64 to 512) */
413     return DIGEST_ALGO_SHA512;
414
415   return DEFAULT_DIGEST_ALGO;
416   /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
417      answer we have if a digest larger than 512 bits is requested.  */
418 }
419
420
421 /*
422   First try --digest-algo.  If that isn't set, see if the recipient
423   has a preferred algorithm (which is also filtered through
424   --personal-digest-prefs).  If we're making a signature without a
425   particular recipient (i.e. signing, rather than signing+encrypting)
426   then take the first algorithm in --personal-digest-prefs that is
427   usable for the pubkey algorithm.  If --personal-digest-prefs isn't
428   set, then take the OpenPGP default (i.e. SHA-1).
429
430   Note that Ed25519+EdDSA takes an input of arbitrary length and thus
431   we don't enforce any particular algorithm like we do for standard
432   ECDSA. However, we use SHA256 as the default algorithm.
433
434   Possible improvement: Use the highest-ranked usable algorithm from
435   the signing key prefs either before or after using the personal
436   list?
437 */
438 static int
439 hash_for (PKT_public_key *pk)
440 {
441   if (opt.def_digest_algo)
442     {
443       return opt.def_digest_algo;
444     }
445   else if (recipient_digest_algo)
446     {
447       return recipient_digest_algo;
448     }
449   else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA
450            && openpgp_oid_is_ed25519 (pk->pkey[0]))
451     {
452       if (opt.personal_digest_prefs)
453         return opt.personal_digest_prefs[0].value;
454       else
455         return DIGEST_ALGO_SHA256;
456     }
457   else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
458            || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
459     {
460       unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
461
462       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
463         qbytes = ecdsa_qbits_from_Q (qbytes);
464       qbytes = qbytes/8;
465
466       /* It's a DSA key, so find a hash that is the same size as q or
467          larger.  If q is 160, assume it is an old DSA key and use a
468          160-bit hash unless --enable-dsa2 is set, in which case act
469          like a new DSA key that just happens to have a 160-bit q
470          (i.e. allow truncation).  If q is not 160, by definition it
471          must be a new DSA key. */
472
473       if (opt.personal_digest_prefs)
474         {
475           prefitem_t *prefs;
476
477           if (qbytes != 20 || opt.flags.dsa2)
478             {
479               for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
480                 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
481                   return prefs->value;
482             }
483           else
484             {
485               for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
486                 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
487                   return prefs->value;
488             }
489         }
490
491       return match_dsa_hash(qbytes);
492     }
493   else if (openpgp_card_v1_p (pk))
494     {
495       /* The sk lives on a smartcard, and old smartcards only handle
496          SHA-1 and RIPEMD/160.  Newer smartcards (v2.0) don't have
497          this restriction anymore.  Fortunately the serial number
498          encodes the version of the card and thus we know that this
499          key is on a v1 card. */
500       if(opt.personal_digest_prefs)
501         {
502           prefitem_t *prefs;
503
504           for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
505             if (prefs->value==DIGEST_ALGO_SHA1
506                 || prefs->value==DIGEST_ALGO_RMD160)
507               return prefs->value;
508         }
509
510       return DIGEST_ALGO_SHA1;
511     }
512   else if (opt.personal_digest_prefs)
513     {
514       /* It's not DSA, so we can use whatever the first hash algorithm
515          is in the pref list */
516       return opt.personal_digest_prefs[0].value;
517     }
518   else
519     return DEFAULT_DIGEST_ALGO;
520 }
521
522
523 static void
524 print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
525 {
526   byte array[MAX_FINGERPRINT_LEN];
527   char buf[100+MAX_FINGERPRINT_LEN*2];
528   size_t n;
529
530   snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
531             what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
532             (ulong)sig->timestamp );
533   fingerprint_from_pk (pk, array, &n);
534   bin2hex (array, n, buf + strlen (buf));
535
536   write_status_text( STATUS_SIG_CREATED, buf );
537 }
538
539
540 /*
541  * Loop over the secret certificates in SK_LIST and build the one pass
542  * signature packets.  OpenPGP says that the data should be bracket by
543  * the onepass-sig and signature-packet; so we build these onepass
544  * packet here in reverse order
545  */
546 static int
547 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
548 {
549     int skcount;
550     SK_LIST sk_rover;
551
552     for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
553         skcount++;
554
555     for (; skcount; skcount--) {
556         PKT_public_key *pk;
557         PKT_onepass_sig *ops;
558         PACKET pkt;
559         int i, rc;
560
561         for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
562             if (++i == skcount)
563                 break;
564         }
565
566         pk = sk_rover->pk;
567         ops = xmalloc_clear (sizeof *ops);
568         ops->sig_class = sigclass;
569         ops->digest_algo = hash_for (pk);
570         ops->pubkey_algo = pk->pubkey_algo;
571         keyid_from_pk (pk, ops->keyid);
572         ops->last = (skcount == 1);
573
574         init_packet(&pkt);
575         pkt.pkttype = PKT_ONEPASS_SIG;
576         pkt.pkt.onepass_sig = ops;
577         rc = build_packet (out, &pkt);
578         free_packet (&pkt);
579         if (rc) {
580             log_error ("build onepass_sig packet failed: %s\n",
581                        gpg_strerror (rc));
582             return rc;
583         }
584     }
585
586     return 0;
587 }
588
589 /*
590  * Helper to write the plaintext (literal data) packet
591  */
592 static int
593 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
594 {
595     PKT_plaintext *pt = NULL;
596     u32 filesize;
597     int rc = 0;
598
599     if (!opt.no_literal)
600       pt=setup_plaintext_name(fname,inp);
601
602     /* try to calculate the length of the data */
603     if ( !iobuf_is_pipe_filename (fname) && *fname )
604       {
605         off_t tmpsize;
606         int overflow;
607
608         if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
609             && !overflow && opt.verbose)
610           log_info (_("WARNING: '%s' is an empty file\n"), fname);
611
612         /* We can't encode the length of very large files because
613            OpenPGP uses only 32 bit for file sizes.  So if the size of
614            a file is larger than 2^32 minus some bytes for packet
615            headers, we switch to partial length encoding. */
616         if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
617           filesize = tmpsize;
618         else
619           filesize = 0;
620
621         /* Because the text_filter modifies the length of the
622          * data, it is not possible to know the used length
623          * without a double read of the file - to avoid that
624          * we simple use partial length packets. */
625         if ( ptmode == 't' )
626           filesize = 0;
627       }
628     else
629       filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
630
631     if (!opt.no_literal) {
632         PACKET pkt;
633
634         pt->timestamp = make_timestamp ();
635         pt->mode = ptmode;
636         pt->len = filesize;
637         pt->new_ctb = !pt->len;
638         pt->buf = inp;
639         init_packet(&pkt);
640         pkt.pkttype = PKT_PLAINTEXT;
641         pkt.pkt.plaintext = pt;
642         /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
643         if( (rc = build_packet (out, &pkt)) )
644             log_error ("build_packet(PLAINTEXT) failed: %s\n",
645                        gpg_strerror (rc) );
646         pt->buf = NULL;
647     }
648     else {
649         byte copy_buffer[4096];
650         int  bytes_copied;
651
652         while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
653             if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
654                 log_error ("copying input to output failed: %s\n",
655                            gpg_strerror (rc));
656                 break;
657             }
658         wipememory(copy_buffer,4096); /* burn buffer */
659     }
660     /* fixme: it seems that we never freed pt/pkt */
661
662     return rc;
663 }
664
665 /*
666  * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
667  * hash which will not be changes here.
668  */
669 static int
670 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
671                          int sigclass, u32 timestamp, u32 duration,
672                          int status_letter, const char *cache_nonce)
673 {
674   SK_LIST sk_rover;
675
676   /* Loop over the certificates with secret keys. */
677   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
678     {
679       PKT_public_key *pk;
680       PKT_signature *sig;
681       gcry_md_hd_t md;
682       int rc;
683
684       pk = sk_rover->pk;
685
686       /* Build the signature packet.  */
687       sig = xmalloc_clear (sizeof *sig);
688       if (duration || opt.sig_policy_url
689           || opt.sig_notations || opt.sig_keyserver_url)
690         sig->version = 4;
691       else
692         sig->version = pk->version;
693
694       keyid_from_pk (pk, sig->keyid);
695       sig->digest_algo = hash_for (pk);
696       sig->pubkey_algo = pk->pubkey_algo;
697       if (timestamp)
698         sig->timestamp = timestamp;
699       else
700         sig->timestamp = make_timestamp();
701       if (duration)
702         sig->expiredate = sig->timestamp + duration;
703       sig->sig_class = sigclass;
704
705       if (gcry_md_copy (&md, hash))
706         BUG ();
707
708       if (sig->version >= 4)
709         {
710           build_sig_subpkt_from_sig (sig);
711           mk_notation_policy_etc (sig, NULL, pk);
712         }
713
714       hash_sigversion_to_magic (md, sig);
715       gcry_md_final (md);
716
717       rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
718       gcry_md_close (md);
719       if (!rc)
720         {
721           /* Write the packet.  */
722           PACKET pkt;
723
724           init_packet (&pkt);
725           pkt.pkttype = PKT_SIGNATURE;
726           pkt.pkt.signature = sig;
727           rc = build_packet (out, &pkt);
728           if (!rc && is_status_enabled())
729             print_status_sig_created (pk, sig, status_letter);
730           free_packet (&pkt);
731           if (rc)
732             log_error ("build signature packet failed: %s\n", gpg_strerror (rc));
733         }
734       if (rc)
735         return rc;
736     }
737
738   return 0;
739 }
740
741
742 /****************
743  * Sign the files whose names are in FILENAME.
744  * If DETACHED has the value true,
745  * make a detached signature.  If FILENAMES->d is NULL read from stdin
746  * and ignore the detached mode.  Sign the file with all secret keys
747  * which can be taken from LOCUSR, if this is NULL, use the default one
748  * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
749  * signed data for these users.
750  * If OUTFILE is not NULL; this file is used for output and the function
751  * does not ask for overwrite permission; output is then always
752  * uncompressed, non-armored and in binary mode.
753  */
754 int
755 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
756            int encryptflag, strlist_t remusr, const char *outfile )
757 {
758     const char *fname;
759     armor_filter_context_t *afx;
760     compress_filter_context_t zfx;
761     md_filter_context_t mfx;
762     text_filter_context_t tfx;
763     progress_filter_context_t *pfx;
764     encrypt_filter_context_t efx;
765     IOBUF inp = NULL, out = NULL;
766     PACKET pkt;
767     int rc = 0;
768     PK_LIST pk_list = NULL;
769     SK_LIST sk_list = NULL;
770     SK_LIST sk_rover = NULL;
771     int multifile = 0;
772     u32 duration=0;
773
774     pfx = new_progress_context ();
775     afx = new_armor_context ();
776     memset( &zfx, 0, sizeof zfx);
777     memset( &mfx, 0, sizeof mfx);
778     memset( &efx, 0, sizeof efx);
779     init_packet( &pkt );
780
781     if( filenames ) {
782         fname = filenames->d;
783         multifile = !!filenames->next;
784     }
785     else
786         fname = NULL;
787
788     if( fname && filenames->next && (!detached || encryptflag) )
789         log_bug("multiple files can only be detached signed");
790
791     if(encryptflag==2
792        && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
793       goto leave;
794
795     if (opt.ask_sig_expire && !opt.batch)
796       duration = ask_expire_interval(1,opt.def_sig_expire);
797     else
798       duration = parse_expire_string(opt.def_sig_expire);
799
800     /* Note: In the old non-agent version the following call used to
801        unprotect the secret key.  This is now done on demand by the agent.  */
802     if( (rc = build_sk_list (locusr, &sk_list, PUBKEY_USAGE_SIG )) )
803         goto leave;
804
805     if (encryptflag
806         && (rc=build_pk_list (ctrl, remusr, &pk_list, PUBKEY_USAGE_ENC)))
807       goto leave;
808
809     /* prepare iobufs */
810     if( multifile )  /* have list of filenames */
811         inp = NULL; /* we do it later */
812     else {
813       inp = iobuf_open(fname);
814       if (inp && is_secured_file (iobuf_get_fd (inp)))
815         {
816           iobuf_close (inp);
817           inp = NULL;
818           gpg_err_set_errno (EPERM);
819         }
820       if( !inp )
821         {
822           rc = gpg_error_from_syserror ();
823           log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
824                      strerror(errno) );
825           goto leave;
826         }
827
828         handle_progress (pfx, inp, fname);
829     }
830
831     if( outfile ) {
832         if (is_secured_filename ( outfile )) {
833             out = NULL;
834             gpg_err_set_errno (EPERM);
835         }
836         else
837           out = iobuf_create (outfile, 0);
838         if( !out )
839           {
840             rc = gpg_error_from_syserror ();
841             log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
842             goto leave;
843           }
844         else if( opt.verbose )
845             log_info(_("writing to '%s'\n"), outfile );
846     }
847     else if( (rc = open_outfile (-1, fname,
848                                  opt.armor? 1: detached? 2:0, 0, &out)))
849         goto leave;
850
851     /* prepare to calculate the MD over the input */
852     if( opt.textmode && !outfile && !multifile )
853       {
854         memset( &tfx, 0, sizeof tfx);
855         iobuf_push_filter( inp, text_filter, &tfx );
856       }
857
858     if ( gcry_md_open (&mfx.md, 0, 0) )
859       BUG ();
860     if (DBG_HASHING)
861       gcry_md_debug (mfx.md, "sign");
862
863     /* If we're encrypting and signing, it is reasonable to pick the
864        hash algorithm to use out of the recipient key prefs.  This is
865        best effort only, as in a DSA2 and smartcard world there are
866        cases where we cannot please everyone with a single hash (DSA2
867        wants >160 and smartcards want =160).  In the future this could
868        be more complex with different hashes for each sk, but the
869        current design requires a single hash for all SKs. */
870     if(pk_list)
871       {
872         if(opt.def_digest_algo)
873           {
874             if(!opt.expert &&
875                select_algo_from_prefs(pk_list,PREFTYPE_HASH,
876                                       opt.def_digest_algo,
877                                       NULL)!=opt.def_digest_algo)
878           log_info(_("WARNING: forcing digest algorithm %s (%d)"
879                      " violates recipient preferences\n"),
880                    gcry_md_algo_name (opt.def_digest_algo),
881                    opt.def_digest_algo );
882           }
883         else
884           {
885             int algo, smartcard=0;
886             union pref_hint hint;
887
888             hint.digest_length = 0;
889
890             /* Of course, if the recipient asks for something
891                unreasonable (like the wrong hash for a DSA key) then
892                don't do it.  Check all sk's - if any are DSA or live
893                on a smartcard, then the hash has restrictions and we
894                may not be able to give the recipient what they want.
895                For DSA, pass a hint for the largest q we have.  Note
896                that this means that a q>160 key will override a q=160
897                key and force the use of truncation for the q=160 key.
898                The alternative would be to ignore the recipient prefs
899                completely and get a different hash for each DSA key in
900                hash_for().  The override behavior here is more or less
901                reasonable as it is under the control of the user which
902                keys they sign with for a given message and the fact
903                that the message with multiple signatures won't be
904                usable on an implementation that doesn't understand
905                DSA2 anyway. */
906
907             for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
908               {
909                 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
910                     || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
911                   {
912                     int temp_hashlen = (gcry_mpi_get_nbits
913                                         (sk_rover->pk->pkey[1]));
914
915                     if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
916                       temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
917                     temp_hashlen = (temp_hashlen+7)/8;
918
919                     /* Pick a hash that is large enough for our
920                        largest q */
921
922                     if (hint.digest_length<temp_hashlen)
923                       hint.digest_length=temp_hashlen;
924                   }
925                 /* FIXME: need to check gpg-agent for this. */
926                 /* else if (sk_rover->pk->is_protected */
927                 /*          && sk_rover->pk->protect.s2k.mode == 1002) */
928                 /*   smartcard = 1;  */
929               }
930
931             /* Current smartcards only do 160-bit hashes.  If we have
932                to have a >160-bit hash, then we can't use the
933                recipient prefs as we'd need both =160 and >160 at the
934                same time and recipient prefs currently require a
935                single hash for all signatures.  All this may well have
936                to change as the cards add algorithms. */
937
938             if (!smartcard || (smartcard && hint.digest_length==20))
939               if ( (algo=
940                    select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
941                 recipient_digest_algo=algo;
942           }
943       }
944
945     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
946       gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
947
948     if( !multifile )
949         iobuf_push_filter( inp, md_filter, &mfx );
950
951     if( detached && !encryptflag)
952         afx->what = 2;
953
954     if( opt.armor && !outfile  )
955         push_armor_filter (afx, out);
956
957     if( encryptflag ) {
958         efx.pk_list = pk_list;
959         /* fixme: set efx.cfx.datalen if known */
960         iobuf_push_filter( out, encrypt_filter, &efx );
961     }
962
963     if (opt.compress_algo && !outfile && !detached)
964       {
965         int compr_algo=opt.compress_algo;
966
967         /* If not forced by user */
968         if(compr_algo==-1)
969           {
970             /* If we're not encrypting, then select_algo_from_prefs
971                will fail and we'll end up with the default.  If we are
972                encrypting, select_algo_from_prefs cannot fail since
973                there is an assumed preference for uncompressed data.
974                Still, if it did fail, we'll also end up with the
975                default. */
976
977             if((compr_algo=
978                 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
979               compr_algo=default_compress_algo();
980           }
981         else if(!opt.expert && pk_list
982                 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
983                                           compr_algo,NULL)!=compr_algo)
984           log_info(_("WARNING: forcing compression algorithm %s (%d)"
985                      " violates recipient preferences\n"),
986                    compress_algo_to_string(compr_algo),compr_algo);
987
988         /* algo 0 means no compression */
989         if( compr_algo )
990           push_compress_filter(out,&zfx,compr_algo);
991       }
992
993     /* Write the one-pass signature packets if needed */
994     if (!detached) {
995         rc = write_onepass_sig_packets (sk_list, out,
996                                         opt.textmode && !outfile ? 0x01:0x00);
997         if (rc)
998             goto leave;
999     }
1000
1001     write_status_begin_signing (mfx.md);
1002
1003     /* Setup the inner packet. */
1004     if( detached ) {
1005         if( multifile ) {
1006             strlist_t sl;
1007
1008             if( opt.verbose )
1009                 log_info(_("signing:") );
1010             /* must walk reverse trough this list */
1011             for( sl = strlist_last(filenames); sl;
1012                         sl = strlist_prev( filenames, sl ) ) {
1013                 inp = iobuf_open(sl->d);
1014                 if (inp && is_secured_file (iobuf_get_fd (inp)))
1015                   {
1016                     iobuf_close (inp);
1017                     inp = NULL;
1018                     gpg_err_set_errno (EPERM);
1019                   }
1020                 if( !inp )
1021                   {
1022                     rc = gpg_error_from_syserror ();
1023                     log_error(_("can't open '%s': %s\n"),
1024                               sl->d,strerror(errno));
1025                     goto leave;
1026                   }
1027                 handle_progress (pfx, inp, sl->d);
1028                 if( opt.verbose )
1029                   log_printf (" '%s'", sl->d );
1030                 if(opt.textmode)
1031                   {
1032                     memset( &tfx, 0, sizeof tfx);
1033                     iobuf_push_filter( inp, text_filter, &tfx );
1034                   }
1035                 iobuf_push_filter( inp, md_filter, &mfx );
1036                 while( iobuf_get(inp) != -1 )
1037                     ;
1038                 iobuf_close(inp); inp = NULL;
1039             }
1040             if( opt.verbose )
1041               log_printf ("\n");
1042         }
1043         else {
1044             /* read, so that the filter can calculate the digest */
1045             while( iobuf_get(inp) != -1 )
1046                 ;
1047         }
1048     }
1049     else {
1050         rc = write_plaintext_packet (out, inp, fname,
1051                                      opt.textmode && !outfile ? 't':'b');
1052     }
1053
1054     /* catch errors from above */
1055     if (rc)
1056         goto leave;
1057
1058     /* write the signatures */
1059     rc = write_signature_packets (sk_list, out, mfx.md,
1060                                   opt.textmode && !outfile? 0x01 : 0x00,
1061                                   0, duration, detached ? 'D':'S', NULL);
1062     if( rc )
1063         goto leave;
1064
1065
1066   leave:
1067     if( rc )
1068         iobuf_cancel(out);
1069     else {
1070         iobuf_close(out);
1071         if (encryptflag)
1072             write_status( STATUS_END_ENCRYPTION );
1073     }
1074     iobuf_close(inp);
1075     gcry_md_close ( mfx.md );
1076     release_sk_list( sk_list );
1077     release_pk_list( pk_list );
1078     recipient_digest_algo=0;
1079     release_progress_context (pfx);
1080     release_armor_context (afx);
1081     return rc;
1082 }
1083
1084
1085
1086 /****************
1087  * make a clear signature. note that opt.armor is not needed
1088  */
1089 int
1090 clearsign_file( const char *fname, strlist_t locusr, const char *outfile )
1091 {
1092     armor_filter_context_t *afx;
1093     progress_filter_context_t *pfx;
1094     gcry_md_hd_t textmd = NULL;
1095     IOBUF inp = NULL, out = NULL;
1096     PACKET pkt;
1097     int rc = 0;
1098     SK_LIST sk_list = NULL;
1099     SK_LIST sk_rover = NULL;
1100     u32 duration=0;
1101
1102     pfx = new_progress_context ();
1103     afx = new_armor_context ();
1104     init_packet( &pkt );
1105
1106     if (opt.ask_sig_expire && !opt.batch)
1107       duration = ask_expire_interval (1,opt.def_sig_expire);
1108     else
1109       duration = parse_expire_string (opt.def_sig_expire);
1110
1111     /* Note: In the old non-agent version the following call used to
1112        unprotect the secret key.  This is now done on demand by the agent.  */
1113     if( (rc=build_sk_list( locusr, &sk_list, PUBKEY_USAGE_SIG )) )
1114         goto leave;
1115
1116     /* prepare iobufs */
1117     inp = iobuf_open(fname);
1118     if (inp && is_secured_file (iobuf_get_fd (inp)))
1119       {
1120         iobuf_close (inp);
1121         inp = NULL;
1122         gpg_err_set_errno (EPERM);
1123       }
1124     if( !inp ) {
1125         rc = gpg_error_from_syserror ();
1126         log_error (_("can't open '%s': %s\n"),
1127                    fname? fname: "[stdin]", strerror(errno) );
1128         goto leave;
1129     }
1130     handle_progress (pfx, inp, fname);
1131
1132     if( outfile ) {
1133         if (is_secured_filename (outfile) ) {
1134             outfile = NULL;
1135             gpg_err_set_errno (EPERM);
1136         }
1137         else
1138           out = iobuf_create (outfile, 0);
1139         if( !out )
1140           {
1141             rc = gpg_error_from_syserror ();
1142             log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
1143             goto leave;
1144           }
1145         else if( opt.verbose )
1146             log_info(_("writing to '%s'\n"), outfile );
1147     }
1148     else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1149         goto leave;
1150
1151     iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1152
1153     {
1154         const char *s;
1155         int any = 0;
1156         byte hashs_seen[256];
1157
1158         memset( hashs_seen, 0, sizeof hashs_seen );
1159         iobuf_writestr(out, "Hash: " );
1160         for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1161             int i = hash_for (sk_rover->pk);
1162
1163             if( !hashs_seen[ i & 0xff ] ) {
1164                 s = gcry_md_algo_name ( i );
1165                 if( s ) {
1166                     hashs_seen[ i & 0xff ] = 1;
1167                     if( any )
1168                         iobuf_put(out, ',' );
1169                     iobuf_writestr(out, s );
1170                     any = 1;
1171                 }
1172             }
1173         }
1174         assert(any);
1175         iobuf_writestr(out, LF );
1176     }
1177
1178     if( opt.not_dash_escaped )
1179       iobuf_writestr( out,
1180                       "NotDashEscaped: You need "GPG_NAME
1181                       " to verify this message" LF );
1182     iobuf_writestr(out, LF );
1183
1184     if ( gcry_md_open (&textmd, 0, 0) )
1185       BUG ();
1186     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1187       gcry_md_enable (textmd, hash_for(sk_rover->pk));
1188
1189     if ( DBG_HASHING )
1190       gcry_md_debug ( textmd, "clearsign" );
1191
1192     copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
1193                         opt.escape_from);
1194     /* fixme: check for read errors */
1195
1196     /* now write the armor */
1197     afx->what = 2;
1198     push_armor_filter (afx, out);
1199
1200     /* Write the signatures.  */
1201     rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
1202                                   NULL);
1203     if( rc )
1204         goto leave;
1205
1206   leave:
1207     if( rc )
1208         iobuf_cancel(out);
1209     else
1210         iobuf_close(out);
1211     iobuf_close(inp);
1212     gcry_md_close ( textmd );
1213     release_sk_list( sk_list );
1214     release_progress_context (pfx);
1215     release_armor_context (afx);
1216     return rc;
1217 }
1218
1219 /*
1220  * Sign and conventionally encrypt the given file.
1221  * FIXME: Far too much code is duplicated - revamp the whole file.
1222  */
1223 int
1224 sign_symencrypt_file (const char *fname, strlist_t locusr)
1225 {
1226     armor_filter_context_t *afx;
1227     progress_filter_context_t *pfx;
1228     compress_filter_context_t zfx;
1229     md_filter_context_t mfx;
1230     text_filter_context_t tfx;
1231     cipher_filter_context_t cfx;
1232     IOBUF inp = NULL, out = NULL;
1233     PACKET pkt;
1234     STRING2KEY *s2k = NULL;
1235     int rc = 0;
1236     SK_LIST sk_list = NULL;
1237     SK_LIST sk_rover = NULL;
1238     int algo;
1239     u32 duration=0;
1240     int canceled;
1241
1242     pfx = new_progress_context ();
1243     afx = new_armor_context ();
1244     memset( &zfx, 0, sizeof zfx);
1245     memset( &mfx, 0, sizeof mfx);
1246     memset( &tfx, 0, sizeof tfx);
1247     memset( &cfx, 0, sizeof cfx);
1248     init_packet( &pkt );
1249
1250     if (opt.ask_sig_expire && !opt.batch)
1251       duration = ask_expire_interval (1, opt.def_sig_expire);
1252     else
1253       duration = parse_expire_string (opt.def_sig_expire);
1254
1255     /* Note: In the old non-agent version the following call used to
1256        unprotect the secret key.  This is now done on demand by the agent.  */
1257     rc = build_sk_list (locusr, &sk_list, PUBKEY_USAGE_SIG);
1258     if (rc)
1259         goto leave;
1260
1261     /* prepare iobufs */
1262     inp = iobuf_open(fname);
1263     if (inp && is_secured_file (iobuf_get_fd (inp)))
1264       {
1265         iobuf_close (inp);
1266         inp = NULL;
1267         gpg_err_set_errno (EPERM);
1268       }
1269     if( !inp ) {
1270         rc = gpg_error_from_syserror ();
1271         log_error (_("can't open '%s': %s\n"),
1272                    fname? fname: "[stdin]", strerror(errno) );
1273         goto leave;
1274     }
1275     handle_progress (pfx, inp, fname);
1276
1277     /* prepare key */
1278     s2k = xmalloc_clear( sizeof *s2k );
1279     s2k->mode = opt.s2k_mode;
1280     s2k->hash_algo = S2K_DIGEST_ALGO;
1281
1282     algo = default_cipher_algo();
1283     if (!opt.quiet || !opt.batch)
1284         log_info (_("%s encryption will be used\n"),
1285                   openpgp_cipher_algo_name (algo) );
1286     cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
1287
1288     if (!cfx.dek || !cfx.dek->keylen) {
1289         rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1290         log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1291         goto leave;
1292     }
1293
1294     /* We have no way to tell if the recipient can handle messages
1295        with an MDC, so this defaults to no.  Perhaps in a few years,
1296        this can be defaulted to yes.  Note that like regular
1297        encrypting, --force-mdc overrides --disable-mdc. */
1298     if(opt.force_mdc)
1299       cfx.dek->use_mdc=1;
1300
1301     /* now create the outfile */
1302     rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1303     if (rc)
1304         goto leave;
1305
1306     /* prepare to calculate the MD over the input */
1307     if (opt.textmode)
1308         iobuf_push_filter (inp, text_filter, &tfx);
1309     if ( gcry_md_open (&mfx.md, 0, 0) )
1310       BUG ();
1311     if ( DBG_HASHING )
1312       gcry_md_debug (mfx.md, "symc-sign");
1313
1314     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1315       gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1316
1317     iobuf_push_filter (inp, md_filter, &mfx);
1318
1319     /* Push armor output filter */
1320     if (opt.armor)
1321         push_armor_filter (afx, out);
1322
1323     /* Write the symmetric key packet */
1324     /*(current filters: armor)*/
1325     {
1326         PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1327         enc->version = 4;
1328         enc->cipher_algo = cfx.dek->algo;
1329         enc->s2k = *s2k;
1330         pkt.pkttype = PKT_SYMKEY_ENC;
1331         pkt.pkt.symkey_enc = enc;
1332         if( (rc = build_packet( out, &pkt )) )
1333             log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
1334         xfree(enc);
1335     }
1336
1337     /* Push the encryption filter */
1338     iobuf_push_filter( out, cipher_filter, &cfx );
1339
1340     /* Push the compress filter */
1341     if (default_compress_algo())
1342       push_compress_filter(out,&zfx,default_compress_algo());
1343
1344     /* Write the one-pass signature packets */
1345     /*(current filters: zip - encrypt - armor)*/
1346     rc = write_onepass_sig_packets (sk_list, out,
1347                                     opt.textmode? 0x01:0x00);
1348     if (rc)
1349       goto leave;
1350
1351     write_status_begin_signing (mfx.md);
1352
1353     /* Pipe data through all filters; i.e. write the signed stuff */
1354     /*(current filters: zip - encrypt - armor)*/
1355     rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1356     if (rc)
1357         goto leave;
1358
1359     /* Write the signatures */
1360     /*(current filters: zip - encrypt - armor)*/
1361     rc = write_signature_packets (sk_list, out, mfx.md,
1362                                   opt.textmode? 0x01 : 0x00,
1363                                   0, duration, 'S', NULL);
1364     if( rc )
1365         goto leave;
1366
1367
1368   leave:
1369     if( rc )
1370         iobuf_cancel(out);
1371     else {
1372         iobuf_close(out);
1373         write_status( STATUS_END_ENCRYPTION );
1374     }
1375     iobuf_close(inp);
1376     release_sk_list( sk_list );
1377     gcry_md_close( mfx.md );
1378     xfree(cfx.dek);
1379     xfree(s2k);
1380     release_progress_context (pfx);
1381     release_armor_context (afx);
1382     return rc;
1383 }
1384
1385
1386 /****************
1387  * Create a signature packet for the given public key certificate and
1388  * the user id and return it in ret_sig. User signature class SIGCLASS
1389  * user-id is not used (and may be NULL if sigclass is 0x20) If
1390  * DIGEST_ALGO is 0 the function selects an appropriate one.
1391  * SIGVERSION gives the minimal required signature packet version;
1392  * this is needed so that special properties like local sign are not
1393  * applied (actually: dropped) when a v3 key is used.  TIMESTAMP is
1394  * the timestamp to use for the signature. 0 means "now" */
1395 int
1396 make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
1397                     PKT_user_id *uid, PKT_public_key *subpk,
1398                     PKT_public_key *pksk,
1399                     int sigclass, int digest_algo,
1400                     u32 timestamp, u32 duration,
1401                     int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1402                     const char *cache_nonce)
1403 {
1404     PKT_signature *sig;
1405     int rc=0;
1406     int sigversion;
1407     gcry_md_hd_t md;
1408
1409     assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1410             || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1411             || sigclass == 0x30 || sigclass == 0x28 );
1412
1413     sigversion = 4;
1414     if (sigversion < pksk->version)
1415         sigversion = pksk->version;
1416
1417     if( !digest_algo )
1418       {
1419         /* Basically, this means use SHA1 always unless the user
1420            specified something (use whatever they said), or it's DSA
1421            (use the best match).  They still can't pick an
1422            inappropriate hash for DSA or the signature will fail.
1423            Note that this still allows the caller of
1424            make_keysig_packet to override the user setting if it
1425            must. */
1426
1427         if(opt.cert_digest_algo)
1428           digest_algo=opt.cert_digest_algo;
1429         else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
1430           digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1431         else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1432                  || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1433           {
1434             if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
1435               digest_algo = DIGEST_ALGO_SHA256;
1436             else
1437               digest_algo = match_dsa_hash
1438                 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1439           }
1440         else
1441           digest_algo = DEFAULT_DIGEST_ALGO;
1442       }
1443
1444     if ( gcry_md_open (&md, digest_algo, 0 ) )
1445       BUG ();
1446
1447     /* Hash the public key certificate. */
1448     hash_public_key( md, pk );
1449
1450     if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1451       {
1452         /* hash the subkey binding/backsig/revocation */
1453         hash_public_key( md, subpk );
1454       }
1455     else if( sigclass != 0x1F && sigclass != 0x20 )
1456       {
1457         /* hash the user id */
1458         hash_uid (md, sigversion, uid);
1459       }
1460     /* and make the signature packet */
1461     sig = xmalloc_clear( sizeof *sig );
1462     sig->version = sigversion;
1463     sig->flags.exportable=1;
1464     sig->flags.revocable=1;
1465     keyid_from_pk (pksk, sig->keyid);
1466     sig->pubkey_algo = pksk->pubkey_algo;
1467     sig->digest_algo = digest_algo;
1468     if(timestamp)
1469       sig->timestamp=timestamp;
1470     else
1471       sig->timestamp=make_timestamp();
1472     if(duration)
1473       sig->expiredate=sig->timestamp+duration;
1474     sig->sig_class = sigclass;
1475
1476     build_sig_subpkt_from_sig( sig );
1477     mk_notation_policy_etc (sig, pk, pksk);
1478
1479     /* Crucial that the call to mksubpkt comes LAST before the calls
1480        to finalize the sig as that makes it possible for the mksubpkt
1481        function to get a reliable pointer to the subpacket area. */
1482     if (mksubpkt)
1483         rc = (*mksubpkt)( sig, opaque );
1484
1485     if( !rc ) {
1486         hash_sigversion_to_magic (md, sig);
1487         gcry_md_final (md);
1488
1489         rc = complete_sig (sig, pksk, md, cache_nonce);
1490     }
1491
1492     gcry_md_close (md);
1493     if( rc )
1494         free_seckey_enc( sig );
1495     else
1496         *ret_sig = sig;
1497     return rc;
1498 }
1499
1500
1501
1502 /****************
1503  * Create a new signature packet based on an existing one.
1504  * Only user ID signatures are supported for now.
1505  * PK is the public key to work on.
1506  * PKSK is the key used to make the signature.
1507  *
1508  * TODO: Merge this with make_keysig_packet.
1509  */
1510 int
1511 update_keysig_packet( PKT_signature **ret_sig,
1512                       PKT_signature *orig_sig,
1513                       PKT_public_key *pk,
1514                       PKT_user_id *uid,
1515                       PKT_public_key *subpk,
1516                       PKT_public_key *pksk,
1517                       int (*mksubpkt)(PKT_signature *, void *),
1518                       void *opaque)
1519 {
1520     PKT_signature *sig;
1521     int rc = 0;
1522     int digest_algo;
1523     gcry_md_hd_t md;
1524
1525     if ((!orig_sig || !pk || !pksk)
1526         || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1527         || (orig_sig->sig_class == 0x18 && !subpk))
1528       return GPG_ERR_GENERAL;
1529
1530     if ( opt.cert_digest_algo )
1531       digest_algo = opt.cert_digest_algo;
1532     else
1533       digest_algo = orig_sig->digest_algo;
1534
1535     if ( gcry_md_open (&md, digest_algo, 0 ) )
1536       BUG ();
1537
1538     /* Hash the public key certificate and the user id. */
1539     hash_public_key( md, pk );
1540
1541     if( orig_sig->sig_class == 0x18 )
1542       hash_public_key( md, subpk );
1543     else
1544       hash_uid (md, orig_sig->version, uid);
1545
1546     /* create a new signature packet */
1547     sig = copy_signature (NULL, orig_sig);
1548
1549     sig->digest_algo=digest_algo;
1550
1551     /* We need to create a new timestamp so that new sig expiration
1552        calculations are done correctly... */
1553     sig->timestamp=make_timestamp();
1554
1555     /* ... but we won't make a timestamp earlier than the existing
1556        one. */
1557     while(sig->timestamp<=orig_sig->timestamp)
1558       {
1559         gnupg_sleep (1);
1560         sig->timestamp=make_timestamp();
1561       }
1562
1563     /* Note that already expired sigs will remain expired (with a
1564        duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1565        detects this case. */
1566
1567     /* Put the updated timestamp into the sig.  Note that this will
1568        automagically lower any sig expiration dates to correctly
1569        correspond to the differences in the timestamps (i.e. the
1570        duration will shrink).  */
1571     build_sig_subpkt_from_sig( sig );
1572
1573     if (mksubpkt)
1574       rc = (*mksubpkt)(sig, opaque);
1575
1576     if (!rc) {
1577         hash_sigversion_to_magic (md, sig);
1578         gcry_md_final (md);
1579
1580         rc = complete_sig (sig, pksk, md, NULL);
1581     }
1582
1583     gcry_md_close (md);
1584     if( rc )
1585         free_seckey_enc (sig);
1586     else
1587         *ret_sig = sig;
1588     return rc;
1589 }