2006-09-24 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / sign.c
blob07947b894c51c907951168ff05f44ff67f1b54f1
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 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 filenames, int detached, STRLIST locusr,
739 int encryptflag, STRLIST 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 memset( &afx, 0, sizeof afx);
758 memset( &zfx, 0, sizeof zfx);
759 memset( &mfx, 0, sizeof mfx);
760 memset( &efx, 0, sizeof efx);
761 init_packet( &pkt );
763 if( filenames ) {
764 fname = filenames->d;
765 multifile = !!filenames->next;
767 else
768 fname = NULL;
770 if( fname && filenames->next && (!detached || encryptflag) )
771 log_bug("multiple files can only be detached signed");
773 if(encryptflag==2
774 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
775 goto leave;
777 if(!opt.force_v3_sigs && !RFC1991)
779 if(opt.ask_sig_expire && !opt.batch)
780 duration=ask_expire_interval(1,opt.def_sig_expire);
781 else
782 duration=parse_expire_string(opt.def_sig_expire);
785 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
786 goto leave;
788 if(PGP2 && !only_old_style(sk_list))
790 log_info(_("you can only detach-sign with PGP 2.x style keys "
791 "while in --pgp2 mode\n"));
792 compliance_failure();
795 if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC )))
796 goto leave;
798 /* prepare iobufs */
799 if( multifile ) /* have list of filenames */
800 inp = NULL; /* we do it later */
801 else {
802 inp = iobuf_open(fname);
803 if (inp && is_secured_file (iobuf_get_fd (inp)))
805 iobuf_close (inp);
806 inp = NULL;
807 errno = EPERM;
809 if( !inp )
811 rc = gpg_error_from_syserror ();
812 log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
813 strerror(errno) );
814 goto leave;
817 handle_progress (&pfx, inp, fname);
820 if( outfile ) {
821 if (is_secured_filename ( outfile )) {
822 out = NULL;
823 errno = EPERM;
825 else
826 out = iobuf_create( outfile );
827 if( !out )
829 rc = gpg_error_from_syserror ();
830 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
831 goto leave;
833 else if( opt.verbose )
834 log_info(_("writing to `%s'\n"), outfile );
836 else if( (rc = open_outfile( fname, opt.armor? 1: detached? 2:0, &out )))
837 goto leave;
839 /* prepare to calculate the MD over the input */
840 if( opt.textmode && !outfile && !multifile )
842 memset( &tfx, 0, sizeof tfx);
843 iobuf_push_filter( inp, text_filter, &tfx );
846 if ( gcry_md_open (&mfx.md, 0, 0) )
847 BUG ();
848 if (DBG_HASHING)
849 gcry_md_start_debug (mfx.md, "sign");
851 /* If we're encrypting and signing, it is reasonable to pick the
852 hash algorithm to use out of the recepient key prefs. This is
853 best effort only, as in a DSA2 and smartcard world there are
854 cases where we cannot please everyone with a single hash (DSA2
855 wants >160 and smartcards want =160). In the future this could
856 be more complex with different hashes for each sk, but the
857 current design requires a single hash for all SKs. */
858 if(pk_list)
860 if(opt.def_digest_algo)
862 if(!opt.expert &&
863 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
864 opt.def_digest_algo,
865 NULL)!=opt.def_digest_algo)
866 log_info(_("WARNING: forcing digest algorithm %s (%d)"
867 " violates recipient preferences\n"),
868 gcry_md_algo_name (opt.def_digest_algo),
869 opt.def_digest_algo );
871 else
873 int algo, smartcard=0;
874 union pref_hint hint;
876 hint.digest_length = 0;
878 /* Of course, if the recipient asks for something
879 unreasonable (like the wrong hash for a DSA key) then
880 don't do it. Check all sk's - if any are DSA or live
881 on a smartcard, then the hash has restrictions and we
882 may not be able to give the recipient what they want.
883 For DSA, pass a hint for the largest q we have. Note
884 that this means that a q>160 key will override a q=160
885 key and force the use of truncation for the q=160 key.
886 The alternative would be to ignore the recipient prefs
887 completely and get a different hash for each DSA key in
888 hash_for(). The override behavior here is more or less
889 reasonable as it is under the control of the user which
890 keys they sign with for a given message and the fact
891 that the message with multiple signatures won't be
892 usable on an implementation that doesn't understand
893 DSA2 anyway. */
895 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
897 if (sk_rover->sk->pubkey_algo == PUBKEY_ALGO_DSA)
899 int temp_hashlen = gcry_mpi_get_nbits
900 (sk_rover->sk->skey[1])+7/8;
902 /* Pick a hash that is large enough for our
903 largest q */
905 if (hint.digest_length<temp_hashlen)
906 hint.digest_length=temp_hashlen;
908 else if (sk_rover->sk->is_protected
909 && sk_rover->sk->protect.s2k.mode == 1002)
910 smartcard = 1;
913 /* Current smartcards only do 160-bit hashes. If we have
914 to have a >160-bit hash, then we can't use the
915 recipient prefs as we'd need both =160 and >160 at the
916 same time and recipient prefs currently require a
917 single hash for all signatures. All this may well have
918 to change as the cards add algorithms. */
920 if (!smartcard || (smartcard && hint.digest_length==20))
921 if ( (algo=
922 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
923 recipient_digest_algo=algo;
927 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
928 PKT_secret_key *sk = sk_rover->sk;
929 gcry_md_enable (mfx.md, hash_for(sk));
932 if( !multifile )
933 iobuf_push_filter( inp, md_filter, &mfx );
935 if( detached && !encryptflag && !RFC1991 )
936 afx.what = 2;
938 if( opt.armor && !outfile )
939 iobuf_push_filter( out, armor_filter, &afx );
941 if( encryptflag ) {
942 efx.pk_list = pk_list;
943 /* fixme: set efx.cfx.datalen if known */
944 iobuf_push_filter( out, encrypt_filter, &efx );
947 if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) )
949 int compr_algo=opt.compress_algo;
951 /* If not forced by user */
952 if(compr_algo==-1)
954 /* If we're not encrypting, then select_algo_from_prefs
955 will fail and we'll end up with the default. If we are
956 encrypting, select_algo_from_prefs cannot fail since
957 there is an assumed preference for uncompressed data.
958 Still, if it did fail, we'll also end up with the
959 default. */
961 if((compr_algo=
962 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
963 compr_algo=default_compress_algo();
965 else if(!opt.expert && pk_list
966 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
967 compr_algo,NULL)!=compr_algo)
968 log_info(_("WARNING: forcing compression algorithm %s (%d)"
969 " violates recipient preferences\n"),
970 compress_algo_to_string(compr_algo),compr_algo);
972 /* algo 0 means no compression */
973 if( compr_algo )
974 push_compress_filter(out,&zfx,compr_algo);
977 /* Write the one-pass signature packets if needed */
978 if (!detached && !RFC1991) {
979 rc = write_onepass_sig_packets (sk_list, out,
980 opt.textmode && !outfile ? 0x01:0x00);
981 if (rc)
982 goto leave;
985 write_status (STATUS_BEGIN_SIGNING);
987 /* Setup the inner packet. */
988 if( detached ) {
989 if( multifile ) {
990 STRLIST sl;
992 if( opt.verbose )
993 log_info(_("signing:") );
994 /* must walk reverse trough this list */
995 for( sl = strlist_last(filenames); sl;
996 sl = strlist_prev( filenames, sl ) ) {
997 inp = iobuf_open(sl->d);
998 if (inp && is_secured_file (iobuf_get_fd (inp)))
1000 iobuf_close (inp);
1001 inp = NULL;
1002 errno = EPERM;
1004 if( !inp )
1006 rc = gpg_error_from_syserror ();
1007 log_error(_("can't open `%s': %s\n"),
1008 sl->d,strerror(errno));
1009 goto leave;
1011 handle_progress (&pfx, inp, sl->d);
1012 if( opt.verbose )
1013 fprintf(stderr, " `%s'", sl->d );
1014 if(opt.textmode)
1016 memset( &tfx, 0, sizeof tfx);
1017 iobuf_push_filter( inp, text_filter, &tfx );
1019 iobuf_push_filter( inp, md_filter, &mfx );
1020 while( iobuf_get(inp) != -1 )
1022 iobuf_close(inp); inp = NULL;
1024 if( opt.verbose )
1025 putc( '\n', stderr );
1027 else {
1028 /* read, so that the filter can calculate the digest */
1029 while( iobuf_get(inp) != -1 )
1033 else {
1034 rc = write_plaintext_packet (out, inp, fname,
1035 opt.textmode && !outfile ? 't':'b');
1038 /* catch errors from above */
1039 if (rc)
1040 goto leave;
1042 /* write the signatures */
1043 rc = write_signature_packets (sk_list, out, mfx.md,
1044 opt.textmode && !outfile? 0x01 : 0x00,
1045 0, duration, detached ? 'D':'S');
1046 if( rc )
1047 goto leave;
1050 leave:
1051 if( rc )
1052 iobuf_cancel(out);
1053 else {
1054 iobuf_close(out);
1055 if (encryptflag)
1056 write_status( STATUS_END_ENCRYPTION );
1058 iobuf_close(inp);
1059 gcry_md_close ( mfx.md );
1060 release_sk_list( sk_list );
1061 release_pk_list( pk_list );
1062 recipient_digest_algo=0;
1063 return rc;
1068 /****************
1069 * make a clear signature. note that opt.armor is not needed
1072 clearsign_file( const char *fname, STRLIST locusr, const char *outfile )
1074 armor_filter_context_t afx;
1075 progress_filter_context_t pfx;
1076 gcry_md_hd_t textmd = NULL;
1077 IOBUF inp = NULL, out = NULL;
1078 PACKET pkt;
1079 int rc = 0;
1080 SK_LIST sk_list = NULL;
1081 SK_LIST sk_rover = NULL;
1082 int old_style = RFC1991;
1083 int only_md5 = 0;
1084 u32 duration=0;
1086 memset( &afx, 0, sizeof afx);
1087 init_packet( &pkt );
1089 if(!opt.force_v3_sigs && !RFC1991)
1091 if(opt.ask_sig_expire && !opt.batch)
1092 duration=ask_expire_interval(1,opt.def_sig_expire);
1093 else
1094 duration=parse_expire_string(opt.def_sig_expire);
1097 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
1098 goto leave;
1100 if( !old_style && !duration )
1101 old_style = only_old_style( sk_list );
1103 if(PGP2 && !only_old_style(sk_list))
1105 log_info(_("you can only clearsign with PGP 2.x style keys "
1106 "while in --pgp2 mode\n"));
1107 compliance_failure();
1110 /* prepare iobufs */
1111 inp = iobuf_open(fname);
1112 if (inp && is_secured_file (iobuf_get_fd (inp)))
1114 iobuf_close (inp);
1115 inp = NULL;
1116 errno = EPERM;
1118 if( !inp ) {
1119 rc = gpg_error_from_syserror ();
1120 log_error (_("can't open `%s': %s\n"),
1121 fname? fname: "[stdin]", strerror(errno) );
1122 goto leave;
1124 handle_progress (&pfx, inp, fname);
1126 if( outfile ) {
1127 if (is_secured_filename (outfile) ) {
1128 outfile = NULL;
1129 errno = EPERM;
1131 else
1132 out = iobuf_create( outfile );
1133 if( !out )
1135 rc = gpg_error_from_syserror ();
1136 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
1137 goto leave;
1139 else if( opt.verbose )
1140 log_info(_("writing to `%s'\n"), outfile );
1142 else if( (rc = open_outfile( fname, 1, &out )) )
1143 goto leave;
1145 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1147 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1148 PKT_secret_key *sk = sk_rover->sk;
1149 if( hash_for(sk) == DIGEST_ALGO_MD5 )
1150 only_md5 = 1;
1151 else {
1152 only_md5 = 0;
1153 break;
1157 if( !(old_style && only_md5) ) {
1158 const char *s;
1159 int any = 0;
1160 byte hashs_seen[256];
1162 memset( hashs_seen, 0, sizeof hashs_seen );
1163 iobuf_writestr(out, "Hash: " );
1164 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1165 PKT_secret_key *sk = sk_rover->sk;
1166 int i = hash_for(sk);
1168 if( !hashs_seen[ i & 0xff ] ) {
1169 s = gcry_md_algo_name ( i );
1170 if( s ) {
1171 hashs_seen[ i & 0xff ] = 1;
1172 if( any )
1173 iobuf_put(out, ',' );
1174 iobuf_writestr(out, s );
1175 any = 1;
1179 assert(any);
1180 iobuf_writestr(out, LF );
1183 if( opt.not_dash_escaped )
1184 iobuf_writestr( out,
1185 "NotDashEscaped: You need GnuPG to verify this message" LF );
1186 iobuf_writestr(out, LF );
1188 if ( gcry_md_open (&textmd, 0, 0) )
1189 BUG ();
1190 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1191 PKT_secret_key *sk = sk_rover->sk;
1192 gcry_md_enable (textmd, hash_for(sk));
1194 if ( DBG_HASHING )
1195 gcry_md_start_debug ( textmd, "clearsign" );
1197 copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
1198 opt.escape_from, (old_style && only_md5) );
1199 /* fixme: check for read errors */
1201 /* now write the armor */
1202 afx.what = 2;
1203 iobuf_push_filter( out, armor_filter, &afx );
1205 /* write the signatures */
1206 rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
1207 if( rc )
1208 goto leave;
1210 leave:
1211 if( rc )
1212 iobuf_cancel(out);
1213 else
1214 iobuf_close(out);
1215 iobuf_close(inp);
1216 gcry_md_close ( textmd );
1217 release_sk_list( sk_list );
1218 return rc;
1222 * Sign and conventionally encrypt the given file.
1223 * FIXME: Far too much code is duplicated - revamp the whole file.
1226 sign_symencrypt_file (const char *fname, STRLIST locusr)
1228 armor_filter_context_t afx;
1229 progress_filter_context_t pfx;
1230 compress_filter_context_t zfx;
1231 md_filter_context_t mfx;
1232 text_filter_context_t tfx;
1233 cipher_filter_context_t cfx;
1234 IOBUF inp = NULL, out = NULL;
1235 PACKET pkt;
1236 STRING2KEY *s2k = NULL;
1237 int rc = 0;
1238 SK_LIST sk_list = NULL;
1239 SK_LIST sk_rover = NULL;
1240 int algo;
1241 u32 duration=0;
1243 memset( &afx, 0, sizeof afx);
1244 memset( &zfx, 0, sizeof zfx);
1245 memset( &mfx, 0, sizeof mfx);
1246 memset( &tfx, 0, sizeof tfx);
1247 memset( &cfx, 0, sizeof cfx);
1248 init_packet( &pkt );
1250 if(!opt.force_v3_sigs && !RFC1991)
1252 if(opt.ask_sig_expire && !opt.batch)
1253 duration=ask_expire_interval(1,opt.def_sig_expire);
1254 else
1255 duration=parse_expire_string(opt.def_sig_expire);
1258 rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
1259 if (rc)
1260 goto leave;
1262 /* prepare iobufs */
1263 inp = iobuf_open(fname);
1264 if (inp && is_secured_file (iobuf_get_fd (inp)))
1266 iobuf_close (inp);
1267 inp = NULL;
1268 errno = EPERM;
1270 if( !inp ) {
1271 rc = gpg_error_from_syserror ();
1272 log_error (_("can't open `%s': %s\n"),
1273 fname? fname: "[stdin]", strerror(errno) );
1274 goto leave;
1276 handle_progress (&pfx, inp, fname);
1278 /* prepare key */
1279 s2k = xmalloc_clear( sizeof *s2k );
1280 s2k->mode = RFC1991? 0:opt.s2k_mode;
1281 s2k->hash_algo = S2K_DIGEST_ALGO;
1283 algo = default_cipher_algo();
1284 if (!opt.quiet || !opt.batch)
1285 log_info (_("%s encryption will be used\n"),
1286 gcry_cipher_algo_name (algo) );
1287 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, NULL);
1289 if (!cfx.dek || !cfx.dek->keylen) {
1290 rc = gpg_error (GPG_ERR_BAD_PASSPHRASE);
1291 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1292 goto leave;
1295 /* We have no way to tell if the recipient can handle messages
1296 with an MDC, so this defaults to no. Perhaps in a few years,
1297 this can be defaulted to yes. Note that like regular
1298 encrypting, --force-mdc overrides --disable-mdc. */
1299 if(opt.force_mdc)
1300 cfx.dek->use_mdc=1;
1302 /* now create the outfile */
1303 rc = open_outfile (fname, opt.armor? 1:0, &out);
1304 if (rc)
1305 goto leave;
1307 /* prepare to calculate the MD over the input */
1308 if (opt.textmode)
1309 iobuf_push_filter (inp, text_filter, &tfx);
1310 if ( gcry_md_open (&mfx.md, 0, 0) )
1311 BUG ();
1312 if ( DBG_HASHING )
1313 gcry_md_start_debug (mfx.md, "symc-sign");
1315 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
1316 PKT_secret_key *sk = sk_rover->sk;
1317 gcry_md_enable (mfx.md, hash_for (sk));
1320 iobuf_push_filter (inp, md_filter, &mfx);
1322 /* Push armor output filter */
1323 if (opt.armor)
1324 iobuf_push_filter (out, armor_filter, &afx);
1326 /* Write the symmetric key packet */
1327 /*(current filters: armor)*/
1328 if (!RFC1991) {
1329 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1330 enc->version = 4;
1331 enc->cipher_algo = cfx.dek->algo;
1332 enc->s2k = *s2k;
1333 pkt.pkttype = PKT_SYMKEY_ENC;
1334 pkt.pkt.symkey_enc = enc;
1335 if( (rc = build_packet( out, &pkt )) )
1336 log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
1337 xfree(enc);
1340 /* Push the encryption filter */
1341 iobuf_push_filter( out, cipher_filter, &cfx );
1343 /* Push the compress filter */
1344 if (default_compress_algo())
1345 push_compress_filter(out,&zfx,default_compress_algo());
1347 /* Write the one-pass signature packets */
1348 /*(current filters: zip - encrypt - armor)*/
1349 if (!RFC1991) {
1350 rc = write_onepass_sig_packets (sk_list, out,
1351 opt.textmode? 0x01:0x00);
1352 if (rc)
1353 goto leave;
1356 write_status (STATUS_BEGIN_SIGNING);
1358 /* Pipe data through all filters; i.e. write the signed stuff */
1359 /*(current filters: zip - encrypt - armor)*/
1360 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1361 if (rc)
1362 goto leave;
1364 /* Write the signatures */
1365 /*(current filters: zip - encrypt - armor)*/
1366 rc = write_signature_packets (sk_list, out, mfx.md,
1367 opt.textmode? 0x01 : 0x00,
1368 0, duration, 'S');
1369 if( rc )
1370 goto leave;
1373 leave:
1374 if( rc )
1375 iobuf_cancel(out);
1376 else {
1377 iobuf_close(out);
1378 write_status( STATUS_END_ENCRYPTION );
1380 iobuf_close(inp);
1381 release_sk_list( sk_list );
1382 gcry_md_close( mfx.md );
1383 xfree(cfx.dek);
1384 xfree(s2k);
1385 return rc;
1389 /****************
1390 * Create a signature packet for the given public key certificate and
1391 * the user id and return it in ret_sig. User signature class SIGCLASS
1392 * user-id is not used (and may be NULL if sigclass is 0x20) If
1393 * DIGEST_ALGO is 0 the function selects an appropriate one.
1394 * SIGVERSION gives the minimal required signature packet version;
1395 * this is needed so that special properties like local sign are not
1396 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1397 * the timestamp to use for the signature. 0 means "now" */
1399 make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
1400 PKT_user_id *uid, PKT_public_key *subpk,
1401 PKT_secret_key *sk,
1402 int sigclass, int digest_algo,
1403 int sigversion, u32 timestamp, u32 duration,
1404 int (*mksubpkt)(PKT_signature *, void *), void *opaque
1407 PKT_signature *sig;
1408 int rc=0;
1409 gcry_md_hd_t md;
1411 assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1412 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1413 || sigclass == 0x30 || sigclass == 0x28 );
1415 if (opt.force_v4_certs)
1416 sigversion = 4;
1418 if (sigversion < sk->version)
1419 sigversion = sk->version;
1421 /* If you are making a signature on a v4 key using your v3 key, it
1422 doesn't make sense to generate a v3 sig. After all, no v3-only
1423 PGP implementation could understand the v4 key in the first
1424 place. Note that this implies that a signature on an attribute
1425 uid is usually going to be v4 as well, since they are not
1426 generally found on v3 keys. */
1427 if (sigversion < pk->version)
1428 sigversion = pk->version;
1430 if( !digest_algo )
1432 /* Basically, this means use SHA1 always unless it's a v3 RSA
1433 key making a v3 cert (use MD5), or the user specified
1434 something (use whatever they said), or it's DSA (use the
1435 best match). They still can't pick an inappropriate hash
1436 for DSA or the signature will fail. Note that this still
1437 allows the caller of make_keysig_packet to override the
1438 user setting if it must. */
1440 if(opt.cert_digest_algo)
1441 digest_algo=opt.cert_digest_algo;
1442 else if(sk->pubkey_algo==PUBKEY_ALGO_RSA
1443 && pk->version<4 && sigversion<4)
1444 digest_algo = DIGEST_ALGO_MD5;
1445 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
1446 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (sk->skey[1])/8);
1447 else
1448 digest_algo = DIGEST_ALGO_SHA1;
1451 if ( gcry_md_open (&md, digest_algo, 0 ) )
1452 BUG ();
1454 /* Hash the public key certificate. */
1455 hash_public_key( md, pk );
1457 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1459 /* hash the subkey binding/backsig/revocation */
1460 hash_public_key( md, subpk );
1462 else if( sigclass != 0x1F && sigclass != 0x20 )
1464 /* hash the user id */
1465 hash_uid (md, sigversion, uid);
1467 /* and make the signature packet */
1468 sig = xmalloc_clear( sizeof *sig );
1469 sig->version = sigversion;
1470 sig->flags.exportable=1;
1471 sig->flags.revocable=1;
1472 keyid_from_sk( sk, sig->keyid );
1473 sig->pubkey_algo = sk->pubkey_algo;
1474 sig->digest_algo = digest_algo;
1475 if(timestamp)
1476 sig->timestamp=timestamp;
1477 else
1478 sig->timestamp=make_timestamp();
1479 if(duration)
1480 sig->expiredate=sig->timestamp+duration;
1481 sig->sig_class = sigclass;
1482 if( sig->version >= 4 )
1483 build_sig_subpkt_from_sig( sig );
1484 mk_notation_policy_etc( sig, pk, sk );
1486 /* Crucial that the call to mksubpkt comes LAST before the calls
1487 to finalize the sig as that makes it possible for the mksubpkt
1488 function to get a reliable pointer to the subpacket area. */
1489 if( sig->version >= 4 && mksubpkt )
1490 rc = (*mksubpkt)( sig, opaque );
1492 if( !rc ) {
1493 hash_sigversion_to_magic (md, sig);
1494 gcry_md_final (md);
1496 rc = complete_sig( sig, sk, md );
1499 gcry_md_close ( md );
1500 if( rc )
1501 free_seckey_enc( sig );
1502 else
1503 *ret_sig = sig;
1504 return rc;
1509 /****************
1510 * Create a new signature packet based on an existing one.
1511 * Only user ID signatures are supported for now.
1512 * TODO: Merge this with make_keysig_packet.
1515 update_keysig_packet( PKT_signature **ret_sig,
1516 PKT_signature *orig_sig,
1517 PKT_public_key *pk,
1518 PKT_user_id *uid,
1519 PKT_public_key *subpk,
1520 PKT_secret_key *sk,
1521 int (*mksubpkt)(PKT_signature *, void *),
1522 void *opaque )
1524 PKT_signature *sig;
1525 int rc=0;
1526 gcry_md_hd_t md;
1528 if ((!orig_sig || !pk || !sk)
1529 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1530 || (orig_sig->sig_class == 0x18 && !subpk))
1531 return G10ERR_GENERAL;
1533 if ( gcry_md_open (&md, orig_sig->digest_algo, 0 ) )
1534 BUG ();
1536 /* Hash the public key certificate and the user id. */
1537 hash_public_key( md, pk );
1539 if( orig_sig->sig_class == 0x18 )
1540 hash_public_key( md, subpk );
1541 else
1542 hash_uid (md, orig_sig->version, uid);
1544 /* create a new signature packet */
1545 sig = copy_signature (NULL, orig_sig);
1547 /* We need to create a new timestamp so that new sig expiration
1548 calculations are done correctly... */
1549 sig->timestamp=make_timestamp();
1551 /* ... but we won't make a timestamp earlier than the existing
1552 one. */
1553 while(sig->timestamp<=orig_sig->timestamp)
1555 sleep(1);
1556 sig->timestamp=make_timestamp();
1559 /* Note that already expired sigs will remain expired (with a
1560 duration of 1) since build-packet.c:build_sig_subpkt_from_sig
1561 detects this case. */
1563 if( sig->version >= 4 )
1565 /* Put the updated timestamp into the sig. Note that this
1566 will automagically lower any sig expiration dates to
1567 correctly correspond to the differences in the timestamps
1568 (i.e. the duration will shrink). */
1569 build_sig_subpkt_from_sig( sig );
1571 if (mksubpkt)
1572 rc = (*mksubpkt)(sig, opaque);
1575 if (!rc) {
1576 hash_sigversion_to_magic (md, sig);
1577 gcry_md_final (md);
1579 rc = complete_sig( sig, sk, md );
1582 gcry_md_close (md);
1583 if( rc )
1584 free_seckey_enc (sig);
1585 else
1586 *ret_sig = sig;
1587 return rc;