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