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