1 /* certlist.c - build list of certificates
2  * Copyright (C) 2001, 2003, 2004, 2005, 2007,
3  *               2008, 2011 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
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 3 of the License, or
10  * (at your option) any later version.
11  *
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.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <time.h>
28 
29 #include "gpgsm.h"
30 #include <gcrypt.h>
31 #include <ksba.h>
32 
33 #include "keydb.h"
34 #include "../common/i18n.h"
35 
36 
37 static const char oid_kp_serverAuth[]     = "1.3.6.1.5.5.7.3.1";
38 static const char oid_kp_clientAuth[]     = "1.3.6.1.5.5.7.3.2";
39 static const char oid_kp_codeSigning[]    = "1.3.6.1.5.5.7.3.3";
40 static const char oid_kp_emailProtection[]= "1.3.6.1.5.5.7.3.4";
41 static const char oid_kp_timeStamping[]   = "1.3.6.1.5.5.7.3.8";
42 static const char oid_kp_ocspSigning[]    = "1.3.6.1.5.5.7.3.9";
43 
44 /* Return 0 if the cert is usable for encryption.  A MODE of 0 checks
45    for signing a MODE of 1 checks for encryption, a MODE of 2 checks
46    for verification and a MODE of 3 for decryption (just for
47    debugging).  MODE 4 is for certificate signing, MODE for COSP
48    response signing. */
49 static int
cert_usage_p(ksba_cert_t cert,int mode,int silent)50 cert_usage_p (ksba_cert_t cert, int mode, int silent)
51 {
52   gpg_error_t err;
53   unsigned int use;
54   char *extkeyusages;
55   int have_ocsp_signing = 0;
56 
57   err = ksba_cert_get_ext_key_usages (cert, &extkeyusages);
58   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
59     err = 0; /* no policy given */
60   if (!err)
61     {
62       unsigned int extusemask = ~0; /* Allow all. */
63 
64       if (extkeyusages)
65         {
66           char *p, *pend;
67           int any_critical = 0;
68 
69           extusemask = 0;
70 
71           p = extkeyusages;
72           while (p && (pend=strchr (p, ':')))
73             {
74               *pend++ = 0;
75               /* Only care about critical flagged usages. */
76               if ( *pend == 'C' )
77                 {
78                   any_critical = 1;
79                   if ( !strcmp (p, oid_kp_serverAuth))
80                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
81                                    | KSBA_KEYUSAGE_KEY_ENCIPHERMENT
82                                    | KSBA_KEYUSAGE_KEY_AGREEMENT);
83                   else if ( !strcmp (p, oid_kp_clientAuth))
84                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
85                                    | KSBA_KEYUSAGE_KEY_AGREEMENT);
86                   else if ( !strcmp (p, oid_kp_codeSigning))
87                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE);
88                   else if ( !strcmp (p, oid_kp_emailProtection))
89                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
90                                    | KSBA_KEYUSAGE_NON_REPUDIATION
91                                    | KSBA_KEYUSAGE_KEY_ENCIPHERMENT
92                                    | KSBA_KEYUSAGE_KEY_AGREEMENT);
93                   else if ( !strcmp (p, oid_kp_timeStamping))
94                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
95                                    | KSBA_KEYUSAGE_NON_REPUDIATION);
96                 }
97 
98               /* This is a hack to cope with OCSP.  Note that we do
99                  not yet fully comply with the requirements and that
100                  the entire CRL/OCSP checking thing should undergo a
101                  thorough review and probably redesign. */
102               if ( !strcmp (p, oid_kp_ocspSigning))
103                 have_ocsp_signing = 1;
104 
105               if ((p = strchr (pend, '\n')))
106                 p++;
107             }
108           xfree (extkeyusages);
109           extkeyusages = NULL;
110 
111           if (!any_critical)
112             extusemask = ~0; /* Reset to the don't care mask. */
113         }
114 
115 
116       err = ksba_cert_get_key_usage (cert, &use);
117       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
118         {
119           err = 0;
120           if (opt.verbose && mode < 2 && !silent)
121             log_info (_("no key usage specified - assuming all usages\n"));
122           use = ~0;
123         }
124 
125       /* Apply extKeyUsage. */
126       use &= extusemask;
127 
128     }
129   if (err)
130     {
131       log_error (_("error getting key usage information: %s\n"),
132                  gpg_strerror (err));
133       xfree (extkeyusages);
134       return err;
135     }
136 
137   if (mode == 4)
138     {
139       if ((use & (KSBA_KEYUSAGE_KEY_CERT_SIGN)))
140         return 0;
141       if (!silent)
142         log_info (_("certificate should not have "
143                     "been used for certification\n"));
144       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
145     }
146 
147   if (mode == 5)
148     {
149       if (use != ~0
150           && (have_ocsp_signing
151               || (use & (KSBA_KEYUSAGE_KEY_CERT_SIGN
152                          |KSBA_KEYUSAGE_CRL_SIGN))))
153         return 0;
154       if (!silent)
155         log_info (_("certificate should not have "
156                     "been used for OCSP response signing\n"));
157       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
158     }
159 
160   if ((use & ((mode&1)?
161               (KSBA_KEYUSAGE_KEY_ENCIPHERMENT|KSBA_KEYUSAGE_DATA_ENCIPHERMENT):
162               (KSBA_KEYUSAGE_DIGITAL_SIGNATURE|KSBA_KEYUSAGE_NON_REPUDIATION)))
163       )
164     return 0;
165 
166   if (!silent)
167     log_info
168       (mode==3? _("certificate should not have been used for encryption\n"):
169        mode==2? _("certificate should not have been used for signing\n"):
170        mode==1? _("certificate is not usable for encryption\n"):
171        /**/     _("certificate is not usable for signing\n"));
172 
173   return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
174 }
175 
176 
177 /* Return 0 if the cert is usable for signing */
178 int
gpgsm_cert_use_sign_p(ksba_cert_t cert,int silent)179 gpgsm_cert_use_sign_p (ksba_cert_t cert, int silent)
180 {
181   return cert_usage_p (cert, 0, silent);
182 }
183 
184 
185 /* Return 0 if the cert is usable for encryption */
186 int
gpgsm_cert_use_encrypt_p(ksba_cert_t cert)187 gpgsm_cert_use_encrypt_p (ksba_cert_t cert)
188 {
189   return cert_usage_p (cert, 1, 0);
190 }
191 
192 int
gpgsm_cert_use_verify_p(ksba_cert_t cert)193 gpgsm_cert_use_verify_p (ksba_cert_t cert)
194 {
195   return cert_usage_p (cert, 2, 0);
196 }
197 
198 int
gpgsm_cert_use_decrypt_p(ksba_cert_t cert)199 gpgsm_cert_use_decrypt_p (ksba_cert_t cert)
200 {
201   return cert_usage_p (cert, 3, 0);
202 }
203 
204 int
gpgsm_cert_use_cert_p(ksba_cert_t cert)205 gpgsm_cert_use_cert_p (ksba_cert_t cert)
206 {
207   return cert_usage_p (cert, 4, 0);
208 }
209 
210 int
gpgsm_cert_use_ocsp_p(ksba_cert_t cert)211 gpgsm_cert_use_ocsp_p (ksba_cert_t cert)
212 {
213   return cert_usage_p (cert, 5, 0);
214 }
215 
216 
217 /* Return true if CERT has the well known private key extension.  */
218 int
gpgsm_cert_has_well_known_private_key(ksba_cert_t cert)219 gpgsm_cert_has_well_known_private_key (ksba_cert_t cert)
220 {
221   int idx;
222   const char *oid;
223 
224   for (idx=0; !ksba_cert_get_extension (cert, idx,
225                                         &oid, NULL, NULL, NULL);idx++)
226     if (!strcmp (oid, "1.3.6.1.4.1.11591.2.2.2") )
227       return 1; /* Yes.  */
228   return 0; /* No.  */
229 }
230 
231 
232 static int
same_subject_issuer(const char * subject,const char * issuer,ksba_cert_t cert)233 same_subject_issuer (const char *subject, const char *issuer, ksba_cert_t cert)
234 {
235   char *subject2 = ksba_cert_get_subject (cert, 0);
236   char *issuer2 = ksba_cert_get_issuer (cert, 0);
237   int tmp;
238 
239   tmp = (subject && subject2
240          && !strcmp (subject, subject2)
241          && issuer && issuer2
242          && !strcmp (issuer, issuer2));
243   xfree (subject2);
244   xfree (issuer2);
245   return tmp;
246 }
247 
248 
249 /* Return true if CERT_A is the same as CERT_B.  */
250 int
gpgsm_certs_identical_p(ksba_cert_t cert_a,ksba_cert_t cert_b)251 gpgsm_certs_identical_p (ksba_cert_t cert_a, ksba_cert_t cert_b)
252 {
253   const unsigned char *img_a, *img_b;
254   size_t len_a, len_b;
255 
256   img_a = ksba_cert_get_image (cert_a, &len_a);
257   if (img_a)
258     {
259       img_b = ksba_cert_get_image (cert_b, &len_b);
260       if (img_b && len_a == len_b && !memcmp (img_a, img_b, len_a))
261         return 1; /* Identical. */
262     }
263   return 0;
264 }
265 
266 
267 /* Return true if CERT is already contained in CERTLIST. */
268 static int
is_cert_in_certlist(ksba_cert_t cert,certlist_t certlist)269 is_cert_in_certlist (ksba_cert_t cert, certlist_t certlist)
270 {
271   const unsigned char *img_a, *img_b;
272   size_t len_a, len_b;
273 
274   img_a = ksba_cert_get_image (cert, &len_a);
275   if (img_a)
276     {
277       for ( ; certlist; certlist = certlist->next)
278         {
279           img_b = ksba_cert_get_image (certlist->cert, &len_b);
280           if (img_b && len_a == len_b && !memcmp (img_a, img_b, len_a))
281             return 1; /* Already contained. */
282         }
283     }
284   return 0;
285 }
286 
287 
288 /* Add CERT to the list of certificates at CERTADDR but avoid
289    duplicates. */
290 int
gpgsm_add_cert_to_certlist(ctrl_t ctrl,ksba_cert_t cert,certlist_t * listaddr,int is_encrypt_to)291 gpgsm_add_cert_to_certlist (ctrl_t ctrl, ksba_cert_t cert,
292                             certlist_t *listaddr, int is_encrypt_to)
293 {
294   (void)ctrl;
295 
296   if (!is_cert_in_certlist (cert, *listaddr))
297     {
298       certlist_t cl = xtrycalloc (1, sizeof *cl);
299       if (!cl)
300         return out_of_core ();
301       cl->cert = cert;
302       ksba_cert_ref (cert);
303       cl->next = *listaddr;
304       cl->is_encrypt_to = is_encrypt_to;
305       *listaddr = cl;
306     }
307    return 0;
308 }
309 
310 /* Add a certificate to a list of certificate and make sure that it is
311    a valid certificate.  With SECRET set to true a secret key must be
312    available for the certificate. IS_ENCRYPT_TO sets the corresponding
313    flag in the new create LISTADDR item.  */
314 int
gpgsm_add_to_certlist(ctrl_t ctrl,const char * name,int secret,certlist_t * listaddr,int is_encrypt_to)315 gpgsm_add_to_certlist (ctrl_t ctrl, const char *name, int secret,
316                        certlist_t *listaddr, int is_encrypt_to)
317 {
318   int rc;
319   KEYDB_SEARCH_DESC desc;
320   KEYDB_HANDLE kh = NULL;
321   ksba_cert_t cert = NULL;
322 
323   rc = classify_user_id (name, &desc, 0);
324   if (!rc)
325     {
326       kh = keydb_new (ctrl);
327       if (!kh)
328         rc = gpg_error (GPG_ERR_ENOMEM);
329       else
330         {
331           int wrong_usage = 0;
332           char *first_subject = NULL;
333           char *first_issuer = NULL;
334 
335         get_next:
336           rc = keydb_search (ctrl, kh, &desc, 1);
337           if (!rc)
338             rc = keydb_get_cert (kh, &cert);
339           if (!rc)
340             {
341               if (!first_subject)
342                 {
343                   /* Save the subject and the issuer for key usage
344                      and ambiguous name tests. */
345                   first_subject = ksba_cert_get_subject (cert, 0);
346                   first_issuer = ksba_cert_get_issuer (cert, 0);
347                 }
348               rc = secret? gpgsm_cert_use_sign_p (cert, 0)
349                          : gpgsm_cert_use_encrypt_p (cert);
350               if (gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE)
351                 {
352                   /* There might be another certificate with the
353                      correct usage, so we try again */
354                   if (!wrong_usage
355                       || same_subject_issuer (first_subject, first_issuer,cert))
356                     {
357                       if (!wrong_usage)
358                         wrong_usage = rc; /* save error of the first match */
359                       ksba_cert_release (cert);
360                       cert = NULL;
361                       log_info (_("looking for another certificate\n"));
362                       goto get_next;
363                     }
364                   else
365                     wrong_usage = rc;
366 
367                 }
368             }
369           /* We want the error code from the first match in this case. */
370           if (rc && wrong_usage)
371             rc = wrong_usage;
372 
373           if (!rc)
374             {
375               certlist_t dup_certs = NULL;
376 
377             next_ambigious:
378               rc = keydb_search (ctrl, kh, &desc, 1);
379               if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
380                 rc = 0;
381               else if (!rc)
382                 {
383                   ksba_cert_t cert2 = NULL;
384 
385                   /* If this is the first possible duplicate, add the original
386                      certificate to our list of duplicates.  */
387                   if (!dup_certs)
388                     gpgsm_add_cert_to_certlist (ctrl, cert, &dup_certs, 0);
389 
390                   /* We have to ignore ambiguous names as long as
391                      there only fault is a bad key usage.  This is
392                      required to support encryption and signing
393                      certificates of the same subject.
394 
395                      Further we ignore them if they are due to an
396                      identical certificate (which may happen if a
397                      certificate is accidentally duplicated in the
398                      keybox).  */
399                   if (!keydb_get_cert (kh, &cert2))
400                     {
401                       int tmp = (same_subject_issuer (first_subject,
402                                                       first_issuer,
403                                                       cert2)
404                                  && ((gpg_err_code (
405                                       secret? gpgsm_cert_use_sign_p (cert2,0)
406                                             : gpgsm_cert_use_encrypt_p (cert2)
407                                       )
408                                      )  == GPG_ERR_WRONG_KEY_USAGE));
409                       if (tmp)
410                         gpgsm_add_cert_to_certlist (ctrl, cert2,
411                                                     &dup_certs, 0);
412                       else
413                         {
414                           if (is_cert_in_certlist (cert2, dup_certs))
415                             tmp = 1;
416                         }
417 
418                       ksba_cert_release (cert2);
419                       if (tmp)
420                         goto next_ambigious;
421                     }
422                   rc = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
423                 }
424               gpgsm_release_certlist (dup_certs);
425             }
426           xfree (first_subject);
427           xfree (first_issuer);
428           first_subject = NULL;
429           first_issuer = NULL;
430 
431           if (!rc && !is_cert_in_certlist (cert, *listaddr))
432             {
433               if (!rc && secret)
434                 {
435                   char *p;
436 
437                   rc = gpg_error (GPG_ERR_NO_SECKEY);
438                   p = gpgsm_get_keygrip_hexstring (cert);
439                   if (p)
440                     {
441                       if (!gpgsm_agent_havekey (ctrl, p))
442                         rc = 0;
443                       xfree (p);
444                     }
445                 }
446               if (!rc)
447                 rc = gpgsm_validate_chain (ctrl, cert, "", NULL,
448                                            0, NULL, 0, NULL);
449               if (!rc)
450                 {
451                   certlist_t cl = xtrycalloc (1, sizeof *cl);
452                   if (!cl)
453                     rc = gpg_error_from_syserror ();
454                   else
455                     {
456                       cl->cert = cert; cert = NULL;
457                       cl->next = *listaddr;
458                       cl->is_encrypt_to = is_encrypt_to;
459                       *listaddr = cl;
460                     }
461                 }
462             }
463         }
464     }
465 
466   keydb_release (kh);
467   ksba_cert_release (cert);
468   return (gpg_err_code (rc) == GPG_ERR_NOT_FOUND
469           ? gpg_error (GPG_ERR_NO_PUBKEY): rc);
470 }
471 
472 
473 void
gpgsm_release_certlist(certlist_t list)474 gpgsm_release_certlist (certlist_t list)
475 {
476   while (list)
477     {
478       certlist_t cl = list->next;
479       ksba_cert_release (list->cert);
480       xfree (list);
481       list = cl;
482     }
483 }
484 
485 
486 /* Like gpgsm_add_to_certlist, but look only for one certificate.  No
487    chain validation is done.  If KEYID is not NULL it is taken as an
488    additional filter value which must match the
489    subjectKeyIdentifier. */
490 int
gpgsm_find_cert(ctrl_t ctrl,const char * name,ksba_sexp_t keyid,ksba_cert_t * r_cert,int allow_ambiguous)491 gpgsm_find_cert (ctrl_t ctrl,
492                  const char *name, ksba_sexp_t keyid, ksba_cert_t *r_cert,
493                  int allow_ambiguous)
494 {
495   int rc;
496   KEYDB_SEARCH_DESC desc;
497   KEYDB_HANDLE kh = NULL;
498 
499   *r_cert = NULL;
500   rc = classify_user_id (name, &desc, 0);
501   if (!rc)
502     {
503       kh = keydb_new (ctrl);
504       if (!kh)
505         rc = gpg_error (GPG_ERR_ENOMEM);
506       else
507         {
508         nextone:
509           rc = keydb_search (ctrl, kh, &desc, 1);
510           if (!rc)
511             {
512               rc = keydb_get_cert (kh, r_cert);
513               if (!rc && keyid)
514                 {
515                   ksba_sexp_t subj;
516 
517                   rc = ksba_cert_get_subj_key_id (*r_cert, NULL, &subj);
518                   if (!rc)
519                     {
520                       if (cmp_simple_canon_sexp (keyid, subj))
521                         {
522                           xfree (subj);
523                           goto nextone;
524                         }
525                       xfree (subj);
526                       /* Okay: Here we know that the certificate's
527                          subjectKeyIdentifier matches the requested
528                          one. */
529                     }
530                   else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
531                     goto nextone;
532                 }
533             }
534 
535           /* If we don't have the KEYID filter we need to check for
536              ambiguous search results.  Note, that it is somewhat
537              reasonable to assume that a specification of a KEYID
538              won't lead to ambiguous names. */
539           if (!rc && !keyid)
540             {
541               ksba_isotime_t notbefore = "";
542               const unsigned char *image = NULL;
543               size_t length = 0;
544               if (allow_ambiguous)
545                 {
546                   /* We want to return the newest certificate */
547                   if (ksba_cert_get_validity (*r_cert, 0, notbefore))
548                     *notbefore = '\0';
549                   image = ksba_cert_get_image (*r_cert, &length);
550                 }
551             next_ambiguous:
552               rc = keydb_search (ctrl, kh, &desc, 1);
553               if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
554                 rc = 0;
555               else
556                 {
557                   if (!rc)
558                     {
559                       ksba_cert_t cert2 = NULL;
560                       ksba_isotime_t notbefore2 = "";
561                       const unsigned char *image2 = NULL;
562                       size_t length2 = 0;
563                       int cmp = 0;
564 
565                       if (!keydb_get_cert (kh, &cert2))
566                         {
567                           if (gpgsm_certs_identical_p (*r_cert, cert2))
568                             {
569                               ksba_cert_release (cert2);
570                               goto next_ambiguous;
571                             }
572                           if (allow_ambiguous)
573                             {
574                               if (ksba_cert_get_validity (cert2, 0, notbefore2))
575                                 *notbefore2 = '\0';
576                               image2 = ksba_cert_get_image (cert2, &length2);
577                               cmp = strcmp (notbefore, notbefore2);
578                               /* use certificate image bits as last resort for stable ordering */
579                               if (!cmp)
580                                 cmp = memcmp (image, image2, length < length2 ? length : length2);
581                               if (!cmp)
582                                 cmp = length < length2 ? -1 : length > length2 ? 1 : 0;
583                               if (cmp < 0)
584                                 {
585                                   ksba_cert_release (*r_cert);
586                                   *r_cert = cert2;
587                                   strcpy (notbefore, notbefore2);
588                                   image = image2;
589                                   length = length2;
590                                 }
591                               else
592                                 ksba_cert_release (cert2);
593                               goto next_ambiguous;
594                             }
595                           ksba_cert_release (cert2);
596                         }
597                       rc = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
598                     }
599                   ksba_cert_release (*r_cert);
600                   *r_cert = NULL;
601                 }
602             }
603         }
604     }
605 
606   keydb_release (kh);
607   return (gpg_err_code (rc) == GPG_ERR_NOT_FOUND?
608           gpg_error (GPG_ERR_NO_PUBKEY): rc);
609 }
610