* gpg.texi (GPG Configuration Options): Make http_proxy option
[gnupg.git] / g10 / sign.c
blob8ae9c0b28ffa42a99a486a8ed32e02b88714e502
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;
506 static void
507 print_status_sig_created ( PKT_secret_key *sk, PKT_signature *sig, int what )
509 byte array[MAX_FINGERPRINT_LEN], *p;
510 char buf[100+MAX_FINGERPRINT_LEN*2];
511 size_t i, n;
513 sprintf(buf, "%c %d %d %02x %lu ",
514 what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
515 (ulong)sig->timestamp );
517 fingerprint_from_sk( sk, array, &n );
518 p = buf + strlen(buf);
519 for(i=0; i < n ; i++ )
520 sprintf(p+2*i, "%02X", array[i] );
522 write_status_text( STATUS_SIG_CREATED, buf );
527 * Loop over the secret certificates in SK_LIST and build the one pass
528 * signature packets. OpenPGP says that the data should be bracket by
529 * the onepass-sig and signature-packet; so we build these onepass
530 * packet here in reverse order
532 static int
533 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
535 int skcount;
536 SK_LIST sk_rover;
538 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
539 skcount++;
541 for (; skcount; skcount--) {
542 PKT_secret_key *sk;
543 PKT_onepass_sig *ops;
544 PACKET pkt;
545 int i, rc;
547 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
548 if (++i == skcount)
549 break;
552 sk = sk_rover->sk;
553 ops = xmalloc_clear (sizeof *ops);
554 ops->sig_class = sigclass;
555 ops->digest_algo = hash_for (sk);
556 ops->pubkey_algo = sk->pubkey_algo;
557 keyid_from_sk (sk, ops->keyid);
558 ops->last = (skcount == 1);
560 init_packet(&pkt);
561 pkt.pkttype = PKT_ONEPASS_SIG;
562 pkt.pkt.onepass_sig = ops;
563 rc = build_packet (out, &pkt);
564 free_packet (&pkt);
565 if (rc) {
566 log_error ("build onepass_sig packet failed: %s\n",
567 g10_errstr(rc));
568 return rc;
572 return 0;
576 * Helper to write the plaintext (literal data) packet
578 static int
579 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
581 PKT_plaintext *pt = NULL;
582 u32 filesize;
583 int rc = 0;
585 if (!opt.no_literal)
586 pt=setup_plaintext_name(fname,inp);
588 /* try to calculate the length of the data */
589 if ( !iobuf_is_pipe_filename (fname) && *fname )
591 off_t tmpsize;
592 int overflow;
594 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
595 && !overflow )
596 log_info (_("WARNING: `%s' is an empty file\n"), fname);
598 /* We can't encode the length of very large files because
599 OpenPGP uses only 32 bit for file sizes. So if the size of
600 a file is larger than 2^32 minus some bytes for packet
601 headers, we switch to partial length encoding. */
602 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
603 filesize = tmpsize;
604 else
605 filesize = 0;
607 /* Because the text_filter modifies the length of the
608 * data, it is not possible to know the used length
609 * without a double read of the file - to avoid that
610 * we simple use partial length packets. */
611 if ( ptmode == 't' )
612 filesize = 0;
614 else
615 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
617 if (!opt.no_literal) {
618 PACKET pkt;
620 pt->timestamp = make_timestamp ();
621 pt->mode = ptmode;
622 pt->len = filesize;
623 pt->new_ctb = !pt->len && !RFC1991;
624 pt->buf = inp;
625 init_packet(&pkt);
626 pkt.pkttype = PKT_PLAINTEXT;
627 pkt.pkt.plaintext = pt;
628 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
629 if( (rc = build_packet (out, &pkt)) )
630 log_error ("build_packet(PLAINTEXT) failed: %s\n",
631 g10_errstr(rc) );
632 pt->buf = NULL;
634 else {
635 byte copy_buffer[4096];
636 int bytes_copied;
638 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
639 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
640 log_error ("copying input to output failed: %s\n",
641 gpg_strerror (rc));
642 break;
644 wipememory(copy_buffer,4096); /* burn buffer */
646 /* fixme: it seems that we never freed pt/pkt */
648 return rc;
652 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
653 * hash which will not be changes here.
655 static int
656 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
657 int sigclass, u32 timestamp, u32 duration,
658 int status_letter)
660 SK_LIST sk_rover;
662 /* loop over the secret certificates */
663 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
664 PKT_secret_key *sk;
665 PKT_signature *sig;
666 gcry_md_hd_t md;
667 int rc;
669 sk = sk_rover->sk;
671 /* build the signature packet */
672 sig = xmalloc_clear (sizeof *sig);
673 if(opt.force_v3_sigs || RFC1991)
674 sig->version=3;
675 else if(duration || opt.sig_policy_url
676 || opt.sig_notations || opt.sig_keyserver_url)
677 sig->version=4;
678 else
679 sig->version=sk->version;
680 keyid_from_sk (sk, sig->keyid);
681 sig->digest_algo = hash_for(sk);
682 sig->pubkey_algo = sk->pubkey_algo;
683 if(timestamp)
684 sig->timestamp = timestamp;
685 else
686 sig->timestamp = make_timestamp();
687 if(duration)
688 sig->expiredate = sig->timestamp+duration;
689 sig->sig_class = sigclass;
691 if (gcry_md_copy (&md, hash))
692 BUG ();
694 if (sig->version >= 4)
695 build_sig_subpkt_from_sig (sig);
696 mk_notation_policy_etc (sig, NULL, sk);
698 hash_sigversion_to_magic (md, sig);
699 gcry_md_final (md);
701 rc = do_sign( sk, sig, md, hash_for (sk) );
702 gcry_md_close (md);
703 if( !rc ) { /* and write it */
704 PACKET pkt;
706 init_packet(&pkt);
707 pkt.pkttype = PKT_SIGNATURE;
708 pkt.pkt.signature = sig;
709 rc = build_packet (out, &pkt);
710 if (!rc && is_status_enabled()) {
711 print_status_sig_created ( sk, sig, status_letter);
713 free_packet (&pkt);
714 if (rc)
715 log_error ("build signature packet failed: %s\n",
716 g10_errstr(rc) );
718 if( rc )
719 return rc;;
722 return 0;
725 /****************
726 * Sign the files whose names are in FILENAME.
727 * If DETACHED has the value true,
728 * make a detached signature. If FILENAMES->d is NULL read from stdin
729 * and ignore the detached mode. Sign the file with all secret keys
730 * which can be taken from LOCUSR, if this is NULL, use the default one
731 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
732 * signed data for these users.
733 * If OUTFILE is not NULL; this file is used for output and the function
734 * does not ask for overwrite permission; output is then always
735 * uncompressed, non-armored and in binary mode.
738 sign_file( strlist_t filenames, int detached, strlist_t locusr,
739 int encryptflag, strlist_t remusr, const char *outfile )
741 const char *fname;
742 armor_filter_context_t *afx;
743 compress_filter_context_t zfx;
744 md_filter_context_t mfx;
745 text_filter_context_t tfx;
746 progress_filter_context_t *pfx;
747 encrypt_filter_context_t efx;
748 IOBUF inp = NULL, out = NULL;
749 PACKET pkt;
750 int rc = 0;
751 PK_LIST pk_list = NULL;
752 SK_LIST sk_list = NULL;
753 SK_LIST sk_rover = NULL;
754 int multifile = 0;
755 u32 duration=0;
757 pfx = new_progress_context ();
758 afx = new_armor_context ();
759 memset( &zfx, 0, sizeof zfx);
760 memset( &mfx, 0, sizeof mfx);
761 memset( &efx, 0, sizeof efx);
762 init_packet( &pkt );
764 if( filenames ) {
765 fname = filenames->d;
766 multifile = !!filenames->next;
768 else
769 fname = NULL;
771 if( fname && filenames->next && (!detached || encryptflag) )
772 log_bug("multiple files can only be detached signed");
774 if(encryptflag==2
775 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
776 goto leave;
778 if(!opt.force_v3_sigs && !RFC1991)
780 if(opt.ask_sig_expire && !opt.batch)
781 duration=ask_expire_interval(1,opt.def_sig_expire);
782 else
783 duration=parse_expire_string(opt.def_sig_expire);
786 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
787 goto leave;
789 if(PGP2 && !only_old_style(sk_list))
791 log_info(_("you can only detach-sign with PGP 2.x style keys "
792 "while in --pgp2 mode\n"));
793 compliance_failure();
796 if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC )))
797 goto leave;
799 /* prepare iobufs */
800 if( multifile ) /* have list of filenames */
801 inp = NULL; /* we do it later */
802 else {
803 inp = iobuf_open(fname);
804 if (inp && is_secured_file (iobuf_get_fd (inp)))
806 iobuf_close (inp);
807 inp = NULL;
808 errno = EPERM;
810 if( !inp )
812 rc = gpg_error_from_syserror ();
813 log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
814 strerror(errno) );
815 goto leave;
818 handle_progress (pfx, inp, fname);
821 if( outfile ) {
822 if (is_secured_filename ( outfile )) {
823 out = NULL;
824 errno = EPERM;
826 else
827 out = iobuf_create( outfile );
828 if( !out )
830 rc = gpg_error_from_syserror ();
831 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
832 goto leave;
834 else if( opt.verbose )
835 log_info(_("writing to `%s'\n"), outfile );
837 else if( (rc = open_outfile( fname, opt.armor? 1: detached? 2:0, &out )))
838 goto leave;
840 /* prepare to calculate the MD over the input */
841 if( opt.textmode && !outfile && !multifile )
843 memset( &tfx, 0, sizeof tfx);
844 iobuf_push_filter( inp, text_filter, &tfx );
847 if ( gcry_md_open (&mfx.md, 0, 0) )
848 BUG ();
849 if (DBG_HASHING)
850 gcry_md_start_debug (mfx.md, "sign");
852 /* If we're encrypting and signing, it is reasonable to pick the
853 hash algorithm to use out of the recepient key prefs. This is
854 best effort only, as in a DSA2 and smartcard world there are
855 cases where we cannot please everyone with a single hash (DSA2
856 wants >160 and smartcards want =160). In the future this could
857 be more complex with different hashes for each sk, but the
858 current design requires a single hash for all SKs. */
859 if(pk_list)
861 if(opt.def_digest_algo)
863 if(!opt.expert &&
864 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
865 opt.def_digest_algo,
866 NULL)!=opt.def_digest_algo)
867 log_info(_("WARNING: forcing digest algorithm %s (%d)"
868 " violates recipient preferences\n"),
869 gcry_md_algo_name (opt.def_digest_algo),
870 opt.def_digest_algo );
872 else
874 int algo, smartcard=0;
875 union pref_hint hint;
877 hint.digest_length = 0;
879 /* Of course, if the recipient asks for something
880 unreasonable (like the wrong hash for a DSA key) then
881 don't do it. Check all sk's - if any are DSA or live
882 on a smartcard, then the hash has restrictions and we
883 may not be able to give the recipient what they want.
884 For DSA, pass a hint for the largest q we have. Note
885 that this means that a q>160 key will override a q=160
886 key and force the use of truncation for the q=160 key.
887 The alternative would be to ignore the recipient prefs
888 completely and get a different hash for each DSA key in
889 hash_for(). The override behavior here is more or less
890 reasonable as it is under the control of the user which
891 keys they sign with for a given message and the fact
892 that the message with multiple signatures won't be
893 usable on an implementation that doesn't understand
894 DSA2 anyway. */
896 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
898 if (sk_rover->sk->pubkey_algo == PUBKEY_ALGO_DSA)
900 int temp_hashlen = gcry_mpi_get_nbits
901 (sk_rover->sk->skey[1])+7/8;
903 /* Pick a hash that is large enough for our
904 largest q */
906 if (hint.digest_length<temp_hashlen)
907 hint.digest_length=temp_hashlen;
909 else if (sk_rover->sk->is_protected
910 && sk_rover->sk->protect.s2k.mode == 1002)
911 smartcard = 1;
914 /* Current smartcards only do 160-bit hashes. If we have
915 to have a >160-bit hash, then we can't use the
916 recipient prefs as we'd need both =160 and >160 at the
917 same time and recipient prefs currently require a
918 single hash for all signatures. All this may well have
919 to change as the cards add algorithms. */
921 if (!smartcard || (smartcard && hint.digest_length==20))
922 if ( (algo=
923 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
924 recipient_digest_algo=algo;
928 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
929 PKT_secret_key *sk = sk_rover->sk;
930 gcry_md_enable (mfx.md, hash_for(sk));
933 if( !multifile )
934 iobuf_push_filter( inp, md_filter, &mfx );
936 if( detached && !encryptflag && !RFC1991 )
937 afx->what = 2;
939 if( opt.armor && !outfile )
940 push_armor_filter (afx, out);
942 if( encryptflag ) {
943 efx.pk_list = pk_list;
944 /* fixme: set efx.cfx.datalen if known */
945 iobuf_push_filter( out, encrypt_filter, &efx );
948 if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) )
950 int compr_algo=opt.compress_algo;
952 /* If not forced by user */
953 if(compr_algo==-1)
955 /* If we're not encrypting, then select_algo_from_prefs
956 will fail and we'll end up with the default. If we are
957 encrypting, select_algo_from_prefs cannot fail since
958 there is an assumed preference for uncompressed data.
959 Still, if it did fail, we'll also end up with the
960 default. */
962 if((compr_algo=
963 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
964 compr_algo=default_compress_algo();
966 else if(!opt.expert && pk_list
967 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
968 compr_algo,NULL)!=compr_algo)
969 log_info(_("WARNING: forcing compression algorithm %s (%d)"
970 " violates recipient preferences\n"),
971 compress_algo_to_string(compr_algo),compr_algo);
973 /* algo 0 means no compression */
974 if( compr_algo )
975 push_compress_filter(out,&zfx,compr_algo);
978 /* Write the one-pass signature packets if needed */
979 if (!detached && !RFC1991) {
980 rc = write_onepass_sig_packets (sk_list, out,
981 opt.textmode && !outfile ? 0x01:0x00);
982 if (rc)
983 goto leave;
986 write_status (STATUS_BEGIN_SIGNING);
988 /* Setup the inner packet. */
989 if( detached ) {
990 if( multifile ) {
991 strlist_t sl;
993 if( opt.verbose )
994 log_info(_("signing:") );
995 /* must walk reverse trough this list */
996 for( sl = strlist_last(filenames); sl;
997 sl = strlist_prev( filenames, sl ) ) {
998 inp = iobuf_open(sl->d);
999 if (inp && is_secured_file (iobuf_get_fd (inp)))
1001 iobuf_close (inp);
1002 inp = NULL;
1003 errno = EPERM;
1005 if( !inp )
1007 rc = gpg_error_from_syserror ();
1008 log_error(_("can't open `%s': %s\n"),
1009 sl->d,strerror(errno));
1010 goto leave;
1012 handle_progress (pfx, inp, sl->d);
1013 if( opt.verbose )
1014 fprintf(stderr, " `%s'", sl->d );
1015 if(opt.textmode)
1017 memset( &tfx, 0, sizeof tfx);
1018 iobuf_push_filter( inp, text_filter, &tfx );
1020 iobuf_push_filter( inp, md_filter, &mfx );
1021 while( iobuf_get(inp) != -1 )
1023 iobuf_close(inp); inp = NULL;
1025 if( opt.verbose )
1026 putc( '\n', stderr );
1028 else {
1029 /* read, so that the filter can calculate the digest */
1030 while( iobuf_get(inp) != -1 )
1034 else {
1035 rc = write_plaintext_packet (out, inp, fname,
1036 opt.textmode && !outfile ? 't':'b');
1039 /* catch errors from above */
1040 if (rc)
1041 goto leave;
1043 /* write the signatures */
1044 rc = write_signature_packets (sk_list, out, mfx.md,
1045 opt.textmode && !outfile? 0x01 : 0x00,
1046 0, duration, detached ? 'D':'S');
1047 if( rc )
1048 goto leave;
1051 leave:
1052 if( rc )
1053 iobuf_cancel(out);
1054 else {
1055 iobuf_close(out);
1056 if (encryptflag)
1057 write_status( STATUS_END_ENCRYPTION );
1059 iobuf_close(inp);
1060 gcry_md_close ( mfx.md );
1061 release_sk_list( sk_list );
1062 release_pk_list( pk_list );
1063 recipient_digest_algo=0;
1064 release_progress_context (pfx);
1065 release_armor_context (afx);
1066 return rc;
1071 /****************
1072 * make a clear signature. note that opt.armor is not needed
1075 clearsign_file( const char *fname, strlist_t locusr, const char *outfile )
1077 armor_filter_context_t *afx;
1078 progress_filter_context_t *pfx;
1079 gcry_md_hd_t textmd = NULL;
1080 IOBUF inp = NULL, out = NULL;
1081 PACKET pkt;
1082 int rc = 0;
1083 SK_LIST sk_list = NULL;
1084 SK_LIST sk_rover = NULL;
1085 int old_style = RFC1991;
1086 int only_md5 = 0;
1087 u32 duration=0;
1089 pfx = new_progress_context ();
1090 afx = new_armor_context ();
1091 init_packet( &pkt );
1093 if(!opt.force_v3_sigs && !RFC1991)
1095 if(opt.ask_sig_expire && !opt.batch)
1096 duration=ask_expire_interval(1,opt.def_sig_expire);
1097 else
1098 duration=parse_expire_string(opt.def_sig_expire);
1101 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
1102 goto leave;
1104 if( !old_style && !duration )
1105 old_style = only_old_style( sk_list );
1107 if(PGP2 && !only_old_style(sk_list))
1109 log_info(_("you can only clearsign with PGP 2.x style keys "
1110 "while in --pgp2 mode\n"));
1111 compliance_failure();
1114 /* prepare iobufs */
1115 inp = iobuf_open(fname);
1116 if (inp && is_secured_file (iobuf_get_fd (inp)))
1118 iobuf_close (inp);
1119 inp = NULL;
1120 errno = EPERM;
1122 if( !inp ) {
1123 rc = gpg_error_from_syserror ();
1124 log_error (_("can't open `%s': %s\n"),
1125 fname? fname: "[stdin]", strerror(errno) );
1126 goto leave;
1128 handle_progress (pfx, inp, fname);
1130 if( outfile ) {
1131 if (is_secured_filename (outfile) ) {
1132 outfile = NULL;
1133 errno = EPERM;
1135 else
1136 out = iobuf_create( outfile );
1137 if( !out )
1139 rc = gpg_error_from_syserror ();
1140 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
1141 goto leave;
1143 else if( opt.verbose )
1144 log_info(_("writing to `%s'\n"), outfile );
1146 else if( (rc = open_outfile( fname, 1, &out )) )
1147 goto leave;
1149 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1151 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1152 PKT_secret_key *sk = sk_rover->sk;
1153 if( hash_for(sk) == DIGEST_ALGO_MD5 )
1154 only_md5 = 1;
1155 else {
1156 only_md5 = 0;
1157 break;
1161 if( !(old_style && only_md5) ) {
1162 const char *s;
1163 int any = 0;
1164 byte hashs_seen[256];
1166 memset( hashs_seen, 0, sizeof hashs_seen );
1167 iobuf_writestr(out, "Hash: " );
1168 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1169 PKT_secret_key *sk = sk_rover->sk;
1170 int i = hash_for(sk);
1172 if( !hashs_seen[ i & 0xff ] ) {
1173 s = gcry_md_algo_name ( i );
1174 if( s ) {
1175 hashs_seen[ i & 0xff ] = 1;
1176 if( any )
1177 iobuf_put(out, ',' );
1178 iobuf_writestr(out, s );
1179 any = 1;
1183 assert(any);
1184 iobuf_writestr(out, LF );
1187 if( opt.not_dash_escaped )
1188 iobuf_writestr( out,
1189 "NotDashEscaped: You need GnuPG to verify this message" LF );
1190 iobuf_writestr(out, LF );
1192 if ( gcry_md_open (&textmd, 0, 0) )
1193 BUG ();
1194 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1195 PKT_secret_key *sk = sk_rover->sk;
1196 gcry_md_enable (textmd, hash_for(sk));
1198 if ( DBG_HASHING )
1199 gcry_md_start_debug ( textmd, "clearsign" );
1201 copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
1202 opt.escape_from, (old_style && only_md5) );
1203 /* fixme: check for read errors */
1205 /* now write the armor */
1206 afx->what = 2;
1207 push_armor_filter (afx, out);
1209 /* write the signatures */
1210 rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
1211 if( rc )
1212 goto leave;
1214 leave:
1215 if( rc )
1216 iobuf_cancel(out);
1217 else
1218 iobuf_close(out);
1219 iobuf_close(inp);
1220 gcry_md_close ( textmd );
1221 release_sk_list( sk_list );
1222 release_progress_context (pfx);
1223 release_armor_context (afx);
1224 return rc;
1228 * Sign and conventionally encrypt the given file.
1229 * FIXME: Far too much code is duplicated - revamp the whole file.
1232 sign_symencrypt_file (const char *fname, strlist_t locusr)
1234 armor_filter_context_t *afx;
1235 progress_filter_context_t *pfx;
1236 compress_filter_context_t zfx;
1237 md_filter_context_t mfx;
1238 text_filter_context_t tfx;
1239 cipher_filter_context_t cfx;
1240 IOBUF inp = NULL, out = NULL;
1241 PACKET pkt;
1242 STRING2KEY *s2k = NULL;
1243 int rc = 0;
1244 SK_LIST sk_list = NULL;
1245 SK_LIST sk_rover = NULL;
1246 int algo;
1247 u32 duration=0;
1248 int canceled;
1250 pfx = new_progress_context ();
1251 afx = new_armor_context ();
1252 memset( &zfx, 0, sizeof zfx);
1253 memset( &mfx, 0, sizeof mfx);
1254 memset( &tfx, 0, sizeof tfx);
1255 memset( &cfx, 0, sizeof cfx);
1256 init_packet( &pkt );
1258 if(!opt.force_v3_sigs && !RFC1991)
1260 if(opt.ask_sig_expire && !opt.batch)
1261 duration=ask_expire_interval(1,opt.def_sig_expire);
1262 else
1263 duration=parse_expire_string(opt.def_sig_expire);
1266 rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
1267 if (rc)
1268 goto leave;
1270 /* prepare iobufs */
1271 inp = iobuf_open(fname);
1272 if (inp && is_secured_file (iobuf_get_fd (inp)))
1274 iobuf_close (inp);
1275 inp = NULL;
1276 errno = EPERM;
1278 if( !inp ) {
1279 rc = gpg_error_from_syserror ();
1280 log_error (_("can't open `%s': %s\n"),
1281 fname? fname: "[stdin]", strerror(errno) );
1282 goto leave;
1284 handle_progress (pfx, inp, fname);
1286 /* prepare key */
1287 s2k = xmalloc_clear( sizeof *s2k );
1288 s2k->mode = RFC1991? 0:opt.s2k_mode;
1289 s2k->hash_algo = S2K_DIGEST_ALGO;
1291 algo = default_cipher_algo();
1292 if (!opt.quiet || !opt.batch)
1293 log_info (_("%s encryption will be used\n"),
1294 gcry_cipher_algo_name (algo) );
1295 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
1297 if (!cfx.dek || !cfx.dek->keylen) {
1298 rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
1299 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1300 goto leave;
1303 /* We have no way to tell if the recipient can handle messages
1304 with an MDC, so this defaults to no. Perhaps in a few years,
1305 this can be defaulted to yes. Note that like regular
1306 encrypting, --force-mdc overrides --disable-mdc. */
1307 if(opt.force_mdc)
1308 cfx.dek->use_mdc=1;
1310 /* now create the outfile */
1311 rc = open_outfile (fname, opt.armor? 1:0, &out);
1312 if (rc)
1313 goto leave;
1315 /* prepare to calculate the MD over the input */
1316 if (opt.textmode)
1317 iobuf_push_filter (inp, text_filter, &tfx);
1318 if ( gcry_md_open (&mfx.md, 0, 0) )
1319 BUG ();
1320 if ( DBG_HASHING )
1321 gcry_md_start_debug (mfx.md, "symc-sign");
1323 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
1324 PKT_secret_key *sk = sk_rover->sk;
1325 gcry_md_enable (mfx.md, hash_for (sk));
1328 iobuf_push_filter (inp, md_filter, &mfx);
1330 /* Push armor output filter */
1331 if (opt.armor)
1332 push_armor_filter (afx, out);
1334 /* Write the symmetric key packet */
1335 /*(current filters: armor)*/
1336 if (!RFC1991) {
1337 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1338 enc->version = 4;
1339 enc->cipher_algo = cfx.dek->algo;
1340 enc->s2k = *s2k;
1341 pkt.pkttype = PKT_SYMKEY_ENC;
1342 pkt.pkt.symkey_enc = enc;
1343 if( (rc = build_packet( out, &pkt )) )
1344 log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
1345 xfree(enc);
1348 /* Push the encryption filter */
1349 iobuf_push_filter( out, cipher_filter, &cfx );
1351 /* Push the compress filter */
1352 if (default_compress_algo())
1353 push_compress_filter(out,&zfx,default_compress_algo());
1355 /* Write the one-pass signature packets */
1356 /*(current filters: zip - encrypt - armor)*/
1357 if (!RFC1991) {
1358 rc = write_onepass_sig_packets (sk_list, out,
1359 opt.textmode? 0x01:0x00);
1360 if (rc)
1361 goto leave;
1364 write_status (STATUS_BEGIN_SIGNING);
1366 /* Pipe data through all filters; i.e. write the signed stuff */
1367 /*(current filters: zip - encrypt - armor)*/
1368 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1369 if (rc)
1370 goto leave;
1372 /* Write the signatures */
1373 /*(current filters: zip - encrypt - armor)*/
1374 rc = write_signature_packets (sk_list, out, mfx.md,
1375 opt.textmode? 0x01 : 0x00,
1376 0, duration, 'S');
1377 if( rc )
1378 goto leave;
1381 leave:
1382 if( rc )
1383 iobuf_cancel(out);
1384 else {
1385 iobuf_close(out);
1386 write_status( STATUS_END_ENCRYPTION );
1388 iobuf_close(inp);
1389 release_sk_list( sk_list );
1390 gcry_md_close( mfx.md );
1391 xfree(cfx.dek);
1392 xfree(s2k);
1393 release_progress_context (pfx);
1394 release_armor_context (afx);
1395 return rc;
1399 /****************
1400 * Create a signature packet for the given public key certificate and
1401 * the user id and return it in ret_sig. User signature class SIGCLASS
1402 * user-id is not used (and may be NULL if sigclass is 0x20) If
1403 * DIGEST_ALGO is 0 the function selects an appropriate one.
1404 * SIGVERSION gives the minimal required signature packet version;
1405 * this is needed so that special properties like local sign are not
1406 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1407 * the timestamp to use for the signature. 0 means "now" */
1409 make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
1410 PKT_user_id *uid, PKT_public_key *subpk,
1411 PKT_secret_key *sk,
1412 int sigclass, int digest_algo,
1413 int sigversion, u32 timestamp, u32 duration,
1414 int (*mksubpkt)(PKT_signature *, void *), void *opaque
1417 PKT_signature *sig;
1418 int rc=0;
1419 gcry_md_hd_t md;
1421 assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1422 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1423 || sigclass == 0x30 || sigclass == 0x28 );
1425 if (opt.force_v4_certs)
1426 sigversion = 4;
1428 if (sigversion < sk->version)
1429 sigversion = sk->version;
1431 /* If you are making a signature on a v4 key using your v3 key, it
1432 doesn't make sense to generate a v3 sig. After all, no v3-only
1433 PGP implementation could understand the v4 key in the first
1434 place. Note that this implies that a signature on an attribute
1435 uid is usually going to be v4 as well, since they are not
1436 generally found on v3 keys. */
1437 if (sigversion < pk->version)
1438 sigversion = pk->version;
1440 if( !digest_algo )
1442 /* Basically, this means use SHA1 always unless it's a v3 RSA
1443 key making a v3 cert (use MD5), or the user specified
1444 something (use whatever they said), or it's DSA (use the
1445 best match). They still can't pick an inappropriate hash
1446 for DSA or the signature will fail. Note that this still
1447 allows the caller of make_keysig_packet to override the
1448 user setting if it must. */
1450 if(opt.cert_digest_algo)
1451 digest_algo=opt.cert_digest_algo;
1452 else if(sk->pubkey_algo==PUBKEY_ALGO_RSA
1453 && pk->version<4 && sigversion<4)
1454 digest_algo = DIGEST_ALGO_MD5;
1455 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
1456 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (sk->skey[1])/8);
1457 else
1458 digest_algo = DIGEST_ALGO_SHA1;
1461 if ( gcry_md_open (&md, digest_algo, 0 ) )
1462 BUG ();
1464 /* Hash the public key certificate. */
1465 hash_public_key( md, pk );
1467 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1469 /* hash the subkey binding/backsig/revocation */
1470 hash_public_key( md, subpk );
1472 else if( sigclass != 0x1F && sigclass != 0x20 )
1474 /* hash the user id */
1475 hash_uid (md, sigversion, uid);
1477 /* and make the signature packet */
1478 sig = xmalloc_clear( sizeof *sig );
1479 sig->version = sigversion;
1480 sig->flags.exportable=1;
1481 sig->flags.revocable=1;
1482 keyid_from_sk( sk, sig->keyid );
1483 sig->pubkey_algo = sk->pubkey_algo;
1484 sig->digest_algo = digest_algo;
1485 if(timestamp)
1486 sig->timestamp=timestamp;
1487 else
1488 sig->timestamp=make_timestamp();
1489 if(duration)
1490 sig->expiredate=sig->timestamp+duration;
1491 sig->sig_class = sigclass;
1492 if( sig->version >= 4 )
1493 build_sig_subpkt_from_sig( sig );
1494 mk_notation_policy_etc( sig, pk, sk );
1496 /* Crucial that the call to mksubpkt comes LAST before the calls
1497 to finalize the sig as that makes it possible for the mksubpkt
1498 function to get a reliable pointer to the subpacket area. */
1499 if( sig->version >= 4 && mksubpkt )
1500 rc = (*mksubpkt)( sig, opaque );
1502 if( !rc ) {
1503 hash_sigversion_to_magic (md, sig);
1504 gcry_md_final (md);
1506 rc = complete_sig( sig, sk, md );
1509 gcry_md_close ( md );
1510 if( rc )
1511 free_seckey_enc( sig );
1512 else
1513 *ret_sig = sig;
1514 return rc;
1519 /****************
1520 * Create a new signature packet based on an existing one.
1521 * Only user ID signatures are supported for now.
1522 * TODO: Merge this with make_keysig_packet.
1525 update_keysig_packet( PKT_signature **ret_sig,
1526 PKT_signature *orig_sig,
1527 PKT_public_key *pk,
1528 PKT_user_id *uid,
1529 PKT_public_key *subpk,
1530 PKT_secret_key *sk,
1531 int (*mksubpkt)(PKT_signature *, void *),
1532 void *opaque )
1534 PKT_signature *sig;
1535 int rc=0;
1536 gcry_md_hd_t md;
1538 if ((!orig_sig || !pk || !sk)
1539 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1540 || (orig_sig->sig_class == 0x18 && !subpk))
1541 return G10ERR_GENERAL;
1543 if ( gcry_md_open (&md, orig_sig->digest_algo, 0 ) )
1544 BUG ();
1546 /* Hash the public key certificate and the user id. */
1547 hash_public_key( md, pk );
1549 if( orig_sig->sig_class == 0x18 )
1550 hash_public_key( md, subpk );
1551 else
1552 hash_uid (md, orig_sig->version, uid);
1554 /* create a new signature packet */
1555 sig = copy_signature (NULL, orig_sig);
1557 /* We need to create a new timestamp so that new sig expiration
1558 calculations are done correctly... */
1559 sig->timestamp=make_timestamp();
1561 /* ... but we won't make a timestamp earlier than the existing
1562 one. */
1563 while(sig->timestamp<=orig_sig->timestamp)
1565 sleep(1);
1566 sig->timestamp=make_timestamp();
1569 /* Note that already expired sigs will remain expired (with a
1570 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1571 detects this case. */
1573 if( sig->version >= 4 )
1575 /* Put the updated timestamp into the sig. Note that this
1576 will automagically lower any sig expiration dates to
1577 correctly correspond to the differences in the timestamps
1578 (i.e. the duration will shrink). */
1579 build_sig_subpkt_from_sig( sig );
1581 if (mksubpkt)
1582 rc = (*mksubpkt)(sig, opaque);
1585 if (!rc) {
1586 hash_sigversion_to_magic (md, sig);
1587 gcry_md_final (md);
1589 rc = complete_sig( sig, sk, md );
1592 gcry_md_close (md);
1593 if( rc )
1594 free_seckey_enc (sig);
1595 else
1596 *ret_sig = sig;
1597 return rc;