2006-06-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / sign.c
blob3e1d7bc5366fbcad116502bd1e2f3b84ed2470d3
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 /* If it's a DSA key, and q is 160 bits, it might be an
324 old-style DSA key. If the hash doesn't match the q, fail
325 unless --enable-dsa2 is set. If the q isn't 160 bits, then
326 allow any hash since it must be a DSA2 key (if the hash is
327 too small, we'll fail in encode_md_value). */
328 if (sk->pubkey_algo==PUBKEY_ALGO_DSA
329 && (gcry_mpi_get_nbits (sk->skey[1])/8)==20
330 && !opt.flags.dsa2
331 && gcry_md_get_algo_dlen (digest_algo)!=20)
333 log_error(_("DSA requires the use of a 160 bit hash algorithm\n"));
334 return G10ERR_GENERAL;
337 frame = encode_md_value( NULL, sk, md, digest_algo );
338 if (!frame)
339 return G10ERR_GENERAL;
340 rc = pk_sign( sk->pubkey_algo, sig->data, frame, sk->skey );
341 gcry_mpi_release (frame);
344 if (!rc && !opt.no_sig_create_check) {
345 /* Check that the signature verification worked and nothing is
346 * fooling us e.g. by a bug in the signature create
347 * code or by deliberately introduced faults. */
348 PKT_public_key *pk = xmalloc_clear (sizeof *pk);
350 if( get_pubkey( pk, sig->keyid ) )
351 rc = G10ERR_NO_PUBKEY;
352 else {
353 frame = encode_md_value (pk, NULL, md, sig->digest_algo );
354 if (!frame)
355 rc = G10ERR_GENERAL;
356 else
357 rc = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey );
358 gcry_mpi_release (frame);
360 if (rc)
361 log_error (_("checking created signature failed: %s\n"),
362 g10_errstr (rc));
363 free_public_key (pk);
365 if( rc )
366 log_error(_("signing failed: %s\n"), g10_errstr(rc) );
367 else {
368 if( opt.verbose ) {
369 char *ustr = get_user_id_string_native (sig->keyid);
370 log_info(_("%s/%s signature from: \"%s\"\n"),
371 gcry_pk_algo_name (sk->pubkey_algo),
372 gcry_md_algo_name (sig->digest_algo),
373 ustr );
374 xfree(ustr);
377 return rc;
382 complete_sig( PKT_signature *sig, PKT_secret_key *sk, gcry_md_hd_t md )
384 int rc=0;
386 if( !(rc=check_secret_key( sk, 0 )) )
387 rc = do_sign( sk, sig, md, 0 );
388 return rc;
393 static int
394 match_dsa_hash (unsigned int qbytes)
396 if (qbytes <= 20)
397 return DIGEST_ALGO_SHA1;
398 #ifdef USE_SHA256
399 if (qbytes <= 28)
400 return DIGEST_ALGO_SHA224;
401 if (qbytes <= 32)
402 return DIGEST_ALGO_SHA256;
403 #endif
405 #ifdef USE_SHA512
406 if (qbytes <= 48)
407 return DIGEST_ALGO_SHA384;
408 if (qbytes <= 64)
409 return DIGEST_ALGO_SHA512;
410 #endif
411 return DEFAULT_DIGEST_ALGO;
412 /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
413 answer we have if the larger SHAs aren't there. */
418 First try --digest-algo. If that isn't set, see if the recipient
419 has a preferred algorithm (which is also filtered through
420 --preferred-digest-prefs). If we're making a signature without a
421 particular recipient (i.e. signing, rather than signing+encrypting)
422 then take the first algorithm in --preferred-digest-prefs that is
423 usable for the pubkey algorithm. If --preferred-digest-prefs isn't
424 set, then take the OpenPGP default (i.e. SHA-1).
426 Possible improvement: Use the highest-ranked usable algorithm from
427 the signing key prefs either before or after using the personal
428 list?
430 static int
431 hash_for(PKT_secret_key *sk)
433 if( opt.def_digest_algo )
434 return opt.def_digest_algo;
435 else if( recipient_digest_algo )
436 return recipient_digest_algo;
437 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
439 unsigned int qbytes = gcry_mpi_get_nbits (sk->skey[1]) / 8;
441 /* It's a DSA key, so find a hash that is the same size as q or
442 larger. If q is 160, assume it is an old DSA key and use a
443 160-bit hash unless --enable-dsa2 is set, in which case act
444 like a new DSA key that just happens to have a 160-bit q
445 (i.e. allow truncation). If q is not 160, by definition it
446 must be a new DSA key. */
448 if (opt.personal_digest_prefs)
450 prefitem_t *prefs;
452 if (qbytes != 20 || opt.flags.dsa2)
454 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
455 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
456 return prefs->value;
458 else
460 for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
461 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
462 return prefs->value;
466 return match_dsa_hash(qbytes);
468 else if (sk->is_protected && sk->protect.s2k.mode==1002)
470 /* The sk lives on a smartcard, and current smartcards only
471 handle SHA-1 and RIPEMD/160. This is correct now, but may
472 need revision as the cards add algorithms. */
474 if(opt.personal_digest_prefs)
476 prefitem_t *prefs;
478 for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
479 if (prefs->value==DIGEST_ALGO_SHA1
480 || prefs->value==DIGEST_ALGO_RMD160)
481 return prefs->value;
484 return DIGEST_ALGO_SHA1;
486 else if (PGP2 && sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
488 /* Old-style PGP only understands MD5 */
489 return DIGEST_ALGO_MD5;
491 else if ( opt.personal_digest_prefs )
493 /* It's not DSA, so we can use whatever the first hash algorithm
494 is in the pref list */
495 return opt.personal_digest_prefs[0].value;
497 else
498 return DEFAULT_DIGEST_ALGO;
502 static int
503 only_old_style( SK_LIST sk_list )
505 SK_LIST sk_rover = NULL;
506 int old_style = 0;
508 /* if there are only old style capable key we use the old sytle */
509 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
510 PKT_secret_key *sk = sk_rover->sk;
511 if( sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 )
512 old_style = 1;
513 else
514 return 0;
516 return old_style;
520 static void
521 print_status_sig_created ( PKT_secret_key *sk, PKT_signature *sig, int what )
523 byte array[MAX_FINGERPRINT_LEN], *p;
524 char buf[100+MAX_FINGERPRINT_LEN*2];
525 size_t i, n;
527 sprintf(buf, "%c %d %d %02x %lu ",
528 what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
529 (ulong)sig->timestamp );
531 fingerprint_from_sk( sk, array, &n );
532 p = buf + strlen(buf);
533 for(i=0; i < n ; i++ )
534 sprintf(p+2*i, "%02X", array[i] );
536 write_status_text( STATUS_SIG_CREATED, buf );
541 * Loop over the secret certificates in SK_LIST and build the one pass
542 * signature packets. OpenPGP says that the data should be bracket by
543 * the onepass-sig and signature-packet; so we build these onepass
544 * packet here in reverse order
546 static int
547 write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
549 int skcount;
550 SK_LIST sk_rover;
552 for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
553 skcount++;
555 for (; skcount; skcount--) {
556 PKT_secret_key *sk;
557 PKT_onepass_sig *ops;
558 PACKET pkt;
559 int i, rc;
561 for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
562 if (++i == skcount)
563 break;
566 sk = sk_rover->sk;
567 ops = xmalloc_clear (sizeof *ops);
568 ops->sig_class = sigclass;
569 ops->digest_algo = hash_for (sk);
570 ops->pubkey_algo = sk->pubkey_algo;
571 keyid_from_sk (sk, ops->keyid);
572 ops->last = (skcount == 1);
574 init_packet(&pkt);
575 pkt.pkttype = PKT_ONEPASS_SIG;
576 pkt.pkt.onepass_sig = ops;
577 rc = build_packet (out, &pkt);
578 free_packet (&pkt);
579 if (rc) {
580 log_error ("build onepass_sig packet failed: %s\n",
581 g10_errstr(rc));
582 return rc;
586 return 0;
590 * Helper to write the plaintext (literal data) packet
592 static int
593 write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
595 PKT_plaintext *pt = NULL;
596 u32 filesize;
597 int rc = 0;
599 if (!opt.no_literal)
600 pt=setup_plaintext_name(fname,inp);
602 /* try to calculate the length of the data */
603 if ( !iobuf_is_pipe_filename (fname) && *fname )
605 off_t tmpsize;
606 int overflow;
608 if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
609 && !overflow )
610 log_info (_("WARNING: `%s' is an empty file\n"), fname);
612 /* We can't encode the length of very large files because
613 OpenPGP uses only 32 bit for file sizes. So if the size of
614 a file is larger than 2^32 minus some bytes for packet
615 headers, we switch to partial length encoding. */
616 if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
617 filesize = tmpsize;
618 else
619 filesize = 0;
621 /* Because the text_filter modifies the length of the
622 * data, it is not possible to know the used length
623 * without a double read of the file - to avoid that
624 * we simple use partial length packets. */
625 if ( ptmode == 't' )
626 filesize = 0;
628 else
629 filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
631 if (!opt.no_literal) {
632 PACKET pkt;
634 pt->timestamp = make_timestamp ();
635 pt->mode = ptmode;
636 pt->len = filesize;
637 pt->new_ctb = !pt->len && !RFC1991;
638 pt->buf = inp;
639 init_packet(&pkt);
640 pkt.pkttype = PKT_PLAINTEXT;
641 pkt.pkt.plaintext = pt;
642 /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
643 if( (rc = build_packet (out, &pkt)) )
644 log_error ("build_packet(PLAINTEXT) failed: %s\n",
645 g10_errstr(rc) );
646 pt->buf = NULL;
648 else {
649 byte copy_buffer[4096];
650 int bytes_copied;
652 while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
653 if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
654 log_error ("copying input to output failed: %s\n",
655 gpg_strerror (rc));
656 break;
658 wipememory(copy_buffer,4096); /* burn buffer */
660 /* fixme: it seems that we never freed pt/pkt */
662 return rc;
666 * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
667 * hash which will not be changes here.
669 static int
670 write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
671 int sigclass, u32 timestamp, u32 duration,
672 int status_letter)
674 SK_LIST sk_rover;
676 /* loop over the secret certificates */
677 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
678 PKT_secret_key *sk;
679 PKT_signature *sig;
680 gcry_md_hd_t md;
681 int rc;
683 sk = sk_rover->sk;
685 /* build the signature packet */
686 sig = xmalloc_clear (sizeof *sig);
687 if(opt.force_v3_sigs || RFC1991)
688 sig->version=3;
689 else if(duration || opt.sig_policy_url
690 || opt.sig_notations || opt.sig_keyserver_url)
691 sig->version=4;
692 else
693 sig->version=sk->version;
694 keyid_from_sk (sk, sig->keyid);
695 sig->digest_algo = hash_for(sk);
696 sig->pubkey_algo = sk->pubkey_algo;
697 if(timestamp)
698 sig->timestamp = timestamp;
699 else
700 sig->timestamp = make_timestamp();
701 if(duration)
702 sig->expiredate = sig->timestamp+duration;
703 sig->sig_class = sigclass;
705 if (gcry_md_copy (&md, hash))
706 BUG ();
708 if (sig->version >= 4)
709 build_sig_subpkt_from_sig (sig);
710 mk_notation_policy_etc (sig, NULL, sk);
712 hash_sigversion_to_magic (md, sig);
713 gcry_md_final (md);
715 rc = do_sign( sk, sig, md, hash_for (sk) );
716 gcry_md_close (md);
717 if( !rc ) { /* and write it */
718 PACKET pkt;
720 init_packet(&pkt);
721 pkt.pkttype = PKT_SIGNATURE;
722 pkt.pkt.signature = sig;
723 rc = build_packet (out, &pkt);
724 if (!rc && is_status_enabled()) {
725 print_status_sig_created ( sk, sig, status_letter);
727 free_packet (&pkt);
728 if (rc)
729 log_error ("build signature packet failed: %s\n",
730 g10_errstr(rc) );
732 if( rc )
733 return rc;;
736 return 0;
739 /****************
740 * Sign the files whose names are in FILENAME.
741 * If DETACHED has the value true,
742 * make a detached signature. If FILENAMES->d is NULL read from stdin
743 * and ignore the detached mode. Sign the file with all secret keys
744 * which can be taken from LOCUSR, if this is NULL, use the default one
745 * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
746 * signed data for these users.
747 * If OUTFILE is not NULL; this file is used for output and the function
748 * does not ask for overwrite permission; output is then always
749 * uncompressed, non-armored and in binary mode.
752 sign_file( STRLIST filenames, int detached, STRLIST locusr,
753 int encryptflag, STRLIST remusr, const char *outfile )
755 const char *fname;
756 armor_filter_context_t afx;
757 compress_filter_context_t zfx;
758 md_filter_context_t mfx;
759 text_filter_context_t tfx;
760 progress_filter_context_t pfx;
761 encrypt_filter_context_t efx;
762 IOBUF inp = NULL, out = NULL;
763 PACKET pkt;
764 int rc = 0;
765 PK_LIST pk_list = NULL;
766 SK_LIST sk_list = NULL;
767 SK_LIST sk_rover = NULL;
768 int multifile = 0;
769 u32 duration=0;
771 memset( &afx, 0, sizeof afx);
772 memset( &zfx, 0, sizeof zfx);
773 memset( &mfx, 0, sizeof mfx);
774 memset( &efx, 0, sizeof efx);
775 init_packet( &pkt );
777 if( filenames ) {
778 fname = filenames->d;
779 multifile = !!filenames->next;
781 else
782 fname = NULL;
784 if( fname && filenames->next && (!detached || encryptflag) )
785 log_bug("multiple files can only be detached signed");
787 if(encryptflag==2
788 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
789 goto leave;
791 if(!opt.force_v3_sigs && !RFC1991)
793 if(opt.ask_sig_expire && !opt.batch)
794 duration=ask_expire_interval(1,opt.def_sig_expire);
795 else
796 duration=parse_expire_string(opt.def_sig_expire);
799 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
800 goto leave;
802 if(PGP2 && !only_old_style(sk_list))
804 log_info(_("you can only detach-sign with PGP 2.x style keys "
805 "while in --pgp2 mode\n"));
806 compliance_failure();
809 if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC )))
810 goto leave;
812 /* prepare iobufs */
813 if( multifile ) /* have list of filenames */
814 inp = NULL; /* we do it later */
815 else {
816 inp = iobuf_open(fname);
817 if (inp && is_secured_file (iobuf_get_fd (inp)))
819 iobuf_close (inp);
820 inp = NULL;
821 errno = EPERM;
823 if( !inp )
825 rc = gpg_error_from_errno (errno);
826 log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
827 strerror(errno) );
828 goto leave;
831 handle_progress (&pfx, inp, fname);
834 if( outfile ) {
835 if (is_secured_filename ( outfile )) {
836 out = NULL;
837 errno = EPERM;
839 else
840 out = iobuf_create( outfile );
841 if( !out )
843 rc = gpg_error_from_errno (errno);
844 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
845 goto leave;
847 else if( opt.verbose )
848 log_info(_("writing to `%s'\n"), outfile );
850 else if( (rc = open_outfile( fname, opt.armor? 1: detached? 2:0, &out )))
851 goto leave;
853 /* prepare to calculate the MD over the input */
854 if( opt.textmode && !outfile && !multifile )
856 memset( &tfx, 0, sizeof tfx);
857 iobuf_push_filter( inp, text_filter, &tfx );
860 if ( gcry_md_open (&mfx.md, 0, 0) )
861 BUG ();
862 if (DBG_HASHING)
863 gcry_md_start_debug (mfx.md, "sign");
865 /* If we're encrypting and signing, it is reasonable to pick the
866 hash algorithm to use out of the recepient key prefs. */
867 if(pk_list)
869 if(opt.def_digest_algo)
871 if(!opt.expert &&
872 select_algo_from_prefs(pk_list,PREFTYPE_HASH,
873 opt.def_digest_algo,
874 NULL)!=opt.def_digest_algo)
875 log_info(_("WARNING: forcing digest algorithm %s (%d)"
876 " violates recipient preferences\n"),
877 gcry_md_algo_name (opt.def_digest_algo),
878 opt.def_digest_algo );
880 else
882 int hashlen=0,algo;
884 /* Of course, if the recipient asks for something
885 unreasonable (like a non-160-bit hash for DSA, for
886 example), then don't do it. Check all sk's - if any
887 are DSA, then the hash must be 160-bit. In the future
888 this can be more complex with different hashes for each
889 sk, but so long as there is only one signing algorithm
890 with hash restrictions, this is ok. -dms */
892 /* Current smartcards only do 160-bit hashes as well.
893 Note that this may well have to change as the cards add
894 algorithms. */
896 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
897 if(sk_rover->sk->pubkey_algo==PUBKEY_ALGO_DSA
898 || (sk_rover->sk->is_protected
899 && sk_rover->sk->protect.s2k.mode==1002))
900 hashlen=20;
902 if((algo=
903 select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,
904 hashlen?&hashlen:NULL))>0)
905 recipient_digest_algo=algo;
909 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
910 PKT_secret_key *sk = sk_rover->sk;
911 gcry_md_enable (mfx.md, hash_for(sk));
914 if( !multifile )
915 iobuf_push_filter( inp, md_filter, &mfx );
917 if( detached && !encryptflag && !RFC1991 )
918 afx.what = 2;
920 if( opt.armor && !outfile )
921 iobuf_push_filter( out, armor_filter, &afx );
923 if( encryptflag ) {
924 efx.pk_list = pk_list;
925 /* fixme: set efx.cfx.datalen if known */
926 iobuf_push_filter( out, encrypt_filter, &efx );
929 if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) )
931 int compr_algo=opt.compress_algo;
933 /* If not forced by user */
934 if(compr_algo==-1)
936 /* If we're not encrypting, then select_algo_from_prefs
937 will fail and we'll end up with the default. If we are
938 encrypting, select_algo_from_prefs cannot fail since
939 there is an assumed preference for uncompressed data.
940 Still, if it did fail, we'll also end up with the
941 default. */
943 if((compr_algo=
944 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
945 compr_algo=default_compress_algo();
947 else if(!opt.expert && pk_list
948 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
949 compr_algo,NULL)!=compr_algo)
950 log_info(_("WARNING: forcing compression algorithm %s (%d)"
951 " violates recipient preferences\n"),
952 compress_algo_to_string(compr_algo),compr_algo);
954 /* algo 0 means no compression */
955 if( compr_algo )
956 push_compress_filter(out,&zfx,compr_algo);
959 /* Write the one-pass signature packets if needed */
960 if (!detached && !RFC1991) {
961 rc = write_onepass_sig_packets (sk_list, out,
962 opt.textmode && !outfile ? 0x01:0x00);
963 if (rc)
964 goto leave;
967 write_status (STATUS_BEGIN_SIGNING);
969 /* Setup the inner packet. */
970 if( detached ) {
971 if( multifile ) {
972 STRLIST sl;
974 if( opt.verbose )
975 log_info(_("signing:") );
976 /* must walk reverse trough this list */
977 for( sl = strlist_last(filenames); sl;
978 sl = strlist_prev( filenames, sl ) ) {
979 inp = iobuf_open(sl->d);
980 if (inp && is_secured_file (iobuf_get_fd (inp)))
982 iobuf_close (inp);
983 inp = NULL;
984 errno = EPERM;
986 if( !inp )
988 rc = gpg_error_from_errno (errno);
989 log_error(_("can't open `%s': %s\n"),
990 sl->d,strerror(errno));
991 goto leave;
993 handle_progress (&pfx, inp, sl->d);
994 if( opt.verbose )
995 fprintf(stderr, " `%s'", sl->d );
996 if(opt.textmode)
998 memset( &tfx, 0, sizeof tfx);
999 iobuf_push_filter( inp, text_filter, &tfx );
1001 iobuf_push_filter( inp, md_filter, &mfx );
1002 while( iobuf_get(inp) != -1 )
1004 iobuf_close(inp); inp = NULL;
1006 if( opt.verbose )
1007 putc( '\n', stderr );
1009 else {
1010 /* read, so that the filter can calculate the digest */
1011 while( iobuf_get(inp) != -1 )
1015 else {
1016 rc = write_plaintext_packet (out, inp, fname,
1017 opt.textmode && !outfile ? 't':'b');
1020 /* catch errors from above */
1021 if (rc)
1022 goto leave;
1024 /* write the signatures */
1025 rc = write_signature_packets (sk_list, out, mfx.md,
1026 opt.textmode && !outfile? 0x01 : 0x00,
1027 0, duration, detached ? 'D':'S');
1028 if( rc )
1029 goto leave;
1032 leave:
1033 if( rc )
1034 iobuf_cancel(out);
1035 else {
1036 iobuf_close(out);
1037 if (encryptflag)
1038 write_status( STATUS_END_ENCRYPTION );
1040 iobuf_close(inp);
1041 gcry_md_close ( mfx.md );
1042 release_sk_list( sk_list );
1043 release_pk_list( pk_list );
1044 recipient_digest_algo=0;
1045 return rc;
1050 /****************
1051 * make a clear signature. note that opt.armor is not needed
1054 clearsign_file( const char *fname, STRLIST locusr, const char *outfile )
1056 armor_filter_context_t afx;
1057 progress_filter_context_t pfx;
1058 gcry_md_hd_t textmd = NULL;
1059 IOBUF inp = NULL, out = NULL;
1060 PACKET pkt;
1061 int rc = 0;
1062 SK_LIST sk_list = NULL;
1063 SK_LIST sk_rover = NULL;
1064 int old_style = RFC1991;
1065 int only_md5 = 0;
1066 u32 duration=0;
1068 memset( &afx, 0, sizeof afx);
1069 init_packet( &pkt );
1071 if(!opt.force_v3_sigs && !RFC1991)
1073 if(opt.ask_sig_expire && !opt.batch)
1074 duration=ask_expire_interval(1,opt.def_sig_expire);
1075 else
1076 duration=parse_expire_string(opt.def_sig_expire);
1079 if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) )
1080 goto leave;
1082 if( !old_style && !duration )
1083 old_style = only_old_style( sk_list );
1085 if(PGP2 && !only_old_style(sk_list))
1087 log_info(_("you can only clearsign with PGP 2.x style keys "
1088 "while in --pgp2 mode\n"));
1089 compliance_failure();
1092 /* prepare iobufs */
1093 inp = iobuf_open(fname);
1094 if (inp && is_secured_file (iobuf_get_fd (inp)))
1096 iobuf_close (inp);
1097 inp = NULL;
1098 errno = EPERM;
1100 if( !inp ) {
1101 rc = gpg_error_from_errno (errno);
1102 log_error (_("can't open `%s': %s\n"),
1103 fname? fname: "[stdin]", strerror(errno) );
1104 goto leave;
1106 handle_progress (&pfx, inp, fname);
1108 if( outfile ) {
1109 if (is_secured_filename (outfile) ) {
1110 outfile = NULL;
1111 errno = EPERM;
1113 else
1114 out = iobuf_create( outfile );
1115 if( !out )
1117 rc = gpg_error_from_errno (errno);
1118 log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
1119 goto leave;
1121 else if( opt.verbose )
1122 log_info(_("writing to `%s'\n"), outfile );
1124 else if( (rc = open_outfile( fname, 1, &out )) )
1125 goto leave;
1127 iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
1129 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1130 PKT_secret_key *sk = sk_rover->sk;
1131 if( hash_for(sk) == DIGEST_ALGO_MD5 )
1132 only_md5 = 1;
1133 else {
1134 only_md5 = 0;
1135 break;
1139 if( !(old_style && only_md5) ) {
1140 const char *s;
1141 int any = 0;
1142 byte hashs_seen[256];
1144 memset( hashs_seen, 0, sizeof hashs_seen );
1145 iobuf_writestr(out, "Hash: " );
1146 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1147 PKT_secret_key *sk = sk_rover->sk;
1148 int i = hash_for(sk);
1150 if( !hashs_seen[ i & 0xff ] ) {
1151 s = gcry_md_algo_name ( i );
1152 if( s ) {
1153 hashs_seen[ i & 0xff ] = 1;
1154 if( any )
1155 iobuf_put(out, ',' );
1156 iobuf_writestr(out, s );
1157 any = 1;
1161 assert(any);
1162 iobuf_writestr(out, LF );
1165 if( opt.not_dash_escaped )
1166 iobuf_writestr( out,
1167 "NotDashEscaped: You need GnuPG to verify this message" LF );
1168 iobuf_writestr(out, LF );
1170 if ( gcry_md_open (&textmd, 0, 0) )
1171 BUG ();
1172 for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
1173 PKT_secret_key *sk = sk_rover->sk;
1174 gcry_md_enable (textmd, hash_for(sk));
1176 if ( DBG_HASHING )
1177 gcry_md_start_debug ( textmd, "clearsign" );
1179 copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
1180 opt.escape_from, (old_style && only_md5) );
1181 /* fixme: check for read errors */
1183 /* now write the armor */
1184 afx.what = 2;
1185 iobuf_push_filter( out, armor_filter, &afx );
1187 /* write the signatures */
1188 rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C');
1189 if( rc )
1190 goto leave;
1192 leave:
1193 if( rc )
1194 iobuf_cancel(out);
1195 else
1196 iobuf_close(out);
1197 iobuf_close(inp);
1198 gcry_md_close ( textmd );
1199 release_sk_list( sk_list );
1200 return rc;
1204 * Sign and conventionally encrypt the given file.
1205 * FIXME: Far too much code is duplicated - revamp the whole file.
1208 sign_symencrypt_file (const char *fname, STRLIST locusr)
1210 armor_filter_context_t afx;
1211 progress_filter_context_t pfx;
1212 compress_filter_context_t zfx;
1213 md_filter_context_t mfx;
1214 text_filter_context_t tfx;
1215 cipher_filter_context_t cfx;
1216 IOBUF inp = NULL, out = NULL;
1217 PACKET pkt;
1218 STRING2KEY *s2k = NULL;
1219 int rc = 0;
1220 SK_LIST sk_list = NULL;
1221 SK_LIST sk_rover = NULL;
1222 int algo;
1223 u32 duration=0;
1225 memset( &afx, 0, sizeof afx);
1226 memset( &zfx, 0, sizeof zfx);
1227 memset( &mfx, 0, sizeof mfx);
1228 memset( &tfx, 0, sizeof tfx);
1229 memset( &cfx, 0, sizeof cfx);
1230 init_packet( &pkt );
1232 if(!opt.force_v3_sigs && !RFC1991)
1234 if(opt.ask_sig_expire && !opt.batch)
1235 duration=ask_expire_interval(1,opt.def_sig_expire);
1236 else
1237 duration=parse_expire_string(opt.def_sig_expire);
1240 rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG);
1241 if (rc)
1242 goto leave;
1244 /* prepare iobufs */
1245 inp = iobuf_open(fname);
1246 if (inp && is_secured_file (iobuf_get_fd (inp)))
1248 iobuf_close (inp);
1249 inp = NULL;
1250 errno = EPERM;
1252 if( !inp ) {
1253 rc = gpg_error_from_errno (errno);
1254 log_error (_("can't open `%s': %s\n"),
1255 fname? fname: "[stdin]", strerror(errno) );
1256 goto leave;
1258 handle_progress (&pfx, inp, fname);
1260 /* prepare key */
1261 s2k = xmalloc_clear( sizeof *s2k );
1262 s2k->mode = RFC1991? 0:opt.s2k_mode;
1263 s2k->hash_algo = S2K_DIGEST_ALGO;
1265 algo = default_cipher_algo();
1266 if (!opt.quiet || !opt.batch)
1267 log_info (_("%s encryption will be used\n"),
1268 gcry_cipher_algo_name (algo) );
1269 cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, NULL);
1271 if (!cfx.dek || !cfx.dek->keylen) {
1272 rc = gpg_error (GPG_ERR_BAD_PASSPHRASE);
1273 log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
1274 goto leave;
1277 /* We have no way to tell if the recipient can handle messages
1278 with an MDC, so this defaults to no. Perhaps in a few years,
1279 this can be defaulted to yes. Note that like regular
1280 encrypting, --force-mdc overrides --disable-mdc. */
1281 if(opt.force_mdc)
1282 cfx.dek->use_mdc=1;
1284 /* now create the outfile */
1285 rc = open_outfile (fname, opt.armor? 1:0, &out);
1286 if (rc)
1287 goto leave;
1289 /* prepare to calculate the MD over the input */
1290 if (opt.textmode)
1291 iobuf_push_filter (inp, text_filter, &tfx);
1292 if ( gcry_md_open (&mfx.md, 0, 0) )
1293 BUG ();
1294 if ( DBG_HASHING )
1295 gcry_md_start_debug (mfx.md, "symc-sign");
1297 for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) {
1298 PKT_secret_key *sk = sk_rover->sk;
1299 gcry_md_enable (mfx.md, hash_for (sk));
1302 iobuf_push_filter (inp, md_filter, &mfx);
1304 /* Push armor output filter */
1305 if (opt.armor)
1306 iobuf_push_filter (out, armor_filter, &afx);
1308 /* Write the symmetric key packet */
1309 /*(current filters: armor)*/
1310 if (!RFC1991) {
1311 PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
1312 enc->version = 4;
1313 enc->cipher_algo = cfx.dek->algo;
1314 enc->s2k = *s2k;
1315 pkt.pkttype = PKT_SYMKEY_ENC;
1316 pkt.pkt.symkey_enc = enc;
1317 if( (rc = build_packet( out, &pkt )) )
1318 log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
1319 xfree(enc);
1322 /* Push the encryption filter */
1323 iobuf_push_filter( out, cipher_filter, &cfx );
1325 /* Push the compress filter */
1326 if (default_compress_algo())
1327 push_compress_filter(out,&zfx,default_compress_algo());
1329 /* Write the one-pass signature packets */
1330 /*(current filters: zip - encrypt - armor)*/
1331 if (!RFC1991) {
1332 rc = write_onepass_sig_packets (sk_list, out,
1333 opt.textmode? 0x01:0x00);
1334 if (rc)
1335 goto leave;
1338 write_status (STATUS_BEGIN_SIGNING);
1340 /* Pipe data through all filters; i.e. write the signed stuff */
1341 /*(current filters: zip - encrypt - armor)*/
1342 rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
1343 if (rc)
1344 goto leave;
1346 /* Write the signatures */
1347 /*(current filters: zip - encrypt - armor)*/
1348 rc = write_signature_packets (sk_list, out, mfx.md,
1349 opt.textmode? 0x01 : 0x00,
1350 0, duration, 'S');
1351 if( rc )
1352 goto leave;
1355 leave:
1356 if( rc )
1357 iobuf_cancel(out);
1358 else {
1359 iobuf_close(out);
1360 write_status( STATUS_END_ENCRYPTION );
1362 iobuf_close(inp);
1363 release_sk_list( sk_list );
1364 gcry_md_close( mfx.md );
1365 xfree(cfx.dek);
1366 xfree(s2k);
1367 return rc;
1371 /****************
1372 * Create a signature packet for the given public key certificate and
1373 * the user id and return it in ret_sig. User signature class SIGCLASS
1374 * user-id is not used (and may be NULL if sigclass is 0x20) If
1375 * DIGEST_ALGO is 0 the function selects an appropriate one.
1376 * SIGVERSION gives the minimal required signature packet version;
1377 * this is needed so that special properties like local sign are not
1378 * applied (actually: dropped) when a v3 key is used. TIMESTAMP is
1379 * the timestamp to use for the signature. 0 means "now" */
1381 make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
1382 PKT_user_id *uid, PKT_public_key *subpk,
1383 PKT_secret_key *sk,
1384 int sigclass, int digest_algo,
1385 int sigversion, u32 timestamp, u32 duration,
1386 int (*mksubpkt)(PKT_signature *, void *), void *opaque
1389 PKT_signature *sig;
1390 int rc=0;
1391 gcry_md_hd_t md;
1393 assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
1394 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
1395 || sigclass == 0x30 || sigclass == 0x28 );
1397 if (opt.force_v4_certs)
1398 sigversion = 4;
1400 if (sigversion < sk->version)
1401 sigversion = sk->version;
1403 /* If you are making a signature on a v4 key using your v3 key, it
1404 doesn't make sense to generate a v3 sig. After all, no v3-only
1405 PGP implementation could understand the v4 key in the first
1406 place. Note that this implies that a signature on an attribute
1407 uid is usually going to be v4 as well, since they are not
1408 generally found on v3 keys. */
1409 if (sigversion < pk->version)
1410 sigversion = pk->version;
1412 if( !digest_algo )
1414 /* Basically, this means use SHA1 always unless it's a v3 RSA
1415 key making a v3 cert (use MD5), or the user specified
1416 something (use whatever they said), or it's DSA (use the
1417 best match). They still can't pick an inappropriate hash
1418 for DSA or the signature will fail. Note that this still
1419 allows the caller of make_keysig_packet to override the
1420 user setting if it must. */
1422 if(opt.cert_digest_algo)
1423 digest_algo=opt.cert_digest_algo;
1424 else if(sk->pubkey_algo==PUBKEY_ALGO_RSA
1425 && pk->version<4 && sigversion<4)
1426 digest_algo = DIGEST_ALGO_MD5;
1427 else if(sk->pubkey_algo==PUBKEY_ALGO_DSA)
1428 digest_algo = match_dsa_hash (gcry_mpi_get_nbits (sk->skey[1])/8);
1429 else
1430 digest_algo = DIGEST_ALGO_SHA1;
1433 if ( gcry_md_open (&md, digest_algo, 0 ) )
1434 BUG ();
1436 /* Hash the public key certificate. */
1437 hash_public_key( md, pk );
1439 if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
1441 /* hash the subkey binding/backsig/revocation */
1442 hash_public_key( md, subpk );
1444 else if( sigclass != 0x1F && sigclass != 0x20 )
1446 /* hash the user id */
1447 hash_uid (md, sigversion, uid);
1449 /* and make the signature packet */
1450 sig = xmalloc_clear( sizeof *sig );
1451 sig->version = sigversion;
1452 sig->flags.exportable=1;
1453 sig->flags.revocable=1;
1454 keyid_from_sk( sk, sig->keyid );
1455 sig->pubkey_algo = sk->pubkey_algo;
1456 sig->digest_algo = digest_algo;
1457 if(timestamp)
1458 sig->timestamp=timestamp;
1459 else
1460 sig->timestamp=make_timestamp();
1461 if(duration)
1462 sig->expiredate=sig->timestamp+duration;
1463 sig->sig_class = sigclass;
1464 if( sig->version >= 4 )
1465 build_sig_subpkt_from_sig( sig );
1466 mk_notation_policy_etc( sig, pk, sk );
1468 /* Crucial that the call to mksubpkt comes LAST before the calls
1469 to finalize the sig as that makes it possible for the mksubpkt
1470 function to get a reliable pointer to the subpacket area. */
1471 if( sig->version >= 4 && mksubpkt )
1472 rc = (*mksubpkt)( sig, opaque );
1474 if( !rc ) {
1475 hash_sigversion_to_magic (md, sig);
1476 gcry_md_final (md);
1478 rc = complete_sig( sig, sk, md );
1481 gcry_md_close ( md );
1482 if( rc )
1483 free_seckey_enc( sig );
1484 else
1485 *ret_sig = sig;
1486 return rc;
1491 /****************
1492 * Create a new signature packet based on an existing one.
1493 * Only user ID signatures are supported for now.
1494 * TODO: Merge this with make_keysig_packet.
1497 update_keysig_packet( PKT_signature **ret_sig,
1498 PKT_signature *orig_sig,
1499 PKT_public_key *pk,
1500 PKT_user_id *uid,
1501 PKT_public_key *subpk,
1502 PKT_secret_key *sk,
1503 int (*mksubpkt)(PKT_signature *, void *),
1504 void *opaque )
1506 PKT_signature *sig;
1507 int rc=0;
1508 gcry_md_hd_t md;
1510 if ((!orig_sig || !pk || !sk)
1511 || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
1512 || (orig_sig->sig_class == 0x18 && !subpk))
1513 return G10ERR_GENERAL;
1515 if ( gcry_md_open (&md, orig_sig->digest_algo, 0 ) )
1516 BUG ();
1518 /* Hash the public key certificate and the user id. */
1519 hash_public_key( md, pk );
1521 if( orig_sig->sig_class == 0x18 )
1522 hash_public_key( md, subpk );
1523 else
1524 hash_uid (md, orig_sig->version, uid);
1526 /* create a new signature packet */
1527 sig = copy_signature (NULL, orig_sig);
1529 /* We need to create a new timestamp so that new sig expiration
1530 calculations are done correctly... */
1531 sig->timestamp=make_timestamp();
1533 /* ... but we won't make a timestamp earlier than the existing
1534 one. */
1535 while(sig->timestamp<=orig_sig->timestamp)
1537 sleep(1);
1538 sig->timestamp=make_timestamp();
1541 /* Note that already expired sigs will remain expired (with a
1542 duration of 0) since build-packet.c:build_sig_subpkt_from_sig
1543 detects this case. */
1545 if( sig->version >= 4 )
1547 /* Put the updated timestamp into the sig. Note that this
1548 will automagically lower any sig expiration dates to
1549 correctly correspond to the differences in the timestamps
1550 (i.e. the duration will shrink). */
1551 build_sig_subpkt_from_sig( sig );
1553 if (mksubpkt)
1554 rc = (*mksubpkt)(sig, opaque);
1557 if (!rc) {
1558 hash_sigversion_to_magic (md, sig);
1559 gcry_md_final (md);
1561 rc = complete_sig( sig, sk, md );
1564 gcry_md_close (md);
1565 if( rc )
1566 free_seckey_enc (sig);
1567 else
1568 *ret_sig = sig;
1569 return rc;