• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * SPDX-License-Identifier: curl
22  *
23  ***************************************************************************/
24 
25 #include "curl_setup.h"
26 
27 #if defined(USE_GNUTLS) || defined(USE_WOLFSSL) ||      \
28   defined(USE_SCHANNEL) || defined(USE_SECTRANSP)
29 
30 #if defined(USE_WOLFSSL) || defined(USE_SCHANNEL)
31 #define WANT_PARSEX509 /* uses Curl_parseX509() */
32 #endif
33 
34 #if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP)
35 #define WANT_EXTRACT_CERTINFO /* uses Curl_extract_certinfo() */
36 #define WANT_PARSEX509 /* ... uses Curl_parseX509() */
37 #endif
38 
39 #include <curl/curl.h>
40 #include "urldata.h"
41 #include "strcase.h"
42 #include "curl_ctype.h"
43 #include "hostcheck.h"
44 #include "vtls/vtls.h"
45 #include "vtls/vtls_int.h"
46 #include "sendf.h"
47 #include "inet_pton.h"
48 #include "curl_base64.h"
49 #include "x509asn1.h"
50 #include "dynbuf.h"
51 
52 /* The last 3 #include files should be in this order */
53 #include "curl_printf.h"
54 #include "curl_memory.h"
55 #include "memdebug.h"
56 
57 /*
58  * Constants.
59  */
60 
61 /* Largest supported ASN.1 structure. */
62 #define CURL_ASN1_MAX                   ((size_t) 0x40000)      /* 256K */
63 
64 /* ASN.1 classes. */
65 #define CURL_ASN1_UNIVERSAL             0
66 #define CURL_ASN1_APPLICATION           1
67 #define CURL_ASN1_CONTEXT_SPECIFIC      2
68 #define CURL_ASN1_PRIVATE               3
69 
70 /* ASN.1 types. */
71 #define CURL_ASN1_BOOLEAN               1
72 #define CURL_ASN1_INTEGER               2
73 #define CURL_ASN1_BIT_STRING            3
74 #define CURL_ASN1_OCTET_STRING          4
75 #define CURL_ASN1_NULL                  5
76 #define CURL_ASN1_OBJECT_IDENTIFIER     6
77 #define CURL_ASN1_OBJECT_DESCRIPTOR     7
78 #define CURL_ASN1_INSTANCE_OF           8
79 #define CURL_ASN1_REAL                  9
80 #define CURL_ASN1_ENUMERATED            10
81 #define CURL_ASN1_EMBEDDED              11
82 #define CURL_ASN1_UTF8_STRING           12
83 #define CURL_ASN1_RELATIVE_OID          13
84 #define CURL_ASN1_SEQUENCE              16
85 #define CURL_ASN1_SET                   17
86 #define CURL_ASN1_NUMERIC_STRING        18
87 #define CURL_ASN1_PRINTABLE_STRING      19
88 #define CURL_ASN1_TELETEX_STRING        20
89 #define CURL_ASN1_VIDEOTEX_STRING       21
90 #define CURL_ASN1_IA5_STRING            22
91 #define CURL_ASN1_UTC_TIME              23
92 #define CURL_ASN1_GENERALIZED_TIME      24
93 #define CURL_ASN1_GRAPHIC_STRING        25
94 #define CURL_ASN1_VISIBLE_STRING        26
95 #define CURL_ASN1_GENERAL_STRING        27
96 #define CURL_ASN1_UNIVERSAL_STRING      28
97 #define CURL_ASN1_CHARACTER_STRING      29
98 #define CURL_ASN1_BMP_STRING            30
99 
100 /* Max sixes */
101 
102 #define MAX_X509_STR  10000
103 #define MAX_X509_CERT 100000
104 
105 #ifdef WANT_EXTRACT_CERTINFO
106 /* ASN.1 OID table entry. */
107 struct Curl_OID {
108   const char *numoid;  /* Dotted-numeric OID. */
109   const char *textoid; /* OID name. */
110 };
111 
112 /* ASN.1 OIDs. */
113 static const char       cnOID[] = "2.5.4.3";    /* Common name. */
114 static const char       sanOID[] = "2.5.29.17"; /* Subject alternative name. */
115 
116 static const struct Curl_OID OIDtable[] = {
117   { "1.2.840.10040.4.1",        "dsa" },
118   { "1.2.840.10040.4.3",        "dsa-with-sha1" },
119   { "1.2.840.10045.2.1",        "ecPublicKey" },
120   { "1.2.840.10045.3.0.1",      "c2pnb163v1" },
121   { "1.2.840.10045.4.1",        "ecdsa-with-SHA1" },
122   { "1.2.840.10046.2.1",        "dhpublicnumber" },
123   { "1.2.840.113549.1.1.1",     "rsaEncryption" },
124   { "1.2.840.113549.1.1.2",     "md2WithRSAEncryption" },
125   { "1.2.840.113549.1.1.4",     "md5WithRSAEncryption" },
126   { "1.2.840.113549.1.1.5",     "sha1WithRSAEncryption" },
127   { "1.2.840.113549.1.1.10",    "RSASSA-PSS" },
128   { "1.2.840.113549.1.1.14",    "sha224WithRSAEncryption" },
129   { "1.2.840.113549.1.1.11",    "sha256WithRSAEncryption" },
130   { "1.2.840.113549.1.1.12",    "sha384WithRSAEncryption" },
131   { "1.2.840.113549.1.1.13",    "sha512WithRSAEncryption" },
132   { "1.2.840.113549.2.2",       "md2" },
133   { "1.2.840.113549.2.5",       "md5" },
134   { "1.3.14.3.2.26",            "sha1" },
135   { cnOID,                      "CN" },
136   { "2.5.4.4",                  "SN" },
137   { "2.5.4.5",                  "serialNumber" },
138   { "2.5.4.6",                  "C" },
139   { "2.5.4.7",                  "L" },
140   { "2.5.4.8",                  "ST" },
141   { "2.5.4.9",                  "streetAddress" },
142   { "2.5.4.10",                 "O" },
143   { "2.5.4.11",                 "OU" },
144   { "2.5.4.12",                 "title" },
145   { "2.5.4.13",                 "description" },
146   { "2.5.4.17",                 "postalCode" },
147   { "2.5.4.41",                 "name" },
148   { "2.5.4.42",                 "givenName" },
149   { "2.5.4.43",                 "initials" },
150   { "2.5.4.44",                 "generationQualifier" },
151   { "2.5.4.45",                 "X500UniqueIdentifier" },
152   { "2.5.4.46",                 "dnQualifier" },
153   { "2.5.4.65",                 "pseudonym" },
154   { "1.2.840.113549.1.9.1",     "emailAddress" },
155   { "2.5.4.72",                 "role" },
156   { sanOID,                     "subjectAltName" },
157   { "2.5.29.18",                "issuerAltName" },
158   { "2.5.29.19",                "basicConstraints" },
159   { "2.16.840.1.101.3.4.2.4",   "sha224" },
160   { "2.16.840.1.101.3.4.2.1",   "sha256" },
161   { "2.16.840.1.101.3.4.2.2",   "sha384" },
162   { "2.16.840.1.101.3.4.2.3",   "sha512" },
163   { "1.2.840.113549.1.9.2",     "unstructuredName" },
164   { (const char *) NULL,        (const char *) NULL }
165 };
166 
167 #endif /* WANT_EXTRACT_CERTINFO */
168 
169 /*
170  * Lightweight ASN.1 parser.
171  * In particular, it does not check for syntactic/lexical errors.
172  * It is intended to support certificate information gathering for SSL backends
173  * that offer a mean to get certificates as a whole, but do not supply
174  * entry points to get particular certificate sub-fields.
175  * Please note there is no pretension here to rewrite a full SSL library.
176  */
177 
178 static const char *getASN1Element(struct Curl_asn1Element *elem,
179                                   const char *beg, const char *end)
180   WARN_UNUSED_RESULT;
181 
getASN1Element(struct Curl_asn1Element * elem,const char * beg,const char * end)182 static const char *getASN1Element(struct Curl_asn1Element *elem,
183                                   const char *beg, const char *end)
184 {
185   unsigned char b;
186   size_t len;
187   struct Curl_asn1Element lelem;
188 
189   /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg'
190      ending at `end'.
191      Returns a pointer in source string after the parsed element, or NULL
192      if an error occurs. */
193   if(!beg || !end || beg >= end || !*beg ||
194      (size_t)(end - beg) > CURL_ASN1_MAX)
195     return NULL;
196 
197   /* Process header byte. */
198   elem->header = beg;
199   b = (unsigned char) *beg++;
200   elem->constructed = (b & 0x20) != 0;
201   elem->class = (b >> 6) & 3;
202   b &= 0x1F;
203   if(b == 0x1F)
204     return NULL; /* Long tag values not supported here. */
205   elem->tag = b;
206 
207   /* Process length. */
208   if(beg >= end)
209     return NULL;
210   b = (unsigned char) *beg++;
211   if(!(b & 0x80))
212     len = b;
213   else if(!(b &= 0x7F)) {
214     /* Unspecified length. Since we have all the data, we can determine the
215        effective length by skipping element until an end element is found. */
216     if(!elem->constructed)
217       return NULL;
218     elem->beg = beg;
219     while(beg < end && *beg) {
220       beg = getASN1Element(&lelem, beg, end);
221       if(!beg)
222         return NULL;
223     }
224     if(beg >= end)
225       return NULL;
226     elem->end = beg;
227     return beg + 1;
228   }
229   else if((unsigned)b > (size_t)(end - beg))
230     return NULL; /* Does not fit in source. */
231   else {
232     /* Get long length. */
233     len = 0;
234     do {
235       if(len & 0xFF000000L)
236         return NULL;  /* Lengths > 32 bits are not supported. */
237       len = (len << 8) | (unsigned char) *beg++;
238     } while(--b);
239   }
240   if(len > (size_t)(end - beg))
241     return NULL;  /* Element data does not fit in source. */
242   elem->beg = beg;
243   elem->end = beg + len;
244   return elem->end;
245 }
246 
247 #ifdef WANT_EXTRACT_CERTINFO
248 
249 /*
250  * Search the null terminated OID or OID identifier in local table.
251  * Return the table entry pointer or NULL if not found.
252  */
searchOID(const char * oid)253 static const struct Curl_OID *searchOID(const char *oid)
254 {
255   const struct Curl_OID *op;
256   for(op = OIDtable; op->numoid; op++)
257     if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid))
258       return op;
259 
260   return NULL;
261 }
262 
263 /*
264  * Convert an ASN.1 Boolean value into its string representation.
265  *
266  * Return error code.
267  */
268 
bool2str(struct dynbuf * store,const char * beg,const char * end)269 static CURLcode bool2str(struct dynbuf *store,
270                          const char *beg, const char *end)
271 {
272   if(end - beg != 1)
273     return CURLE_BAD_FUNCTION_ARGUMENT;
274   return Curl_dyn_add(store, *beg? "TRUE": "FALSE");
275 }
276 
277 /*
278  * Convert an ASN.1 octet string to a printable string.
279  *
280  * Return error code.
281  */
octet2str(struct dynbuf * store,const char * beg,const char * end)282 static CURLcode octet2str(struct dynbuf *store,
283                           const char *beg, const char *end)
284 {
285   CURLcode result = CURLE_OK;
286 
287   while(!result && beg < end)
288     result = Curl_dyn_addf(store, "%02x:", (unsigned char) *beg++);
289 
290   return result;
291 }
292 
bit2str(struct dynbuf * store,const char * beg,const char * end)293 static CURLcode bit2str(struct dynbuf *store,
294                         const char *beg, const char *end)
295 {
296   /* Convert an ASN.1 bit string to a printable string. */
297 
298   if(++beg > end)
299     return CURLE_BAD_FUNCTION_ARGUMENT;
300   return octet2str(store, beg, end);
301 }
302 
303 /*
304  * Convert an ASN.1 integer value into its string representation.
305  *
306  * Returns error.
307  */
int2str(struct dynbuf * store,const char * beg,const char * end)308 static CURLcode int2str(struct dynbuf *store,
309                         const char *beg, const char *end)
310 {
311   unsigned int val = 0;
312   size_t n = end - beg;
313 
314   if(!n)
315     return CURLE_BAD_FUNCTION_ARGUMENT;
316 
317   if(n > 4)
318     return octet2str(store, beg, end);
319 
320   /* Represent integers <= 32-bit as a single value. */
321   if(*beg & 0x80)
322     val = ~val;
323 
324   do
325     val = (val << 8) | *(const unsigned char *) beg++;
326   while(beg < end);
327   return Curl_dyn_addf(store, "%s%x", val >= 10? "0x": "", val);
328 }
329 
330 /*
331  * Convert from an ASN.1 typed string to UTF8.
332  *
333  * The result is stored in a dynbuf that is inited by the user of this
334  * function.
335  *
336  * Returns error.
337  */
338 static CURLcode
utf8asn1str(struct dynbuf * to,int type,const char * from,const char * end)339 utf8asn1str(struct dynbuf *to, int type, const char *from, const char *end)
340 {
341   size_t inlength = end - from;
342   int size = 1;
343   CURLcode result = CURLE_OK;
344 
345   switch(type) {
346   case CURL_ASN1_BMP_STRING:
347     size = 2;
348     break;
349   case CURL_ASN1_UNIVERSAL_STRING:
350     size = 4;
351     break;
352   case CURL_ASN1_NUMERIC_STRING:
353   case CURL_ASN1_PRINTABLE_STRING:
354   case CURL_ASN1_TELETEX_STRING:
355   case CURL_ASN1_IA5_STRING:
356   case CURL_ASN1_VISIBLE_STRING:
357   case CURL_ASN1_UTF8_STRING:
358     break;
359   default:
360     return CURLE_BAD_FUNCTION_ARGUMENT;  /* Conversion not supported. */
361   }
362 
363   if(inlength % size)
364     /* Length inconsistent with character size. */
365     return CURLE_BAD_FUNCTION_ARGUMENT;
366 
367   if(type == CURL_ASN1_UTF8_STRING) {
368     /* Just copy. */
369     if(inlength)
370       result = Curl_dyn_addn(to, from, inlength);
371   }
372   else {
373     while(!result && (from < end)) {
374       char buf[4]; /* decode buffer */
375       int charsize = 1;
376       unsigned int wc = 0;
377 
378       switch(size) {
379       case 4:
380         wc = (wc << 8) | *(const unsigned char *) from++;
381         wc = (wc << 8) | *(const unsigned char *) from++;
382         FALLTHROUGH();
383       case 2:
384         wc = (wc << 8) | *(const unsigned char *) from++;
385         FALLTHROUGH();
386       default: /* case 1: */
387         wc = (wc << 8) | *(const unsigned char *) from++;
388       }
389       if(wc >= 0x00000080) {
390         if(wc >= 0x00000800) {
391           if(wc >= 0x00010000) {
392             if(wc >= 0x00200000) {
393               /* Invalid char. size for target encoding. */
394               return CURLE_WEIRD_SERVER_REPLY;
395             }
396             buf[3] = (char) (0x80 | (wc & 0x3F));
397             wc = (wc >> 6) | 0x00010000;
398             charsize++;
399           }
400           buf[2] = (char) (0x80 | (wc & 0x3F));
401           wc = (wc >> 6) | 0x00000800;
402           charsize++;
403         }
404         buf[1] = (char) (0x80 | (wc & 0x3F));
405         wc = (wc >> 6) | 0x000000C0;
406         charsize++;
407       }
408       buf[0] = (char) wc;
409       result = Curl_dyn_addn(to, buf, charsize);
410     }
411   }
412   return result;
413 }
414 
415 /*
416  * Convert an ASN.1 OID into its dotted string representation.
417  *
418  * Return error code.
419  */
encodeOID(struct dynbuf * store,const char * beg,const char * end)420 static CURLcode encodeOID(struct dynbuf *store,
421                           const char *beg, const char *end)
422 {
423   unsigned int x;
424   unsigned int y;
425   CURLcode result = CURLE_OK;
426 
427   /* Process the first two numbers. */
428   y = *(const unsigned char *) beg++;
429   x = y / 40;
430   y -= x * 40;
431 
432   result = Curl_dyn_addf(store, "%u.%u", x, y);
433   if(result)
434     return result;
435 
436   /* Process the trailing numbers. */
437   while(beg < end) {
438     x = 0;
439     do {
440       if(x & 0xFF000000)
441         return 0;
442       y = *(const unsigned char *) beg++;
443       x = (x << 7) | (y & 0x7F);
444     } while(y & 0x80);
445     result = Curl_dyn_addf(store, ".%u", x);
446   }
447   return result;
448 }
449 
450 /*
451  * Convert an ASN.1 OID into its dotted or symbolic string representation.
452  *
453  * Return error code.
454  */
455 
OID2str(struct dynbuf * store,const char * beg,const char * end,bool symbolic)456 static CURLcode OID2str(struct dynbuf *store,
457                         const char *beg, const char *end, bool symbolic)
458 {
459   CURLcode result = CURLE_OK;
460   if(beg < end) {
461     if(symbolic) {
462       struct dynbuf buf;
463       Curl_dyn_init(&buf, MAX_X509_STR);
464       result = encodeOID(&buf, beg, end);
465 
466       if(!result) {
467         const struct Curl_OID *op = searchOID(Curl_dyn_ptr(&buf));
468         if(op)
469           result = Curl_dyn_add(store, op->textoid);
470         else
471           result = CURLE_BAD_FUNCTION_ARGUMENT;
472         Curl_dyn_free(&buf);
473       }
474     }
475     else
476       result = encodeOID(store, beg, end);
477   }
478   return result;
479 }
480 
GTime2str(struct dynbuf * store,const char * beg,const char * end)481 static CURLcode GTime2str(struct dynbuf *store,
482                           const char *beg, const char *end)
483 {
484   const char *tzp;
485   const char *fracp;
486   char sec1, sec2;
487   size_t fracl;
488   size_t tzl;
489   const char *sep = "";
490 
491   /* Convert an ASN.1 Generalized time to a printable string.
492      Return the dynamically allocated string, or NULL if an error occurs. */
493 
494   for(fracp = beg; fracp < end && ISDIGIT(*fracp); fracp++)
495     ;
496 
497   /* Get seconds digits. */
498   sec1 = '0';
499   switch(fracp - beg - 12) {
500   case 0:
501     sec2 = '0';
502     break;
503   case 2:
504     sec1 = fracp[-2];
505     FALLTHROUGH();
506   case 1:
507     sec2 = fracp[-1];
508     break;
509   default:
510     return CURLE_BAD_FUNCTION_ARGUMENT;
511   }
512 
513   /* timezone follows optional fractional seconds. */
514   tzp = fracp;
515   fracl = 0; /* no fractional seconds detected so far */
516   if(fracp < end && (*fracp == '.' || *fracp == ',')) {
517     /* Have fractional seconds, e.g. "[.,]\d+". How many? */
518     fracp++; /* should be a digit char or BAD ARGUMENT */
519     tzp = fracp;
520     while(tzp < end && ISDIGIT(*tzp))
521       tzp++;
522     if(tzp == fracp) /* never looped, no digit after [.,] */
523       return CURLE_BAD_FUNCTION_ARGUMENT;
524     fracl = tzp - fracp; /* number of fractional sec digits */
525     DEBUGASSERT(fracl > 0);
526     /* Strip trailing zeroes in fractional seconds.
527      * May reduce fracl to 0 if only '0's are present. */
528     while(fracl && fracp[fracl - 1] == '0')
529       fracl--;
530   }
531 
532   /* Process timezone. */
533   if(tzp >= end) {
534     tzp = "";
535     tzl = 0;
536   }
537   else if(*tzp == 'Z') {
538     sep = " ";
539     tzp = "GMT";
540     tzl = 3;
541   }
542   else if((*tzp == '+') || (*tzp == '-')) {
543     sep = " UTC";
544     tzl = end - tzp;
545   }
546   else {
547     sep = " ";
548     tzl = end - tzp;
549   }
550 
551   return Curl_dyn_addf(store,
552                        "%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s",
553                        beg, beg + 4, beg + 6,
554                        beg + 8, beg + 10, sec1, sec2,
555                        fracl? ".": "", (int)fracl, fracp,
556                        sep, (int)tzl, tzp);
557 }
558 
559 /*
560  * Convert an ASN.1 UTC time to a printable string.
561  *
562  * Return error code.
563  */
UTime2str(struct dynbuf * store,const char * beg,const char * end)564 static CURLcode UTime2str(struct dynbuf *store,
565                              const char *beg, const char *end)
566 {
567   const char *tzp;
568   size_t tzl;
569   const char *sec;
570 
571   for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++)
572     ;
573   /* Get the seconds. */
574   sec = beg + 10;
575   switch(tzp - sec) {
576   case 0:
577     sec = "00";
578     FALLTHROUGH();
579   case 2:
580     break;
581   default:
582     return CURLE_BAD_FUNCTION_ARGUMENT;
583   }
584 
585   /* Process timezone. */
586   if(tzp >= end)
587     return CURLE_BAD_FUNCTION_ARGUMENT;
588   if(*tzp == 'Z') {
589     tzp = "GMT";
590     end = tzp + 3;
591   }
592   else
593     tzp++;
594 
595   tzl = end - tzp;
596   return Curl_dyn_addf(store, "%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s",
597                        20 - (*beg >= '5'), beg, beg + 2, beg + 4,
598                        beg + 6, beg + 8, sec,
599                        (int)tzl, tzp);
600 }
601 
602 /*
603  * Convert an ASN.1 element to a printable string.
604  *
605  * Return error
606  */
ASN1tostr(struct dynbuf * store,struct Curl_asn1Element * elem,int type)607 static CURLcode ASN1tostr(struct dynbuf *store,
608                           struct Curl_asn1Element *elem, int type)
609 {
610   CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
611   if(elem->constructed)
612     return CURLE_OK; /* No conversion of structured elements. */
613 
614   if(!type)
615     type = elem->tag;   /* Type not forced: use element tag as type. */
616 
617   switch(type) {
618   case CURL_ASN1_BOOLEAN:
619     result = bool2str(store, elem->beg, elem->end);
620     break;
621   case CURL_ASN1_INTEGER:
622   case CURL_ASN1_ENUMERATED:
623     result = int2str(store, elem->beg, elem->end);
624     break;
625   case CURL_ASN1_BIT_STRING:
626     result = bit2str(store, elem->beg, elem->end);
627     break;
628   case CURL_ASN1_OCTET_STRING:
629     result = octet2str(store, elem->beg, elem->end);
630     break;
631   case CURL_ASN1_NULL:
632     result = Curl_dyn_addn(store, "", 1);
633     break;
634   case CURL_ASN1_OBJECT_IDENTIFIER:
635     result = OID2str(store, elem->beg, elem->end, TRUE);
636     break;
637   case CURL_ASN1_UTC_TIME:
638     result = UTime2str(store, elem->beg, elem->end);
639     break;
640   case CURL_ASN1_GENERALIZED_TIME:
641     result = GTime2str(store, elem->beg, elem->end);
642     break;
643   case CURL_ASN1_UTF8_STRING:
644   case CURL_ASN1_NUMERIC_STRING:
645   case CURL_ASN1_PRINTABLE_STRING:
646   case CURL_ASN1_TELETEX_STRING:
647   case CURL_ASN1_IA5_STRING:
648   case CURL_ASN1_VISIBLE_STRING:
649   case CURL_ASN1_UNIVERSAL_STRING:
650   case CURL_ASN1_BMP_STRING:
651     result = utf8asn1str(store, type, elem->beg, elem->end);
652     break;
653   }
654 
655   return result;
656 }
657 
658 /*
659  * ASCII encode distinguished name at `dn' into the store dynbuf.
660  *
661  * Returns error.
662  */
encodeDN(struct dynbuf * store,struct Curl_asn1Element * dn)663 static CURLcode encodeDN(struct dynbuf *store, struct Curl_asn1Element *dn)
664 {
665   struct Curl_asn1Element rdn;
666   struct Curl_asn1Element atv;
667   struct Curl_asn1Element oid;
668   struct Curl_asn1Element value;
669   const char *p1;
670   const char *p2;
671   const char *p3;
672   const char *str;
673   CURLcode result = CURLE_OK;
674   bool added = FALSE;
675   struct dynbuf temp;
676   Curl_dyn_init(&temp, MAX_X509_STR);
677 
678   for(p1 = dn->beg; p1 < dn->end;) {
679     p1 = getASN1Element(&rdn, p1, dn->end);
680     if(!p1) {
681       result = CURLE_BAD_FUNCTION_ARGUMENT;
682       goto error;
683     }
684     for(p2 = rdn.beg; p2 < rdn.end;) {
685       p2 = getASN1Element(&atv, p2, rdn.end);
686       if(!p2) {
687         result = CURLE_BAD_FUNCTION_ARGUMENT;
688         goto error;
689       }
690       p3 = getASN1Element(&oid, atv.beg, atv.end);
691       if(!p3) {
692         result = CURLE_BAD_FUNCTION_ARGUMENT;
693         goto error;
694       }
695       if(!getASN1Element(&value, p3, atv.end)) {
696         result = CURLE_BAD_FUNCTION_ARGUMENT;
697         goto error;
698       }
699       Curl_dyn_reset(&temp);
700       result = ASN1tostr(&temp, &oid, 0);
701       if(result)
702         goto error;
703 
704       str = Curl_dyn_ptr(&temp);
705 
706       /* Encode delimiter.
707          If attribute has a short uppercase name, delimiter is ", ". */
708       for(p3 = str; ISUPPER(*p3); p3++)
709         ;
710       if(added) {
711         if(p3 - str > 2)
712           result = Curl_dyn_addn(store, "/", 1);
713         else
714           result = Curl_dyn_addn(store, ", ", 2);
715         if(result)
716           goto error;
717       }
718 
719       /* Encode attribute name. */
720       result = Curl_dyn_add(store, str);
721       if(result)
722         goto error;
723 
724       /* Generate equal sign. */
725       result = Curl_dyn_addn(store, "=", 1);
726       if(result)
727         goto error;
728 
729       /* Generate value. */
730       result = ASN1tostr(store, &value, 0);
731       if(result)
732         goto error;
733       Curl_dyn_reset(&temp);
734       added = TRUE; /* use separator for next */
735     }
736   }
737 error:
738   Curl_dyn_free(&temp);
739 
740   return result;
741 }
742 
743 #endif /* WANT_EXTRACT_CERTINFO */
744 
745 #ifdef WANT_PARSEX509
746 /*
747  * ASN.1 parse an X509 certificate into structure subfields.
748  * Syntax is assumed to have already been checked by the SSL backend.
749  * See RFC 5280.
750  */
Curl_parseX509(struct Curl_X509certificate * cert,const char * beg,const char * end)751 int Curl_parseX509(struct Curl_X509certificate *cert,
752                    const char *beg, const char *end)
753 {
754   struct Curl_asn1Element elem;
755   struct Curl_asn1Element tbsCertificate;
756   const char *ccp;
757   static const char defaultVersion = 0;  /* v1. */
758 
759   cert->certificate.header = NULL;
760   cert->certificate.beg = beg;
761   cert->certificate.end = end;
762 
763   /* Get the sequence content. */
764   if(!getASN1Element(&elem, beg, end))
765     return -1;  /* Invalid bounds/size. */
766   beg = elem.beg;
767   end = elem.end;
768 
769   /* Get tbsCertificate. */
770   beg = getASN1Element(&tbsCertificate, beg, end);
771   if(!beg)
772     return -1;
773   /* Skip the signatureAlgorithm. */
774   beg = getASN1Element(&cert->signatureAlgorithm, beg, end);
775   if(!beg)
776     return -1;
777   /* Get the signatureValue. */
778   if(!getASN1Element(&cert->signature, beg, end))
779     return -1;
780 
781   /* Parse TBSCertificate. */
782   beg = tbsCertificate.beg;
783   end = tbsCertificate.end;
784   /* Get optional version, get serialNumber. */
785   cert->version.header = NULL;
786   cert->version.beg = &defaultVersion;
787   cert->version.end = &defaultVersion + sizeof(defaultVersion);
788   beg = getASN1Element(&elem, beg, end);
789   if(!beg)
790     return -1;
791   if(elem.tag == 0) {
792     if(!getASN1Element(&cert->version, elem.beg, elem.end))
793       return -1;
794     beg = getASN1Element(&elem, beg, end);
795     if(!beg)
796       return -1;
797   }
798   cert->serialNumber = elem;
799   /* Get signature algorithm. */
800   beg = getASN1Element(&cert->signatureAlgorithm, beg, end);
801   /* Get issuer. */
802   beg = getASN1Element(&cert->issuer, beg, end);
803   if(!beg)
804     return -1;
805   /* Get notBefore and notAfter. */
806   beg = getASN1Element(&elem, beg, end);
807   if(!beg)
808     return -1;
809   ccp = getASN1Element(&cert->notBefore, elem.beg, elem.end);
810   if(!ccp)
811     return -1;
812   if(!getASN1Element(&cert->notAfter, ccp, elem.end))
813     return -1;
814   /* Get subject. */
815   beg = getASN1Element(&cert->subject, beg, end);
816   if(!beg)
817     return -1;
818   /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
819   beg = getASN1Element(&cert->subjectPublicKeyInfo, beg, end);
820   if(!beg)
821     return -1;
822   ccp = getASN1Element(&cert->subjectPublicKeyAlgorithm,
823                        cert->subjectPublicKeyInfo.beg,
824                        cert->subjectPublicKeyInfo.end);
825   if(!ccp)
826     return -1;
827   if(!getASN1Element(&cert->subjectPublicKey, ccp,
828                      cert->subjectPublicKeyInfo.end))
829     return -1;
830   /* Get optional issuerUiqueID, subjectUniqueID and extensions. */
831   cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0;
832   cert->extensions.tag = elem.tag = 0;
833   cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL;
834   cert->issuerUniqueID.beg = cert->issuerUniqueID.end = "";
835   cert->subjectUniqueID.beg = cert->subjectUniqueID.end = "";
836   cert->extensions.header = NULL;
837   cert->extensions.beg = cert->extensions.end = "";
838   if(beg < end) {
839     beg = getASN1Element(&elem, beg, end);
840     if(!beg)
841       return -1;
842   }
843   if(elem.tag == 1) {
844     cert->issuerUniqueID = elem;
845     if(beg < end) {
846       beg = getASN1Element(&elem, beg, end);
847       if(!beg)
848         return -1;
849     }
850   }
851   if(elem.tag == 2) {
852     cert->subjectUniqueID = elem;
853     if(beg < end) {
854       beg = getASN1Element(&elem, beg, end);
855       if(!beg)
856         return -1;
857     }
858   }
859   if(elem.tag == 3)
860     if(!getASN1Element(&cert->extensions, elem.beg, elem.end))
861       return -1;
862   return 0;
863 }
864 
865 #endif /* WANT_PARSEX509 */
866 
867 #ifdef WANT_EXTRACT_CERTINFO
868 
dumpAlgo(struct dynbuf * store,struct Curl_asn1Element * param,const char * beg,const char * end)869 static CURLcode dumpAlgo(struct dynbuf *store,
870                          struct Curl_asn1Element *param,
871                          const char *beg, const char *end)
872 {
873   struct Curl_asn1Element oid;
874 
875   /* Get algorithm parameters and return algorithm name. */
876 
877   beg = getASN1Element(&oid, beg, end);
878   if(!beg)
879     return CURLE_BAD_FUNCTION_ARGUMENT;
880   param->header = NULL;
881   param->tag = 0;
882   param->beg = param->end = end;
883   if(beg < end) {
884     const char *p = getASN1Element(param, beg, end);
885     if(!p)
886       return CURLE_BAD_FUNCTION_ARGUMENT;
887   }
888   return OID2str(store, oid.beg, oid.end, TRUE);
889 }
890 
891 /*
892  * This is a convenience function for push_certinfo_len that takes a zero
893  * terminated value.
894  */
ssl_push_certinfo(struct Curl_easy * data,int certnum,const char * label,const char * value)895 static CURLcode ssl_push_certinfo(struct Curl_easy *data,
896                                   int certnum,
897                                   const char *label,
898                                   const char *value)
899 {
900   size_t valuelen = strlen(value);
901 
902   return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
903 }
904 
905 /*
906  * This is a convenience function for push_certinfo_len that takes a
907  * dynbuf value.
908  *
909  * It also does the verbose output if !certnum.
910  */
ssl_push_certinfo_dyn(struct Curl_easy * data,int certnum,const char * label,struct dynbuf * ptr)911 static CURLcode ssl_push_certinfo_dyn(struct Curl_easy *data,
912                                       int certnum,
913                                       const char *label,
914                                       struct dynbuf *ptr)
915 {
916   size_t valuelen = Curl_dyn_len(ptr);
917   char *value = Curl_dyn_ptr(ptr);
918 
919   CURLcode result = Curl_ssl_push_certinfo_len(data, certnum, label,
920                                                value, valuelen);
921 
922   if(!certnum && !result)
923     infof(data, "   %s: %s", label, value);
924 
925   return result;
926 }
927 
do_pubkey_field(struct Curl_easy * data,int certnum,const char * label,struct Curl_asn1Element * elem)928 static CURLcode do_pubkey_field(struct Curl_easy *data, int certnum,
929                                 const char *label,
930                                 struct Curl_asn1Element *elem)
931 {
932   CURLcode result;
933   struct dynbuf out;
934 
935   Curl_dyn_init(&out, MAX_X509_STR);
936 
937   /* Generate a certificate information record for the public key. */
938 
939   result = ASN1tostr(&out, elem, 0);
940   if(!result) {
941     if(data->set.ssl.certinfo)
942       result = ssl_push_certinfo_dyn(data, certnum, label, &out);
943     Curl_dyn_free(&out);
944   }
945   return result;
946 }
947 
948 /* return 0 on success, 1 on error */
do_pubkey(struct Curl_easy * data,int certnum,const char * algo,struct Curl_asn1Element * param,struct Curl_asn1Element * pubkey)949 static int do_pubkey(struct Curl_easy *data, int certnum,
950                      const char *algo, struct Curl_asn1Element *param,
951                      struct Curl_asn1Element *pubkey)
952 {
953   struct Curl_asn1Element elem;
954   struct Curl_asn1Element pk;
955   const char *p;
956 
957   /* Generate all information records for the public key. */
958 
959   if(strcasecompare(algo, "ecPublicKey")) {
960     /*
961      * ECC public key is all the data, a value of type BIT STRING mapped to
962      * OCTET STRING and should not be parsed as an ASN.1 value.
963      */
964     const size_t len = ((pubkey->end - pubkey->beg - 2) * 4);
965     if(!certnum)
966       infof(data, "   ECC Public Key (%zu bits)", len);
967     if(data->set.ssl.certinfo) {
968       char q[sizeof(len) * 8 / 3 + 1];
969       (void)msnprintf(q, sizeof(q), "%zu", len);
970       if(ssl_push_certinfo(data, certnum, "ECC Public Key", q))
971         return 1;
972     }
973     return do_pubkey_field(data, certnum, "ecPublicKey", pubkey);
974   }
975 
976   /* Get the public key (single element). */
977   if(!getASN1Element(&pk, pubkey->beg + 1, pubkey->end))
978     return 1;
979 
980   if(strcasecompare(algo, "rsaEncryption")) {
981     const char *q;
982     size_t len;
983 
984     p = getASN1Element(&elem, pk.beg, pk.end);
985     if(!p)
986       return 1;
987 
988     /* Compute key length. */
989     for(q = elem.beg; !*q && q < elem.end; q++)
990       ;
991     len = ((elem.end - q) * 8);
992     if(len) {
993       unsigned int i;
994       for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
995         len--;
996     }
997     if(len > 32)
998       elem.beg = q;     /* Strip leading zero bytes. */
999     if(!certnum)
1000       infof(data, "   RSA Public Key (%zu bits)", len);
1001     if(data->set.ssl.certinfo) {
1002       char r[sizeof(len) * 8 / 3 + 1];
1003       msnprintf(r, sizeof(r), "%zu", len);
1004       if(ssl_push_certinfo(data, certnum, "RSA Public Key", r))
1005         return 1;
1006     }
1007     /* Generate coefficients. */
1008     if(do_pubkey_field(data, certnum, "rsa(n)", &elem))
1009       return 1;
1010     if(!getASN1Element(&elem, p, pk.end))
1011       return 1;
1012     if(do_pubkey_field(data, certnum, "rsa(e)", &elem))
1013       return 1;
1014   }
1015   else if(strcasecompare(algo, "dsa")) {
1016     p = getASN1Element(&elem, param->beg, param->end);
1017     if(p) {
1018       if(do_pubkey_field(data, certnum, "dsa(p)", &elem))
1019         return 1;
1020       p = getASN1Element(&elem, p, param->end);
1021       if(p) {
1022         if(do_pubkey_field(data, certnum, "dsa(q)", &elem))
1023           return 1;
1024         if(getASN1Element(&elem, p, param->end)) {
1025           if(do_pubkey_field(data, certnum, "dsa(g)", &elem))
1026             return 1;
1027           if(do_pubkey_field(data, certnum, "dsa(pub_key)", &pk))
1028             return 1;
1029         }
1030       }
1031     }
1032   }
1033   else if(strcasecompare(algo, "dhpublicnumber")) {
1034     p = getASN1Element(&elem, param->beg, param->end);
1035     if(p) {
1036       if(do_pubkey_field(data, certnum, "dh(p)", &elem))
1037         return 1;
1038       if(getASN1Element(&elem, param->beg, param->end)) {
1039         if(do_pubkey_field(data, certnum, "dh(g)", &elem))
1040           return 1;
1041         if(do_pubkey_field(data, certnum, "dh(pub_key)", &pk))
1042           return 1;
1043       }
1044     }
1045   }
1046   return 0;
1047 }
1048 
1049 /*
1050  * Convert an ASN.1 distinguished name into a printable string.
1051  * Return error.
1052  */
DNtostr(struct dynbuf * store,struct Curl_asn1Element * dn)1053 static CURLcode DNtostr(struct dynbuf *store,
1054                         struct Curl_asn1Element *dn)
1055 {
1056   return encodeDN(store, dn);
1057 }
1058 
Curl_extract_certinfo(struct Curl_easy * data,int certnum,const char * beg,const char * end)1059 CURLcode Curl_extract_certinfo(struct Curl_easy *data,
1060                                int certnum,
1061                                const char *beg,
1062                                const char *end)
1063 {
1064   struct Curl_X509certificate cert;
1065   struct Curl_asn1Element param;
1066   char *certptr;
1067   size_t clen;
1068   struct dynbuf out;
1069   CURLcode result = CURLE_OK;
1070   unsigned int version;
1071   const char *ptr;
1072   int rc;
1073 
1074   if(!data->set.ssl.certinfo)
1075     if(certnum)
1076       return CURLE_OK;
1077 
1078   Curl_dyn_init(&out, MAX_X509_STR);
1079   /* Prepare the certificate information for curl_easy_getinfo(). */
1080 
1081   /* Extract the certificate ASN.1 elements. */
1082   if(Curl_parseX509(&cert, beg, end))
1083     return CURLE_PEER_FAILED_VERIFICATION;
1084 
1085   /* Subject. */
1086   result = DNtostr(&out, &cert.subject);
1087   if(result)
1088     goto done;
1089   if(data->set.ssl.certinfo) {
1090     result = ssl_push_certinfo_dyn(data, certnum, "Subject", &out);
1091     if(result)
1092       goto done;
1093   }
1094   Curl_dyn_reset(&out);
1095 
1096   /* Issuer. */
1097   result = DNtostr(&out, &cert.issuer);
1098   if(result)
1099     goto done;
1100   if(data->set.ssl.certinfo) {
1101     result = ssl_push_certinfo_dyn(data, certnum, "Issuer", &out);
1102     if(result)
1103       goto done;
1104   }
1105   Curl_dyn_reset(&out);
1106 
1107   /* Version (always fits in less than 32 bits). */
1108   version = 0;
1109   for(ptr = cert.version.beg; ptr < cert.version.end; ptr++)
1110     version = (version << 8) | *(const unsigned char *) ptr;
1111   if(data->set.ssl.certinfo) {
1112     result = Curl_dyn_addf(&out, "%x", version);
1113     if(result)
1114       goto done;
1115     result = ssl_push_certinfo_dyn(data, certnum, "Version", &out);
1116     if(result)
1117       goto done;
1118     Curl_dyn_reset(&out);
1119   }
1120 
1121   /* Serial number. */
1122   result = ASN1tostr(&out, &cert.serialNumber, 0);
1123   if(result)
1124     goto done;
1125   if(data->set.ssl.certinfo) {
1126     result = ssl_push_certinfo_dyn(data, certnum, "Serial Number", &out);
1127     if(result)
1128       goto done;
1129   }
1130   Curl_dyn_reset(&out);
1131 
1132   /* Signature algorithm .*/
1133   result = dumpAlgo(&out, &param, cert.signatureAlgorithm.beg,
1134                     cert.signatureAlgorithm.end);
1135   if(result)
1136     goto done;
1137   if(data->set.ssl.certinfo) {
1138     result = ssl_push_certinfo_dyn(data, certnum, "Signature Algorithm",
1139                                    &out);
1140     if(result)
1141       goto done;
1142   }
1143   Curl_dyn_reset(&out);
1144 
1145   /* Start Date. */
1146   result = ASN1tostr(&out, &cert.notBefore, 0);
1147   if(result)
1148     goto done;
1149   if(data->set.ssl.certinfo) {
1150     result = ssl_push_certinfo_dyn(data, certnum, "Start Date", &out);
1151     if(result)
1152       goto done;
1153   }
1154   Curl_dyn_reset(&out);
1155 
1156   /* Expire Date. */
1157   result = ASN1tostr(&out, &cert.notAfter, 0);
1158   if(result)
1159     goto done;
1160   if(data->set.ssl.certinfo) {
1161     result = ssl_push_certinfo_dyn(data, certnum, "Expire Date", &out);
1162     if(result)
1163       goto done;
1164   }
1165   Curl_dyn_reset(&out);
1166 
1167   /* Public Key Algorithm. */
1168   result = dumpAlgo(&out, &param, cert.subjectPublicKeyAlgorithm.beg,
1169                     cert.subjectPublicKeyAlgorithm.end);
1170   if(result)
1171     goto done;
1172   if(data->set.ssl.certinfo) {
1173     result = ssl_push_certinfo_dyn(data, certnum, "Public Key Algorithm",
1174                                    &out);
1175     if(result)
1176       goto done;
1177   }
1178 
1179   rc = do_pubkey(data, certnum, Curl_dyn_ptr(&out),
1180                  &param, &cert.subjectPublicKey);
1181   if(rc) {
1182     result = CURLE_OUT_OF_MEMORY; /* the most likely error */
1183     goto done;
1184   }
1185   Curl_dyn_reset(&out);
1186 
1187   /* Signature. */
1188   result = ASN1tostr(&out, &cert.signature, 0);
1189   if(result)
1190     goto done;
1191   if(data->set.ssl.certinfo) {
1192     result = ssl_push_certinfo_dyn(data, certnum, "Signature", &out);
1193     if(result)
1194       goto done;
1195   }
1196   Curl_dyn_reset(&out);
1197 
1198   /* Generate PEM certificate. */
1199   result = Curl_base64_encode(cert.certificate.beg,
1200                               cert.certificate.end - cert.certificate.beg,
1201                               &certptr, &clen);
1202   if(result)
1203     goto done;
1204 
1205   /* Generate the final output certificate string. Format is:
1206      -----BEGIN CERTIFICATE-----\n
1207      <max 64 base64 characters>\n
1208      .
1209      .
1210      .
1211      -----END CERTIFICATE-----\n
1212    */
1213 
1214   Curl_dyn_reset(&out);
1215 
1216   /* Build the certificate string. */
1217   result = Curl_dyn_add(&out, "-----BEGIN CERTIFICATE-----\n");
1218   if(!result) {
1219     size_t j = 0;
1220 
1221     while(!result && (j < clen)) {
1222       size_t chunksize = (clen - j) > 64 ? 64 : (clen - j);
1223       result = Curl_dyn_addn(&out, &certptr[j], chunksize);
1224       if(!result)
1225         result = Curl_dyn_addn(&out, "\n", 1);
1226       j += chunksize;
1227     }
1228     if(!result)
1229       result = Curl_dyn_add(&out, "-----END CERTIFICATE-----\n");
1230   }
1231   free(certptr);
1232   if(!result)
1233     if(data->set.ssl.certinfo)
1234       result = ssl_push_certinfo_dyn(data, certnum, "Cert", &out);
1235 
1236 done:
1237   Curl_dyn_free(&out);
1238   return result;
1239 }
1240 
1241 #endif /* WANT_EXTRACT_CERTINFO */
1242 
1243 #endif /* USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL or USE_SECTRANSP */
1244