chiark / gitweb /
Import gnupg2_2.1.17.orig.tar.bz2
[gnupg2.git] / g10 / sig-check.c
1 /* sig-check.c -  Check a signature
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003,
3  *               2004, 2006 Free Software Foundation, Inc.
4  * Copyright (C) 2015, 2016 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "gpg.h"
28 #include "util.h"
29 #include "packet.h"
30 #include "keydb.h"
31 #include "main.h"
32 #include "status.h"
33 #include "i18n.h"
34 #include "options.h"
35 #include "pkglue.h"
36
37 static int check_signature_end (PKT_public_key *pk, PKT_signature *sig,
38                                 gcry_md_hd_t digest,
39                                 int *r_expired, int *r_revoked,
40                                 PKT_public_key *ret_pk);
41
42 static int check_signature_end_simple (PKT_public_key *pk, PKT_signature *sig,
43                                        gcry_md_hd_t digest);
44
45 /* Check a signature.  This is shorthand for check_signature2 with
46    the unnamed arguments passed as NULL.  */
47 int
48 check_signature (PKT_signature *sig, gcry_md_hd_t digest)
49 {
50     return check_signature2 (sig, digest, NULL, NULL, NULL, NULL);
51 }
52
53
54 /* Check a signature.
55  *
56  * Looks up the public key that created the signature (SIG->KEYID)
57  * from the key db.  Makes sure that the signature is valid (it was
58  * not created prior to the key, the public key was created in the
59  * past, and the signature does not include any unsupported critical
60  * features), finishes computing the hash of the signature data, and
61  * checks that the signature verifies the digest.  If the key that
62  * generated the signature is a subkey, this function also verifies
63  * that there is a valid backsig from the subkey to the primary key.
64  * Finally, if status fd is enabled and the signature class is 0x00 or
65  * 0x01, then a STATUS_SIG_ID is emitted on the status fd.
66  *
67  * SIG is the signature to check.
68  *
69  * DIGEST contains a valid hash context that already includes the
70  * signed data.  This function adds the relevant meta-data from the
71  * signature packet to compute the final hash.  (See Section 5.2 of
72  * RFC 4880: "The concatenation of the data being signed and the
73  * signature data from the version number through the hashed subpacket
74  * data (inclusive) is hashed.")
75  *
76  * If R_EXPIREDATE is not NULL, R_EXPIREDATE is set to the key's
77  * expiry.
78  *
79  * If R_EXPIRED is not NULL, *R_EXPIRED is set to 1 if PK has expired
80  * (0 otherwise).  Note: PK being expired does not cause this function
81  * to fail.
82  *
83  * If R_REVOKED is not NULL, *R_REVOKED is set to 1 if PK has been
84  * revoked (0 otherwise).  Note: PK being revoked does not cause this
85  * function to fail.
86  *
87  * If R_PK is not NULL, the public key is stored at that address if it
88  * was found; other wise NULL is stored.
89  *
90  * Returns 0 on success.  An error code otherwise.  */
91 gpg_error_t
92 check_signature2 (PKT_signature *sig, gcry_md_hd_t digest, u32 *r_expiredate,
93                   int *r_expired, int *r_revoked, PKT_public_key **r_pk)
94 {
95     int rc=0;
96     PKT_public_key *pk;
97
98     if (r_expiredate)
99       *r_expiredate = 0;
100     if (r_expired)
101       *r_expired = 0;
102     if (r_revoked)
103       *r_revoked = 0;
104     if (r_pk)
105       *r_pk = NULL;
106
107     pk = xtrycalloc (1, sizeof *pk);
108     if (!pk)
109       return gpg_error_from_syserror ();
110
111     if ( (rc=openpgp_md_test_algo(sig->digest_algo)) )
112       ; /* We don't have this digest. */
113     else if ((rc=openpgp_pk_test_algo(sig->pubkey_algo)))
114       ; /* We don't have this pubkey algo. */
115     else if (!gcry_md_is_enabled (digest,sig->digest_algo))
116       {
117         /* Sanity check that the md has a context for the hash that the
118            sig is expecting.  This can happen if a onepass sig header does
119            not match the actual sig, and also if the clearsign "Hash:"
120            header is missing or does not match the actual sig. */
121
122         log_info(_("WARNING: signature digest conflict in message\n"));
123         rc = gpg_error (GPG_ERR_GENERAL);
124       }
125     else if( get_pubkey( pk, sig->keyid ) )
126       rc = gpg_error (GPG_ERR_NO_PUBKEY);
127     else if(!pk->flags.valid)
128       {
129         /* You cannot have a good sig from an invalid key.  */
130         rc = gpg_error (GPG_ERR_BAD_PUBKEY);
131       }
132     else
133       {
134         if(r_expiredate)
135           *r_expiredate = pk->expiredate;
136
137         rc = check_signature_end (pk, sig, digest, r_expired, r_revoked, NULL);
138
139         /* Check the backsig.  This is a 0x19 signature from the
140            subkey on the primary key.  The idea here is that it should
141            not be possible for someone to "steal" subkeys and claim
142            them as their own.  The attacker couldn't actually use the
143            subkey, but they could try and claim ownership of any
144            signatures issued by it. */
145         if (!rc && !pk->flags.primary && pk->flags.backsig < 2)
146           {
147             if (!pk->flags.backsig)
148               {
149                 log_info(_("WARNING: signing subkey %s is not"
150                            " cross-certified\n"),keystr_from_pk(pk));
151                 log_info(_("please see %s for more information\n"),
152                          "https://gnupg.org/faq/subkey-cross-certify.html");
153                 /* --require-cross-certification makes this warning an
154                      error.  TODO: change the default to require this
155                      after more keys have backsigs. */
156                 if(opt.flags.require_cross_cert)
157                   rc = gpg_error (GPG_ERR_GENERAL);
158               }
159             else if(pk->flags.backsig == 1)
160               {
161                 log_info(_("WARNING: signing subkey %s has an invalid"
162                            " cross-certification\n"),keystr_from_pk(pk));
163                 rc = gpg_error (GPG_ERR_GENERAL);
164               }
165           }
166       }
167
168     if( !rc && sig->sig_class < 2 && is_status_enabled() ) {
169         /* This signature id works best with DLP algorithms because
170          * they use a random parameter for every signature.  Instead of
171          * this sig-id we could have also used the hash of the document
172          * and the timestamp, but the drawback of this is, that it is
173          * not possible to sign more than one identical document within
174          * one second.  Some remote batch processing applications might
175          * like this feature here.
176          *
177          * Note that before 2.0.10, we used RIPE-MD160 for the hash
178          * and accidentally didn't include the timestamp and algorithm
179          * information in the hash.  Given that this feature is not
180          * commonly used and that a replay attacks detection should
181          * not solely be based on this feature (because it does not
182          * work with RSA), we take the freedom and switch to SHA-1
183          * with 2.0.10 to take advantage of hardware supported SHA-1
184          * implementations.  We also include the missing information
185          * in the hash.  Note also the SIG_ID as computed by gpg 1.x
186          * and gpg 2.x didn't matched either because 2.x used to print
187          * MPIs not in PGP format.  */
188         u32 a = sig->timestamp;
189         int nsig = pubkey_get_nsig( sig->pubkey_algo );
190         unsigned char *p, *buffer;
191         size_t n, nbytes;
192         int i;
193         char hashbuf[20];
194
195         nbytes = 6;
196         for (i=0; i < nsig; i++ )
197           {
198             if (gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &n, sig->data[i]))
199               BUG();
200             nbytes += n;
201           }
202
203         /* Make buffer large enough to be later used as output buffer.  */
204         if (nbytes < 100)
205           nbytes = 100;
206         nbytes += 10;  /* Safety margin.  */
207
208         /* Fill and hash buffer.  */
209         buffer = p = xmalloc (nbytes);
210         *p++ = sig->pubkey_algo;
211         *p++ = sig->digest_algo;
212         *p++ = (a >> 24) & 0xff;
213         *p++ = (a >> 16) & 0xff;
214         *p++ = (a >>  8) & 0xff;
215         *p++ =  a & 0xff;
216         nbytes -= 6;
217         for (i=0; i < nsig; i++ )
218           {
219             if (gcry_mpi_print (GCRYMPI_FMT_PGP, p, nbytes, &n, sig->data[i]))
220               BUG();
221             p += n;
222             nbytes -= n;
223           }
224         gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, buffer, p-buffer);
225
226         p = make_radix64_string (hashbuf, 20);
227         sprintf (buffer, "%s %s %lu",
228                  p, strtimestamp (sig->timestamp), (ulong)sig->timestamp);
229         xfree (p);
230         write_status_text (STATUS_SIG_ID, buffer);
231         xfree (buffer);
232     }
233
234     if (r_pk)
235       *r_pk = pk;
236     else
237       {
238         release_public_key_parts (pk);
239         xfree (pk);
240       }
241
242     return rc;
243 }
244
245
246 /* The signature SIG was generated with the public key PK.  Check
247  * whether the signature is valid in the following sense:
248  *
249  *   - Make sure the public key was created before the signature was
250  *     generated.
251  *
252  *   - Make sure the public key was created in the past
253  *
254  *   - Check whether PK has expired (set *R_EXPIRED to 1 if so and 0
255  *     otherwise)
256  *
257  *   - Check whether PK has been revoked (set *R_REVOKED to 1 if so
258  *     and 0 otherwise).
259  *
260  * If either of the first two tests fail, returns an error code.
261  * Otherwise returns 0.  (Thus, this function doesn't fail if the
262  * public key is expired or revoked.)  */
263 static int
264 check_signature_metadata_validity (PKT_public_key *pk, PKT_signature *sig,
265                                    int *r_expired, int *r_revoked)
266 {
267     u32 cur_time;
268
269     if(r_expired)
270       *r_expired = 0;
271     if(r_revoked)
272       *r_revoked = 0;
273
274     if( pk->timestamp > sig->timestamp )
275       {
276         ulong d = pk->timestamp - sig->timestamp;
277         if ( d < 86400 )
278           {
279             log_info
280               (ngettext
281                ("public key %s is %lu second newer than the signature\n",
282                 "public key %s is %lu seconds newer than the signature\n",
283                 d), keystr_from_pk (pk), d);
284           }
285         else
286           {
287             d /= 86400;
288             log_info
289               (ngettext
290                ("public key %s is %lu day newer than the signature\n",
291                 "public key %s is %lu days newer than the signature\n",
292                 d), keystr_from_pk (pk), d);
293           }
294         if (!opt.ignore_time_conflict)
295           return GPG_ERR_TIME_CONFLICT; /* pubkey newer than signature.  */
296       }
297
298     cur_time = make_timestamp();
299     if( pk->timestamp > cur_time )
300       {
301         ulong d = pk->timestamp - cur_time;
302         if (d < 86400)
303           {
304             log_info (ngettext("key %s was created %lu second"
305                                " in the future (time warp or clock problem)\n",
306                                "key %s was created %lu seconds"
307                                " in the future (time warp or clock problem)\n",
308                                d), keystr_from_pk (pk), d);
309           }
310         else
311           {
312             d /= 86400;
313             log_info (ngettext("key %s was created %lu day"
314                                " in the future (time warp or clock problem)\n",
315                                "key %s was created %lu days"
316                                " in the future (time warp or clock problem)\n",
317                                d), keystr_from_pk (pk), d);
318           }
319         if (!opt.ignore_time_conflict)
320           return GPG_ERR_TIME_CONFLICT;
321       }
322
323     /* Check whether the key has expired.  We check the has_expired
324        flag which is set after a full evaluation of the key (getkey.c)
325        as well as a simple compare to the current time in case the
326        merge has for whatever reasons not been done.  */
327     if( pk->has_expired || (pk->expiredate && pk->expiredate < cur_time)) {
328         char buf[11];
329         if (opt.verbose)
330           log_info(_("Note: signature key %s expired %s\n"),
331                    keystr_from_pk(pk), asctimestamp( pk->expiredate ) );
332         sprintf(buf,"%lu",(ulong)pk->expiredate);
333         write_status_text(STATUS_KEYEXPIRED,buf);
334         if(r_expired)
335           *r_expired = 1;
336     }
337
338     if (pk->flags.revoked)
339       {
340         if (opt.verbose)
341           log_info (_("Note: signature key %s has been revoked\n"),
342                     keystr_from_pk(pk));
343         if (r_revoked)
344           *r_revoked=1;
345       }
346
347     return 0;
348 }
349
350
351 /* Finish generating a signature and check it.  Concretely: make sure
352  * that the signature is valid (it was not created prior to the key,
353  * the public key was created in the past, and the signature does not
354  * include any unsupported critical features), finish computing the
355  * digest by adding the relevant data from the signature packet, and
356  * check that the signature verifies the digest.
357  *
358  * DIGEST contains a hash context, which has already hashed the signed
359  * data.  This function adds the relevant meta-data from the signature
360  * packet to compute the final hash.  (See Section 5.2 of RFC 4880:
361  * "The concatenation of the data being signed and the signature data
362  * from the version number through the hashed subpacket data
363  * (inclusive) is hashed.")
364  *
365  * SIG is the signature to check.
366  *
367  * PK is the public key used to generate the signature.
368  *
369  * If R_EXPIRED is not NULL, *R_EXPIRED is set to 1 if PK has expired
370  * (0 otherwise).  Note: PK being expired does not cause this function
371  * to fail.
372  *
373  * If R_REVOKED is not NULL, *R_REVOKED is set to 1 if PK has been
374  * revoked (0 otherwise).  Note: PK being revoked does not cause this
375  * function to fail.
376  *
377  * If RET_PK is not NULL, PK is copied into RET_PK on success.
378  *
379  * Returns 0 on success.  An error code other.  */
380 static int
381 check_signature_end (PKT_public_key *pk, PKT_signature *sig,
382                      gcry_md_hd_t digest,
383                      int *r_expired, int *r_revoked, PKT_public_key *ret_pk)
384 {
385     int rc = 0;
386
387     if ((rc = check_signature_metadata_validity (pk, sig,
388                                                  r_expired, r_revoked)))
389         return rc;
390
391     if ((rc = check_signature_end_simple (pk, sig, digest)))
392       return rc;
393
394     if(!rc && ret_pk)
395       copy_public_key(ret_pk,pk);
396
397     return rc;
398 }
399
400 /* This function is similar to check_signature_end, but it only checks
401    whether the signature was generated by PK.  It does not check
402    expiration, revocation, etc.  */
403 static int
404 check_signature_end_simple (PKT_public_key *pk, PKT_signature *sig,
405                             gcry_md_hd_t digest)
406 {
407     gcry_mpi_t result = NULL;
408     int rc = 0;
409     const struct weakhash *weak;
410
411     if (!opt.flags.allow_weak_digest_algos)
412       for (weak = opt.weak_digests; weak; weak = weak->next)
413         if (sig->digest_algo == weak->algo)
414           {
415             print_digest_rejected_note(sig->digest_algo);
416             return GPG_ERR_DIGEST_ALGO;
417           }
418
419     /* Make sure the digest algo is enabled (in case of a detached
420        signature).  */
421     gcry_md_enable (digest, sig->digest_algo);
422
423     /* Complete the digest. */
424     if( sig->version >= 4 )
425         gcry_md_putc( digest, sig->version );
426     gcry_md_putc( digest, sig->sig_class );
427     if( sig->version < 4 ) {
428         u32 a = sig->timestamp;
429         gcry_md_putc( digest, (a >> 24) & 0xff );
430         gcry_md_putc( digest, (a >> 16) & 0xff );
431         gcry_md_putc( digest, (a >>     8) & 0xff );
432         gcry_md_putc( digest,  a           & 0xff );
433     }
434     else {
435         byte buf[6];
436         size_t n;
437         gcry_md_putc( digest, sig->pubkey_algo );
438         gcry_md_putc( digest, sig->digest_algo );
439         if( sig->hashed ) {
440             n = sig->hashed->len;
441             gcry_md_putc (digest, (n >> 8) );
442             gcry_md_putc (digest,  n       );
443             gcry_md_write (digest, sig->hashed->data, n);
444             n += 6;
445         }
446         else {
447           /* Two octets for the (empty) length of the hashed
448              section. */
449           gcry_md_putc (digest, 0);
450           gcry_md_putc (digest, 0);
451           n = 6;
452         }
453         /* add some magic per Section 5.2.4 of RFC 4880.  */
454         buf[0] = sig->version;
455         buf[1] = 0xff;
456         buf[2] = n >> 24;
457         buf[3] = n >> 16;
458         buf[4] = n >>  8;
459         buf[5] = n;
460         gcry_md_write( digest, buf, 6 );
461     }
462     gcry_md_final( digest );
463
464     /* Convert the digest to an MPI.  */
465     result = encode_md_value (pk, digest, sig->digest_algo );
466     if (!result)
467         return GPG_ERR_GENERAL;
468
469     /* Verify the signature.  */
470     rc = pk_verify( pk->pubkey_algo, result, sig->data, pk->pkey );
471     gcry_mpi_release (result);
472
473     if( !rc && sig->flags.unknown_critical )
474       {
475         log_info(_("assuming bad signature from key %s"
476                    " due to an unknown critical bit\n"),keystr_from_pk(pk));
477         rc = GPG_ERR_BAD_SIGNATURE;
478       }
479
480     return rc;
481 }
482
483
484 /* Add a uid node to a hash context.  See section 5.2.4, paragraph 4
485    of RFC 4880.  */
486 static void
487 hash_uid_packet (PKT_user_id *uid, gcry_md_hd_t md, PKT_signature *sig )
488 {
489     if( uid->attrib_data ) {
490         if( sig->version >=4 ) {
491             byte buf[5];
492             buf[0] = 0xd1;                   /* packet of type 17 */
493             buf[1] = uid->attrib_len >> 24;  /* always use 4 length bytes */
494             buf[2] = uid->attrib_len >> 16;
495             buf[3] = uid->attrib_len >>  8;
496             buf[4] = uid->attrib_len;
497             gcry_md_write( md, buf, 5 );
498         }
499         gcry_md_write( md, uid->attrib_data, uid->attrib_len );
500     }
501     else {
502         if( sig->version >=4 ) {
503             byte buf[5];
504             buf[0] = 0xb4;            /* indicates a userid packet */
505             buf[1] = uid->len >> 24;  /* always use 4 length bytes */
506             buf[2] = uid->len >> 16;
507             buf[3] = uid->len >>  8;
508             buf[4] = uid->len;
509             gcry_md_write( md, buf, 5 );
510         }
511         gcry_md_write( md, uid->name, uid->len );
512     }
513 }
514
515 static void
516 cache_sig_result ( PKT_signature *sig, int result )
517 {
518     if ( !result ) {
519         sig->flags.checked = 1;
520         sig->flags.valid = 1;
521     }
522     else if ( gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE ) {
523         sig->flags.checked = 1;
524         sig->flags.valid = 0;
525     }
526     else {
527         sig->flags.checked = 0;
528         sig->flags.valid = 0;
529     }
530 }
531
532
533 /* SIG is a key revocation signature.  Check if this signature was
534  * generated by any of the public key PK's designated revokers.
535  *
536  *   PK is the public key that SIG allegedly revokes.
537  *
538  *   SIG is the revocation signature to check.
539  *
540  * This function avoids infinite recursion, which can happen if two
541  * keys are designed revokers for each other and they revoke each
542  * other.  This is done by observing that if a key A is revoked by key
543  * B we still consider the revocation to be valid even if B is
544  * revoked.  Thus, we don't need to determine whether B is revoked to
545  * determine whether A has been revoked by B, we just need to check
546  * the signature.
547  *
548  * Returns 0 if sig is valid (i.e. pk is revoked), non-0 if not
549  * revoked.  We are careful to make sure that GPG_ERR_NO_PUBKEY is
550  * only returned when a revocation signature is from a valid
551  * revocation key designated in a revkey subpacket, but the revocation
552  * key itself isn't present.
553  *
554  * XXX: This code will need to be modified if gpg ever becomes
555  * multi-threaded.  Note that this guarantees that a designated
556  * revocation sig will never be considered valid unless it is actually
557  * valid, as well as being issued by a revocation key in a valid
558  * direct signature.  Note also that this is written so that a revoked
559  * revoker can still issue revocations: i.e. If A revokes B, but A is
560  * revoked, B is still revoked.  I'm not completely convinced this is
561  * the proper behavior, but it matches how PGP does it. -dms */
562 int
563 check_revocation_keys (PKT_public_key *pk, PKT_signature *sig)
564 {
565   static int busy=0;
566   int i;
567   int rc = GPG_ERR_GENERAL;
568
569   log_assert (IS_KEY_REV(sig));
570   log_assert ((sig->keyid[0]!=pk->keyid[0]) || (sig->keyid[0]!=pk->keyid[1]));
571
572   /* Avoid infinite recursion.  Consider the following:
573    *
574    *   - We want to check if A is revoked.
575    *
576    *   - C is a designated revoker for B and has revoked B.
577    *
578    *   - B is a designated revoker for A and has revoked A.
579    *
580    * When checking if A is revoked (in merge_selfsigs_main), we
581    * observe that A has a designed revoker.  As such, we call this
582    * function.  This function sees that there is a valid revocation
583    * signature, which is signed by B.  It then calls check_signature()
584    * to verify that the signature is good.  To check the sig, we need
585    * to lookup B.  Looking up B means calling merge_selfsigs_main,
586    * which checks whether B is revoked, which calls this function to
587    * see if B was revoked by some key.
588    *
589    * In this case, the added level of indirection doesn't hurt.  It
590    * just means a bit more work.  However, if C == A, then we'd end up
591    * in a loop.  But, it doesn't make sense to look up C anyways: even
592    * if B is revoked, we conservatively consider a valid revocation
593    * signed by B to revoke A.  Since this is the only place where this
594    * type of recursion can occur, we simply cause this function to
595    * fail if it is entered recursively.  */
596   if (busy)
597     {
598       /* Return an error (i.e. not revoked), but mark the pk as
599          uncacheable as we don't really know its revocation status
600          until it is checked directly.  */
601       pk->flags.dont_cache = 1;
602       return rc;
603     }
604
605   busy=1;
606
607   /*  es_printf("looking at %08lX with a sig from %08lX\n",(ulong)pk->keyid[1],
608       (ulong)sig->keyid[1]); */
609
610   /* is the issuer of the sig one of our revokers? */
611   if( !pk->revkey && pk->numrevkeys )
612      BUG();
613   else
614       for(i=0;i<pk->numrevkeys;i++)
615         {
616           /* The revoker's keyid.  */
617           u32 keyid[2];
618
619           keyid_from_fingerprint(pk->revkey[i].fpr,MAX_FINGERPRINT_LEN,keyid);
620
621           if(keyid[0]==sig->keyid[0] && keyid[1]==sig->keyid[1])
622             /* The signature was generated by a designated revoker.
623                Verify the signature.  */
624             {
625               gcry_md_hd_t md;
626
627               if (gcry_md_open (&md, sig->digest_algo, 0))
628                 BUG ();
629               hash_public_key(md,pk);
630               /* Note: check_signature only checks that the signature
631                  is good.  It does not fail if the key is revoked.  */
632               rc=check_signature(sig,md);
633               cache_sig_result(sig,rc);
634               gcry_md_close (md);
635               break;
636             }
637         }
638
639   busy=0;
640
641   return rc;
642 }
643
644 /* Check that the backsig BACKSIG from the subkey SUB_PK to its
645    primary key MAIN_PK is valid.
646
647    Backsigs (0x19) have the same format as binding sigs (0x18), but
648    this function is simpler than check_key_signature in a few ways.
649    For example, there is no support for expiring backsigs since it is
650    questionable what such a thing actually means.  Note also that the
651    sig cache check here, unlike other sig caches in GnuPG, is not
652    persistent. */
653 int
654 check_backsig (PKT_public_key *main_pk,PKT_public_key *sub_pk,
655                PKT_signature *backsig)
656 {
657   gcry_md_hd_t md;
658   int rc;
659
660   /* Always check whether the algorithm is available.  Although
661      gcry_md_open would throw an error, some libgcrypt versions will
662      print a debug message in that case too. */
663   if ((rc=openpgp_md_test_algo (backsig->digest_algo)))
664     return rc;
665
666   if(!opt.no_sig_cache && backsig->flags.checked)
667     return backsig->flags.valid? 0 : gpg_error (GPG_ERR_BAD_SIGNATURE);
668
669   rc = gcry_md_open (&md, backsig->digest_algo,0);
670   if (!rc)
671     {
672       hash_public_key(md,main_pk);
673       hash_public_key(md,sub_pk);
674       rc = check_signature_end (sub_pk, backsig, md, NULL, NULL, NULL);
675       cache_sig_result(backsig,rc);
676       gcry_md_close(md);
677     }
678
679   return rc;
680 }
681
682
683 /* Check that a signature over a key is valid.  This is a
684  * specialization of check_key_signature2 with the unnamed parameters
685  * passed as NULL.  See the documentation for that function for more
686  * details.  */
687 int
688 check_key_signature (KBNODE root, KBNODE node, int *is_selfsig)
689 {
690   return check_key_signature2 (root, node, NULL, NULL, is_selfsig, NULL, NULL);
691 }
692
693
694 /* Returns whether SIGNER generated the signature SIG over the packet
695    PACKET, which is a key, subkey or uid, and comes from the key block
696    KB.  (KB is PACKET's corresponding keyblock; we don't assume that
697    SIG has been added to the keyblock.)
698
699    If SIGNER is set, then checks whether SIGNER generated the
700    signature.  Otherwise, uses SIG->KEYID to find the alleged signer.
701    This parameter can be used to effectively override the alleged
702    signer that is stored in SIG.
703
704    KB may be NULL if SIGNER is set.
705
706    Unlike check_key_signature, this function ignores any cached
707    results!  That is, it does not consider SIG->FLAGS.CHECKED and
708    SIG->FLAGS.VALID nor does it set them.
709
710    This doesn't check the signature's semantic mean.  Concretely, it
711    doesn't check whether a non-self signed revocation signature was
712    created by a designated revoker.  In fact, it doesn't return an
713    error for a binding generated by a completely different key!
714
715    Returns 0 if the signature is valid.  Returns GPG_ERR_SIG_CLASS if
716    this signature can't be over PACKET.  Returns GPG_ERR_NOT_FOUND if
717    the key that generated the signature (according to SIG) could not
718    be found.  Returns GPG_ERR_BAD_SIGNATURE if the signature is bad.
719    Other errors codes may be returned if something else goes wrong.
720
721    IF IS_SELFSIG is not NULL, sets *IS_SELFSIG to 1 if this is a
722    self-signature (by the key's primary key) or 0 if not.
723
724    If RET_PK is not NULL, returns a copy of the public key that
725    generated the signature (i.e., the signer) on success.  This must
726    be released by the caller using release_public_key_parts ().  */
727 gpg_error_t
728 check_signature_over_key_or_uid (PKT_public_key *signer,
729                                  PKT_signature *sig, KBNODE kb, PACKET *packet,
730                                  int *is_selfsig, PKT_public_key *ret_pk)
731 {
732   int rc;
733   PKT_public_key *pripk = kb->pkt->pkt.public_key;
734   gcry_md_hd_t md;
735   int signer_alloced = 0;
736
737   rc = openpgp_pk_test_algo (sig->pubkey_algo);
738   if (rc)
739     return rc;
740   rc = openpgp_md_test_algo (sig->digest_algo);
741   if (rc)
742     return rc;
743
744   /* A signature's class indicates the type of packet that it
745      signs.  */
746   if (/* Primary key binding (made by a subkey).  */
747       sig->sig_class == 0x19
748       /* Direct key signature.  */
749       || sig->sig_class == 0x1f
750       /* Primary key revocation.  */
751       || sig->sig_class == 0x20)
752     {
753       if (packet->pkttype != PKT_PUBLIC_KEY)
754         /* Key revocations can only be over primary keys.  */
755         return gpg_error (GPG_ERR_SIG_CLASS);
756     }
757   else if (/* Subkey binding.  */
758            sig->sig_class == 0x18
759            /* Subkey revocation.  */
760            || sig->sig_class == 0x28)
761     {
762       if (packet->pkttype != PKT_PUBLIC_SUBKEY)
763         return gpg_error (GPG_ERR_SIG_CLASS);
764     }
765   else if (/* Certification.  */
766            sig->sig_class == 0x10
767            || sig->sig_class == 0x11
768            || sig->sig_class == 0x12
769            || sig->sig_class == 0x13
770            /* Certification revocation.  */
771            || sig->sig_class == 0x30)
772     {
773       if (packet->pkttype != PKT_USER_ID)
774         return gpg_error (GPG_ERR_SIG_CLASS);
775     }
776   else
777     return gpg_error (GPG_ERR_SIG_CLASS);
778
779   /* PACKET is the right type for SIG.  */
780
781   if (signer)
782     {
783       if (is_selfsig)
784         {
785           if (signer->keyid[0] == pripk->keyid[0]
786               && signer->keyid[1] == pripk->keyid[1])
787             *is_selfsig = 1;
788           else
789             *is_selfsig = 0;
790         }
791     }
792   else
793     {
794       /* Get the signer.  If possible, avoid a look up.  */
795       if (sig->keyid[0] == pripk->keyid[0]
796           && sig->keyid[1] == pripk->keyid[1])
797         /* Issued by the primary key.  */
798         {
799           signer = pripk;
800           if (is_selfsig)
801             *is_selfsig = 1;
802         }
803       else
804         {
805           kbnode_t ctx = NULL;
806           kbnode_t n;
807
808           /* See if one of the subkeys was the signer (although this
809              is extremely unlikely).  */
810           while ((n = walk_kbnode (kb, &ctx, 0)))
811             {
812               PKT_public_key *subk;
813
814               if (n->pkt->pkttype != PKT_PUBLIC_SUBKEY)
815                 continue;
816
817               subk = n->pkt->pkt.public_key;
818               if (sig->keyid[0] == subk->keyid[0]
819                   && sig->keyid[1] == subk->keyid[1])
820                 /* Issued by a subkey.  */
821                 {
822                   signer = subk;
823                   break;
824                 }
825             }
826
827           if (! signer)
828             /* Signer by some other key.  */
829             {
830               if (is_selfsig)
831                 *is_selfsig = 0;
832               if (ret_pk)
833                 {
834                   signer = ret_pk;
835                   memset (signer, 0, sizeof (*signer));
836                   signer_alloced = 1;
837                 }
838               else
839                 {
840                   signer = xmalloc_clear (sizeof (*signer));
841                   signer_alloced = 2;
842                 }
843
844               rc = get_pubkey (signer, sig->keyid);
845               if (rc)
846                 {
847                   xfree (signer);
848                   signer = NULL;
849                   signer_alloced = 0;
850                   goto out;
851                 }
852             }
853         }
854     }
855
856   /* We checked above that we supported this algo, so an error here is
857      a bug.  */
858   if (gcry_md_open (&md, sig->digest_algo, 0))
859     BUG ();
860
861   /* Hash the relevant data.  */
862
863   if (/* Direct key signature.  */
864       sig->sig_class == 0x1f
865       /* Primary key revocation.  */
866       || sig->sig_class == 0x20)
867     {
868       log_assert (packet->pkttype == PKT_PUBLIC_KEY);
869       hash_public_key (md, packet->pkt.public_key);
870       rc = check_signature_end_simple (signer, sig, md);
871     }
872   else if (/* Primary key binding (made by a subkey).  */
873       sig->sig_class == 0x19)
874     {
875       log_assert (packet->pkttype == PKT_PUBLIC_KEY);
876       hash_public_key (md, packet->pkt.public_key);
877       hash_public_key (md, signer);
878       rc = check_signature_end_simple (signer, sig, md);
879     }
880   else if (/* Subkey binding.  */
881            sig->sig_class == 0x18
882            /* Subkey revocation.  */
883            || sig->sig_class == 0x28)
884     {
885       log_assert (packet->pkttype == PKT_PUBLIC_SUBKEY);
886       hash_public_key (md, pripk);
887       hash_public_key (md, packet->pkt.public_key);
888       rc = check_signature_end_simple (signer, sig, md);
889     }
890   else if (/* Certification.  */
891            sig->sig_class == 0x10
892            || sig->sig_class == 0x11
893            || sig->sig_class == 0x12
894            || sig->sig_class == 0x13
895            /* Certification revocation.  */
896            || sig->sig_class == 0x30)
897     {
898       log_assert (packet->pkttype == PKT_USER_ID);
899       hash_public_key (md, pripk);
900       hash_uid_packet (packet->pkt.user_id, md, sig);
901       rc = check_signature_end_simple (signer, sig, md);
902     }
903   else
904     /* We should never get here.  (The first if above should have
905        already caught this error.)  */
906     BUG ();
907
908   gcry_md_close (md);
909
910  out:
911   if (! rc && ret_pk && (signer_alloced == -1 || ret_pk != signer))
912     copy_public_key (ret_pk, signer);
913   if (signer_alloced == 1)
914     /* We looked up SIGNER; it is not a pointer into KB.  */
915     {
916       release_public_key_parts (signer);
917       if (signer_alloced == 2)
918         /* We also allocated the memory.  */
919         xfree (signer);
920     }
921
922   return rc;
923 }
924
925 /* Check that a signature over a key (e.g., a key revocation, key
926  * binding, user id certification, etc.) is valid.  If the function
927  * detects a self-signature, it uses the public key from the specified
928  * key block and does not bother looking up the key specified in the
929  * signature packet.
930  *
931  * ROOT is a keyblock.
932  *
933  * NODE references a signature packet that appears in the keyblock
934  * that should be verified.
935  *
936  * If CHECK_PK is set, the specified key is sometimes preferred for
937  * verifying signatures.  See the implementation for details.
938  *
939  * If RET_PK is not NULL, the public key that successfully verified
940  * the signature is copied into *RET_PK.
941  *
942  * If IS_SELFSIG is not NULL, *IS_SELFSIG is set to 1 if NODE is a
943  * self-signature.
944  *
945  * If R_EXPIREDATE is not NULL, *R_EXPIREDATE is set to the expiry
946  * date.
947  *
948  * If R_EXPIRED is not NULL, *R_EXPIRED is set to 1 if PK has been
949  * expired (0 otherwise).  Note: PK being revoked does not cause this
950  * function to fail.
951  *
952  *
953  * If OPT.NO_SIG_CACHE is not set, this function will first check if
954  * the result of a previous verification is already cached in the
955  * signature packet's data structure.
956  *
957  * TODO: add r_revoked here as well.  It has the same problems as
958  * r_expiredate and r_expired and the cache.  */
959 int
960 check_key_signature2 (kbnode_t root, kbnode_t node, PKT_public_key *check_pk,
961                       PKT_public_key *ret_pk, int *is_selfsig,
962                       u32 *r_expiredate, int *r_expired )
963 {
964   PKT_public_key *pk;
965   PKT_signature *sig;
966   int algo;
967   int rc;
968
969   if (is_selfsig)
970     *is_selfsig = 0;
971   if (r_expiredate)
972     *r_expiredate = 0;
973   if (r_expired)
974     *r_expired = 0;
975   log_assert (node->pkt->pkttype == PKT_SIGNATURE);
976   log_assert (root->pkt->pkttype == PKT_PUBLIC_KEY);
977
978   pk = root->pkt->pkt.public_key;
979   sig = node->pkt->pkt.signature;
980   algo = sig->digest_algo;
981
982   /* Check whether we have cached the result of a previous signature
983      check.  Note that we may no longer have the pubkey or hash
984      needed to verify a sig, but can still use the cached value.  A
985      cache refresh detects and clears these cases. */
986   if ( !opt.no_sig_cache )
987     {
988       if (sig->flags.checked) /* Cached status available.  */
989         {
990           if (is_selfsig)
991             {
992               u32 keyid[2];
993
994               keyid_from_pk (pk, keyid);
995               if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1])
996                 *is_selfsig = 1;
997             }
998           /* BUG: This is wrong for non-self-sigs... needs to be the
999              actual pk.  */
1000           rc = check_signature_metadata_validity (pk, sig, r_expired, NULL);
1001           if (rc)
1002             return rc;
1003           return sig->flags.valid? 0 : gpg_error (GPG_ERR_BAD_SIGNATURE);
1004         }
1005     }
1006
1007   rc = openpgp_pk_test_algo(sig->pubkey_algo);
1008   if (rc)
1009     return rc;
1010   rc = openpgp_md_test_algo(algo);
1011   if (rc)
1012     return rc;
1013
1014   if (sig->sig_class == 0x20) /* key revocation */
1015     {
1016       u32 keyid[2];
1017       keyid_from_pk( pk, keyid );
1018
1019       /* Is it a designated revoker? */
1020       if (keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1])
1021         rc = check_revocation_keys (pk, sig);
1022       else
1023         {
1024           rc = check_signature_metadata_validity (pk, sig,
1025                                                   r_expired, NULL);
1026           if (! rc)
1027             rc = check_signature_over_key_or_uid (pk, sig, root, root->pkt,
1028                                                   is_selfsig, ret_pk);
1029         }
1030     }
1031   else if (sig->sig_class == 0x28  /* subkey revocation */
1032            || sig->sig_class == 0x18) /* key binding */
1033     {
1034       kbnode_t snode = find_prev_kbnode (root, node, PKT_PUBLIC_SUBKEY);
1035
1036       if (snode)
1037         {
1038           rc = check_signature_metadata_validity (pk, sig,
1039                                                   r_expired, NULL);
1040           if (! rc)
1041             /* 0x28 must be a self-sig, but 0x18 needn't be.  */
1042             rc = check_signature_over_key_or_uid (sig->sig_class == 0x18
1043                                                   ? NULL : pk,
1044                                                   sig, root, snode->pkt,
1045                                                   is_selfsig, ret_pk);
1046         }
1047       else
1048         {
1049           if (opt.verbose)
1050             {
1051               if (sig->sig_class == 0x28)
1052                 log_info (_("key %s: no subkey for subkey"
1053                             " revocation signature\n"), keystr_from_pk(pk));
1054               else if (sig->sig_class == 0x18)
1055                 log_info(_("key %s: no subkey for subkey"
1056                            " binding signature\n"), keystr_from_pk(pk));
1057             }
1058           rc = GPG_ERR_SIG_CLASS;
1059         }
1060     }
1061     else if (sig->sig_class == 0x1f) /* direct key signature */
1062       {
1063         rc = check_signature_metadata_validity (pk, sig,
1064                                                 r_expired, NULL);
1065         if (! rc)
1066           rc = check_signature_over_key_or_uid (pk, sig, root, root->pkt,
1067                                                 is_selfsig, ret_pk);
1068       }
1069     else if (/* Certification.  */
1070              sig->sig_class == 0x10
1071              || sig->sig_class == 0x11
1072              || sig->sig_class == 0x12
1073              || sig->sig_class == 0x13
1074              /* Certification revocation.  */
1075              || sig->sig_class == 0x30)
1076       {
1077         kbnode_t unode = find_prev_kbnode (root, node, PKT_USER_ID);
1078
1079         if (unode)
1080           {
1081             rc = check_signature_metadata_validity (pk, sig, r_expired, NULL);
1082             if (! rc)
1083               /* If this is a self-sig, ignore check_pk.  */
1084               rc = check_signature_over_key_or_uid
1085                 (keyid_cmp (pk_keyid (pk), sig->keyid) == 0 ? pk : check_pk,
1086                  sig, root, unode->pkt, NULL, ret_pk);
1087           }
1088         else
1089           {
1090             if (!opt.quiet)
1091               log_info ("key %s: no user ID for key signature packet"
1092                         " of class %02x\n",keystr_from_pk(pk),sig->sig_class);
1093             rc = GPG_ERR_SIG_CLASS;
1094           }
1095       }
1096   else
1097     {
1098       log_info ("sig issued by %s with class %d (digest: %02x %02x)"
1099                 " is not valid over a user id or a key id, ignoring.\n",
1100                 keystr (sig->keyid), sig->sig_class,
1101                 sig->digest_start[0], sig->digest_start[1]);
1102       rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
1103     }
1104
1105   cache_sig_result  (sig, rc);
1106
1107   return rc;
1108 }