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