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