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