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 <http://www.gnu.org/licenses/>.
43 #include "call-agent.h"
46 #ifdef HAVE_DOSISH_SYSTEM
52 static int recipient_digest_algo=0;
55 * Create notations and other stuff. It is assumed that the stings in
56 * STRLIST are already checked to contain only printable data and have
57 * a valid NAME=VALUE format.
60 mk_notation_policy_etc (PKT_signature *sig,
61 PKT_public_key *pk, PKT_public_key *pksk)
66 struct notation *nd=NULL;
67 struct expando_args args;
69 assert(sig->version>=4);
71 memset(&args,0,sizeof(args));
76 if(IS_SIG(sig) && opt.sig_notations)
78 else if( IS_CERT(sig) && opt.cert_notations )
79 nd=opt.cert_notations;
87 i->altvalue=pct_expando(i->value,&args);
89 log_error(_("WARNING: unable to %%-expand notation "
90 "(too large). Using unexpanded.\n"));
93 keygen_add_notations(sig,nd);
103 if( IS_SIG(sig) && opt.sig_policy_url )
104 pu=opt.sig_policy_url;
105 else if( IS_CERT(sig) && opt.cert_policy_url )
106 pu=opt.cert_policy_url;
112 s=pct_expando(string,&args);
115 log_error(_("WARNING: unable to %%-expand policy URL "
116 "(too large). Using unexpanded.\n"));
120 build_sig_subpkt(sig,SIGSUBPKT_POLICY|
121 ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
127 /* preferred keyserver URL */
128 if( IS_SIG(sig) && opt.sig_keyserver_url )
129 pu=opt.sig_keyserver_url;
135 s=pct_expando(string,&args);
138 log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
139 " (too large). Using unexpanded.\n"));
143 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS|
144 ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
153 * Helper to hash a user ID packet.
156 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
162 if (uid->attrib_data)
164 buf[0] = 0xd1; /* Indicates an attribute packet. */
165 buf[1] = uid->attrib_len >> 24; /* Always use 4 length bytes. */
166 buf[2] = uid->attrib_len >> 16;
167 buf[3] = uid->attrib_len >> 8;
168 buf[4] = uid->attrib_len;
172 buf[0] = 0xb4; /* Indicates a userid packet. */
173 buf[1] = uid->len >> 24; /* Always use 4 length bytes. */
174 buf[2] = uid->len >> 16;
175 buf[3] = uid->len >> 8;
178 gcry_md_write( md, buf, 5 );
180 if (uid->attrib_data)
181 gcry_md_write (md, uid->attrib_data, uid->attrib_len );
183 gcry_md_write (md, uid->name, uid->len );
188 * Helper to hash some parts from the signature
191 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
196 gcry_md_putc (md, sig->version);
197 gcry_md_putc (md, sig->sig_class);
198 gcry_md_putc (md, sig->pubkey_algo);
199 gcry_md_putc (md, sig->digest_algo);
202 n = sig->hashed->len;
203 gcry_md_putc (md, (n >> 8) );
204 gcry_md_putc (md, n );
205 gcry_md_write (md, sig->hashed->data, n );
210 gcry_md_putc (md, 0); /* Always hash the length of the subpacket. */
211 gcry_md_putc (md, 0);
214 /* Add some magic. */
215 buf[0] = sig->version;
217 buf[2] = n >> 24; /* (n is only 16 bit, so this is always 0) */
221 gcry_md_write (md, buf, 6);
225 /* Perform the sign operation. If CACHE_NONCE is given the agent is
226 advised to use that cached passphrase fro the key. */
228 do_sign (PKT_public_key *pksk, PKT_signature *sig,
229 gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
236 if (pksk->timestamp > sig->timestamp )
238 ulong d = pksk->timestamp - sig->timestamp;
239 log_info (d==1 ? _("key has been created %lu second "
240 "in future (time warp or clock problem)\n")
241 : _("key has been created %lu seconds "
242 "in future (time warp or clock problem)\n"), d );
243 if (!opt.ignore_time_conflict)
244 return gpg_error (GPG_ERR_TIME_CONFLICT);
248 print_pubkey_algo_note (pksk->pubkey_algo);
251 mdalgo = gcry_md_get_algo (md);
253 print_digest_algo_note (mdalgo);
254 dp = gcry_md_read (md, mdalgo);
255 sig->digest_algo = mdalgo;
256 sig->digest_start[0] = dp[0];
257 sig->digest_start[1] = dp[1];
262 err = hexkeygrip_from_pk (pksk, &hexgrip);
266 gcry_sexp_t s_sigval;
268 desc = gpg_format_keydesc (pksk, FORMAT_KEYDESC_NORMAL, 1);
269 err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
270 pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
271 dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
277 else if (pksk->pubkey_algo == GCRY_PK_RSA
278 || pksk->pubkey_algo == GCRY_PK_RSA_S)
279 sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
280 else if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
282 sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE);
283 sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE);
287 sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
288 sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
291 gcry_sexp_release (s_sigval);
295 /* Check that the signature verification worked and nothing is
296 * fooling us e.g. by a bug in the signature create code or by
297 * deliberately introduced faults. Because Libgcrypt 1.7 does this
298 * for RSA internally there is no need to do it here again. */
300 #if GCRYPT_VERSION_NUMBER >= 0x010700 /* Libgcrypt >= 1.7 */
301 && !is_RSA (pksk->pubkey_algo)
302 #endif /* Libgcrypt >= 1.7 */
305 PKT_public_key *pk = xmalloc_clear (sizeof *pk);
307 if (get_pubkey (pk, sig->keyid ))
308 err = gpg_error (GPG_ERR_NO_PUBKEY);
311 frame = encode_md_value (pk, md, sig->digest_algo );
313 err = gpg_error (GPG_ERR_GENERAL);
315 err = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey);
316 gcry_mpi_release (frame);
319 log_error (_("checking created signature failed: %s\n"),
321 free_public_key (pk);
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);
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. */
629 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
631 if (!opt.no_literal) {
634 pt->timestamp = make_timestamp ();
637 pt->new_ctb = !pt->len;
640 pkt.pkttype = PKT_PLAINTEXT;
641 pkt.pkt.plaintext = pt;
642 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
643 if( (rc = build_packet (out, &pkt)) )
644 log_error ("build_packet(PLAINTEXT) failed: %s\n",
649 byte copy_buffer[4096];
652 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
653 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
654 log_error ("copying input to output failed: %s\n",
658 wipememory(copy_buffer,4096); /* burn buffer */
660 /* fixme: it seems that we never freed pt/pkt */
666 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
667 * hash which will not be changes here.
670 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
671 int sigclass, u32 timestamp, u32 duration,
672 int status_letter, const char *cache_nonce)
676 /* Loop over the certificates with secret keys. */
677 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
686 /* Build the signature packet. */
687 sig = xmalloc_clear (sizeof *sig);
688 if (duration || opt.sig_policy_url
689 || opt.sig_notations || opt.sig_keyserver_url)
692 sig->version = pk->version;
694 keyid_from_pk (pk, sig->keyid);
695 sig->digest_algo = hash_for (pk);
696 sig->pubkey_algo = pk->pubkey_algo;
698 sig->timestamp = timestamp;
700 sig->timestamp = make_timestamp();
702 sig->expiredate = sig->timestamp + duration;
703 sig->sig_class = sigclass;
705 if (gcry_md_copy (&md, hash))
708 if (sig->version >= 4)
710 build_sig_subpkt_from_sig (sig);
711 mk_notation_policy_etc (sig, NULL, pk);
714 hash_sigversion_to_magic (md, sig);
717 rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
721 /* Write the packet. */
725 pkt.pkttype = PKT_SIGNATURE;
726 pkt.pkt.signature = sig;
727 rc = build_packet (out, &pkt);
728 if (!rc && is_status_enabled())
729 print_status_sig_created (pk, sig, status_letter);
732 log_error ("build signature packet failed: %s\n", gpg_strerror (rc));
743 * Sign the files whose names are in FILENAME.
744 * If DETACHED has the value true,
745 * make a detached signature. If FILENAMES->d is NULL read from stdin
746 * and ignore the detached mode. Sign the file with all secret keys
747 * which can be taken from LOCUSR, if this is NULL, use the default one
748 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
749 * signed data for these users.
750 * If OUTFILE is not NULL; this file is used for output and the function
751 * does not ask for overwrite permission; output is then always
752 * uncompressed, non-armored and in binary mode.
755 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
756 int encryptflag, strlist_t remusr, const char *outfile )
759 armor_filter_context_t *afx;
760 compress_filter_context_t zfx;
761 md_filter_context_t mfx;
762 text_filter_context_t tfx;
763 progress_filter_context_t *pfx;
764 encrypt_filter_context_t efx;
765 IOBUF inp = NULL, out = NULL;
768 PK_LIST pk_list = NULL;
769 SK_LIST sk_list = NULL;
770 SK_LIST sk_rover = NULL;
774 pfx = new_progress_context ();
775 afx = new_armor_context ();
776 memset( &zfx, 0, sizeof zfx);
777 memset( &mfx, 0, sizeof mfx);
778 memset( &efx, 0, sizeof efx);
782 fname = filenames->d;
783 multifile = !!filenames->next;
788 if( fname && filenames->next && (!detached || encryptflag) )
789 log_bug("multiple files can only be detached signed");
792 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
795 if (opt.ask_sig_expire && !opt.batch)
796 duration = ask_expire_interval(1,opt.def_sig_expire);
798 duration = parse_expire_string(opt.def_sig_expire);
800 /* Note: In the old non-agent version the following call used to
801 unprotect the secret key. This is now done on demand by the agent. */
802 if( (rc = build_sk_list (locusr, &sk_list, PUBKEY_USAGE_SIG )) )
806 && (rc=build_pk_list (ctrl, remusr, &pk_list, PUBKEY_USAGE_ENC)))
810 if( multifile ) /* have list of filenames */
811 inp = NULL; /* we do it later */
813 inp = iobuf_open(fname);
814 if (inp && is_secured_file (iobuf_get_fd (inp)))
818 gpg_err_set_errno (EPERM);
822 rc = gpg_error_from_syserror ();
823 log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
828 handle_progress (pfx, inp, fname);
832 if (is_secured_filename ( outfile )) {
834 gpg_err_set_errno (EPERM);
837 out = iobuf_create (outfile, 0);
840 rc = gpg_error_from_syserror ();
841 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
844 else if( opt.verbose )
845 log_info(_("writing to '%s'\n"), outfile );
847 else if( (rc = open_outfile (-1, fname,
848 opt.armor? 1: detached? 2:0, 0, &out)))
851 /* prepare to calculate the MD over the input */
852 if( opt.textmode && !outfile && !multifile )
854 memset( &tfx, 0, sizeof tfx);
855 iobuf_push_filter( inp, text_filter, &tfx );
858 if ( gcry_md_open (&mfx.md, 0, 0) )
861 gcry_md_debug (mfx.md, "sign");
863 /* If we're encrypting and signing, it is reasonable to pick the
864 hash algorithm to use out of the recipient key prefs. This is
865 best effort only, as in a DSA2 and smartcard world there are
866 cases where we cannot please everyone with a single hash (DSA2
867 wants >160 and smartcards want =160). In the future this could
868 be more complex with different hashes for each sk, but the
869 current design requires a single hash for all SKs. */
872 if(opt.def_digest_algo)
875 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
877 NULL)!=opt.def_digest_algo)
878 log_info(_("WARNING: forcing digest algorithm %s (%d)"
879 " violates recipient preferences\n"),
880 gcry_md_algo_name (opt.def_digest_algo),
881 opt.def_digest_algo );
885 int algo, smartcard=0;
886 union pref_hint hint;
888 hint.digest_length = 0;
890 /* Of course, if the recipient asks for something
891 unreasonable (like the wrong hash for a DSA key) then
892 don't do it. Check all sk's - if any are DSA or live
893 on a smartcard, then the hash has restrictions and we
894 may not be able to give the recipient what they want.
895 For DSA, pass a hint for the largest q we have. Note
896 that this means that a q>160 key will override a q=160
897 key and force the use of truncation for the q=160 key.
898 The alternative would be to ignore the recipient prefs
899 completely and get a different hash for each DSA key in
900 hash_for(). The override behavior here is more or less
901 reasonable as it is under the control of the user which
902 keys they sign with for a given message and the fact
903 that the message with multiple signatures won't be
904 usable on an implementation that doesn't understand
907 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
909 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
910 || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
912 int temp_hashlen = (gcry_mpi_get_nbits
913 (sk_rover->pk->pkey[1]));
915 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
916 temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
917 temp_hashlen = (temp_hashlen+7)/8;
919 /* Pick a hash that is large enough for our
922 if (hint.digest_length<temp_hashlen)
923 hint.digest_length=temp_hashlen;
925 /* FIXME: need to check gpg-agent for this. */
926 /* else if (sk_rover->pk->is_protected */
927 /* && sk_rover->pk->protect.s2k.mode == 1002) */
931 /* Current smartcards only do 160-bit hashes. If we have
932 to have a >160-bit hash, then we can't use the
933 recipient prefs as we'd need both =160 and >160 at the
934 same time and recipient prefs currently require a
935 single hash for all signatures. All this may well have
936 to change as the cards add algorithms. */
938 if (!smartcard || (smartcard && hint.digest_length==20))
940 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
941 recipient_digest_algo=algo;
945 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
946 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
949 iobuf_push_filter( inp, md_filter, &mfx );
951 if( detached && !encryptflag)
954 if( opt.armor && !outfile )
955 push_armor_filter (afx, out);
958 efx.pk_list = pk_list;
959 /* fixme: set efx.cfx.datalen if known */
960 iobuf_push_filter( out, encrypt_filter, &efx );
963 if (opt.compress_algo && !outfile && !detached)
965 int compr_algo=opt.compress_algo;
967 /* If not forced by user */
970 /* If we're not encrypting, then select_algo_from_prefs
971 will fail and we'll end up with the default. If we are
972 encrypting, select_algo_from_prefs cannot fail since
973 there is an assumed preference for uncompressed data.
974 Still, if it did fail, we'll also end up with the
978 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
979 compr_algo=default_compress_algo();
981 else if(!opt.expert && pk_list
982 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
983 compr_algo,NULL)!=compr_algo)
984 log_info(_("WARNING: forcing compression algorithm %s (%d)"
985 " violates recipient preferences\n"),
986 compress_algo_to_string(compr_algo),compr_algo);
988 /* algo 0 means no compression */
990 push_compress_filter(out,&zfx,compr_algo);
993 /* Write the one-pass signature packets if needed */
995 rc = write_onepass_sig_packets (sk_list, out,
996 opt.textmode && !outfile ? 0x01:0x00);
1001 write_status_begin_signing (mfx.md);
1003 /* Setup the inner packet. */
1009 log_info(_("signing:") );
1010 /* must walk reverse trough this list */
1011 for( sl = strlist_last(filenames); sl;
1012 sl = strlist_prev( filenames, sl ) ) {
1013 inp = iobuf_open(sl->d);
1014 if (inp && is_secured_file (iobuf_get_fd (inp)))
1018 gpg_err_set_errno (EPERM);
1022 rc = gpg_error_from_syserror ();
1023 log_error(_("can't open '%s': %s\n"),
1024 sl->d,strerror(errno));
1027 handle_progress (pfx, inp, sl->d);
1029 log_printf (" '%s'", sl->d );
1032 memset( &tfx, 0, sizeof tfx);
1033 iobuf_push_filter( inp, text_filter, &tfx );
1035 iobuf_push_filter( inp, md_filter, &mfx );
1036 while( iobuf_get(inp) != -1 )
1038 iobuf_close(inp); inp = NULL;
1044 /* read, so that the filter can calculate the digest */
1045 while( iobuf_get(inp) != -1 )
1050 rc = write_plaintext_packet (out, inp, fname,
1051 opt.textmode && !outfile ? 't':'b');
1054 /* catch errors from above */
1058 /* write the signatures */
1059 rc = write_signature_packets (sk_list, out, mfx.md,
1060 opt.textmode && !outfile? 0x01 : 0x00,
1061 0, duration, detached ? 'D':'S', NULL);
1072 write_status( STATUS_END_ENCRYPTION );
1075 gcry_md_close ( mfx.md );
1076 release_sk_list( sk_list );
1077 release_pk_list( pk_list );
1078 recipient_digest_algo=0;
1079 release_progress_context (pfx);
1080 release_armor_context (afx);
1087 * make a clear signature. note that opt.armor is not needed
1090 clearsign_file( const char *fname, strlist_t locusr, const char *outfile )
1092 armor_filter_context_t *afx;
1093 progress_filter_context_t *pfx;
1094 gcry_md_hd_t textmd = NULL;
1095 IOBUF inp = NULL, out = NULL;
1098 SK_LIST sk_list = NULL;
1099 SK_LIST sk_rover = NULL;
1102 pfx = new_progress_context ();
1103 afx = new_armor_context ();
1104 init_packet( &pkt );
1106 if (opt.ask_sig_expire && !opt.batch)
1107 duration = ask_expire_interval (1,opt.def_sig_expire);
1109 duration = parse_expire_string (opt.def_sig_expire);
1111 /* Note: In the old non-agent version the following call used to
1112 unprotect the secret key. This is now done on demand by the agent. */
1113 if( (rc=build_sk_list( locusr, &sk_list, PUBKEY_USAGE_SIG )) )
1116 /* prepare iobufs */
1117 inp = iobuf_open(fname);
1118 if (inp && is_secured_file (iobuf_get_fd (inp)))
1122 gpg_err_set_errno (EPERM);
1125 rc = gpg_error_from_syserror ();
1126 log_error (_("can't open '%s': %s\n"),
1127 fname? fname: "[stdin]", strerror(errno) );
1130 handle_progress (pfx, inp, fname);
1133 if (is_secured_filename (outfile) ) {
1135 gpg_err_set_errno (EPERM);
1138 out = iobuf_create (outfile, 0);
1141 rc = gpg_error_from_syserror ();
1142 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
1145 else if( opt.verbose )
1146 log_info(_("writing to '%s'\n"), outfile );
1148 else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1151 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1156 byte hashs_seen[256];
1158 memset( hashs_seen, 0, sizeof hashs_seen );
1159 iobuf_writestr(out, "Hash: " );
1160 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1161 int i = hash_for (sk_rover->pk);
1163 if( !hashs_seen[ i & 0xff ] ) {
1164 s = gcry_md_algo_name ( i );
1166 hashs_seen[ i & 0xff ] = 1;
1168 iobuf_put(out, ',' );
1169 iobuf_writestr(out, s );
1175 iobuf_writestr(out, LF );
1178 if( opt.not_dash_escaped )
1179 iobuf_writestr( out,
1180 "NotDashEscaped: You need "GPG_NAME
1181 " to verify this message" LF );
1182 iobuf_writestr(out, LF );
1184 if ( gcry_md_open (&textmd, 0, 0) )
1186 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1187 gcry_md_enable (textmd, hash_for(sk_rover->pk));
1190 gcry_md_debug ( textmd, "clearsign" );
1192 copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
1194 /* fixme: check for read errors */
1196 /* now write the armor */
1198 push_armor_filter (afx, out);
1200 /* Write the signatures. */
1201 rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
1212 gcry_md_close ( textmd );
1213 release_sk_list( sk_list );
1214 release_progress_context (pfx);
1215 release_armor_context (afx);
1220 * Sign and conventionally encrypt the given file.
1221 * FIXME: Far too much code is duplicated - revamp the whole file.
1224 sign_symencrypt_file (const char *fname, strlist_t locusr)
1226 armor_filter_context_t *afx;
1227 progress_filter_context_t *pfx;
1228 compress_filter_context_t zfx;
1229 md_filter_context_t mfx;
1230 text_filter_context_t tfx;
1231 cipher_filter_context_t cfx;
1232 IOBUF inp = NULL, out = NULL;
1234 STRING2KEY *s2k = NULL;
1236 SK_LIST sk_list = NULL;
1237 SK_LIST sk_rover = NULL;
1242 pfx = new_progress_context ();
1243 afx = new_armor_context ();
1244 memset( &zfx, 0, sizeof zfx);
1245 memset( &mfx, 0, sizeof mfx);
1246 memset( &tfx, 0, sizeof tfx);
1247 memset( &cfx, 0, sizeof cfx);
1248 init_packet( &pkt );
1250 if (opt.ask_sig_expire && !opt.batch)
1251 duration = ask_expire_interval (1, opt.def_sig_expire);
1253 duration = parse_expire_string (opt.def_sig_expire);
1255 /* Note: In the old non-agent version the following call used to
1256 unprotect the secret key. This is now done on demand by the agent. */
1257 rc = build_sk_list (locusr, &sk_list, PUBKEY_USAGE_SIG);
1261 /* prepare iobufs */
1262 inp = iobuf_open(fname);
1263 if (inp && is_secured_file (iobuf_get_fd (inp)))
1267 gpg_err_set_errno (EPERM);
1270 rc = gpg_error_from_syserror ();
1271 log_error (_("can't open '%s': %s\n"),
1272 fname? fname: "[stdin]", strerror(errno) );
1275 handle_progress (pfx, inp, fname);
1278 s2k = xmalloc_clear( sizeof *s2k );
1279 s2k->mode = opt.s2k_mode;
1280 s2k->hash_algo = S2K_DIGEST_ALGO;
1282 algo = default_cipher_algo();
1283 if (!opt.quiet || !opt.batch)
1284 log_info (_("%s encryption will be used\n"),
1285 openpgp_cipher_algo_name (algo) );
1286 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
1288 if (!cfx.dek || !cfx.dek->keylen) {
1289 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1290 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1294 /* We have no way to tell if the recipient can handle messages
1295 with an MDC, so this defaults to no. Perhaps in a few years,
1296 this can be defaulted to yes. Note that like regular
1297 encrypting, --force-mdc overrides --disable-mdc. */
1301 /* now create the outfile */
1302 rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1306 /* prepare to calculate the MD over the input */
1308 iobuf_push_filter (inp, text_filter, &tfx);
1309 if ( gcry_md_open (&mfx.md, 0, 0) )
1312 gcry_md_debug (mfx.md, "symc-sign");
1314 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1315 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1317 iobuf_push_filter (inp, md_filter, &mfx);
1319 /* Push armor output filter */
1321 push_armor_filter (afx, out);
1323 /* Write the symmetric key packet */
1324 /*(current filters: armor)*/
1326 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1328 enc->cipher_algo = cfx.dek->algo;
1330 pkt.pkttype = PKT_SYMKEY_ENC;
1331 pkt.pkt.symkey_enc = enc;
1332 if( (rc = build_packet( out, &pkt )) )
1333 log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
1337 /* Push the encryption filter */
1338 iobuf_push_filter( out, cipher_filter, &cfx );
1340 /* Push the compress filter */
1341 if (default_compress_algo())
1342 push_compress_filter(out,&zfx,default_compress_algo());
1344 /* Write the one-pass signature packets */
1345 /*(current filters: zip - encrypt - armor)*/
1346 rc = write_onepass_sig_packets (sk_list, out,
1347 opt.textmode? 0x01:0x00);
1351 write_status_begin_signing (mfx.md);
1353 /* Pipe data through all filters; i.e. write the signed stuff */
1354 /*(current filters: zip - encrypt - armor)*/
1355 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1359 /* Write the signatures */
1360 /*(current filters: zip - encrypt - armor)*/
1361 rc = write_signature_packets (sk_list, out, mfx.md,
1362 opt.textmode? 0x01 : 0x00,
1363 0, duration, 'S', NULL);
1373 write_status( STATUS_END_ENCRYPTION );
1376 release_sk_list( sk_list );
1377 gcry_md_close( mfx.md );
1380 release_progress_context (pfx);
1381 release_armor_context (afx);
1387 * Create a signature packet for the given public key certificate and
1388 * the user id and return it in ret_sig. User signature class SIGCLASS
1389 * user-id is not used (and may be NULL if sigclass is 0x20) If
1390 * DIGEST_ALGO is 0 the function selects an appropriate one.
1391 * SIGVERSION gives the minimal required signature packet version;
1392 * this is needed so that special properties like local sign are not
1393 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1394 * the timestamp to use for the signature. 0 means "now" */
1396 make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
1397 PKT_user_id *uid, PKT_public_key *subpk,
1398 PKT_public_key *pksk,
1399 int sigclass, int digest_algo,
1400 u32 timestamp, u32 duration,
1401 int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1402 const char *cache_nonce)
1409 assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1410 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1411 || sigclass == 0x30 || sigclass == 0x28 );
1414 if (sigversion < pksk->version)
1415 sigversion = pksk->version;
1419 /* Basically, this means use SHA1 always unless the user
1420 specified something (use whatever they said), or it's DSA
1421 (use the best match). They still can't pick an
1422 inappropriate hash for DSA or the signature will fail.
1423 Note that this still allows the caller of
1424 make_keysig_packet to override the user setting if it
1427 if(opt.cert_digest_algo)
1428 digest_algo=opt.cert_digest_algo;
1429 else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
1430 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1431 else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1432 || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1434 if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
1435 digest_algo = DIGEST_ALGO_SHA256;
1437 digest_algo = match_dsa_hash
1438 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1441 digest_algo = DEFAULT_DIGEST_ALGO;
1444 if ( gcry_md_open (&md, digest_algo, 0 ) )
1447 /* Hash the public key certificate. */
1448 hash_public_key( md, pk );
1450 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1452 /* hash the subkey binding/backsig/revocation */
1453 hash_public_key( md, subpk );
1455 else if( sigclass != 0x1F && sigclass != 0x20 )
1457 /* hash the user id */
1458 hash_uid (md, sigversion, uid);
1460 /* and make the signature packet */
1461 sig = xmalloc_clear( sizeof *sig );
1462 sig->version = sigversion;
1463 sig->flags.exportable=1;
1464 sig->flags.revocable=1;
1465 keyid_from_pk (pksk, sig->keyid);
1466 sig->pubkey_algo = pksk->pubkey_algo;
1467 sig->digest_algo = digest_algo;
1469 sig->timestamp=timestamp;
1471 sig->timestamp=make_timestamp();
1473 sig->expiredate=sig->timestamp+duration;
1474 sig->sig_class = sigclass;
1476 build_sig_subpkt_from_sig( sig );
1477 mk_notation_policy_etc (sig, pk, pksk);
1479 /* Crucial that the call to mksubpkt comes LAST before the calls
1480 to finalize the sig as that makes it possible for the mksubpkt
1481 function to get a reliable pointer to the subpacket area. */
1483 rc = (*mksubpkt)( sig, opaque );
1486 hash_sigversion_to_magic (md, sig);
1489 rc = complete_sig (sig, pksk, md, cache_nonce);
1494 free_seckey_enc( sig );
1503 * Create a new signature packet based on an existing one.
1504 * Only user ID signatures are supported for now.
1505 * PK is the public key to work on.
1506 * PKSK is the key used to make the signature.
1508 * TODO: Merge this with make_keysig_packet.
1511 update_keysig_packet( PKT_signature **ret_sig,
1512 PKT_signature *orig_sig,
1515 PKT_public_key *subpk,
1516 PKT_public_key *pksk,
1517 int (*mksubpkt)(PKT_signature *, void *),
1525 if ((!orig_sig || !pk || !pksk)
1526 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1527 || (orig_sig->sig_class == 0x18 && !subpk))
1528 return GPG_ERR_GENERAL;
1530 if ( opt.cert_digest_algo )
1531 digest_algo = opt.cert_digest_algo;
1533 digest_algo = orig_sig->digest_algo;
1535 if ( gcry_md_open (&md, digest_algo, 0 ) )
1538 /* Hash the public key certificate and the user id. */
1539 hash_public_key( md, pk );
1541 if( orig_sig->sig_class == 0x18 )
1542 hash_public_key( md, subpk );
1544 hash_uid (md, orig_sig->version, uid);
1546 /* create a new signature packet */
1547 sig = copy_signature (NULL, orig_sig);
1549 sig->digest_algo=digest_algo;
1551 /* We need to create a new timestamp so that new sig expiration
1552 calculations are done correctly... */
1553 sig->timestamp=make_timestamp();
1555 /* ... but we won't make a timestamp earlier than the existing
1557 while(sig->timestamp<=orig_sig->timestamp)
1560 sig->timestamp=make_timestamp();
1563 /* Note that already expired sigs will remain expired (with a
1564 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1565 detects this case. */
1567 /* Put the updated timestamp into the sig. Note that this will
1568 automagically lower any sig expiration dates to correctly
1569 correspond to the differences in the timestamps (i.e. the
1570 duration will shrink). */
1571 build_sig_subpkt_from_sig( sig );
1574 rc = (*mksubpkt)(sig, opaque);
1577 hash_sigversion_to_magic (md, sig);
1580 rc = complete_sig (sig, pksk, md, NULL);
1585 free_seckey_enc (sig);