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