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