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 = xtrycalloc (1, sizeof *sig);
691 return gpg_error_from_syserror ();
693 if (duration || opt.sig_policy_url
694 || opt.sig_notations || opt.sig_keyserver_url)
697 sig->version = pk->version;
699 keyid_from_pk (pk, sig->keyid);
700 sig->digest_algo = hash_for (pk);
701 sig->pubkey_algo = pk->pubkey_algo;
703 sig->timestamp = timestamp;
705 sig->timestamp = make_timestamp();
707 sig->expiredate = sig->timestamp + duration;
708 sig->sig_class = sigclass;
710 if (gcry_md_copy (&md, hash))
713 if (sig->version >= 4)
715 build_sig_subpkt_from_sig (sig, pk);
716 mk_notation_policy_etc (sig, NULL, pk);
719 hash_sigversion_to_magic (md, sig);
722 rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
726 /* Write the packet. */
730 pkt.pkttype = PKT_SIGNATURE;
731 pkt.pkt.signature = sig;
732 rc = build_packet (out, &pkt);
733 if (!rc && is_status_enabled())
734 print_status_sig_created (pk, sig, status_letter);
737 log_error ("build signature packet failed: %s\n",
752 * Sign the files whose names are in FILENAME.
753 * If DETACHED has the value true,
754 * make a detached signature. If FILENAMES->d is NULL read from stdin
755 * and ignore the detached mode. Sign the file with all secret keys
756 * which can be taken from LOCUSR, if this is NULL, use the default one
757 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
758 * signed data for these users.
759 * If OUTFILE is not NULL; this file is used for output and the function
760 * does not ask for overwrite permission; output is then always
761 * uncompressed, non-armored and in binary mode.
764 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
765 int encryptflag, strlist_t remusr, const char *outfile )
768 armor_filter_context_t *afx;
769 compress_filter_context_t zfx;
770 md_filter_context_t mfx;
771 text_filter_context_t tfx;
772 progress_filter_context_t *pfx;
773 encrypt_filter_context_t efx;
774 IOBUF inp = NULL, out = NULL;
777 PK_LIST pk_list = NULL;
778 SK_LIST sk_list = NULL;
779 SK_LIST sk_rover = NULL;
783 pfx = new_progress_context ();
784 afx = new_armor_context ();
785 memset( &zfx, 0, sizeof zfx);
786 memset( &mfx, 0, sizeof mfx);
787 memset( &efx, 0, sizeof efx);
791 fname = filenames->d;
792 multifile = !!filenames->next;
797 if( fname && filenames->next && (!detached || encryptflag) )
798 log_bug("multiple files can only be detached signed");
801 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
804 if (opt.ask_sig_expire && !opt.batch)
805 duration = ask_expire_interval(1,opt.def_sig_expire);
807 duration = parse_expire_string(opt.def_sig_expire);
809 /* Note: In the old non-agent version the following call used to
810 unprotect the secret key. This is now done on demand by the agent. */
811 if( (rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
815 && (rc=build_pk_list (ctrl, remusr, &pk_list)))
819 if( multifile ) /* have list of filenames */
820 inp = NULL; /* we do it later */
822 inp = iobuf_open(fname);
823 if (inp && is_secured_file (iobuf_get_fd (inp)))
827 gpg_err_set_errno (EPERM);
831 rc = gpg_error_from_syserror ();
832 log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
837 handle_progress (pfx, inp, fname);
841 if (is_secured_filename ( outfile )) {
843 gpg_err_set_errno (EPERM);
846 out = iobuf_create (outfile, 0);
849 rc = gpg_error_from_syserror ();
850 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
853 else if( opt.verbose )
854 log_info(_("writing to '%s'\n"), outfile );
856 else if( (rc = open_outfile (-1, fname,
857 opt.armor? 1: detached? 2:0, 0, &out)))
860 /* prepare to calculate the MD over the input */
861 if( opt.textmode && !outfile && !multifile )
863 memset( &tfx, 0, sizeof tfx);
864 iobuf_push_filter( inp, text_filter, &tfx );
867 if ( gcry_md_open (&mfx.md, 0, 0) )
870 gcry_md_debug (mfx.md, "sign");
872 /* If we're encrypting and signing, it is reasonable to pick the
873 hash algorithm to use out of the recipient key prefs. This is
874 best effort only, as in a DSA2 and smartcard world there are
875 cases where we cannot please everyone with a single hash (DSA2
876 wants >160 and smartcards want =160). In the future this could
877 be more complex with different hashes for each sk, but the
878 current design requires a single hash for all SKs. */
881 if(opt.def_digest_algo)
884 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
886 NULL)!=opt.def_digest_algo)
887 log_info(_("WARNING: forcing digest algorithm %s (%d)"
888 " violates recipient preferences\n"),
889 gcry_md_algo_name (opt.def_digest_algo),
890 opt.def_digest_algo );
894 int algo, smartcard=0;
895 union pref_hint hint;
897 hint.digest_length = 0;
899 /* Of course, if the recipient asks for something
900 unreasonable (like the wrong hash for a DSA key) then
901 don't do it. Check all sk's - if any are DSA or live
902 on a smartcard, then the hash has restrictions and we
903 may not be able to give the recipient what they want.
904 For DSA, pass a hint for the largest q we have. Note
905 that this means that a q>160 key will override a q=160
906 key and force the use of truncation for the q=160 key.
907 The alternative would be to ignore the recipient prefs
908 completely and get a different hash for each DSA key in
909 hash_for(). The override behavior here is more or less
910 reasonable as it is under the control of the user which
911 keys they sign with for a given message and the fact
912 that the message with multiple signatures won't be
913 usable on an implementation that doesn't understand
916 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
918 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
919 || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
921 int temp_hashlen = (gcry_mpi_get_nbits
922 (sk_rover->pk->pkey[1]));
924 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
925 temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
926 temp_hashlen = (temp_hashlen+7)/8;
928 /* Pick a hash that is large enough for our
931 if (hint.digest_length<temp_hashlen)
932 hint.digest_length=temp_hashlen;
934 /* FIXME: need to check gpg-agent for this. */
935 /* else if (sk_rover->pk->is_protected */
936 /* && sk_rover->pk->protect.s2k.mode == 1002) */
940 /* Current smartcards only do 160-bit hashes. If we have
941 to have a >160-bit hash, then we can't use the
942 recipient prefs as we'd need both =160 and >160 at the
943 same time and recipient prefs currently require a
944 single hash for all signatures. All this may well have
945 to change as the cards add algorithms. */
947 if (!smartcard || (smartcard && hint.digest_length==20))
949 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
950 recipient_digest_algo=algo;
954 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
955 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
958 iobuf_push_filter( inp, md_filter, &mfx );
960 if( detached && !encryptflag)
963 if( opt.armor && !outfile )
964 push_armor_filter (afx, out);
967 efx.pk_list = pk_list;
968 /* fixme: set efx.cfx.datalen if known */
969 iobuf_push_filter( out, encrypt_filter, &efx );
972 if (opt.compress_algo && !outfile && !detached)
974 int compr_algo=opt.compress_algo;
976 /* If not forced by user */
979 /* If we're not encrypting, then select_algo_from_prefs
980 will fail and we'll end up with the default. If we are
981 encrypting, select_algo_from_prefs cannot fail since
982 there is an assumed preference for uncompressed data.
983 Still, if it did fail, we'll also end up with the
987 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
988 compr_algo=default_compress_algo();
990 else if(!opt.expert && pk_list
991 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
992 compr_algo,NULL)!=compr_algo)
993 log_info(_("WARNING: forcing compression algorithm %s (%d)"
994 " violates recipient preferences\n"),
995 compress_algo_to_string(compr_algo),compr_algo);
997 /* algo 0 means no compression */
999 push_compress_filter(out,&zfx,compr_algo);
1002 /* Write the one-pass signature packets if needed */
1004 rc = write_onepass_sig_packets (sk_list, out,
1005 opt.textmode && !outfile ? 0x01:0x00);
1010 write_status_begin_signing (mfx.md);
1012 /* Setup the inner packet. */
1018 log_info(_("signing:") );
1019 /* must walk reverse trough this list */
1020 for( sl = strlist_last(filenames); sl;
1021 sl = strlist_prev( filenames, sl ) ) {
1022 inp = iobuf_open(sl->d);
1023 if (inp && is_secured_file (iobuf_get_fd (inp)))
1027 gpg_err_set_errno (EPERM);
1031 rc = gpg_error_from_syserror ();
1032 log_error(_("can't open '%s': %s\n"),
1033 sl->d,strerror(errno));
1036 handle_progress (pfx, inp, sl->d);
1038 log_printf (" '%s'", sl->d );
1041 memset( &tfx, 0, sizeof tfx);
1042 iobuf_push_filter( inp, text_filter, &tfx );
1044 iobuf_push_filter( inp, md_filter, &mfx );
1045 while( iobuf_get(inp) != -1 )
1047 iobuf_close(inp); inp = NULL;
1053 /* read, so that the filter can calculate the digest */
1054 while( iobuf_get(inp) != -1 )
1059 rc = write_plaintext_packet (out, inp, fname,
1060 opt.textmode && !outfile ?
1061 (opt.mimemode? 'm':'t'):'b');
1064 /* catch errors from above */
1068 /* write the signatures */
1069 rc = write_signature_packets (sk_list, out, mfx.md,
1070 opt.textmode && !outfile? 0x01 : 0x00,
1071 0, duration, detached ? 'D':'S', NULL);
1082 write_status( STATUS_END_ENCRYPTION );
1085 gcry_md_close ( mfx.md );
1086 release_sk_list( sk_list );
1087 release_pk_list( pk_list );
1088 recipient_digest_algo=0;
1089 release_progress_context (pfx);
1090 release_armor_context (afx);
1097 * make a clear signature. note that opt.armor is not needed
1100 clearsign_file (ctrl_t ctrl,
1101 const char *fname, strlist_t locusr, const char *outfile )
1103 armor_filter_context_t *afx;
1104 progress_filter_context_t *pfx;
1105 gcry_md_hd_t textmd = NULL;
1106 IOBUF inp = NULL, out = NULL;
1109 SK_LIST sk_list = NULL;
1110 SK_LIST sk_rover = NULL;
1113 pfx = new_progress_context ();
1114 afx = new_armor_context ();
1115 init_packet( &pkt );
1117 if (opt.ask_sig_expire && !opt.batch)
1118 duration = ask_expire_interval (1,opt.def_sig_expire);
1120 duration = parse_expire_string (opt.def_sig_expire);
1122 /* Note: In the old non-agent version the following call used to
1123 unprotect the secret key. This is now done on demand by the agent. */
1124 if( (rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
1127 /* prepare iobufs */
1128 inp = iobuf_open(fname);
1129 if (inp && is_secured_file (iobuf_get_fd (inp)))
1133 gpg_err_set_errno (EPERM);
1136 rc = gpg_error_from_syserror ();
1137 log_error (_("can't open '%s': %s\n"),
1138 fname? fname: "[stdin]", strerror(errno) );
1141 handle_progress (pfx, inp, fname);
1144 if (is_secured_filename (outfile) ) {
1146 gpg_err_set_errno (EPERM);
1149 out = iobuf_create (outfile, 0);
1152 rc = gpg_error_from_syserror ();
1153 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
1156 else if( opt.verbose )
1157 log_info(_("writing to '%s'\n"), outfile );
1159 else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1162 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1167 byte hashs_seen[256];
1169 memset( hashs_seen, 0, sizeof hashs_seen );
1170 iobuf_writestr(out, "Hash: " );
1171 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1172 int i = hash_for (sk_rover->pk);
1174 if( !hashs_seen[ i & 0xff ] ) {
1175 s = gcry_md_algo_name ( i );
1177 hashs_seen[ i & 0xff ] = 1;
1179 iobuf_put(out, ',' );
1180 iobuf_writestr(out, s );
1186 iobuf_writestr(out, LF );
1189 if( opt.not_dash_escaped )
1190 iobuf_writestr( out,
1191 "NotDashEscaped: You need "GPG_NAME
1192 " to verify this message" LF );
1193 iobuf_writestr(out, LF );
1195 if ( gcry_md_open (&textmd, 0, 0) )
1197 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1198 gcry_md_enable (textmd, hash_for(sk_rover->pk));
1201 gcry_md_debug ( textmd, "clearsign" );
1203 copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
1205 /* fixme: check for read errors */
1207 /* now write the armor */
1209 push_armor_filter (afx, out);
1211 /* Write the signatures. */
1212 rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
1223 gcry_md_close ( textmd );
1224 release_sk_list( sk_list );
1225 release_progress_context (pfx);
1226 release_armor_context (afx);
1231 * Sign and conventionally encrypt the given file.
1232 * FIXME: Far too much code is duplicated - revamp the whole file.
1235 sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
1237 armor_filter_context_t *afx;
1238 progress_filter_context_t *pfx;
1239 compress_filter_context_t zfx;
1240 md_filter_context_t mfx;
1241 text_filter_context_t tfx;
1242 cipher_filter_context_t cfx;
1243 IOBUF inp = NULL, out = NULL;
1245 STRING2KEY *s2k = NULL;
1247 SK_LIST sk_list = NULL;
1248 SK_LIST sk_rover = NULL;
1253 pfx = new_progress_context ();
1254 afx = new_armor_context ();
1255 memset( &zfx, 0, sizeof zfx);
1256 memset( &mfx, 0, sizeof mfx);
1257 memset( &tfx, 0, sizeof tfx);
1258 memset( &cfx, 0, sizeof cfx);
1259 init_packet( &pkt );
1261 if (opt.ask_sig_expire && !opt.batch)
1262 duration = ask_expire_interval (1, opt.def_sig_expire);
1264 duration = parse_expire_string (opt.def_sig_expire);
1266 /* Note: In the old non-agent version the following call used to
1267 unprotect the secret key. This is now done on demand by the agent. */
1268 rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
1272 /* prepare iobufs */
1273 inp = iobuf_open(fname);
1274 if (inp && is_secured_file (iobuf_get_fd (inp)))
1278 gpg_err_set_errno (EPERM);
1281 rc = gpg_error_from_syserror ();
1282 log_error (_("can't open '%s': %s\n"),
1283 fname? fname: "[stdin]", strerror(errno) );
1286 handle_progress (pfx, inp, fname);
1289 s2k = xmalloc_clear( sizeof *s2k );
1290 s2k->mode = opt.s2k_mode;
1291 s2k->hash_algo = S2K_DIGEST_ALGO;
1293 algo = default_cipher_algo();
1294 if (!opt.quiet || !opt.batch)
1295 log_info (_("%s encryption will be used\n"),
1296 openpgp_cipher_algo_name (algo) );
1297 cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, &canceled);
1299 if (!cfx.dek || !cfx.dek->keylen) {
1300 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1301 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1305 cfx.dek->use_mdc = use_mdc (NULL, cfx.dek->algo);
1307 /* now create the outfile */
1308 rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1312 /* prepare to calculate the MD over the input */
1314 iobuf_push_filter (inp, text_filter, &tfx);
1315 if ( gcry_md_open (&mfx.md, 0, 0) )
1318 gcry_md_debug (mfx.md, "symc-sign");
1320 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1321 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1323 iobuf_push_filter (inp, md_filter, &mfx);
1325 /* Push armor output filter */
1327 push_armor_filter (afx, out);
1329 /* Write the symmetric key packet */
1330 /*(current filters: armor)*/
1332 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1334 enc->cipher_algo = cfx.dek->algo;
1336 pkt.pkttype = PKT_SYMKEY_ENC;
1337 pkt.pkt.symkey_enc = enc;
1338 if( (rc = build_packet( out, &pkt )) )
1339 log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
1343 /* Push the encryption filter */
1344 iobuf_push_filter( out, cipher_filter, &cfx );
1346 /* Push the compress filter */
1347 if (default_compress_algo())
1349 if (cfx.dek && cfx.dek->use_mdc)
1351 push_compress_filter (out, &zfx,default_compress_algo() );
1354 /* Write the one-pass signature packets */
1355 /*(current filters: zip - encrypt - armor)*/
1356 rc = write_onepass_sig_packets (sk_list, out,
1357 opt.textmode? 0x01:0x00);
1361 write_status_begin_signing (mfx.md);
1363 /* Pipe data through all filters; i.e. write the signed stuff */
1364 /*(current filters: zip - encrypt - armor)*/
1365 rc = write_plaintext_packet (out, inp, fname,
1366 opt.textmode ? (opt.mimemode?'m':'t'):'b');
1370 /* Write the signatures */
1371 /*(current filters: zip - encrypt - armor)*/
1372 rc = write_signature_packets (sk_list, out, mfx.md,
1373 opt.textmode? 0x01 : 0x00,
1374 0, duration, 'S', NULL);
1384 write_status( STATUS_END_ENCRYPTION );
1387 release_sk_list( sk_list );
1388 gcry_md_close( mfx.md );
1391 release_progress_context (pfx);
1392 release_armor_context (afx);
1398 * Create a v4 signature in *RET_SIG.
1400 * PK is the primary key to sign (required for all sigs)
1401 * UID is the user id to sign (required for 0x10..0x13, 0x30)
1402 * SUBPK is subkey to sign (required for 0x18, 0x19, 0x28)
1404 * PKSK is the signing key
1406 * SIGCLASS is the type of signature to create.
1408 * DIGEST_ALGO is the digest algorithm. If it is 0 the function
1409 * selects an appropriate one.
1411 * TIMESTAMP is the timestamp to use for the signature. 0 means "now"
1413 * DURATION is the amount of time (in seconds) until the signature
1416 * This function creates the following subpackets: issuer, created,
1417 * and expire (if duration is not 0). Additional subpackets can be
1418 * added using MKSUBPKT, which is called after these subpackets are
1419 * added and before the signature is generated. OPAQUE is passed to
1423 make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
1424 PKT_user_id *uid, PKT_public_key *subpk,
1425 PKT_public_key *pksk,
1426 int sigclass, int digest_algo,
1427 u32 timestamp, u32 duration,
1428 int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1429 const char *cache_nonce)
1436 log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1437 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1438 || sigclass == 0x30 || sigclass == 0x28 );
1441 if (sigversion < pksk->version)
1442 sigversion = pksk->version;
1446 /* Basically, this means use SHA1 always unless the user
1447 specified something (use whatever they said), or it's DSA
1448 (use the best match). They still can't pick an
1449 inappropriate hash for DSA or the signature will fail.
1450 Note that this still allows the caller of
1451 make_keysig_packet to override the user setting if it
1454 if(opt.cert_digest_algo)
1455 digest_algo=opt.cert_digest_algo;
1456 else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
1457 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1458 else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1459 || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1461 if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
1462 digest_algo = DIGEST_ALGO_SHA256;
1464 digest_algo = match_dsa_hash
1465 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1468 digest_algo = DEFAULT_DIGEST_ALGO;
1471 if ( gcry_md_open (&md, digest_algo, 0 ) )
1474 /* Hash the public key certificate. */
1475 hash_public_key( md, pk );
1477 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1479 /* hash the subkey binding/backsig/revocation */
1480 hash_public_key( md, subpk );
1482 else if( sigclass != 0x1F && sigclass != 0x20 )
1484 /* hash the user id */
1485 hash_uid (md, sigversion, uid);
1487 /* and make the signature packet */
1488 sig = xmalloc_clear( sizeof *sig );
1489 sig->version = sigversion;
1490 sig->flags.exportable=1;
1491 sig->flags.revocable=1;
1492 keyid_from_pk (pksk, sig->keyid);
1493 sig->pubkey_algo = pksk->pubkey_algo;
1494 sig->digest_algo = digest_algo;
1496 sig->timestamp=timestamp;
1498 sig->timestamp=make_timestamp();
1500 sig->expiredate=sig->timestamp+duration;
1501 sig->sig_class = sigclass;
1503 build_sig_subpkt_from_sig (sig, pksk);
1504 mk_notation_policy_etc (sig, pk, pksk);
1506 /* Crucial that the call to mksubpkt comes LAST before the calls
1507 to finalize the sig as that makes it possible for the mksubpkt
1508 function to get a reliable pointer to the subpacket area. */
1510 rc = (*mksubpkt)( sig, opaque );
1513 hash_sigversion_to_magic (md, sig);
1516 rc = complete_sig (sig, pksk, md, cache_nonce);
1521 free_seckey_enc( sig );
1530 * Create a new signature packet based on an existing one.
1531 * Only user ID signatures are supported for now.
1532 * PK is the public key to work on.
1533 * PKSK is the key used to make the signature.
1535 * TODO: Merge this with make_keysig_packet.
1538 update_keysig_packet( PKT_signature **ret_sig,
1539 PKT_signature *orig_sig,
1542 PKT_public_key *subpk,
1543 PKT_public_key *pksk,
1544 int (*mksubpkt)(PKT_signature *, void *),
1552 if ((!orig_sig || !pk || !pksk)
1553 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1554 || (orig_sig->sig_class == 0x18 && !subpk))
1555 return GPG_ERR_GENERAL;
1557 if ( opt.cert_digest_algo )
1558 digest_algo = opt.cert_digest_algo;
1560 digest_algo = orig_sig->digest_algo;
1562 if ( gcry_md_open (&md, digest_algo, 0 ) )
1565 /* Hash the public key certificate and the user id. */
1566 hash_public_key( md, pk );
1568 if( orig_sig->sig_class == 0x18 )
1569 hash_public_key( md, subpk );
1571 hash_uid (md, orig_sig->version, uid);
1573 /* create a new signature packet */
1574 sig = copy_signature (NULL, orig_sig);
1576 sig->digest_algo=digest_algo;
1578 /* We need to create a new timestamp so that new sig expiration
1579 calculations are done correctly... */
1580 sig->timestamp=make_timestamp();
1582 /* ... but we won't make a timestamp earlier than the existing
1586 while(sig->timestamp<=orig_sig->timestamp)
1588 if (++tmout > 5 && !opt.ignore_time_conflict)
1590 rc = gpg_error (GPG_ERR_TIME_CONFLICT);
1594 sig->timestamp=make_timestamp();
1598 /* Note that already expired sigs will remain expired (with a
1599 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1600 detects this case. */
1602 /* Put the updated timestamp into the sig. Note that this will
1603 automagically lower any sig expiration dates to correctly
1604 correspond to the differences in the timestamps (i.e. the
1605 duration will shrink). */
1606 build_sig_subpkt_from_sig (sig, pksk);
1609 rc = (*mksubpkt)(sig, opaque);
1612 hash_sigversion_to_magic (md, sig);
1615 rc = complete_sig (sig, pksk, md, NULL);
1621 free_seckey_enc (sig);