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/>.
42 #include "call-agent.h"
43 #include "mbox-util.h"
45 #ifdef HAVE_DOSISH_SYSTEM
51 static int recipient_digest_algo=0;
54 * Create notations and other stuff. It is assumed that the stings in
55 * STRLIST are already checked to contain only printable data and have
56 * a valid NAME=VALUE format.
59 mk_notation_policy_etc (PKT_signature *sig,
60 PKT_public_key *pk, PKT_public_key *pksk)
65 struct notation *nd = NULL;
66 struct expando_args args;
68 log_assert (sig->version >= 4);
70 memset (&args, 0, sizeof(args));
75 if (IS_SIG(sig) && opt.sig_notations)
76 nd = opt.sig_notations;
77 else if (IS_CERT(sig) && opt.cert_notations)
78 nd = opt.cert_notations;
82 struct notation *item;
84 for (item = nd; item; item = item->next)
86 item->altvalue = pct_expando (item->value,&args);
88 log_error (_("WARNING: unable to %%-expand notation "
89 "(too large). Using unexpanded.\n"));
92 keygen_add_notations (sig, nd);
94 for (item = nd; item; item = item->next)
96 xfree (item->altvalue);
97 item->altvalue = NULL;
101 /* Set policy URL. */
102 if (IS_SIG(sig) && opt.sig_policy_url)
103 pu = opt.sig_policy_url;
104 else if (IS_CERT(sig) && opt.cert_policy_url)
105 pu = opt.cert_policy_url;
107 for (; pu; pu = pu->next)
111 p = pct_expando (string, &args);
114 log_error(_("WARNING: unable to %%-expand policy URL "
115 "(too large). Using unexpanded.\n"));
119 build_sig_subpkt (sig, (SIGSUBPKT_POLICY
120 | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
126 /* Preferred keyserver URL. */
127 if (IS_SIG(sig) && opt.sig_keyserver_url)
128 pu = opt.sig_keyserver_url;
130 for (; pu; pu = pu->next)
134 p = pct_expando (string, &args);
137 log_error (_("WARNING: unable to %%-expand preferred keyserver URL"
138 " (too large). Using unexpanded.\n"));
139 p = xstrdup (string);
142 build_sig_subpkt (sig, (SIGSUBPKT_PREF_KS
143 | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
148 /* Set signer's user id. */
149 if (IS_SIG (sig) && !opt.flags.disable_signer_uid)
153 /* For now we use the uid which was used to locate the key. */
154 if (pksk->user_id && (mbox = mailbox_from_userid (pksk->user_id->name)))
157 log_debug ("setting Signer's UID to '%s'\n", mbox);
158 build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, mbox, strlen (mbox));
161 else if (opt.sender_list)
163 /* If a list of --sender was given we scan that list and use
164 * the first one matching a user id of the current key. */
166 /* FIXME: We need to get the list of user ids for the PKSK
167 * packet. That requires either a function to look it up
168 * again or we need to extend the key packet struct to link
169 * to the primary key which in turn could link to the user
170 * ids. Too much of a change right now. Let's take just
171 * one from the supplied list and hope that the caller
172 * passed a matching one. */
173 build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
174 opt.sender_list->d, strlen (opt.sender_list->d));
181 * Helper to hash a user ID packet.
184 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
190 if (uid->attrib_data)
192 buf[0] = 0xd1; /* Indicates an attribute packet. */
193 buf[1] = uid->attrib_len >> 24; /* Always use 4 length bytes. */
194 buf[2] = uid->attrib_len >> 16;
195 buf[3] = uid->attrib_len >> 8;
196 buf[4] = uid->attrib_len;
200 buf[0] = 0xb4; /* Indicates a userid packet. */
201 buf[1] = uid->len >> 24; /* Always use 4 length bytes. */
202 buf[2] = uid->len >> 16;
203 buf[3] = uid->len >> 8;
206 gcry_md_write( md, buf, 5 );
208 if (uid->attrib_data)
209 gcry_md_write (md, uid->attrib_data, uid->attrib_len );
211 gcry_md_write (md, uid->name, uid->len );
216 * Helper to hash some parts from the signature
219 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
224 gcry_md_putc (md, sig->version);
225 gcry_md_putc (md, sig->sig_class);
226 gcry_md_putc (md, sig->pubkey_algo);
227 gcry_md_putc (md, sig->digest_algo);
230 n = sig->hashed->len;
231 gcry_md_putc (md, (n >> 8) );
232 gcry_md_putc (md, n );
233 gcry_md_write (md, sig->hashed->data, n );
238 gcry_md_putc (md, 0); /* Always hash the length of the subpacket. */
239 gcry_md_putc (md, 0);
242 /* Add some magic. */
243 buf[0] = sig->version;
245 buf[2] = n >> 24; /* (n is only 16 bit, so this is always 0) */
249 gcry_md_write (md, buf, 6);
253 /* Perform the sign operation. If CACHE_NONCE is given the agent is
254 advised to use that cached passphrase fro the key. */
256 do_sign (PKT_public_key *pksk, PKT_signature *sig,
257 gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
263 if (pksk->timestamp > sig->timestamp )
265 ulong d = pksk->timestamp - sig->timestamp;
266 log_info (ngettext("key %s was created %lu second"
267 " in the future (time warp or clock problem)\n",
268 "key %s was created %lu seconds"
269 " in the future (time warp or clock problem)\n",
270 d), keystr_from_pk (pksk), d);
271 if (!opt.ignore_time_conflict)
272 return gpg_error (GPG_ERR_TIME_CONFLICT);
275 print_pubkey_algo_note (pksk->pubkey_algo);
278 mdalgo = gcry_md_get_algo (md);
280 print_digest_algo_note (mdalgo);
281 dp = gcry_md_read (md, mdalgo);
282 sig->digest_algo = mdalgo;
283 sig->digest_start[0] = dp[0];
284 sig->digest_start[1] = dp[1];
285 mpi_release (sig->data[0]);
287 mpi_release (sig->data[1]);
291 err = hexkeygrip_from_pk (pksk, &hexgrip);
295 gcry_sexp_t s_sigval;
297 desc = gpg_format_keydesc (pksk, FORMAT_KEYDESC_NORMAL, 1);
298 err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
299 pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
300 dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
306 else if (pksk->pubkey_algo == GCRY_PK_RSA
307 || pksk->pubkey_algo == GCRY_PK_RSA_S)
308 sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
309 else if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
311 sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE);
312 sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE);
316 sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
317 sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
320 gcry_sexp_release (s_sigval);
325 log_error (_("signing failed: %s\n"), gpg_strerror (err));
330 char *ustr = get_user_id_string_native (sig->keyid);
331 log_info (_("%s/%s signature from: \"%s\"\n"),
332 openpgp_pk_algo_name (pksk->pubkey_algo),
333 openpgp_md_algo_name (sig->digest_algo),
343 complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
344 const char *cache_nonce)
348 /* if (!(rc = check_secret_key (pksk, 0))) */
349 rc = do_sign (pksk, sig, md, 0, cache_nonce);
354 /* Return true if the key seems to be on a version 1 OpenPGP card.
355 This works by asking the agent and may fail if the card has not yet
356 been used with the agent. */
358 openpgp_card_v1_p (PKT_public_key *pk)
363 /* Shortcut if we are not using RSA: The v1 cards only support RSA
364 thus there is no point in looking any further. */
365 if (!is_RSA (pk->pubkey_algo))
368 if (!pk->flags.serialno_valid)
372 err = hexkeygrip_from_pk (pk, &hexgrip);
375 log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
376 return 0; /* Ooops. */
379 xfree (pk->serialno);
380 agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL);
382 pk->flags.serialno_valid = 1;
386 result = 0; /* Error from a past agent_get_keyinfo or no card. */
389 /* The version number of the card is included in the serialno. */
390 result = !strncmp (pk->serialno, "D2760001240101", 14);
398 match_dsa_hash (unsigned int qbytes)
401 return DIGEST_ALGO_SHA1;
404 return DIGEST_ALGO_SHA224;
407 return DIGEST_ALGO_SHA256;
410 return DIGEST_ALGO_SHA384;
412 if (qbytes <= 66 ) /* 66 corresponds to 521 (64 to 512) */
413 return DIGEST_ALGO_SHA512;
415 return DEFAULT_DIGEST_ALGO;
416 /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
417 answer we have if a digest larger than 512 bits is requested. */
422 First try --digest-algo. If that isn't set, see if the recipient
423 has a preferred algorithm (which is also filtered through
424 --personal-digest-prefs). If we're making a signature without a
425 particular recipient (i.e. signing, rather than signing+encrypting)
426 then take the first algorithm in --personal-digest-prefs that is
427 usable for the pubkey algorithm. If --personal-digest-prefs isn't
428 set, then take the OpenPGP default (i.e. SHA-1).
430 Note that Ed25519+EdDSA takes an input of arbitrary length and thus
431 we don't enforce any particular algorithm like we do for standard
432 ECDSA. However, we use SHA256 as the default algorithm.
434 Possible improvement: Use the highest-ranked usable algorithm from
435 the signing key prefs either before or after using the personal
439 hash_for (PKT_public_key *pk)
441 if (opt.def_digest_algo)
443 return opt.def_digest_algo;
445 else if (recipient_digest_algo)
447 return recipient_digest_algo;
449 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA
450 && openpgp_oid_is_ed25519 (pk->pkey[0]))
452 if (opt.personal_digest_prefs)
453 return opt.personal_digest_prefs[0].value;
455 return DIGEST_ALGO_SHA256;
457 else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
458 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
460 unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
462 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
463 qbytes = ecdsa_qbits_from_Q (qbytes);
466 /* It's a DSA key, so find a hash that is the same size as q or
467 larger. If q is 160, assume it is an old DSA key and use a
468 160-bit hash unless --enable-dsa2 is set, in which case act
469 like a new DSA key that just happens to have a 160-bit q
470 (i.e. allow truncation). If q is not 160, by definition it
471 must be a new DSA key. */
473 if (opt.personal_digest_prefs)
477 if (qbytes != 20 || opt.flags.dsa2)
479 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
480 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
485 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
486 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
491 return match_dsa_hash(qbytes);
493 else if (openpgp_card_v1_p (pk))
495 /* The sk lives on a smartcard, and old smartcards only handle
496 SHA-1 and RIPEMD/160. Newer smartcards (v2.0) don't have
497 this restriction anymore. Fortunately the serial number
498 encodes the version of the card and thus we know that this
499 key is on a v1 card. */
500 if(opt.personal_digest_prefs)
504 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
505 if (prefs->value==DIGEST_ALGO_SHA1
506 || prefs->value==DIGEST_ALGO_RMD160)
510 return DIGEST_ALGO_SHA1;
512 else if (opt.personal_digest_prefs)
514 /* It's not DSA, so we can use whatever the first hash algorithm
515 is in the pref list */
516 return opt.personal_digest_prefs[0].value;
519 return DEFAULT_DIGEST_ALGO;
524 print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
526 byte array[MAX_FINGERPRINT_LEN];
527 char buf[100+MAX_FINGERPRINT_LEN*2];
530 snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
531 what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
532 (ulong)sig->timestamp );
533 fingerprint_from_pk (pk, array, &n);
534 bin2hex (array, n, buf + strlen (buf));
536 write_status_text( STATUS_SIG_CREATED, buf );
541 * Loop over the secret certificates in SK_LIST and build the one pass
542 * signature packets. OpenPGP says that the data should be bracket by
543 * the onepass-sig and signature-packet; so we build these onepass
544 * packet here in reverse order
547 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
552 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
555 for (; skcount; skcount--) {
557 PKT_onepass_sig *ops;
561 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
567 ops = xmalloc_clear (sizeof *ops);
568 ops->sig_class = sigclass;
569 ops->digest_algo = hash_for (pk);
570 ops->pubkey_algo = pk->pubkey_algo;
571 keyid_from_pk (pk, ops->keyid);
572 ops->last = (skcount == 1);
575 pkt.pkttype = PKT_ONEPASS_SIG;
576 pkt.pkt.onepass_sig = ops;
577 rc = build_packet (out, &pkt);
580 log_error ("build onepass_sig packet failed: %s\n",
590 * Helper to write the plaintext (literal data) packet
593 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
595 PKT_plaintext *pt = NULL;
600 pt=setup_plaintext_name(fname,inp);
602 /* try to calculate the length of the data */
603 if ( !iobuf_is_pipe_filename (fname) && *fname )
608 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
609 && !overflow && opt.verbose)
610 log_info (_("WARNING: '%s' is an empty file\n"), fname);
612 /* We can't encode the length of very large files because
613 OpenPGP uses only 32 bit for file sizes. So if the size of
614 a file is larger than 2^32 minus some bytes for packet
615 headers, we switch to partial length encoding. */
616 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
621 /* Because the text_filter modifies the length of the
622 * data, it is not possible to know the used length
623 * without a double read of the file - to avoid that
624 * we simple use partial length packets. */
625 if ( ptmode == 't' || ptmode == 'u' || ptmode == 'm')
629 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
631 if (!opt.no_literal) {
634 /* Note that PT has been initialized above in no_literal mode. */
635 pt->timestamp = make_timestamp ();
638 pt->new_ctb = !pt->len;
641 pkt.pkttype = PKT_PLAINTEXT;
642 pkt.pkt.plaintext = pt;
643 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
644 if( (rc = build_packet (out, &pkt)) )
645 log_error ("build_packet(PLAINTEXT) failed: %s\n",
651 byte copy_buffer[4096];
654 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
655 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
656 log_error ("copying input to output failed: %s\n",
660 wipememory(copy_buffer,4096); /* burn buffer */
662 /* fixme: it seems that we never freed pt/pkt */
668 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
669 * hash which will not be changes here.
672 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
673 int sigclass, u32 timestamp, u32 duration,
674 int status_letter, const char *cache_nonce)
678 /* Loop over the certificates with secret keys. */
679 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
688 /* Build the signature packet. */
689 sig = xmalloc_clear (sizeof *sig);
690 if (duration || opt.sig_policy_url
691 || opt.sig_notations || opt.sig_keyserver_url)
694 sig->version = pk->version;
696 keyid_from_pk (pk, sig->keyid);
697 sig->digest_algo = hash_for (pk);
698 sig->pubkey_algo = pk->pubkey_algo;
700 sig->timestamp = timestamp;
702 sig->timestamp = make_timestamp();
704 sig->expiredate = sig->timestamp + duration;
705 sig->sig_class = sigclass;
707 if (gcry_md_copy (&md, hash))
710 if (sig->version >= 4)
712 build_sig_subpkt_from_sig (sig, pk);
713 mk_notation_policy_etc (sig, NULL, pk);
716 hash_sigversion_to_magic (md, sig);
719 rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
723 /* Write the packet. */
727 pkt.pkttype = PKT_SIGNATURE;
728 pkt.pkt.signature = sig;
729 rc = build_packet (out, &pkt);
730 if (!rc && is_status_enabled())
731 print_status_sig_created (pk, sig, status_letter);
734 log_error ("build signature packet failed: %s\n", gpg_strerror (rc));
745 * Sign the files whose names are in FILENAME.
746 * If DETACHED has the value true,
747 * make a detached signature. If FILENAMES->d is NULL read from stdin
748 * and ignore the detached mode. Sign the file with all secret keys
749 * which can be taken from LOCUSR, if this is NULL, use the default one
750 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
751 * signed data for these users.
752 * If OUTFILE is not NULL; this file is used for output and the function
753 * does not ask for overwrite permission; output is then always
754 * uncompressed, non-armored and in binary mode.
757 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
758 int encryptflag, strlist_t remusr, const char *outfile )
761 armor_filter_context_t *afx;
762 compress_filter_context_t zfx;
763 md_filter_context_t mfx;
764 text_filter_context_t tfx;
765 progress_filter_context_t *pfx;
766 encrypt_filter_context_t efx;
767 IOBUF inp = NULL, out = NULL;
770 PK_LIST pk_list = NULL;
771 SK_LIST sk_list = NULL;
772 SK_LIST sk_rover = NULL;
776 pfx = new_progress_context ();
777 afx = new_armor_context ();
778 memset( &zfx, 0, sizeof zfx);
779 memset( &mfx, 0, sizeof mfx);
780 memset( &efx, 0, sizeof efx);
784 fname = filenames->d;
785 multifile = !!filenames->next;
790 if( fname && filenames->next && (!detached || encryptflag) )
791 log_bug("multiple files can only be detached signed");
794 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
797 if (opt.ask_sig_expire && !opt.batch)
798 duration = ask_expire_interval(1,opt.def_sig_expire);
800 duration = parse_expire_string(opt.def_sig_expire);
802 /* Note: In the old non-agent version the following call used to
803 unprotect the secret key. This is now done on demand by the agent. */
804 if( (rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
808 && (rc=build_pk_list (ctrl, remusr, &pk_list)))
812 if( multifile ) /* have list of filenames */
813 inp = NULL; /* we do it later */
815 inp = iobuf_open(fname);
816 if (inp && is_secured_file (iobuf_get_fd (inp)))
820 gpg_err_set_errno (EPERM);
824 rc = gpg_error_from_syserror ();
825 log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
830 handle_progress (pfx, inp, fname);
834 if (is_secured_filename ( outfile )) {
836 gpg_err_set_errno (EPERM);
839 out = iobuf_create (outfile, 0);
842 rc = gpg_error_from_syserror ();
843 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
846 else if( opt.verbose )
847 log_info(_("writing to '%s'\n"), outfile );
849 else if( (rc = open_outfile (-1, fname,
850 opt.armor? 1: detached? 2:0, 0, &out)))
853 /* prepare to calculate the MD over the input */
854 if( opt.textmode && !outfile && !multifile )
856 memset( &tfx, 0, sizeof tfx);
857 iobuf_push_filter( inp, text_filter, &tfx );
860 if ( gcry_md_open (&mfx.md, 0, 0) )
863 gcry_md_debug (mfx.md, "sign");
865 /* If we're encrypting and signing, it is reasonable to pick the
866 hash algorithm to use out of the recipient key prefs. This is
867 best effort only, as in a DSA2 and smartcard world there are
868 cases where we cannot please everyone with a single hash (DSA2
869 wants >160 and smartcards want =160). In the future this could
870 be more complex with different hashes for each sk, but the
871 current design requires a single hash for all SKs. */
874 if(opt.def_digest_algo)
877 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
879 NULL)!=opt.def_digest_algo)
880 log_info(_("WARNING: forcing digest algorithm %s (%d)"
881 " violates recipient preferences\n"),
882 gcry_md_algo_name (opt.def_digest_algo),
883 opt.def_digest_algo );
887 int algo, smartcard=0;
888 union pref_hint hint;
890 hint.digest_length = 0;
892 /* Of course, if the recipient asks for something
893 unreasonable (like the wrong hash for a DSA key) then
894 don't do it. Check all sk's - if any are DSA or live
895 on a smartcard, then the hash has restrictions and we
896 may not be able to give the recipient what they want.
897 For DSA, pass a hint for the largest q we have. Note
898 that this means that a q>160 key will override a q=160
899 key and force the use of truncation for the q=160 key.
900 The alternative would be to ignore the recipient prefs
901 completely and get a different hash for each DSA key in
902 hash_for(). The override behavior here is more or less
903 reasonable as it is under the control of the user which
904 keys they sign with for a given message and the fact
905 that the message with multiple signatures won't be
906 usable on an implementation that doesn't understand
909 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
911 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
912 || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
914 int temp_hashlen = (gcry_mpi_get_nbits
915 (sk_rover->pk->pkey[1]));
917 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
918 temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
919 temp_hashlen = (temp_hashlen+7)/8;
921 /* Pick a hash that is large enough for our
924 if (hint.digest_length<temp_hashlen)
925 hint.digest_length=temp_hashlen;
927 /* FIXME: need to check gpg-agent for this. */
928 /* else if (sk_rover->pk->is_protected */
929 /* && sk_rover->pk->protect.s2k.mode == 1002) */
933 /* Current smartcards only do 160-bit hashes. If we have
934 to have a >160-bit hash, then we can't use the
935 recipient prefs as we'd need both =160 and >160 at the
936 same time and recipient prefs currently require a
937 single hash for all signatures. All this may well have
938 to change as the cards add algorithms. */
940 if (!smartcard || (smartcard && hint.digest_length==20))
942 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
943 recipient_digest_algo=algo;
947 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
948 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
951 iobuf_push_filter( inp, md_filter, &mfx );
953 if( detached && !encryptflag)
956 if( opt.armor && !outfile )
957 push_armor_filter (afx, out);
960 efx.pk_list = pk_list;
961 /* fixme: set efx.cfx.datalen if known */
962 iobuf_push_filter( out, encrypt_filter, &efx );
965 if (opt.compress_algo && !outfile && !detached)
967 int compr_algo=opt.compress_algo;
969 /* If not forced by user */
972 /* If we're not encrypting, then select_algo_from_prefs
973 will fail and we'll end up with the default. If we are
974 encrypting, select_algo_from_prefs cannot fail since
975 there is an assumed preference for uncompressed data.
976 Still, if it did fail, we'll also end up with the
980 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
981 compr_algo=default_compress_algo();
983 else if(!opt.expert && pk_list
984 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
985 compr_algo,NULL)!=compr_algo)
986 log_info(_("WARNING: forcing compression algorithm %s (%d)"
987 " violates recipient preferences\n"),
988 compress_algo_to_string(compr_algo),compr_algo);
990 /* algo 0 means no compression */
992 push_compress_filter(out,&zfx,compr_algo);
995 /* Write the one-pass signature packets if needed */
997 rc = write_onepass_sig_packets (sk_list, out,
998 opt.textmode && !outfile ? 0x01:0x00);
1003 write_status_begin_signing (mfx.md);
1005 /* Setup the inner packet. */
1011 log_info(_("signing:") );
1012 /* must walk reverse trough this list */
1013 for( sl = strlist_last(filenames); sl;
1014 sl = strlist_prev( filenames, sl ) ) {
1015 inp = iobuf_open(sl->d);
1016 if (inp && is_secured_file (iobuf_get_fd (inp)))
1020 gpg_err_set_errno (EPERM);
1024 rc = gpg_error_from_syserror ();
1025 log_error(_("can't open '%s': %s\n"),
1026 sl->d,strerror(errno));
1029 handle_progress (pfx, inp, sl->d);
1031 log_printf (" '%s'", sl->d );
1034 memset( &tfx, 0, sizeof tfx);
1035 iobuf_push_filter( inp, text_filter, &tfx );
1037 iobuf_push_filter( inp, md_filter, &mfx );
1038 while( iobuf_get(inp) != -1 )
1040 iobuf_close(inp); inp = NULL;
1046 /* read, so that the filter can calculate the digest */
1047 while( iobuf_get(inp) != -1 )
1052 rc = write_plaintext_packet (out, inp, fname,
1053 opt.textmode && !outfile ?
1054 (opt.mimemode? 'm':'t'):'b');
1057 /* catch errors from above */
1061 /* write the signatures */
1062 rc = write_signature_packets (sk_list, out, mfx.md,
1063 opt.textmode && !outfile? 0x01 : 0x00,
1064 0, duration, detached ? 'D':'S', NULL);
1075 write_status( STATUS_END_ENCRYPTION );
1078 gcry_md_close ( mfx.md );
1079 release_sk_list( sk_list );
1080 release_pk_list( pk_list );
1081 recipient_digest_algo=0;
1082 release_progress_context (pfx);
1083 release_armor_context (afx);
1090 * make a clear signature. note that opt.armor is not needed
1093 clearsign_file (ctrl_t ctrl,
1094 const char *fname, strlist_t locusr, const char *outfile )
1096 armor_filter_context_t *afx;
1097 progress_filter_context_t *pfx;
1098 gcry_md_hd_t textmd = NULL;
1099 IOBUF inp = NULL, out = NULL;
1102 SK_LIST sk_list = NULL;
1103 SK_LIST sk_rover = NULL;
1106 pfx = new_progress_context ();
1107 afx = new_armor_context ();
1108 init_packet( &pkt );
1110 if (opt.ask_sig_expire && !opt.batch)
1111 duration = ask_expire_interval (1,opt.def_sig_expire);
1113 duration = parse_expire_string (opt.def_sig_expire);
1115 /* Note: In the old non-agent version the following call used to
1116 unprotect the secret key. This is now done on demand by the agent. */
1117 if( (rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
1120 /* prepare iobufs */
1121 inp = iobuf_open(fname);
1122 if (inp && is_secured_file (iobuf_get_fd (inp)))
1126 gpg_err_set_errno (EPERM);
1129 rc = gpg_error_from_syserror ();
1130 log_error (_("can't open '%s': %s\n"),
1131 fname? fname: "[stdin]", strerror(errno) );
1134 handle_progress (pfx, inp, fname);
1137 if (is_secured_filename (outfile) ) {
1139 gpg_err_set_errno (EPERM);
1142 out = iobuf_create (outfile, 0);
1145 rc = gpg_error_from_syserror ();
1146 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
1149 else if( opt.verbose )
1150 log_info(_("writing to '%s'\n"), outfile );
1152 else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1155 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1160 byte hashs_seen[256];
1162 memset( hashs_seen, 0, sizeof hashs_seen );
1163 iobuf_writestr(out, "Hash: " );
1164 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1165 int i = hash_for (sk_rover->pk);
1167 if( !hashs_seen[ i & 0xff ] ) {
1168 s = gcry_md_algo_name ( i );
1170 hashs_seen[ i & 0xff ] = 1;
1172 iobuf_put(out, ',' );
1173 iobuf_writestr(out, s );
1179 iobuf_writestr(out, LF );
1182 if( opt.not_dash_escaped )
1183 iobuf_writestr( out,
1184 "NotDashEscaped: You need "GPG_NAME
1185 " to verify this message" LF );
1186 iobuf_writestr(out, LF );
1188 if ( gcry_md_open (&textmd, 0, 0) )
1190 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1191 gcry_md_enable (textmd, hash_for(sk_rover->pk));
1194 gcry_md_debug ( textmd, "clearsign" );
1196 copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
1198 /* fixme: check for read errors */
1200 /* now write the armor */
1202 push_armor_filter (afx, out);
1204 /* Write the signatures. */
1205 rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
1216 gcry_md_close ( textmd );
1217 release_sk_list( sk_list );
1218 release_progress_context (pfx);
1219 release_armor_context (afx);
1224 * Sign and conventionally encrypt the given file.
1225 * FIXME: Far too much code is duplicated - revamp the whole file.
1228 sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
1230 armor_filter_context_t *afx;
1231 progress_filter_context_t *pfx;
1232 compress_filter_context_t zfx;
1233 md_filter_context_t mfx;
1234 text_filter_context_t tfx;
1235 cipher_filter_context_t cfx;
1236 IOBUF inp = NULL, out = NULL;
1238 STRING2KEY *s2k = NULL;
1240 SK_LIST sk_list = NULL;
1241 SK_LIST sk_rover = NULL;
1246 pfx = new_progress_context ();
1247 afx = new_armor_context ();
1248 memset( &zfx, 0, sizeof zfx);
1249 memset( &mfx, 0, sizeof mfx);
1250 memset( &tfx, 0, sizeof tfx);
1251 memset( &cfx, 0, sizeof cfx);
1252 init_packet( &pkt );
1254 if (opt.ask_sig_expire && !opt.batch)
1255 duration = ask_expire_interval (1, opt.def_sig_expire);
1257 duration = parse_expire_string (opt.def_sig_expire);
1259 /* Note: In the old non-agent version the following call used to
1260 unprotect the secret key. This is now done on demand by the agent. */
1261 rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
1265 /* prepare iobufs */
1266 inp = iobuf_open(fname);
1267 if (inp && is_secured_file (iobuf_get_fd (inp)))
1271 gpg_err_set_errno (EPERM);
1274 rc = gpg_error_from_syserror ();
1275 log_error (_("can't open '%s': %s\n"),
1276 fname? fname: "[stdin]", strerror(errno) );
1279 handle_progress (pfx, inp, fname);
1282 s2k = xmalloc_clear( sizeof *s2k );
1283 s2k->mode = opt.s2k_mode;
1284 s2k->hash_algo = S2K_DIGEST_ALGO;
1286 algo = default_cipher_algo();
1287 if (!opt.quiet || !opt.batch)
1288 log_info (_("%s encryption will be used\n"),
1289 openpgp_cipher_algo_name (algo) );
1290 cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, &canceled);
1292 if (!cfx.dek || !cfx.dek->keylen) {
1293 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1294 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1298 cfx.dek->use_mdc = use_mdc (NULL, cfx.dek->algo);
1300 /* now create the outfile */
1301 rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1305 /* prepare to calculate the MD over the input */
1307 iobuf_push_filter (inp, text_filter, &tfx);
1308 if ( gcry_md_open (&mfx.md, 0, 0) )
1311 gcry_md_debug (mfx.md, "symc-sign");
1313 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1314 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1316 iobuf_push_filter (inp, md_filter, &mfx);
1318 /* Push armor output filter */
1320 push_armor_filter (afx, out);
1322 /* Write the symmetric key packet */
1323 /*(current filters: armor)*/
1325 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1327 enc->cipher_algo = cfx.dek->algo;
1329 pkt.pkttype = PKT_SYMKEY_ENC;
1330 pkt.pkt.symkey_enc = enc;
1331 if( (rc = build_packet( out, &pkt )) )
1332 log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
1336 /* Push the encryption filter */
1337 iobuf_push_filter( out, cipher_filter, &cfx );
1339 /* Push the compress filter */
1340 if (default_compress_algo())
1342 if (cfx.dek && cfx.dek->use_mdc)
1344 push_compress_filter (out, &zfx,default_compress_algo() );
1347 /* Write the one-pass signature packets */
1348 /*(current filters: zip - encrypt - armor)*/
1349 rc = write_onepass_sig_packets (sk_list, out,
1350 opt.textmode? 0x01:0x00);
1354 write_status_begin_signing (mfx.md);
1356 /* Pipe data through all filters; i.e. write the signed stuff */
1357 /*(current filters: zip - encrypt - armor)*/
1358 rc = write_plaintext_packet (out, inp, fname,
1359 opt.textmode ? (opt.mimemode?'m':'t'):'b');
1363 /* Write the signatures */
1364 /*(current filters: zip - encrypt - armor)*/
1365 rc = write_signature_packets (sk_list, out, mfx.md,
1366 opt.textmode? 0x01 : 0x00,
1367 0, duration, 'S', NULL);
1377 write_status( STATUS_END_ENCRYPTION );
1380 release_sk_list( sk_list );
1381 gcry_md_close( mfx.md );
1384 release_progress_context (pfx);
1385 release_armor_context (afx);
1391 * Create a v4 signature in *RET_SIG.
1393 * PK is the primary key to sign (required for all sigs)
1394 * UID is the user id to sign (required for 0x10..0x13, 0x30)
1395 * SUBPK is subkey to sign (required for 0x18, 0x19, 0x28)
1397 * PKSK is the signing key
1399 * SIGCLASS is the type of signature to create.
1401 * DIGEST_ALGO is the digest algorithm. If it is 0 the function
1402 * selects an appropriate one.
1404 * TIMESTAMP is the timestamp to use for the signature. 0 means "now"
1406 * DURATION is the amount of time (in seconds) until the signature
1409 * This function creates the following subpackets: issuer, created,
1410 * and expire (if duration is not 0). Additional subpackets can be
1411 * added using MKSUBPKT, which is called after these subpackets are
1412 * added and before the signature is generated. OPAQUE is passed to
1416 make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
1417 PKT_user_id *uid, PKT_public_key *subpk,
1418 PKT_public_key *pksk,
1419 int sigclass, int digest_algo,
1420 u32 timestamp, u32 duration,
1421 int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1422 const char *cache_nonce)
1429 log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1430 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1431 || sigclass == 0x30 || sigclass == 0x28 );
1434 if (sigversion < pksk->version)
1435 sigversion = pksk->version;
1439 /* Basically, this means use SHA1 always unless the user
1440 specified something (use whatever they said), or it's DSA
1441 (use the best match). They still can't pick an
1442 inappropriate hash for DSA or the signature will fail.
1443 Note that this still allows the caller of
1444 make_keysig_packet to override the user setting if it
1447 if(opt.cert_digest_algo)
1448 digest_algo=opt.cert_digest_algo;
1449 else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
1450 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1451 else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1452 || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1454 if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
1455 digest_algo = DIGEST_ALGO_SHA256;
1457 digest_algo = match_dsa_hash
1458 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1461 digest_algo = DEFAULT_DIGEST_ALGO;
1464 if ( gcry_md_open (&md, digest_algo, 0 ) )
1467 /* Hash the public key certificate. */
1468 hash_public_key( md, pk );
1470 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1472 /* hash the subkey binding/backsig/revocation */
1473 hash_public_key( md, subpk );
1475 else if( sigclass != 0x1F && sigclass != 0x20 )
1477 /* hash the user id */
1478 hash_uid (md, sigversion, uid);
1480 /* and make the signature packet */
1481 sig = xmalloc_clear( sizeof *sig );
1482 sig->version = sigversion;
1483 sig->flags.exportable=1;
1484 sig->flags.revocable=1;
1485 keyid_from_pk (pksk, sig->keyid);
1486 sig->pubkey_algo = pksk->pubkey_algo;
1487 sig->digest_algo = digest_algo;
1489 sig->timestamp=timestamp;
1491 sig->timestamp=make_timestamp();
1493 sig->expiredate=sig->timestamp+duration;
1494 sig->sig_class = sigclass;
1496 build_sig_subpkt_from_sig (sig, pksk);
1497 mk_notation_policy_etc (sig, pk, pksk);
1499 /* Crucial that the call to mksubpkt comes LAST before the calls
1500 to finalize the sig as that makes it possible for the mksubpkt
1501 function to get a reliable pointer to the subpacket area. */
1503 rc = (*mksubpkt)( sig, opaque );
1506 hash_sigversion_to_magic (md, sig);
1509 rc = complete_sig (sig, pksk, md, cache_nonce);
1514 free_seckey_enc( sig );
1523 * Create a new signature packet based on an existing one.
1524 * Only user ID signatures are supported for now.
1525 * PK is the public key to work on.
1526 * PKSK is the key used to make the signature.
1528 * TODO: Merge this with make_keysig_packet.
1531 update_keysig_packet( PKT_signature **ret_sig,
1532 PKT_signature *orig_sig,
1535 PKT_public_key *subpk,
1536 PKT_public_key *pksk,
1537 int (*mksubpkt)(PKT_signature *, void *),
1545 if ((!orig_sig || !pk || !pksk)
1546 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1547 || (orig_sig->sig_class == 0x18 && !subpk))
1548 return GPG_ERR_GENERAL;
1550 if ( opt.cert_digest_algo )
1551 digest_algo = opt.cert_digest_algo;
1553 digest_algo = orig_sig->digest_algo;
1555 if ( gcry_md_open (&md, digest_algo, 0 ) )
1558 /* Hash the public key certificate and the user id. */
1559 hash_public_key( md, pk );
1561 if( orig_sig->sig_class == 0x18 )
1562 hash_public_key( md, subpk );
1564 hash_uid (md, orig_sig->version, uid);
1566 /* create a new signature packet */
1567 sig = copy_signature (NULL, orig_sig);
1569 sig->digest_algo=digest_algo;
1571 /* We need to create a new timestamp so that new sig expiration
1572 calculations are done correctly... */
1573 sig->timestamp=make_timestamp();
1575 /* ... but we won't make a timestamp earlier than the existing
1579 while(sig->timestamp<=orig_sig->timestamp)
1581 if (++tmout > 5 && !opt.ignore_time_conflict)
1583 rc = gpg_error (GPG_ERR_TIME_CONFLICT);
1587 sig->timestamp=make_timestamp();
1591 /* Note that already expired sigs will remain expired (with a
1592 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1593 detects this case. */
1595 /* Put the updated timestamp into the sig. Note that this will
1596 automagically lower any sig expiration dates to correctly
1597 correspond to the differences in the timestamps (i.e. the
1598 duration will shrink). */
1599 build_sig_subpkt_from_sig (sig, pksk);
1602 rc = (*mksubpkt)(sig, opaque);
1605 hash_sigversion_to_magic (md, sig);
1608 rc = complete_sig (sig, pksk, md, NULL);
1614 free_seckey_enc (sig);