chiark / gitweb /
dirmngr: Fix error handling.
[gnupg2.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 <https://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           xfree (mbox);
160         }
161       else if (opt.sender_list)
162         {
163           /* If a list of --sender was given we scan that list and use
164            * the first one matching a user id of the current key.  */
165
166           /* FIXME: We need to get the list of user ids for the PKSK
167            * packet.  That requires either a function to look it up
168            * again or we need to extend the key packet struct to link
169            * to the primary key which in turn could link to the user
170            * ids.  Too much of a change right now.  Let's take just
171            * one from the supplied list and hope that the caller
172            * passed a matching one.  */
173           build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
174                             opt.sender_list->d, strlen (opt.sender_list->d));
175         }
176     }
177 }
178
179
180 /*
181  * Helper to hash a user ID packet.
182  */
183 static void
184 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
185 {
186   byte buf[5];
187
188   (void)sigversion;
189
190   if (uid->attrib_data)
191     {
192       buf[0] = 0xd1;                   /* Indicates an attribute packet.  */
193       buf[1] = uid->attrib_len >> 24;  /* Always use 4 length bytes.  */
194       buf[2] = uid->attrib_len >> 16;
195       buf[3] = uid->attrib_len >>  8;
196       buf[4] = uid->attrib_len;
197     }
198   else
199     {
200       buf[0] = 0xb4;                   /* Indicates a userid packet.  */
201       buf[1] = uid->len >> 24;         /* Always use 4 length bytes.  */
202       buf[2] = uid->len >> 16;
203       buf[3] = uid->len >>  8;
204       buf[4] = uid->len;
205     }
206   gcry_md_write( md, buf, 5 );
207
208   if (uid->attrib_data)
209     gcry_md_write (md, uid->attrib_data, uid->attrib_len );
210   else
211     gcry_md_write (md, uid->name, uid->len );
212 }
213
214
215 /*
216  * Helper to hash some parts from the signature
217  */
218 static void
219 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
220 {
221   byte buf[6];
222   size_t n;
223
224   gcry_md_putc (md, sig->version);
225   gcry_md_putc (md, sig->sig_class);
226   gcry_md_putc (md, sig->pubkey_algo);
227   gcry_md_putc (md, sig->digest_algo);
228   if (sig->hashed)
229     {
230       n = sig->hashed->len;
231       gcry_md_putc (md, (n >> 8) );
232       gcry_md_putc (md,  n       );
233       gcry_md_write (md, sig->hashed->data, n );
234       n += 6;
235     }
236   else
237     {
238       gcry_md_putc (md, 0);  /* Always hash the length of the subpacket.  */
239       gcry_md_putc (md, 0);
240       n = 6;
241     }
242   /* Add some magic.  */
243   buf[0] = sig->version;
244   buf[1] = 0xff;
245   buf[2] = n >> 24;         /* (n is only 16 bit, so this is always 0) */
246   buf[3] = n >> 16;
247   buf[4] = n >>  8;
248   buf[5] = n;
249   gcry_md_write (md, buf, 6);
250 }
251
252
253 /* Perform the sign operation.  If CACHE_NONCE is given the agent is
254    advised to use that cached passphrase fro the key.  */
255 static int
256 do_sign (PKT_public_key *pksk, PKT_signature *sig,
257          gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
258 {
259   gpg_error_t err;
260   byte *dp;
261   char *hexgrip;
262
263   if (pksk->timestamp > sig->timestamp )
264     {
265       ulong d = pksk->timestamp - sig->timestamp;
266       log_info (ngettext("key %s was created %lu second"
267                          " in the future (time warp or clock problem)\n",
268                          "key %s was created %lu seconds"
269                          " in the future (time warp or clock problem)\n",
270                          d), keystr_from_pk (pksk), d);
271       if (!opt.ignore_time_conflict)
272         return gpg_error (GPG_ERR_TIME_CONFLICT);
273     }
274
275   print_pubkey_algo_note (pksk->pubkey_algo);
276
277   if (!mdalgo)
278     mdalgo = gcry_md_get_algo (md);
279
280   print_digest_algo_note (mdalgo);
281   dp = gcry_md_read  (md, mdalgo);
282   sig->digest_algo = mdalgo;
283   sig->digest_start[0] = dp[0];
284   sig->digest_start[1] = dp[1];
285   mpi_release (sig->data[0]);
286   sig->data[0] = NULL;
287   mpi_release (sig->data[1]);
288   sig->data[1] = NULL;
289
290
291   err = hexkeygrip_from_pk (pksk, &hexgrip);
292   if (!err)
293     {
294       char *desc;
295       gcry_sexp_t s_sigval;
296
297       desc = gpg_format_keydesc (pksk, FORMAT_KEYDESC_NORMAL, 1);
298       err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
299                           pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
300                           dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
301                           &s_sigval);
302       xfree (desc);
303
304       if (err)
305         ;
306       else if (pksk->pubkey_algo == GCRY_PK_RSA
307                || pksk->pubkey_algo == GCRY_PK_RSA_S)
308         sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
309       else if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
310         {
311           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE);
312           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE);
313         }
314       else
315         {
316           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
317           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
318         }
319
320       gcry_sexp_release (s_sigval);
321     }
322   xfree (hexgrip);
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, NULL);
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' || ptmode == 'u' || ptmode == 'm')
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         /* Note that PT has been initialized above in no_literal mode.  */
635         pt->timestamp = make_timestamp ();
636         pt->mode = ptmode;
637         pt->len = filesize;
638         pt->new_ctb = !pt->len;
639         pt->buf = inp;
640         init_packet(&pkt);
641         pkt.pkttype = PKT_PLAINTEXT;
642         pkt.pkt.plaintext = pt;
643         /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
644         if( (rc = build_packet (out, &pkt)) )
645             log_error ("build_packet(PLAINTEXT) failed: %s\n",
646                        gpg_strerror (rc) );
647         pt->buf = NULL;
648         free_packet (&pkt);
649     }
650     else {
651         byte copy_buffer[4096];
652         int  bytes_copied;
653
654         while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
655             if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
656                 log_error ("copying input to output failed: %s\n",
657                            gpg_strerror (rc));
658                 break;
659             }
660         wipememory(copy_buffer,4096); /* burn buffer */
661     }
662     /* fixme: it seems that we never freed pt/pkt */
663
664     return rc;
665 }
666
667 /*
668  * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
669  * hash which will not be changes here.
670  */
671 static int
672 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
673                          int sigclass, u32 timestamp, u32 duration,
674                          int status_letter, const char *cache_nonce)
675 {
676   SK_LIST sk_rover;
677
678   /* Loop over the certificates with secret keys. */
679   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
680     {
681       PKT_public_key *pk;
682       PKT_signature *sig;
683       gcry_md_hd_t md;
684       int rc;
685
686       pk = sk_rover->pk;
687
688       /* Build the signature packet.  */
689       sig = xtrycalloc (1, sizeof *sig);
690       if (!sig)
691         return gpg_error_from_syserror ();
692
693       if (duration || opt.sig_policy_url
694           || opt.sig_notations || opt.sig_keyserver_url)
695         sig->version = 4;
696       else
697         sig->version = pk->version;
698
699       keyid_from_pk (pk, sig->keyid);
700       sig->digest_algo = hash_for (pk);
701       sig->pubkey_algo = pk->pubkey_algo;
702       if (timestamp)
703         sig->timestamp = timestamp;
704       else
705         sig->timestamp = make_timestamp();
706       if (duration)
707         sig->expiredate = sig->timestamp + duration;
708       sig->sig_class = sigclass;
709
710       if (gcry_md_copy (&md, hash))
711         BUG ();
712
713       if (sig->version >= 4)
714         {
715           build_sig_subpkt_from_sig (sig, pk);
716           mk_notation_policy_etc (sig, NULL, pk);
717         }
718
719       hash_sigversion_to_magic (md, sig);
720       gcry_md_final (md);
721
722       rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
723       gcry_md_close (md);
724       if (!rc)
725         {
726           /* Write the packet.  */
727           PACKET pkt;
728
729           init_packet (&pkt);
730           pkt.pkttype = PKT_SIGNATURE;
731           pkt.pkt.signature = sig;
732           rc = build_packet (out, &pkt);
733           if (!rc && is_status_enabled())
734             print_status_sig_created (pk, sig, status_letter);
735           free_packet (&pkt);
736           if (rc)
737             log_error ("build signature packet failed: %s\n",
738                        gpg_strerror (rc));
739         }
740       else
741         xfree (sig);
742
743       if (rc)
744         return rc;
745     }
746
747   return 0;
748 }
749
750
751 /****************
752  * Sign the files whose names are in FILENAME.
753  * If DETACHED has the value true,
754  * make a detached signature.  If FILENAMES->d is NULL read from stdin
755  * and ignore the detached mode.  Sign the file with all secret keys
756  * which can be taken from LOCUSR, if this is NULL, use the default one
757  * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
758  * signed data for these users.
759  * If OUTFILE is not NULL; this file is used for output and the function
760  * does not ask for overwrite permission; output is then always
761  * uncompressed, non-armored and in binary mode.
762  */
763 int
764 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
765            int encryptflag, strlist_t remusr, const char *outfile )
766 {
767     const char *fname;
768     armor_filter_context_t *afx;
769     compress_filter_context_t zfx;
770     md_filter_context_t mfx;
771     text_filter_context_t tfx;
772     progress_filter_context_t *pfx;
773     encrypt_filter_context_t efx;
774     IOBUF inp = NULL, out = NULL;
775     PACKET pkt;
776     int rc = 0;
777     PK_LIST pk_list = NULL;
778     SK_LIST sk_list = NULL;
779     SK_LIST sk_rover = NULL;
780     int multifile = 0;
781     u32 duration=0;
782
783     pfx = new_progress_context ();
784     afx = new_armor_context ();
785     memset( &zfx, 0, sizeof zfx);
786     memset( &mfx, 0, sizeof mfx);
787     memset( &efx, 0, sizeof efx);
788     init_packet( &pkt );
789
790     if( filenames ) {
791         fname = filenames->d;
792         multifile = !!filenames->next;
793     }
794     else
795         fname = NULL;
796
797     if( fname && filenames->next && (!detached || encryptflag) )
798         log_bug("multiple files can only be detached signed");
799
800     if(encryptflag==2
801        && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
802       goto leave;
803
804     if (opt.ask_sig_expire && !opt.batch)
805       duration = ask_expire_interval(1,opt.def_sig_expire);
806     else
807       duration = parse_expire_string(opt.def_sig_expire);
808
809     /* Note: In the old non-agent version the following call used to
810        unprotect the secret key.  This is now done on demand by the agent.  */
811     if( (rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
812         goto leave;
813
814     if (encryptflag
815         && (rc=build_pk_list (ctrl, remusr, &pk_list)))
816       goto leave;
817
818     /* prepare iobufs */
819     if( multifile )  /* have list of filenames */
820         inp = NULL; /* we do it later */
821     else {
822       inp = iobuf_open(fname);
823       if (inp && is_secured_file (iobuf_get_fd (inp)))
824         {
825           iobuf_close (inp);
826           inp = NULL;
827           gpg_err_set_errno (EPERM);
828         }
829       if( !inp )
830         {
831           rc = gpg_error_from_syserror ();
832           log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
833                      strerror(errno) );
834           goto leave;
835         }
836
837         handle_progress (pfx, inp, fname);
838     }
839
840     if( outfile ) {
841         if (is_secured_filename ( outfile )) {
842             out = NULL;
843             gpg_err_set_errno (EPERM);
844         }
845         else
846           out = iobuf_create (outfile, 0);
847         if( !out )
848           {
849             rc = gpg_error_from_syserror ();
850             log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
851             goto leave;
852           }
853         else if( opt.verbose )
854             log_info(_("writing to '%s'\n"), outfile );
855     }
856     else if( (rc = open_outfile (-1, fname,
857                                  opt.armor? 1: detached? 2:0, 0, &out)))
858         goto leave;
859
860     /* prepare to calculate the MD over the input */
861     if( opt.textmode && !outfile && !multifile )
862       {
863         memset( &tfx, 0, sizeof tfx);
864         iobuf_push_filter( inp, text_filter, &tfx );
865       }
866
867     if ( gcry_md_open (&mfx.md, 0, 0) )
868       BUG ();
869     if (DBG_HASHING)
870       gcry_md_debug (mfx.md, "sign");
871
872     /* If we're encrypting and signing, it is reasonable to pick the
873        hash algorithm to use out of the recipient key prefs.  This is
874        best effort only, as in a DSA2 and smartcard world there are
875        cases where we cannot please everyone with a single hash (DSA2
876        wants >160 and smartcards want =160).  In the future this could
877        be more complex with different hashes for each sk, but the
878        current design requires a single hash for all SKs. */
879     if(pk_list)
880       {
881         if(opt.def_digest_algo)
882           {
883             if(!opt.expert &&
884                select_algo_from_prefs(pk_list,PREFTYPE_HASH,
885                                       opt.def_digest_algo,
886                                       NULL)!=opt.def_digest_algo)
887           log_info(_("WARNING: forcing digest algorithm %s (%d)"
888                      " violates recipient preferences\n"),
889                    gcry_md_algo_name (opt.def_digest_algo),
890                    opt.def_digest_algo );
891           }
892         else
893           {
894             int algo, smartcard=0;
895             union pref_hint hint;
896
897             hint.digest_length = 0;
898
899             /* Of course, if the recipient asks for something
900                unreasonable (like the wrong hash for a DSA key) then
901                don't do it.  Check all sk's - if any are DSA or live
902                on a smartcard, then the hash has restrictions and we
903                may not be able to give the recipient what they want.
904                For DSA, pass a hint for the largest q we have.  Note
905                that this means that a q>160 key will override a q=160
906                key and force the use of truncation for the q=160 key.
907                The alternative would be to ignore the recipient prefs
908                completely and get a different hash for each DSA key in
909                hash_for().  The override behavior here is more or less
910                reasonable as it is under the control of the user which
911                keys they sign with for a given message and the fact
912                that the message with multiple signatures won't be
913                usable on an implementation that doesn't understand
914                DSA2 anyway. */
915
916             for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
917               {
918                 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
919                     || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
920                   {
921                     int temp_hashlen = (gcry_mpi_get_nbits
922                                         (sk_rover->pk->pkey[1]));
923
924                     if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
925                       temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
926                     temp_hashlen = (temp_hashlen+7)/8;
927
928                     /* Pick a hash that is large enough for our
929                        largest q */
930
931                     if (hint.digest_length<temp_hashlen)
932                       hint.digest_length=temp_hashlen;
933                   }
934                 /* FIXME: need to check gpg-agent for this. */
935                 /* else if (sk_rover->pk->is_protected */
936                 /*          && sk_rover->pk->protect.s2k.mode == 1002) */
937                 /*   smartcard = 1;  */
938               }
939
940             /* Current smartcards only do 160-bit hashes.  If we have
941                to have a >160-bit hash, then we can't use the
942                recipient prefs as we'd need both =160 and >160 at the
943                same time and recipient prefs currently require a
944                single hash for all signatures.  All this may well have
945                to change as the cards add algorithms. */
946
947             if (!smartcard || (smartcard && hint.digest_length==20))
948               if ( (algo=
949                    select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
950                 recipient_digest_algo=algo;
951           }
952       }
953
954     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
955       gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
956
957     if( !multifile )
958         iobuf_push_filter( inp, md_filter, &mfx );
959
960     if( detached && !encryptflag)
961         afx->what = 2;
962
963     if( opt.armor && !outfile  )
964         push_armor_filter (afx, out);
965
966     if( encryptflag ) {
967         efx.pk_list = pk_list;
968         /* fixme: set efx.cfx.datalen if known */
969         iobuf_push_filter( out, encrypt_filter, &efx );
970     }
971
972     if (opt.compress_algo && !outfile && !detached)
973       {
974         int compr_algo=opt.compress_algo;
975
976         /* If not forced by user */
977         if(compr_algo==-1)
978           {
979             /* If we're not encrypting, then select_algo_from_prefs
980                will fail and we'll end up with the default.  If we are
981                encrypting, select_algo_from_prefs cannot fail since
982                there is an assumed preference for uncompressed data.
983                Still, if it did fail, we'll also end up with the
984                default. */
985
986             if((compr_algo=
987                 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
988               compr_algo=default_compress_algo();
989           }
990         else if(!opt.expert && pk_list
991                 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
992                                           compr_algo,NULL)!=compr_algo)
993           log_info(_("WARNING: forcing compression algorithm %s (%d)"
994                      " violates recipient preferences\n"),
995                    compress_algo_to_string(compr_algo),compr_algo);
996
997         /* algo 0 means no compression */
998         if( compr_algo )
999           push_compress_filter(out,&zfx,compr_algo);
1000       }
1001
1002     /* Write the one-pass signature packets if needed */
1003     if (!detached) {
1004         rc = write_onepass_sig_packets (sk_list, out,
1005                                         opt.textmode && !outfile ? 0x01:0x00);
1006         if (rc)
1007             goto leave;
1008     }
1009
1010     write_status_begin_signing (mfx.md);
1011
1012     /* Setup the inner packet. */
1013     if( detached ) {
1014         if( multifile ) {
1015             strlist_t sl;
1016
1017             if( opt.verbose )
1018                 log_info(_("signing:") );
1019             /* must walk reverse trough this list */
1020             for( sl = strlist_last(filenames); sl;
1021                         sl = strlist_prev( filenames, sl ) ) {
1022                 inp = iobuf_open(sl->d);
1023                 if (inp && is_secured_file (iobuf_get_fd (inp)))
1024                   {
1025                     iobuf_close (inp);
1026                     inp = NULL;
1027                     gpg_err_set_errno (EPERM);
1028                   }
1029                 if( !inp )
1030                   {
1031                     rc = gpg_error_from_syserror ();
1032                     log_error(_("can't open '%s': %s\n"),
1033                               sl->d,strerror(errno));
1034                     goto leave;
1035                   }
1036                 handle_progress (pfx, inp, sl->d);
1037                 if( opt.verbose )
1038                   log_printf (" '%s'", sl->d );
1039                 if(opt.textmode)
1040                   {
1041                     memset( &tfx, 0, sizeof tfx);
1042                     iobuf_push_filter( inp, text_filter, &tfx );
1043                   }
1044                 iobuf_push_filter( inp, md_filter, &mfx );
1045                 while( iobuf_get(inp) != -1 )
1046                     ;
1047                 iobuf_close(inp); inp = NULL;
1048             }
1049             if( opt.verbose )
1050               log_printf ("\n");
1051         }
1052         else {
1053             /* read, so that the filter can calculate the digest */
1054             while( iobuf_get(inp) != -1 )
1055                 ;
1056         }
1057     }
1058     else {
1059         rc = write_plaintext_packet (out, inp, fname,
1060                                      opt.textmode && !outfile ?
1061                                      (opt.mimemode? 'm':'t'):'b');
1062     }
1063
1064     /* catch errors from above */
1065     if (rc)
1066         goto leave;
1067
1068     /* write the signatures */
1069     rc = write_signature_packets (sk_list, out, mfx.md,
1070                                   opt.textmode && !outfile? 0x01 : 0x00,
1071                                   0, duration, detached ? 'D':'S', NULL);
1072     if( rc )
1073         goto leave;
1074
1075
1076   leave:
1077     if( rc )
1078         iobuf_cancel(out);
1079     else {
1080         iobuf_close(out);
1081         if (encryptflag)
1082             write_status( STATUS_END_ENCRYPTION );
1083     }
1084     iobuf_close(inp);
1085     gcry_md_close ( mfx.md );
1086     release_sk_list( sk_list );
1087     release_pk_list( pk_list );
1088     recipient_digest_algo=0;
1089     release_progress_context (pfx);
1090     release_armor_context (afx);
1091     return rc;
1092 }
1093
1094
1095
1096 /****************
1097  * make a clear signature. note that opt.armor is not needed
1098  */
1099 int
1100 clearsign_file (ctrl_t ctrl,
1101                 const char *fname, strlist_t locusr, const char *outfile )
1102 {
1103     armor_filter_context_t *afx;
1104     progress_filter_context_t *pfx;
1105     gcry_md_hd_t textmd = NULL;
1106     IOBUF inp = NULL, out = NULL;
1107     PACKET pkt;
1108     int rc = 0;
1109     SK_LIST sk_list = NULL;
1110     SK_LIST sk_rover = NULL;
1111     u32 duration=0;
1112
1113     pfx = new_progress_context ();
1114     afx = new_armor_context ();
1115     init_packet( &pkt );
1116
1117     if (opt.ask_sig_expire && !opt.batch)
1118       duration = ask_expire_interval (1,opt.def_sig_expire);
1119     else
1120       duration = parse_expire_string (opt.def_sig_expire);
1121
1122     /* Note: In the old non-agent version the following call used to
1123        unprotect the secret key.  This is now done on demand by the agent.  */
1124     if( (rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
1125         goto leave;
1126
1127     /* prepare iobufs */
1128     inp = iobuf_open(fname);
1129     if (inp && is_secured_file (iobuf_get_fd (inp)))
1130       {
1131         iobuf_close (inp);
1132         inp = NULL;
1133         gpg_err_set_errno (EPERM);
1134       }
1135     if( !inp ) {
1136         rc = gpg_error_from_syserror ();
1137         log_error (_("can't open '%s': %s\n"),
1138                    fname? fname: "[stdin]", strerror(errno) );
1139         goto leave;
1140     }
1141     handle_progress (pfx, inp, fname);
1142
1143     if( outfile ) {
1144         if (is_secured_filename (outfile) ) {
1145             outfile = NULL;
1146             gpg_err_set_errno (EPERM);
1147         }
1148         else
1149           out = iobuf_create (outfile, 0);
1150         if( !out )
1151           {
1152             rc = gpg_error_from_syserror ();
1153             log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
1154             goto leave;
1155           }
1156         else if( opt.verbose )
1157             log_info(_("writing to '%s'\n"), outfile );
1158     }
1159     else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1160         goto leave;
1161
1162     iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1163
1164     {
1165         const char *s;
1166         int any = 0;
1167         byte hashs_seen[256];
1168
1169         memset( hashs_seen, 0, sizeof hashs_seen );
1170         iobuf_writestr(out, "Hash: " );
1171         for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1172             int i = hash_for (sk_rover->pk);
1173
1174             if( !hashs_seen[ i & 0xff ] ) {
1175                 s = gcry_md_algo_name ( i );
1176                 if( s ) {
1177                     hashs_seen[ i & 0xff ] = 1;
1178                     if( any )
1179                         iobuf_put(out, ',' );
1180                     iobuf_writestr(out, s );
1181                     any = 1;
1182                 }
1183             }
1184         }
1185         log_assert(any);
1186         iobuf_writestr(out, LF );
1187     }
1188
1189     if( opt.not_dash_escaped )
1190       iobuf_writestr( out,
1191                       "NotDashEscaped: You need "GPG_NAME
1192                       " to verify this message" LF );
1193     iobuf_writestr(out, LF );
1194
1195     if ( gcry_md_open (&textmd, 0, 0) )
1196       BUG ();
1197     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1198       gcry_md_enable (textmd, hash_for(sk_rover->pk));
1199
1200     if ( DBG_HASHING )
1201       gcry_md_debug ( textmd, "clearsign" );
1202
1203     copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
1204                         opt.escape_from);
1205     /* fixme: check for read errors */
1206
1207     /* now write the armor */
1208     afx->what = 2;
1209     push_armor_filter (afx, out);
1210
1211     /* Write the signatures.  */
1212     rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
1213                                   NULL);
1214     if( rc )
1215         goto leave;
1216
1217   leave:
1218     if( rc )
1219         iobuf_cancel(out);
1220     else
1221         iobuf_close(out);
1222     iobuf_close(inp);
1223     gcry_md_close ( textmd );
1224     release_sk_list( sk_list );
1225     release_progress_context (pfx);
1226     release_armor_context (afx);
1227     return rc;
1228 }
1229
1230 /*
1231  * Sign and conventionally encrypt the given file.
1232  * FIXME: Far too much code is duplicated - revamp the whole file.
1233  */
1234 int
1235 sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
1236 {
1237     armor_filter_context_t *afx;
1238     progress_filter_context_t *pfx;
1239     compress_filter_context_t zfx;
1240     md_filter_context_t mfx;
1241     text_filter_context_t tfx;
1242     cipher_filter_context_t cfx;
1243     IOBUF inp = NULL, out = NULL;
1244     PACKET pkt;
1245     STRING2KEY *s2k = NULL;
1246     int rc = 0;
1247     SK_LIST sk_list = NULL;
1248     SK_LIST sk_rover = NULL;
1249     int algo;
1250     u32 duration=0;
1251     int canceled;
1252
1253     pfx = new_progress_context ();
1254     afx = new_armor_context ();
1255     memset( &zfx, 0, sizeof zfx);
1256     memset( &mfx, 0, sizeof mfx);
1257     memset( &tfx, 0, sizeof tfx);
1258     memset( &cfx, 0, sizeof cfx);
1259     init_packet( &pkt );
1260
1261     if (opt.ask_sig_expire && !opt.batch)
1262       duration = ask_expire_interval (1, opt.def_sig_expire);
1263     else
1264       duration = parse_expire_string (opt.def_sig_expire);
1265
1266     /* Note: In the old non-agent version the following call used to
1267        unprotect the secret key.  This is now done on demand by the agent.  */
1268     rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
1269     if (rc)
1270         goto leave;
1271
1272     /* prepare iobufs */
1273     inp = iobuf_open(fname);
1274     if (inp && is_secured_file (iobuf_get_fd (inp)))
1275       {
1276         iobuf_close (inp);
1277         inp = NULL;
1278         gpg_err_set_errno (EPERM);
1279       }
1280     if( !inp ) {
1281         rc = gpg_error_from_syserror ();
1282         log_error (_("can't open '%s': %s\n"),
1283                    fname? fname: "[stdin]", strerror(errno) );
1284         goto leave;
1285     }
1286     handle_progress (pfx, inp, fname);
1287
1288     /* prepare key */
1289     s2k = xmalloc_clear( sizeof *s2k );
1290     s2k->mode = opt.s2k_mode;
1291     s2k->hash_algo = S2K_DIGEST_ALGO;
1292
1293     algo = default_cipher_algo();
1294     if (!opt.quiet || !opt.batch)
1295         log_info (_("%s encryption will be used\n"),
1296                   openpgp_cipher_algo_name (algo) );
1297     cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, &canceled);
1298
1299     if (!cfx.dek || !cfx.dek->keylen) {
1300         rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1301         log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1302         goto leave;
1303     }
1304
1305     cfx.dek->use_mdc = use_mdc (NULL, cfx.dek->algo);
1306
1307     /* now create the outfile */
1308     rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1309     if (rc)
1310         goto leave;
1311
1312     /* prepare to calculate the MD over the input */
1313     if (opt.textmode)
1314         iobuf_push_filter (inp, text_filter, &tfx);
1315     if ( gcry_md_open (&mfx.md, 0, 0) )
1316       BUG ();
1317     if ( DBG_HASHING )
1318       gcry_md_debug (mfx.md, "symc-sign");
1319
1320     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1321       gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1322
1323     iobuf_push_filter (inp, md_filter, &mfx);
1324
1325     /* Push armor output filter */
1326     if (opt.armor)
1327         push_armor_filter (afx, out);
1328
1329     /* Write the symmetric key packet */
1330     /*(current filters: armor)*/
1331     {
1332         PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1333         enc->version = 4;
1334         enc->cipher_algo = cfx.dek->algo;
1335         enc->s2k = *s2k;
1336         pkt.pkttype = PKT_SYMKEY_ENC;
1337         pkt.pkt.symkey_enc = enc;
1338         if( (rc = build_packet( out, &pkt )) )
1339             log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
1340         xfree(enc);
1341     }
1342
1343     /* Push the encryption filter */
1344     iobuf_push_filter( out, cipher_filter, &cfx );
1345
1346     /* Push the compress filter */
1347     if (default_compress_algo())
1348       {
1349         if (cfx.dek && cfx.dek->use_mdc)
1350           zfx.new_ctb = 1;
1351         push_compress_filter (out, &zfx,default_compress_algo() );
1352       }
1353
1354     /* Write the one-pass signature packets */
1355     /*(current filters: zip - encrypt - armor)*/
1356     rc = write_onepass_sig_packets (sk_list, out,
1357                                     opt.textmode? 0x01:0x00);
1358     if (rc)
1359       goto leave;
1360
1361     write_status_begin_signing (mfx.md);
1362
1363     /* Pipe data through all filters; i.e. write the signed stuff */
1364     /*(current filters: zip - encrypt - armor)*/
1365     rc = write_plaintext_packet (out, inp, fname,
1366                                  opt.textmode ? (opt.mimemode?'m':'t'):'b');
1367     if (rc)
1368         goto leave;
1369
1370     /* Write the signatures */
1371     /*(current filters: zip - encrypt - armor)*/
1372     rc = write_signature_packets (sk_list, out, mfx.md,
1373                                   opt.textmode? 0x01 : 0x00,
1374                                   0, duration, 'S', NULL);
1375     if( rc )
1376         goto leave;
1377
1378
1379   leave:
1380     if( rc )
1381         iobuf_cancel(out);
1382     else {
1383         iobuf_close(out);
1384         write_status( STATUS_END_ENCRYPTION );
1385     }
1386     iobuf_close(inp);
1387     release_sk_list( sk_list );
1388     gcry_md_close( mfx.md );
1389     xfree(cfx.dek);
1390     xfree(s2k);
1391     release_progress_context (pfx);
1392     release_armor_context (afx);
1393     return rc;
1394 }
1395
1396
1397 /****************
1398  * Create a v4 signature in *RET_SIG.
1399  *
1400  * PK is the primary key to sign (required for all sigs)
1401  * UID is the user id to sign (required for 0x10..0x13, 0x30)
1402  * SUBPK is subkey to sign (required for 0x18, 0x19, 0x28)
1403  *
1404  * PKSK is the signing key
1405  *
1406  * SIGCLASS is the type of signature to create.
1407  *
1408  * DIGEST_ALGO is the digest algorithm.  If it is 0 the function
1409  * selects an appropriate one.
1410  *
1411  * TIMESTAMP is the timestamp to use for the signature. 0 means "now"
1412  *
1413  * DURATION is the amount of time (in seconds) until the signature
1414  * expires.
1415  *
1416  * This function creates the following subpackets: issuer, created,
1417  * and expire (if duration is not 0).  Additional subpackets can be
1418  * added using MKSUBPKT, which is called after these subpackets are
1419  * added and before the signature is generated.  OPAQUE is passed to
1420  * MKSUBPKT.
1421  */
1422 int
1423 make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
1424                     PKT_user_id *uid, PKT_public_key *subpk,
1425                     PKT_public_key *pksk,
1426                     int sigclass, int digest_algo,
1427                     u32 timestamp, u32 duration,
1428                     int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1429                     const char *cache_nonce)
1430 {
1431     PKT_signature *sig;
1432     int rc=0;
1433     int sigversion;
1434     gcry_md_hd_t md;
1435
1436     log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1437                 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1438                 || sigclass == 0x30 || sigclass == 0x28 );
1439
1440     sigversion = 4;
1441     if (sigversion < pksk->version)
1442         sigversion = pksk->version;
1443
1444     if( !digest_algo )
1445       {
1446         /* Basically, this means use SHA1 always unless the user
1447            specified something (use whatever they said), or it's DSA
1448            (use the best match).  They still can't pick an
1449            inappropriate hash for DSA or the signature will fail.
1450            Note that this still allows the caller of
1451            make_keysig_packet to override the user setting if it
1452            must. */
1453
1454         if(opt.cert_digest_algo)
1455           digest_algo=opt.cert_digest_algo;
1456         else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
1457           digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1458         else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1459                  || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1460           {
1461             if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
1462               digest_algo = DIGEST_ALGO_SHA256;
1463             else
1464               digest_algo = match_dsa_hash
1465                 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1466           }
1467         else
1468           digest_algo = DEFAULT_DIGEST_ALGO;
1469       }
1470
1471     if ( gcry_md_open (&md, digest_algo, 0 ) )
1472       BUG ();
1473
1474     /* Hash the public key certificate. */
1475     hash_public_key( md, pk );
1476
1477     if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1478       {
1479         /* hash the subkey binding/backsig/revocation */
1480         hash_public_key( md, subpk );
1481       }
1482     else if( sigclass != 0x1F && sigclass != 0x20 )
1483       {
1484         /* hash the user id */
1485         hash_uid (md, sigversion, uid);
1486       }
1487     /* and make the signature packet */
1488     sig = xmalloc_clear( sizeof *sig );
1489     sig->version = sigversion;
1490     sig->flags.exportable=1;
1491     sig->flags.revocable=1;
1492     keyid_from_pk (pksk, sig->keyid);
1493     sig->pubkey_algo = pksk->pubkey_algo;
1494     sig->digest_algo = digest_algo;
1495     if(timestamp)
1496       sig->timestamp=timestamp;
1497     else
1498       sig->timestamp=make_timestamp();
1499     if(duration)
1500       sig->expiredate=sig->timestamp+duration;
1501     sig->sig_class = sigclass;
1502
1503     build_sig_subpkt_from_sig (sig, pksk);
1504     mk_notation_policy_etc (sig, pk, pksk);
1505
1506     /* Crucial that the call to mksubpkt comes LAST before the calls
1507        to finalize the sig as that makes it possible for the mksubpkt
1508        function to get a reliable pointer to the subpacket area. */
1509     if (mksubpkt)
1510         rc = (*mksubpkt)( sig, opaque );
1511
1512     if( !rc ) {
1513         hash_sigversion_to_magic (md, sig);
1514         gcry_md_final (md);
1515
1516         rc = complete_sig (sig, pksk, md, cache_nonce);
1517     }
1518
1519     gcry_md_close (md);
1520     if( rc )
1521         free_seckey_enc( sig );
1522     else
1523         *ret_sig = sig;
1524     return rc;
1525 }
1526
1527
1528
1529 /****************
1530  * Create a new signature packet based on an existing one.
1531  * Only user ID signatures are supported for now.
1532  * PK is the public key to work on.
1533  * PKSK is the key used to make the signature.
1534  *
1535  * TODO: Merge this with make_keysig_packet.
1536  */
1537 gpg_error_t
1538 update_keysig_packet( PKT_signature **ret_sig,
1539                       PKT_signature *orig_sig,
1540                       PKT_public_key *pk,
1541                       PKT_user_id *uid,
1542                       PKT_public_key *subpk,
1543                       PKT_public_key *pksk,
1544                       int (*mksubpkt)(PKT_signature *, void *),
1545                       void *opaque)
1546 {
1547     PKT_signature *sig;
1548     gpg_error_t rc = 0;
1549     int digest_algo;
1550     gcry_md_hd_t md;
1551
1552     if ((!orig_sig || !pk || !pksk)
1553         || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1554         || (orig_sig->sig_class == 0x18 && !subpk))
1555       return GPG_ERR_GENERAL;
1556
1557     if ( opt.cert_digest_algo )
1558       digest_algo = opt.cert_digest_algo;
1559     else
1560       digest_algo = orig_sig->digest_algo;
1561
1562     if ( gcry_md_open (&md, digest_algo, 0 ) )
1563       BUG ();
1564
1565     /* Hash the public key certificate and the user id. */
1566     hash_public_key( md, pk );
1567
1568     if( orig_sig->sig_class == 0x18 )
1569       hash_public_key( md, subpk );
1570     else
1571       hash_uid (md, orig_sig->version, uid);
1572
1573     /* create a new signature packet */
1574     sig = copy_signature (NULL, orig_sig);
1575
1576     sig->digest_algo=digest_algo;
1577
1578     /* We need to create a new timestamp so that new sig expiration
1579        calculations are done correctly... */
1580     sig->timestamp=make_timestamp();
1581
1582     /* ... but we won't make a timestamp earlier than the existing
1583        one. */
1584     {
1585       int tmout = 0;
1586       while(sig->timestamp<=orig_sig->timestamp)
1587         {
1588           if (++tmout > 5 && !opt.ignore_time_conflict)
1589             {
1590               rc = gpg_error (GPG_ERR_TIME_CONFLICT);
1591               goto leave;
1592             }
1593           gnupg_sleep (1);
1594           sig->timestamp=make_timestamp();
1595         }
1596     }
1597
1598     /* Note that already expired sigs will remain expired (with a
1599        duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1600        detects this case. */
1601
1602     /* Put the updated timestamp into the sig.  Note that this will
1603        automagically lower any sig expiration dates to correctly
1604        correspond to the differences in the timestamps (i.e. the
1605        duration will shrink).  */
1606     build_sig_subpkt_from_sig (sig, pksk);
1607
1608     if (mksubpkt)
1609       rc = (*mksubpkt)(sig, opaque);
1610
1611     if (!rc) {
1612         hash_sigversion_to_magic (md, sig);
1613         gcry_md_final (md);
1614
1615         rc = complete_sig (sig, pksk, md, NULL);
1616     }
1617
1618  leave:
1619     gcry_md_close (md);
1620     if( rc )
1621         free_seckey_enc (sig);
1622     else
1623         *ret_sig = sig;
1624     return rc;
1625 }