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