Fix for bug 797.
[gnupg.git] / g10 / sign.c
blob062fa9f48c35a32ba753ef0755db2dcf71403b2c
1 /* sign.c - sign data
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,
20 * USA.
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <assert.h>
29 #include <unistd.h> /* need sleep() */
31 #include "gpg.h"
32 #include "options.h"
33 #include "packet.h"
34 #include "errors.h"
35 #include "iobuf.h"
36 #include "keydb.h"
37 #include "util.h"
38 #include "main.h"
39 #include "filter.h"
40 #include "ttyio.h"
41 #include "trustdb.h"
42 #include "status.h"
43 #include "i18n.h"
44 #include "pkglue.h"
45 #include "call-agent.h"
48 #ifdef HAVE_DOSISH_SYSTEM
49 #define LF "\r\n"
50 void __stdcall Sleep(ulong);
51 #define sleep(a) Sleep((a)*1000)
52 #else
53 #define LF "\n"
54 #endif
56 static int recipient_digest_algo=0;
58 /****************
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.
63 static void
64 mk_notation_policy_etc( PKT_signature *sig,
65 PKT_public_key *pk, PKT_secret_key *sk )
67 const char *string;
68 char *s=NULL;
69 strlist_t pu=NULL;
70 struct notation *nd=NULL;
71 struct expando_args args;
73 memset(&args,0,sizeof(args));
74 args.pk=pk;
75 args.sk=sk;
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. */
82 /* notation data */
83 if(IS_SIG(sig) && opt.sig_notations)
85 if(sig->version<4)
86 log_error(_("can't put notation data into v3 (PGP 2.x style) "
87 "signatures\n"));
88 else
89 nd=opt.sig_notations;
91 else if( IS_CERT(sig) && opt.cert_notations )
93 if(sig->version<4)
94 log_error(_("can't put notation data into v3 (PGP 2.x style) "
95 "key signatures\n"));
96 else
97 nd=opt.cert_notations;
100 if(nd)
102 struct notation *i;
104 for(i=nd;i;i=i->next)
106 i->altvalue=pct_expando(i->value,&args);
107 if(!i->altvalue)
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)
116 xfree(i->altvalue);
117 i->altvalue=NULL;
121 /* set policy URL */
122 if( IS_SIG(sig) && opt.sig_policy_url )
124 if(sig->version<4)
125 log_error(_("can't put a policy URL into v3 (PGP 2.x style) "
126 "signatures\n"));
127 else
128 pu=opt.sig_policy_url;
130 else if( IS_CERT(sig) && opt.cert_policy_url )
132 if(sig->version<4)
133 log_error(_("can't put a policy URL into v3 key (PGP 2.x style) "
134 "signatures\n"));
135 else
136 pu=opt.cert_policy_url;
139 for(;pu;pu=pu->next)
141 string = pu->d;
143 s=pct_expando(string,&args);
144 if(!s)
146 log_error(_("WARNING: unable to %%-expand policy URL "
147 "(too large). Using unexpanded.\n"));
148 s=xstrdup(string);
151 build_sig_subpkt(sig,SIGSUBPKT_POLICY|
152 ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
153 s,strlen(s));
155 xfree(s);
158 /* preferred keyserver URL */
159 if( IS_SIG(sig) && opt.sig_keyserver_url )
161 if(sig->version<4)
162 log_info("can't put a preferred keyserver URL into v3 signatures\n");
163 else
164 pu=opt.sig_keyserver_url;
167 for(;pu;pu=pu->next)
169 string = pu->d;
171 s=pct_expando(string,&args);
172 if(!s)
174 log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
175 " (too large). Using unexpanded.\n"));
176 s=xstrdup(string);
179 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS|
180 ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
181 s,strlen(s));
183 xfree(s);
189 * Helper to hash a user ID packet.
191 static void
192 hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
194 if ( sigversion >= 4 ) {
195 byte buf[5];
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;
204 else {
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;
209 buf[4] = uid->len;
211 gcry_md_write( md, buf, 5 );
214 if(uid->attrib_data)
215 gcry_md_write (md, uid->attrib_data, uid->attrib_len );
216 else
217 gcry_md_write (md, uid->name, uid->len );
222 * Helper to hash some parts from the signature
224 static void
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 );
237 else {
238 byte buf[6];
239 size_t n;
241 gcry_md_putc (md, sig->pubkey_algo);
242 gcry_md_putc (md, sig->digest_algo);
243 if (sig->hashed) {
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 );
248 n += 6;
250 else {
251 gcry_md_putc (md, 0); /* always hash the length of the subpacket*/
252 gcry_md_putc (md, 0);
253 n = 6;
255 /* add some magic */
256 buf[0] = sig->version;
257 buf[1] = 0xff;
258 buf[2] = n >> 24; /* hmmm, n is only 16 bit, so this is always 0 */
259 buf[3] = n >> 16;
260 buf[4] = n >> 8;
261 buf[5] = n;
262 gcry_md_write (md, buf, 6);
267 static int
268 do_sign( PKT_secret_key *sk, PKT_signature *sig,
269 gcry_md_hd_t md, int digest_algo )
271 gcry_mpi_t frame;
272 byte *dp;
273 int rc;
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);
288 if( !digest_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
299 unsigned char *rbuf;
300 size_t rbuflen;
301 char *snbuf;
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),
308 &rbuf, &rbuflen);
309 xfree (snbuf);
310 if (!rc)
312 if (gcry_mpi_scan (&sig->data[0], GCRYMPI_FMT_USG,
313 rbuf, rbuflen, NULL))
314 BUG ();
315 xfree (rbuf);
317 #else
318 return gpg_error (GPG_ERR_NOT_SUPPORTED);
319 #endif /* ENABLE_CARD_SUPPORT */
321 else
323 frame = encode_md_value( NULL, sk, md, digest_algo );
324 if (!frame)
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;
338 else {
339 frame = encode_md_value (pk, NULL, md, sig->digest_algo );
340 if (!frame)
341 rc = G10ERR_GENERAL;
342 else
343 rc = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey );
344 gcry_mpi_release (frame);
346 if (rc)
347 log_error (_("checking created signature failed: %s\n"),
348 g10_errstr (rc));
349 free_public_key (pk);
351 if( rc )
352 log_error(_("signing failed: %s\n"), g10_errstr(rc) );
353 else {
354 if( opt.verbose ) {
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),
359 ustr );
360 xfree(ustr);
363 return rc;
368 complete_sig( PKT_signature *sig, PKT_secret_key *sk, gcry_md_hd_t md )
370 int rc=0;
372 if( !(rc=check_secret_key( sk, 0 )) )
373 rc = do_sign( sk, sig, md, 0 );
374 return rc;
379 static int
380 match_dsa_hash (unsigned int qbytes)
382 if (qbytes <= 20)
383 return DIGEST_ALGO_SHA1;
384 #ifdef USE_SHA256
385 if (qbytes <= 28)
386 return DIGEST_ALGO_SHA224;
387 if (qbytes <= 32)
388 return DIGEST_ALGO_SHA256;
389 #endif
391 #ifdef USE_SHA512
392 if (qbytes <= 48)
393 return DIGEST_ALGO_SHA384;
394 if (qbytes <= 64)
395 return DIGEST_ALGO_SHA512;
396 #endif
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
414 list?
416 static int
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)
436 prefitem_t *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)
442 return prefs->value;
444 else
446 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
447 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
448 return prefs->value;
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)
462 prefitem_t *prefs;
464 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
465 if (prefs->value==DIGEST_ALGO_SHA1
466 || prefs->value==DIGEST_ALGO_RMD160)
467 return prefs->value;
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;
483 else
484 return DEFAULT_DIGEST_ALGO;
488 static int
489 only_old_style( SK_LIST sk_list )
491 SK_LIST sk_rover = NULL;
492 int old_style = 0;
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 )
498 old_style = 1;
499 else
500 return 0;
502 return old_style;
507 static void
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];
512 size_t i, n;
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
533 static int
534 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
536 int skcount;
537 SK_LIST sk_rover;
539 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
540 skcount++;
542 for (; skcount; skcount--) {
543 PKT_secret_key *sk;
544 PKT_onepass_sig *ops;
545 PACKET pkt;
546 int i, rc;
548 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
549 if (++i == skcount)
550 break;
553 sk = sk_rover->sk;
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);
561 init_packet(&pkt);
562 pkt.pkttype = PKT_ONEPASS_SIG;
563 pkt.pkt.onepass_sig = ops;
564 rc = build_packet (out, &pkt);
565 free_packet (&pkt);
566 if (rc) {
567 log_error ("build onepass_sig packet failed: %s\n",
568 g10_errstr(rc));
569 return rc;
573 return 0;
577 * Helper to write the plaintext (literal data) packet
579 static int
580 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
582 PKT_plaintext *pt = NULL;
583 u32 filesize;
584 int rc = 0;
586 if (!opt.no_literal)
587 pt=setup_plaintext_name(fname,inp);
589 /* try to calculate the length of the data */
590 if ( !iobuf_is_pipe_filename (fname) && *fname )
592 off_t tmpsize;
593 int overflow;
595 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
596 && !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) )
604 filesize = tmpsize;
605 else
606 filesize = 0;
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. */
612 if ( ptmode == 't' )
613 filesize = 0;
615 else
616 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
618 if (!opt.no_literal) {
619 PACKET pkt;
621 pt->timestamp = make_timestamp ();
622 pt->mode = ptmode;
623 pt->len = filesize;
624 pt->new_ctb = !pt->len && !RFC1991;
625 pt->buf = inp;
626 init_packet(&pkt);
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",
632 g10_errstr(rc) );
633 pt->buf = NULL;
635 else {
636 byte copy_buffer[4096];
637 int bytes_copied;
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",
642 gpg_strerror (rc));
643 break;
645 wipememory(copy_buffer,4096); /* burn buffer */
647 /* fixme: it seems that we never freed pt/pkt */
649 return rc;
653 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
654 * hash which will not be changes here.
656 static int
657 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
658 int sigclass, u32 timestamp, u32 duration,
659 int status_letter)
661 SK_LIST sk_rover;
663 /* loop over the secret certificates */
664 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
665 PKT_secret_key *sk;
666 PKT_signature *sig;
667 gcry_md_hd_t md;
668 int rc;
670 sk = sk_rover->sk;
672 /* build the signature packet */
673 sig = xmalloc_clear (sizeof *sig);
674 if(opt.force_v3_sigs || RFC1991)
675 sig->version=3;
676 else if(duration || opt.sig_policy_url
677 || opt.sig_notations || opt.sig_keyserver_url)
678 sig->version=4;
679 else
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;
684 if(timestamp)
685 sig->timestamp = timestamp;
686 else
687 sig->timestamp = make_timestamp();
688 if(duration)
689 sig->expiredate = sig->timestamp+duration;
690 sig->sig_class = sigclass;
692 if (gcry_md_copy (&md, hash))
693 BUG ();
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);
700 gcry_md_final (md);
702 rc = do_sign( sk, sig, md, hash_for (sk) );
703 gcry_md_close (md);
704 if( !rc ) { /* and write it */
705 PACKET pkt;
707 init_packet(&pkt);
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);
714 free_packet (&pkt);
715 if (rc)
716 log_error ("build signature packet failed: %s\n",
717 g10_errstr(rc) );
719 if( rc )
720 return rc;;
723 return 0;
726 /****************
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 )
742 const char *fname;
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;
750 PACKET pkt;
751 int rc = 0;
752 PK_LIST pk_list = NULL;
753 SK_LIST sk_list = NULL;
754 SK_LIST sk_rover = NULL;
755 int multifile = 0;
756 u32 duration=0;
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);
763 init_packet( &pkt );
765 if( filenames ) {
766 fname = filenames->d;
767 multifile = !!filenames->next;
769 else
770 fname = NULL;
772 if( fname && filenames->next && (!detached || encryptflag) )
773 log_bug("multiple files can only be detached signed");
775 if(encryptflag==2
776 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
777 goto leave;
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);
783 else
784 duration=parse_expire_string(opt.def_sig_expire);
787 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
788 goto leave;
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 )))
798 goto leave;
800 /* prepare iobufs */
801 if( multifile ) /* have list of filenames */
802 inp = NULL; /* we do it later */
803 else {
804 inp = iobuf_open(fname);
805 if (inp && is_secured_file (iobuf_get_fd (inp)))
807 iobuf_close (inp);
808 inp = NULL;
809 errno = EPERM;
811 if( !inp )
813 rc = gpg_error_from_syserror ();
814 log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
815 strerror(errno) );
816 goto leave;
819 handle_progress (pfx, inp, fname);
822 if( outfile ) {
823 if (is_secured_filename ( outfile )) {
824 out = NULL;
825 errno = EPERM;
827 else
828 out = iobuf_create( outfile );
829 if( !out )
831 rc = gpg_error_from_syserror ();
832 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
833 goto leave;
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 )))
839 goto leave;
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) )
849 BUG ();
850 if (DBG_HASHING)
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. */
860 if(pk_list)
862 if(opt.def_digest_algo)
864 if(!opt.expert &&
865 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
866 opt.def_digest_algo,
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 );
873 else
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
895 DSA2 anyway. */
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
905 largest q */
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)
912 smartcard = 1;
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))
923 if ( (algo=
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));
934 if( !multifile )
935 iobuf_push_filter( inp, md_filter, &mfx );
937 if( detached && !encryptflag && !RFC1991 )
938 afx->what = 2;
940 if( opt.armor && !outfile )
941 push_armor_filter (afx, out);
943 if( encryptflag ) {
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 */
954 if(compr_algo==-1)
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
961 default. */
963 if((compr_algo=
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 */
975 if( compr_algo )
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);
983 if (rc)
984 goto leave;
987 write_status_begin_signing (mfx.md);
989 /* Setup the inner packet. */
990 if( detached ) {
991 if( multifile ) {
992 strlist_t sl;
994 if( opt.verbose )
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)))
1002 iobuf_close (inp);
1003 inp = NULL;
1004 errno = EPERM;
1006 if( !inp )
1008 rc = gpg_error_from_syserror ();
1009 log_error(_("can't open `%s': %s\n"),
1010 sl->d,strerror(errno));
1011 goto leave;
1013 handle_progress (pfx, inp, sl->d);
1014 if( opt.verbose )
1015 fprintf(stderr, " `%s'", sl->d );
1016 if(opt.textmode)
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;
1026 if( opt.verbose )
1027 putc( '\n', stderr );
1029 else {
1030 /* read, so that the filter can calculate the digest */
1031 while( iobuf_get(inp) != -1 )
1035 else {
1036 rc = write_plaintext_packet (out, inp, fname,
1037 opt.textmode && !outfile ? 't':'b');
1040 /* catch errors from above */
1041 if (rc)
1042 goto leave;
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');
1048 if( rc )
1049 goto leave;
1052 leave:
1053 if( rc )
1054 iobuf_cancel(out);
1055 else {
1056 iobuf_close(out);
1057 if (encryptflag)
1058 write_status( STATUS_END_ENCRYPTION );
1060 iobuf_close(inp);
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);
1067 return rc;
1072 /****************
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;
1082 PACKET pkt;
1083 int rc = 0;
1084 SK_LIST sk_list = NULL;
1085 SK_LIST sk_rover = NULL;
1086 int old_style = RFC1991;
1087 int only_md5 = 0;
1088 u32 duration=0;
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);
1098 else
1099 duration=parse_expire_string(opt.def_sig_expire);
1102 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
1103 goto leave;
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)))
1119 iobuf_close (inp);
1120 inp = NULL;
1121 errno = EPERM;
1123 if( !inp ) {
1124 rc = gpg_error_from_syserror ();
1125 log_error (_("can't open `%s': %s\n"),
1126 fname? fname: "[stdin]", strerror(errno) );
1127 goto leave;
1129 handle_progress (pfx, inp, fname);
1131 if( outfile ) {
1132 if (is_secured_filename (outfile) ) {
1133 outfile = NULL;
1134 errno = EPERM;
1136 else
1137 out = iobuf_create( outfile );
1138 if( !out )
1140 rc = gpg_error_from_syserror ();
1141 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
1142 goto leave;
1144 else if( opt.verbose )
1145 log_info(_("writing to `%s'\n"), outfile );
1147 else if( (rc = open_outfile( fname, 1, &out )) )
1148 goto leave;
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 )
1155 only_md5 = 1;
1156 else {
1157 only_md5 = 0;
1158 break;
1162 if( !(old_style && only_md5) ) {
1163 const char *s;
1164 int any = 0;
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 );
1175 if( s ) {
1176 hashs_seen[ i & 0xff ] = 1;
1177 if( any )
1178 iobuf_put(out, ',' );
1179 iobuf_writestr(out, s );
1180 any = 1;
1184 assert(any);
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) )
1194 BUG ();
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));
1199 if ( DBG_HASHING )
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 */
1207 afx->what = 2;
1208 push_armor_filter (afx, out);
1210 /* write the signatures */
1211 rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
1212 if( rc )
1213 goto leave;
1215 leave:
1216 if( rc )
1217 iobuf_cancel(out);
1218 else
1219 iobuf_close(out);
1220 iobuf_close(inp);
1221 gcry_md_close ( textmd );
1222 release_sk_list( sk_list );
1223 release_progress_context (pfx);
1224 release_armor_context (afx);
1225 return rc;
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;
1242 PACKET pkt;
1243 STRING2KEY *s2k = NULL;
1244 int rc = 0;
1245 SK_LIST sk_list = NULL;
1246 SK_LIST sk_rover = NULL;
1247 int algo;
1248 u32 duration=0;
1249 int canceled;
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);
1263 else
1264 duration=parse_expire_string(opt.def_sig_expire);
1267 rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
1268 if (rc)
1269 goto leave;
1271 /* prepare iobufs */
1272 inp = iobuf_open(fname);
1273 if (inp && is_secured_file (iobuf_get_fd (inp)))
1275 iobuf_close (inp);
1276 inp = NULL;
1277 errno = EPERM;
1279 if( !inp ) {
1280 rc = gpg_error_from_syserror ();
1281 log_error (_("can't open `%s': %s\n"),
1282 fname? fname: "[stdin]", strerror(errno) );
1283 goto leave;
1285 handle_progress (pfx, inp, fname);
1287 /* prepare key */
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) );
1301 goto leave;
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. */
1308 if(opt.force_mdc)
1309 cfx.dek->use_mdc=1;
1311 /* now create the outfile */
1312 rc = open_outfile (fname, opt.armor? 1:0, &out);
1313 if (rc)
1314 goto leave;
1316 /* prepare to calculate the MD over the input */
1317 if (opt.textmode)
1318 iobuf_push_filter (inp, text_filter, &tfx);
1319 if ( gcry_md_open (&mfx.md, 0, 0) )
1320 BUG ();
1321 if ( DBG_HASHING )
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 */
1332 if (opt.armor)
1333 push_armor_filter (afx, out);
1335 /* Write the symmetric key packet */
1336 /*(current filters: armor)*/
1337 if (!RFC1991) {
1338 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1339 enc->version = 4;
1340 enc->cipher_algo = cfx.dek->algo;
1341 enc->s2k = *s2k;
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) );
1346 xfree(enc);
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)*/
1358 if (!RFC1991) {
1359 rc = write_onepass_sig_packets (sk_list, out,
1360 opt.textmode? 0x01:0x00);
1361 if (rc)
1362 goto leave;
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');
1370 if (rc)
1371 goto leave;
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,
1377 0, duration, 'S');
1378 if( rc )
1379 goto leave;
1382 leave:
1383 if( rc )
1384 iobuf_cancel(out);
1385 else {
1386 iobuf_close(out);
1387 write_status( STATUS_END_ENCRYPTION );
1389 iobuf_close(inp);
1390 release_sk_list( sk_list );
1391 gcry_md_close( mfx.md );
1392 xfree(cfx.dek);
1393 xfree(s2k);
1394 release_progress_context (pfx);
1395 release_armor_context (afx);
1396 return rc;
1400 /****************
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,
1412 PKT_secret_key *sk,
1413 int sigclass, int digest_algo,
1414 int sigversion, u32 timestamp, u32 duration,
1415 int (*mksubpkt)(PKT_signature *, void *), void *opaque
1418 PKT_signature *sig;
1419 int rc=0;
1420 gcry_md_hd_t md;
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)
1427 sigversion = 4;
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;
1441 if( !digest_algo )
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);
1458 else
1459 digest_algo = DIGEST_ALGO_SHA1;
1462 if ( gcry_md_open (&md, digest_algo, 0 ) )
1463 BUG ();
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;
1486 if(timestamp)
1487 sig->timestamp=timestamp;
1488 else
1489 sig->timestamp=make_timestamp();
1490 if(duration)
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 );
1503 if( !rc ) {
1504 hash_sigversion_to_magic (md, sig);
1505 gcry_md_final (md);
1507 rc = complete_sig( sig, sk, md );
1510 gcry_md_close ( md );
1511 if( rc )
1512 free_seckey_enc( sig );
1513 else
1514 *ret_sig = sig;
1515 return rc;
1520 /****************
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,
1528 PKT_public_key *pk,
1529 PKT_user_id *uid,
1530 PKT_public_key *subpk,
1531 PKT_secret_key *sk,
1532 int (*mksubpkt)(PKT_signature *, void *),
1533 void *opaque )
1535 PKT_signature *sig;
1536 int rc=0;
1537 gcry_md_hd_t md;
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 ) )
1545 BUG ();
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 );
1552 else
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
1563 one. */
1564 while(sig->timestamp<=orig_sig->timestamp)
1566 sleep(1);
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 );
1582 if (mksubpkt)
1583 rc = (*mksubpkt)(sig, opaque);
1586 if (!rc) {
1587 hash_sigversion_to_magic (md, sig);
1588 gcry_md_final (md);
1590 rc = complete_sig( sig, sk, md );
1593 gcry_md_close (md);
1594 if( rc )
1595 free_seckey_enc (sig);
1596 else
1597 *ret_sig = sig;
1598 return rc;