2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006 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 2 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, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
29 #include <unistd.h> /* need sleep() */
45 #include "call-agent.h"
48 #ifdef HAVE_DOSISH_SYSTEM
50 void __stdcall
Sleep(ulong
);
51 #define sleep(a) Sleep((a)*1000)
56 static int recipient_digest_algo
=0;
59 * Create notations and other stuff. It is assumed that the stings in
60 * STRLIST are already checked to contain only printable data and have
61 * a valid NAME=VALUE format.
64 mk_notation_policy_etc( PKT_signature
*sig
,
65 PKT_public_key
*pk
, PKT_secret_key
*sk
)
70 struct notation
*nd
=NULL
;
71 struct expando_args args
;
73 memset(&args
,0,sizeof(args
));
77 /* It is actually impossible to get here when making a v3 key
78 signature since keyedit.c:sign_uids will automatically bump a
79 signature with a notation or policy url up to v4, but it is
80 good to do these checks anyway. */
83 if(IS_SIG(sig
) && opt
.sig_notations
)
86 log_error(_("can't put notation data into v3 (PGP 2.x style) "
91 else if( IS_CERT(sig
) && opt
.cert_notations
)
94 log_error(_("can't put notation data into v3 (PGP 2.x style) "
97 nd
=opt
.cert_notations
;
104 for(i
=nd
;i
;i
=i
->next
)
106 i
->altvalue
=pct_expando(i
->value
,&args
);
108 log_error(_("WARNING: unable to %%-expand notation "
109 "(too large). Using unexpanded.\n"));
112 keygen_add_notations(sig
,nd
);
114 for(i
=nd
;i
;i
=i
->next
)
122 if( IS_SIG(sig
) && opt
.sig_policy_url
)
125 log_error(_("can't put a policy URL into v3 (PGP 2.x style) "
128 pu
=opt
.sig_policy_url
;
130 else if( IS_CERT(sig
) && opt
.cert_policy_url
)
133 log_error(_("can't put a policy URL into v3 key (PGP 2.x style) "
136 pu
=opt
.cert_policy_url
;
143 s
=pct_expando(string
,&args
);
146 log_error(_("WARNING: unable to %%-expand policy URL "
147 "(too large). Using unexpanded.\n"));
151 build_sig_subpkt(sig
,SIGSUBPKT_POLICY
|
152 ((pu
->flags
& 1)?SIGSUBPKT_FLAG_CRITICAL
:0),
158 /* preferred keyserver URL */
159 if( IS_SIG(sig
) && opt
.sig_keyserver_url
)
162 log_info("can't put a preferred keyserver URL into v3 signatures\n");
164 pu
=opt
.sig_keyserver_url
;
171 s
=pct_expando(string
,&args
);
174 log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
175 " (too large). Using unexpanded.\n"));
179 build_sig_subpkt(sig
,SIGSUBPKT_PREF_KS
|
180 ((pu
->flags
& 1)?SIGSUBPKT_FLAG_CRITICAL
:0),
189 * Helper to hash a user ID packet.
192 hash_uid (gcry_md_hd_t md
, int sigversion
, const PKT_user_id
*uid
)
194 if ( sigversion
>= 4 ) {
197 if(uid
->attrib_data
) {
198 buf
[0] = 0xd1; /* indicates an attribute packet */
199 buf
[1] = uid
->attrib_len
>> 24; /* always use 4 length bytes */
200 buf
[2] = uid
->attrib_len
>> 16;
201 buf
[3] = uid
->attrib_len
>> 8;
202 buf
[4] = uid
->attrib_len
;
205 buf
[0] = 0xb4; /* indicates a userid packet */
206 buf
[1] = uid
->len
>> 24; /* always use 4 length bytes */
207 buf
[2] = uid
->len
>> 16;
208 buf
[3] = uid
->len
>> 8;
211 gcry_md_write( md
, buf
, 5 );
215 gcry_md_write (md
, uid
->attrib_data
, uid
->attrib_len
);
217 gcry_md_write (md
, uid
->name
, uid
->len
);
222 * Helper to hash some parts from the signature
225 hash_sigversion_to_magic (gcry_md_hd_t md
, const PKT_signature
*sig
)
227 if (sig
->version
>= 4)
228 gcry_md_putc (md
, sig
->version
);
229 gcry_md_putc (md
, sig
->sig_class
);
230 if (sig
->version
< 4) {
231 u32 a
= sig
->timestamp
;
232 gcry_md_putc (md
, (a
>> 24) & 0xff );
233 gcry_md_putc (md
, (a
>> 16) & 0xff );
234 gcry_md_putc (md
, (a
>> 8) & 0xff );
235 gcry_md_putc (md
, a
& 0xff );
241 gcry_md_putc (md
, sig
->pubkey_algo
);
242 gcry_md_putc (md
, sig
->digest_algo
);
244 n
= sig
->hashed
->len
;
245 gcry_md_putc (md
, (n
>> 8) );
246 gcry_md_putc (md
, n
);
247 gcry_md_write (md
, sig
->hashed
->data
, n
);
251 gcry_md_putc (md
, 0); /* always hash the length of the subpacket*/
252 gcry_md_putc (md
, 0);
256 buf
[0] = sig
->version
;
258 buf
[2] = n
>> 24; /* hmmm, n is only 16 bit, so this is always 0 */
262 gcry_md_write (md
, buf
, 6);
268 do_sign( PKT_secret_key
*sk
, PKT_signature
*sig
,
269 gcry_md_hd_t md
, int digest_algo
)
275 if( sk
->timestamp
> sig
->timestamp
) {
276 ulong d
= sk
->timestamp
- sig
->timestamp
;
277 log_info( d
==1 ? _("key has been created %lu second "
278 "in future (time warp or clock problem)\n")
279 : _("key has been created %lu seconds "
280 "in future (time warp or clock problem)\n"), d
);
281 if( !opt
.ignore_time_conflict
)
282 return G10ERR_TIME_CONFLICT
;
286 print_pubkey_algo_note(sk
->pubkey_algo
);
289 digest_algo
= gcry_md_get_algo (md
);
291 print_digest_algo_note( digest_algo
);
292 dp
= gcry_md_read ( md
, digest_algo
);
293 sig
->digest_algo
= digest_algo
;
294 sig
->digest_start
[0] = dp
[0];
295 sig
->digest_start
[1] = dp
[1];
296 if (sk
->is_protected
&& sk
->protect
.s2k
.mode
== 1002)
298 #ifdef ENABLE_CARD_SUPPORT
303 snbuf
= serialno_and_fpr_from_sk (sk
->protect
.iv
,
304 sk
->protect
.ivlen
, sk
);
305 rc
= agent_scd_pksign (snbuf
, digest_algo
,
306 gcry_md_read (md
, digest_algo
),
307 gcry_md_get_algo_dlen (digest_algo
),
312 if (gcry_mpi_scan (&sig
->data
[0], GCRYMPI_FMT_USG
,
313 rbuf
, rbuflen
, NULL
))
318 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
319 #endif /* ENABLE_CARD_SUPPORT */
323 frame
= encode_md_value( NULL
, sk
, md
, digest_algo
);
325 return G10ERR_GENERAL
;
326 rc
= pk_sign( sk
->pubkey_algo
, sig
->data
, frame
, sk
->skey
);
327 gcry_mpi_release (frame
);
330 if (!rc
&& !opt
.no_sig_create_check
) {
331 /* Check that the signature verification worked and nothing is
332 * fooling us e.g. by a bug in the signature create
333 * code or by deliberately introduced faults. */
334 PKT_public_key
*pk
= xmalloc_clear (sizeof *pk
);
336 if( get_pubkey( pk
, sig
->keyid
) )
337 rc
= G10ERR_NO_PUBKEY
;
339 frame
= encode_md_value (pk
, NULL
, md
, sig
->digest_algo
);
343 rc
= pk_verify (pk
->pubkey_algo
, frame
, sig
->data
, pk
->pkey
);
344 gcry_mpi_release (frame
);
347 log_error (_("checking created signature failed: %s\n"),
349 free_public_key (pk
);
352 log_error(_("signing failed: %s\n"), g10_errstr(rc
) );
355 char *ustr
= get_user_id_string_native (sig
->keyid
);
356 log_info(_("%s/%s signature from: \"%s\"\n"),
357 gcry_pk_algo_name (sk
->pubkey_algo
),
358 gcry_md_algo_name (sig
->digest_algo
),
368 complete_sig( PKT_signature
*sig
, PKT_secret_key
*sk
, gcry_md_hd_t md
)
372 if( !(rc
=check_secret_key( sk
, 0 )) )
373 rc
= do_sign( sk
, sig
, md
, 0 );
380 match_dsa_hash (unsigned int qbytes
)
383 return DIGEST_ALGO_SHA1
;
386 return DIGEST_ALGO_SHA224
;
388 return DIGEST_ALGO_SHA256
;
393 return DIGEST_ALGO_SHA384
;
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 the larger SHAs aren't there. */
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 --preferred-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 --preferred-digest-prefs that is
409 usable for the pubkey algorithm. If --preferred-digest-prefs isn't
410 set, then take the OpenPGP default (i.e. SHA-1).
412 Possible improvement: Use the highest-ranked usable algorithm from
413 the signing key prefs either before or after using the personal
417 hash_for(PKT_secret_key
*sk
)
419 if( opt
.def_digest_algo
)
420 return opt
.def_digest_algo
;
421 else if( recipient_digest_algo
)
422 return recipient_digest_algo
;
423 else if(sk
->pubkey_algo
==PUBKEY_ALGO_DSA
)
425 unsigned int qbytes
= gcry_mpi_get_nbits (sk
->skey
[1]) / 8;
427 /* It's a DSA key, so find a hash that is the same size as q or
428 larger. If q is 160, assume it is an old DSA key and use a
429 160-bit hash unless --enable-dsa2 is set, in which case act
430 like a new DSA key that just happens to have a 160-bit q
431 (i.e. allow truncation). If q is not 160, by definition it
432 must be a new DSA key. */
434 if (opt
.personal_digest_prefs
)
438 if (qbytes
!= 20 || opt
.flags
.dsa2
)
440 for (prefs
=opt
.personal_digest_prefs
; prefs
->type
; prefs
++)
441 if (gcry_md_get_algo_dlen (prefs
->value
) >= qbytes
)
446 for (prefs
=opt
.personal_digest_prefs
; prefs
->type
; prefs
++)
447 if (gcry_md_get_algo_dlen (prefs
->value
) == qbytes
)
452 return match_dsa_hash(qbytes
);
454 else if (sk
->is_protected
&& sk
->protect
.s2k
.mode
==1002)
456 /* The sk lives on a smartcard, and current smartcards only
457 handle SHA-1 and RIPEMD/160. This is correct now, but may
458 need revision as the cards add algorithms. */
460 if(opt
.personal_digest_prefs
)
464 for (prefs
=opt
.personal_digest_prefs
;prefs
->type
;prefs
++)
465 if (prefs
->value
==DIGEST_ALGO_SHA1
466 || prefs
->value
==DIGEST_ALGO_RMD160
)
470 return DIGEST_ALGO_SHA1
;
472 else if (PGP2
&& sk
->pubkey_algo
== PUBKEY_ALGO_RSA
&& sk
->version
< 4 )
474 /* Old-style PGP only understands MD5 */
475 return DIGEST_ALGO_MD5
;
477 else if ( opt
.personal_digest_prefs
)
479 /* It's not DSA, so we can use whatever the first hash algorithm
480 is in the pref list */
481 return opt
.personal_digest_prefs
[0].value
;
484 return DEFAULT_DIGEST_ALGO
;
489 only_old_style( SK_LIST sk_list
)
491 SK_LIST sk_rover
= NULL
;
494 /* if there are only old style capable key we use the old sytle */
495 for( sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
496 PKT_secret_key
*sk
= sk_rover
->sk
;
497 if( sk
->pubkey_algo
== PUBKEY_ALGO_RSA
&& sk
->version
< 4 )
508 print_status_sig_created ( PKT_secret_key
*sk
, PKT_signature
*sig
, int what
)
510 byte array
[MAX_FINGERPRINT_LEN
], *p
;
511 char buf
[100+MAX_FINGERPRINT_LEN
*2];
514 sprintf(buf
, "%c %d %d %02x %lu ",
515 what
, sig
->pubkey_algo
, sig
->digest_algo
, sig
->sig_class
,
516 (ulong
)sig
->timestamp
);
518 fingerprint_from_sk( sk
, array
, &n
);
519 p
= buf
+ strlen(buf
);
520 for(i
=0; i
< n
; i
++ )
521 sprintf(p
+2*i
, "%02X", array
[i
] );
523 write_status_text( STATUS_SIG_CREATED
, buf
);
528 * Loop over the secret certificates in SK_LIST and build the one pass
529 * signature packets. OpenPGP says that the data should be bracket by
530 * the onepass-sig and signature-packet; so we build these onepass
531 * packet here in reverse order
534 write_onepass_sig_packets (SK_LIST sk_list
, IOBUF out
, int sigclass
)
539 for (skcount
=0, sk_rover
=sk_list
; sk_rover
; sk_rover
= sk_rover
->next
)
542 for (; skcount
; skcount
--) {
544 PKT_onepass_sig
*ops
;
548 for (i
=0, sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
554 ops
= xmalloc_clear (sizeof *ops
);
555 ops
->sig_class
= sigclass
;
556 ops
->digest_algo
= hash_for (sk
);
557 ops
->pubkey_algo
= sk
->pubkey_algo
;
558 keyid_from_sk (sk
, ops
->keyid
);
559 ops
->last
= (skcount
== 1);
562 pkt
.pkttype
= PKT_ONEPASS_SIG
;
563 pkt
.pkt
.onepass_sig
= ops
;
564 rc
= build_packet (out
, &pkt
);
567 log_error ("build onepass_sig packet failed: %s\n",
577 * Helper to write the plaintext (literal data) packet
580 write_plaintext_packet (IOBUF out
, IOBUF inp
, const char *fname
, int ptmode
)
582 PKT_plaintext
*pt
= NULL
;
587 pt
=setup_plaintext_name(fname
,inp
);
589 /* try to calculate the length of the data */
590 if ( !iobuf_is_pipe_filename (fname
) && *fname
)
595 if( !(tmpsize
= iobuf_get_filelength(inp
, &overflow
))
597 log_info (_("WARNING: `%s' is an empty file\n"), fname
);
599 /* We can't encode the length of very large files because
600 OpenPGP uses only 32 bit for file sizes. So if the size of
601 a file is larger than 2^32 minus some bytes for packet
602 headers, we switch to partial length encoding. */
603 if ( tmpsize
< (IOBUF_FILELENGTH_LIMIT
- 65536) )
608 /* Because the text_filter modifies the length of the
609 * data, it is not possible to know the used length
610 * without a double read of the file - to avoid that
611 * we simple use partial length packets. */
616 filesize
= opt
.set_filesize
? opt
.set_filesize
: 0; /* stdin */
618 if (!opt
.no_literal
) {
621 pt
->timestamp
= make_timestamp ();
624 pt
->new_ctb
= !pt
->len
&& !RFC1991
;
627 pkt
.pkttype
= PKT_PLAINTEXT
;
628 pkt
.pkt
.plaintext
= pt
;
629 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
630 if( (rc
= build_packet (out
, &pkt
)) )
631 log_error ("build_packet(PLAINTEXT) failed: %s\n",
636 byte copy_buffer
[4096];
639 while ((bytes_copied
= iobuf_read(inp
, copy_buffer
, 4096)) != -1)
640 if ( (rc
=iobuf_write(out
, copy_buffer
, bytes_copied
)) ) {
641 log_error ("copying input to output failed: %s\n",
645 wipememory(copy_buffer
,4096); /* burn buffer */
647 /* fixme: it seems that we never freed pt/pkt */
653 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
654 * hash which will not be changes here.
657 write_signature_packets (SK_LIST sk_list
, IOBUF out
, gcry_md_hd_t hash
,
658 int sigclass
, u32 timestamp
, u32 duration
,
663 /* loop over the secret certificates */
664 for (sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
672 /* build the signature packet */
673 sig
= xmalloc_clear (sizeof *sig
);
674 if(opt
.force_v3_sigs
|| RFC1991
)
676 else if(duration
|| opt
.sig_policy_url
677 || opt
.sig_notations
|| opt
.sig_keyserver_url
)
680 sig
->version
=sk
->version
;
681 keyid_from_sk (sk
, sig
->keyid
);
682 sig
->digest_algo
= hash_for(sk
);
683 sig
->pubkey_algo
= sk
->pubkey_algo
;
685 sig
->timestamp
= timestamp
;
687 sig
->timestamp
= make_timestamp();
689 sig
->expiredate
= sig
->timestamp
+duration
;
690 sig
->sig_class
= sigclass
;
692 if (gcry_md_copy (&md
, hash
))
695 if (sig
->version
>= 4)
696 build_sig_subpkt_from_sig (sig
);
697 mk_notation_policy_etc (sig
, NULL
, sk
);
699 hash_sigversion_to_magic (md
, sig
);
702 rc
= do_sign( sk
, sig
, md
, hash_for (sk
) );
704 if( !rc
) { /* and write it */
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 ( sk
, sig
, status_letter
);
716 log_error ("build signature packet failed: %s\n",
727 * Sign the files whose names are in FILENAME.
728 * If DETACHED has the value true,
729 * make a detached signature. If FILENAMES->d is NULL read from stdin
730 * and ignore the detached mode. Sign the file with all secret keys
731 * which can be taken from LOCUSR, if this is NULL, use the default one
732 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
733 * signed data for these users.
734 * If OUTFILE is not NULL; this file is used for output and the function
735 * does not ask for overwrite permission; output is then always
736 * uncompressed, non-armored and in binary mode.
739 sign_file( strlist_t filenames
, int detached
, strlist_t locusr
,
740 int encryptflag
, strlist_t remusr
, const char *outfile
)
743 armor_filter_context_t
*afx
;
744 compress_filter_context_t zfx
;
745 md_filter_context_t mfx
;
746 text_filter_context_t tfx
;
747 progress_filter_context_t
*pfx
;
748 encrypt_filter_context_t efx
;
749 IOBUF inp
= NULL
, out
= NULL
;
752 PK_LIST pk_list
= NULL
;
753 SK_LIST sk_list
= NULL
;
754 SK_LIST sk_rover
= NULL
;
758 pfx
= new_progress_context ();
759 afx
= new_armor_context ();
760 memset( &zfx
, 0, sizeof zfx
);
761 memset( &mfx
, 0, sizeof mfx
);
762 memset( &efx
, 0, sizeof efx
);
766 fname
= filenames
->d
;
767 multifile
= !!filenames
->next
;
772 if( fname
&& filenames
->next
&& (!detached
|| encryptflag
) )
773 log_bug("multiple files can only be detached signed");
776 && (rc
=setup_symkey(&efx
.symkey_s2k
,&efx
.symkey_dek
)))
779 if(!opt
.force_v3_sigs
&& !RFC1991
)
781 if(opt
.ask_sig_expire
&& !opt
.batch
)
782 duration
=ask_expire_interval(1,opt
.def_sig_expire
);
784 duration
=parse_expire_string(opt
.def_sig_expire
);
787 if( (rc
=build_sk_list( locusr
, &sk_list
, 1, PUBKEY_USAGE_SIG
)) )
790 if(PGP2
&& !only_old_style(sk_list
))
792 log_info(_("you can only detach-sign with PGP 2.x style keys "
793 "while in --pgp2 mode\n"));
794 compliance_failure();
797 if(encryptflag
&& (rc
=build_pk_list( remusr
, &pk_list
, PUBKEY_USAGE_ENC
)))
801 if( multifile
) /* have list of filenames */
802 inp
= NULL
; /* we do it later */
804 inp
= iobuf_open(fname
);
805 if (inp
&& is_secured_file (iobuf_get_fd (inp
)))
813 rc
= gpg_error_from_syserror ();
814 log_error (_("can't open `%s': %s\n"), fname
? fname
: "[stdin]",
819 handle_progress (pfx
, inp
, fname
);
823 if (is_secured_filename ( outfile
)) {
828 out
= iobuf_create( outfile
);
831 rc
= gpg_error_from_syserror ();
832 log_error(_("can't create `%s': %s\n"), outfile
, strerror(errno
) );
835 else if( opt
.verbose
)
836 log_info(_("writing to `%s'\n"), outfile
);
838 else if( (rc
= open_outfile( fname
, opt
.armor
? 1: detached
? 2:0, &out
)))
841 /* prepare to calculate the MD over the input */
842 if( opt
.textmode
&& !outfile
&& !multifile
)
844 memset( &tfx
, 0, sizeof tfx
);
845 iobuf_push_filter( inp
, text_filter
, &tfx
);
848 if ( gcry_md_open (&mfx
.md
, 0, 0) )
851 gcry_md_start_debug (mfx
.md
, "sign");
853 /* If we're encrypting and signing, it is reasonable to pick the
854 hash algorithm to use out of the recepient key prefs. This is
855 best effort only, as in a DSA2 and smartcard world there are
856 cases where we cannot please everyone with a single hash (DSA2
857 wants >160 and smartcards want =160). In the future this could
858 be more complex with different hashes for each sk, but the
859 current design requires a single hash for all SKs. */
862 if(opt
.def_digest_algo
)
865 select_algo_from_prefs(pk_list
,PREFTYPE_HASH
,
867 NULL
)!=opt
.def_digest_algo
)
868 log_info(_("WARNING: forcing digest algorithm %s (%d)"
869 " violates recipient preferences\n"),
870 gcry_md_algo_name (opt
.def_digest_algo
),
871 opt
.def_digest_algo
);
875 int algo
, smartcard
=0;
876 union pref_hint hint
;
878 hint
.digest_length
= 0;
880 /* Of course, if the recipient asks for something
881 unreasonable (like the wrong hash for a DSA key) then
882 don't do it. Check all sk's - if any are DSA or live
883 on a smartcard, then the hash has restrictions and we
884 may not be able to give the recipient what they want.
885 For DSA, pass a hint for the largest q we have. Note
886 that this means that a q>160 key will override a q=160
887 key and force the use of truncation for the q=160 key.
888 The alternative would be to ignore the recipient prefs
889 completely and get a different hash for each DSA key in
890 hash_for(). The override behavior here is more or less
891 reasonable as it is under the control of the user which
892 keys they sign with for a given message and the fact
893 that the message with multiple signatures won't be
894 usable on an implementation that doesn't understand
897 for (sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
)
899 if (sk_rover
->sk
->pubkey_algo
== PUBKEY_ALGO_DSA
)
901 int temp_hashlen
= gcry_mpi_get_nbits
902 (sk_rover
->sk
->skey
[1])+7/8;
904 /* Pick a hash that is large enough for our
907 if (hint
.digest_length
<temp_hashlen
)
908 hint
.digest_length
=temp_hashlen
;
910 else if (sk_rover
->sk
->is_protected
911 && sk_rover
->sk
->protect
.s2k
.mode
== 1002)
915 /* Current smartcards only do 160-bit hashes. If we have
916 to have a >160-bit hash, then we can't use the
917 recipient prefs as we'd need both =160 and >160 at the
918 same time and recipient prefs currently require a
919 single hash for all signatures. All this may well have
920 to change as the cards add algorithms. */
922 if (!smartcard
|| (smartcard
&& hint
.digest_length
==20))
924 select_algo_from_prefs(pk_list
,PREFTYPE_HASH
,-1,&hint
)) > 0)
925 recipient_digest_algo
=algo
;
929 for( sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
930 PKT_secret_key
*sk
= sk_rover
->sk
;
931 gcry_md_enable (mfx
.md
, hash_for(sk
));
935 iobuf_push_filter( inp
, md_filter
, &mfx
);
937 if( detached
&& !encryptflag
&& !RFC1991
)
940 if( opt
.armor
&& !outfile
)
941 push_armor_filter (afx
, out
);
944 efx
.pk_list
= pk_list
;
945 /* fixme: set efx.cfx.datalen if known */
946 iobuf_push_filter( out
, encrypt_filter
, &efx
);
949 if( opt
.compress_algo
&& !outfile
&& ( !detached
|| opt
.compress_sigs
) )
951 int compr_algo
=opt
.compress_algo
;
953 /* If not forced by user */
956 /* If we're not encrypting, then select_algo_from_prefs
957 will fail and we'll end up with the default. If we are
958 encrypting, select_algo_from_prefs cannot fail since
959 there is an assumed preference for uncompressed data.
960 Still, if it did fail, we'll also end up with the
964 select_algo_from_prefs(pk_list
,PREFTYPE_ZIP
,-1,NULL
))==-1)
965 compr_algo
=default_compress_algo();
967 else if(!opt
.expert
&& pk_list
968 && select_algo_from_prefs(pk_list
,PREFTYPE_ZIP
,
969 compr_algo
,NULL
)!=compr_algo
)
970 log_info(_("WARNING: forcing compression algorithm %s (%d)"
971 " violates recipient preferences\n"),
972 compress_algo_to_string(compr_algo
),compr_algo
);
974 /* algo 0 means no compression */
976 push_compress_filter(out
,&zfx
,compr_algo
);
979 /* Write the one-pass signature packets if needed */
980 if (!detached
&& !RFC1991
) {
981 rc
= write_onepass_sig_packets (sk_list
, out
,
982 opt
.textmode
&& !outfile
? 0x01:0x00);
987 write_status_begin_signing (mfx
.md
);
989 /* Setup the inner packet. */
995 log_info(_("signing:") );
996 /* must walk reverse trough this list */
997 for( sl
= strlist_last(filenames
); sl
;
998 sl
= strlist_prev( filenames
, sl
) ) {
999 inp
= iobuf_open(sl
->d
);
1000 if (inp
&& is_secured_file (iobuf_get_fd (inp
)))
1008 rc
= gpg_error_from_syserror ();
1009 log_error(_("can't open `%s': %s\n"),
1010 sl
->d
,strerror(errno
));
1013 handle_progress (pfx
, inp
, sl
->d
);
1015 fprintf(stderr
, " `%s'", sl
->d
);
1018 memset( &tfx
, 0, sizeof tfx
);
1019 iobuf_push_filter( inp
, text_filter
, &tfx
);
1021 iobuf_push_filter( inp
, md_filter
, &mfx
);
1022 while( iobuf_get(inp
) != -1 )
1024 iobuf_close(inp
); inp
= NULL
;
1027 putc( '\n', stderr
);
1030 /* read, so that the filter can calculate the digest */
1031 while( iobuf_get(inp
) != -1 )
1036 rc
= write_plaintext_packet (out
, inp
, fname
,
1037 opt
.textmode
&& !outfile
? 't':'b');
1040 /* catch errors from above */
1044 /* write the signatures */
1045 rc
= write_signature_packets (sk_list
, out
, mfx
.md
,
1046 opt
.textmode
&& !outfile
? 0x01 : 0x00,
1047 0, duration
, detached
? 'D':'S');
1058 write_status( STATUS_END_ENCRYPTION
);
1061 gcry_md_close ( mfx
.md
);
1062 release_sk_list( sk_list
);
1063 release_pk_list( pk_list
);
1064 recipient_digest_algo
=0;
1065 release_progress_context (pfx
);
1066 release_armor_context (afx
);
1073 * make a clear signature. note that opt.armor is not needed
1076 clearsign_file( const char *fname
, strlist_t locusr
, const char *outfile
)
1078 armor_filter_context_t
*afx
;
1079 progress_filter_context_t
*pfx
;
1080 gcry_md_hd_t textmd
= NULL
;
1081 IOBUF inp
= NULL
, out
= NULL
;
1084 SK_LIST sk_list
= NULL
;
1085 SK_LIST sk_rover
= NULL
;
1086 int old_style
= RFC1991
;
1090 pfx
= new_progress_context ();
1091 afx
= new_armor_context ();
1092 init_packet( &pkt
);
1094 if(!opt
.force_v3_sigs
&& !RFC1991
)
1096 if(opt
.ask_sig_expire
&& !opt
.batch
)
1097 duration
=ask_expire_interval(1,opt
.def_sig_expire
);
1099 duration
=parse_expire_string(opt
.def_sig_expire
);
1102 if( (rc
=build_sk_list( locusr
, &sk_list
, 1, PUBKEY_USAGE_SIG
)) )
1105 if( !old_style
&& !duration
)
1106 old_style
= only_old_style( sk_list
);
1108 if(PGP2
&& !only_old_style(sk_list
))
1110 log_info(_("you can only clearsign with PGP 2.x style keys "
1111 "while in --pgp2 mode\n"));
1112 compliance_failure();
1115 /* prepare iobufs */
1116 inp
= iobuf_open(fname
);
1117 if (inp
&& is_secured_file (iobuf_get_fd (inp
)))
1124 rc
= gpg_error_from_syserror ();
1125 log_error (_("can't open `%s': %s\n"),
1126 fname
? fname
: "[stdin]", strerror(errno
) );
1129 handle_progress (pfx
, inp
, fname
);
1132 if (is_secured_filename (outfile
) ) {
1137 out
= iobuf_create( outfile
);
1140 rc
= gpg_error_from_syserror ();
1141 log_error(_("can't create `%s': %s\n"), outfile
, strerror(errno
) );
1144 else if( opt
.verbose
)
1145 log_info(_("writing to `%s'\n"), outfile
);
1147 else if( (rc
= open_outfile( fname
, 1, &out
)) )
1150 iobuf_writestr(out
, "-----BEGIN PGP SIGNED MESSAGE-----" LF
);
1152 for( sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
1153 PKT_secret_key
*sk
= sk_rover
->sk
;
1154 if( hash_for(sk
) == DIGEST_ALGO_MD5
)
1162 if( !(old_style
&& only_md5
) ) {
1165 byte hashs_seen
[256];
1167 memset( hashs_seen
, 0, sizeof hashs_seen
);
1168 iobuf_writestr(out
, "Hash: " );
1169 for( sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
1170 PKT_secret_key
*sk
= sk_rover
->sk
;
1171 int i
= hash_for(sk
);
1173 if( !hashs_seen
[ i
& 0xff ] ) {
1174 s
= gcry_md_algo_name ( i
);
1176 hashs_seen
[ i
& 0xff ] = 1;
1178 iobuf_put(out
, ',' );
1179 iobuf_writestr(out
, s
);
1185 iobuf_writestr(out
, LF
);
1188 if( opt
.not_dash_escaped
)
1189 iobuf_writestr( out
,
1190 "NotDashEscaped: You need GnuPG to verify this message" LF
);
1191 iobuf_writestr(out
, LF
);
1193 if ( gcry_md_open (&textmd
, 0, 0) )
1195 for( sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
1196 PKT_secret_key
*sk
= sk_rover
->sk
;
1197 gcry_md_enable (textmd
, hash_for(sk
));
1200 gcry_md_start_debug ( textmd
, "clearsign" );
1202 copy_clearsig_text( out
, inp
, textmd
, !opt
.not_dash_escaped
,
1203 opt
.escape_from
, (old_style
&& only_md5
) );
1204 /* fixme: check for read errors */
1206 /* now write the armor */
1208 push_armor_filter (afx
, out
);
1210 /* write the signatures */
1211 rc
=write_signature_packets (sk_list
, out
, textmd
, 0x01, 0, duration
, 'C');
1221 gcry_md_close ( textmd
);
1222 release_sk_list( sk_list
);
1223 release_progress_context (pfx
);
1224 release_armor_context (afx
);
1229 * Sign and conventionally encrypt the given file.
1230 * FIXME: Far too much code is duplicated - revamp the whole file.
1233 sign_symencrypt_file (const char *fname
, strlist_t locusr
)
1235 armor_filter_context_t
*afx
;
1236 progress_filter_context_t
*pfx
;
1237 compress_filter_context_t zfx
;
1238 md_filter_context_t mfx
;
1239 text_filter_context_t tfx
;
1240 cipher_filter_context_t cfx
;
1241 IOBUF inp
= NULL
, out
= NULL
;
1243 STRING2KEY
*s2k
= NULL
;
1245 SK_LIST sk_list
= NULL
;
1246 SK_LIST sk_rover
= NULL
;
1251 pfx
= new_progress_context ();
1252 afx
= new_armor_context ();
1253 memset( &zfx
, 0, sizeof zfx
);
1254 memset( &mfx
, 0, sizeof mfx
);
1255 memset( &tfx
, 0, sizeof tfx
);
1256 memset( &cfx
, 0, sizeof cfx
);
1257 init_packet( &pkt
);
1259 if(!opt
.force_v3_sigs
&& !RFC1991
)
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
);
1267 rc
= build_sk_list (locusr
, &sk_list
, 1, PUBKEY_USAGE_SIG
);
1271 /* prepare iobufs */
1272 inp
= iobuf_open(fname
);
1273 if (inp
&& is_secured_file (iobuf_get_fd (inp
)))
1280 rc
= gpg_error_from_syserror ();
1281 log_error (_("can't open `%s': %s\n"),
1282 fname
? fname
: "[stdin]", strerror(errno
) );
1285 handle_progress (pfx
, inp
, fname
);
1288 s2k
= xmalloc_clear( sizeof *s2k
);
1289 s2k
->mode
= RFC1991
? 0:opt
.s2k_mode
;
1290 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
1292 algo
= default_cipher_algo();
1293 if (!opt
.quiet
|| !opt
.batch
)
1294 log_info (_("%s encryption will be used\n"),
1295 gcry_cipher_algo_name (algo
) );
1296 cfx
.dek
= passphrase_to_dek( NULL
, 0, algo
, s2k
, 2, NULL
, &canceled
);
1298 if (!cfx
.dek
|| !cfx
.dek
->keylen
) {
1299 rc
= gpg_error (canceled
?GPG_ERR_CANCELED
:GPG_ERR_BAD_PASSPHRASE
);
1300 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc
) );
1304 /* We have no way to tell if the recipient can handle messages
1305 with an MDC, so this defaults to no. Perhaps in a few years,
1306 this can be defaulted to yes. Note that like regular
1307 encrypting, --force-mdc overrides --disable-mdc. */
1311 /* now create the outfile */
1312 rc
= open_outfile (fname
, opt
.armor
? 1:0, &out
);
1316 /* prepare to calculate the MD over the input */
1318 iobuf_push_filter (inp
, text_filter
, &tfx
);
1319 if ( gcry_md_open (&mfx
.md
, 0, 0) )
1322 gcry_md_start_debug (mfx
.md
, "symc-sign");
1324 for (sk_rover
= sk_list
; sk_rover
; sk_rover
= sk_rover
->next
) {
1325 PKT_secret_key
*sk
= sk_rover
->sk
;
1326 gcry_md_enable (mfx
.md
, hash_for (sk
));
1329 iobuf_push_filter (inp
, md_filter
, &mfx
);
1331 /* Push armor output filter */
1333 push_armor_filter (afx
, out
);
1335 /* Write the symmetric key packet */
1336 /*(current filters: armor)*/
1338 PKT_symkey_enc
*enc
= xmalloc_clear( sizeof *enc
);
1340 enc
->cipher_algo
= cfx
.dek
->algo
;
1342 pkt
.pkttype
= PKT_SYMKEY_ENC
;
1343 pkt
.pkt
.symkey_enc
= enc
;
1344 if( (rc
= build_packet( out
, &pkt
)) )
1345 log_error("build symkey packet failed: %s\n", g10_errstr(rc
) );
1349 /* Push the encryption filter */
1350 iobuf_push_filter( out
, cipher_filter
, &cfx
);
1352 /* Push the compress filter */
1353 if (default_compress_algo())
1354 push_compress_filter(out
,&zfx
,default_compress_algo());
1356 /* Write the one-pass signature packets */
1357 /*(current filters: zip - encrypt - armor)*/
1359 rc
= write_onepass_sig_packets (sk_list
, out
,
1360 opt
.textmode
? 0x01:0x00);
1365 write_status_begin_signing (mfx
.md
);
1367 /* Pipe data through all filters; i.e. write the signed stuff */
1368 /*(current filters: zip - encrypt - armor)*/
1369 rc
= write_plaintext_packet (out
, inp
, fname
, opt
.textmode
? 't':'b');
1373 /* Write the signatures */
1374 /*(current filters: zip - encrypt - armor)*/
1375 rc
= write_signature_packets (sk_list
, out
, mfx
.md
,
1376 opt
.textmode
? 0x01 : 0x00,
1387 write_status( STATUS_END_ENCRYPTION
);
1390 release_sk_list( sk_list
);
1391 gcry_md_close( mfx
.md
);
1394 release_progress_context (pfx
);
1395 release_armor_context (afx
);
1401 * Create a signature packet for the given public key certificate and
1402 * the user id and return it in ret_sig. User signature class SIGCLASS
1403 * user-id is not used (and may be NULL if sigclass is 0x20) If
1404 * DIGEST_ALGO is 0 the function selects an appropriate one.
1405 * SIGVERSION gives the minimal required signature packet version;
1406 * this is needed so that special properties like local sign are not
1407 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1408 * the timestamp to use for the signature. 0 means "now" */
1410 make_keysig_packet( PKT_signature
**ret_sig
, PKT_public_key
*pk
,
1411 PKT_user_id
*uid
, PKT_public_key
*subpk
,
1413 int sigclass
, int digest_algo
,
1414 int sigversion
, u32 timestamp
, u32 duration
,
1415 int (*mksubpkt
)(PKT_signature
*, void *), void *opaque
1422 assert( (sigclass
>= 0x10 && sigclass
<= 0x13) || sigclass
== 0x1F
1423 || sigclass
== 0x20 || sigclass
== 0x18 || sigclass
== 0x19
1424 || sigclass
== 0x30 || sigclass
== 0x28 );
1426 if (opt
.force_v4_certs
)
1429 if (sigversion
< sk
->version
)
1430 sigversion
= sk
->version
;
1432 /* If you are making a signature on a v4 key using your v3 key, it
1433 doesn't make sense to generate a v3 sig. After all, no v3-only
1434 PGP implementation could understand the v4 key in the first
1435 place. Note that this implies that a signature on an attribute
1436 uid is usually going to be v4 as well, since they are not
1437 generally found on v3 keys. */
1438 if (sigversion
< pk
->version
)
1439 sigversion
= pk
->version
;
1443 /* Basically, this means use SHA1 always unless it's a v3 RSA
1444 key making a v3 cert (use MD5), or the user specified
1445 something (use whatever they said), or it's DSA (use the
1446 best match). They still can't pick an inappropriate hash
1447 for DSA or the signature will fail. Note that this still
1448 allows the caller of make_keysig_packet to override the
1449 user setting if it must. */
1451 if(opt
.cert_digest_algo
)
1452 digest_algo
=opt
.cert_digest_algo
;
1453 else if(sk
->pubkey_algo
==PUBKEY_ALGO_RSA
1454 && pk
->version
<4 && sigversion
<4)
1455 digest_algo
= DIGEST_ALGO_MD5
;
1456 else if(sk
->pubkey_algo
==PUBKEY_ALGO_DSA
)
1457 digest_algo
= match_dsa_hash (gcry_mpi_get_nbits (sk
->skey
[1])/8);
1459 digest_algo
= DIGEST_ALGO_SHA1
;
1462 if ( gcry_md_open (&md
, digest_algo
, 0 ) )
1465 /* Hash the public key certificate. */
1466 hash_public_key( md
, pk
);
1468 if( sigclass
== 0x18 || sigclass
== 0x19 || sigclass
== 0x28 )
1470 /* hash the subkey binding/backsig/revocation */
1471 hash_public_key( md
, subpk
);
1473 else if( sigclass
!= 0x1F && sigclass
!= 0x20 )
1475 /* hash the user id */
1476 hash_uid (md
, sigversion
, uid
);
1478 /* and make the signature packet */
1479 sig
= xmalloc_clear( sizeof *sig
);
1480 sig
->version
= sigversion
;
1481 sig
->flags
.exportable
=1;
1482 sig
->flags
.revocable
=1;
1483 keyid_from_sk( sk
, sig
->keyid
);
1484 sig
->pubkey_algo
= sk
->pubkey_algo
;
1485 sig
->digest_algo
= digest_algo
;
1487 sig
->timestamp
=timestamp
;
1489 sig
->timestamp
=make_timestamp();
1491 sig
->expiredate
=sig
->timestamp
+duration
;
1492 sig
->sig_class
= sigclass
;
1493 if( sig
->version
>= 4 )
1494 build_sig_subpkt_from_sig( sig
);
1495 mk_notation_policy_etc( sig
, pk
, sk
);
1497 /* Crucial that the call to mksubpkt comes LAST before the calls
1498 to finalize the sig as that makes it possible for the mksubpkt
1499 function to get a reliable pointer to the subpacket area. */
1500 if( sig
->version
>= 4 && mksubpkt
)
1501 rc
= (*mksubpkt
)( sig
, opaque
);
1504 hash_sigversion_to_magic (md
, sig
);
1507 rc
= complete_sig( sig
, sk
, md
);
1510 gcry_md_close ( md
);
1512 free_seckey_enc( sig
);
1521 * Create a new signature packet based on an existing one.
1522 * Only user ID signatures are supported for now.
1523 * TODO: Merge this with make_keysig_packet.
1526 update_keysig_packet( PKT_signature
**ret_sig
,
1527 PKT_signature
*orig_sig
,
1530 PKT_public_key
*subpk
,
1532 int (*mksubpkt
)(PKT_signature
*, void *),
1539 if ((!orig_sig
|| !pk
|| !sk
)
1540 || (orig_sig
->sig_class
>= 0x10 && orig_sig
->sig_class
<= 0x13 && !uid
)
1541 || (orig_sig
->sig_class
== 0x18 && !subpk
))
1542 return G10ERR_GENERAL
;
1544 if ( gcry_md_open (&md
, orig_sig
->digest_algo
, 0 ) )
1547 /* Hash the public key certificate and the user id. */
1548 hash_public_key( md
, pk
);
1550 if( orig_sig
->sig_class
== 0x18 )
1551 hash_public_key( md
, subpk
);
1553 hash_uid (md
, orig_sig
->version
, uid
);
1555 /* create a new signature packet */
1556 sig
= copy_signature (NULL
, orig_sig
);
1558 /* We need to create a new timestamp so that new sig expiration
1559 calculations are done correctly... */
1560 sig
->timestamp
=make_timestamp();
1562 /* ... but we won't make a timestamp earlier than the existing
1564 while(sig
->timestamp
<=orig_sig
->timestamp
)
1567 sig
->timestamp
=make_timestamp();
1570 /* Note that already expired sigs will remain expired (with a
1571 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1572 detects this case. */
1574 if( sig
->version
>= 4 )
1576 /* Put the updated timestamp into the sig. Note that this
1577 will automagically lower any sig expiration dates to
1578 correctly correspond to the differences in the timestamps
1579 (i.e. the duration will shrink). */
1580 build_sig_subpkt_from_sig( sig
);
1583 rc
= (*mksubpkt
)(sig
, opaque
);
1587 hash_sigversion_to_magic (md
, sig
);
1590 rc
= complete_sig( sig
, sk
, md
);
1595 free_seckey_enc (sig
);