Fixed EOF detection for encrypted packets.
[gnupg.git] / g10 / sign.c
blob92617a98160ffa4e238c69af3922f6ff71e49bc0
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 if (qbytes <= 28)
350 return DIGEST_ALGO_SHA224;
352 if (qbytes <= 32)
353 return DIGEST_ALGO_SHA256;
355 if (qbytes <= 48)
356 return DIGEST_ALGO_SHA384;
358 if (qbytes <= 64)
359 return DIGEST_ALGO_SHA512;
361 return DEFAULT_DIGEST_ALGO;
362 /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
363 answer we have if a digest larger than 512 bits is requested. */
368 First try --digest-algo. If that isn't set, see if the recipient
369 has a preferred algorithm (which is also filtered through
370 --preferred-digest-prefs). If we're making a signature without a
371 particular recipient (i.e. signing, rather than signing+encrypting)
372 then take the first algorithm in --preferred-digest-prefs that is
373 usable for the pubkey algorithm. If --preferred-digest-prefs isn't
374 set, then take the OpenPGP default (i.e. SHA-1).
376 Possible improvement: Use the highest-ranked usable algorithm from
377 the signing key prefs either before or after using the personal
378 list?
380 static int
381 hash_for(PKT_secret_key *sk)
383 if( opt.def_digest_algo )
384 return opt.def_digest_algo;
385 else if( recipient_digest_algo )
386 return recipient_digest_algo;
387 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
389 unsigned int qbytes = gcry_mpi_get_nbits (sk->skey[1]) / 8;
391 /* It's a DSA key, so find a hash that is the same size as q or
392 larger. If q is 160, assume it is an old DSA key and use a
393 160-bit hash unless --enable-dsa2 is set, in which case act
394 like a new DSA key that just happens to have a 160-bit q
395 (i.e. allow truncation). If q is not 160, by definition it
396 must be a new DSA key. */
398 if (opt.personal_digest_prefs)
400 prefitem_t *prefs;
402 if (qbytes != 20 || opt.flags.dsa2)
404 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
405 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
406 return prefs->value;
408 else
410 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
411 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
412 return prefs->value;
416 return match_dsa_hash(qbytes);
418 else if (sk->is_protected && sk->protect.s2k.mode==1002)
420 /* The sk lives on a smartcard, and current smartcards only
421 handle SHA-1 and RIPEMD/160. This is correct now, but may
422 need revision as the cards add algorithms. */
424 if(opt.personal_digest_prefs)
426 prefitem_t *prefs;
428 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
429 if (prefs->value==DIGEST_ALGO_SHA1
430 || prefs->value==DIGEST_ALGO_RMD160)
431 return prefs->value;
434 return DIGEST_ALGO_SHA1;
436 else if (PGP2 && sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
438 /* Old-style PGP only understands MD5 */
439 return DIGEST_ALGO_MD5;
441 else if ( opt.personal_digest_prefs )
443 /* It's not DSA, so we can use whatever the first hash algorithm
444 is in the pref list */
445 return opt.personal_digest_prefs[0].value;
447 else
448 return DEFAULT_DIGEST_ALGO;
452 static int
453 only_old_style( SK_LIST sk_list )
455 SK_LIST sk_rover = NULL;
456 int old_style = 0;
458 /* if there are only old style capable key we use the old sytle */
459 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
460 PKT_secret_key *sk = sk_rover->sk;
461 if( sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
462 old_style = 1;
463 else
464 return 0;
466 return old_style;
471 static void
472 print_status_sig_created ( PKT_secret_key *sk, PKT_signature *sig, int what )
474 byte array[MAX_FINGERPRINT_LEN], *p;
475 char buf[100+MAX_FINGERPRINT_LEN*2];
476 size_t i, n;
478 sprintf(buf, "%c %d %d %02x %lu ",
479 what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
480 (ulong)sig->timestamp );
482 fingerprint_from_sk( sk, array, &n );
483 p = buf + strlen(buf);
484 for(i=0; i < n ; i++ )
485 sprintf(p+2*i, "%02X", array[i] );
487 write_status_text( STATUS_SIG_CREATED, buf );
492 * Loop over the secret certificates in SK_LIST and build the one pass
493 * signature packets. OpenPGP says that the data should be bracket by
494 * the onepass-sig and signature-packet; so we build these onepass
495 * packet here in reverse order
497 static int
498 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
500 int skcount;
501 SK_LIST sk_rover;
503 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
504 skcount++;
506 for (; skcount; skcount--) {
507 PKT_secret_key *sk;
508 PKT_onepass_sig *ops;
509 PACKET pkt;
510 int i, rc;
512 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
513 if (++i == skcount)
514 break;
517 sk = sk_rover->sk;
518 ops = xmalloc_clear (sizeof *ops);
519 ops->sig_class = sigclass;
520 ops->digest_algo = hash_for (sk);
521 ops->pubkey_algo = sk->pubkey_algo;
522 keyid_from_sk (sk, ops->keyid);
523 ops->last = (skcount == 1);
525 init_packet(&pkt);
526 pkt.pkttype = PKT_ONEPASS_SIG;
527 pkt.pkt.onepass_sig = ops;
528 rc = build_packet (out, &pkt);
529 free_packet (&pkt);
530 if (rc) {
531 log_error ("build onepass_sig packet failed: %s\n",
532 g10_errstr(rc));
533 return rc;
537 return 0;
541 * Helper to write the plaintext (literal data) packet
543 static int
544 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
546 PKT_plaintext *pt = NULL;
547 u32 filesize;
548 int rc = 0;
550 if (!opt.no_literal)
551 pt=setup_plaintext_name(fname,inp);
553 /* try to calculate the length of the data */
554 if ( !iobuf_is_pipe_filename (fname) && *fname )
556 off_t tmpsize;
557 int overflow;
559 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
560 && !overflow && opt.verbose)
561 log_info (_("WARNING: `%s' is an empty file\n"), fname);
563 /* We can't encode the length of very large files because
564 OpenPGP uses only 32 bit for file sizes. So if the size of
565 a file is larger than 2^32 minus some bytes for packet
566 headers, we switch to partial length encoding. */
567 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
568 filesize = tmpsize;
569 else
570 filesize = 0;
572 /* Because the text_filter modifies the length of the
573 * data, it is not possible to know the used length
574 * without a double read of the file - to avoid that
575 * we simple use partial length packets. */
576 if ( ptmode == 't' )
577 filesize = 0;
579 else
580 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
582 if (!opt.no_literal) {
583 PACKET pkt;
585 pt->timestamp = make_timestamp ();
586 pt->mode = ptmode;
587 pt->len = filesize;
588 pt->new_ctb = !pt->len && !RFC1991;
589 pt->buf = inp;
590 init_packet(&pkt);
591 pkt.pkttype = PKT_PLAINTEXT;
592 pkt.pkt.plaintext = pt;
593 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
594 if( (rc = build_packet (out, &pkt)) )
595 log_error ("build_packet(PLAINTEXT) failed: %s\n",
596 g10_errstr(rc) );
597 pt->buf = NULL;
599 else {
600 byte copy_buffer[4096];
601 int bytes_copied;
603 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
604 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
605 log_error ("copying input to output failed: %s\n",
606 gpg_strerror (rc));
607 break;
609 wipememory(copy_buffer,4096); /* burn buffer */
611 /* fixme: it seems that we never freed pt/pkt */
613 return rc;
617 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
618 * hash which will not be changes here.
620 static int
621 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
622 int sigclass, u32 timestamp, u32 duration,
623 int status_letter)
625 SK_LIST sk_rover;
627 /* loop over the secret certificates */
628 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
629 PKT_secret_key *sk;
630 PKT_signature *sig;
631 gcry_md_hd_t md;
632 int rc;
634 sk = sk_rover->sk;
636 /* build the signature packet */
637 sig = xmalloc_clear (sizeof *sig);
638 if(opt.force_v3_sigs || RFC1991)
639 sig->version=3;
640 else if(duration || opt.sig_policy_url
641 || opt.sig_notations || opt.sig_keyserver_url)
642 sig->version=4;
643 else
644 sig->version=sk->version;
645 keyid_from_sk (sk, sig->keyid);
646 sig->digest_algo = hash_for(sk);
647 sig->pubkey_algo = sk->pubkey_algo;
648 if(timestamp)
649 sig->timestamp = timestamp;
650 else
651 sig->timestamp = make_timestamp();
652 if(duration)
653 sig->expiredate = sig->timestamp+duration;
654 sig->sig_class = sigclass;
656 if (gcry_md_copy (&md, hash))
657 BUG ();
659 if (sig->version >= 4)
661 build_sig_subpkt_from_sig (sig);
662 mk_notation_policy_etc (sig, NULL, sk);
665 hash_sigversion_to_magic (md, sig);
666 gcry_md_final (md);
668 rc = do_sign( sk, sig, md, hash_for (sk) );
669 gcry_md_close (md);
670 if( !rc ) { /* and write it */
671 PACKET pkt;
673 init_packet(&pkt);
674 pkt.pkttype = PKT_SIGNATURE;
675 pkt.pkt.signature = sig;
676 rc = build_packet (out, &pkt);
677 if (!rc && is_status_enabled()) {
678 print_status_sig_created ( sk, sig, status_letter);
680 free_packet (&pkt);
681 if (rc)
682 log_error ("build signature packet failed: %s\n",
683 g10_errstr(rc) );
685 if( rc )
686 return rc;;
689 return 0;
692 /****************
693 * Sign the files whose names are in FILENAME.
694 * If DETACHED has the value true,
695 * make a detached signature. If FILENAMES->d is NULL read from stdin
696 * and ignore the detached mode. Sign the file with all secret keys
697 * which can be taken from LOCUSR, if this is NULL, use the default one
698 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
699 * signed data for these users.
700 * If OUTFILE is not NULL; this file is used for output and the function
701 * does not ask for overwrite permission; output is then always
702 * uncompressed, non-armored and in binary mode.
705 sign_file( strlist_t filenames, int detached, strlist_t locusr,
706 int encryptflag, strlist_t remusr, const char *outfile )
708 const char *fname;
709 armor_filter_context_t *afx;
710 compress_filter_context_t zfx;
711 md_filter_context_t mfx;
712 text_filter_context_t tfx;
713 progress_filter_context_t *pfx;
714 encrypt_filter_context_t efx;
715 IOBUF inp = NULL, out = NULL;
716 PACKET pkt;
717 int rc = 0;
718 PK_LIST pk_list = NULL;
719 SK_LIST sk_list = NULL;
720 SK_LIST sk_rover = NULL;
721 int multifile = 0;
722 u32 duration=0;
724 pfx = new_progress_context ();
725 afx = new_armor_context ();
726 memset( &zfx, 0, sizeof zfx);
727 memset( &mfx, 0, sizeof mfx);
728 memset( &efx, 0, sizeof efx);
729 init_packet( &pkt );
731 if( filenames ) {
732 fname = filenames->d;
733 multifile = !!filenames->next;
735 else
736 fname = NULL;
738 if( fname && filenames->next && (!detached || encryptflag) )
739 log_bug("multiple files can only be detached signed");
741 if(encryptflag==2
742 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
743 goto leave;
745 if(!opt.force_v3_sigs && !RFC1991)
747 if(opt.ask_sig_expire && !opt.batch)
748 duration=ask_expire_interval(1,opt.def_sig_expire);
749 else
750 duration=parse_expire_string(opt.def_sig_expire);
753 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
754 goto leave;
756 if(PGP2 && !only_old_style(sk_list))
758 log_info(_("you can only detach-sign with PGP 2.x style keys "
759 "while in --pgp2 mode\n"));
760 compliance_failure();
763 if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC )))
764 goto leave;
766 /* prepare iobufs */
767 if( multifile ) /* have list of filenames */
768 inp = NULL; /* we do it later */
769 else {
770 inp = iobuf_open(fname);
771 if (inp && is_secured_file (iobuf_get_fd (inp)))
773 iobuf_close (inp);
774 inp = NULL;
775 errno = EPERM;
777 if( !inp )
779 rc = gpg_error_from_syserror ();
780 log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
781 strerror(errno) );
782 goto leave;
785 handle_progress (pfx, inp, fname);
788 if( outfile ) {
789 if (is_secured_filename ( outfile )) {
790 out = NULL;
791 errno = EPERM;
793 else
794 out = iobuf_create( outfile );
795 if( !out )
797 rc = gpg_error_from_syserror ();
798 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
799 goto leave;
801 else if( opt.verbose )
802 log_info(_("writing to `%s'\n"), outfile );
804 else if( (rc = open_outfile (GNUPG_INVALID_FD, fname,
805 opt.armor? 1: detached? 2:0, &out )))
806 goto leave;
808 /* prepare to calculate the MD over the input */
809 if( opt.textmode && !outfile && !multifile )
811 memset( &tfx, 0, sizeof tfx);
812 iobuf_push_filter( inp, text_filter, &tfx );
815 if ( gcry_md_open (&mfx.md, 0, 0) )
816 BUG ();
817 if (DBG_HASHING)
818 gcry_md_start_debug (mfx.md, "sign");
820 /* If we're encrypting and signing, it is reasonable to pick the
821 hash algorithm to use out of the recepient key prefs. This is
822 best effort only, as in a DSA2 and smartcard world there are
823 cases where we cannot please everyone with a single hash (DSA2
824 wants >160 and smartcards want =160). In the future this could
825 be more complex with different hashes for each sk, but the
826 current design requires a single hash for all SKs. */
827 if(pk_list)
829 if(opt.def_digest_algo)
831 if(!opt.expert &&
832 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
833 opt.def_digest_algo,
834 NULL)!=opt.def_digest_algo)
835 log_info(_("WARNING: forcing digest algorithm %s (%d)"
836 " violates recipient preferences\n"),
837 gcry_md_algo_name (opt.def_digest_algo),
838 opt.def_digest_algo );
840 else
842 int algo, smartcard=0;
843 union pref_hint hint;
845 hint.digest_length = 0;
847 /* Of course, if the recipient asks for something
848 unreasonable (like the wrong hash for a DSA key) then
849 don't do it. Check all sk's - if any are DSA or live
850 on a smartcard, then the hash has restrictions and we
851 may not be able to give the recipient what they want.
852 For DSA, pass a hint for the largest q we have. Note
853 that this means that a q>160 key will override a q=160
854 key and force the use of truncation for the q=160 key.
855 The alternative would be to ignore the recipient prefs
856 completely and get a different hash for each DSA key in
857 hash_for(). The override behavior here is more or less
858 reasonable as it is under the control of the user which
859 keys they sign with for a given message and the fact
860 that the message with multiple signatures won't be
861 usable on an implementation that doesn't understand
862 DSA2 anyway. */
864 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
866 if (sk_rover->sk->pubkey_algo == PUBKEY_ALGO_DSA)
868 int temp_hashlen = gcry_mpi_get_nbits
869 (sk_rover->sk->skey[1])+7/8;
871 /* Pick a hash that is large enough for our
872 largest q */
874 if (hint.digest_length<temp_hashlen)
875 hint.digest_length=temp_hashlen;
877 else if (sk_rover->sk->is_protected
878 && sk_rover->sk->protect.s2k.mode == 1002)
879 smartcard = 1;
882 /* Current smartcards only do 160-bit hashes. If we have
883 to have a >160-bit hash, then we can't use the
884 recipient prefs as we'd need both =160 and >160 at the
885 same time and recipient prefs currently require a
886 single hash for all signatures. All this may well have
887 to change as the cards add algorithms. */
889 if (!smartcard || (smartcard && hint.digest_length==20))
890 if ( (algo=
891 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
892 recipient_digest_algo=algo;
896 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
897 PKT_secret_key *sk = sk_rover->sk;
898 gcry_md_enable (mfx.md, hash_for(sk));
901 if( !multifile )
902 iobuf_push_filter( inp, md_filter, &mfx );
904 if( detached && !encryptflag && !RFC1991 )
905 afx->what = 2;
907 if( opt.armor && !outfile )
908 push_armor_filter (afx, out);
910 if( encryptflag ) {
911 efx.pk_list = pk_list;
912 /* fixme: set efx.cfx.datalen if known */
913 iobuf_push_filter( out, encrypt_filter, &efx );
916 if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) )
918 int compr_algo=opt.compress_algo;
920 /* If not forced by user */
921 if(compr_algo==-1)
923 /* If we're not encrypting, then select_algo_from_prefs
924 will fail and we'll end up with the default. If we are
925 encrypting, select_algo_from_prefs cannot fail since
926 there is an assumed preference for uncompressed data.
927 Still, if it did fail, we'll also end up with the
928 default. */
930 if((compr_algo=
931 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
932 compr_algo=default_compress_algo();
934 else if(!opt.expert && pk_list
935 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
936 compr_algo,NULL)!=compr_algo)
937 log_info(_("WARNING: forcing compression algorithm %s (%d)"
938 " violates recipient preferences\n"),
939 compress_algo_to_string(compr_algo),compr_algo);
941 /* algo 0 means no compression */
942 if( compr_algo )
943 push_compress_filter(out,&zfx,compr_algo);
946 /* Write the one-pass signature packets if needed */
947 if (!detached && !RFC1991) {
948 rc = write_onepass_sig_packets (sk_list, out,
949 opt.textmode && !outfile ? 0x01:0x00);
950 if (rc)
951 goto leave;
954 write_status_begin_signing (mfx.md);
956 /* Setup the inner packet. */
957 if( detached ) {
958 if( multifile ) {
959 strlist_t sl;
961 if( opt.verbose )
962 log_info(_("signing:") );
963 /* must walk reverse trough this list */
964 for( sl = strlist_last(filenames); sl;
965 sl = strlist_prev( filenames, sl ) ) {
966 inp = iobuf_open(sl->d);
967 if (inp && is_secured_file (iobuf_get_fd (inp)))
969 iobuf_close (inp);
970 inp = NULL;
971 errno = EPERM;
973 if( !inp )
975 rc = gpg_error_from_syserror ();
976 log_error(_("can't open `%s': %s\n"),
977 sl->d,strerror(errno));
978 goto leave;
980 handle_progress (pfx, inp, sl->d);
981 if( opt.verbose )
982 fprintf(stderr, " `%s'", sl->d );
983 if(opt.textmode)
985 memset( &tfx, 0, sizeof tfx);
986 iobuf_push_filter( inp, text_filter, &tfx );
988 iobuf_push_filter( inp, md_filter, &mfx );
989 while( iobuf_get(inp) != -1 )
991 iobuf_close(inp); inp = NULL;
993 if( opt.verbose )
994 putc( '\n', stderr );
996 else {
997 /* read, so that the filter can calculate the digest */
998 while( iobuf_get(inp) != -1 )
1002 else {
1003 rc = write_plaintext_packet (out, inp, fname,
1004 opt.textmode && !outfile ? 't':'b');
1007 /* catch errors from above */
1008 if (rc)
1009 goto leave;
1011 /* write the signatures */
1012 rc = write_signature_packets (sk_list, out, mfx.md,
1013 opt.textmode && !outfile? 0x01 : 0x00,
1014 0, duration, detached ? 'D':'S');
1015 if( rc )
1016 goto leave;
1019 leave:
1020 if( rc )
1021 iobuf_cancel(out);
1022 else {
1023 iobuf_close(out);
1024 if (encryptflag)
1025 write_status( STATUS_END_ENCRYPTION );
1027 iobuf_close(inp);
1028 gcry_md_close ( mfx.md );
1029 release_sk_list( sk_list );
1030 release_pk_list( pk_list );
1031 recipient_digest_algo=0;
1032 release_progress_context (pfx);
1033 release_armor_context (afx);
1034 return rc;
1039 /****************
1040 * make a clear signature. note that opt.armor is not needed
1043 clearsign_file( const char *fname, strlist_t locusr, const char *outfile )
1045 armor_filter_context_t *afx;
1046 progress_filter_context_t *pfx;
1047 gcry_md_hd_t textmd = NULL;
1048 IOBUF inp = NULL, out = NULL;
1049 PACKET pkt;
1050 int rc = 0;
1051 SK_LIST sk_list = NULL;
1052 SK_LIST sk_rover = NULL;
1053 int old_style = RFC1991;
1054 int only_md5 = 0;
1055 u32 duration=0;
1057 pfx = new_progress_context ();
1058 afx = new_armor_context ();
1059 init_packet( &pkt );
1061 if(!opt.force_v3_sigs && !RFC1991)
1063 if(opt.ask_sig_expire && !opt.batch)
1064 duration=ask_expire_interval(1,opt.def_sig_expire);
1065 else
1066 duration=parse_expire_string(opt.def_sig_expire);
1069 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
1070 goto leave;
1072 if( !old_style && !duration )
1073 old_style = only_old_style( sk_list );
1075 if(PGP2 && !only_old_style(sk_list))
1077 log_info(_("you can only clearsign with PGP 2.x style keys "
1078 "while in --pgp2 mode\n"));
1079 compliance_failure();
1082 /* prepare iobufs */
1083 inp = iobuf_open(fname);
1084 if (inp && is_secured_file (iobuf_get_fd (inp)))
1086 iobuf_close (inp);
1087 inp = NULL;
1088 errno = EPERM;
1090 if( !inp ) {
1091 rc = gpg_error_from_syserror ();
1092 log_error (_("can't open `%s': %s\n"),
1093 fname? fname: "[stdin]", strerror(errno) );
1094 goto leave;
1096 handle_progress (pfx, inp, fname);
1098 if( outfile ) {
1099 if (is_secured_filename (outfile) ) {
1100 outfile = NULL;
1101 errno = EPERM;
1103 else
1104 out = iobuf_create( outfile );
1105 if( !out )
1107 rc = gpg_error_from_syserror ();
1108 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
1109 goto leave;
1111 else if( opt.verbose )
1112 log_info(_("writing to `%s'\n"), outfile );
1114 else if( (rc = open_outfile (GNUPG_INVALID_FD, fname, 1, &out )) )
1115 goto leave;
1117 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1119 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1120 PKT_secret_key *sk = sk_rover->sk;
1121 if( hash_for(sk) == DIGEST_ALGO_MD5 )
1122 only_md5 = 1;
1123 else {
1124 only_md5 = 0;
1125 break;
1129 if( !(old_style && only_md5) ) {
1130 const char *s;
1131 int any = 0;
1132 byte hashs_seen[256];
1134 memset( hashs_seen, 0, sizeof hashs_seen );
1135 iobuf_writestr(out, "Hash: " );
1136 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1137 PKT_secret_key *sk = sk_rover->sk;
1138 int i = hash_for(sk);
1140 if( !hashs_seen[ i & 0xff ] ) {
1141 s = gcry_md_algo_name ( i );
1142 if( s ) {
1143 hashs_seen[ i & 0xff ] = 1;
1144 if( any )
1145 iobuf_put(out, ',' );
1146 iobuf_writestr(out, s );
1147 any = 1;
1151 assert(any);
1152 iobuf_writestr(out, LF );
1155 if( opt.not_dash_escaped )
1156 iobuf_writestr( out,
1157 "NotDashEscaped: You need GnuPG to verify this message" LF );
1158 iobuf_writestr(out, LF );
1160 if ( gcry_md_open (&textmd, 0, 0) )
1161 BUG ();
1162 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1163 PKT_secret_key *sk = sk_rover->sk;
1164 gcry_md_enable (textmd, hash_for(sk));
1166 if ( DBG_HASHING )
1167 gcry_md_start_debug ( textmd, "clearsign" );
1169 copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
1170 opt.escape_from, (old_style && only_md5) );
1171 /* fixme: check for read errors */
1173 /* now write the armor */
1174 afx->what = 2;
1175 push_armor_filter (afx, out);
1177 /* write the signatures */
1178 rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
1179 if( rc )
1180 goto leave;
1182 leave:
1183 if( rc )
1184 iobuf_cancel(out);
1185 else
1186 iobuf_close(out);
1187 iobuf_close(inp);
1188 gcry_md_close ( textmd );
1189 release_sk_list( sk_list );
1190 release_progress_context (pfx);
1191 release_armor_context (afx);
1192 return rc;
1196 * Sign and conventionally encrypt the given file.
1197 * FIXME: Far too much code is duplicated - revamp the whole file.
1200 sign_symencrypt_file (const char *fname, strlist_t locusr)
1202 armor_filter_context_t *afx;
1203 progress_filter_context_t *pfx;
1204 compress_filter_context_t zfx;
1205 md_filter_context_t mfx;
1206 text_filter_context_t tfx;
1207 cipher_filter_context_t cfx;
1208 IOBUF inp = NULL, out = NULL;
1209 PACKET pkt;
1210 STRING2KEY *s2k = NULL;
1211 int rc = 0;
1212 SK_LIST sk_list = NULL;
1213 SK_LIST sk_rover = NULL;
1214 int algo;
1215 u32 duration=0;
1216 int canceled;
1218 pfx = new_progress_context ();
1219 afx = new_armor_context ();
1220 memset( &zfx, 0, sizeof zfx);
1221 memset( &mfx, 0, sizeof mfx);
1222 memset( &tfx, 0, sizeof tfx);
1223 memset( &cfx, 0, sizeof cfx);
1224 init_packet( &pkt );
1226 if(!opt.force_v3_sigs && !RFC1991)
1228 if(opt.ask_sig_expire && !opt.batch)
1229 duration=ask_expire_interval(1,opt.def_sig_expire);
1230 else
1231 duration=parse_expire_string(opt.def_sig_expire);
1234 rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
1235 if (rc)
1236 goto leave;
1238 /* prepare iobufs */
1239 inp = iobuf_open(fname);
1240 if (inp && is_secured_file (iobuf_get_fd (inp)))
1242 iobuf_close (inp);
1243 inp = NULL;
1244 errno = EPERM;
1246 if( !inp ) {
1247 rc = gpg_error_from_syserror ();
1248 log_error (_("can't open `%s': %s\n"),
1249 fname? fname: "[stdin]", strerror(errno) );
1250 goto leave;
1252 handle_progress (pfx, inp, fname);
1254 /* prepare key */
1255 s2k = xmalloc_clear( sizeof *s2k );
1256 s2k->mode = RFC1991? 0:opt.s2k_mode;
1257 s2k->hash_algo = S2K_DIGEST_ALGO;
1259 algo = default_cipher_algo();
1260 if (!opt.quiet || !opt.batch)
1261 log_info (_("%s encryption will be used\n"),
1262 openpgp_cipher_algo_name (algo) );
1263 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
1265 if (!cfx.dek || !cfx.dek->keylen) {
1266 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1267 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1268 goto leave;
1271 /* We have no way to tell if the recipient can handle messages
1272 with an MDC, so this defaults to no. Perhaps in a few years,
1273 this can be defaulted to yes. Note that like regular
1274 encrypting, --force-mdc overrides --disable-mdc. */
1275 if(opt.force_mdc)
1276 cfx.dek->use_mdc=1;
1278 /* now create the outfile */
1279 rc = open_outfile (GNUPG_INVALID_FD, fname, opt.armor? 1:0, &out);
1280 if (rc)
1281 goto leave;
1283 /* prepare to calculate the MD over the input */
1284 if (opt.textmode)
1285 iobuf_push_filter (inp, text_filter, &tfx);
1286 if ( gcry_md_open (&mfx.md, 0, 0) )
1287 BUG ();
1288 if ( DBG_HASHING )
1289 gcry_md_start_debug (mfx.md, "symc-sign");
1291 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
1292 PKT_secret_key *sk = sk_rover->sk;
1293 gcry_md_enable (mfx.md, hash_for (sk));
1296 iobuf_push_filter (inp, md_filter, &mfx);
1298 /* Push armor output filter */
1299 if (opt.armor)
1300 push_armor_filter (afx, out);
1302 /* Write the symmetric key packet */
1303 /*(current filters: armor)*/
1304 if (!RFC1991) {
1305 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1306 enc->version = 4;
1307 enc->cipher_algo = cfx.dek->algo;
1308 enc->s2k = *s2k;
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", g10_errstr(rc) );
1313 xfree(enc);
1316 /* Push the encryption filter */
1317 iobuf_push_filter( out, cipher_filter, &cfx );
1319 /* Push the compress filter */
1320 if (default_compress_algo())
1321 push_compress_filter(out,&zfx,default_compress_algo());
1323 /* Write the one-pass signature packets */
1324 /*(current filters: zip - encrypt - armor)*/
1325 if (!RFC1991) {
1326 rc = write_onepass_sig_packets (sk_list, out,
1327 opt.textmode? 0x01:0x00);
1328 if (rc)
1329 goto leave;
1332 write_status_begin_signing (mfx.md);
1334 /* Pipe data through all filters; i.e. write the signed stuff */
1335 /*(current filters: zip - encrypt - armor)*/
1336 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1337 if (rc)
1338 goto leave;
1340 /* Write the signatures */
1341 /*(current filters: zip - encrypt - armor)*/
1342 rc = write_signature_packets (sk_list, out, mfx.md,
1343 opt.textmode? 0x01 : 0x00,
1344 0, duration, 'S');
1345 if( rc )
1346 goto leave;
1349 leave:
1350 if( rc )
1351 iobuf_cancel(out);
1352 else {
1353 iobuf_close(out);
1354 write_status( STATUS_END_ENCRYPTION );
1356 iobuf_close(inp);
1357 release_sk_list( sk_list );
1358 gcry_md_close( mfx.md );
1359 xfree(cfx.dek);
1360 xfree(s2k);
1361 release_progress_context (pfx);
1362 release_armor_context (afx);
1363 return rc;
1367 /****************
1368 * Create a signature packet for the given public key certificate and
1369 * the user id and return it in ret_sig. User signature class SIGCLASS
1370 * user-id is not used (and may be NULL if sigclass is 0x20) If
1371 * DIGEST_ALGO is 0 the function selects an appropriate one.
1372 * SIGVERSION gives the minimal required signature packet version;
1373 * this is needed so that special properties like local sign are not
1374 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1375 * the timestamp to use for the signature. 0 means "now" */
1377 make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
1378 PKT_user_id *uid, PKT_public_key *subpk,
1379 PKT_secret_key *sk,
1380 int sigclass, int digest_algo,
1381 int sigversion, u32 timestamp, u32 duration,
1382 int (*mksubpkt)(PKT_signature *, void *), void *opaque
1385 PKT_signature *sig;
1386 int rc=0;
1387 gcry_md_hd_t md;
1389 assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1390 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1391 || sigclass == 0x30 || sigclass == 0x28 );
1393 if (opt.force_v4_certs)
1394 sigversion = 4;
1396 if (sigversion < sk->version)
1397 sigversion = sk->version;
1399 /* If you are making a signature on a v4 key using your v3 key, it
1400 doesn't make sense to generate a v3 sig. After all, no v3-only
1401 PGP implementation could understand the v4 key in the first
1402 place. Note that this implies that a signature on an attribute
1403 uid is usually going to be v4 as well, since they are not
1404 generally found on v3 keys. */
1405 if (sigversion < pk->version)
1406 sigversion = pk->version;
1408 if( !digest_algo )
1410 /* Basically, this means use SHA1 always unless it's a v3 RSA
1411 key making a v3 cert (use MD5), or the user specified
1412 something (use whatever they said), or it's DSA (use the
1413 best match). They still can't pick an inappropriate hash
1414 for DSA or the signature will fail. Note that this still
1415 allows the caller of make_keysig_packet to override the
1416 user setting if it must. */
1418 if(opt.cert_digest_algo)
1419 digest_algo=opt.cert_digest_algo;
1420 else if(sk->pubkey_algo==PUBKEY_ALGO_RSA
1421 && pk->version<4 && sigversion<4)
1422 digest_algo = DIGEST_ALGO_MD5;
1423 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
1424 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (sk->skey[1])/8);
1425 else
1426 digest_algo = DIGEST_ALGO_SHA1;
1429 if ( gcry_md_open (&md, digest_algo, 0 ) )
1430 BUG ();
1432 /* Hash the public key certificate. */
1433 hash_public_key( md, pk );
1435 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1437 /* hash the subkey binding/backsig/revocation */
1438 hash_public_key( md, subpk );
1440 else if( sigclass != 0x1F && sigclass != 0x20 )
1442 /* hash the user id */
1443 hash_uid (md, sigversion, uid);
1445 /* and make the signature packet */
1446 sig = xmalloc_clear( sizeof *sig );
1447 sig->version = sigversion;
1448 sig->flags.exportable=1;
1449 sig->flags.revocable=1;
1450 keyid_from_sk( sk, sig->keyid );
1451 sig->pubkey_algo = sk->pubkey_algo;
1452 sig->digest_algo = digest_algo;
1453 if(timestamp)
1454 sig->timestamp=timestamp;
1455 else
1456 sig->timestamp=make_timestamp();
1457 if(duration)
1458 sig->expiredate=sig->timestamp+duration;
1459 sig->sig_class = sigclass;
1460 if( sig->version >= 4 )
1462 build_sig_subpkt_from_sig( sig );
1463 mk_notation_policy_etc( sig, pk, sk );
1466 /* Crucial that the call to mksubpkt comes LAST before the calls
1467 to finalize the sig as that makes it possible for the mksubpkt
1468 function to get a reliable pointer to the subpacket area. */
1469 if( sig->version >= 4 && mksubpkt )
1470 rc = (*mksubpkt)( sig, opaque );
1472 if( !rc ) {
1473 hash_sigversion_to_magic (md, sig);
1474 gcry_md_final (md);
1476 rc = complete_sig( sig, sk, md );
1479 gcry_md_close ( md );
1480 if( rc )
1481 free_seckey_enc( sig );
1482 else
1483 *ret_sig = sig;
1484 return rc;
1489 /****************
1490 * Create a new signature packet based on an existing one.
1491 * Only user ID signatures are supported for now.
1492 * TODO: Merge this with make_keysig_packet.
1495 update_keysig_packet( PKT_signature **ret_sig,
1496 PKT_signature *orig_sig,
1497 PKT_public_key *pk,
1498 PKT_user_id *uid,
1499 PKT_public_key *subpk,
1500 PKT_secret_key *sk,
1501 int (*mksubpkt)(PKT_signature *, void *),
1502 void *opaque )
1504 PKT_signature *sig;
1505 int rc=0;
1506 gcry_md_hd_t md;
1508 if ((!orig_sig || !pk || !sk)
1509 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1510 || (orig_sig->sig_class == 0x18 && !subpk))
1511 return G10ERR_GENERAL;
1513 if ( gcry_md_open (&md, orig_sig->digest_algo, 0 ) )
1514 BUG ();
1516 /* Hash the public key certificate and the user id. */
1517 hash_public_key( md, pk );
1519 if( orig_sig->sig_class == 0x18 )
1520 hash_public_key( md, subpk );
1521 else
1522 hash_uid (md, orig_sig->version, uid);
1524 /* create a new signature packet */
1525 sig = copy_signature (NULL, orig_sig);
1527 /* We need to create a new timestamp so that new sig expiration
1528 calculations are done correctly... */
1529 sig->timestamp=make_timestamp();
1531 /* ... but we won't make a timestamp earlier than the existing
1532 one. */
1533 while(sig->timestamp<=orig_sig->timestamp)
1535 gnupg_sleep (1);
1536 sig->timestamp=make_timestamp();
1539 /* Note that already expired sigs will remain expired (with a
1540 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1541 detects this case. */
1543 if( sig->version >= 4 )
1545 /* Put the updated timestamp into the sig. Note that this
1546 will automagically lower any sig expiration dates to
1547 correctly correspond to the differences in the timestamps
1548 (i.e. the duration will shrink). */
1549 build_sig_subpkt_from_sig( sig );
1551 if (mksubpkt)
1552 rc = (*mksubpkt)(sig, opaque);
1555 if (!rc) {
1556 hash_sigversion_to_magic (md, sig);
1557 gcry_md_final (md);
1559 rc = complete_sig( sig, sk, md );
1562 gcry_md_close (md);
1563 if( rc )
1564 free_seckey_enc (sig);
1565 else
1566 *ret_sig = sig;
1567 return rc;