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