2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 2010, 2012 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
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/>.
30 #include "../common/status.h"
31 #include "../common/iobuf.h"
33 #include "../common/util.h"
36 #include "../common/ttyio.h"
38 #include "../common/status.h"
39 #include "../common/i18n.h"
41 #include "../common/sysutils.h"
42 #include "call-agent.h"
43 #include "../common/mbox-util.h"
44 #include "../common/compliance.h"
46 #ifdef HAVE_DOSISH_SYSTEM
54 static int recipient_digest_algo;
57 /* A type for the extra data we hash into v5 signature packets. */
58 struct pt_extra_hash_data_s
62 unsigned char namelen;
65 typedef struct pt_extra_hash_data_s *pt_extra_hash_data_t;
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.
74 mk_notation_policy_etc (ctrl_t ctrl, PKT_signature *sig,
75 PKT_public_key *pk, PKT_public_key *pksk)
80 struct notation *nd = NULL;
81 struct expando_args args;
83 log_assert (sig->version >= 4);
85 memset (&args, 0, sizeof(args));
90 if (IS_ATTST_SIGS(sig))
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;
99 struct notation *item;
101 for (item = nd; item; item = item->next)
103 item->altvalue = pct_expando (ctrl, item->value,&args);
105 log_error (_("WARNING: unable to %%-expand notation "
106 "(too large). Using unexpanded.\n"));
109 keygen_add_notations (sig, nd);
111 for (item = nd; item; item = item->next)
113 xfree (item->altvalue);
114 item->altvalue = NULL;
118 /* Set policy URL. */
119 if (IS_ATTST_SIGS(sig))
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;
126 for (; pu; pu = pu->next)
130 p = pct_expando (ctrl, string, &args);
133 log_error(_("WARNING: unable to %%-expand policy URL "
134 "(too large). Using unexpanded.\n"));
138 build_sig_subpkt (sig, (SIGSUBPKT_POLICY
139 | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
145 /* Preferred keyserver URL. */
146 if (IS_SIG(sig) && opt.sig_keyserver_url)
147 pu = opt.sig_keyserver_url;
149 for (; pu; pu = pu->next)
153 p = pct_expando (ctrl, string, &args);
156 log_error (_("WARNING: unable to %%-expand preferred keyserver URL"
157 " (too large). Using unexpanded.\n"));
158 p = xstrdup (string);
161 build_sig_subpkt (sig, (SIGSUBPKT_PREF_KS
162 | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
167 /* Set signer's user id. */
168 if (IS_SIG (sig) && !opt.flags.disable_signer_uid)
172 /* For now we use the uid which was used to locate the key. */
174 && (mbox = mailbox_from_userid (pksk->user_id->name, 0)))
177 log_debug ("setting Signer's UID to '%s'\n", mbox);
178 build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, mbox, strlen (mbox));
181 else if (opt.sender_list)
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. */
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));
202 * Put the Key Block subpacket into SIG for key PKSK. Returns an
203 * error code on failure.
206 mk_sig_subpkt_key_block (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pksk)
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];
216 kbnode_t keyblock = NULL;
218 push_export_filters ();
221 hexfingerprint (pksk, hexfpr, sizeof hexfpr);
223 /* Get the user id so that we know which one to insert into the
226 && (mbox = mailbox_from_userid (pksk->user_id->name, 0)))
229 log_debug ("including key with UID '%s' (specified)\n", mbox);
230 filterexp = xasprintf ("keep-uid= -- mbox = %s", mbox);
233 else if (opt.sender_list)
235 /* If --sender was given we use the first one from that list. */
237 log_debug ("including key with UID '%s' (--sender)\n",
239 filterexp = xasprintf ("keep-uid= -- mbox = %s", opt.sender_list->d);
241 else /* Use the primary user id. */
244 log_debug ("including key with primary UID\n");
245 filterexp = xstrdup ("keep-uid= primary -t");
249 log_debug ("export filter expression: %s\n", filterexp);
250 err = parse_and_set_export_filter (filterexp);
254 filterexp = xasprintf ("drop-subkey= fpr <> %s && usage !~ e", hexfpr);
256 log_debug ("export filter expression: %s\n", filterexp);
257 err = parse_and_set_export_filter (filterexp);
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;
269 log_error ("failed to get to be included key: %s\n", gpg_strerror (err));
273 build_sig_subpkt (sig, SIGSUBPKT_KEY_BLOCK, data, datalen);
277 release_kbnode (keyblock);
279 opt.armor = save_opt_armor;
280 pop_export_filters ();
286 * Helper to hash a user ID packet.
289 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
295 if (uid->attrib_data)
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;
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;
311 gcry_md_write( md, buf, 5 );
313 if (uid->attrib_data)
314 gcry_md_write (md, uid->attrib_data, uid->attrib_len );
316 gcry_md_write (md, uid->name, uid->len );
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.
326 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig,
327 pt_extra_hash_data_t extrahash)
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);
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 );
347 gcry_md_putc (md, 0); /* Always hash the length of the subpacket. */
348 gcry_md_putc (md, 0);
351 /* Hash data from the literal data packet. */
352 if (sig->version >= 5 && (sig->sig_class == 0x00 || sig->sig_class == 0x01))
354 /* - One octet content format
355 * - File name (one octet length followed by the name)
356 * - Four octet timestamp */
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);
370 else /* Detached signatures */
373 gcry_md_write (md, buf, 6);
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
383 buf[i++] = sig->version; /* Hash convention version. */
384 buf[i++] = 0xff; /* Not any sig type value. */
385 if (sig->version >= 5)
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. */
394 buf[i++] = n >> 24; /* (n is only 16 bit, so this is always 0) */
398 gcry_md_write (md, buf, i);
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. */
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)
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))
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);
429 print_pubkey_algo_note (pksk->pubkey_algo);
432 mdalgo = gcry_md_get_algo (md);
434 if ((signhints & SIGNHINT_KEYSIG) && !(signhints & SIGNHINT_SELFSIG)
435 && mdalgo == GCRY_MD_SHA1
436 && !opt.flags.allow_weak_key_signatures)
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);
447 /* Check compliance. */
448 if (! gnupg_digest_is_allowed (opt.compliance, 1, mdalgo))
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);
457 if (! gnupg_pk_is_allowed (opt.compliance, PK_USE_SIGNING,
458 pksk->pubkey_algo, 0,
459 pksk->pkey, nbits_from_pk (pksk), NULL))
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);
468 if (!gnupg_rng_is_compliant (opt.compliance))
470 err = gpg_error (GPG_ERR_FORBIDDEN);
471 log_error (_("%s is not compliant with %s mode\n"),
473 gnupg_compliance_option_string (opt.compliance));
474 write_status_error ("random-compliance", err);
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]);
485 mpi_release (sig->data[1]);
489 err = hexkeygrip_from_pk (pksk, &hexgrip);
493 gcry_sexp_t s_sigval;
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,
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]))
510 err = sexp_extract_param_sos_nlz (s_sigval, "r", &sig->data[0]);
512 err = sexp_extract_param_sos_nlz (s_sigval, "s", &sig->data[1]);
514 else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
515 || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
517 err = sexp_extract_param_sos (s_sigval, "r", &sig->data[0]);
519 err = sexp_extract_param_sos (s_sigval, "s", &sig->data[1]);
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);
527 gcry_sexp_release (s_sigval);
533 log_error (_("signing failed: %s\n"), gpg_strerror (err));
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),
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)
557 /* if (!(rc = check_secret_key (pksk, 0))) */
558 rc = do_sign (ctrl, pksk, sig, md, 0, cache_nonce, signhints);
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. */
567 openpgp_card_v1_p (PKT_public_key *pk)
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))
577 if (!pk->flags.serialno_valid)
581 err = hexkeygrip_from_pk (pk, &hexgrip);
584 log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
585 return 0; /* Ooops. */
588 xfree (pk->serialno);
589 agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL);
591 pk->flags.serialno_valid = 1;
595 result = 0; /* Error from a past agent_get_keyinfo or no card. */
598 /* The version number of the card is included in the serialno. */
599 result = !strncmp (pk->serialno, "D2760001240101", 14);
605 /* Get a matching hash algorithm for DSA and ECDSA. */
607 match_dsa_hash (unsigned int qbytes)
610 return DIGEST_ALGO_SHA1;
613 return DIGEST_ALGO_SHA224;
616 return DIGEST_ALGO_SHA256;
619 return DIGEST_ALGO_SHA384;
621 if (qbytes <= 66 ) /* 66 corresponds to 521 (64 to 512) */
622 return DIGEST_ALGO_SHA512;
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. */
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).
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.
643 Possible improvement: Use the highest-ranked usable algorithm from
644 the signing key prefs either before or after using the personal
648 hash_for (PKT_public_key *pk)
650 if (opt.def_digest_algo)
652 return opt.def_digest_algo;
654 else if (recipient_digest_algo && !is_weak_digest (recipient_digest_algo))
656 return recipient_digest_algo;
658 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
660 if (opt.personal_digest_prefs)
661 return opt.personal_digest_prefs[0].value;
663 if (gcry_mpi_get_nbits (pk->pkey[1]) > 256)
664 return DIGEST_ALGO_SHA512;
666 return DIGEST_ALGO_SHA256;
668 else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
669 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
671 unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
673 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
674 qbytes = ecdsa_qbits_from_Q (qbytes);
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). */
688 if (pk->pubkey_algo == PUBKEY_ALGO_DSA && opt.personal_digest_prefs)
692 if (qbytes != 20 || opt.flags.dsa2)
694 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
695 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
700 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
701 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
706 return match_dsa_hash(qbytes);
708 else if (openpgp_card_v1_p (pk))
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)
719 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
720 if (prefs->value==DIGEST_ALGO_SHA1
721 || prefs->value==DIGEST_ALGO_RMD160)
725 return DIGEST_ALGO_SHA1;
727 else if (opt.personal_digest_prefs)
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;
734 return DEFAULT_DIGEST_ALGO;
739 print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
741 byte array[MAX_FINGERPRINT_LEN];
742 char buf[100+MAX_FINGERPRINT_LEN*2];
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));
751 write_status_text( STATUS_SIG_CREATED, buf );
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.
762 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
767 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
770 for (; skcount; skcount--)
773 PKT_onepass_sig *ops;
777 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
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);
790 pkt.pkttype = PKT_ONEPASS_SIG;
791 pkt.pkt.onepass_sig = ops;
792 rc = build_packet (out, &pkt);
793 free_packet (&pkt, NULL);
796 log_error ("build onepass_sig packet failed: %s\n",
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.
812 write_plaintext_packet (iobuf_t out, iobuf_t inp,
813 const char *fname, int ptmode,
814 pt_extra_hash_data_t *r_extrahash)
816 PKT_plaintext *pt = NULL;
821 pt = setup_plaintext_name (fname, inp);
823 /* Try to calculate the length of the data. */
824 if ( !iobuf_is_pipe_filename (fname) && *fname)
828 tmpsize = iobuf_get_filelength (inp);
829 if (!tmpsize && opt.verbose)
830 log_info (_("WARNING: '%s' is an empty file\n"), fname);
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))
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')
849 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
855 /* Note that PT has been initialized above in no_literal mode. */
856 pt->timestamp = make_timestamp ();
859 pt->new_ctb = !pt->len;
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",
869 *r_extrahash = xtrymalloc (sizeof **r_extrahash + pt->namelen);
871 rc = gpg_error_from_syserror ();
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);
882 free_packet (&pkt, NULL);
886 byte copy_buffer[4096];
889 *r_extrahash = xtrymalloc (sizeof **r_extrahash);
892 rc = gpg_error_from_syserror ();
895 /* FIXME: We need to parse INP to get the to be hashed data from
897 (*r_extrahash)->mode = 0;
898 (*r_extrahash)->timestamp = 0;
899 (*r_extrahash)->namelen = 0;
901 while ((bytes_copied = iobuf_read (inp, copy_buffer, 4096)) != -1)
902 if ((rc = iobuf_write (out, copy_buffer, bytes_copied)))
904 log_error ("copying input to output failed: %s\n",
908 wipememory (copy_buffer, 4096); /* burn buffer */
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.
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)
930 /* Loop over the certificates with secret keys. */
931 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
940 /* Build the signature packet. */
941 sig = xtrycalloc (1, sizeof *sig);
943 return gpg_error_from_syserror ();
945 if (pk->version >= 5)
946 sig->version = 5; /* Required for v5 keys. */
948 sig->version = 4; /* Required. */
950 keyid_from_pk (pk, sig->keyid);
951 sig->digest_algo = hash_for (pk);
952 sig->pubkey_algo = pk->pubkey_algo;
954 sig->timestamp = timestamp;
956 sig->timestamp = make_timestamp();
958 sig->expiredate = sig->timestamp + duration;
959 sig->sig_class = sigclass;
961 if (gcry_md_copy (&md, hash))
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);
970 hash_sigversion_to_magic (md, sig, extrahash);
974 err = do_sign (ctrl, pk, sig, md, hash_for (pk), cache_nonce, 0);
978 /* Write the packet. */
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);
989 log_error ("build signature packet failed: %s\n",
993 free_seckey_enc (sig);
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
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
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.
1017 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
1018 int encryptflag, strlist_t remusr, const char *outfile )
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;
1031 PK_LIST pk_list = NULL;
1032 SK_LIST sk_list = NULL;
1033 SK_LIST sk_rover = NULL;
1036 pt_extra_hash_data_t extrahash = NULL;
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);
1051 fname = filenames->d;
1052 multifile = !!filenames->next;
1057 if (fname && filenames->next && (!detached || encryptflag))
1058 log_bug ("multiple files can only be detached signed");
1060 if (encryptflag == 2
1061 && (rc = setup_symkey (&efx.symkey_s2k, &efx.symkey_dek)))
1064 if (opt.ask_sig_expire && !opt.batch)
1065 duration = ask_expire_interval(1,opt.def_sig_expire);
1067 duration = parse_expire_string(opt.def_sig_expire);
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 )))
1075 && (rc = build_pk_list (ctrl, remusr, &pk_list)))
1078 /* Prepare iobufs. */
1079 if (multifile) /* have list of filenames */
1080 inp = NULL; /* we do it later */
1083 inp = iobuf_open(fname);
1084 if (inp && is_secured_file (iobuf_get_fd (inp)))
1088 gpg_err_set_errno (EPERM);
1092 rc = gpg_error_from_syserror ();
1093 log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
1098 peekbuflen = iobuf_ioctl (inp, IOBUF_IOCTL_PEEK, sizeof peekbuf, peekbuf);
1103 log_debug ("peeking at input failed\n");
1106 handle_progress (pfx, inp, fname);
1111 if (is_secured_filename (outfile))
1114 gpg_err_set_errno (EPERM);
1117 out = iobuf_create (outfile, 0);
1120 rc = gpg_error_from_syserror ();
1121 log_error (_("can't create '%s': %s\n"), outfile, gpg_strerror (rc));
1124 else if (opt.verbose)
1125 log_info (_("writing to '%s'\n"), outfile);
1127 else if ((rc = open_outfile (-1, fname,
1128 opt.armor? 1 : detached? 2 : 0, 0, &out)))
1133 /* Prepare to calculate the MD over the input. */
1134 if (opt.textmode && !outfile && !multifile)
1136 memset (&tfx, 0, sizeof tfx);
1137 iobuf_push_filter (inp, text_filter, &tfx);
1140 if (gcry_md_open (&mfx.md, 0, 0))
1143 gcry_md_debug (mfx.md, "sign");
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. */
1154 if (opt.def_digest_algo)
1157 && select_algo_from_prefs (pk_list,PREFTYPE_HASH,
1158 opt.def_digest_algo,
1159 NULL) != opt.def_digest_algo)
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);
1171 struct pref_hint hint = { 0 };
1173 hint.digest_length = 0;
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
1191 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
1193 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
1194 || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1196 int temp_hashlen = gcry_mpi_get_nbits (sk_rover->pk->pkey[1]);
1198 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1200 temp_hashlen = ecdsa_qbits_from_Q (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)
1210 temp_hashlen = (temp_hashlen+7)/8;
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
1216 if (hint.digest_length < temp_hashlen)
1218 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
1224 hint.digest_length = temp_hashlen;
1230 && (algo = select_algo_from_prefs (pk_list, PREFTYPE_HASH,
1233 /* Note that we later check that the algo is not weak. */
1234 recipient_digest_algo = algo;
1239 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1240 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1243 iobuf_push_filter (inp, md_filter, &mfx);
1245 if (detached && !encryptflag)
1248 if (opt.armor && !outfile)
1249 push_armor_filter (afx, out);
1253 efx.pk_list = pk_list;
1254 /* fixme: set efx.cfx.datalen if known */
1255 iobuf_push_filter (out, encrypt_filter, &efx);
1258 if (opt.compress_algo && !outfile && !detached)
1260 int compr_algo = opt.compress_algo;
1262 if (!opt.explicit_compress_option
1263 && is_file_compressed (peekbuf, peekbuflen))
1266 log_info(_("'%s' already compressed\n"), fname? fname: "[stdin]");
1269 else if (compr_algo==-1)
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
1277 if ((compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP,
1280 compr_algo = default_compress_algo();
1283 else if (!opt.expert && pk_list
1284 && select_algo_from_prefs (pk_list, PREFTYPE_ZIP,
1285 compr_algo, NULL) != compr_algo)
1287 log_info (_("WARNING: forcing compression algorithm %s (%d)"
1288 " violates recipient preferences\n"),
1289 compress_algo_to_string (compr_algo), compr_algo);
1292 /* Algo 0 means no compression. */
1294 push_compress_filter (out, &zfx, compr_algo);
1297 /* Write the one-pass signature packets if needed */
1300 rc = write_onepass_sig_packets (sk_list, out,
1301 opt.textmode && !outfile ? 0x01:0x00);
1306 write_status_begin_signing (mfx.md);
1308 /* Setup the inner packet. */
1311 size_t iobuf_size = iobuf_set_buffer_size(0) * 1024;
1318 log_info (_("signing:") );
1319 /* Must walk reverse trough this list. */
1320 for (sl = strlist_last(filenames);
1322 sl = strlist_prev( filenames, sl))
1324 inp = iobuf_open (sl->d);
1325 if (inp && is_secured_file (iobuf_get_fd (inp)))
1329 gpg_err_set_errno (EPERM);
1333 rc = gpg_error_from_syserror ();
1334 log_error (_("can't open '%s': %s\n"),
1335 sl->d, gpg_strerror (rc));
1338 handle_progress (pfx, inp, sl->d);
1340 log_printf (" '%s'", sl->d );
1343 memset (&tfx, 0, sizeof tfx);
1344 iobuf_push_filter (inp, text_filter, &tfx);
1346 iobuf_push_filter (inp, md_filter, &mfx);
1347 while (iobuf_read (inp, NULL, iobuf_size) != -1)
1357 /* Read, so that the filter can calculate the digest. */
1358 while (iobuf_read (inp, NULL, iobuf_size) != -1)
1364 rc = write_plaintext_packet (out, inp, fname,
1365 (opt.textmode && !outfile) ?
1366 (opt.mimemode? 'm' : 't') : 'b',
1370 /* Catch errors from above. */
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);
1389 write_status (STATUS_END_ENCRYPTION);
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);
1404 * Make a clear signature. Note that opt.armor is not needed.
1407 clearsign_file (ctrl_t ctrl,
1408 const char *fname, strlist_t locusr, const char *outfile)
1410 armor_filter_context_t *afx;
1411 progress_filter_context_t *pfx;
1412 gcry_md_hd_t textmd = NULL;
1417 SK_LIST sk_list = NULL;
1418 SK_LIST sk_rover = NULL;
1420 pt_extra_hash_data_t extrahash = NULL;
1422 pfx = new_progress_context ();
1423 afx = new_armor_context ();
1424 init_packet( &pkt );
1426 if (opt.ask_sig_expire && !opt.batch)
1427 duration = ask_expire_interval (1, opt.def_sig_expire);
1429 duration = parse_expire_string (opt.def_sig_expire);
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)))
1436 /* Prepare iobufs. */
1437 inp = iobuf_open (fname);
1438 if (inp && is_secured_file (iobuf_get_fd (inp)))
1442 gpg_err_set_errno (EPERM);
1446 rc = gpg_error_from_syserror ();
1447 log_error (_("can't open '%s': %s\n"),
1448 fname? fname: "[stdin]", gpg_strerror (rc));
1451 handle_progress (pfx, inp, fname);
1455 if (is_secured_filename (outfile))
1458 gpg_err_set_errno (EPERM);
1461 out = iobuf_create (outfile, 0);
1465 rc = gpg_error_from_syserror ();
1466 log_error (_("can't create '%s': %s\n"), outfile, gpg_strerror (rc));
1469 else if (opt.verbose)
1470 log_info (_("writing to '%s'\n"), outfile);
1473 else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1478 iobuf_writestr (out, "-----BEGIN PGP SIGNED MESSAGE-----" LF);
1483 byte hashs_seen[256];
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)
1489 int i = hash_for (sk_rover->pk);
1491 if (!hashs_seen[ i & 0xff ])
1493 s = gcry_md_algo_name (i);
1496 hashs_seen[ i & 0xff ] = 1;
1498 iobuf_put (out, ',');
1499 iobuf_writestr (out, s);
1505 iobuf_writestr (out, LF);
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 );
1514 if (gcry_md_open (&textmd, 0, 0))
1516 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1517 gcry_md_enable (textmd, hash_for(sk_rover->pk));
1520 gcry_md_debug (textmd, "clearsign");
1522 copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped, opt.escape_from);
1523 /* fixme: check for read errors */
1525 /* Now write the armor. */
1527 push_armor_filter (afx, out);
1529 /* Prepare EXTRAHASH, so that it can be used for v5 signature. */
1530 extrahash = xtrymalloc (sizeof *extrahash);
1533 rc = gpg_error_from_syserror ();
1538 extrahash->mode = 't';
1539 extrahash->timestamp = 0;
1540 extrahash->namelen = 0;
1543 /* Write the signatures. */
1544 rc = write_signature_packets (ctrl, sk_list, out, textmd, extrahash,
1545 0x01, 0, duration, 'C', NULL);
1555 gcry_md_close (textmd);
1556 release_sk_list (sk_list);
1557 release_progress_context (pfx);
1558 release_armor_context (afx);
1565 * Sign and conventionally encrypt the given file.
1566 * FIXME: Far too much code is duplicated - revamp the whole file.
1569 sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
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;
1580 STRING2KEY *s2k = NULL;
1582 SK_LIST sk_list = NULL;
1583 SK_LIST sk_rover = NULL;
1587 pt_extra_hash_data_t extrahash = NULL;
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);
1597 if (opt.ask_sig_expire && !opt.batch)
1598 duration = ask_expire_interval (1, opt.def_sig_expire);
1600 duration = parse_expire_string (opt.def_sig_expire);
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);
1608 /* Prepare iobufs. */
1609 inp = iobuf_open (fname);
1610 if (inp && is_secured_file (iobuf_get_fd (inp)))
1614 gpg_err_set_errno (EPERM);
1618 rc = gpg_error_from_syserror ();
1619 log_error (_("can't open '%s': %s\n"),
1620 fname? fname: "[stdin]", gpg_strerror (rc));
1623 handle_progress (pfx, inp, fname);
1626 s2k = xmalloc_clear (sizeof *s2k);
1627 s2k->mode = opt.s2k_mode;
1628 s2k->hash_algo = S2K_DIGEST_ALGO;
1630 algo = default_cipher_algo ();
1631 cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, 0, &canceled);
1633 if (!cfx.dek || !cfx.dek->keylen)
1635 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1636 log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
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);
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)
1650 /* Now create the outfile. */
1651 rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1655 /* Prepare to calculate the MD over the input. */
1657 iobuf_push_filter (inp, text_filter, &tfx);
1658 if (gcry_md_open (&mfx.md, 0, 0))
1661 gcry_md_debug (mfx.md, "symc-sign");
1663 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1664 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1666 iobuf_push_filter (inp, md_filter, &mfx);
1668 /* Push armor output filter */
1670 push_armor_filter (afx, out);
1672 /* Write the symmetric key packet */
1673 /* (current filters: armor)*/
1675 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1677 enc->version = cfx.dek->use_aead ? 5 : 4;
1678 enc->cipher_algo = cfx.dek->algo;
1679 enc->aead_algo = cfx.dek->use_aead;
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));
1688 /* Push the encryption filter */
1689 iobuf_push_filter (out,
1690 cfx.dek->use_aead? cipher_filter_aead
1691 /**/ : cipher_filter_cfb,
1694 /* Push the compress filter */
1695 if (default_compress_algo())
1697 if (cfx.dek && (cfx.dek->use_mdc || cfx.dek->use_aead))
1699 push_compress_filter (out, &zfx,default_compress_algo() );
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);
1708 write_status_begin_signing (mfx.md);
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',
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);
1733 write_status (STATUS_END_ENCRYPTION);
1736 release_sk_list (sk_list);
1737 gcry_md_close (mfx.md);
1740 release_progress_context (pfx);
1741 release_armor_context (afx);
1748 * Create a v4 signature in *RET_SIG.
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)
1754 * PKSK is the signing key
1756 * SIGCLASS is the type of signature to create.
1758 * TIMESTAMP is the timestamp to use for the signature. 0 means "now"
1760 * DURATION is the amount of time (in seconds) until the signature
1763 * If CACHED_NONCE is not NULL the agent may use it to avoid
1764 * additional pinnetry popups for the same keyblock.
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
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,
1778 u32 timestamp, u32 duration,
1779 int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1780 const char *cache_nonce)
1787 u32 pk_keyid[2], pksk_keyid[2];
1788 unsigned int signhints;
1790 log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1791 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1792 || sigclass == 0x30 || sigclass == 0x28 );
1794 if (pksk->version >= 5)
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)
1809 if (gcry_mpi_get_nbits (pksk->pkey[1]) > 256)
1810 digest_algo = DIGEST_ALGO_SHA512;
1812 digest_algo = DIGEST_ALGO_SHA256;
1814 else /* Use the default. */
1815 digest_algo = DEFAULT_DIGEST_ALGO;
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;
1823 if (gcry_md_open (&md, digest_algo, 0))
1826 /* Hash the public key certificate. */
1827 hash_public_key (md, pk);
1829 if (sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28)
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;
1836 else if (sigclass != 0x1F && sigclass != 0x20)
1838 /* Hash the user id. */
1839 hash_uid (md, sigversion, uid);
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 ();
1851 sig->expiredate = sig->timestamp + duration;
1852 sig->sig_class = sigclass;
1854 build_sig_subpkt_from_sig (sig, pksk, signhints);
1855 mk_notation_policy_etc (ctrl, sig, pk, pksk);
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. */
1861 rc = (*mksubpkt)(sig, opaque);
1865 hash_sigversion_to_magic (md, sig, NULL);
1867 rc = complete_sig (ctrl, sig, pksk, md, cache_nonce, signhints);
1872 free_seckey_enc (sig);
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.
1886 * TODO: Merge this with make_keysig_packet.
1889 update_keysig_packet (ctrl_t ctrl,
1890 PKT_signature **ret_sig,
1891 PKT_signature *orig_sig,
1894 PKT_public_key *subpk,
1895 PKT_public_key *pksk,
1896 int (*mksubpkt)(PKT_signature *, void *),
1903 u32 pk_keyid[2], pksk_keyid[2];
1904 unsigned int signhints = 0;
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;
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;
1925 digest_algo = orig_sig->digest_algo;
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;
1933 if (gcry_md_open (&md, digest_algo, 0))
1936 /* Hash the public key certificate and the user id. */
1937 hash_public_key (md, pk);
1939 if (orig_sig->sig_class == 0x18)
1940 hash_public_key (md, subpk);
1942 hash_uid (md, orig_sig->version, uid);
1944 /* Create a new signature packet. */
1945 sig = copy_signature (NULL, orig_sig);
1947 /* Don't generate version 3 signature, but newer. */
1948 if (sig->version == 3)
1950 if (pk->version > 3)
1951 sig->version = pk->version;
1956 sig->digest_algo = digest_algo;
1958 /* We need to create a new timestamp so that new sig expiration
1959 * calculations are done correctly... */
1960 sig->timestamp = make_timestamp();
1962 /* ... but we won't make a timestamp earlier than the existing
1966 while (sig->timestamp <= orig_sig->timestamp)
1968 if (++tmout > 5 && !opt.ignore_time_conflict)
1970 rc = gpg_error (GPG_ERR_TIME_CONFLICT);
1974 sig->timestamp = make_timestamp();
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;
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. */
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);
1995 rc = (*mksubpkt)(sig, opaque);
1999 hash_sigversion_to_magic (md, sig, NULL);
2001 rc = complete_sig (ctrl, sig, pksk, md, NULL, signhints);
2007 free_seckey_enc (sig);