FreeRDP
Loading...
Searching...
No Matches
x509_utils.c
1
21
22#include <ctype.h>
23
24#include <openssl/objects.h>
25#include <openssl/x509v3.h>
26#include <openssl/pem.h>
27#include <openssl/rsa.h>
28#include <openssl/err.h>
29
30#include <freerdp/config.h>
31
32#include <winpr/crt.h>
33#include <winpr/string.h>
34#include <winpr/assert.h>
35#include <winpr/winsock.h>
36
37#include <freerdp/log.h>
38
39#include "x509_utils.h"
40
41#define TAG FREERDP_TAG("crypto")
42
43#if (OPENSSL_VERSION_NUMBER >= 0x30500000L)
44/* SHAKE256 with 512 bits of output over the DER encoding of the cert */
45static void* ed448_cert_digest(const X509* cert, size_t* pLength)
46{
47 WINPR_ASSERT(pLength);
48
49 *pLength = 0;
50
51 int ok = 0;
52 unsigned char* der = nullptr;
53 const int derlen = i2d_X509(cert, &der);
54 EVP_MD_CTX* ctx = EVP_MD_CTX_new();
55 void* out = calloc(32, sizeof(BYTE));
56 if ((derlen <= 0) || !ctx || !out || !der)
57 goto fail;
58
59 ok = EVP_DigestInit_ex(ctx, EVP_shake256(), nullptr) &&
60 EVP_DigestUpdate(ctx, der, (size_t)derlen) && EVP_DigestFinalXOF(ctx, out, 32);
61
62fail:
63
64 EVP_MD_CTX_free(ctx);
65 OPENSSL_free(der);
66 if (!ok)
67 {
68 free(out);
69 return nullptr;
70 }
71 *pLength = 32;
72 return out;
73}
74#endif
75
76BYTE* x509_utils_get_hash(const X509* xcert, const char* hash, size_t* length)
77{
78 UINT32 fp_len = EVP_MAX_MD_SIZE;
79 BYTE* fp = nullptr;
80 const EVP_MD* md = EVP_get_digestbyname(hash);
81 if (!md)
82 {
83 WLog_ERR(TAG, "System does not support %s hash!", hash);
84 return nullptr;
85 }
86 if (!xcert || !length)
87 {
88 WLog_ERR(TAG, "Invalid arguments: xcert=%p, length=%p",
89 WINPR_CXX_COMPAT_CAST(const void*, xcert),
90 WINPR_CXX_COMPAT_CAST(const void*, length));
91 return nullptr;
92 }
93
94 fp = calloc(fp_len + 1, sizeof(BYTE));
95 if (!fp)
96 {
97 WLog_ERR(TAG, "could not allocate %" PRIu32 " bytes", fp_len);
98 return nullptr;
99 }
100
101 if (X509_digest(xcert, md, fp, &fp_len) != 1)
102 {
103 free(fp);
104#if (OPENSSL_VERSION_NUMBER >= 0x30500000L)
105 if (_stricmp("shake256", hash) == 0)
106 {
107 fp = ed448_cert_digest(xcert, length);
108 return fp;
109 }
110#endif
111 WLog_ERR(TAG, "certificate does not have a %s hash!", hash);
112 return nullptr;
113 }
114
115 *length = fp_len;
116 return fp;
117}
118
119WINPR_ATTR_NODISCARD
120static long ASN1_STRING_length_wrapper(const ASN1_STRING* asn)
121{
122 if (!asn)
123 return 0;
124#if (OPENSSL_VERSION_NUMBER >= 0x40100000L)
125 const size_t rc = ASN1_STRING_get_length(asn);
126 if (rc > LONG_MAX)
127 return 0;
128 return WINPR_ASSERTING_INT_CAST(long, rc);
129#else
130 return ASN1_STRING_length(asn);
131#endif
132}
133
134BYTE* x509_utils_get_hashless_signature_hash(const X509* xcert, size_t* length)
135{
136 WINPR_ASSERT(xcert);
137 WINPR_ASSERT(length);
138
139 /* RFC 5929 section 4.1 leaves tls-server-end-point undefined when the certificate's
140 * signatureAlgorithm uses no hash (Ed25519, Ed448, ML-DSA, SLH-DSA). Use the hash
141 * X509_digest_sig() picks for these: SHA-512 for Ed25519 (the RFC 8419 default), SHA-256
142 * for ML-DSA and SLH-DSA. Ed448 (SHAKE256) gives no result with OpenSSL 3.5, which needs an
143 * output length for it. RSA-PSS and the algorithms with a hash are not handled here. */
144#if (OPENSSL_VERSION_NUMBER >= 0x30000000L) && !defined(LIBRESSL_VERSION_NUMBER)
145 const int nid = X509_get_signature_nid(xcert);
146 int md_nid = NID_undef;
147 int pk_nid = NID_undef;
148 if ((nid == NID_rsassaPss) || (OBJ_find_sigid_algs(nid, &md_nid, &pk_nid) != 1) ||
149 (md_nid != NID_undef) || (pk_nid == NID_undef))
150 return nullptr;
151
152 int fallback = 0;
153 BYTE* hash = nullptr;
154 ASN1_OCTET_STRING* digest = X509_digest_sig(xcert, nullptr, &fallback);
155 const long len = ASN1_STRING_length_wrapper(digest);
156 if (fallback)
157 {
158 if (len > 0)
159 {
160 hash = calloc((size_t)len + 1, sizeof(BYTE));
161 if (hash)
162 {
163 memcpy(hash, ASN1_STRING_get0_data(digest), (size_t)len);
164 *length = (size_t)len;
165 }
166#if (OPENSSL_VERSION_NUMBER >= 0x30500000L)
167 }
168 else if (nid == NID_ED448)
169 {
170 hash = x509_utils_get_hash(xcert, "shake256", length);
171#endif
172 }
173 }
174 ASN1_OCTET_STRING_free(digest);
175 return hash;
176#else
177 WINPR_UNUSED(xcert);
178 WINPR_UNUSED(length);
179 return nullptr;
180#endif
181}
182
183WINPR_ATTR_NODISCARD
184static char* crypto_print_name(const X509_NAME* name)
185{
186 char* buffer = nullptr;
187 BIO* outBIO = BIO_new(BIO_s_mem());
188 if (!outBIO)
189 return nullptr;
190
191 if (X509_NAME_print_ex(outBIO, name, 0, XN_FLAG_ONELINE) > 0)
192 buffer = x509_utils_bio_read(outBIO, nullptr);
193
194 BIO_free_all(outBIO);
195 return buffer;
196}
197
198char* x509_utils_get_subject(const X509* xcert)
199{
200 char* subject = nullptr;
201 if (!xcert)
202 {
203 WLog_ERR(TAG, "Invalid certificate nullptr");
204 return nullptr;
205 }
206 subject = crypto_print_name(X509_get_subject_name(xcert));
207 if (!subject)
208 WLog_WARN(TAG, "certificate does not have a subject!");
209 return subject;
210}
211
212/* GENERAL_NAME type labels */
213
214static const char* general_name_type_labels[] = { "OTHERNAME", "EMAIL ", "DNS ",
215 "X400 ", "DIRNAME ", "EDIPARTY ",
216 "URI ", "IPADD ", "RID " };
217
218WINPR_ATTR_NODISCARD
219static const char* general_name_type_label(int general_name_type)
220{
221 if ((0 <= general_name_type) &&
222 ((size_t)general_name_type < ARRAYSIZE(general_name_type_labels)))
223 {
224 return general_name_type_labels[general_name_type];
225 }
226 else
227 {
228 static char buffer[80] = WINPR_C_ARRAY_INIT;
229 (void)snprintf(buffer, sizeof(buffer), "Unknown general name type (%d)", general_name_type);
230 return buffer;
231 }
232}
233
234/*
235
236map_subject_alt_name(x509, general_name_type, mapper, data)
237
238Call the function mapper with subjectAltNames found in the x509
239certificate and data. if generate_name_type is GEN_ALL, the the
240mapper is called for all the names, else it's called only for names
241of the given type.
242
243
244We implement the following extractors:
245
246 - a string extractor that can be used to get the subjectAltNames of
247 the following types: GEN_URI, GEN_DNS, GEN_EMAIL
248
249 - an IP address extractor that converts the binary GEN_IPADD value
250 into its presentation format
251
252 - a ASN1_OBJECT filter/extractor that can be used to get the
253 subjectAltNames of OTHERNAME type.
254
255 Note: usually, it's a string, but some type of otherNames can be
256 associated with different classes of objects. eg. a KPN may be a
257 sequence of realm and principal name, instead of a single string
258 object.
259
260Not implemented yet: extractors for the types: GEN_X400, GEN_DIRNAME,
261GEN_EDIPARTY, GEN_RID.
262
263
264mapper(name, data, index, count)
265
266The mapper is passed:
267 - the GENERAL_NAME selected,
268 - the data,
269 - the index of the general name in the subjectAltNames,
270 - the total number of names in the subjectAltNames.
271
272The last parameter let's the mapper allocate arrays to collect objects.
273Note: if names are filtered, not all the indices from 0 to count-1 are
274passed to mapper, only the indices selected.
275
276When the mapper returns 0, map_subject_alt_name stops the iteration immediately.
277
278*/
279
280#define GEN_ALL (-1)
281
282typedef int (*general_name_mapper_pr)(const X509* x509, GENERAL_NAME* name, void* data, int index,
283 int count);
284
285static void map_subject_alt_name(const X509* x509, int general_name_type,
286 general_name_mapper_pr mapper, void* data)
287{
288 STACK_OF(GENERAL_NAME)* gens = X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr);
289
290 if (!gens)
291 return;
292
293 const int num = sk_GENERAL_NAME_num(gens);
294
295 for (int i = 0; (i < num); i++)
296 {
297 GENERAL_NAME* name = sk_GENERAL_NAME_value(gens, i);
298
299 if (name)
300 {
301 if ((general_name_type == GEN_ALL) || (general_name_type == name->type))
302 {
303 if (!mapper(x509, name, data, i, num))
304 {
305 break;
306 }
307 }
308 }
309 }
310
311 sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
312}
313
314/*
315extract_string -- string extractor
316
317- the strings array is allocated lazily, when we first have to store a
318 string.
319
320- allocated contains the size of the strings array, or -1 if
321 allocation failed.
322
323- count contains the actual count of strings in the strings array.
324
325- maximum limits the number of strings we can store in the strings
326 array: beyond, the extractor returns 0 to short-cut the search.
327
328extract_string stores in the string list OPENSSL strings,
329that must be freed with OPENSSL_free.
330
331*/
332
333typedef struct string_list
334{
335 char** strings;
336 size_t* lengths;
337 size_t allocated;
338 size_t count;
339 size_t maximum;
340} string_list;
341
342static string_list string_list_initialize(void)
343{
344 const string_list empty = {
345 .strings = nullptr, .lengths = nullptr, .allocated = 0, .count = 0, .maximum = INT_MAX
346 };
347 return empty;
348}
349
350static BOOL string_list_allocate(string_list* list, size_t allocate_count)
351{
352 WINPR_ASSERT(list);
353 if (!list->strings && (list->allocated == 0) && (allocate_count > 0))
354 {
355 list->strings = (char**)calloc(allocate_count, sizeof(char*));
356 list->lengths = calloc(allocate_count, sizeof(size_t));
357 list->count = 0;
358 if (!list->strings || !list->lengths)
359 {
360 free((void*)list->strings);
361 free(list->lengths);
362 list->strings = nullptr;
363 list->lengths = nullptr;
364 return FALSE;
365 }
366 list->allocated = allocate_count;
367 }
368 return TRUE;
369}
370
371static void string_list_free(string_list* list)
372{
373 /* Note: we don't free the contents of the strings array: this */
374 /* is handled by the caller, either by returning this */
375 /* content, or freeing it itself. */
376 free((void*)list->strings);
377 free(list->lengths);
378}
379
380WINPR_ATTR_NODISCARD
381static BOOL check_string_is_email(WINPR_ATTR_UNUSED const X509* x509, const unsigned char* ustr,
382 size_t length)
383{
384 const size_t MAX_EMAIL_LENGTH = 256;
385 const size_t MIN_EMAIL_LENGTH = 5;
386
387 if (ustr == nullptr)
388 return FALSE;
389
390 const char* email = (const char*)ustr;
391 const size_t len = strnlen(email, length);
392 if ((len < MIN_EMAIL_LENGTH) || (len > MAX_EMAIL_LENGTH))
393 return FALSE;
394
395 size_t at_pos = 0;
396 size_t at_count = 0;
397
398 for (size_t i = 0; i < len; i++)
399 {
400 char cur = email[i];
401 if (cur == '@')
402 {
403 /* @ must not be first or last */
404 if (i == 0)
405 return FALSE;
406 if (i == len - 1)
407 return FALSE;
408 at_pos = i;
409 at_count++;
410 }
411 if (isspace(cur))
412 return FALSE;
413 }
414
415 /* only one @ allowed */
416 if (at_count != 1)
417 {
418 return FALSE;
419 }
420
421 /* local part */
422 if ((email[0] == '.') || (email[at_pos - 1] == '.'))
423 return FALSE;
424
425 /* .. forbidden */
426 for (size_t i = 0; i < at_pos - 1; i++)
427 {
428 if ((email[i] == '.') && (email[i + 1] == '.'))
429 return FALSE;
430 }
431
432 // Validate the domain part (after '@')
433 const char* domain = &email[at_pos + 1];
434 size_t domain_len = strnlen(domain, len);
435
436 if (!winpr_str_is_valid_hostnameN(domain, domain_len))
437 return FALSE;
438
439 /* local part */
440 for (size_t i = 0; i < at_pos; i++)
441 {
442 if (!isalnum(email[i]) && email[i] != '.' && email[i] != '-' && email[i] != '_' &&
443 email[i] != '+')
444 {
445 return FALSE;
446 }
447 }
448
449 return TRUE;
450}
451
452WINPR_ATTR_NODISCARD
453static BOOL check_string_is_host_or_ip(WINPR_ATTR_UNUSED const X509* x509,
454 const unsigned char* ustr, size_t length)
455{
456 const char* str = (const char*)ustr;
457 if (strnlen(str, length) != length)
458 return FALSE;
459 return winpr_str_is_valid_hostnameN(str, length);
460}
461
462WINPR_ATTR_NODISCARD
463static BOOL check_string_is_dns_name(const X509* x509, const unsigned char* ustr, size_t length)
464{
465 /* RFC 6125 wildcard DNS names (e.g. *.example.com): validate the part after
466 * the leading label; tls_match_hostname applies the single-label rule.
467 * Like OpenSSL, require at least two non-empty labels after the wildcard,
468 * so *.com, *..com and *.com. are rejected. */
469 if ((length > 2) && (ustr[0] == '*') && (ustr[1] == '.'))
470 {
471 const unsigned char* suffix = &ustr[2];
472 const size_t suffixLength = length - 2;
473 size_t dots = 0;
474
475 if ((suffix[0] == '.') || (suffix[suffixLength - 1] == '.'))
476 return FALSE;
477
478 for (size_t x = 1; x < suffixLength; x++)
479 {
480 if (suffix[x] == '.')
481 {
482 if (suffix[x - 1] == '.')
483 return FALSE;
484 dots++;
485 }
486 }
487
488 if (dots == 0)
489 return FALSE;
490 return check_string_is_host_or_ip(x509, suffix, suffixLength);
491 }
492 return check_string_is_host_or_ip(x509, ustr, length);
493}
494
495WINPR_ATTR_NODISCARD
496static BOOL check_string_is_host_or_ip_or_email(WINPR_ATTR_UNUSED const X509* x509,
497 const unsigned char* ustr, size_t length)
498{
499 if (check_string_is_host_or_ip(x509, ustr, length))
500 return TRUE;
501 return check_string_is_email(x509, ustr, length);
502}
503
504static char* ip_address_to_string(const ASN1_STRING* str)
505{
506 WINPR_ASSERT(str);
507
508 const long length = ASN1_STRING_length_wrapper(str);
509 int family = AF_UNSPEC;
510
511 switch (length)
512 {
513 case 4:
514 family = AF_INET;
515 break;
516 case 16:
517 family = AF_INET6;
518 break;
519 default:
520 return nullptr;
521 }
522
523 char buffer[INET6_ADDRSTRLEN] = WINPR_C_ARRAY_INIT;
524 const void* data = ASN1_STRING_get0_data(str);
525 if (!inet_ntop(family, data, buffer, sizeof(buffer)))
526 return nullptr;
527
528 return OPENSSL_strdup(buffer);
529}
530
531WINPR_ATTR_NODISCARD
532static int
533extract_string_generic(const X509* x509, GENERAL_NAME* name, void* data, int index, int count,
534 BOOL (*fkt)(const X509* x509, const unsigned char* str, size_t length))
535{
536 string_list* list = data;
537 WINPR_ASSERT(list);
538 WINPR_ASSERT(fkt);
539
540 WINPR_ASSERT(name);
541 WINPR_UNUSED(index);
542
543 const ASN1_STRING* str = nullptr;
544 switch (name->type)
545 {
546 case GEN_URI:
547 str = name->d.uniformResourceIdentifier;
548 break;
549
550 case GEN_DNS:
551 str = name->d.dNSName;
552 break;
553
554 case GEN_EMAIL:
555 str = name->d.rfc822Name;
556 break;
557
558 default:
559 return 1;
560 }
561
562 unsigned char* cstring = nullptr;
563 const int rc = ASN1_STRING_to_UTF8(&cstring, str);
564 if (rc < 0)
565 {
566 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() failed for %s: %s",
567 general_name_type_label(name->type), ERR_error_string(ERR_get_error(), nullptr));
568 return 1;
569 }
570
571 if (!fkt(x509, cstring, WINPR_ASSERTING_INT_CAST(size_t, rc)))
572 {
573 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() does not conform to expected format %s: %s",
574 general_name_type_label(name->type), (const char*)str);
575 OPENSSL_free(cstring);
576 return -1;
577 }
578
579 if (!string_list_allocate(list, WINPR_ASSERTING_INT_CAST(WINPR_CIPHER_TYPE, count)) ||
580 (list->allocated <= 0))
581 {
582 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() allocation failed: %s",
583 general_name_type_label(name->type));
584 OPENSSL_free(cstring);
585 return 0;
586 }
587
588 list->strings[list->count] = (char*)cstring;
589 list->lengths[list->count] = WINPR_ASSERTING_INT_CAST(size_t, rc);
590 list->count++;
591
592 if (list->count >= list->maximum)
593 {
594 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() limit exceeded: %s",
595 general_name_type_label(name->type));
596 return 0;
597 }
598
599 return 1;
600}
601
602WINPR_ATTR_NODISCARD
603static int extract_string(const X509* x509, GENERAL_NAME* name, void* data, int index, int count)
604{
605 return extract_string_generic(x509, name, data, index, count, check_string_is_dns_name);
606}
607
608static int extract_email(const X509* x509, GENERAL_NAME* name, void* data, int index, int count)
609{
610 return extract_string_generic(x509, name, data, index, count, check_string_is_email);
611}
612
613static int extract_ip_address(const X509* x509, GENERAL_NAME* name, void* data, int index,
614 int count)
615{
616 string_list* list = data;
617 WINPR_ASSERT(list);
618 WINPR_ASSERT(name);
619 WINPR_UNUSED(x509);
620 WINPR_UNUSED(index);
621
622 if (name->type != GEN_IPADD)
623 return 1;
624
625 char* address = ip_address_to_string(name->d.iPAddress);
626 if (!address)
627 {
628 WLog_ERR(TAG, "Failed to convert %s to a string", general_name_type_label(name->type));
629 return 1;
630 }
631
632 if (!string_list_allocate(list, WINPR_ASSERTING_INT_CAST(size_t, count)) ||
633 (list->allocated <= 0))
634 {
635 WLog_ERR(TAG, "Failed to allocate %s list", general_name_type_label(name->type));
636 OPENSSL_free(address);
637 return 0;
638 }
639
640 list->strings[list->count] = address;
641 list->lengths[list->count] = strlen(address);
642 list->count++;
643
644 if (list->count >= list->maximum)
645 {
646 WLog_ERR(TAG, "Too many %s entries", general_name_type_label(name->type));
647 return 0;
648 }
649
650 return 1;
651}
652
653/*
654extract_othername_object -- object extractor.
655
656- the objects array is allocated lazily, when we first have to store a
657 string.
658
659- allocated contains the size of the objects array, or -1 if
660 allocation failed.
661
662- count contains the actual count of objects in the objects array.
663
664- maximum limits the number of objects we can store in the objects
665 array: beyond, the extractor returns 0 to short-cut the search.
666
667extract_othername_objects stores in the objects array ASN1_TYPE *
668pointers directly obtained from the GENERAL_NAME.
669*/
670
671typedef struct object_list
672{
673 ASN1_OBJECT* type_id;
674 char** strings;
675 size_t* lengths;
676
677 size_t allocated;
678 size_t count;
679 size_t maximum;
680} object_list;
681
682static object_list object_list_initialize(void)
683{
684 const object_list empty = { .type_id = nullptr,
685 .strings = nullptr,
686 .lengths = nullptr,
687 .allocated = 0,
688 .count = 0,
689 .maximum = INT_MAX };
690 return empty;
691}
692
693WINPR_ATTR_NODISCARD
694static BOOL object_list_allocate(object_list* list, size_t allocate_count)
695{
696 if (!list->strings && (list->allocated == 0) && (allocate_count > 0))
697 {
698 list->strings = (char**)calloc(allocate_count, sizeof(list->strings[0]));
699 list->lengths = calloc(allocate_count, sizeof(size_t));
700 list->count = 0;
701 if (!list->strings || !list->lengths)
702 {
703 free((void*)list->strings);
704 free(list->lengths);
705 list->strings = nullptr;
706 list->lengths = nullptr;
707 return FALSE;
708 }
709 list->allocated = allocate_count;
710 }
711 return TRUE;
712}
713
714WINPR_ATTR_MALLOC(free, 1)
715static char* object_string(const X509* x509, ASN1_TYPE* object, size_t* pLength)
716{
717 unsigned char* utf8String = nullptr;
718
719 WINPR_ASSERT(object);
720 WINPR_ASSERT(pLength);
721
722 *pLength = 0;
723
724 /* TODO: check that object.type is a string type. */
725 const int length = ASN1_STRING_to_UTF8(&utf8String, object->value.asn1_string);
726
727 if (length < 0)
728 return nullptr;
729
730 char* result = nullptr;
731 if (check_string_is_host_or_ip_or_email(x509, utf8String,
732 WINPR_ASSERTING_INT_CAST(size_t, length)))
733 {
734 result = strndup((char*)utf8String, WINPR_ASSERTING_INT_CAST(size_t, length));
735 if (result)
736 *pLength = WINPR_ASSERTING_INT_CAST(size_t, length);
737 }
738 else
739 WLog_ERR(TAG, "Found invalid object_string entry in certificate: '%s'", utf8String);
740 OPENSSL_free(utf8String);
741 return result;
742}
743
744static void object_list_free(object_list* list)
745{
746 WINPR_ASSERT(list);
747 free((void*)list->strings);
748 free(list->lengths);
749}
750
751WINPR_ATTR_NODISCARD
752static int extract_othername_object_as_string(const X509* x509, GENERAL_NAME* name, void* data,
753 int index, int count)
754{
755 object_list* list = data;
756 WINPR_UNUSED(index);
757 WINPR_ASSERT(x509);
758
759 if (count < 0)
760 return -1;
761
762 if (name->type != GEN_OTHERNAME)
763 {
764 return 1;
765 }
766
767 if (0 != OBJ_cmp(name->d.otherName->type_id, list->type_id))
768 {
769 return 1;
770 }
771
772 if (!object_list_allocate(list, WINPR_ASSERTING_INT_CAST(size_t, count)) ||
773 (list->allocated <= 0))
774 {
775 return 0;
776 }
777
778 list->strings[list->count] =
779 object_string(x509, name->d.otherName->value, &list->lengths[list->count]);
780 if (list->strings[list->count])
781 {
782 list->count++;
783 }
784
785 if (list->count >= list->maximum)
786 {
787 return 0;
788 }
789
790 return 1;
791}
792
793char* x509_utils_get_email(const X509* x509)
794{
795 string_list list = string_list_initialize();
796 list.maximum = 1;
797 map_subject_alt_name(x509, GEN_EMAIL, extract_email, &list);
798
799 if (list.count == 0)
800 {
801 string_list_free(&list);
802 return nullptr;
803 }
804
805 char* result = strndup(list.strings[0], list.lengths[0]);
806 OPENSSL_free(list.strings[0]);
807 string_list_free(&list);
808 return result;
809}
810
811char* x509_utils_get_upn(const X509* x509)
812{
813 object_list list = object_list_initialize();
814
815 list.type_id = OBJ_nid2obj(NID_ms_upn);
816 list.maximum = 1;
817 map_subject_alt_name(x509, GEN_OTHERNAME, extract_othername_object_as_string, &list);
818
819 if (list.count == 0)
820 {
821 object_list_free(&list);
822 return nullptr;
823 }
824
825 char* result = list.strings[0];
826 object_list_free(&list);
827 return result;
828}
829
830char* x509_utils_get_date(const X509* x509, BOOL startDate)
831{
832 WINPR_ASSERT(x509);
833
834 const ASN1_TIME* date = startDate ? X509_get0_notBefore(x509) : X509_get0_notAfter(x509);
835 if (!date)
836 return nullptr;
837
838 BIO* bmem = BIO_new(BIO_s_mem());
839 if (!bmem)
840 return nullptr;
841
842 char* str = nullptr;
843 if (ASN1_TIME_print(bmem, date))
844 {
845 BUF_MEM* bptr = nullptr;
846
847 BIO_get_mem_ptr(bmem, &bptr);
848 str = strndup(bptr->data, bptr->length);
849 }
850 else
851 { // Log error
852 }
853 BIO_free_all(bmem);
854 return str;
855}
856
857void x509_utils_dns_names_free(size_t count, size_t* lengths, char** dns_names)
858{
859 free(lengths);
860
861 if (dns_names)
862 {
863 for (size_t i = 0; i < count; i++)
864 {
865 if (dns_names[i])
866 {
867 OPENSSL_free(dns_names[i]);
868 }
869 }
870
871 free((void*)dns_names);
872 }
873}
874
875WINPR_ATTR_NODISCARD
876static char** x509_utils_get_names(const X509* xcert, int general_name_type,
877 general_name_mapper_pr mapper, size_t* count, size_t** lengths)
878{
879 string_list list = string_list_initialize();
880 map_subject_alt_name(xcert, general_name_type, mapper, &list);
881 (*count) = list.count;
882
883 if (list.count <= 0)
884 {
885 string_list_free(&list);
886 return nullptr;
887 }
888
889 /* lengths are not useful, since we converted the
890 strings to utf-8, there cannot be nul-bytes in them. */
891 char** result = (char**)calloc(list.count, sizeof(*result));
892 (*lengths) = calloc(list.count, sizeof(**lengths));
893
894 if (!result || !(*lengths))
895 {
896 string_list_free(&list);
897 free((void*)result);
898 free(*lengths);
899 (*lengths) = nullptr;
900 (*count) = 0;
901 return nullptr;
902 }
903
904 for (size_t i = 0; i < list.count; i++)
905 {
906 result[i] = list.strings[i];
907 (*lengths)[i] = list.lengths[i];
908 }
909
910 string_list_free(&list);
911 return result;
912}
913
914char** x509_utils_get_dns_names(const X509* xcert, size_t* count, size_t** pplengths)
915{
916 return x509_utils_get_names(xcert, GEN_DNS, extract_string, count, pplengths);
917}
918
919char** x509_utils_get_ip_names(const X509* xcert, size_t* count, size_t** pplengths)
920{
921 return x509_utils_get_names(xcert, GEN_IPADD, extract_ip_address, count, pplengths);
922}
923
924WINPR_ATTR_NODISCARD
925static int found_name(WINPR_ATTR_UNUSED const X509* x509, WINPR_ATTR_UNUSED GENERAL_NAME* name,
926 void* data, WINPR_ATTR_UNUSED int index, WINPR_ATTR_UNUSED int count)
927{
928 BOOL* found = data;
929 WINPR_ASSERT(found);
930
931 *found = TRUE;
932 return 0; /* one is enough, stop the iteration */
933}
934
935BOOL x509_utils_has_dns_names(const X509* xcert)
936{
937 /* Unlike x509_utils_get_dns_names this does not filter the entries:
938 * a malformed dNSName can never match, but it is still a DNS SAN. */
939 BOOL found = FALSE;
940 map_subject_alt_name(xcert, GEN_DNS, found_name, &found);
941 return found;
942}
943
944BOOL x509_utils_has_ip_names(const X509* xcert)
945{
946 /* Unlike x509_utils_get_dns_names this does not filter the entries:
947 * a malformed dNSName can never match, but it is still a DNS SAN. */
948 BOOL found = FALSE;
949 map_subject_alt_name(xcert, GEN_IPADD, found_name, &found);
950 return found;
951}
952
953char* x509_utils_get_issuer(const X509* xcert)
954{
955 char* issuer = nullptr;
956 if (!xcert)
957 {
958 WLog_ERR(TAG, "Invalid certificate nullptr");
959 return nullptr;
960 }
961 issuer = crypto_print_name(X509_get_issuer_name(xcert));
962 if (!issuer)
963 WLog_WARN(TAG, "certificate does not have an issuer!");
964 return issuer;
965}
966
967WINPR_ATTR_NODISCARD
968static int asn1_object_cmp(const ASN1_OBJECT* const* a, const ASN1_OBJECT* const* b)
969{
970 if (!a || !b)
971 return (a == b) ? 0 : (a ? 1 : -1);
972
973 if (!*a || !*b)
974 return (*a == *b) ? 0 : (*a ? 1 : -1);
975
976 return OBJ_cmp(*a, *b);
977}
978
979BOOL x509_utils_check_eku(const X509* xcert, int nid)
980{
981 BOOL ret = FALSE;
982 STACK_OF(ASN1_OBJECT)* oid_stack = nullptr;
983 ASN1_OBJECT* oid = nullptr;
984
985 if (!xcert)
986 return FALSE;
987
988 oid = OBJ_nid2obj(nid);
989 if (!oid)
990 return FALSE;
991
992 oid_stack = X509_get_ext_d2i(xcert, NID_ext_key_usage, nullptr, nullptr);
993 if (!oid_stack)
994 return FALSE;
995
996 /* sk_ASN1_OBJECT_set_cmp_func does some function pointer casting that produces a warning. We
997 * can not fix upstream, so silence it here. */
998 WINPR_PRAGMA_DIAG_PUSH
999 WINPR_PRAGMA_DIAG_IGNORED_CAST_FUNCTION_TYPE
1000 sk_ASN1_OBJECT_set_cmp_func(oid_stack, asn1_object_cmp);
1001 WINPR_PRAGMA_DIAG_POP
1002 if (sk_ASN1_OBJECT_find(oid_stack, oid) >= 0)
1003 ret = TRUE;
1004
1005 sk_ASN1_OBJECT_pop_free(oid_stack, ASN1_OBJECT_free);
1006 return ret;
1007}
1008
1009void x509_utils_print_info(const X509* xcert)
1010{
1011 char* subject = x509_utils_get_subject(xcert);
1012 char* issuer = x509_utils_get_issuer(xcert);
1013 char* fp = (char*)x509_utils_get_hash(xcert, "sha256", nullptr);
1014
1015 if (!fp)
1016 {
1017 WLog_ERR(TAG, "error computing fingerprint");
1018 goto out_free_issuer;
1019 }
1020
1021 WLog_INFO(TAG, "Certificate details:");
1022 WLog_INFO(TAG, "\tSubject: %s", subject);
1023 WLog_INFO(TAG, "\tIssuer: %s", issuer);
1024 WLog_INFO(TAG, "\tThumbprint: %s", fp);
1025 WLog_INFO(TAG,
1026 "The above X.509 certificate could not be verified, possibly because you do not have "
1027 "the CA certificate in your certificate store, or the certificate has expired. "
1028 "Please look at the OpenSSL documentation on how to add a private CA to the store.");
1029 free(fp);
1030out_free_issuer:
1031 free(issuer);
1032 free(subject);
1033}
1034
1035X509* x509_utils_from_pem(const char* data, size_t len, BOOL fromFile)
1036{
1037 BIO* bio = nullptr;
1038 if (fromFile)
1039 bio = BIO_new_file(data, "rb");
1040 else
1041 {
1042 if (len > INT_MAX)
1043 return nullptr;
1044
1045 bio = BIO_new_mem_buf(data, (int)len);
1046 }
1047
1048 if (!bio)
1049 {
1050 WLog_ERR(TAG, "BIO_new failed for certificate");
1051 return nullptr;
1052 }
1053
1054 X509* x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
1055 BIO_free_all(bio);
1056 if (!x509)
1057 WLog_ERR(TAG, "PEM_read_bio_X509 returned nullptr [input length %" PRIuz "]", len);
1058
1059 return x509;
1060}
1061
1062WINPR_ATTR_NODISCARD
1063static WINPR_MD_TYPE hash_nid_to_winpr(int hash_nid)
1064{
1065 switch (hash_nid)
1066 {
1067 case NID_md2:
1068 return WINPR_MD_MD2;
1069 case NID_md4:
1070 return WINPR_MD_MD4;
1071 case NID_md5:
1072 return WINPR_MD_MD5;
1073 case NID_sha1:
1074 return WINPR_MD_SHA1;
1075 case NID_sha224:
1076 return WINPR_MD_SHA224;
1077 case NID_sha256:
1078 return WINPR_MD_SHA256;
1079 case NID_sha384:
1080 return WINPR_MD_SHA384;
1081 case NID_sha512:
1082 return WINPR_MD_SHA512;
1083 case NID_ripemd160:
1084 return WINPR_MD_RIPEMD160;
1085#if (OPENSSL_VERSION_NUMBER >= 0x1010101fL) && !defined(LIBRESSL_VERSION_NUMBER)
1086 case NID_sha3_224:
1087 return WINPR_MD_SHA3_224;
1088 case NID_sha3_256:
1089 return WINPR_MD_SHA3_256;
1090 case NID_sha3_384:
1091 return WINPR_MD_SHA3_384;
1092 case NID_sha3_512:
1093 return WINPR_MD_SHA3_512;
1094 case NID_shake128:
1095 return WINPR_MD_SHAKE128;
1096 case NID_shake256:
1097 return WINPR_MD_SHAKE256;
1098#endif
1099 case NID_undef:
1100 default:
1101 return WINPR_MD_NONE;
1102 }
1103}
1104
1105WINPR_ATTR_NODISCARD
1106static WINPR_MD_TYPE get_rsa_pss_digest(const X509_ALGOR* alg)
1107{
1108 WINPR_MD_TYPE ret = WINPR_MD_NONE;
1109 WINPR_MD_TYPE message_digest = WINPR_MD_NONE;
1110 WINPR_MD_TYPE mgf1_digest = WINPR_MD_NONE;
1111 int param_type = 0;
1112 const void* param_value = nullptr;
1113 const ASN1_STRING* sequence = nullptr;
1114 const unsigned char* inp = nullptr;
1115 RSA_PSS_PARAMS* params = nullptr;
1116 X509_ALGOR* mgf1_digest_alg = nullptr;
1117
1118 /* The RSA-PSS digest is encoded in a complex structure, defined in
1119 https://www.rfc-editor.org/rfc/rfc4055.html. */
1120 X509_ALGOR_get0(nullptr, &param_type, &param_value, alg);
1121
1122 /* param_type and param_value the parameter in ASN1_TYPE form, but split into two parameters. A
1123 SEQUENCE is has type V_ASN1_SEQUENCE, and the value is an ASN1_STRING with the encoded
1124 structure. */
1125 if (param_type != V_ASN1_SEQUENCE)
1126 goto end;
1127 sequence = param_value;
1128
1129 /* Decode the structure. */
1130 inp = ASN1_STRING_get0_data(sequence);
1131 params = d2i_RSA_PSS_PARAMS(nullptr, &inp, ASN1_STRING_length_wrapper(sequence));
1132 if (params == nullptr)
1133 goto end;
1134
1135 /* RSA-PSS uses two hash algorithms, a message digest and also an MGF function which is, itself,
1136 parameterized by a hash function. Both fields default to SHA-1, so we must also check for the
1137 value being nullptr. */
1138 message_digest = WINPR_MD_SHA1;
1139 if (params->hashAlgorithm != nullptr)
1140 {
1141 const ASN1_OBJECT* obj = nullptr;
1142 X509_ALGOR_get0(&obj, nullptr, nullptr, params->hashAlgorithm);
1143 message_digest = hash_nid_to_winpr(OBJ_obj2nid(obj));
1144 if (message_digest == WINPR_MD_NONE)
1145 goto end;
1146 }
1147
1148 mgf1_digest = WINPR_MD_SHA1;
1149 if (params->maskGenAlgorithm != nullptr)
1150 {
1151 const ASN1_OBJECT* obj = nullptr;
1152 int mgf_param_type = 0;
1153 const void* mgf_param_value = nullptr;
1154 const ASN1_STRING* mgf_param_sequence = nullptr;
1155 /* First, check this is MGF-1, the only one ever defined. */
1156 X509_ALGOR_get0(&obj, &mgf_param_type, &mgf_param_value, params->maskGenAlgorithm);
1157 if (OBJ_obj2nid(obj) != NID_mgf1)
1158 goto end;
1159
1160 /* MGF-1 is, itself, parameterized by a hash function, encoded as an AlgorithmIdentifier. */
1161 if (mgf_param_type != V_ASN1_SEQUENCE)
1162 goto end;
1163 mgf_param_sequence = mgf_param_value;
1164 inp = ASN1_STRING_get0_data(mgf_param_sequence);
1165 mgf1_digest_alg =
1166 d2i_X509_ALGOR(nullptr, &inp, ASN1_STRING_length_wrapper(mgf_param_sequence));
1167 if (mgf1_digest_alg == nullptr)
1168 goto end;
1169
1170 /* Finally, extract the digest. */
1171 X509_ALGOR_get0(&obj, nullptr, nullptr, mgf1_digest_alg);
1172 mgf1_digest = hash_nid_to_winpr(OBJ_obj2nid(obj));
1173 if (mgf1_digest == WINPR_MD_NONE)
1174 goto end;
1175 }
1176
1177 /* If the two digests do not match, it is ambiguous which to return. tls-server-end-point leaves
1178 it undefined, so return none.
1179 https://www.rfc-editor.org/rfc/rfc5929.html#section-4.1 */
1180 if (message_digest != mgf1_digest)
1181 goto end;
1182 ret = message_digest;
1183
1184end:
1185 RSA_PSS_PARAMS_free(params);
1186 X509_ALGOR_free(mgf1_digest_alg);
1187 return ret;
1188}
1189
1190WINPR_MD_TYPE x509_utils_get_signature_alg(const X509* xcert)
1191{
1192 WINPR_ASSERT(xcert);
1193
1194 const int nid = X509_get_signature_nid(xcert);
1195
1196 if (nid == NID_rsassaPss)
1197 {
1198 const X509_ALGOR* alg = nullptr;
1199 X509_get0_signature(nullptr, &alg, xcert);
1200 return get_rsa_pss_digest(alg);
1201 }
1202
1203 int hash_nid = 0;
1204 if (OBJ_find_sigid_algs(nid, &hash_nid, nullptr) != 1)
1205 return WINPR_MD_NONE;
1206
1207 return hash_nid_to_winpr(hash_nid);
1208}
1209
1210char* x509_utils_get_common_name(const X509* xcert, size_t* plength)
1211{
1212 const X509_NAME* subject_name = X509_get_subject_name(xcert);
1213 if (subject_name == nullptr)
1214 return nullptr;
1215
1216 const int index = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
1217 if (index < 0)
1218 return nullptr;
1219
1220 const X509_NAME_ENTRY* entry = X509_NAME_get_entry(subject_name, index);
1221 if (entry == nullptr)
1222 return nullptr;
1223
1224 const ASN1_STRING* entry_data = X509_NAME_ENTRY_get_data(entry);
1225 if (entry_data == nullptr)
1226 return nullptr;
1227
1228 BYTE* common_name_raw = nullptr;
1229 const int length = ASN1_STRING_to_UTF8(&common_name_raw, entry_data);
1230 if (length < 0)
1231 return nullptr;
1232
1233 char* common_name = nullptr;
1234 if (check_string_is_dns_name(xcert, common_name_raw, WINPR_ASSERTING_INT_CAST(size_t, length)))
1235 {
1236 if (plength)
1237 *plength = (size_t)length;
1238
1239 common_name = strndup((char*)common_name_raw, (size_t)length);
1240 }
1241 OPENSSL_free(common_name_raw);
1242 return common_name;
1243}
1244
1245WINPR_ATTR_NODISCARD
1246static int verify_cb(int ok, X509_STORE_CTX* csc)
1247{
1248 if (ok != 1)
1249 {
1250 WINPR_ASSERT(csc);
1251 int err = X509_STORE_CTX_get_error(csc);
1252 int derr = X509_STORE_CTX_get_error_depth(csc);
1253 X509* where = X509_STORE_CTX_get_current_cert(csc);
1254 const char* what = X509_verify_cert_error_string(err);
1255 char* name = x509_utils_get_subject(where);
1256
1257 WLog_WARN(TAG, "Certificate verification failure '%s (%d)' at stack position %d", what, err,
1258 derr);
1259 WLog_WARN(TAG, "%s", name);
1260
1261 free(name);
1262 }
1263 return ok;
1264}
1265
1266BOOL x509_utils_verify(X509* xcert, STACK_OF(X509) * chain, const char* certificate_store_path)
1267{
1268 const int purposes[] = { X509_PURPOSE_SSL_SERVER };
1269 BOOL status = FALSE;
1270
1271 if (!xcert)
1272 return FALSE;
1273
1274 X509_STORE* cert_ctx = X509_STORE_new();
1275
1276 if (cert_ctx == nullptr)
1277 goto end;
1278
1279#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1280 OpenSSL_add_all_algorithms();
1281#else
1282 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS |
1283 OPENSSL_INIT_LOAD_CONFIG,
1284 nullptr);
1285#endif
1286
1287 if (X509_STORE_set_default_paths(cert_ctx) != 1)
1288 goto end;
1289
1290 X509_LOOKUP* lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
1291
1292 if (lookup == nullptr)
1293 goto end;
1294
1295 X509_LOOKUP_add_dir(lookup, nullptr, X509_FILETYPE_DEFAULT);
1296
1297 if (certificate_store_path != nullptr)
1298 {
1299 X509_LOOKUP_add_dir(lookup, certificate_store_path, X509_FILETYPE_PEM);
1300 }
1301
1302 X509_STORE_set_flags(cert_ctx, 0);
1303
1304 for (size_t i = 0; i < ARRAYSIZE(purposes); i++)
1305 {
1306 int err = -1;
1307 int rc = -1;
1308 int purpose = purposes[i];
1309 X509_STORE_CTX* csc = X509_STORE_CTX_new();
1310
1311 if (csc == nullptr)
1312 goto skip;
1313 if (!X509_STORE_CTX_init(csc, cert_ctx, xcert, chain))
1314 goto skip;
1315
1316 X509_STORE_CTX_set_purpose(csc, purpose);
1317 X509_STORE_CTX_set_verify_cb(csc, verify_cb);
1318
1319 rc = X509_verify_cert(csc);
1320 err = X509_STORE_CTX_get_error(csc);
1321 skip:
1322 X509_STORE_CTX_free(csc);
1323 if (rc == 1)
1324 {
1325 status = TRUE;
1326 break;
1327 }
1328 else if (err != X509_V_ERR_INVALID_PURPOSE)
1329 break;
1330 }
1331
1332 X509_STORE_free(cert_ctx);
1333end:
1334 return status;
1335}
1336
1337char* x509_utils_bio_read(BIO* bio, size_t* plen)
1338{
1339 char* buffer = nullptr;
1340 WINPR_ASSERT(bio);
1341
1342 if (plen)
1343 *plen = 0;
1344
1345 BIO_flush(bio);
1346
1347 const UINT64 size = BIO_number_written(bio);
1348 if (size > INT_MAX)
1349 return nullptr;
1350
1351 buffer = calloc(1, (size_t)size + 1ull);
1352
1353 if (!buffer)
1354 return nullptr;
1355
1356 ERR_clear_error();
1357 const int rc = BIO_read(bio, buffer, (int)size);
1358 if (rc <= 0)
1359 goto fail;
1360
1361 if (plen)
1362 *plen = size;
1363 return buffer;
1364
1365fail:
1366 free(buffer);
1367 return nullptr;
1368}
1369
1370void x509_utils_ip_names_free(size_t count, size_t* lengths, char** dns_names)
1371{
1372 x509_utils_dns_names_free(count, lengths, dns_names);
1373}