1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 * SPDX-License-Identifier: curl
23 ***************************************************************************/
25 #include "curl_setup.h"
27 #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \
28 defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP)
30 #if defined(USE_GSKIT) || defined(USE_WOLFSSL) || defined(USE_SCHANNEL)
31 #define WANT_PARSEX509 /* uses Curl_parseX509() */
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() */
40 #if defined(USE_GSKIT)
41 #define WANT_VERIFYHOST /* uses Curl_verifyhost () */
42 #define WANT_PARSEX509 /* ... uses Curl_parseX509() */
45 #include <curl/curl.h>
48 #include "curl_ctype.h"
49 #include "hostcheck.h"
50 #include "vtls/vtls.h"
52 #include "inet_pton.h"
53 #include "curl_base64.h"
57 /* The last 3 #include files should be in this order */
58 #include "curl_printf.h"
59 #include "curl_memory.h"
66 /* Largest supported ASN.1 structure. */
67 #define CURL_ASN1_MAX ((size_t) 0x40000) /* 256K */
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
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
105 #ifdef WANT_EXTRACT_CERTINFO
106 /* ASN.1 OID table entry. */
108 const char *numoid; /* Dotted-numeric OID. */
109 const char *textoid; /* OID name. */
113 static const char cnOID[] = "2.5.4.3"; /* Common name. */
114 static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */
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" },
137 { "2.5.4.5", "serialNumber" },
141 { "2.5.4.9", "streetAddress" },
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 }
166 #endif /* WANT_EXTRACT_CERTINFO */
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.
177 static const char *getASN1Element(struct Curl_asn1Element *elem,
178 const char *beg, const char *end)
181 static const char *getASN1Element(struct Curl_asn1Element *elem,
182 const char *beg, const char *end)
186 struct Curl_asn1Element lelem;
188 /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg'
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)
196 /* Process header byte. */
198 b = (unsigned char) *beg++;
199 elem->constructed = (b & 0x20) != 0;
200 elem->class = (b >> 6) & 3;
203 return NULL; /* Long tag values not supported here. */
206 /* Process length. */
209 b = (unsigned char) *beg++;
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)
218 while(beg < end && *beg) {
219 beg = getASN1Element(&lelem, beg, end);
228 else if((unsigned)b > (size_t)(end - beg))
229 return NULL; /* Does not fit in source. */
231 /* Get long length. */
234 if(len & 0xFF000000L)
235 return NULL; /* Lengths > 32 bits are not supported. */
236 len = (len << 8) | (unsigned char) *beg++;
239 if(len > (size_t)(end - beg))
240 return NULL; /* Element data does not fit in source. */
242 elem->end = beg + len;
246 #ifdef WANT_EXTRACT_CERTINFO
249 * Search the null terminated OID or OID identifier in local table.
250 * Return the table entry pointer or NULL if not found.
252 static const struct Curl_OID *searchOID(const char *oid)
254 const struct Curl_OID *op;
255 for(op = OIDtable; op->numoid; op++)
256 if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid))
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
268 static const char *bool2str(const char *beg, const char *end)
272 return strdup(*beg? "TRUE": "FALSE");
276 * Convert an ASN.1 octet string to a printable string.
277 * Return the dynamically allocated string, or NULL if an error occurs.
279 static const char *octet2str(const char *beg, const char *end)
284 Curl_dyn_init(&buf, 3 * CURL_ASN1_MAX + 1);
285 result = Curl_dyn_addn(&buf, "", 0);
287 while(!result && beg < end)
288 result = Curl_dyn_addf(&buf, "%02x:", (unsigned char) *beg++);
290 return Curl_dyn_ptr(&buf);
293 static const char *bit2str(const char *beg, const char *end)
295 /* Convert an ASN.1 bit string to a printable string.
296 Return the dynamically allocated string, or NULL if an error occurs. */
300 return octet2str(beg, end);
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.
308 static const char *int2str(const char *beg, const char *end)
310 unsigned long val = 0;
311 size_t n = end - beg;
317 return octet2str(beg, end);
319 /* Represent integers <= 32-bit as a single value. */
324 val = (val << 8) | *(const unsigned char *) beg++;
326 return curl_maprintf("%s%lx", val >= 10? "0x": "", val);
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
337 utf8asn1str(char **to, int type, const char *from, const char *end)
339 size_t inlength = end - from;
346 case CURL_ASN1_BMP_STRING:
349 case CURL_ASN1_UNIVERSAL_STRING:
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:
360 return -1; /* Conversion not supported. */
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);
369 return -1; /* Not enough memory. */
371 if(type == CURL_ASN1_UTF8_STRING) {
373 outlength = inlength;
375 memcpy(buf, from, outlength);
378 for(outlength = 0; from < end;) {
385 wc = (wc << 8) | *(const unsigned char *) from++;
386 wc = (wc << 8) | *(const unsigned char *) from++;
389 wc = (wc << 8) | *(const unsigned char *) from++;
391 default: /* case 1: */
392 wc = (wc << 8) | *(const unsigned char *) from++;
395 if(wc >= 0x00000080) {
396 if(wc >= 0x00000800) {
397 if(wc >= 0x00010000) {
398 if(wc >= 0x00200000) {
400 return -1; /* Invalid char. size for target encoding. */
402 buf[outlength + 3] = (char) (0x80 | (wc & 0x3F));
403 wc = (wc >> 6) | 0x00010000;
406 buf[outlength + 2] = (char) (0x80 | (wc & 0x3F));
407 wc = (wc >> 6) | 0x00000800;
410 buf[outlength + 1] = (char) (0x80 | (wc & 0x3F));
411 wc = (wc >> 6) | 0x000000C0;
414 buf[outlength] = (char) wc;
415 outlength += charsize;
418 buf[outlength] = '\0';
424 * Convert an ASN.1 String into its UTF-8 string representation.
425 * Return the dynamically allocated string, or NULL if an error occurs.
427 static const char *string2str(int type, const char *beg, const char *end)
430 if(utf8asn1str(&buf, type, beg, end) < 0)
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
440 static size_t encodeUint(char *buf, size_t buflen, unsigned int x)
443 unsigned int y = x / 10;
446 i = encodeUint(buf, buflen, y);
450 buf[i] = (char) ('0' + x);
453 buf[i] = '\0'; /* Store a terminator if possible. */
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.
462 static size_t encodeOID(char *buf, size_t buflen,
463 const char *beg, const char *end)
469 /* Process the first two numbers. */
470 y = *(const unsigned char *) beg++;
473 i = encodeUint(buf, buflen, x);
478 i += encodeUint(NULL, 0, y);
480 i += encodeUint(buf + i, buflen - i, y);
482 /* Process the trailing numbers. */
491 y = *(const unsigned char *) beg++;
492 x = (x << 7) | (y & 0x7F);
495 i += encodeUint(NULL, 0, x);
497 i += encodeUint(buf + i, buflen - i, x);
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.
509 static const char *OID2str(const char *beg, const char *end, bool symbolic)
513 size_t buflen = encodeOID(NULL, 0, beg, end);
515 buf = malloc(buflen + 1); /* one extra for the zero byte */
517 encodeOID(buf, buflen, beg, end);
521 const struct Curl_OID *op = searchOID(buf);
524 buf = strdup(op->textoid);
533 static const char *GTime2str(const char *beg, const char *end)
540 const char *sep = "";
542 /* Convert an ASN.1 Generalized time to a printable string.
543 Return the dynamically allocated string, or NULL if an error occurs. */
545 for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++)
548 /* Get seconds digits. */
550 switch(fracp - beg - 12) {
564 /* Scan for timezone, measure fractional seconds. */
567 if(fracp < end && (*fracp == '.' || *fracp == ',')) {
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--)
577 /* Process timezone. */
579 ; /* Nothing to do. */
580 else if(*tzp == 'Z') {
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,
598 * Convert an ASN.1 UTC time to a printable string.
599 * Return the dynamically allocated string, or NULL if an error occurs.
601 static const char *UTime2str(const char *beg, const char *end)
607 for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++)
609 /* Get the seconds. */
620 /* Process timezone. */
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,
638 * Convert an ASN.1 element to a printable string.
639 * Return the dynamically allocated string, or NULL if an error occurs.
641 static const char *ASN1tostr(struct Curl_asn1Element *elem, int type)
643 if(elem->constructed)
644 return NULL; /* No conversion of structured elements. */
647 type = elem->tag; /* Type not forced: use element tag as 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);
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);
678 return NULL; /* Unsupported. */
682 * ASCII encode distinguished name at `dn' into the `buflen'-sized buffer at
685 * Returns the total string length, even if larger than `buflen' or -1 on
688 static ssize_t encodeDN(char *buf, size_t buflen, struct Curl_asn1Element *dn)
690 struct Curl_asn1Element rdn;
691 struct Curl_asn1Element atv;
692 struct Curl_asn1Element oid;
693 struct Curl_asn1Element value;
700 for(p1 = dn->beg; p1 < dn->end;) {
701 p1 = getASN1Element(&rdn, p1, dn->end);
704 for(p2 = rdn.beg; p2 < rdn.end;) {
705 p2 = getASN1Element(&atv, p2, rdn.end);
708 p3 = getASN1Element(&oid, atv.beg, atv.end);
711 if(!getASN1Element(&value, p3, atv.end))
713 str = ASN1tostr(&oid, 0);
718 If attribute has a short uppercase name, delimiter is ", ". */
720 for(p3 = str; ISUPPER(*p3); p3++)
722 for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) {
729 /* Encode attribute name. */
730 for(p3 = str; *p3; p3++) {
737 /* Generate equal sign. */
742 /* Generate value. */
743 str = ASN1tostr(&value, 0);
746 for(p3 = str; *p3; p3++) {
758 #endif /* WANT_EXTRACT_CERTINFO */
760 #ifdef WANT_PARSEX509
762 * ASN.1 parse an X509 certificate into structure subfields.
763 * Syntax is assumed to have already been checked by the SSL backend.
766 int Curl_parseX509(struct Curl_X509certificate *cert,
767 const char *beg, const char *end)
769 struct Curl_asn1Element elem;
770 struct Curl_asn1Element tbsCertificate;
772 static const char defaultVersion = 0; /* v1. */
774 cert->certificate.header = NULL;
775 cert->certificate.beg = beg;
776 cert->certificate.end = end;
778 /* Get the sequence content. */
779 if(!getASN1Element(&elem, beg, end))
780 return -1; /* Invalid bounds/size. */
784 /* Get tbsCertificate. */
785 beg = getASN1Element(&tbsCertificate, beg, end);
788 /* Skip the signatureAlgorithm. */
789 beg = getASN1Element(&cert->signatureAlgorithm, beg, end);
792 /* Get the signatureValue. */
793 if(!getASN1Element(&cert->signature, beg, end))
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);
807 if(!getASN1Element(&cert->version, elem.beg, elem.end))
809 beg = getASN1Element(&elem, beg, end);
813 cert->serialNumber = elem;
814 /* Get signature algorithm. */
815 beg = getASN1Element(&cert->signatureAlgorithm, beg, end);
817 beg = getASN1Element(&cert->issuer, beg, end);
820 /* Get notBefore and notAfter. */
821 beg = getASN1Element(&elem, beg, end);
824 ccp = getASN1Element(&cert->notBefore, elem.beg, elem.end);
827 if(!getASN1Element(&cert->notAfter, ccp, elem.end))
830 beg = getASN1Element(&cert->subject, beg, end);
833 /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
834 beg = getASN1Element(&cert->subjectPublicKeyInfo, beg, end);
837 ccp = getASN1Element(&cert->subjectPublicKeyAlgorithm,
838 cert->subjectPublicKeyInfo.beg,
839 cert->subjectPublicKeyInfo.end);
842 if(!getASN1Element(&cert->subjectPublicKey, ccp,
843 cert->subjectPublicKeyInfo.end))
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 = "";
854 beg = getASN1Element(&elem, beg, end);
859 cert->issuerUniqueID = elem;
861 beg = getASN1Element(&elem, beg, end);
867 cert->subjectUniqueID = elem;
869 beg = getASN1Element(&elem, beg, end);
875 if(!getASN1Element(&cert->extensions, elem.beg, elem.end))
880 #endif /* WANT_PARSEX509 */
882 #ifdef WANT_EXTRACT_CERTINFO
885 * Copy at most 64-characters, terminate with a newline and returns the
886 * effective number of stored characters.
888 static size_t copySubstring(char *to, const char *from)
891 for(i = 0; i < 64; i++) {
901 static const char *dumpAlgo(struct Curl_asn1Element *param,
902 const char *beg, const char *end)
904 struct Curl_asn1Element oid;
906 /* Get algorithm parameters and return algorithm name. */
908 beg = getASN1Element(&oid, beg, end);
911 param->header = NULL;
913 param->beg = param->end = end;
915 if(!getASN1Element(param, beg, end))
917 return OID2str(oid.beg, oid.end, TRUE);
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)
925 CURLcode result = CURLE_OK;
927 /* Generate a certificate information record for the public key. */
929 output = ASN1tostr(elem, 0);
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);
937 return result ? 1 : 0;
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)
945 struct Curl_asn1Element elem;
946 struct Curl_asn1Element pk;
949 /* Generate all information records for the public key. */
951 if(strcasecompare(algo, "ecPublicKey")) {
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.
956 const unsigned long len =
957 (unsigned long)((pubkey->end - pubkey->beg - 2) * 4);
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))
966 return do_pubkey_field(data, certnum, "ecPublicKey", pubkey);
969 /* Get the public key (single element). */
970 if(!getASN1Element(&pk, pubkey->beg + 1, pubkey->end))
973 if(strcasecompare(algo, "rsaEncryption")) {
977 p = getASN1Element(&elem, pk.beg, pk.end);
981 /* Compute key length. */
982 for(q = elem.beg; !*q && q < elem.end; q++)
984 len = (unsigned long)((elem.end - q) * 8);
987 for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
991 elem.beg = q; /* Strip leading zero bytes. */
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))
1000 /* Generate coefficients. */
1001 if(do_pubkey_field(data, certnum, "rsa(n)", &elem))
1003 if(!getASN1Element(&elem, p, pk.end))
1005 if(do_pubkey_field(data, certnum, "rsa(e)", &elem))
1008 else if(strcasecompare(algo, "dsa")) {
1009 p = getASN1Element(&elem, param->beg, param->end);
1011 if(do_pubkey_field(data, certnum, "dsa(p)", &elem))
1013 p = getASN1Element(&elem, p, param->end);
1015 if(do_pubkey_field(data, certnum, "dsa(q)", &elem))
1017 if(getASN1Element(&elem, p, param->end)) {
1018 if(do_pubkey_field(data, certnum, "dsa(g)", &elem))
1020 if(do_pubkey_field(data, certnum, "dsa(pub_key)", &pk))
1026 else if(strcasecompare(algo, "dhpublicnumber")) {
1027 p = getASN1Element(&elem, param->beg, param->end);
1029 if(do_pubkey_field(data, certnum, "dh(p)", &elem))
1031 if(getASN1Element(&elem, param->beg, param->end)) {
1032 if(do_pubkey_field(data, certnum, "dh(g)", &elem))
1034 if(do_pubkey_field(data, certnum, "dh(pub_key)", &pk))
1043 * Convert an ASN.1 distinguished name into a printable string.
1044 * Return the dynamically allocated string, or NULL if an error occurs.
1046 static const char *DNtostr(struct Curl_asn1Element *dn)
1049 ssize_t buflen = encodeDN(NULL, 0, dn);
1052 buf = malloc(buflen + 1);
1054 if(encodeDN(buf, buflen + 1, dn) == -1) {
1064 CURLcode Curl_extract_certinfo(struct Curl_easy *data,
1069 struct Curl_X509certificate cert;
1070 struct Curl_asn1Element param;
1075 CURLcode result = CURLE_OK;
1076 unsigned long version;
1080 if(!data->set.ssl.certinfo)
1084 /* Prepare the certificate information for curl_easy_getinfo(). */
1086 /* Extract the certificate ASN.1 elements. */
1087 if(Curl_parseX509(&cert, beg, end))
1088 return CURLE_PEER_FAILED_VERIFICATION;
1091 ccp = DNtostr(&cert.subject);
1093 return CURLE_OUT_OF_MEMORY;
1094 if(data->set.ssl.certinfo) {
1095 result = Curl_ssl_push_certinfo(data, certnum, "Subject", ccp);
1100 infof(data, "%2d Subject: %s", certnum, ccp);
1104 ccp = DNtostr(&cert.issuer);
1106 return CURLE_OUT_OF_MEMORY;
1107 if(data->set.ssl.certinfo) {
1108 result = Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp);
1111 infof(data, " Issuer: %s", ccp);
1116 /* Version (always fits in less than 32 bits). */
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);
1123 return CURLE_OUT_OF_MEMORY;
1124 result = Curl_ssl_push_certinfo(data, certnum, "Version", ccp);
1130 infof(data, " Version: %lu (0x%lx)", version + 1, version);
1132 /* Serial number. */
1133 ccp = ASN1tostr(&cert.serialNumber, 0);
1135 return CURLE_OUT_OF_MEMORY;
1136 if(data->set.ssl.certinfo)
1137 result = Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp);
1139 infof(data, " Serial Number: %s", ccp);
1144 /* Signature algorithm .*/
1145 ccp = dumpAlgo(¶m, cert.signatureAlgorithm.beg,
1146 cert.signatureAlgorithm.end);
1148 return CURLE_OUT_OF_MEMORY;
1149 if(data->set.ssl.certinfo)
1150 result = Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp);
1152 infof(data, " Signature Algorithm: %s", ccp);
1158 ccp = ASN1tostr(&cert.notBefore, 0);
1160 return CURLE_OUT_OF_MEMORY;
1161 if(data->set.ssl.certinfo)
1162 result = Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp);
1164 infof(data, " Start Date: %s", ccp);
1170 ccp = ASN1tostr(&cert.notAfter, 0);
1172 return CURLE_OUT_OF_MEMORY;
1173 if(data->set.ssl.certinfo)
1174 result = Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp);
1176 infof(data, " Expire Date: %s", ccp);
1181 /* Public Key Algorithm. */
1182 ccp = dumpAlgo(¶m, cert.subjectPublicKeyAlgorithm.beg,
1183 cert.subjectPublicKeyAlgorithm.end);
1185 return CURLE_OUT_OF_MEMORY;
1186 if(data->set.ssl.certinfo)
1187 result = Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm",
1192 infof(data, " Public Key Algorithm: %s", ccp);
1193 ret = do_pubkey(data, certnum, ccp, ¶m, &cert.subjectPublicKey);
1195 result = CURLE_OUT_OF_MEMORY; /* the most likely error */
1202 ccp = ASN1tostr(&cert.signature, 0);
1204 return CURLE_OUT_OF_MEMORY;
1205 if(data->set.ssl.certinfo)
1206 result = Curl_ssl_push_certinfo(data, certnum, "Signature", ccp);
1208 infof(data, " Signature: %s", ccp);
1213 /* Generate PEM certificate. */
1214 result = Curl_base64_encode(cert.certificate.beg,
1215 cert.certificate.end - cert.certificate.beg,
1219 /* Compute the number of characters in final certificate string. Format is:
1220 -----BEGIN CERTIFICATE-----\n
1221 <max 64 base64 characters>\n
1225 -----END CERTIFICATE-----\n
1227 i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26;
1228 cp2 = malloc(i + 1);
1231 return CURLE_OUT_OF_MEMORY;
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-----");
1240 if(data->set.ssl.certinfo)
1241 result = Curl_ssl_push_certinfo(data, certnum, "Cert", cp2);
1243 infof(data, "%s", cp2);
1248 #endif /* WANT_EXTRACT_CERTINFO */
1250 #endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL
1251 * or USE_SECTRANSP */
1253 #ifdef WANT_VERIFYHOST
1255 static const char *checkOID(const char *beg, const char *end,
1258 struct Curl_asn1Element e;
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. */
1266 ccp = getASN1Element(&e, beg, end);
1267 if(!ccp || e.tag != CURL_ASN1_OBJECT_IDENTIFIER)
1270 p = OID2str(e.beg, e.end, FALSE);
1274 matched = !strcmp(p, oid);
1276 return matched? ccp: NULL;
1279 CURLcode Curl_verifyhost(struct Curl_easy *data, struct connectdata *conn,
1280 const char *beg, const char *end)
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;
1291 size_t addrlen = (size_t) -1;
1293 const char * const hostname = SSL_HOST_NAME();
1294 const char * const dispname = SSL_HOST_DISPNAME();
1295 size_t hostlen = strlen(hostname);
1297 struct in6_addr addr;
1299 struct in_addr addr;
1302 /* Verify that connection server matches info in X509 certificate at
1305 if(!SSL_CONN_CONFIG(verifyhost))
1308 if(Curl_parseX509(&cert, beg, end))
1309 return CURLE_PEER_FAILED_VERIFICATION;
1311 /* Get the server IP address. */
1313 if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, hostname, &addr))
1314 addrlen = sizeof(struct in6_addr);
1317 if(Curl_inet_pton(AF_INET, hostname, &addr))
1318 addrlen = sizeof(struct in_addr);
1320 /* Process extensions. */
1321 for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) {
1322 p = getASN1Element(&ext, p, cert.extensions.end);
1324 return CURLE_PEER_FAILED_VERIFICATION;
1326 /* Check if extension is a subjectAlternativeName. */
1327 ext.beg = checkOID(ext.beg, ext.end, sanOID);
1329 ext.beg = getASN1Element(&elem, ext.beg, ext.end);
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);
1336 return CURLE_PEER_FAILED_VERIFICATION;
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);
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);
1358 case 7: /* IP address. */
1359 matched = (size_t) (name.end - name.beg) == addrlen &&
1360 !memcmp(&addr, name.beg, addrlen);
1369 /* an alternative name matched the server hostname */
1370 infof(data, " subjectAltName: %s matched", dispname);
1373 /* an alternative name field existed, but didn't match and then
1375 infof(data, " subjectAltName does not match %s", dispname);
1376 return CURLE_PEER_FAILED_VERIFICATION;
1379 /* Process subject. */
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);
1389 for(p = dn.beg; p < dn.end;) {
1390 p = getASN1Element(&elem, p, dn.end);
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);
1396 name = elem; /* Latch CN. */
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");
1404 len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end);
1407 return CURLE_OUT_OF_MEMORY;
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);
1418 failf(data, "SSL: certificate subject name '%s' does not match "
1419 "target host name '%s'", dnsname, dispname);
1423 return CURLE_PEER_FAILED_VERIFICATION;
1426 #endif /* WANT_VERIFYHOST */