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