2008-05-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / sign.c
blob022622b203bf5684adc24c710158a1d6d3a856a4
1 /* sign.c - sign data
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007 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/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "iobuf.h"
33 #include "keydb.h"
34 #include "util.h"
35 #include "main.h"
36 #include "filter.h"
37 #include "ttyio.h"
38 #include "trustdb.h"
39 #include "status.h"
40 #include "i18n.h"
41 #include "pkglue.h"
42 #include "sysutils.h"
43 #include "call-agent.h"
46 #ifdef HAVE_DOSISH_SYSTEM
47 #define LF "\r\n"
48 #else
49 #define LF "\n"
50 #endif
52 static int recipient_digest_algo=0;
54 /****************
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.
59 static void
60 mk_notation_policy_etc( PKT_signature *sig,
61 PKT_public_key *pk, PKT_secret_key *sk )
63 const char *string;
64 char *s=NULL;
65 strlist_t pu=NULL;
66 struct notation *nd=NULL;
67 struct expando_args args;
69 assert(sig->version>=4);
71 memset(&args,0,sizeof(args));
72 args.pk=pk;
73 args.sk=sk;
75 /* notation data */
76 if(IS_SIG(sig) && opt.sig_notations)
77 nd=opt.sig_notations;
78 else if( IS_CERT(sig) && opt.cert_notations )
79 nd=opt.cert_notations;
81 if(nd)
83 struct notation *i;
85 for(i=nd;i;i=i->next)
87 i->altvalue=pct_expando(i->value,&args);
88 if(!i->altvalue)
89 log_error(_("WARNING: unable to %%-expand notation "
90 "(too large). Using unexpanded.\n"));
93 keygen_add_notations(sig,nd);
95 for(i=nd;i;i=i->next)
97 xfree(i->altvalue);
98 i->altvalue=NULL;
102 /* set policy URL */
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;
108 for(;pu;pu=pu->next)
110 string = pu->d;
112 s=pct_expando(string,&args);
113 if(!s)
115 log_error(_("WARNING: unable to %%-expand policy URL "
116 "(too large). Using unexpanded.\n"));
117 s=xstrdup(string);
120 build_sig_subpkt(sig,SIGSUBPKT_POLICY|
121 ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
122 s,strlen(s));
124 xfree(s);
127 /* preferred keyserver URL */
128 if( IS_SIG(sig) && opt.sig_keyserver_url )
129 pu=opt.sig_keyserver_url;
131 for(;pu;pu=pu->next)
133 string = pu->d;
135 s=pct_expando(string,&args);
136 if(!s)
138 log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
139 " (too large). Using unexpanded.\n"));
140 s=xstrdup(string);
143 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS|
144 ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
145 s,strlen(s));
147 xfree(s);
153 * Helper to hash a user ID packet.
155 static void
156 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
158 if ( sigversion >= 4 ) {
159 byte buf[5];
161 if(uid->attrib_data) {
162 buf[0] = 0xd1; /* indicates an attribute packet */
163 buf[1] = uid->attrib_len >> 24; /* always use 4 length bytes */
164 buf[2] = uid->attrib_len >> 16;
165 buf[3] = uid->attrib_len >> 8;
166 buf[4] = uid->attrib_len;
168 else {
169 buf[0] = 0xb4; /* indicates a userid packet */
170 buf[1] = uid->len >> 24; /* always use 4 length bytes */
171 buf[2] = uid->len >> 16;
172 buf[3] = uid->len >> 8;
173 buf[4] = uid->len;
175 gcry_md_write( md, buf, 5 );
178 if(uid->attrib_data)
179 gcry_md_write (md, uid->attrib_data, uid->attrib_len );
180 else
181 gcry_md_write (md, uid->name, uid->len );
186 * Helper to hash some parts from the signature
188 static void
189 hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
191 if (sig->version >= 4)
192 gcry_md_putc (md, sig->version);
193 gcry_md_putc (md, sig->sig_class);
194 if (sig->version < 4) {
195 u32 a = sig->timestamp;
196 gcry_md_putc (md, (a >> 24) & 0xff );
197 gcry_md_putc (md, (a >> 16) & 0xff );
198 gcry_md_putc (md, (a >> 8) & 0xff );
199 gcry_md_putc (md, a & 0xff );
201 else {
202 byte buf[6];
203 size_t n;
205 gcry_md_putc (md, sig->pubkey_algo);
206 gcry_md_putc (md, sig->digest_algo);
207 if (sig->hashed) {
208 n = sig->hashed->len;
209 gcry_md_putc (md, (n >> 8) );
210 gcry_md_putc (md, n );
211 gcry_md_write (md, sig->hashed->data, n );
212 n += 6;
214 else {
215 gcry_md_putc (md, 0); /* always hash the length of the subpacket*/
216 gcry_md_putc (md, 0);
217 n = 6;
219 /* add some magic */
220 buf[0] = sig->version;
221 buf[1] = 0xff;
222 buf[2] = n >> 24; /* hmmm, n is only 16 bit, so this is always 0 */
223 buf[3] = n >> 16;
224 buf[4] = n >> 8;
225 buf[5] = n;
226 gcry_md_write (md, buf, 6);
231 static int
232 do_sign( PKT_secret_key *sk, PKT_signature *sig,
233 gcry_md_hd_t md, int digest_algo )
235 gcry_mpi_t frame;
236 byte *dp;
237 int rc;
239 if( sk->timestamp > sig->timestamp ) {
240 ulong d = sk->timestamp - sig->timestamp;
241 log_info( d==1 ? _("key has been created %lu second "
242 "in future (time warp or clock problem)\n")
243 : _("key has been created %lu seconds "
244 "in future (time warp or clock problem)\n"), d );
245 if( !opt.ignore_time_conflict )
246 return G10ERR_TIME_CONFLICT;
250 print_pubkey_algo_note(sk->pubkey_algo);
252 if( !digest_algo )
253 digest_algo = gcry_md_get_algo (md);
255 print_digest_algo_note( digest_algo );
256 dp = gcry_md_read ( md, digest_algo );
257 sig->digest_algo = digest_algo;
258 sig->digest_start[0] = dp[0];
259 sig->digest_start[1] = dp[1];
260 if (sk->is_protected && sk->protect.s2k.mode == 1002)
262 #ifdef ENABLE_CARD_SUPPORT
263 unsigned char *rbuf;
264 size_t rbuflen;
265 char *snbuf;
267 snbuf = serialno_and_fpr_from_sk (sk->protect.iv,
268 sk->protect.ivlen, sk);
269 rc = agent_scd_pksign (snbuf, digest_algo,
270 gcry_md_read (md, digest_algo),
271 gcry_md_get_algo_dlen (digest_algo),
272 &rbuf, &rbuflen);
273 xfree (snbuf);
274 if (!rc)
276 if (gcry_mpi_scan (&sig->data[0], GCRYMPI_FMT_USG,
277 rbuf, rbuflen, NULL))
278 BUG ();
279 xfree (rbuf);
281 #else
282 return gpg_error (GPG_ERR_NOT_SUPPORTED);
283 #endif /* ENABLE_CARD_SUPPORT */
285 else
287 frame = encode_md_value( NULL, sk, md, digest_algo );
288 if (!frame)
289 return G10ERR_GENERAL;
290 rc = pk_sign( sk->pubkey_algo, sig->data, frame, sk->skey );
291 gcry_mpi_release (frame);
294 if (!rc && !opt.no_sig_create_check) {
295 /* Check that the signature verification worked and nothing is
296 * fooling us e.g. by a bug in the signature create
297 * code or by deliberately introduced faults. */
298 PKT_public_key *pk = xmalloc_clear (sizeof *pk);
300 if( get_pubkey( pk, sig->keyid ) )
301 rc = G10ERR_NO_PUBKEY;
302 else {
303 frame = encode_md_value (pk, NULL, md, sig->digest_algo );
304 if (!frame)
305 rc = G10ERR_GENERAL;
306 else
307 rc = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey );
308 gcry_mpi_release (frame);
310 if (rc)
311 log_error (_("checking created signature failed: %s\n"),
312 g10_errstr (rc));
313 free_public_key (pk);
315 if( rc )
316 log_error(_("signing failed: %s\n"), g10_errstr(rc) );
317 else {
318 if( opt.verbose ) {
319 char *ustr = get_user_id_string_native (sig->keyid);
320 log_info(_("%s/%s signature from: \"%s\"\n"),
321 gcry_pk_algo_name (sk->pubkey_algo),
322 gcry_md_algo_name (sig->digest_algo),
323 ustr );
324 xfree(ustr);
327 return rc;
332 complete_sig( PKT_signature *sig, PKT_secret_key *sk, gcry_md_hd_t md )
334 int rc=0;
336 if( !(rc=check_secret_key( sk, 0 )) )
337 rc = do_sign( sk, sig, md, 0 );
338 return rc;
343 static int
344 match_dsa_hash (unsigned int qbytes)
346 if (qbytes <= 20)
347 return DIGEST_ALGO_SHA1;
349 /* SHA244 is only available with libgcrypt 1.4 - thus do a runtime
350 test. */
351 if (qbytes <= 28 && !gcry_md_test_algo (DIGEST_ALGO_SHA224))
352 return DIGEST_ALGO_SHA224;
354 if (qbytes <= 32)
355 return DIGEST_ALGO_SHA256;
357 if (qbytes <= 48)
358 return DIGEST_ALGO_SHA384;
360 if (qbytes <= 64)
361 return DIGEST_ALGO_SHA512;
363 return DEFAULT_DIGEST_ALGO;
364 /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
365 answer we have if a digest larger than 512 bits is requested. */
370 First try --digest-algo. If that isn't set, see if the recipient
371 has a preferred algorithm (which is also filtered through
372 --preferred-digest-prefs). If we're making a signature without a
373 particular recipient (i.e. signing, rather than signing+encrypting)
374 then take the first algorithm in --preferred-digest-prefs that is
375 usable for the pubkey algorithm. If --preferred-digest-prefs isn't
376 set, then take the OpenPGP default (i.e. SHA-1).
378 Possible improvement: Use the highest-ranked usable algorithm from
379 the signing key prefs either before or after using the personal
380 list?
382 static int
383 hash_for(PKT_secret_key *sk)
385 if( opt.def_digest_algo )
386 return opt.def_digest_algo;
387 else if( recipient_digest_algo )
388 return recipient_digest_algo;
389 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
391 unsigned int qbytes = gcry_mpi_get_nbits (sk->skey[1]) / 8;
393 /* It's a DSA key, so find a hash that is the same size as q or
394 larger. If q is 160, assume it is an old DSA key and use a
395 160-bit hash unless --enable-dsa2 is set, in which case act
396 like a new DSA key that just happens to have a 160-bit q
397 (i.e. allow truncation). If q is not 160, by definition it
398 must be a new DSA key. */
400 if (opt.personal_digest_prefs)
402 prefitem_t *prefs;
404 if (qbytes != 20 || opt.flags.dsa2)
406 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
407 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
408 return prefs->value;
410 else
412 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
413 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
414 return prefs->value;
418 return match_dsa_hash(qbytes);
420 else if (sk->is_protected && sk->protect.s2k.mode==1002)
422 /* The sk lives on a smartcard, and current smartcards only
423 handle SHA-1 and RIPEMD/160. This is correct now, but may
424 need revision as the cards add algorithms. */
426 if(opt.personal_digest_prefs)
428 prefitem_t *prefs;
430 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
431 if (prefs->value==DIGEST_ALGO_SHA1
432 || prefs->value==DIGEST_ALGO_RMD160)
433 return prefs->value;
436 return DIGEST_ALGO_SHA1;
438 else if (PGP2 && sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
440 /* Old-style PGP only understands MD5 */
441 return DIGEST_ALGO_MD5;
443 else if ( opt.personal_digest_prefs )
445 /* It's not DSA, so we can use whatever the first hash algorithm
446 is in the pref list */
447 return opt.personal_digest_prefs[0].value;
449 else
450 return DEFAULT_DIGEST_ALGO;
454 static int
455 only_old_style( SK_LIST sk_list )
457 SK_LIST sk_rover = NULL;
458 int old_style = 0;
460 /* if there are only old style capable key we use the old sytle */
461 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
462 PKT_secret_key *sk = sk_rover->sk;
463 if( sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
464 old_style = 1;
465 else
466 return 0;
468 return old_style;
473 static void
474 print_status_sig_created ( PKT_secret_key *sk, PKT_signature *sig, int what )
476 byte array[MAX_FINGERPRINT_LEN], *p;
477 char buf[100+MAX_FINGERPRINT_LEN*2];
478 size_t i, n;
480 sprintf(buf, "%c %d %d %02x %lu ",
481 what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
482 (ulong)sig->timestamp );
484 fingerprint_from_sk( sk, array, &n );
485 p = buf + strlen(buf);
486 for(i=0; i < n ; i++ )
487 sprintf(p+2*i, "%02X", array[i] );
489 write_status_text( STATUS_SIG_CREATED, buf );
494 * Loop over the secret certificates in SK_LIST and build the one pass
495 * signature packets. OpenPGP says that the data should be bracket by
496 * the onepass-sig and signature-packet; so we build these onepass
497 * packet here in reverse order
499 static int
500 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
502 int skcount;
503 SK_LIST sk_rover;
505 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
506 skcount++;
508 for (; skcount; skcount--) {
509 PKT_secret_key *sk;
510 PKT_onepass_sig *ops;
511 PACKET pkt;
512 int i, rc;
514 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
515 if (++i == skcount)
516 break;
519 sk = sk_rover->sk;
520 ops = xmalloc_clear (sizeof *ops);
521 ops->sig_class = sigclass;
522 ops->digest_algo = hash_for (sk);
523 ops->pubkey_algo = sk->pubkey_algo;
524 keyid_from_sk (sk, ops->keyid);
525 ops->last = (skcount == 1);
527 init_packet(&pkt);
528 pkt.pkttype = PKT_ONEPASS_SIG;
529 pkt.pkt.onepass_sig = ops;
530 rc = build_packet (out, &pkt);
531 free_packet (&pkt);
532 if (rc) {
533 log_error ("build onepass_sig packet failed: %s\n",
534 g10_errstr(rc));
535 return rc;
539 return 0;
543 * Helper to write the plaintext (literal data) packet
545 static int
546 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
548 PKT_plaintext *pt = NULL;
549 u32 filesize;
550 int rc = 0;
552 if (!opt.no_literal)
553 pt=setup_plaintext_name(fname,inp);
555 /* try to calculate the length of the data */
556 if ( !iobuf_is_pipe_filename (fname) && *fname )
558 off_t tmpsize;
559 int overflow;
561 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
562 && !overflow )
563 log_info (_("WARNING: `%s' is an empty file\n"), fname);
565 /* We can't encode the length of very large files because
566 OpenPGP uses only 32 bit for file sizes. So if the size of
567 a file is larger than 2^32 minus some bytes for packet
568 headers, we switch to partial length encoding. */
569 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
570 filesize = tmpsize;
571 else
572 filesize = 0;
574 /* Because the text_filter modifies the length of the
575 * data, it is not possible to know the used length
576 * without a double read of the file - to avoid that
577 * we simple use partial length packets. */
578 if ( ptmode == 't' )
579 filesize = 0;
581 else
582 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
584 if (!opt.no_literal) {
585 PACKET pkt;
587 pt->timestamp = make_timestamp ();
588 pt->mode = ptmode;
589 pt->len = filesize;
590 pt->new_ctb = !pt->len && !RFC1991;
591 pt->buf = inp;
592 init_packet(&pkt);
593 pkt.pkttype = PKT_PLAINTEXT;
594 pkt.pkt.plaintext = pt;
595 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
596 if( (rc = build_packet (out, &pkt)) )
597 log_error ("build_packet(PLAINTEXT) failed: %s\n",
598 g10_errstr(rc) );
599 pt->buf = NULL;
601 else {
602 byte copy_buffer[4096];
603 int bytes_copied;
605 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
606 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
607 log_error ("copying input to output failed: %s\n",
608 gpg_strerror (rc));
609 break;
611 wipememory(copy_buffer,4096); /* burn buffer */
613 /* fixme: it seems that we never freed pt/pkt */
615 return rc;
619 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
620 * hash which will not be changes here.
622 static int
623 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
624 int sigclass, u32 timestamp, u32 duration,
625 int status_letter)
627 SK_LIST sk_rover;
629 /* loop over the secret certificates */
630 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
631 PKT_secret_key *sk;
632 PKT_signature *sig;
633 gcry_md_hd_t md;
634 int rc;
636 sk = sk_rover->sk;
638 /* build the signature packet */
639 sig = xmalloc_clear (sizeof *sig);
640 if(opt.force_v3_sigs || RFC1991)
641 sig->version=3;
642 else if(duration || opt.sig_policy_url
643 || opt.sig_notations || opt.sig_keyserver_url)
644 sig->version=4;
645 else
646 sig->version=sk->version;
647 keyid_from_sk (sk, sig->keyid);
648 sig->digest_algo = hash_for(sk);
649 sig->pubkey_algo = sk->pubkey_algo;
650 if(timestamp)
651 sig->timestamp = timestamp;
652 else
653 sig->timestamp = make_timestamp();
654 if(duration)
655 sig->expiredate = sig->timestamp+duration;
656 sig->sig_class = sigclass;
658 if (gcry_md_copy (&md, hash))
659 BUG ();
661 if (sig->version >= 4)
663 build_sig_subpkt_from_sig (sig);
664 mk_notation_policy_etc (sig, NULL, sk);
667 hash_sigversion_to_magic (md, sig);
668 gcry_md_final (md);
670 rc = do_sign( sk, sig, md, hash_for (sk) );
671 gcry_md_close (md);
672 if( !rc ) { /* and write it */
673 PACKET pkt;
675 init_packet(&pkt);
676 pkt.pkttype = PKT_SIGNATURE;
677 pkt.pkt.signature = sig;
678 rc = build_packet (out, &pkt);
679 if (!rc && is_status_enabled()) {
680 print_status_sig_created ( sk, sig, status_letter);
682 free_packet (&pkt);
683 if (rc)
684 log_error ("build signature packet failed: %s\n",
685 g10_errstr(rc) );
687 if( rc )
688 return rc;;
691 return 0;
694 /****************
695 * Sign the files whose names are in FILENAME.
696 * If DETACHED has the value true,
697 * make a detached signature. If FILENAMES->d is NULL read from stdin
698 * and ignore the detached mode. Sign the file with all secret keys
699 * which can be taken from LOCUSR, if this is NULL, use the default one
700 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
701 * signed data for these users.
702 * If OUTFILE is not NULL; this file is used for output and the function
703 * does not ask for overwrite permission; output is then always
704 * uncompressed, non-armored and in binary mode.
707 sign_file( strlist_t filenames, int detached, strlist_t locusr,
708 int encryptflag, strlist_t remusr, const char *outfile )
710 const char *fname;
711 armor_filter_context_t *afx;
712 compress_filter_context_t zfx;
713 md_filter_context_t mfx;
714 text_filter_context_t tfx;
715 progress_filter_context_t *pfx;
716 encrypt_filter_context_t efx;
717 IOBUF inp = NULL, out = NULL;
718 PACKET pkt;
719 int rc = 0;
720 PK_LIST pk_list = NULL;
721 SK_LIST sk_list = NULL;
722 SK_LIST sk_rover = NULL;
723 int multifile = 0;
724 u32 duration=0;
726 pfx = new_progress_context ();
727 afx = new_armor_context ();
728 memset( &zfx, 0, sizeof zfx);
729 memset( &mfx, 0, sizeof mfx);
730 memset( &efx, 0, sizeof efx);
731 init_packet( &pkt );
733 if( filenames ) {
734 fname = filenames->d;
735 multifile = !!filenames->next;
737 else
738 fname = NULL;
740 if( fname && filenames->next && (!detached || encryptflag) )
741 log_bug("multiple files can only be detached signed");
743 if(encryptflag==2
744 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
745 goto leave;
747 if(!opt.force_v3_sigs && !RFC1991)
749 if(opt.ask_sig_expire && !opt.batch)
750 duration=ask_expire_interval(1,opt.def_sig_expire);
751 else
752 duration=parse_expire_string(opt.def_sig_expire);
755 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
756 goto leave;
758 if(PGP2 && !only_old_style(sk_list))
760 log_info(_("you can only detach-sign with PGP 2.x style keys "
761 "while in --pgp2 mode\n"));
762 compliance_failure();
765 if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC )))
766 goto leave;
768 /* prepare iobufs */
769 if( multifile ) /* have list of filenames */
770 inp = NULL; /* we do it later */
771 else {
772 inp = iobuf_open(fname);
773 if (inp && is_secured_file (iobuf_get_fd (inp)))
775 iobuf_close (inp);
776 inp = NULL;
777 errno = EPERM;
779 if( !inp )
781 rc = gpg_error_from_syserror ();
782 log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
783 strerror(errno) );
784 goto leave;
787 handle_progress (pfx, inp, fname);
790 if( outfile ) {
791 if (is_secured_filename ( outfile )) {
792 out = NULL;
793 errno = EPERM;
795 else
796 out = iobuf_create( outfile );
797 if( !out )
799 rc = gpg_error_from_syserror ();
800 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
801 goto leave;
803 else if( opt.verbose )
804 log_info(_("writing to `%s'\n"), outfile );
806 else if( (rc = open_outfile( fname, opt.armor? 1: detached? 2:0, &out )))
807 goto leave;
809 /* prepare to calculate the MD over the input */
810 if( opt.textmode && !outfile && !multifile )
812 memset( &tfx, 0, sizeof tfx);
813 iobuf_push_filter( inp, text_filter, &tfx );
816 if ( gcry_md_open (&mfx.md, 0, 0) )
817 BUG ();
818 if (DBG_HASHING)
819 gcry_md_start_debug (mfx.md, "sign");
821 /* If we're encrypting and signing, it is reasonable to pick the
822 hash algorithm to use out of the recepient key prefs. This is
823 best effort only, as in a DSA2 and smartcard world there are
824 cases where we cannot please everyone with a single hash (DSA2
825 wants >160 and smartcards want =160). In the future this could
826 be more complex with different hashes for each sk, but the
827 current design requires a single hash for all SKs. */
828 if(pk_list)
830 if(opt.def_digest_algo)
832 if(!opt.expert &&
833 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
834 opt.def_digest_algo,
835 NULL)!=opt.def_digest_algo)
836 log_info(_("WARNING: forcing digest algorithm %s (%d)"
837 " violates recipient preferences\n"),
838 gcry_md_algo_name (opt.def_digest_algo),
839 opt.def_digest_algo );
841 else
843 int algo, smartcard=0;
844 union pref_hint hint;
846 hint.digest_length = 0;
848 /* Of course, if the recipient asks for something
849 unreasonable (like the wrong hash for a DSA key) then
850 don't do it. Check all sk's - if any are DSA or live
851 on a smartcard, then the hash has restrictions and we
852 may not be able to give the recipient what they want.
853 For DSA, pass a hint for the largest q we have. Note
854 that this means that a q>160 key will override a q=160
855 key and force the use of truncation for the q=160 key.
856 The alternative would be to ignore the recipient prefs
857 completely and get a different hash for each DSA key in
858 hash_for(). The override behavior here is more or less
859 reasonable as it is under the control of the user which
860 keys they sign with for a given message and the fact
861 that the message with multiple signatures won't be
862 usable on an implementation that doesn't understand
863 DSA2 anyway. */
865 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
867 if (sk_rover->sk->pubkey_algo == PUBKEY_ALGO_DSA)
869 int temp_hashlen = gcry_mpi_get_nbits
870 (sk_rover->sk->skey[1])+7/8;
872 /* Pick a hash that is large enough for our
873 largest q */
875 if (hint.digest_length<temp_hashlen)
876 hint.digest_length=temp_hashlen;
878 else if (sk_rover->sk->is_protected
879 && sk_rover->sk->protect.s2k.mode == 1002)
880 smartcard = 1;
883 /* Current smartcards only do 160-bit hashes. If we have
884 to have a >160-bit hash, then we can't use the
885 recipient prefs as we'd need both =160 and >160 at the
886 same time and recipient prefs currently require a
887 single hash for all signatures. All this may well have
888 to change as the cards add algorithms. */
890 if (!smartcard || (smartcard && hint.digest_length==20))
891 if ( (algo=
892 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
893 recipient_digest_algo=algo;
897 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
898 PKT_secret_key *sk = sk_rover->sk;
899 gcry_md_enable (mfx.md, hash_for(sk));
902 if( !multifile )
903 iobuf_push_filter( inp, md_filter, &mfx );
905 if( detached && !encryptflag && !RFC1991 )
906 afx->what = 2;
908 if( opt.armor && !outfile )
909 push_armor_filter (afx, out);
911 if( encryptflag ) {
912 efx.pk_list = pk_list;
913 /* fixme: set efx.cfx.datalen if known */
914 iobuf_push_filter( out, encrypt_filter, &efx );
917 if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) )
919 int compr_algo=opt.compress_algo;
921 /* If not forced by user */
922 if(compr_algo==-1)
924 /* If we're not encrypting, then select_algo_from_prefs
925 will fail and we'll end up with the default. If we are
926 encrypting, select_algo_from_prefs cannot fail since
927 there is an assumed preference for uncompressed data.
928 Still, if it did fail, we'll also end up with the
929 default. */
931 if((compr_algo=
932 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
933 compr_algo=default_compress_algo();
935 else if(!opt.expert && pk_list
936 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
937 compr_algo,NULL)!=compr_algo)
938 log_info(_("WARNING: forcing compression algorithm %s (%d)"
939 " violates recipient preferences\n"),
940 compress_algo_to_string(compr_algo),compr_algo);
942 /* algo 0 means no compression */
943 if( compr_algo )
944 push_compress_filter(out,&zfx,compr_algo);
947 /* Write the one-pass signature packets if needed */
948 if (!detached && !RFC1991) {
949 rc = write_onepass_sig_packets (sk_list, out,
950 opt.textmode && !outfile ? 0x01:0x00);
951 if (rc)
952 goto leave;
955 write_status_begin_signing (mfx.md);
957 /* Setup the inner packet. */
958 if( detached ) {
959 if( multifile ) {
960 strlist_t sl;
962 if( opt.verbose )
963 log_info(_("signing:") );
964 /* must walk reverse trough this list */
965 for( sl = strlist_last(filenames); sl;
966 sl = strlist_prev( filenames, sl ) ) {
967 inp = iobuf_open(sl->d);
968 if (inp && is_secured_file (iobuf_get_fd (inp)))
970 iobuf_close (inp);
971 inp = NULL;
972 errno = EPERM;
974 if( !inp )
976 rc = gpg_error_from_syserror ();
977 log_error(_("can't open `%s': %s\n"),
978 sl->d,strerror(errno));
979 goto leave;
981 handle_progress (pfx, inp, sl->d);
982 if( opt.verbose )
983 fprintf(stderr, " `%s'", sl->d );
984 if(opt.textmode)
986 memset( &tfx, 0, sizeof tfx);
987 iobuf_push_filter( inp, text_filter, &tfx );
989 iobuf_push_filter( inp, md_filter, &mfx );
990 while( iobuf_get(inp) != -1 )
992 iobuf_close(inp); inp = NULL;
994 if( opt.verbose )
995 putc( '\n', stderr );
997 else {
998 /* read, so that the filter can calculate the digest */
999 while( iobuf_get(inp) != -1 )
1003 else {
1004 rc = write_plaintext_packet (out, inp, fname,
1005 opt.textmode && !outfile ? 't':'b');
1008 /* catch errors from above */
1009 if (rc)
1010 goto leave;
1012 /* write the signatures */
1013 rc = write_signature_packets (sk_list, out, mfx.md,
1014 opt.textmode && !outfile? 0x01 : 0x00,
1015 0, duration, detached ? 'D':'S');
1016 if( rc )
1017 goto leave;
1020 leave:
1021 if( rc )
1022 iobuf_cancel(out);
1023 else {
1024 iobuf_close(out);
1025 if (encryptflag)
1026 write_status( STATUS_END_ENCRYPTION );
1028 iobuf_close(inp);
1029 gcry_md_close ( mfx.md );
1030 release_sk_list( sk_list );
1031 release_pk_list( pk_list );
1032 recipient_digest_algo=0;
1033 release_progress_context (pfx);
1034 release_armor_context (afx);
1035 return rc;
1040 /****************
1041 * make a clear signature. note that opt.armor is not needed
1044 clearsign_file( const char *fname, strlist_t locusr, const char *outfile )
1046 armor_filter_context_t *afx;
1047 progress_filter_context_t *pfx;
1048 gcry_md_hd_t textmd = NULL;
1049 IOBUF inp = NULL, out = NULL;
1050 PACKET pkt;
1051 int rc = 0;
1052 SK_LIST sk_list = NULL;
1053 SK_LIST sk_rover = NULL;
1054 int old_style = RFC1991;
1055 int only_md5 = 0;
1056 u32 duration=0;
1058 pfx = new_progress_context ();
1059 afx = new_armor_context ();
1060 init_packet( &pkt );
1062 if(!opt.force_v3_sigs && !RFC1991)
1064 if(opt.ask_sig_expire && !opt.batch)
1065 duration=ask_expire_interval(1,opt.def_sig_expire);
1066 else
1067 duration=parse_expire_string(opt.def_sig_expire);
1070 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
1071 goto leave;
1073 if( !old_style && !duration )
1074 old_style = only_old_style( sk_list );
1076 if(PGP2 && !only_old_style(sk_list))
1078 log_info(_("you can only clearsign with PGP 2.x style keys "
1079 "while in --pgp2 mode\n"));
1080 compliance_failure();
1083 /* prepare iobufs */
1084 inp = iobuf_open(fname);
1085 if (inp && is_secured_file (iobuf_get_fd (inp)))
1087 iobuf_close (inp);
1088 inp = NULL;
1089 errno = EPERM;
1091 if( !inp ) {
1092 rc = gpg_error_from_syserror ();
1093 log_error (_("can't open `%s': %s\n"),
1094 fname? fname: "[stdin]", strerror(errno) );
1095 goto leave;
1097 handle_progress (pfx, inp, fname);
1099 if( outfile ) {
1100 if (is_secured_filename (outfile) ) {
1101 outfile = NULL;
1102 errno = EPERM;
1104 else
1105 out = iobuf_create( outfile );
1106 if( !out )
1108 rc = gpg_error_from_syserror ();
1109 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
1110 goto leave;
1112 else if( opt.verbose )
1113 log_info(_("writing to `%s'\n"), outfile );
1115 else if( (rc = open_outfile( fname, 1, &out )) )
1116 goto leave;
1118 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1120 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1121 PKT_secret_key *sk = sk_rover->sk;
1122 if( hash_for(sk) == DIGEST_ALGO_MD5 )
1123 only_md5 = 1;
1124 else {
1125 only_md5 = 0;
1126 break;
1130 if( !(old_style && only_md5) ) {
1131 const char *s;
1132 int any = 0;
1133 byte hashs_seen[256];
1135 memset( hashs_seen, 0, sizeof hashs_seen );
1136 iobuf_writestr(out, "Hash: " );
1137 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1138 PKT_secret_key *sk = sk_rover->sk;
1139 int i = hash_for(sk);
1141 if( !hashs_seen[ i & 0xff ] ) {
1142 s = gcry_md_algo_name ( i );
1143 if( s ) {
1144 hashs_seen[ i & 0xff ] = 1;
1145 if( any )
1146 iobuf_put(out, ',' );
1147 iobuf_writestr(out, s );
1148 any = 1;
1152 assert(any);
1153 iobuf_writestr(out, LF );
1156 if( opt.not_dash_escaped )
1157 iobuf_writestr( out,
1158 "NotDashEscaped: You need GnuPG to verify this message" LF );
1159 iobuf_writestr(out, LF );
1161 if ( gcry_md_open (&textmd, 0, 0) )
1162 BUG ();
1163 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1164 PKT_secret_key *sk = sk_rover->sk;
1165 gcry_md_enable (textmd, hash_for(sk));
1167 if ( DBG_HASHING )
1168 gcry_md_start_debug ( textmd, "clearsign" );
1170 copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
1171 opt.escape_from, (old_style && only_md5) );
1172 /* fixme: check for read errors */
1174 /* now write the armor */
1175 afx->what = 2;
1176 push_armor_filter (afx, out);
1178 /* write the signatures */
1179 rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
1180 if( rc )
1181 goto leave;
1183 leave:
1184 if( rc )
1185 iobuf_cancel(out);
1186 else
1187 iobuf_close(out);
1188 iobuf_close(inp);
1189 gcry_md_close ( textmd );
1190 release_sk_list( sk_list );
1191 release_progress_context (pfx);
1192 release_armor_context (afx);
1193 return rc;
1197 * Sign and conventionally encrypt the given file.
1198 * FIXME: Far too much code is duplicated - revamp the whole file.
1201 sign_symencrypt_file (const char *fname, strlist_t locusr)
1203 armor_filter_context_t *afx;
1204 progress_filter_context_t *pfx;
1205 compress_filter_context_t zfx;
1206 md_filter_context_t mfx;
1207 text_filter_context_t tfx;
1208 cipher_filter_context_t cfx;
1209 IOBUF inp = NULL, out = NULL;
1210 PACKET pkt;
1211 STRING2KEY *s2k = NULL;
1212 int rc = 0;
1213 SK_LIST sk_list = NULL;
1214 SK_LIST sk_rover = NULL;
1215 int algo;
1216 u32 duration=0;
1217 int canceled;
1219 pfx = new_progress_context ();
1220 afx = new_armor_context ();
1221 memset( &zfx, 0, sizeof zfx);
1222 memset( &mfx, 0, sizeof mfx);
1223 memset( &tfx, 0, sizeof tfx);
1224 memset( &cfx, 0, sizeof cfx);
1225 init_packet( &pkt );
1227 if(!opt.force_v3_sigs && !RFC1991)
1229 if(opt.ask_sig_expire && !opt.batch)
1230 duration=ask_expire_interval(1,opt.def_sig_expire);
1231 else
1232 duration=parse_expire_string(opt.def_sig_expire);
1235 rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
1236 if (rc)
1237 goto leave;
1239 /* prepare iobufs */
1240 inp = iobuf_open(fname);
1241 if (inp && is_secured_file (iobuf_get_fd (inp)))
1243 iobuf_close (inp);
1244 inp = NULL;
1245 errno = EPERM;
1247 if( !inp ) {
1248 rc = gpg_error_from_syserror ();
1249 log_error (_("can't open `%s': %s\n"),
1250 fname? fname: "[stdin]", strerror(errno) );
1251 goto leave;
1253 handle_progress (pfx, inp, fname);
1255 /* prepare key */
1256 s2k = xmalloc_clear( sizeof *s2k );
1257 s2k->mode = RFC1991? 0:opt.s2k_mode;
1258 s2k->hash_algo = S2K_DIGEST_ALGO;
1260 algo = default_cipher_algo();
1261 if (!opt.quiet || !opt.batch)
1262 log_info (_("%s encryption will be used\n"),
1263 openpgp_cipher_algo_name (algo) );
1264 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
1266 if (!cfx.dek || !cfx.dek->keylen) {
1267 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1268 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1269 goto leave;
1272 /* We have no way to tell if the recipient can handle messages
1273 with an MDC, so this defaults to no. Perhaps in a few years,
1274 this can be defaulted to yes. Note that like regular
1275 encrypting, --force-mdc overrides --disable-mdc. */
1276 if(opt.force_mdc)
1277 cfx.dek->use_mdc=1;
1279 /* now create the outfile */
1280 rc = open_outfile (fname, opt.armor? 1:0, &out);
1281 if (rc)
1282 goto leave;
1284 /* prepare to calculate the MD over the input */
1285 if (opt.textmode)
1286 iobuf_push_filter (inp, text_filter, &tfx);
1287 if ( gcry_md_open (&mfx.md, 0, 0) )
1288 BUG ();
1289 if ( DBG_HASHING )
1290 gcry_md_start_debug (mfx.md, "symc-sign");
1292 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
1293 PKT_secret_key *sk = sk_rover->sk;
1294 gcry_md_enable (mfx.md, hash_for (sk));
1297 iobuf_push_filter (inp, md_filter, &mfx);
1299 /* Push armor output filter */
1300 if (opt.armor)
1301 push_armor_filter (afx, out);
1303 /* Write the symmetric key packet */
1304 /*(current filters: armor)*/
1305 if (!RFC1991) {
1306 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1307 enc->version = 4;
1308 enc->cipher_algo = cfx.dek->algo;
1309 enc->s2k = *s2k;
1310 pkt.pkttype = PKT_SYMKEY_ENC;
1311 pkt.pkt.symkey_enc = enc;
1312 if( (rc = build_packet( out, &pkt )) )
1313 log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
1314 xfree(enc);
1317 /* Push the encryption filter */
1318 iobuf_push_filter( out, cipher_filter, &cfx );
1320 /* Push the compress filter */
1321 if (default_compress_algo())
1322 push_compress_filter(out,&zfx,default_compress_algo());
1324 /* Write the one-pass signature packets */
1325 /*(current filters: zip - encrypt - armor)*/
1326 if (!RFC1991) {
1327 rc = write_onepass_sig_packets (sk_list, out,
1328 opt.textmode? 0x01:0x00);
1329 if (rc)
1330 goto leave;
1333 write_status_begin_signing (mfx.md);
1335 /* Pipe data through all filters; i.e. write the signed stuff */
1336 /*(current filters: zip - encrypt - armor)*/
1337 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1338 if (rc)
1339 goto leave;
1341 /* Write the signatures */
1342 /*(current filters: zip - encrypt - armor)*/
1343 rc = write_signature_packets (sk_list, out, mfx.md,
1344 opt.textmode? 0x01 : 0x00,
1345 0, duration, 'S');
1346 if( rc )
1347 goto leave;
1350 leave:
1351 if( rc )
1352 iobuf_cancel(out);
1353 else {
1354 iobuf_close(out);
1355 write_status( STATUS_END_ENCRYPTION );
1357 iobuf_close(inp);
1358 release_sk_list( sk_list );
1359 gcry_md_close( mfx.md );
1360 xfree(cfx.dek);
1361 xfree(s2k);
1362 release_progress_context (pfx);
1363 release_armor_context (afx);
1364 return rc;
1368 /****************
1369 * Create a signature packet for the given public key certificate and
1370 * the user id and return it in ret_sig. User signature class SIGCLASS
1371 * user-id is not used (and may be NULL if sigclass is 0x20) If
1372 * DIGEST_ALGO is 0 the function selects an appropriate one.
1373 * SIGVERSION gives the minimal required signature packet version;
1374 * this is needed so that special properties like local sign are not
1375 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1376 * the timestamp to use for the signature. 0 means "now" */
1378 make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
1379 PKT_user_id *uid, PKT_public_key *subpk,
1380 PKT_secret_key *sk,
1381 int sigclass, int digest_algo,
1382 int sigversion, u32 timestamp, u32 duration,
1383 int (*mksubpkt)(PKT_signature *, void *), void *opaque
1386 PKT_signature *sig;
1387 int rc=0;
1388 gcry_md_hd_t md;
1390 assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1391 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1392 || sigclass == 0x30 || sigclass == 0x28 );
1394 if (opt.force_v4_certs)
1395 sigversion = 4;
1397 if (sigversion < sk->version)
1398 sigversion = sk->version;
1400 /* If you are making a signature on a v4 key using your v3 key, it
1401 doesn't make sense to generate a v3 sig. After all, no v3-only
1402 PGP implementation could understand the v4 key in the first
1403 place. Note that this implies that a signature on an attribute
1404 uid is usually going to be v4 as well, since they are not
1405 generally found on v3 keys. */
1406 if (sigversion < pk->version)
1407 sigversion = pk->version;
1409 if( !digest_algo )
1411 /* Basically, this means use SHA1 always unless it's a v3 RSA
1412 key making a v3 cert (use MD5), or the user specified
1413 something (use whatever they said), or it's DSA (use the
1414 best match). They still can't pick an inappropriate hash
1415 for DSA or the signature will fail. Note that this still
1416 allows the caller of make_keysig_packet to override the
1417 user setting if it must. */
1419 if(opt.cert_digest_algo)
1420 digest_algo=opt.cert_digest_algo;
1421 else if(sk->pubkey_algo==PUBKEY_ALGO_RSA
1422 && pk->version<4 && sigversion<4)
1423 digest_algo = DIGEST_ALGO_MD5;
1424 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
1425 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (sk->skey[1])/8);
1426 else
1427 digest_algo = DIGEST_ALGO_SHA1;
1430 if ( gcry_md_open (&md, digest_algo, 0 ) )
1431 BUG ();
1433 /* Hash the public key certificate. */
1434 hash_public_key( md, pk );
1436 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1438 /* hash the subkey binding/backsig/revocation */
1439 hash_public_key( md, subpk );
1441 else if( sigclass != 0x1F && sigclass != 0x20 )
1443 /* hash the user id */
1444 hash_uid (md, sigversion, uid);
1446 /* and make the signature packet */
1447 sig = xmalloc_clear( sizeof *sig );
1448 sig->version = sigversion;
1449 sig->flags.exportable=1;
1450 sig->flags.revocable=1;
1451 keyid_from_sk( sk, sig->keyid );
1452 sig->pubkey_algo = sk->pubkey_algo;
1453 sig->digest_algo = digest_algo;
1454 if(timestamp)
1455 sig->timestamp=timestamp;
1456 else
1457 sig->timestamp=make_timestamp();
1458 if(duration)
1459 sig->expiredate=sig->timestamp+duration;
1460 sig->sig_class = sigclass;
1461 if( sig->version >= 4 )
1463 build_sig_subpkt_from_sig( sig );
1464 mk_notation_policy_etc( sig, pk, sk );
1467 /* Crucial that the call to mksubpkt comes LAST before the calls
1468 to finalize the sig as that makes it possible for the mksubpkt
1469 function to get a reliable pointer to the subpacket area. */
1470 if( sig->version >= 4 && mksubpkt )
1471 rc = (*mksubpkt)( sig, opaque );
1473 if( !rc ) {
1474 hash_sigversion_to_magic (md, sig);
1475 gcry_md_final (md);
1477 rc = complete_sig( sig, sk, md );
1480 gcry_md_close ( md );
1481 if( rc )
1482 free_seckey_enc( sig );
1483 else
1484 *ret_sig = sig;
1485 return rc;
1490 /****************
1491 * Create a new signature packet based on an existing one.
1492 * Only user ID signatures are supported for now.
1493 * TODO: Merge this with make_keysig_packet.
1496 update_keysig_packet( PKT_signature **ret_sig,
1497 PKT_signature *orig_sig,
1498 PKT_public_key *pk,
1499 PKT_user_id *uid,
1500 PKT_public_key *subpk,
1501 PKT_secret_key *sk,
1502 int (*mksubpkt)(PKT_signature *, void *),
1503 void *opaque )
1505 PKT_signature *sig;
1506 int rc=0;
1507 gcry_md_hd_t md;
1509 if ((!orig_sig || !pk || !sk)
1510 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1511 || (orig_sig->sig_class == 0x18 && !subpk))
1512 return G10ERR_GENERAL;
1514 if ( gcry_md_open (&md, orig_sig->digest_algo, 0 ) )
1515 BUG ();
1517 /* Hash the public key certificate and the user id. */
1518 hash_public_key( md, pk );
1520 if( orig_sig->sig_class == 0x18 )
1521 hash_public_key( md, subpk );
1522 else
1523 hash_uid (md, orig_sig->version, uid);
1525 /* create a new signature packet */
1526 sig = copy_signature (NULL, orig_sig);
1528 /* We need to create a new timestamp so that new sig expiration
1529 calculations are done correctly... */
1530 sig->timestamp=make_timestamp();
1532 /* ... but we won't make a timestamp earlier than the existing
1533 one. */
1534 while(sig->timestamp<=orig_sig->timestamp)
1536 gnupg_sleep (1);
1537 sig->timestamp=make_timestamp();
1540 /* Note that already expired sigs will remain expired (with a
1541 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1542 detects this case. */
1544 if( sig->version >= 4 )
1546 /* Put the updated timestamp into the sig. Note that this
1547 will automagically lower any sig expiration dates to
1548 correctly correspond to the differences in the timestamps
1549 (i.e. the duration will shrink). */
1550 build_sig_subpkt_from_sig( sig );
1552 if (mksubpkt)
1553 rc = (*mksubpkt)(sig, opaque);
1556 if (!rc) {
1557 hash_sigversion_to_magic (md, sig);
1558 gcry_md_final (md);
1560 rc = complete_sig( sig, sk, md );
1563 gcry_md_close (md);
1564 if( rc )
1565 free_seckey_enc (sig);
1566 else
1567 *ret_sig = sig;
1568 return rc;