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/>.
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));
165 * Helper to hash a user ID packet.
168 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
174 if (uid->attrib_data)
176 buf[0] = 0xd1; /* Indicates an attribute packet. */
177 buf[1] = uid->attrib_len >> 24; /* Always use 4 length bytes. */
178 buf[2] = uid->attrib_len >> 16;
179 buf[3] = uid->attrib_len >> 8;
180 buf[4] = uid->attrib_len;
184 buf[0] = 0xb4; /* Indicates a userid packet. */
185 buf[1] = uid->len >> 24; /* Always use 4 length bytes. */
186 buf[2] = uid->len >> 16;
187 buf[3] = uid->len >> 8;
190 gcry_md_write( md, buf, 5 );
192 if (uid->attrib_data)
193 gcry_md_write (md, uid->attrib_data, uid->attrib_len );
195 gcry_md_write (md, uid->name, uid->len );
200 * Helper to hash some parts from the signature
203 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
208 gcry_md_putc (md, sig->version);
209 gcry_md_putc (md, sig->sig_class);
210 gcry_md_putc (md, sig->pubkey_algo);
211 gcry_md_putc (md, sig->digest_algo);
214 n = sig->hashed->len;
215 gcry_md_putc (md, (n >> 8) );
216 gcry_md_putc (md, n );
217 gcry_md_write (md, sig->hashed->data, n );
222 gcry_md_putc (md, 0); /* Always hash the length of the subpacket. */
223 gcry_md_putc (md, 0);
226 /* Add some magic. */
227 buf[0] = sig->version;
229 buf[2] = n >> 24; /* (n is only 16 bit, so this is always 0) */
233 gcry_md_write (md, buf, 6);
237 /* Perform the sign operation. If CACHE_NONCE is given the agent is
238 advised to use that cached passphrase fro the key. */
240 do_sign (PKT_public_key *pksk, PKT_signature *sig,
241 gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
247 if (pksk->timestamp > sig->timestamp )
249 ulong d = pksk->timestamp - sig->timestamp;
250 log_info (ngettext("key %s was created %lu second"
251 " in the future (time warp or clock problem)\n",
252 "key %s was created %lu seconds"
253 " in the future (time warp or clock problem)\n",
254 d), keystr_from_pk (pksk), d);
255 if (!opt.ignore_time_conflict)
256 return gpg_error (GPG_ERR_TIME_CONFLICT);
259 print_pubkey_algo_note (pksk->pubkey_algo);
262 mdalgo = gcry_md_get_algo (md);
264 print_digest_algo_note (mdalgo);
265 dp = gcry_md_read (md, mdalgo);
266 sig->digest_algo = mdalgo;
267 sig->digest_start[0] = dp[0];
268 sig->digest_start[1] = dp[1];
273 err = hexkeygrip_from_pk (pksk, &hexgrip);
277 gcry_sexp_t s_sigval;
279 desc = gpg_format_keydesc (pksk, FORMAT_KEYDESC_NORMAL, 1);
280 err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
281 pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
282 dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
288 else if (pksk->pubkey_algo == GCRY_PK_RSA
289 || pksk->pubkey_algo == GCRY_PK_RSA_S)
290 sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
291 else if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
293 sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE);
294 sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE);
298 sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
299 sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
302 gcry_sexp_release (s_sigval);
307 log_error (_("signing failed: %s\n"), gpg_strerror (err));
312 char *ustr = get_user_id_string_native (sig->keyid);
313 log_info (_("%s/%s signature from: \"%s\"\n"),
314 openpgp_pk_algo_name (pksk->pubkey_algo),
315 openpgp_md_algo_name (sig->digest_algo),
325 complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
326 const char *cache_nonce)
330 /* if (!(rc = check_secret_key (pksk, 0))) */
331 rc = do_sign (pksk, sig, md, 0, cache_nonce);
336 /* Return true if the key seems to be on a version 1 OpenPGP card.
337 This works by asking the agent and may fail if the card has not yet
338 been used with the agent. */
340 openpgp_card_v1_p (PKT_public_key *pk)
345 /* Shortcut if we are not using RSA: The v1 cards only support RSA
346 thus there is no point in looking any further. */
347 if (!is_RSA (pk->pubkey_algo))
350 if (!pk->flags.serialno_valid)
354 err = hexkeygrip_from_pk (pk, &hexgrip);
357 log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
358 return 0; /* Ooops. */
361 xfree (pk->serialno);
362 agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL);
364 pk->flags.serialno_valid = 1;
368 result = 0; /* Error from a past agent_get_keyinfo or no card. */
371 /* The version number of the card is included in the serialno. */
372 result = !strncmp (pk->serialno, "D2760001240101", 14);
380 match_dsa_hash (unsigned int qbytes)
383 return DIGEST_ALGO_SHA1;
386 return DIGEST_ALGO_SHA224;
389 return DIGEST_ALGO_SHA256;
392 return DIGEST_ALGO_SHA384;
394 if (qbytes <= 66 ) /* 66 corresponds to 521 (64 to 512) */
395 return DIGEST_ALGO_SHA512;
397 return DEFAULT_DIGEST_ALGO;
398 /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
399 answer we have if a digest larger than 512 bits is requested. */
404 First try --digest-algo. If that isn't set, see if the recipient
405 has a preferred algorithm (which is also filtered through
406 --personal-digest-prefs). If we're making a signature without a
407 particular recipient (i.e. signing, rather than signing+encrypting)
408 then take the first algorithm in --personal-digest-prefs that is
409 usable for the pubkey algorithm. If --personal-digest-prefs isn't
410 set, then take the OpenPGP default (i.e. SHA-1).
412 Note that Ed25519+EdDSA takes an input of arbitrary length and thus
413 we don't enforce any particular algorithm like we do for standard
414 ECDSA. However, we use SHA256 as the default algorithm.
416 Possible improvement: Use the highest-ranked usable algorithm from
417 the signing key prefs either before or after using the personal
421 hash_for (PKT_public_key *pk)
423 if (opt.def_digest_algo)
425 return opt.def_digest_algo;
427 else if (recipient_digest_algo)
429 return recipient_digest_algo;
431 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA
432 && openpgp_oid_is_ed25519 (pk->pkey[0]))
434 if (opt.personal_digest_prefs)
435 return opt.personal_digest_prefs[0].value;
437 return DIGEST_ALGO_SHA256;
439 else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
440 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
442 unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
444 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
445 qbytes = ecdsa_qbits_from_Q (qbytes);
448 /* It's a DSA key, so find a hash that is the same size as q or
449 larger. If q is 160, assume it is an old DSA key and use a
450 160-bit hash unless --enable-dsa2 is set, in which case act
451 like a new DSA key that just happens to have a 160-bit q
452 (i.e. allow truncation). If q is not 160, by definition it
453 must be a new DSA key. */
455 if (opt.personal_digest_prefs)
459 if (qbytes != 20 || opt.flags.dsa2)
461 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
462 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
467 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
468 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
473 return match_dsa_hash(qbytes);
475 else if (openpgp_card_v1_p (pk))
477 /* The sk lives on a smartcard, and old smartcards only handle
478 SHA-1 and RIPEMD/160. Newer smartcards (v2.0) don't have
479 this restriction anymore. Fortunately the serial number
480 encodes the version of the card and thus we know that this
481 key is on a v1 card. */
482 if(opt.personal_digest_prefs)
486 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
487 if (prefs->value==DIGEST_ALGO_SHA1
488 || prefs->value==DIGEST_ALGO_RMD160)
492 return DIGEST_ALGO_SHA1;
494 else if (opt.personal_digest_prefs)
496 /* It's not DSA, so we can use whatever the first hash algorithm
497 is in the pref list */
498 return opt.personal_digest_prefs[0].value;
501 return DEFAULT_DIGEST_ALGO;
506 print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
508 byte array[MAX_FINGERPRINT_LEN];
509 char buf[100+MAX_FINGERPRINT_LEN*2];
512 snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
513 what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
514 (ulong)sig->timestamp );
515 fingerprint_from_pk (pk, array, &n);
516 bin2hex (array, n, buf + strlen (buf));
518 write_status_text( STATUS_SIG_CREATED, buf );
523 * Loop over the secret certificates in SK_LIST and build the one pass
524 * signature packets. OpenPGP says that the data should be bracket by
525 * the onepass-sig and signature-packet; so we build these onepass
526 * packet here in reverse order
529 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
534 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
537 for (; skcount; skcount--) {
539 PKT_onepass_sig *ops;
543 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
549 ops = xmalloc_clear (sizeof *ops);
550 ops->sig_class = sigclass;
551 ops->digest_algo = hash_for (pk);
552 ops->pubkey_algo = pk->pubkey_algo;
553 keyid_from_pk (pk, ops->keyid);
554 ops->last = (skcount == 1);
557 pkt.pkttype = PKT_ONEPASS_SIG;
558 pkt.pkt.onepass_sig = ops;
559 rc = build_packet (out, &pkt);
562 log_error ("build onepass_sig packet failed: %s\n",
572 * Helper to write the plaintext (literal data) packet
575 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
577 PKT_plaintext *pt = NULL;
582 pt=setup_plaintext_name(fname,inp);
584 /* try to calculate the length of the data */
585 if ( !iobuf_is_pipe_filename (fname) && *fname )
590 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
591 && !overflow && opt.verbose)
592 log_info (_("WARNING: '%s' is an empty file\n"), fname);
594 /* We can't encode the length of very large files because
595 OpenPGP uses only 32 bit for file sizes. So if the size of
596 a file is larger than 2^32 minus some bytes for packet
597 headers, we switch to partial length encoding. */
598 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
603 /* Because the text_filter modifies the length of the
604 * data, it is not possible to know the used length
605 * without a double read of the file - to avoid that
606 * we simple use partial length packets. */
611 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
613 if (!opt.no_literal) {
616 /* Note that PT has been initialized above in no_literal mode. */
617 pt->timestamp = make_timestamp ();
620 pt->new_ctb = !pt->len;
623 pkt.pkttype = PKT_PLAINTEXT;
624 pkt.pkt.plaintext = pt;
625 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
626 if( (rc = build_packet (out, &pkt)) )
627 log_error ("build_packet(PLAINTEXT) failed: %s\n",
632 byte copy_buffer[4096];
635 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
636 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
637 log_error ("copying input to output failed: %s\n",
641 wipememory(copy_buffer,4096); /* burn buffer */
643 /* fixme: it seems that we never freed pt/pkt */
649 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
650 * hash which will not be changes here.
653 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
654 int sigclass, u32 timestamp, u32 duration,
655 int status_letter, const char *cache_nonce)
659 /* Loop over the certificates with secret keys. */
660 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
669 /* Build the signature packet. */
670 sig = xmalloc_clear (sizeof *sig);
671 if (duration || opt.sig_policy_url
672 || opt.sig_notations || opt.sig_keyserver_url)
675 sig->version = pk->version;
677 keyid_from_pk (pk, sig->keyid);
678 sig->digest_algo = hash_for (pk);
679 sig->pubkey_algo = pk->pubkey_algo;
681 sig->timestamp = timestamp;
683 sig->timestamp = make_timestamp();
685 sig->expiredate = sig->timestamp + duration;
686 sig->sig_class = sigclass;
688 if (gcry_md_copy (&md, hash))
691 if (sig->version >= 4)
693 build_sig_subpkt_from_sig (sig);
694 mk_notation_policy_etc (sig, NULL, pk);
697 hash_sigversion_to_magic (md, sig);
700 rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
704 /* Write the packet. */
708 pkt.pkttype = PKT_SIGNATURE;
709 pkt.pkt.signature = sig;
710 rc = build_packet (out, &pkt);
711 if (!rc && is_status_enabled())
712 print_status_sig_created (pk, sig, status_letter);
715 log_error ("build signature packet failed: %s\n", gpg_strerror (rc));
726 * Sign the files whose names are in FILENAME.
727 * If DETACHED has the value true,
728 * make a detached signature. If FILENAMES->d is NULL read from stdin
729 * and ignore the detached mode. Sign the file with all secret keys
730 * which can be taken from LOCUSR, if this is NULL, use the default one
731 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
732 * signed data for these users.
733 * If OUTFILE is not NULL; this file is used for output and the function
734 * does not ask for overwrite permission; output is then always
735 * uncompressed, non-armored and in binary mode.
738 sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
739 int encryptflag, strlist_t remusr, const char *outfile )
742 armor_filter_context_t *afx;
743 compress_filter_context_t zfx;
744 md_filter_context_t mfx;
745 text_filter_context_t tfx;
746 progress_filter_context_t *pfx;
747 encrypt_filter_context_t efx;
748 IOBUF inp = NULL, out = NULL;
751 PK_LIST pk_list = NULL;
752 SK_LIST sk_list = NULL;
753 SK_LIST sk_rover = NULL;
757 pfx = new_progress_context ();
758 afx = new_armor_context ();
759 memset( &zfx, 0, sizeof zfx);
760 memset( &mfx, 0, sizeof mfx);
761 memset( &efx, 0, sizeof efx);
765 fname = filenames->d;
766 multifile = !!filenames->next;
771 if( fname && filenames->next && (!detached || encryptflag) )
772 log_bug("multiple files can only be detached signed");
775 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
778 if (opt.ask_sig_expire && !opt.batch)
779 duration = ask_expire_interval(1,opt.def_sig_expire);
781 duration = parse_expire_string(opt.def_sig_expire);
783 /* Note: In the old non-agent version the following call used to
784 unprotect the secret key. This is now done on demand by the agent. */
785 if( (rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
789 && (rc=build_pk_list (ctrl, remusr, &pk_list)))
793 if( multifile ) /* have list of filenames */
794 inp = NULL; /* we do it later */
796 inp = iobuf_open(fname);
797 if (inp && is_secured_file (iobuf_get_fd (inp)))
801 gpg_err_set_errno (EPERM);
805 rc = gpg_error_from_syserror ();
806 log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
811 handle_progress (pfx, inp, fname);
815 if (is_secured_filename ( outfile )) {
817 gpg_err_set_errno (EPERM);
820 out = iobuf_create (outfile, 0);
823 rc = gpg_error_from_syserror ();
824 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
827 else if( opt.verbose )
828 log_info(_("writing to '%s'\n"), outfile );
830 else if( (rc = open_outfile (-1, fname,
831 opt.armor? 1: detached? 2:0, 0, &out)))
834 /* prepare to calculate the MD over the input */
835 if( opt.textmode && !outfile && !multifile )
837 memset( &tfx, 0, sizeof tfx);
838 iobuf_push_filter( inp, text_filter, &tfx );
841 if ( gcry_md_open (&mfx.md, 0, 0) )
844 gcry_md_debug (mfx.md, "sign");
846 /* If we're encrypting and signing, it is reasonable to pick the
847 hash algorithm to use out of the recipient key prefs. This is
848 best effort only, as in a DSA2 and smartcard world there are
849 cases where we cannot please everyone with a single hash (DSA2
850 wants >160 and smartcards want =160). In the future this could
851 be more complex with different hashes for each sk, but the
852 current design requires a single hash for all SKs. */
855 if(opt.def_digest_algo)
858 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
860 NULL)!=opt.def_digest_algo)
861 log_info(_("WARNING: forcing digest algorithm %s (%d)"
862 " violates recipient preferences\n"),
863 gcry_md_algo_name (opt.def_digest_algo),
864 opt.def_digest_algo );
868 int algo, smartcard=0;
869 union pref_hint hint;
871 hint.digest_length = 0;
873 /* Of course, if the recipient asks for something
874 unreasonable (like the wrong hash for a DSA key) then
875 don't do it. Check all sk's - if any are DSA or live
876 on a smartcard, then the hash has restrictions and we
877 may not be able to give the recipient what they want.
878 For DSA, pass a hint for the largest q we have. Note
879 that this means that a q>160 key will override a q=160
880 key and force the use of truncation for the q=160 key.
881 The alternative would be to ignore the recipient prefs
882 completely and get a different hash for each DSA key in
883 hash_for(). The override behavior here is more or less
884 reasonable as it is under the control of the user which
885 keys they sign with for a given message and the fact
886 that the message with multiple signatures won't be
887 usable on an implementation that doesn't understand
890 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
892 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
893 || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
895 int temp_hashlen = (gcry_mpi_get_nbits
896 (sk_rover->pk->pkey[1]));
898 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
899 temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
900 temp_hashlen = (temp_hashlen+7)/8;
902 /* Pick a hash that is large enough for our
905 if (hint.digest_length<temp_hashlen)
906 hint.digest_length=temp_hashlen;
908 /* FIXME: need to check gpg-agent for this. */
909 /* else if (sk_rover->pk->is_protected */
910 /* && sk_rover->pk->protect.s2k.mode == 1002) */
914 /* Current smartcards only do 160-bit hashes. If we have
915 to have a >160-bit hash, then we can't use the
916 recipient prefs as we'd need both =160 and >160 at the
917 same time and recipient prefs currently require a
918 single hash for all signatures. All this may well have
919 to change as the cards add algorithms. */
921 if (!smartcard || (smartcard && hint.digest_length==20))
923 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
924 recipient_digest_algo=algo;
928 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
929 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
932 iobuf_push_filter( inp, md_filter, &mfx );
934 if( detached && !encryptflag)
937 if( opt.armor && !outfile )
938 push_armor_filter (afx, out);
941 efx.pk_list = pk_list;
942 /* fixme: set efx.cfx.datalen if known */
943 iobuf_push_filter( out, encrypt_filter, &efx );
946 if (opt.compress_algo && !outfile && !detached)
948 int compr_algo=opt.compress_algo;
950 /* If not forced by user */
953 /* If we're not encrypting, then select_algo_from_prefs
954 will fail and we'll end up with the default. If we are
955 encrypting, select_algo_from_prefs cannot fail since
956 there is an assumed preference for uncompressed data.
957 Still, if it did fail, we'll also end up with the
961 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
962 compr_algo=default_compress_algo();
964 else if(!opt.expert && pk_list
965 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
966 compr_algo,NULL)!=compr_algo)
967 log_info(_("WARNING: forcing compression algorithm %s (%d)"
968 " violates recipient preferences\n"),
969 compress_algo_to_string(compr_algo),compr_algo);
971 /* algo 0 means no compression */
973 push_compress_filter(out,&zfx,compr_algo);
976 /* Write the one-pass signature packets if needed */
978 rc = write_onepass_sig_packets (sk_list, out,
979 opt.textmode && !outfile ? 0x01:0x00);
984 write_status_begin_signing (mfx.md);
986 /* Setup the inner packet. */
992 log_info(_("signing:") );
993 /* must walk reverse trough this list */
994 for( sl = strlist_last(filenames); sl;
995 sl = strlist_prev( filenames, sl ) ) {
996 inp = iobuf_open(sl->d);
997 if (inp && is_secured_file (iobuf_get_fd (inp)))
1001 gpg_err_set_errno (EPERM);
1005 rc = gpg_error_from_syserror ();
1006 log_error(_("can't open '%s': %s\n"),
1007 sl->d,strerror(errno));
1010 handle_progress (pfx, inp, sl->d);
1012 log_printf (" '%s'", sl->d );
1015 memset( &tfx, 0, sizeof tfx);
1016 iobuf_push_filter( inp, text_filter, &tfx );
1018 iobuf_push_filter( inp, md_filter, &mfx );
1019 while( iobuf_get(inp) != -1 )
1021 iobuf_close(inp); inp = NULL;
1027 /* read, so that the filter can calculate the digest */
1028 while( iobuf_get(inp) != -1 )
1033 rc = write_plaintext_packet (out, inp, fname,
1034 opt.textmode && !outfile ? 't':'b');
1037 /* catch errors from above */
1041 /* write the signatures */
1042 rc = write_signature_packets (sk_list, out, mfx.md,
1043 opt.textmode && !outfile? 0x01 : 0x00,
1044 0, duration, detached ? 'D':'S', NULL);
1055 write_status( STATUS_END_ENCRYPTION );
1058 gcry_md_close ( mfx.md );
1059 release_sk_list( sk_list );
1060 release_pk_list( pk_list );
1061 recipient_digest_algo=0;
1062 release_progress_context (pfx);
1063 release_armor_context (afx);
1070 * make a clear signature. note that opt.armor is not needed
1073 clearsign_file (ctrl_t ctrl,
1074 const char *fname, strlist_t locusr, const char *outfile )
1076 armor_filter_context_t *afx;
1077 progress_filter_context_t *pfx;
1078 gcry_md_hd_t textmd = NULL;
1079 IOBUF inp = NULL, out = NULL;
1082 SK_LIST sk_list = NULL;
1083 SK_LIST sk_rover = NULL;
1086 pfx = new_progress_context ();
1087 afx = new_armor_context ();
1088 init_packet( &pkt );
1090 if (opt.ask_sig_expire && !opt.batch)
1091 duration = ask_expire_interval (1,opt.def_sig_expire);
1093 duration = parse_expire_string (opt.def_sig_expire);
1095 /* Note: In the old non-agent version the following call used to
1096 unprotect the secret key. This is now done on demand by the agent. */
1097 if( (rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
1100 /* prepare iobufs */
1101 inp = iobuf_open(fname);
1102 if (inp && is_secured_file (iobuf_get_fd (inp)))
1106 gpg_err_set_errno (EPERM);
1109 rc = gpg_error_from_syserror ();
1110 log_error (_("can't open '%s': %s\n"),
1111 fname? fname: "[stdin]", strerror(errno) );
1114 handle_progress (pfx, inp, fname);
1117 if (is_secured_filename (outfile) ) {
1119 gpg_err_set_errno (EPERM);
1122 out = iobuf_create (outfile, 0);
1125 rc = gpg_error_from_syserror ();
1126 log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
1129 else if( opt.verbose )
1130 log_info(_("writing to '%s'\n"), outfile );
1132 else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
1135 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1140 byte hashs_seen[256];
1142 memset( hashs_seen, 0, sizeof hashs_seen );
1143 iobuf_writestr(out, "Hash: " );
1144 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1145 int i = hash_for (sk_rover->pk);
1147 if( !hashs_seen[ i & 0xff ] ) {
1148 s = gcry_md_algo_name ( i );
1150 hashs_seen[ i & 0xff ] = 1;
1152 iobuf_put(out, ',' );
1153 iobuf_writestr(out, s );
1159 iobuf_writestr(out, LF );
1162 if( opt.not_dash_escaped )
1163 iobuf_writestr( out,
1164 "NotDashEscaped: You need "GPG_NAME
1165 " to verify this message" LF );
1166 iobuf_writestr(out, LF );
1168 if ( gcry_md_open (&textmd, 0, 0) )
1170 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1171 gcry_md_enable (textmd, hash_for(sk_rover->pk));
1174 gcry_md_debug ( textmd, "clearsign" );
1176 copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
1178 /* fixme: check for read errors */
1180 /* now write the armor */
1182 push_armor_filter (afx, out);
1184 /* Write the signatures. */
1185 rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
1196 gcry_md_close ( textmd );
1197 release_sk_list( sk_list );
1198 release_progress_context (pfx);
1199 release_armor_context (afx);
1204 * Sign and conventionally encrypt the given file.
1205 * FIXME: Far too much code is duplicated - revamp the whole file.
1208 sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
1210 armor_filter_context_t *afx;
1211 progress_filter_context_t *pfx;
1212 compress_filter_context_t zfx;
1213 md_filter_context_t mfx;
1214 text_filter_context_t tfx;
1215 cipher_filter_context_t cfx;
1216 IOBUF inp = NULL, out = NULL;
1218 STRING2KEY *s2k = NULL;
1220 SK_LIST sk_list = NULL;
1221 SK_LIST sk_rover = NULL;
1226 pfx = new_progress_context ();
1227 afx = new_armor_context ();
1228 memset( &zfx, 0, sizeof zfx);
1229 memset( &mfx, 0, sizeof mfx);
1230 memset( &tfx, 0, sizeof tfx);
1231 memset( &cfx, 0, sizeof cfx);
1232 init_packet( &pkt );
1234 if (opt.ask_sig_expire && !opt.batch)
1235 duration = ask_expire_interval (1, opt.def_sig_expire);
1237 duration = parse_expire_string (opt.def_sig_expire);
1239 /* Note: In the old non-agent version the following call used to
1240 unprotect the secret key. This is now done on demand by the agent. */
1241 rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
1245 /* prepare iobufs */
1246 inp = iobuf_open(fname);
1247 if (inp && is_secured_file (iobuf_get_fd (inp)))
1251 gpg_err_set_errno (EPERM);
1254 rc = gpg_error_from_syserror ();
1255 log_error (_("can't open '%s': %s\n"),
1256 fname? fname: "[stdin]", strerror(errno) );
1259 handle_progress (pfx, inp, fname);
1262 s2k = xmalloc_clear( sizeof *s2k );
1263 s2k->mode = opt.s2k_mode;
1264 s2k->hash_algo = S2K_DIGEST_ALGO;
1266 algo = default_cipher_algo();
1267 if (!opt.quiet || !opt.batch)
1268 log_info (_("%s encryption will be used\n"),
1269 openpgp_cipher_algo_name (algo) );
1270 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
1272 if (!cfx.dek || !cfx.dek->keylen) {
1273 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1274 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1278 cfx.dek->use_mdc = use_mdc (NULL, cfx.dek->algo);
1280 /* now create the outfile */
1281 rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
1285 /* prepare to calculate the MD over the input */
1287 iobuf_push_filter (inp, text_filter, &tfx);
1288 if ( gcry_md_open (&mfx.md, 0, 0) )
1291 gcry_md_debug (mfx.md, "symc-sign");
1293 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1294 gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
1296 iobuf_push_filter (inp, md_filter, &mfx);
1298 /* Push armor output filter */
1300 push_armor_filter (afx, out);
1302 /* Write the symmetric key packet */
1303 /*(current filters: armor)*/
1305 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1307 enc->cipher_algo = cfx.dek->algo;
1309 pkt.pkttype = PKT_SYMKEY_ENC;
1310 pkt.pkt.symkey_enc = enc;
1311 if( (rc = build_packet( out, &pkt )) )
1312 log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
1316 /* Push the encryption filter */
1317 iobuf_push_filter( out, cipher_filter, &cfx );
1319 /* Push the compress filter */
1320 if (default_compress_algo())
1322 if (cfx.dek && cfx.dek->use_mdc)
1324 push_compress_filter (out, &zfx,default_compress_algo() );
1327 /* Write the one-pass signature packets */
1328 /*(current filters: zip - encrypt - armor)*/
1329 rc = write_onepass_sig_packets (sk_list, out,
1330 opt.textmode? 0x01:0x00);
1334 write_status_begin_signing (mfx.md);
1336 /* Pipe data through all filters; i.e. write the signed stuff */
1337 /*(current filters: zip - encrypt - armor)*/
1338 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1342 /* Write the signatures */
1343 /*(current filters: zip - encrypt - armor)*/
1344 rc = write_signature_packets (sk_list, out, mfx.md,
1345 opt.textmode? 0x01 : 0x00,
1346 0, duration, 'S', NULL);
1356 write_status( STATUS_END_ENCRYPTION );
1359 release_sk_list( sk_list );
1360 gcry_md_close( mfx.md );
1363 release_progress_context (pfx);
1364 release_armor_context (afx);
1370 * Create a signature packet for the given public key certificate and
1371 * the user id and return it in ret_sig. User signature class SIGCLASS
1372 * user-id is not used (and may be NULL if sigclass is 0x20) If
1373 * DIGEST_ALGO is 0 the function selects an appropriate one.
1374 * SIGVERSION gives the minimal required signature packet version;
1375 * this is needed so that special properties like local sign are not
1376 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1377 * the timestamp to use for the signature. 0 means "now" */
1379 make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
1380 PKT_user_id *uid, PKT_public_key *subpk,
1381 PKT_public_key *pksk,
1382 int sigclass, int digest_algo,
1383 u32 timestamp, u32 duration,
1384 int (*mksubpkt)(PKT_signature *, void *), void *opaque,
1385 const char *cache_nonce)
1392 log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1393 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1394 || sigclass == 0x30 || sigclass == 0x28 );
1397 if (sigversion < pksk->version)
1398 sigversion = pksk->version;
1402 /* Basically, this means use SHA1 always unless the user
1403 specified something (use whatever they said), or it's DSA
1404 (use the best match). They still can't pick an
1405 inappropriate hash for DSA or the signature will fail.
1406 Note that this still allows the caller of
1407 make_keysig_packet to override the user setting if it
1410 if(opt.cert_digest_algo)
1411 digest_algo=opt.cert_digest_algo;
1412 else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
1413 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
1414 else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
1415 || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
1417 if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
1418 digest_algo = DIGEST_ALGO_SHA256;
1420 digest_algo = match_dsa_hash
1421 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
1424 digest_algo = DEFAULT_DIGEST_ALGO;
1427 if ( gcry_md_open (&md, digest_algo, 0 ) )
1430 /* Hash the public key certificate. */
1431 hash_public_key( md, pk );
1433 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1435 /* hash the subkey binding/backsig/revocation */
1436 hash_public_key( md, subpk );
1438 else if( sigclass != 0x1F && sigclass != 0x20 )
1440 /* hash the user id */
1441 hash_uid (md, sigversion, uid);
1443 /* and make the signature packet */
1444 sig = xmalloc_clear( sizeof *sig );
1445 sig->version = sigversion;
1446 sig->flags.exportable=1;
1447 sig->flags.revocable=1;
1448 keyid_from_pk (pksk, sig->keyid);
1449 sig->pubkey_algo = pksk->pubkey_algo;
1450 sig->digest_algo = digest_algo;
1452 sig->timestamp=timestamp;
1454 sig->timestamp=make_timestamp();
1456 sig->expiredate=sig->timestamp+duration;
1457 sig->sig_class = sigclass;
1459 build_sig_subpkt_from_sig( sig );
1460 mk_notation_policy_etc (sig, pk, pksk);
1462 /* Crucial that the call to mksubpkt comes LAST before the calls
1463 to finalize the sig as that makes it possible for the mksubpkt
1464 function to get a reliable pointer to the subpacket area. */
1466 rc = (*mksubpkt)( sig, opaque );
1469 hash_sigversion_to_magic (md, sig);
1472 rc = complete_sig (sig, pksk, md, cache_nonce);
1477 free_seckey_enc( sig );
1486 * Create a new signature packet based on an existing one.
1487 * Only user ID signatures are supported for now.
1488 * PK is the public key to work on.
1489 * PKSK is the key used to make the signature.
1491 * TODO: Merge this with make_keysig_packet.
1494 update_keysig_packet( PKT_signature **ret_sig,
1495 PKT_signature *orig_sig,
1498 PKT_public_key *subpk,
1499 PKT_public_key *pksk,
1500 int (*mksubpkt)(PKT_signature *, void *),
1508 if ((!orig_sig || !pk || !pksk)
1509 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1510 || (orig_sig->sig_class == 0x18 && !subpk))
1511 return GPG_ERR_GENERAL;
1513 if ( opt.cert_digest_algo )
1514 digest_algo = opt.cert_digest_algo;
1516 digest_algo = orig_sig->digest_algo;
1518 if ( gcry_md_open (&md, digest_algo, 0 ) )
1521 /* Hash the public key certificate and the user id. */
1522 hash_public_key( md, pk );
1524 if( orig_sig->sig_class == 0x18 )
1525 hash_public_key( md, subpk );
1527 hash_uid (md, orig_sig->version, uid);
1529 /* create a new signature packet */
1530 sig = copy_signature (NULL, orig_sig);
1532 sig->digest_algo=digest_algo;
1534 /* We need to create a new timestamp so that new sig expiration
1535 calculations are done correctly... */
1536 sig->timestamp=make_timestamp();
1538 /* ... but we won't make a timestamp earlier than the existing
1542 while(sig->timestamp<=orig_sig->timestamp)
1544 if (++tmout > 5 && !opt.ignore_time_conflict)
1546 rc = gpg_error (GPG_ERR_TIME_CONFLICT);
1550 sig->timestamp=make_timestamp();
1554 /* Note that already expired sigs will remain expired (with a
1555 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1556 detects this case. */
1558 /* Put the updated timestamp into the sig. Note that this will
1559 automagically lower any sig expiration dates to correctly
1560 correspond to the differences in the timestamps (i.e. the
1561 duration will shrink). */
1562 build_sig_subpkt_from_sig( sig );
1565 rc = (*mksubpkt)(sig, opaque);
1568 hash_sigversion_to_magic (md, sig);
1571 rc = complete_sig (sig, pksk, md, NULL);
1577 free_seckey_enc (sig);