Coverage Report

Created: 2024-05-20 06:11

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