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 does some function pointer casting that produces a warning. We
748 * can not fix upstream, so silence it here. */
749 WINPR_PRAGMA_DIAG_PUSH
750 WINPR_PRAGMA_DIAG_IGNORED_CAST_FUNCTION_TYPE
751 sk_ASN1_OBJECT_set_cmp_func(oid_stack, asn1_object_cmp);
752 WINPR_PRAGMA_DIAG_POP
753 if (sk_ASN1_OBJECT_find(oid_stack, oid) >= 0)
754 ret = TRUE;
755
756 sk_ASN1_OBJECT_pop_free(oid_stack, ASN1_OBJECT_free);
757 return ret;
758}
759
760void x509_utils_print_info(const X509* xcert)
761{
762 char* subject = x509_utils_get_subject(xcert);
763 char* issuer = x509_utils_get_issuer(xcert);
764 char* fp = (char*)x509_utils_get_hash(xcert, "sha256", nullptr);
765
766 if (!fp)
767 {
768 WLog_ERR(TAG, "error computing fingerprint");
769 goto out_free_issuer;
770 }
771
772 WLog_INFO(TAG, "Certificate details:");
773 WLog_INFO(TAG, "\tSubject: %s", subject);
774 WLog_INFO(TAG, "\tIssuer: %s", issuer);
775 WLog_INFO(TAG, "\tThumbprint: %s", fp);
776 WLog_INFO(TAG,
777 "The above X.509 certificate could not be verified, possibly because you do not have "
778 "the CA certificate in your certificate store, or the certificate has expired. "
779 "Please look at the OpenSSL documentation on how to add a private CA to the store.");
780 free(fp);
781out_free_issuer:
782 free(issuer);
783 free(subject);
784}
785
786X509* x509_utils_from_pem(const char* data, size_t len, BOOL fromFile)
787{
788 BIO* bio = nullptr;
789 if (fromFile)
790 bio = BIO_new_file(data, "rb");
791 else
792 {
793 if (len > INT_MAX)
794 return nullptr;
795
796 bio = BIO_new_mem_buf(data, (int)len);
797 }
798
799 if (!bio)
800 {
801 WLog_ERR(TAG, "BIO_new failed for certificate");
802 return nullptr;
803 }
804
805 X509* x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
806 BIO_free_all(bio);
807 if (!x509)
808 WLog_ERR(TAG, "PEM_read_bio_X509 returned nullptr [input length %" PRIuz "]", len);
809
810 return x509;
811}
812
813WINPR_ATTR_NODISCARD
814static WINPR_MD_TYPE hash_nid_to_winpr(int hash_nid)
815{
816 switch (hash_nid)
817 {
818 case NID_md2:
819 return WINPR_MD_MD2;
820 case NID_md4:
821 return WINPR_MD_MD4;
822 case NID_md5:
823 return WINPR_MD_MD5;
824 case NID_sha1:
825 return WINPR_MD_SHA1;
826 case NID_sha224:
827 return WINPR_MD_SHA224;
828 case NID_sha256:
829 return WINPR_MD_SHA256;
830 case NID_sha384:
831 return WINPR_MD_SHA384;
832 case NID_sha512:
833 return WINPR_MD_SHA512;
834 case NID_ripemd160:
835 return WINPR_MD_RIPEMD160;
836#if (OPENSSL_VERSION_NUMBER >= 0x1010101fL) && !defined(LIBRESSL_VERSION_NUMBER)
837 case NID_sha3_224:
838 return WINPR_MD_SHA3_224;
839 case NID_sha3_256:
840 return WINPR_MD_SHA3_256;
841 case NID_sha3_384:
842 return WINPR_MD_SHA3_384;
843 case NID_sha3_512:
844 return WINPR_MD_SHA3_512;
845 case NID_shake128:
846 return WINPR_MD_SHAKE128;
847 case NID_shake256:
848 return WINPR_MD_SHAKE256;
849#endif
850 case NID_undef:
851 default:
852 return WINPR_MD_NONE;
853 }
854}
855
856WINPR_ATTR_NODISCARD
857static WINPR_MD_TYPE get_rsa_pss_digest(const X509_ALGOR* alg)
858{
859 WINPR_MD_TYPE ret = WINPR_MD_NONE;
860 WINPR_MD_TYPE message_digest = WINPR_MD_NONE;
861 WINPR_MD_TYPE mgf1_digest = WINPR_MD_NONE;
862 int param_type = 0;
863 const void* param_value = nullptr;
864 const ASN1_STRING* sequence = nullptr;
865 const unsigned char* inp = nullptr;
866 RSA_PSS_PARAMS* params = nullptr;
867 X509_ALGOR* mgf1_digest_alg = nullptr;
868
869 /* The RSA-PSS digest is encoded in a complex structure, defined in
870 https://www.rfc-editor.org/rfc/rfc4055.html. */
871 X509_ALGOR_get0(nullptr, &param_type, &param_value, alg);
872
873 /* param_type and param_value the parameter in ASN1_TYPE form, but split into two parameters. A
874 SEQUENCE is has type V_ASN1_SEQUENCE, and the value is an ASN1_STRING with the encoded
875 structure. */
876 if (param_type != V_ASN1_SEQUENCE)
877 goto end;
878 sequence = param_value;
879
880 /* Decode the structure. */
881 inp = ASN1_STRING_get0_data(sequence);
882 params = d2i_RSA_PSS_PARAMS(nullptr, &inp, ASN1_STRING_length(sequence));
883 if (params == nullptr)
884 goto end;
885
886 /* RSA-PSS uses two hash algorithms, a message digest and also an MGF function which is, itself,
887 parameterized by a hash function. Both fields default to SHA-1, so we must also check for the
888 value being nullptr. */
889 message_digest = WINPR_MD_SHA1;
890 if (params->hashAlgorithm != nullptr)
891 {
892 const ASN1_OBJECT* obj = nullptr;
893 X509_ALGOR_get0(&obj, nullptr, nullptr, params->hashAlgorithm);
894 message_digest = hash_nid_to_winpr(OBJ_obj2nid(obj));
895 if (message_digest == WINPR_MD_NONE)
896 goto end;
897 }
898
899 mgf1_digest = WINPR_MD_SHA1;
900 if (params->maskGenAlgorithm != nullptr)
901 {
902 const ASN1_OBJECT* obj = nullptr;
903 int mgf_param_type = 0;
904 const void* mgf_param_value = nullptr;
905 const ASN1_STRING* mgf_param_sequence = nullptr;
906 /* First, check this is MGF-1, the only one ever defined. */
907 X509_ALGOR_get0(&obj, &mgf_param_type, &mgf_param_value, params->maskGenAlgorithm);
908 if (OBJ_obj2nid(obj) != NID_mgf1)
909 goto end;
910
911 /* MGF-1 is, itself, parameterized by a hash function, encoded as an AlgorithmIdentifier. */
912 if (mgf_param_type != V_ASN1_SEQUENCE)
913 goto end;
914 mgf_param_sequence = mgf_param_value;
915 inp = ASN1_STRING_get0_data(mgf_param_sequence);
916 mgf1_digest_alg = d2i_X509_ALGOR(nullptr, &inp, ASN1_STRING_length(mgf_param_sequence));
917 if (mgf1_digest_alg == nullptr)
918 goto end;
919
920 /* Finally, extract the digest. */
921 X509_ALGOR_get0(&obj, nullptr, nullptr, mgf1_digest_alg);
922 mgf1_digest = hash_nid_to_winpr(OBJ_obj2nid(obj));
923 if (mgf1_digest == WINPR_MD_NONE)
924 goto end;
925 }
926
927 /* If the two digests do not match, it is ambiguous which to return. tls-server-end-point leaves
928 it undefined, so return none.
929 https://www.rfc-editor.org/rfc/rfc5929.html#section-4.1 */
930 if (message_digest != mgf1_digest)
931 goto end;
932 ret = message_digest;
933
934end:
935 RSA_PSS_PARAMS_free(params);
936 X509_ALGOR_free(mgf1_digest_alg);
937 return ret;
938}
939
940WINPR_MD_TYPE x509_utils_get_signature_alg(const X509* xcert)
941{
942 WINPR_ASSERT(xcert);
943
944 const int nid = X509_get_signature_nid(xcert);
945
946 if (nid == NID_rsassaPss)
947 {
948 const X509_ALGOR* alg = nullptr;
949 X509_get0_signature(nullptr, &alg, xcert);
950 return get_rsa_pss_digest(alg);
951 }
952
953 int hash_nid = 0;
954 if (OBJ_find_sigid_algs(nid, &hash_nid, nullptr) != 1)
955 return WINPR_MD_NONE;
956
957 return hash_nid_to_winpr(hash_nid);
958}
959
960char* x509_utils_get_common_name(const X509* xcert, size_t* plength)
961{
962 const X509_NAME* subject_name = X509_get_subject_name(xcert);
963 if (subject_name == nullptr)
964 return nullptr;
965
966 const int index = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
967 if (index < 0)
968 return nullptr;
969
970 const X509_NAME_ENTRY* entry = X509_NAME_get_entry(subject_name, index);
971 if (entry == nullptr)
972 return nullptr;
973
974 const ASN1_STRING* entry_data = X509_NAME_ENTRY_get_data(entry);
975 if (entry_data == nullptr)
976 return nullptr;
977
978 BYTE* common_name_raw = nullptr;
979 const int length = ASN1_STRING_to_UTF8(&common_name_raw, entry_data);
980 if (length < 0)
981 return nullptr;
982
983 char* common_name = nullptr;
984 if (check_string_is_host_or_ip(xcert, common_name_raw,
985 WINPR_ASSERTING_INT_CAST(size_t, length)))
986 {
987 if (plength)
988 *plength = (size_t)length;
989
990 common_name = strndup((char*)common_name_raw, (size_t)length);
991 }
992 OPENSSL_free(common_name_raw);
993 return common_name;
994}
995
996WINPR_ATTR_NODISCARD
997static int verify_cb(int ok, X509_STORE_CTX* csc)
998{
999 if (ok != 1)
1000 {
1001 WINPR_ASSERT(csc);
1002 int err = X509_STORE_CTX_get_error(csc);
1003 int derr = X509_STORE_CTX_get_error_depth(csc);
1004 X509* where = X509_STORE_CTX_get_current_cert(csc);
1005 const char* what = X509_verify_cert_error_string(err);
1006 char* name = x509_utils_get_subject(where);
1007
1008 WLog_WARN(TAG, "Certificate verification failure '%s (%d)' at stack position %d", what, err,
1009 derr);
1010 WLog_WARN(TAG, "%s", name);
1011
1012 free(name);
1013 }
1014 return ok;
1015}
1016
1017BOOL x509_utils_verify(X509* xcert, STACK_OF(X509) * chain, const char* certificate_store_path)
1018{
1019 const int purposes[] = { X509_PURPOSE_SSL_SERVER };
1020 BOOL status = FALSE;
1021
1022 if (!xcert)
1023 return FALSE;
1024
1025 X509_STORE* cert_ctx = X509_STORE_new();
1026
1027 if (cert_ctx == nullptr)
1028 goto end;
1029
1030#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1031 OpenSSL_add_all_algorithms();
1032#else
1033 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS |
1034 OPENSSL_INIT_LOAD_CONFIG,
1035 nullptr);
1036#endif
1037
1038 if (X509_STORE_set_default_paths(cert_ctx) != 1)
1039 goto end;
1040
1041 X509_LOOKUP* lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
1042
1043 if (lookup == nullptr)
1044 goto end;
1045
1046 X509_LOOKUP_add_dir(lookup, nullptr, X509_FILETYPE_DEFAULT);
1047
1048 if (certificate_store_path != nullptr)
1049 {
1050 X509_LOOKUP_add_dir(lookup, certificate_store_path, X509_FILETYPE_PEM);
1051 }
1052
1053 X509_STORE_set_flags(cert_ctx, 0);
1054
1055 for (size_t i = 0; i < ARRAYSIZE(purposes); i++)
1056 {
1057 int err = -1;
1058 int rc = -1;
1059 int purpose = purposes[i];
1060 X509_STORE_CTX* csc = X509_STORE_CTX_new();
1061
1062 if (csc == nullptr)
1063 goto skip;
1064 if (!X509_STORE_CTX_init(csc, cert_ctx, xcert, chain))
1065 goto skip;
1066
1067 X509_STORE_CTX_set_purpose(csc, purpose);
1068 X509_STORE_CTX_set_verify_cb(csc, verify_cb);
1069
1070 rc = X509_verify_cert(csc);
1071 err = X509_STORE_CTX_get_error(csc);
1072 skip:
1073 X509_STORE_CTX_free(csc);
1074 if (rc == 1)
1075 {
1076 status = TRUE;
1077 break;
1078 }
1079 else if (err != X509_V_ERR_INVALID_PURPOSE)
1080 break;
1081 }
1082
1083 X509_STORE_free(cert_ctx);
1084end:
1085 return status;
1086}
1087
1088char* x509_utils_bio_read(BIO* bio, size_t* plen)
1089{
1090 char* buffer = nullptr;
1091 WINPR_ASSERT(bio);
1092
1093 if (plen)
1094 *plen = 0;
1095
1096 BIO_flush(bio);
1097
1098 const UINT64 size = BIO_number_written(bio);
1099 if (size > INT_MAX)
1100 return nullptr;
1101
1102 buffer = calloc(1, (size_t)size + 1ull);
1103
1104 if (!buffer)
1105 return nullptr;
1106
1107 ERR_clear_error();
1108 const int rc = BIO_read(bio, buffer, (int)size);
1109 if (rc <= 0)
1110 goto fail;
1111
1112 if (plen)
1113 *plen = size;
1114 return buffer;
1115
1116fail:
1117 free(buffer);
1118 return nullptr;
1119}