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_hostnameN(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_hostnameN(str, length);
352}
353
354WINPR_ATTR_NODISCARD
355static BOOL check_string_is_dns_name(const X509* x509, const unsigned char* ustr, size_t length)
356{
357 /* RFC 6125 wildcard DNS names (e.g. *.example.com): validate the part after
358 * the leading label; tls_match_hostname applies the single-label rule.
359 * Like OpenSSL, require at least two non-empty labels after the wildcard,
360 * so *.com, *..com and *.com. are rejected. */
361 if ((length > 2) && (ustr[0] == '*') && (ustr[1] == '.'))
362 {
363 const unsigned char* suffix = &ustr[2];
364 const size_t suffixLength = length - 2;
365 size_t dots = 0;
366
367 if ((suffix[0] == '.') || (suffix[suffixLength - 1] == '.'))
368 return FALSE;
369
370 for (size_t x = 1; x < suffixLength; x++)
371 {
372 if (suffix[x] == '.')
373 {
374 if (suffix[x - 1] == '.')
375 return FALSE;
376 dots++;
377 }
378 }
379
380 if (dots == 0)
381 return FALSE;
382 return check_string_is_host_or_ip(x509, suffix, suffixLength);
383 }
384 return check_string_is_host_or_ip(x509, ustr, length);
385}
386
387WINPR_ATTR_NODISCARD
388static BOOL check_string_is_host_or_ip_or_email(WINPR_ATTR_UNUSED const X509* x509,
389 const unsigned char* ustr, size_t length)
390{
391 if (check_string_is_host_or_ip(x509, ustr, length))
392 return TRUE;
393 return check_string_is_email(x509, ustr, length);
394}
395
396WINPR_ATTR_NODISCARD
397static int
398extract_string_generic(const X509* x509, GENERAL_NAME* name, void* data, int index, int count,
399 BOOL (*fkt)(const X509* x509, const unsigned char* str, size_t length))
400{
401 string_list* list = data;
402 WINPR_ASSERT(list);
403 WINPR_ASSERT(fkt);
404
405 WINPR_ASSERT(name);
406 WINPR_UNUSED(index);
407
408 const ASN1_STRING* str = nullptr;
409 switch (name->type)
410 {
411 case GEN_URI:
412 str = name->d.uniformResourceIdentifier;
413 break;
414
415 case GEN_DNS:
416 str = name->d.dNSName;
417 break;
418
419 case GEN_EMAIL:
420 str = name->d.rfc822Name;
421 break;
422
423 default:
424 return 1;
425 }
426
427 unsigned char* cstring = nullptr;
428 const int rc = ASN1_STRING_to_UTF8(&cstring, str);
429 if (rc < 0)
430 {
431 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() failed for %s: %s",
432 general_name_type_label(name->type), ERR_error_string(ERR_get_error(), nullptr));
433 return 1;
434 }
435
436 if (!fkt(x509, cstring, WINPR_ASSERTING_INT_CAST(size_t, rc)))
437 {
438 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() does not conform to expected format %s: %s",
439 general_name_type_label(name->type), (const char*)str);
440 OPENSSL_free(cstring);
441 return -1;
442 }
443
444 if (!string_list_allocate(list, WINPR_ASSERTING_INT_CAST(WINPR_CIPHER_TYPE, count)) ||
445 (list->allocated <= 0))
446 {
447 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() allocation failed: %s",
448 general_name_type_label(name->type));
449 OPENSSL_free(cstring);
450 return 0;
451 }
452
453 list->strings[list->count] = (char*)cstring;
454 list->lengths[list->count] = WINPR_ASSERTING_INT_CAST(size_t, rc);
455 list->count++;
456
457 if (list->count >= list->maximum)
458 {
459 WLog_ERR(TAG, "ASN1_STRING_to_UTF8() limit exceeded: %s",
460 general_name_type_label(name->type));
461 return 0;
462 }
463
464 return 1;
465}
466
467WINPR_ATTR_NODISCARD
468static int extract_string(const X509* x509, GENERAL_NAME* name, void* data, int index, int count)
469{
470 return extract_string_generic(x509, name, data, index, count, check_string_is_dns_name);
471}
472
473static int extract_email(const X509* x509, GENERAL_NAME* name, void* data, int index, int count)
474{
475 return extract_string_generic(x509, name, data, index, count, check_string_is_email);
476}
477
478/*
479extract_othername_object -- object extractor.
480
481- the objects array is allocated lazily, when we first have to store a
482 string.
483
484- allocated contains the size of the objects array, or -1 if
485 allocation failed.
486
487- count contains the actual count of objects in the objects array.
488
489- maximum limits the number of objects we can store in the objects
490 array: beyond, the extractor returns 0 to short-cut the search.
491
492extract_othername_objects stores in the objects array ASN1_TYPE *
493pointers directly obtained from the GENERAL_NAME.
494*/
495
496typedef struct object_list
497{
498 ASN1_OBJECT* type_id;
499 char** strings;
500 size_t* lengths;
501
502 size_t allocated;
503 size_t count;
504 size_t maximum;
505} object_list;
506
507static object_list object_list_initialize(void)
508{
509 const object_list empty = { .type_id = nullptr,
510 .strings = nullptr,
511 .lengths = nullptr,
512 .allocated = 0,
513 .count = 0,
514 .maximum = INT_MAX };
515 return empty;
516}
517
518WINPR_ATTR_NODISCARD
519static BOOL object_list_allocate(object_list* list, size_t allocate_count)
520{
521 if (!list->strings && (list->allocated == 0) && (allocate_count > 0))
522 {
523 list->strings = (char**)calloc(allocate_count, sizeof(list->strings[0]));
524 list->lengths = calloc(allocate_count, sizeof(size_t));
525 list->count = 0;
526 if (!list->strings || !list->lengths)
527 {
528 free((void*)list->strings);
529 free(list->lengths);
530 list->strings = nullptr;
531 list->lengths = nullptr;
532 return FALSE;
533 }
534 list->allocated = allocate_count;
535 }
536 return TRUE;
537}
538
539WINPR_ATTR_MALLOC(free, 1)
540static char* object_string(const X509* x509, ASN1_TYPE* object, size_t* pLength)
541{
542 unsigned char* utf8String = nullptr;
543
544 WINPR_ASSERT(object);
545 WINPR_ASSERT(pLength);
546
547 *pLength = 0;
548
549 /* TODO: check that object.type is a string type. */
550 const int length = ASN1_STRING_to_UTF8(&utf8String, object->value.asn1_string);
551
552 if (length < 0)
553 return nullptr;
554
555 char* result = nullptr;
556 if (check_string_is_host_or_ip_or_email(x509, utf8String,
557 WINPR_ASSERTING_INT_CAST(size_t, length)))
558 {
559 result = strndup((char*)utf8String, WINPR_ASSERTING_INT_CAST(size_t, length));
560 if (result)
561 *pLength = WINPR_ASSERTING_INT_CAST(size_t, length);
562 }
563 else
564 WLog_ERR(TAG, "Found invalid object_string entry in certificate: '%s'", utf8String);
565 OPENSSL_free(utf8String);
566 return result;
567}
568
569static void object_list_free(object_list* list)
570{
571 WINPR_ASSERT(list);
572 free((void*)list->strings);
573 free(list->lengths);
574}
575
576WINPR_ATTR_NODISCARD
577static int extract_othername_object_as_string(const X509* x509, GENERAL_NAME* name, void* data,
578 int index, int count)
579{
580 object_list* list = data;
581 WINPR_UNUSED(index);
582 WINPR_ASSERT(x509);
583
584 if (count < 0)
585 return -1;
586
587 if (name->type != GEN_OTHERNAME)
588 {
589 return 1;
590 }
591
592 if (0 != OBJ_cmp(name->d.otherName->type_id, list->type_id))
593 {
594 return 1;
595 }
596
597 if (!object_list_allocate(list, WINPR_ASSERTING_INT_CAST(size_t, count)) ||
598 (list->allocated <= 0))
599 {
600 return 0;
601 }
602
603 list->strings[list->count] =
604 object_string(x509, name->d.otherName->value, &list->lengths[list->count]);
605 if (list->strings[list->count])
606 {
607 list->count++;
608 }
609
610 if (list->count >= list->maximum)
611 {
612 return 0;
613 }
614
615 return 1;
616}
617
618char* x509_utils_get_email(const X509* x509)
619{
620 string_list list = string_list_initialize();
621 list.maximum = 1;
622 map_subject_alt_name(x509, GEN_EMAIL, extract_email, &list);
623
624 if (list.count == 0)
625 {
626 string_list_free(&list);
627 return nullptr;
628 }
629
630 char* result = strndup(list.strings[0], list.lengths[0]);
631 OPENSSL_free(list.strings[0]);
632 string_list_free(&list);
633 return result;
634}
635
636char* x509_utils_get_upn(const X509* x509)
637{
638 object_list list = object_list_initialize();
639
640 list.type_id = OBJ_nid2obj(NID_ms_upn);
641 list.maximum = 1;
642 map_subject_alt_name(x509, GEN_OTHERNAME, extract_othername_object_as_string, &list);
643
644 if (list.count == 0)
645 {
646 object_list_free(&list);
647 return nullptr;
648 }
649
650 char* result = list.strings[0];
651 object_list_free(&list);
652 return result;
653}
654
655char* x509_utils_get_date(const X509* x509, BOOL startDate)
656{
657 WINPR_ASSERT(x509);
658
659 const ASN1_TIME* date = startDate ? X509_get0_notBefore(x509) : X509_get0_notAfter(x509);
660 if (!date)
661 return nullptr;
662
663 BIO* bmem = BIO_new(BIO_s_mem());
664 if (!bmem)
665 return nullptr;
666
667 char* str = nullptr;
668 if (ASN1_TIME_print(bmem, date))
669 {
670 BUF_MEM* bptr = nullptr;
671
672 BIO_get_mem_ptr(bmem, &bptr);
673 str = strndup(bptr->data, bptr->length);
674 }
675 else
676 { // Log error
677 }
678 BIO_free_all(bmem);
679 return str;
680}
681
682void x509_utils_dns_names_free(size_t count, size_t* lengths, char** dns_names)
683{
684 free(lengths);
685
686 if (dns_names)
687 {
688 for (size_t i = 0; i < count; i++)
689 {
690 if (dns_names[i])
691 {
692 OPENSSL_free(dns_names[i]);
693 }
694 }
695
696 free((void*)dns_names);
697 }
698}
699
700WINPR_ATTR_NODISCARD
701static char** x509_utils_get_names(const X509* xcert, int general_name_type, size_t* count,
702 size_t** lengths)
703{
704 string_list list = string_list_initialize();
705 map_subject_alt_name(xcert, general_name_type, extract_string, &list);
706 (*count) = list.count;
707
708 if (list.count <= 0)
709 {
710 string_list_free(&list);
711 return nullptr;
712 }
713
714 /* lengths are not useful, since we converted the
715 strings to utf-8, there cannot be nul-bytes in them. */
716 char** result = (char**)calloc(list.count, sizeof(*result));
717 (*lengths) = calloc(list.count, sizeof(**lengths));
718
719 if (!result || !(*lengths))
720 {
721 string_list_free(&list);
722 free((void*)result);
723 free(*lengths);
724 (*lengths) = nullptr;
725 (*count) = 0;
726 return nullptr;
727 }
728
729 for (size_t i = 0; i < list.count; i++)
730 {
731 result[i] = list.strings[i];
732 (*lengths)[i] = list.lengths[i];
733 }
734
735 string_list_free(&list);
736 return result;
737}
738
739char** x509_utils_get_dns_names(const X509* xcert, size_t* count, size_t** pplengths)
740{
741 return x509_utils_get_names(xcert, GEN_DNS, count, pplengths);
742}
743
744char** x509_utils_get_ip_names(const X509* xcert, size_t* count, size_t** pplengths)
745{
746 return x509_utils_get_names(xcert, GEN_IPADD, count, pplengths);
747}
748
749char* x509_utils_get_issuer(const X509* xcert)
750{
751 char* issuer = nullptr;
752 if (!xcert)
753 {
754 WLog_ERR(TAG, "Invalid certificate nullptr");
755 return nullptr;
756 }
757 issuer = crypto_print_name(X509_get_issuer_name(xcert));
758 if (!issuer)
759 WLog_WARN(TAG, "certificate does not have an issuer!");
760 return issuer;
761}
762
763WINPR_ATTR_NODISCARD
764static int asn1_object_cmp(const ASN1_OBJECT* const* a, const ASN1_OBJECT* const* b)
765{
766 if (!a || !b)
767 return (a == b) ? 0 : (a ? 1 : -1);
768
769 if (!*a || !*b)
770 return (*a == *b) ? 0 : (*a ? 1 : -1);
771
772 return OBJ_cmp(*a, *b);
773}
774
775BOOL x509_utils_check_eku(const X509* xcert, int nid)
776{
777 BOOL ret = FALSE;
778 STACK_OF(ASN1_OBJECT)* oid_stack = nullptr;
779 ASN1_OBJECT* oid = nullptr;
780
781 if (!xcert)
782 return FALSE;
783
784 oid = OBJ_nid2obj(nid);
785 if (!oid)
786 return FALSE;
787
788 oid_stack = X509_get_ext_d2i(xcert, NID_ext_key_usage, nullptr, nullptr);
789 if (!oid_stack)
790 return FALSE;
791
792 /* sk_ASN1_OBJECT_set_cmp_func does some function pointer casting that produces a warning. We
793 * can not fix upstream, so silence it here. */
794 WINPR_PRAGMA_DIAG_PUSH
795 WINPR_PRAGMA_DIAG_IGNORED_CAST_FUNCTION_TYPE
796 sk_ASN1_OBJECT_set_cmp_func(oid_stack, asn1_object_cmp);
797 WINPR_PRAGMA_DIAG_POP
798 if (sk_ASN1_OBJECT_find(oid_stack, oid) >= 0)
799 ret = TRUE;
800
801 sk_ASN1_OBJECT_pop_free(oid_stack, ASN1_OBJECT_free);
802 return ret;
803}
804
805void x509_utils_print_info(const X509* xcert)
806{
807 char* subject = x509_utils_get_subject(xcert);
808 char* issuer = x509_utils_get_issuer(xcert);
809 char* fp = (char*)x509_utils_get_hash(xcert, "sha256", nullptr);
810
811 if (!fp)
812 {
813 WLog_ERR(TAG, "error computing fingerprint");
814 goto out_free_issuer;
815 }
816
817 WLog_INFO(TAG, "Certificate details:");
818 WLog_INFO(TAG, "\tSubject: %s", subject);
819 WLog_INFO(TAG, "\tIssuer: %s", issuer);
820 WLog_INFO(TAG, "\tThumbprint: %s", fp);
821 WLog_INFO(TAG,
822 "The above X.509 certificate could not be verified, possibly because you do not have "
823 "the CA certificate in your certificate store, or the certificate has expired. "
824 "Please look at the OpenSSL documentation on how to add a private CA to the store.");
825 free(fp);
826out_free_issuer:
827 free(issuer);
828 free(subject);
829}
830
831X509* x509_utils_from_pem(const char* data, size_t len, BOOL fromFile)
832{
833 BIO* bio = nullptr;
834 if (fromFile)
835 bio = BIO_new_file(data, "rb");
836 else
837 {
838 if (len > INT_MAX)
839 return nullptr;
840
841 bio = BIO_new_mem_buf(data, (int)len);
842 }
843
844 if (!bio)
845 {
846 WLog_ERR(TAG, "BIO_new failed for certificate");
847 return nullptr;
848 }
849
850 X509* x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
851 BIO_free_all(bio);
852 if (!x509)
853 WLog_ERR(TAG, "PEM_read_bio_X509 returned nullptr [input length %" PRIuz "]", len);
854
855 return x509;
856}
857
858WINPR_ATTR_NODISCARD
859static WINPR_MD_TYPE hash_nid_to_winpr(int hash_nid)
860{
861 switch (hash_nid)
862 {
863 case NID_md2:
864 return WINPR_MD_MD2;
865 case NID_md4:
866 return WINPR_MD_MD4;
867 case NID_md5:
868 return WINPR_MD_MD5;
869 case NID_sha1:
870 return WINPR_MD_SHA1;
871 case NID_sha224:
872 return WINPR_MD_SHA224;
873 case NID_sha256:
874 return WINPR_MD_SHA256;
875 case NID_sha384:
876 return WINPR_MD_SHA384;
877 case NID_sha512:
878 return WINPR_MD_SHA512;
879 case NID_ripemd160:
880 return WINPR_MD_RIPEMD160;
881#if (OPENSSL_VERSION_NUMBER >= 0x1010101fL) && !defined(LIBRESSL_VERSION_NUMBER)
882 case NID_sha3_224:
883 return WINPR_MD_SHA3_224;
884 case NID_sha3_256:
885 return WINPR_MD_SHA3_256;
886 case NID_sha3_384:
887 return WINPR_MD_SHA3_384;
888 case NID_sha3_512:
889 return WINPR_MD_SHA3_512;
890 case NID_shake128:
891 return WINPR_MD_SHAKE128;
892 case NID_shake256:
893 return WINPR_MD_SHAKE256;
894#endif
895 case NID_undef:
896 default:
897 return WINPR_MD_NONE;
898 }
899}
900
901WINPR_ATTR_NODISCARD
902static WINPR_MD_TYPE get_rsa_pss_digest(const X509_ALGOR* alg)
903{
904 WINPR_MD_TYPE ret = WINPR_MD_NONE;
905 WINPR_MD_TYPE message_digest = WINPR_MD_NONE;
906 WINPR_MD_TYPE mgf1_digest = WINPR_MD_NONE;
907 int param_type = 0;
908 const void* param_value = nullptr;
909 const ASN1_STRING* sequence = nullptr;
910 const unsigned char* inp = nullptr;
911 RSA_PSS_PARAMS* params = nullptr;
912 X509_ALGOR* mgf1_digest_alg = nullptr;
913
914 /* The RSA-PSS digest is encoded in a complex structure, defined in
915 https://www.rfc-editor.org/rfc/rfc4055.html. */
916 X509_ALGOR_get0(nullptr, &param_type, &param_value, alg);
917
918 /* param_type and param_value the parameter in ASN1_TYPE form, but split into two parameters. A
919 SEQUENCE is has type V_ASN1_SEQUENCE, and the value is an ASN1_STRING with the encoded
920 structure. */
921 if (param_type != V_ASN1_SEQUENCE)
922 goto end;
923 sequence = param_value;
924
925 /* Decode the structure. */
926 inp = ASN1_STRING_get0_data(sequence);
927 params = d2i_RSA_PSS_PARAMS(nullptr, &inp, ASN1_STRING_length(sequence));
928 if (params == nullptr)
929 goto end;
930
931 /* RSA-PSS uses two hash algorithms, a message digest and also an MGF function which is, itself,
932 parameterized by a hash function. Both fields default to SHA-1, so we must also check for the
933 value being nullptr. */
934 message_digest = WINPR_MD_SHA1;
935 if (params->hashAlgorithm != nullptr)
936 {
937 const ASN1_OBJECT* obj = nullptr;
938 X509_ALGOR_get0(&obj, nullptr, nullptr, params->hashAlgorithm);
939 message_digest = hash_nid_to_winpr(OBJ_obj2nid(obj));
940 if (message_digest == WINPR_MD_NONE)
941 goto end;
942 }
943
944 mgf1_digest = WINPR_MD_SHA1;
945 if (params->maskGenAlgorithm != nullptr)
946 {
947 const ASN1_OBJECT* obj = nullptr;
948 int mgf_param_type = 0;
949 const void* mgf_param_value = nullptr;
950 const ASN1_STRING* mgf_param_sequence = nullptr;
951 /* First, check this is MGF-1, the only one ever defined. */
952 X509_ALGOR_get0(&obj, &mgf_param_type, &mgf_param_value, params->maskGenAlgorithm);
953 if (OBJ_obj2nid(obj) != NID_mgf1)
954 goto end;
955
956 /* MGF-1 is, itself, parameterized by a hash function, encoded as an AlgorithmIdentifier. */
957 if (mgf_param_type != V_ASN1_SEQUENCE)
958 goto end;
959 mgf_param_sequence = mgf_param_value;
960 inp = ASN1_STRING_get0_data(mgf_param_sequence);
961 mgf1_digest_alg = d2i_X509_ALGOR(nullptr, &inp, ASN1_STRING_length(mgf_param_sequence));
962 if (mgf1_digest_alg == nullptr)
963 goto end;
964
965 /* Finally, extract the digest. */
966 X509_ALGOR_get0(&obj, nullptr, nullptr, mgf1_digest_alg);
967 mgf1_digest = hash_nid_to_winpr(OBJ_obj2nid(obj));
968 if (mgf1_digest == WINPR_MD_NONE)
969 goto end;
970 }
971
972 /* If the two digests do not match, it is ambiguous which to return. tls-server-end-point leaves
973 it undefined, so return none.
974 https://www.rfc-editor.org/rfc/rfc5929.html#section-4.1 */
975 if (message_digest != mgf1_digest)
976 goto end;
977 ret = message_digest;
978
979end:
980 RSA_PSS_PARAMS_free(params);
981 X509_ALGOR_free(mgf1_digest_alg);
982 return ret;
983}
984
985WINPR_MD_TYPE x509_utils_get_signature_alg(const X509* xcert)
986{
987 WINPR_ASSERT(xcert);
988
989 const int nid = X509_get_signature_nid(xcert);
990
991 if (nid == NID_rsassaPss)
992 {
993 const X509_ALGOR* alg = nullptr;
994 X509_get0_signature(nullptr, &alg, xcert);
995 return get_rsa_pss_digest(alg);
996 }
997
998 int hash_nid = 0;
999 if (OBJ_find_sigid_algs(nid, &hash_nid, nullptr) != 1)
1000 return WINPR_MD_NONE;
1001
1002 return hash_nid_to_winpr(hash_nid);
1003}
1004
1005char* x509_utils_get_common_name(const X509* xcert, size_t* plength)
1006{
1007 const X509_NAME* subject_name = X509_get_subject_name(xcert);
1008 if (subject_name == nullptr)
1009 return nullptr;
1010
1011 const int index = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
1012 if (index < 0)
1013 return nullptr;
1014
1015 const X509_NAME_ENTRY* entry = X509_NAME_get_entry(subject_name, index);
1016 if (entry == nullptr)
1017 return nullptr;
1018
1019 const ASN1_STRING* entry_data = X509_NAME_ENTRY_get_data(entry);
1020 if (entry_data == nullptr)
1021 return nullptr;
1022
1023 BYTE* common_name_raw = nullptr;
1024 const int length = ASN1_STRING_to_UTF8(&common_name_raw, entry_data);
1025 if (length < 0)
1026 return nullptr;
1027
1028 char* common_name = nullptr;
1029 if (check_string_is_dns_name(xcert, common_name_raw, WINPR_ASSERTING_INT_CAST(size_t, length)))
1030 {
1031 if (plength)
1032 *plength = (size_t)length;
1033
1034 common_name = strndup((char*)common_name_raw, (size_t)length);
1035 }
1036 OPENSSL_free(common_name_raw);
1037 return common_name;
1038}
1039
1040WINPR_ATTR_NODISCARD
1041static int verify_cb(int ok, X509_STORE_CTX* csc)
1042{
1043 if (ok != 1)
1044 {
1045 WINPR_ASSERT(csc);
1046 int err = X509_STORE_CTX_get_error(csc);
1047 int derr = X509_STORE_CTX_get_error_depth(csc);
1048 X509* where = X509_STORE_CTX_get_current_cert(csc);
1049 const char* what = X509_verify_cert_error_string(err);
1050 char* name = x509_utils_get_subject(where);
1051
1052 WLog_WARN(TAG, "Certificate verification failure '%s (%d)' at stack position %d", what, err,
1053 derr);
1054 WLog_WARN(TAG, "%s", name);
1055
1056 free(name);
1057 }
1058 return ok;
1059}
1060
1061BOOL x509_utils_verify(X509* xcert, STACK_OF(X509) * chain, const char* certificate_store_path)
1062{
1063 const int purposes[] = { X509_PURPOSE_SSL_SERVER };
1064 BOOL status = FALSE;
1065
1066 if (!xcert)
1067 return FALSE;
1068
1069 X509_STORE* cert_ctx = X509_STORE_new();
1070
1071 if (cert_ctx == nullptr)
1072 goto end;
1073
1074#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1075 OpenSSL_add_all_algorithms();
1076#else
1077 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS |
1078 OPENSSL_INIT_LOAD_CONFIG,
1079 nullptr);
1080#endif
1081
1082 if (X509_STORE_set_default_paths(cert_ctx) != 1)
1083 goto end;
1084
1085 X509_LOOKUP* lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
1086
1087 if (lookup == nullptr)
1088 goto end;
1089
1090 X509_LOOKUP_add_dir(lookup, nullptr, X509_FILETYPE_DEFAULT);
1091
1092 if (certificate_store_path != nullptr)
1093 {
1094 X509_LOOKUP_add_dir(lookup, certificate_store_path, X509_FILETYPE_PEM);
1095 }
1096
1097 X509_STORE_set_flags(cert_ctx, 0);
1098
1099 for (size_t i = 0; i < ARRAYSIZE(purposes); i++)
1100 {
1101 int err = -1;
1102 int rc = -1;
1103 int purpose = purposes[i];
1104 X509_STORE_CTX* csc = X509_STORE_CTX_new();
1105
1106 if (csc == nullptr)
1107 goto skip;
1108 if (!X509_STORE_CTX_init(csc, cert_ctx, xcert, chain))
1109 goto skip;
1110
1111 X509_STORE_CTX_set_purpose(csc, purpose);
1112 X509_STORE_CTX_set_verify_cb(csc, verify_cb);
1113
1114 rc = X509_verify_cert(csc);
1115 err = X509_STORE_CTX_get_error(csc);
1116 skip:
1117 X509_STORE_CTX_free(csc);
1118 if (rc == 1)
1119 {
1120 status = TRUE;
1121 break;
1122 }
1123 else if (err != X509_V_ERR_INVALID_PURPOSE)
1124 break;
1125 }
1126
1127 X509_STORE_free(cert_ctx);
1128end:
1129 return status;
1130}
1131
1132char* x509_utils_bio_read(BIO* bio, size_t* plen)
1133{
1134 char* buffer = nullptr;
1135 WINPR_ASSERT(bio);
1136
1137 if (plen)
1138 *plen = 0;
1139
1140 BIO_flush(bio);
1141
1142 const UINT64 size = BIO_number_written(bio);
1143 if (size > INT_MAX)
1144 return nullptr;
1145
1146 buffer = calloc(1, (size_t)size + 1ull);
1147
1148 if (!buffer)
1149 return nullptr;
1150
1151 ERR_clear_error();
1152 const int rc = BIO_read(bio, buffer, (int)size);
1153 if (rc <= 0)
1154 goto fail;
1155
1156 if (plen)
1157 *plen = size;
1158 return buffer;
1159
1160fail:
1161 free(buffer);
1162 return nullptr;
1163}
1164
1165void x509_utils_ip_names_free(size_t count, size_t* lengths, char** dns_names)
1166{
1167 x509_utils_dns_names_free(count, lengths, dns_names);
1168}