Imported Upstream version 2.4.3
[platform/upstream/gpg2.git] / g10 / sign.c
1 /* sign.c - sign data
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2007, 2010, 2012 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <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 "../common/status.h"
31 #include "../common/iobuf.h"
32 #include "keydb.h"
33 #include "../common/util.h"
34 #include "main.h"
35 #include "filter.h"
36 #include "../common/ttyio.h"
37 #include "trustdb.h"
38 #include "../common/status.h"
39 #include "../common/i18n.h"
40 #include "pkglue.h"
41 #include "../common/sysutils.h"
42 #include "call-agent.h"
43 #include "../common/mbox-util.h"
44 #include "../common/compliance.h"
45
46 #ifdef HAVE_DOSISH_SYSTEM
47 #define LF "\r\n"
48 #else
49 #define LF "\n"
50 #endif
51
52
53 /* Hack */
54 static int recipient_digest_algo;
55
56
57 /* A type for the extra data we hash into v5 signature packets.  */
58 struct pt_extra_hash_data_s
59 {
60   unsigned char mode;
61   u32 timestamp;
62   unsigned char namelen;
63   char name[1];
64 };
65 typedef struct pt_extra_hash_data_s *pt_extra_hash_data_t;
66
67
68 /*
69  * Create notations and other stuff.  It is assumed that the strings in
70  * STRLIST are already checked to contain only printable data and have
71  * a valid NAME=VALUE format.
72  */
73 static void
74 mk_notation_policy_etc (ctrl_t ctrl, PKT_signature *sig,
75                         PKT_public_key *pk, PKT_public_key *pksk)
76 {
77   const char *string;
78   char *p = NULL;
79   strlist_t pu = NULL;
80   struct notation *nd = NULL;
81   struct expando_args args;
82
83   log_assert (sig->version >= 4);
84
85   memset (&args, 0, sizeof(args));
86   args.pk = pk;
87   args.pksk = pksk;
88
89   /* Notation data. */
90   if (IS_ATTST_SIGS(sig))
91     ;
92   else if (IS_SIG(sig) && opt.sig_notations)
93     nd = opt.sig_notations;
94   else if (IS_CERT(sig) && opt.cert_notations)
95     nd = opt.cert_notations;
96
97   if (nd)
98     {
99       struct notation *item;
100
101       for (item = nd; item; item = item->next)
102         {
103           item->altvalue = pct_expando (ctrl, item->value,&args);
104           if (!item->altvalue)
105             log_error (_("WARNING: unable to %%-expand notation "
106                          "(too large).  Using unexpanded.\n"));
107         }
108
109       keygen_add_notations (sig, nd);
110
111       for (item = nd; item; item = item->next)
112         {
113           xfree (item->altvalue);
114           item->altvalue = NULL;
115         }
116     }
117
118   /* Set policy URL. */
119   if (IS_ATTST_SIGS(sig))
120     ;
121   else if (IS_SIG(sig) && opt.sig_policy_url)
122     pu = opt.sig_policy_url;
123   else if (IS_CERT(sig) && opt.cert_policy_url)
124     pu = opt.cert_policy_url;
125
126   for (; pu; pu = pu->next)
127     {
128       string = pu->d;
129
130       p = pct_expando (ctrl, string, &args);
131       if (!p)
132         {
133           log_error(_("WARNING: unable to %%-expand policy URL "
134                       "(too large).  Using unexpanded.\n"));
135           p = xstrdup(string);
136         }
137
138       build_sig_subpkt (sig, (SIGSUBPKT_POLICY
139                               | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
140                         p, strlen (p));
141
142       xfree (p);
143     }
144
145   /* Preferred keyserver URL. */
146   if (IS_SIG(sig) && opt.sig_keyserver_url)
147     pu = opt.sig_keyserver_url;
148
149   for (; pu; pu = pu->next)
150     {
151       string = pu->d;
152
153       p = pct_expando (ctrl, string, &args);
154       if (!p)
155         {
156           log_error (_("WARNING: unable to %%-expand preferred keyserver URL"
157                        " (too large).  Using unexpanded.\n"));
158           p = xstrdup (string);
159         }
160
161       build_sig_subpkt (sig, (SIGSUBPKT_PREF_KS
162                               | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
163                         p, strlen (p));
164       xfree (p);
165     }
166
167   /* Set signer's user id.  */
168   if (IS_SIG (sig) && !opt.flags.disable_signer_uid)
169     {
170       char *mbox;
171
172       /* For now we use the uid which was used to locate the key.  */
173       if (pksk->user_id
174           && (mbox = mailbox_from_userid (pksk->user_id->name, 0)))
175         {
176           if (DBG_LOOKUP)
177             log_debug ("setting Signer's UID to '%s'\n", mbox);
178           build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, mbox, strlen (mbox));
179           xfree (mbox);
180         }
181       else if (opt.sender_list)
182         {
183           /* If a list of --sender was given we scan that list and use
184            * the first one matching a user id of the current key.  */
185
186           /* FIXME: We need to get the list of user ids for the PKSK
187            * packet.  That requires either a function to look it up
188            * again or we need to extend the key packet struct to link
189            * to the primary key which in turn could link to the user
190            * ids.  Too much of a change right now.  Let's take just
191            * one from the supplied list and hope that the caller
192            * passed a matching one.  */
193           build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
194                             opt.sender_list->d, strlen (opt.sender_list->d));
195         }
196     }
197 }
198
199
200
201 /*
202  * Put the Key Block subpacket into SIG for key PKSK.  Returns an
203  * error code on failure.
204  */
205 static gpg_error_t
206 mk_sig_subpkt_key_block (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pksk)
207 {
208   gpg_error_t err;
209   char *mbox;
210   char *filterexp = NULL;
211   int save_opt_armor = opt.armor;
212   int save_opt_verbose = opt.verbose;
213   char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
214   void *data = NULL;
215   size_t datalen;
216   kbnode_t keyblock = NULL;
217
218   push_export_filters ();
219   opt.armor = 0;
220
221   hexfingerprint (pksk, hexfpr, sizeof hexfpr);
222
223   /* Get the user id so that we know which one to insert into the
224    * key.  */
225   if (pksk->user_id
226       && (mbox = mailbox_from_userid (pksk->user_id->name, 0)))
227     {
228       if (DBG_LOOKUP)
229         log_debug ("including key with UID '%s' (specified)\n", mbox);
230       filterexp = xasprintf ("keep-uid= -- mbox = %s", mbox);
231       xfree (mbox);
232     }
233   else if (opt.sender_list)
234     {
235       /* If --sender was given we use the first one from that list.  */
236       if (DBG_LOOKUP)
237         log_debug ("including key with UID '%s' (--sender)\n",
238                    opt.sender_list->d);
239       filterexp = xasprintf ("keep-uid= -- mbox = %s", opt.sender_list->d);
240     }
241   else  /* Use the primary user id.  */
242     {
243       if (DBG_LOOKUP)
244         log_debug ("including key with primary UID\n");
245       filterexp = xstrdup ("keep-uid= primary -t");
246     }
247
248   if (DBG_LOOKUP)
249     log_debug ("export filter expression: %s\n", filterexp);
250   err = parse_and_set_export_filter (filterexp);
251   if (err)
252     goto leave;
253   xfree (filterexp);
254   filterexp = xasprintf ("drop-subkey= fpr <> %s && usage !~ e", hexfpr);
255   if (DBG_LOOKUP)
256     log_debug ("export filter expression: %s\n", filterexp);
257   err = parse_and_set_export_filter (filterexp);
258   if (err)
259     goto leave;
260
261
262   opt.verbose = 0;
263   err = export_pubkey_buffer (ctrl, hexfpr, EXPORT_MINIMAL|EXPORT_CLEAN,
264                               "", 1, /* Prefix with the reserved byte. */
265                               NULL, &keyblock, &data, &datalen);
266   opt.verbose = save_opt_verbose;
267   if (err)
268     {
269       log_error ("failed to get to be included key: %s\n", gpg_strerror (err));
270       goto leave;
271     }
272
273   build_sig_subpkt (sig, SIGSUBPKT_KEY_BLOCK, data, datalen);
274
275  leave:
276   xfree (data);
277   release_kbnode (keyblock);
278   xfree (filterexp);
279   opt.armor = save_opt_armor;
280   pop_export_filters ();
281   return err;
282 }
283
284
285 /*
286  * Helper to hash a user ID packet.
287  */
288 static void
289 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
290 {
291   byte buf[5];
292
293   (void)sigversion;
294
295   if (uid->attrib_data)
296     {
297       buf[0] = 0xd1;                   /* Indicates an attribute packet.  */
298       buf[1] = uid->attrib_len >> 24;  /* Always use 4 length bytes.  */
299       buf[2] = uid->attrib_len >> 16;
300       buf[3] = uid->attrib_len >>  8;
301       buf[4] = uid->attrib_len;
302     }
303   else
304     {
305       buf[0] = 0xb4;                   /* Indicates a userid packet.  */
306       buf[1] = uid->len >> 24;         /* Always use 4 length bytes.  */
307       buf[2] = uid->len >> 16;
308       buf[3] = uid->len >>  8;
309       buf[4] = uid->len;
310     }
311   gcry_md_write( md, buf, 5 );
312
313   if (uid->attrib_data)
314     gcry_md_write (md, uid->attrib_data, uid->attrib_len );
315   else
316     gcry_md_write (md, uid->name, uid->len );
317 }
318
319
320 /*
321  * Helper to hash some parts from the signature.  EXTRAHASH gives the
322  * extra data to be hashed into v5 signatures; it may by NULL for
323  * detached signatures.
324  */
325 static void
326 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig,
327                           pt_extra_hash_data_t extrahash)
328 {
329   byte buf[10];
330   int i;
331   size_t n;
332
333   gcry_md_putc (md, sig->version);
334   gcry_md_putc (md, sig->sig_class);
335   gcry_md_putc (md, sig->pubkey_algo);
336   gcry_md_putc (md, sig->digest_algo);
337   if (sig->hashed)
338     {
339       n = sig->hashed->len;
340       gcry_md_putc (md, (n >> 8) );
341       gcry_md_putc (md,  n       );
342       gcry_md_write (md, sig->hashed->data, n );
343       n += 6;
344     }
345   else
346     {
347       gcry_md_putc (md, 0);  /* Always hash the length of the subpacket.  */
348       gcry_md_putc (md, 0);
349       n = 6;
350     }
351   /* Hash data from the literal data packet.  */
352   if (sig->version >= 5 && (sig->sig_class == 0x00 || sig->sig_class == 0x01))
353     {
354       /* - One octet content format
355        * - File name (one octet length followed by the name)
356        * - Four octet timestamp */
357       if (extrahash)
358         {
359           buf[0] = extrahash->mode;
360           buf[1] = extrahash->namelen;
361           gcry_md_write (md, buf, 2);
362           if (extrahash->namelen)
363             gcry_md_write (md, extrahash->name, extrahash->namelen);
364           buf[0] = extrahash->timestamp >> 24;
365           buf[1] = extrahash->timestamp >> 16;
366           buf[2] = extrahash->timestamp >>  8;
367           buf[3] = extrahash->timestamp;
368           gcry_md_write (md, buf, 4);
369         }
370       else /* Detached signatures */
371         {
372           memset (buf, 0, 6);
373           gcry_md_write (md, buf, 6);
374         }
375     }
376   /* Add some magic aka known as postscript.  The idea was to make it
377    * impossible to make up a document with a v3 signature and then
378    * turn this into a v4 signature for another document.  The last
379    * hashed 5 bytes of a v4 signature should never look like a the
380    * last 5 bytes of a v3 signature.  The length can be used to parse
381    * from the end. */
382   i = 0;
383   buf[i++] = sig->version;  /* Hash convention version.  */
384   buf[i++] = 0xff;          /* Not any sig type value.   */
385   if (sig->version >= 5)
386     {
387       /* Note: We don't hashed any data larger than 2^32 and thus we
388        * can always use 0 here.  See also note below.  */
389       buf[i++] = 0;
390       buf[i++] = 0;
391       buf[i++] = 0;
392       buf[i++] = 0;
393     }
394   buf[i++] = n >> 24;         /* (n is only 16 bit, so this is always 0) */
395   buf[i++] = n >> 16;
396   buf[i++] = n >>  8;
397   buf[i++] = n;
398   gcry_md_write (md, buf, i);
399 }
400
401
402 /* Perform the sign operation.  If CACHE_NONCE is given the agent is
403  * advised to use that cached passphrase for the key.  SIGNHINTS has
404  * hints so that we can do some additional checks. */
405 static int
406 do_sign (ctrl_t ctrl, PKT_public_key *pksk, PKT_signature *sig,
407          gcry_md_hd_t md, int mdalgo,
408          const char *cache_nonce, unsigned int signhints)
409 {
410   gpg_error_t err;
411   byte *dp;
412   char *hexgrip;
413
414   /* An ADSK key commonly has a creation date older than the primary
415    * key.  For example because the ADSK is used as an archive key for
416    * a group of users.  */
417   if (pksk->timestamp > sig->timestamp && !(signhints & SIGNHINT_ADSK))
418     {
419       ulong d = pksk->timestamp - sig->timestamp;
420       log_info (ngettext("key %s was created %lu second"
421                          " in the future (time warp or clock problem)\n",
422                          "key %s was created %lu seconds"
423                          " in the future (time warp or clock problem)\n",
424                          d), keystr_from_pk (pksk), d);
425       if (!opt.ignore_time_conflict)
426         return gpg_error (GPG_ERR_TIME_CONFLICT);
427     }
428
429   print_pubkey_algo_note (pksk->pubkey_algo);
430
431   if (!mdalgo)
432     mdalgo = gcry_md_get_algo (md);
433
434   if ((signhints & SIGNHINT_KEYSIG) && !(signhints & SIGNHINT_SELFSIG)
435       && mdalgo == GCRY_MD_SHA1
436       && !opt.flags.allow_weak_key_signatures)
437     {
438       /* We do not allow the creation of third-party key signatures
439        * using SHA-1 because we also reject them when verifying.  Note
440        * that this will render dsa1024 keys unsuitable for such
441        * keysigs and in turn the WoT. */
442       print_sha1_keysig_rejected_note ();
443       err = gpg_error (GPG_ERR_DIGEST_ALGO);
444       goto leave;
445     }
446
447   /* Check compliance.  */
448   if (! gnupg_digest_is_allowed (opt.compliance, 1, mdalgo))
449     {
450       log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
451                  gcry_md_algo_name (mdalgo),
452                  gnupg_compliance_option_string (opt.compliance));
453       err = gpg_error (GPG_ERR_DIGEST_ALGO);
454       goto leave;
455     }
456
457   if (! gnupg_pk_is_allowed (opt.compliance, PK_USE_SIGNING,
458                              pksk->pubkey_algo, 0,
459                              pksk->pkey, nbits_from_pk (pksk), NULL))
460     {
461       log_error (_("key %s may not be used for signing in %s mode\n"),
462                  keystr_from_pk (pksk),
463                  gnupg_compliance_option_string (opt.compliance));
464       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
465       goto leave;
466     }
467
468   if (!gnupg_rng_is_compliant (opt.compliance))
469     {
470       err = gpg_error (GPG_ERR_FORBIDDEN);
471       log_error (_("%s is not compliant with %s mode\n"),
472                  "RNG",
473                  gnupg_compliance_option_string (opt.compliance));
474       write_status_error ("random-compliance", err);
475       goto leave;
476     }
477
478   print_digest_algo_note (mdalgo);
479   dp = gcry_md_read  (md, mdalgo);
480   sig->digest_algo = mdalgo;
481   sig->digest_start[0] = dp[0];
482   sig->digest_start[1] = dp[1];
483   mpi_release (sig->data[0]);
484   sig->data[0] = NULL;
485   mpi_release (sig->data[1]);
486   sig->data[1] = NULL;
487
488
489   err = hexkeygrip_from_pk (pksk, &hexgrip);
490   if (!err)
491     {
492       char *desc;
493       gcry_sexp_t s_sigval;
494
495       desc = gpg_format_keydesc (ctrl, pksk, FORMAT_KEYDESC_NORMAL, 1);
496       err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
497                           pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
498                           dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
499                           &s_sigval);
500       xfree (desc);
501
502       if (err)
503         ;
504       else if (pksk->pubkey_algo == GCRY_PK_RSA
505                || pksk->pubkey_algo == GCRY_PK_RSA_S)
506         sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
507       else if (pksk->pubkey_algo == PUBKEY_ALGO_EDDSA
508                && openpgp_oid_is_ed25519 (pksk->pkey[0]))
509         {
510           err = sexp_extract_param_sos_nlz (s_sigval, "r", &sig->data[0]);
511           if (!err)
512             err = sexp_extract_param_sos_nlz (s_sigval, "s", &sig->data[1]);
513         }
514       else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
515                || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
516         {
517           err = sexp_extract_param_sos (s_sigval, "r", &sig->data[0]);
518           if (!err)
519             err = sexp_extract_param_sos (s_sigval, "s", &sig->data[1]);
520         }
521       else
522         {
523           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
524           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
525         }
526
527       gcry_sexp_release (s_sigval);
528     }
529   xfree (hexgrip);
530
531  leave:
532   if (err)
533     log_error (_("signing failed: %s\n"), gpg_strerror (err));
534   else
535     {
536       if (opt.verbose)
537         {
538           char *ustr = get_user_id_string_native (ctrl, sig->keyid);
539           log_info (_("%s/%s signature from: \"%s\"\n"),
540                     openpgp_pk_algo_name (pksk->pubkey_algo),
541                     openpgp_md_algo_name (sig->digest_algo),
542                     ustr);
543           xfree (ustr);
544         }
545     }
546   return err;
547 }
548
549
550 static int
551 complete_sig (ctrl_t ctrl,
552               PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
553               const char *cache_nonce, unsigned int signhints)
554 {
555   int rc;
556
557   /* if (!(rc = check_secret_key (pksk, 0))) */
558   rc = do_sign (ctrl, pksk, sig, md, 0, cache_nonce, signhints);
559   return rc;
560 }
561
562
563 /* Return true if the key seems to be on a version 1 OpenPGP card.
564    This works by asking the agent and may fail if the card has not yet
565    been used with the agent.  */
566 static int
567 openpgp_card_v1_p (PKT_public_key *pk)
568 {
569   gpg_error_t err;
570   int result;
571
572   /* Shortcut if we are not using RSA: The v1 cards only support RSA
573      thus there is no point in looking any further.  */
574   if (!is_RSA (pk->pubkey_algo))
575     return 0;
576
577   if (!pk->flags.serialno_valid)
578     {
579       char *hexgrip;
580
581       err = hexkeygrip_from_pk (pk, &hexgrip);
582       if (err)
583         {
584           log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
585           return 0; /* Ooops.  */
586         }
587
588       xfree (pk->serialno);
589       agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL);
590       xfree (hexgrip);
591       pk->flags.serialno_valid = 1;
592     }
593
594   if (!pk->serialno)
595     result = 0; /* Error from a past agent_get_keyinfo or no card.  */
596   else
597     {
598       /* The version number of the card is included in the serialno.  */
599       result = !strncmp (pk->serialno, "D2760001240101", 14);
600     }
601   return result;
602 }
603
604
605 /* Get a matching hash algorithm for DSA and ECDSA.  */
606 static int
607 match_dsa_hash (unsigned int qbytes)
608 {
609   if (qbytes <= 20)
610     return DIGEST_ALGO_SHA1;
611
612   if (qbytes <= 28)
613     return DIGEST_ALGO_SHA224;
614
615   if (qbytes <= 32)
616     return DIGEST_ALGO_SHA256;
617
618   if (qbytes <= 48)
619     return DIGEST_ALGO_SHA384;
620
621   if (qbytes <= 66 )    /* 66 corresponds to 521 (64 to 512) */
622     return DIGEST_ALGO_SHA512;
623
624   return DEFAULT_DIGEST_ALGO;
625   /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
626      answer we have if a digest larger than 512 bits is requested.  */
627 }
628
629
630 /*
631   First try --digest-algo.  If that isn't set, see if the recipient
632   has a preferred algorithm (which is also filtered through
633   --personal-digest-prefs).  If we're making a signature without a
634   particular recipient (i.e. signing, rather than signing+encrypting)
635   then take the first algorithm in --personal-digest-prefs that is
636   usable for the pubkey algorithm.  If --personal-digest-prefs isn't
637   set, then take the OpenPGP default (i.e. SHA-1).
638
639   Note that EdDSA takes an input of arbitrary length and thus
640   we don't enforce any particular algorithm like we do for standard
641   ECDSA. However, we use SHA256 as the default algorithm.
642
643   Possible improvement: Use the highest-ranked usable algorithm from
644   the signing key prefs either before or after using the personal
645   list?
646 */
647 static int
648 hash_for (PKT_public_key *pk)
649 {
650   if (opt.def_digest_algo)
651     {
652       return opt.def_digest_algo;
653     }
654   else if (recipient_digest_algo && !is_weak_digest (recipient_digest_algo))
655     {
656       return recipient_digest_algo;
657     }
658   else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
659     {
660       if (opt.personal_digest_prefs)
661         return opt.personal_digest_prefs[0].value;
662       else
663         if (gcry_mpi_get_nbits (pk->pkey[1]) > 256)
664           return DIGEST_ALGO_SHA512;
665         else
666           return DIGEST_ALGO_SHA256;
667     }
668   else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
669            || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
670     {
671       unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
672
673       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
674         qbytes = ecdsa_qbits_from_Q (qbytes);
675       qbytes = qbytes/8;
676
677       /* It's a DSA key, so find a hash that is the same size as q or
678          larger.  If q is 160, assume it is an old DSA key and use a
679          160-bit hash unless --enable-dsa2 is set, in which case act
680          like a new DSA key that just happens to have a 160-bit q
681          (i.e. allow truncation).  If q is not 160, by definition it
682          must be a new DSA key.  We ignore the personal_digest_prefs
683          for ECDSA because they should always macth the curve and
684          truncated hashes are not useful either.  Even worse,
685          smartcards may reject non matching hash lengths for curves
686          (e.g. using SHA-512 with brainpooolP385r1 on a Yubikey).  */
687
688       if (pk->pubkey_algo == PUBKEY_ALGO_DSA && opt.personal_digest_prefs)
689         {
690           prefitem_t *prefs;
691
692           if (qbytes != 20 || opt.flags.dsa2)
693             {
694               for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
695                 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
696                   return prefs->value;
697             }
698           else
699             {
700               for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
701                 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
702                   return prefs->value;
703             }
704         }
705
706       return match_dsa_hash(qbytes);
707     }
708   else if (openpgp_card_v1_p (pk))
709     {
710       /* The sk lives on a smartcard, and old smartcards only handle
711          SHA-1 and RIPEMD/160.  Newer smartcards (v2.0) don't have
712          this restriction anymore.  Fortunately the serial number
713          encodes the version of the card and thus we know that this
714          key is on a v1 card. */
715       if(opt.personal_digest_prefs)
716         {
717           prefitem_t *prefs;
718
719           for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
720             if (prefs->value==DIGEST_ALGO_SHA1
721                 || prefs->value==DIGEST_ALGO_RMD160)
722               return prefs->value;
723         }
724
725       return DIGEST_ALGO_SHA1;
726     }
727   else if (opt.personal_digest_prefs)
728     {
729       /* It's not DSA, so we can use whatever the first hash algorithm
730          is in the pref list */
731       return opt.personal_digest_prefs[0].value;
732     }
733   else
734     return DEFAULT_DIGEST_ALGO;
735 }
736
737
738 static void
739 print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
740 {
741   byte array[MAX_FINGERPRINT_LEN];
742   char buf[100+MAX_FINGERPRINT_LEN*2];
743   size_t n;
744
745   snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
746             what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
747             (ulong)sig->timestamp );
748   fingerprint_from_pk (pk, array, &n);
749   bin2hex (array, n, buf + strlen (buf));
750
751   write_status_text( STATUS_SIG_CREATED, buf );
752 }
753
754
755 /*
756  * Loop over the secret certificates in SK_LIST and build the one pass
757  * signature packets.  OpenPGP says that the data should be bracket by
758  * the onepass-sig and signature-packet; so we build these onepass
759  * packet here in reverse order.
760  */
761 static int
762 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
763 {
764   int skcount;
765   SK_LIST sk_rover;
766
767   for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
768     skcount++;
769
770   for (; skcount; skcount--)
771     {
772       PKT_public_key *pk;
773       PKT_onepass_sig *ops;
774       PACKET pkt;
775       int i, rc;
776
777       for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
778         if (++i == skcount)
779           break;
780
781       pk = sk_rover->pk;
782       ops = xmalloc_clear (sizeof *ops);
783       ops->sig_class = sigclass;
784       ops->digest_algo = hash_for (pk);
785       ops->pubkey_algo = pk->pubkey_algo;
786       keyid_from_pk (pk, ops->keyid);
787       ops->last = (skcount == 1);
788
789       init_packet (&pkt);
790       pkt.pkttype = PKT_ONEPASS_SIG;
791       pkt.pkt.onepass_sig = ops;
792       rc = build_packet (out, &pkt);
793       free_packet (&pkt, NULL);
794       if (rc)
795         {
796           log_error ("build onepass_sig packet failed: %s\n",
797                      gpg_strerror (rc));
798           return rc;
799         }
800     }
801
802   return 0;
803 }
804
805
806 /*
807  * Helper to write the plaintext (literal data) packet.  At
808  * R_EXTRAHASH a malloced object with the with the extra data hashed
809  * into v5 signatures is stored.
810  */
811 static int
812 write_plaintext_packet (iobuf_t out, iobuf_t inp,
813                         const char *fname, int ptmode,
814                         pt_extra_hash_data_t *r_extrahash)
815 {
816   PKT_plaintext *pt = NULL;
817   u32 filesize;
818   int rc = 0;
819
820   if (!opt.no_literal)
821     pt = setup_plaintext_name (fname, inp);
822
823   /* Try to calculate the length of the data. */
824   if ( !iobuf_is_pipe_filename (fname) && *fname)
825     {
826       uint64_t tmpsize;
827
828       tmpsize = iobuf_get_filelength (inp);
829       if (!tmpsize && opt.verbose)
830         log_info (_("WARNING: '%s' is an empty file\n"), fname);
831
832       /* We can't encode the length of very large files because
833        * OpenPGP uses only 32 bit for file sizes.  So if the size of a
834        * file is larger than 2^32 minus some bytes for packet headers,
835        * we switch to partial length encoding. */
836       if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536))
837         filesize = tmpsize;
838       else
839         filesize = 0;
840
841       /* Because the text_filter modifies the length of the
842        * data, it is not possible to know the used length
843        * without a double read of the file - to avoid that
844        * we simple use partial length packets. */
845       if (ptmode == 't' || ptmode == 'u' || ptmode == 'm')
846         filesize = 0;
847     }
848   else
849     filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
850
851   if (!opt.no_literal)
852     {
853       PACKET pkt;
854
855       /* Note that PT has been initialized above in no_literal mode.  */
856       pt->timestamp = make_timestamp ();
857       pt->mode = ptmode;
858       pt->len = filesize;
859       pt->new_ctb = !pt->len;
860       pt->buf = inp;
861       init_packet (&pkt);
862       pkt.pkttype = PKT_PLAINTEXT;
863       pkt.pkt.plaintext = pt;
864       /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
865       if ((rc = build_packet (out, &pkt)))
866         log_error ("build_packet(PLAINTEXT) failed: %s\n",
867                    gpg_strerror (rc) );
868
869       *r_extrahash = xtrymalloc (sizeof **r_extrahash + pt->namelen);
870       if (!*r_extrahash)
871         rc = gpg_error_from_syserror ();
872       else
873         {
874           (*r_extrahash)->mode = pt->mode;
875           (*r_extrahash)->timestamp = pt->timestamp;
876           (*r_extrahash)->namelen = pt->namelen;
877           /* Note that the last byte of NAME won't be initialized
878            * because we don't need it.  */
879           memcpy ((*r_extrahash)->name, pt->name, pt->namelen);
880         }
881       pt->buf = NULL;
882       free_packet (&pkt, NULL);
883     }
884   else
885     {
886       byte copy_buffer[4096];
887       int  bytes_copied;
888
889       *r_extrahash = xtrymalloc (sizeof **r_extrahash);
890       if (!*r_extrahash)
891         {
892           rc = gpg_error_from_syserror ();
893           goto leave;
894         }
895       /* FIXME: We need to parse INP to get the to be hashed data from
896        * it.  */
897       (*r_extrahash)->mode = 0;
898       (*r_extrahash)->timestamp = 0;
899       (*r_extrahash)->namelen = 0;
900
901       while ((bytes_copied = iobuf_read (inp, copy_buffer, 4096)) != -1)
902         if ((rc = iobuf_write (out, copy_buffer, bytes_copied)))
903           {
904             log_error ("copying input to output failed: %s\n",
905                        gpg_strerror (rc));
906             break;
907           }
908       wipememory (copy_buffer, 4096); /* burn buffer */
909     }
910
911  leave:
912   return rc;
913 }
914
915
916 /*
917  * Write the signatures from the SK_LIST to OUT. HASH must be a
918  * non-finalized hash which will not be changes here.  EXTRAHASH is
919  * either NULL or the extra data tro be hashed into v5 signatures.
920  */
921 static int
922 write_signature_packets (ctrl_t ctrl,
923                          SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
924                          pt_extra_hash_data_t extrahash,
925                          int sigclass, u32 timestamp, u32 duration,
926                          int status_letter, const char *cache_nonce)
927 {
928   SK_LIST sk_rover;
929
930   /* Loop over the certificates with secret keys. */
931   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
932     {
933       PKT_public_key *pk;
934       PKT_signature *sig;
935       gcry_md_hd_t md;
936       gpg_error_t err;
937
938       pk = sk_rover->pk;
939
940       /* Build the signature packet.  */
941       sig = xtrycalloc (1, sizeof *sig);
942       if (!sig)
943         return gpg_error_from_syserror ();
944
945       if (pk->version >= 5)
946         sig->version = 5;  /* Required for v5 keys.  */
947       else
948         sig->version = 4;  /* Required.  */
949
950       keyid_from_pk (pk, sig->keyid);
951       sig->digest_algo = hash_for (pk);
952       sig->pubkey_algo = pk->pubkey_algo;
953       if (timestamp)
954         sig->timestamp = timestamp;
955       else
956         sig->timestamp = make_timestamp();
957       if (duration)
958         sig->expiredate = sig->timestamp + duration;
959       sig->sig_class = sigclass;
960
961       if (gcry_md_copy (&md, hash))
962         BUG ();
963
964       build_sig_subpkt_from_sig (sig, pk, 0);
965       mk_notation_policy_etc (ctrl, sig, NULL, pk);
966       if (opt.flags.include_key_block && IS_SIG (sig))
967         err = mk_sig_subpkt_key_block (ctrl, sig, pk);
968       else
969         err = 0;
970       hash_sigversion_to_magic (md, sig, extrahash);
971       gcry_md_final (md);
972
973       if (!err)
974         err = do_sign (ctrl, pk, sig, md, hash_for (pk), cache_nonce, 0);
975       gcry_md_close (md);
976       if (!err)
977         {
978           /* Write the packet.  */
979           PACKET pkt;
980
981           init_packet (&pkt);
982           pkt.pkttype = PKT_SIGNATURE;
983           pkt.pkt.signature = sig;
984           err = build_packet (out, &pkt);
985           if (!err && is_status_enabled())
986             print_status_sig_created (pk, sig, status_letter);
987           free_packet (&pkt, NULL);
988           if (err)
989             log_error ("build signature packet failed: %s\n",
990                        gpg_strerror (err));
991         }
992       else
993         free_seckey_enc (sig);
994
995       if (err)
996         return err;
997     }
998
999   return 0;
1000 }
1001
1002
1003 /*
1004  * Sign the files whose names are in FILENAME using all secret keys
1005  * which can be taken from LOCUSR, if this is NULL, use the default
1006  * secret key.
1007  * If DETACHED has the value true, make a detached signature.
1008  * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
1009  * signed data for these users.  If ENCRYPTFLAG is 2 symmetric encryption
1010  * is also used.
1011  * If FILENAMES->d is NULL read from stdin and ignore the detached mode.
1012  * If OUTFILE is not NULL; this file is used for output and the function
1013  * does not ask for overwrite permission; output is then always
1014  * uncompressed, non-armored and in binary mode.
1015  */
1016 int
1017 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
1018            int encryptflag, strlist_t remusr, const char *outfile )
1019 {
1020   const char *fname;
1021   armor_filter_context_t *afx;
1022   compress_filter_context_t zfx;
1023   md_filter_context_t mfx;
1024   text_filter_context_t tfx;
1025   progress_filter_context_t *pfx;
1026   encrypt_filter_context_t efx;
1027   iobuf_t inp = NULL;
1028   iobuf_t out = NULL;
1029   PACKET pkt;
1030   int rc = 0;
1031   PK_LIST pk_list = NULL;
1032   SK_LIST sk_list = NULL;
1033   SK_LIST sk_rover = NULL;
1034   int multifile = 0;
1035   u32 duration=0;
1036   pt_extra_hash_data_t extrahash = NULL;
1037   char peekbuf[32];
1038   int  peekbuflen = 0;
1039
1040
1041   pfx = new_progress_context ();
1042   afx = new_armor_context ();
1043   memset (&zfx, 0, sizeof zfx);
1044   memset (&mfx, 0, sizeof mfx);
1045   memset (&efx, 0, sizeof efx);
1046   efx.ctrl = ctrl;
1047   init_packet (&pkt);
1048
1049   if (filenames)
1050     {
1051       fname = filenames->d;
1052       multifile = !!filenames->next;
1053     }
1054   else
1055     fname = NULL;
1056
1057   if (fname && filenames->next && (!detached || encryptflag))
1058     log_bug ("multiple files can only be detached signed");
1059
1060   if (encryptflag == 2
1061       && (rc = setup_symkey (&efx.symkey_s2k, &efx.symkey_dek)))
1062     goto leave;
1063
1064   if (opt.ask_sig_expire && !opt.batch)
1065     duration = ask_expire_interval(1,opt.def_sig_expire);
1066   else
1067     duration = parse_expire_string(opt.def_sig_expire);
1068
1069   /* Note: In the old non-agent version the following call used to
1070    * unprotect the secret key.  This is now done on demand by the agent.  */
1071   if ((rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )))
1072     goto leave;
1073
1074   if (encryptflag
1075       && (rc = build_pk_list (ctrl, remusr, &pk_list)))
1076     goto leave;
1077
1078   /* Prepare iobufs. */
1079   if (multifile)    /* have list of filenames */
1080     inp = NULL;     /* we do it later */
1081   else
1082     {
1083       inp = iobuf_open(fname);
1084       if (inp && is_secured_file (iobuf_get_fd (inp)))
1085         {
1086           iobuf_close (inp);
1087           inp = NULL;
1088           gpg_err_set_errno (EPERM);
1089         }
1090       if (!inp)
1091         {
1092           rc = gpg_error_from_syserror ();
1093           log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
1094                      strerror (errno));
1095           goto leave;
1096         }
1097
1098       peekbuflen = iobuf_ioctl (inp, IOBUF_IOCTL_PEEK, sizeof peekbuf, peekbuf);
1099       if (peekbuflen < 0)
1100         {
1101           peekbuflen = 0;
1102           if (DBG_FILTER)
1103             log_debug ("peeking at input failed\n");
1104         }
1105
1106       handle_progress (pfx, inp, fname);
1107     }
1108
1109   if (outfile)
1110     {
1111       if (is_secured_filename (outfile))
1112         {
1113           out = NULL;
1114           gpg_err_set_errno (EPERM);
1115         }
1116       else
1117         out = iobuf_create (outfile, 0);
1118       if (!out)
1119         {
1120           rc = gpg_error_from_syserror ();
1121           log_error (_("can't create '%s': %s\n"), outfile, gpg_strerror (rc));
1122           goto leave;
1123         }
1124       else if (opt.verbose)
1125         log_info (_("writing to '%s'\n"), outfile);
1126     }
1127   else if ((rc = open_outfile (-1, fname,
1128                                opt.armor? 1 : detached? 2 : 0, 0, &out)))
1129     {
1130       goto leave;
1131     }
1132
1133   /* Prepare to calculate the MD over the input.  */
1134   if (opt.textmode && !outfile && !multifile)
1135     {
1136       memset (&tfx, 0, sizeof tfx);
1137       iobuf_push_filter (inp, text_filter, &tfx);
1138     }
1139
1140   if (gcry_md_open (&mfx.md, 0, 0))
1141     BUG ();
1142   if (DBG_HASHING)
1143     gcry_md_debug (mfx.md, "sign");
1144
1145   /* If we're encrypting and signing, it is reasonable to pick the
1146    * hash algorithm to use out of the recipient key prefs.  This is
1147    * best effort only, as in a DSA2 and smartcard world there are
1148    * cases where we cannot please everyone with a single hash (DSA2
1149    * wants >160 and smartcards want =160).  In the future this could
1150    * be more complex with different hashes for each sk, but the
1151    * current design requires a single hash for all SKs. */
1152   if (pk_list)
1153     {
1154       if (opt.def_digest_algo)
1155         {
1156           if (!opt.expert
1157               && select_algo_from_prefs (pk_list,PREFTYPE_HASH,
1158                                          opt.def_digest_algo,
1159                                          NULL) != opt.def_digest_algo)
1160             {
1161               log_info (_("WARNING: forcing digest algorithm %s (%d)"
1162                           " violates recipient preferences\n"),
1163                         gcry_md_algo_name (opt.def_digest_algo),
1164                         opt.def_digest_algo);
1165             }
1166         }
1167       else
1168         {
1169           int algo;
1170           int conflict = 0;
1171           struct pref_hint hint = { 0 };
1172
1173           hint.digest_length = 0;
1174
1175           /* Of course, if the recipient asks for something
1176            * unreasonable (like the wrong hash for a DSA key) then
1177            * don't do it.  Check all sk's - if any are DSA or live
1178            * on a smartcard, then the hash has restrictions and we
1179            * may not be able to give the recipient what they want.
1180            * For DSA, pass a hint for the largest q we have.  Note
1181            * that this means that a q>160 key will override a q=160
1182            * key and force the use of truncation for the q=160 key.
1183            * The alternative would be to ignore the recipient prefs
1184            * completely and get a different hash for each DSA key in
1185            * hash_for().  The override behavior here is more or less
1186            * reasonable as it is under the control of the user which
1187            * keys they sign with for a given message and the fact
1188            * that the message with multiple signatures won't be
1189            * usable on an implementation that doesn't understand
1190            * DSA2 anyway. */
1191           for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
1192             {
1193               if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
1194                   || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1195                 {
1196                   int temp_hashlen = gcry_mpi_get_nbits (sk_rover->pk->pkey[1]);
1197
1198                   if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1199                     {
1200                       temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
1201                       if (!temp_hashlen)
1202                         conflict = 1;  /* Better don't use the prefs. */
1203                       temp_hashlen = (temp_hashlen+7)/8;
1204                       /* Fixup for that funny nistp521 (yes, 521) were
1205                        * we need to use a 512 bit hash algo.  */
1206                       if (temp_hashlen == 66)
1207                         temp_hashlen = 64;
1208                     }
1209                   else
1210                     temp_hashlen = (temp_hashlen+7)/8;
1211
1212                   /* Pick a hash that is large enough for our largest
1213                    * Q or matches our Q.  If there are several of them
1214                    * we run into a conflict and don't use the
1215                    * preferences.  */
1216                   if (hint.digest_length < temp_hashlen)
1217                     {
1218                       if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1219                         {
1220                           if (hint.exact)
1221                             conflict = 1;
1222                           hint.exact = 1;
1223                         }
1224                       hint.digest_length = temp_hashlen;
1225                     }
1226                 }
1227             }
1228
1229           if (!conflict
1230               && (algo = select_algo_from_prefs (pk_list, PREFTYPE_HASH,
1231                                                   -1, &hint)) > 0)
1232             {
1233               /* Note that we later check that the algo is not weak.  */
1234               recipient_digest_algo = algo;
1235             }
1236         }
1237     }
1238
1239   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1240     gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1241
1242   if (!multifile)
1243     iobuf_push_filter (inp, md_filter, &mfx);
1244
1245   if (detached && !encryptflag)
1246     afx->what = 2;
1247
1248   if (opt.armor && !outfile)
1249     push_armor_filter (afx, out);
1250
1251   if (encryptflag)
1252     {
1253       efx.pk_list = pk_list;
1254       /* fixme: set efx.cfx.datalen if known */
1255       iobuf_push_filter (out, encrypt_filter, &efx);
1256     }
1257
1258   if (opt.compress_algo && !outfile && !detached)
1259     {
1260       int compr_algo = opt.compress_algo;
1261
1262       if (!opt.explicit_compress_option
1263           && is_file_compressed (peekbuf, peekbuflen))
1264         {
1265           if (opt.verbose)
1266             log_info(_("'%s' already compressed\n"), fname? fname: "[stdin]");
1267           compr_algo = 0;
1268         }
1269       else if (compr_algo==-1)
1270         {
1271           /* If we're not encrypting, then select_algo_from_prefs
1272            * will fail and we'll end up with the default.  If we are
1273            * encrypting, select_algo_from_prefs cannot fail since
1274            * there is an assumed preference for uncompressed data.
1275            * Still, if it did fail, we'll also end up with the
1276            * default. */
1277           if ((compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP,
1278                                                     -1, NULL)) == -1)
1279             {
1280               compr_algo = default_compress_algo();
1281             }
1282         }
1283       else if (!opt.expert && pk_list
1284                && select_algo_from_prefs (pk_list, PREFTYPE_ZIP,
1285                                           compr_algo, NULL) != compr_algo)
1286         {
1287           log_info (_("WARNING: forcing compression algorithm %s (%d)"
1288                       " violates recipient preferences\n"),
1289                     compress_algo_to_string (compr_algo), compr_algo);
1290         }
1291
1292       /* Algo 0 means no compression. */
1293       if (compr_algo)
1294         push_compress_filter (out, &zfx, compr_algo);
1295     }
1296
1297   /* Write the one-pass signature packets if needed */
1298   if (!detached)
1299     {
1300       rc = write_onepass_sig_packets (sk_list, out,
1301                                       opt.textmode && !outfile ? 0x01:0x00);
1302       if (rc)
1303         goto leave;
1304     }
1305
1306   write_status_begin_signing (mfx.md);
1307
1308   /* Setup the inner packet. */
1309   if (detached)
1310     {
1311       size_t iobuf_size = iobuf_set_buffer_size(0) * 1024;
1312
1313       if (multifile)
1314         {
1315           strlist_t sl;
1316
1317           if (opt.verbose)
1318             log_info (_("signing:") );
1319           /* Must walk reverse trough this list.  */
1320           for (sl = strlist_last(filenames);
1321                sl;
1322                sl = strlist_prev( filenames, sl))
1323             {
1324               inp = iobuf_open (sl->d);
1325               if (inp && is_secured_file (iobuf_get_fd (inp)))
1326                 {
1327                   iobuf_close (inp);
1328                   inp = NULL;
1329                   gpg_err_set_errno (EPERM);
1330                 }
1331               if (!inp)
1332                 {
1333                   rc = gpg_error_from_syserror ();
1334                   log_error (_("can't open '%s': %s\n"),
1335                              sl->d, gpg_strerror (rc));
1336                   goto leave;
1337                 }
1338               handle_progress (pfx, inp, sl->d);
1339               if (opt.verbose)
1340                 log_printf (" '%s'", sl->d );
1341               if (opt.textmode)
1342                 {
1343                   memset (&tfx, 0, sizeof tfx);
1344                   iobuf_push_filter (inp, text_filter, &tfx);
1345                 }
1346               iobuf_push_filter (inp, md_filter, &mfx);
1347               while (iobuf_read (inp, NULL, iobuf_size) != -1)
1348                 ;
1349               iobuf_close (inp);
1350               inp = NULL;
1351             }
1352           if (opt.verbose)
1353             log_printf ("\n");
1354         }
1355       else
1356         {
1357           /* Read, so that the filter can calculate the digest. */
1358           while (iobuf_read (inp, NULL, iobuf_size) != -1)
1359             ;
1360         }
1361     }
1362   else
1363     {
1364       rc = write_plaintext_packet (out, inp, fname,
1365                                    (opt.textmode && !outfile) ?
1366                                    (opt.mimemode? 'm' : 't') : 'b',
1367                                    &extrahash);
1368     }
1369
1370   /* Catch errors from above. */
1371   if (rc)
1372     goto leave;
1373
1374   /* Write the signatures. */
1375   rc = write_signature_packets (ctrl, sk_list, out, mfx.md, extrahash,
1376                                 opt.textmode && !outfile? 0x01 : 0x00,
1377                                 0, duration, detached ? 'D':'S', NULL);
1378   if (rc)
1379     goto leave;
1380
1381
1382  leave:
1383   if (rc)
1384     iobuf_cancel (out);
1385   else
1386     {
1387       iobuf_close (out);
1388       if (encryptflag)
1389         write_status (STATUS_END_ENCRYPTION);
1390     }
1391   iobuf_close (inp);
1392   gcry_md_close (mfx.md);
1393   release_sk_list (sk_list);
1394   release_pk_list (pk_list);
1395   recipient_digest_algo = 0;
1396   release_progress_context (pfx);
1397   release_armor_context (afx);
1398   xfree (extrahash);
1399   return rc;
1400 }
1401
1402
1403 /*
1404  * Make a clear signature.  Note that opt.armor is not needed.
1405  */
1406 int
1407 clearsign_file (ctrl_t ctrl,
1408                 const char *fname, strlist_t locusr, const char *outfile)
1409 {
1410   armor_filter_context_t *afx;
1411   progress_filter_context_t *pfx;
1412   gcry_md_hd_t textmd = NULL;
1413   iobuf_t inp = NULL;
1414   iobuf_t out = NULL;
1415   PACKET pkt;
1416   int rc = 0;
1417   SK_LIST sk_list = NULL;
1418   SK_LIST sk_rover = NULL;
1419   u32 duration = 0;
1420   pt_extra_hash_data_t extrahash = NULL;
1421
1422   pfx = new_progress_context ();
1423   afx = new_armor_context ();
1424   init_packet( &pkt );
1425
1426   if (opt.ask_sig_expire && !opt.batch)
1427     duration = ask_expire_interval (1, opt.def_sig_expire);
1428   else
1429     duration = parse_expire_string (opt.def_sig_expire);
1430
1431   /* Note: In the old non-agent version the following call used to
1432    * unprotect the secret key.  This is now done on demand by the agent.  */
1433   if ((rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG)))
1434     goto leave;
1435
1436   /* Prepare iobufs.  */
1437   inp = iobuf_open (fname);
1438   if (inp && is_secured_file (iobuf_get_fd (inp)))
1439     {
1440       iobuf_close (inp);
1441       inp = NULL;
1442       gpg_err_set_errno (EPERM);
1443     }
1444   if (!inp)
1445     {
1446       rc = gpg_error_from_syserror ();
1447       log_error (_("can't open '%s': %s\n"),
1448                  fname? fname: "[stdin]", gpg_strerror (rc));
1449       goto leave;
1450     }
1451   handle_progress (pfx, inp, fname);
1452
1453   if (outfile)
1454     {
1455       if (is_secured_filename (outfile))
1456         {
1457           outfile = NULL;
1458           gpg_err_set_errno (EPERM);
1459         }
1460       else
1461         out = iobuf_create (outfile, 0);
1462
1463       if (!out)
1464         {
1465           rc = gpg_error_from_syserror ();
1466           log_error (_("can't create '%s': %s\n"), outfile, gpg_strerror (rc));
1467           goto leave;
1468         }
1469       else if (opt.verbose)
1470         log_info (_("writing to '%s'\n"), outfile);
1471
1472     }
1473   else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1474     {
1475       goto leave;
1476     }
1477
1478   iobuf_writestr (out, "-----BEGIN PGP SIGNED MESSAGE-----" LF);
1479
1480   {
1481     const char *s;
1482     int any = 0;
1483     byte hashs_seen[256];
1484
1485     memset (hashs_seen, 0, sizeof hashs_seen);
1486     iobuf_writestr (out, "Hash: " );
1487     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1488       {
1489         int i = hash_for (sk_rover->pk);
1490
1491         if (!hashs_seen[ i & 0xff ])
1492           {
1493             s = gcry_md_algo_name (i);
1494             if (s)
1495               {
1496                 hashs_seen[ i & 0xff ] = 1;
1497                 if (any)
1498                   iobuf_put (out, ',');
1499                 iobuf_writestr (out, s);
1500                 any = 1;
1501               }
1502           }
1503       }
1504     log_assert (any);
1505     iobuf_writestr (out, LF);
1506   }
1507
1508   if (opt.not_dash_escaped)
1509     iobuf_writestr (out,
1510                     "NotDashEscaped: You need "GPG_NAME
1511                     " to verify this message" LF);
1512   iobuf_writestr (out, LF );
1513
1514   if (gcry_md_open (&textmd, 0, 0))
1515     BUG ();
1516   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1517     gcry_md_enable (textmd, hash_for(sk_rover->pk));
1518
1519   if (DBG_HASHING)
1520     gcry_md_debug (textmd, "clearsign");
1521
1522   copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped, opt.escape_from);
1523   /* fixme: check for read errors */
1524
1525   /* Now write the armor. */
1526   afx->what = 2;
1527   push_armor_filter (afx, out);
1528
1529   /* Prepare EXTRAHASH, so that it can be used for v5 signature.  */
1530   extrahash = xtrymalloc (sizeof *extrahash);
1531   if (!extrahash)
1532     {
1533       rc = gpg_error_from_syserror ();
1534       goto leave;
1535     }
1536   else
1537     {
1538       extrahash->mode = 't';
1539       extrahash->timestamp = 0;
1540       extrahash->namelen = 0;
1541     }
1542
1543   /* Write the signatures.  */
1544   rc = write_signature_packets (ctrl, sk_list, out, textmd, extrahash,
1545                                 0x01, 0, duration, 'C', NULL);
1546   if (rc)
1547     goto leave;
1548
1549  leave:
1550   if (rc)
1551     iobuf_cancel (out);
1552   else
1553     iobuf_close (out);
1554   iobuf_close (inp);
1555   gcry_md_close (textmd);
1556   release_sk_list (sk_list);
1557   release_progress_context (pfx);
1558   release_armor_context (afx);
1559   xfree (extrahash);
1560   return rc;
1561 }
1562
1563
1564 /*
1565  * Sign and conventionally encrypt the given file.
1566  * FIXME: Far too much code is duplicated - revamp the whole file.
1567  */
1568 int
1569 sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
1570 {
1571   armor_filter_context_t *afx;
1572   progress_filter_context_t *pfx;
1573   compress_filter_context_t zfx;
1574   md_filter_context_t mfx;
1575   text_filter_context_t tfx;
1576   cipher_filter_context_t cfx;
1577   iobuf_t inp = NULL;
1578   iobuf_t out = NULL;
1579   PACKET pkt;
1580   STRING2KEY *s2k = NULL;
1581   int rc = 0;
1582   SK_LIST sk_list = NULL;
1583   SK_LIST sk_rover = NULL;
1584   int algo;
1585   u32 duration = 0;
1586   int canceled;
1587   pt_extra_hash_data_t extrahash = NULL;
1588
1589   pfx = new_progress_context ();
1590   afx = new_armor_context ();
1591   memset (&zfx, 0, sizeof zfx);
1592   memset (&mfx, 0, sizeof mfx);
1593   memset (&tfx, 0, sizeof tfx);
1594   memset (&cfx, 0, sizeof cfx);
1595   init_packet (&pkt);
1596
1597   if (opt.ask_sig_expire && !opt.batch)
1598     duration = ask_expire_interval (1, opt.def_sig_expire);
1599   else
1600     duration = parse_expire_string (opt.def_sig_expire);
1601
1602   /* Note: In the old non-agent version the following call used to
1603    * unprotect the secret key.  This is now done on demand by the agent.  */
1604   rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
1605   if (rc)
1606     goto leave;
1607
1608   /* Prepare iobufs.  */
1609   inp = iobuf_open (fname);
1610   if (inp && is_secured_file (iobuf_get_fd (inp)))
1611     {
1612       iobuf_close (inp);
1613       inp = NULL;
1614       gpg_err_set_errno (EPERM);
1615     }
1616   if (!inp)
1617     {
1618       rc = gpg_error_from_syserror ();
1619       log_error (_("can't open '%s': %s\n"),
1620                  fname? fname: "[stdin]", gpg_strerror (rc));
1621       goto leave;
1622     }
1623   handle_progress (pfx, inp, fname);
1624
1625   /* Prepare key.  */
1626   s2k = xmalloc_clear (sizeof *s2k);
1627   s2k->mode = opt.s2k_mode;
1628   s2k->hash_algo = S2K_DIGEST_ALGO;
1629
1630   algo = default_cipher_algo ();
1631   cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, 0, &canceled);
1632
1633   if (!cfx.dek || !cfx.dek->keylen)
1634     {
1635       rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1636       log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
1637       goto leave;
1638     }
1639
1640   cfx.dek->use_aead = use_aead (NULL, cfx.dek->algo);
1641   if (!cfx.dek->use_aead)
1642     cfx.dek->use_mdc = !!use_mdc (NULL, cfx.dek->algo);
1643
1644   if (!opt.quiet || !opt.batch)
1645     log_info (_("%s.%s encryption will be used\n"),
1646               openpgp_cipher_algo_name (algo),
1647               cfx.dek->use_aead? openpgp_aead_algo_name (cfx.dek->use_aead)
1648               /**/             : "CFB");
1649
1650   /* Now create the outfile.  */
1651   rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1652   if (rc)
1653     goto leave;
1654
1655   /* Prepare to calculate the MD over the input.  */
1656   if (opt.textmode)
1657     iobuf_push_filter (inp, text_filter, &tfx);
1658   if (gcry_md_open (&mfx.md, 0, 0))
1659     BUG ();
1660   if  (DBG_HASHING)
1661     gcry_md_debug (mfx.md, "symc-sign");
1662
1663   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1664     gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1665
1666   iobuf_push_filter (inp, md_filter, &mfx);
1667
1668   /* Push armor output filter */
1669   if (opt.armor)
1670     push_armor_filter (afx, out);
1671
1672   /* Write the symmetric key packet */
1673   /* (current filters: armor)*/
1674   {
1675     PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1676
1677     enc->version = cfx.dek->use_aead ? 5 : 4;
1678     enc->cipher_algo = cfx.dek->algo;
1679     enc->aead_algo = cfx.dek->use_aead;
1680     enc->s2k = *s2k;
1681     pkt.pkttype = PKT_SYMKEY_ENC;
1682     pkt.pkt.symkey_enc = enc;
1683     if ((rc = build_packet (out, &pkt)))
1684       log_error ("build symkey packet failed: %s\n", gpg_strerror (rc));
1685     xfree (enc);
1686   }
1687
1688   /* Push the encryption filter */
1689   iobuf_push_filter (out,
1690                      cfx.dek->use_aead? cipher_filter_aead
1691                      /**/             : cipher_filter_cfb,
1692                      &cfx);
1693
1694   /* Push the compress filter */
1695   if (default_compress_algo())
1696     {
1697       if (cfx.dek && (cfx.dek->use_mdc || cfx.dek->use_aead))
1698         zfx.new_ctb = 1;
1699       push_compress_filter (out, &zfx,default_compress_algo() );
1700     }
1701
1702   /* Write the one-pass signature packets */
1703   /* (current filters: zip - encrypt - armor) */
1704   rc = write_onepass_sig_packets (sk_list, out, opt.textmode? 0x01:0x00);
1705   if (rc)
1706     goto leave;
1707
1708   write_status_begin_signing (mfx.md);
1709
1710   /* Pipe data through all filters; i.e. write the signed stuff.  */
1711   /* (current filters: zip - encrypt - armor) */
1712   rc = write_plaintext_packet (out, inp, fname,
1713                                opt.textmode ? (opt.mimemode?'m':'t'):'b',
1714                                &extrahash);
1715   if (rc)
1716     goto leave;
1717
1718   /* Write the signatures.  */
1719   /* (current filters: zip - encrypt - armor) */
1720   rc = write_signature_packets (ctrl, sk_list, out, mfx.md, extrahash,
1721                                 opt.textmode? 0x01 : 0x00,
1722                                 0, duration, 'S', NULL);
1723   if (rc)
1724     goto leave;
1725
1726
1727  leave:
1728   if (rc)
1729     iobuf_cancel (out);
1730   else
1731     {
1732       iobuf_close (out);
1733       write_status (STATUS_END_ENCRYPTION);
1734     }
1735   iobuf_close (inp);
1736   release_sk_list (sk_list);
1737   gcry_md_close (mfx.md);
1738   xfree (cfx.dek);
1739   xfree (s2k);
1740   release_progress_context (pfx);
1741   release_armor_context (afx);
1742   xfree (extrahash);
1743   return rc;
1744 }
1745
1746
1747 /*
1748  * Create a v4 signature in *RET_SIG.
1749  *
1750  * PK is the primary key to sign (required for all sigs)
1751  * UID is the user id to sign (required for 0x10..0x13, 0x30)
1752  * SUBPK is subkey to sign (required for 0x18, 0x19, 0x28)
1753  *
1754  * PKSK is the signing key
1755  *
1756  * SIGCLASS is the type of signature to create.
1757  *
1758  * TIMESTAMP is the timestamp to use for the signature. 0 means "now"
1759  *
1760  * DURATION is the amount of time (in seconds) until the signature
1761  * expires.
1762  *
1763  * If CACHED_NONCE is not NULL the agent may use it to avoid
1764  * additional pinnetry popups for the same keyblock.
1765  *
1766  * This function creates the following subpackets: issuer, created,
1767  * and expire (if duration is not 0).  Additional subpackets can be
1768  * added using MKSUBPKT, which is called after these subpackets are
1769  * added and before the signature is generated.  OPAQUE is passed to
1770  * MKSUBPKT.
1771  */
1772 int
1773 make_keysig_packet (ctrl_t ctrl,
1774                     PKT_signature **ret_sig, PKT_public_key *pk,
1775                     PKT_user_id *uid, PKT_public_key *subpk,
1776                     PKT_public_key *pksk,
1777                     int sigclass,
1778                     u32 timestamp, u32 duration,
1779                     int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1780                     const char *cache_nonce)
1781 {
1782   PKT_signature *sig;
1783   int rc = 0;
1784   int sigversion;
1785   int digest_algo;
1786   gcry_md_hd_t md;
1787   u32 pk_keyid[2], pksk_keyid[2];
1788   unsigned int signhints;
1789
1790   log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1791               || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1792               || sigclass == 0x30 || sigclass == 0x28 );
1793
1794   if (pksk->version >= 5)
1795     sigversion = 5;
1796   else
1797     sigversion = 4;
1798
1799   /* Select the digest algo to use. */
1800   if (opt.cert_digest_algo)     /* Forceful override by the user.  */
1801     digest_algo = opt.cert_digest_algo;
1802   else if (pksk->pubkey_algo == PUBKEY_ALGO_DSA) /* Meet DSA requirements.  */
1803     digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1804   else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA) /* Meet ECDSA requirements. */
1805     digest_algo = match_dsa_hash
1806       (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1807   else if (pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1808     {
1809       if (gcry_mpi_get_nbits (pksk->pkey[1]) > 256)
1810         digest_algo = DIGEST_ALGO_SHA512;
1811       else
1812         digest_algo = DIGEST_ALGO_SHA256;
1813     }
1814   else /* Use the default.  */
1815     digest_algo = DEFAULT_DIGEST_ALGO;
1816
1817   signhints = SIGNHINT_KEYSIG;
1818   keyid_from_pk (pk, pk_keyid);
1819   keyid_from_pk (pksk, pksk_keyid);
1820   if (pk_keyid[0] == pksk_keyid[0] && pk_keyid[1] == pksk_keyid[1])
1821     signhints |= SIGNHINT_SELFSIG;
1822
1823   if (gcry_md_open (&md, digest_algo, 0))
1824     BUG ();
1825
1826   /* Hash the public key certificate. */
1827   hash_public_key (md, pk);
1828
1829   if (sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28)
1830     {
1831       /* Hash the subkey binding/backsig/revocation.  */
1832       hash_public_key (md, subpk);
1833       if ((subpk->pubkey_usage & PUBKEY_USAGE_RENC))
1834         signhints |= SIGNHINT_ADSK;
1835     }
1836   else if (sigclass != 0x1F && sigclass != 0x20)
1837     {
1838       /* Hash the user id. */
1839       hash_uid (md, sigversion, uid);
1840     }
1841   /* Make the signature packet.  */
1842   sig = xmalloc_clear (sizeof *sig);
1843   sig->version = sigversion;
1844   sig->flags.exportable = 1;
1845   sig->flags.revocable = 1;
1846   keyid_from_pk (pksk, sig->keyid);
1847   sig->pubkey_algo = pksk->pubkey_algo;
1848   sig->digest_algo = digest_algo;
1849   sig->timestamp = timestamp? timestamp : make_timestamp ();
1850   if (duration)
1851     sig->expiredate = sig->timestamp + duration;
1852   sig->sig_class = sigclass;
1853
1854   build_sig_subpkt_from_sig (sig, pksk, signhints);
1855   mk_notation_policy_etc (ctrl, sig, pk, pksk);
1856
1857   /* Crucial that the call to mksubpkt comes LAST before the calls
1858    * to finalize the sig as that makes it possible for the mksubpkt
1859    * function to get a reliable pointer to the subpacket area. */
1860   if (mksubpkt)
1861     rc = (*mksubpkt)(sig, opaque);
1862
1863   if (!rc)
1864     {
1865       hash_sigversion_to_magic (md, sig, NULL);
1866       gcry_md_final (md);
1867       rc = complete_sig (ctrl, sig, pksk, md, cache_nonce, signhints);
1868     }
1869
1870   gcry_md_close (md);
1871   if (rc)
1872     free_seckey_enc (sig);
1873   else
1874     *ret_sig = sig;
1875   return rc;
1876 }
1877
1878
1879
1880 /*
1881  * Create a new signature packet based on an existing one.
1882  * Only user ID signatures are supported for now.
1883  * PK is the public key to work on.
1884  * PKSK is the key used to make the signature.
1885  *
1886  * TODO: Merge this with make_keysig_packet.
1887  */
1888 gpg_error_t
1889 update_keysig_packet (ctrl_t ctrl,
1890                       PKT_signature **ret_sig,
1891                       PKT_signature *orig_sig,
1892                       PKT_public_key *pk,
1893                       PKT_user_id *uid,
1894                       PKT_public_key *subpk,
1895                       PKT_public_key *pksk,
1896                       int (*mksubpkt)(PKT_signature *, void *),
1897                       void *opaque)
1898 {
1899   PKT_signature *sig;
1900   gpg_error_t rc = 0;
1901   int digest_algo;
1902   gcry_md_hd_t md;
1903   u32 pk_keyid[2], pksk_keyid[2];
1904   unsigned int signhints = 0;
1905
1906   if ((!orig_sig || !pk || !pksk)
1907       || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1908       || (orig_sig->sig_class == 0x18 && !subpk))
1909     return GPG_ERR_GENERAL;
1910
1911   /* Either use the override digest algo or in the normal case the
1912    * original digest algorithm.  However, iff the original digest
1913    * algorithms is SHA-1 and we are in gnupg or de-vs compliance mode
1914    * we switch to SHA-256 (done by the macro).  */
1915   if  (opt.cert_digest_algo)
1916     digest_algo = opt.cert_digest_algo;
1917   else if (pksk->pubkey_algo == PUBKEY_ALGO_DSA
1918            || pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1919            || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1920     digest_algo = orig_sig->digest_algo;
1921   else if (orig_sig->digest_algo == DIGEST_ALGO_SHA1
1922            || orig_sig->digest_algo == DIGEST_ALGO_RMD160)
1923     digest_algo = DEFAULT_DIGEST_ALGO;
1924   else
1925     digest_algo = orig_sig->digest_algo;
1926
1927   signhints = SIGNHINT_KEYSIG;
1928   keyid_from_pk (pk, pk_keyid);
1929   keyid_from_pk (pksk, pksk_keyid);
1930   if (pk_keyid[0] == pksk_keyid[0] && pk_keyid[1] == pksk_keyid[1])
1931     signhints |= SIGNHINT_SELFSIG;
1932
1933   if (gcry_md_open (&md, digest_algo, 0))
1934     BUG ();
1935
1936   /* Hash the public key certificate and the user id. */
1937   hash_public_key (md, pk);
1938
1939   if (orig_sig->sig_class == 0x18)
1940     hash_public_key (md, subpk);
1941   else
1942     hash_uid (md, orig_sig->version, uid);
1943
1944   /* Create a new signature packet.  */
1945   sig = copy_signature (NULL, orig_sig);
1946
1947   /* Don't generate version 3 signature, but newer.  */
1948   if (sig->version == 3)
1949     {
1950       if (pk->version > 3)
1951         sig->version = pk->version;
1952       else
1953         sig->version = 4;
1954     }
1955
1956   sig->digest_algo = digest_algo;
1957
1958   /* We need to create a new timestamp so that new sig expiration
1959    * calculations are done correctly... */
1960   sig->timestamp = make_timestamp();
1961
1962   /* ... but we won't make a timestamp earlier than the existing
1963    * one. */
1964   {
1965     int tmout = 0;
1966     while (sig->timestamp <= orig_sig->timestamp)
1967       {
1968         if (++tmout > 5 && !opt.ignore_time_conflict)
1969           {
1970             rc = gpg_error (GPG_ERR_TIME_CONFLICT);
1971             goto leave;
1972           }
1973         gnupg_sleep (1);
1974         sig->timestamp = make_timestamp();
1975       }
1976   }
1977
1978   /* Detect an ADSK key binding signature.  */
1979   if ((sig->sig_class == 0x18
1980        || sig->sig_class == 0x19 || sig->sig_class == 0x28)
1981       && (pk->pubkey_usage & PUBKEY_USAGE_RENC))
1982     signhints |= SIGNHINT_ADSK;
1983
1984   /* Note that already expired sigs will remain expired (with a
1985    * duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1986    * detects this case. */
1987
1988   /* Put the updated timestamp into the sig.  Note that this will
1989    * automagically lower any sig expiration dates to correctly
1990    * correspond to the differences in the timestamps (i.e. the
1991    * duration will shrink).  */
1992   build_sig_subpkt_from_sig (sig, pksk, signhints);
1993
1994   if (mksubpkt)
1995     rc = (*mksubpkt)(sig, opaque);
1996
1997   if (!rc)
1998     {
1999       hash_sigversion_to_magic (md, sig, NULL);
2000       gcry_md_final (md);
2001       rc = complete_sig (ctrl, sig, pksk, md, NULL, signhints);
2002     }
2003
2004  leave:
2005   gcry_md_close (md);
2006   if (rc)
2007     free_seckey_enc (sig);
2008   else
2009     *ret_sig = sig;
2010   return rc;
2011 }