forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenssl.c
More file actions
1517 lines (1249 loc) · 38.3 KB
/
Copy pathopenssl.c
File metadata and controls
1517 lines (1249 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_err.h"
#include "pal_types.h"
#include "pal_utilities.h"
#include "pal_safecrt.h"
#include "pal_x509.h"
#include "openssl.h"
#ifdef FEATURE_DISTRO_AGNOSTIC_SSL
#include "opensslshim.h"
#endif
#include <assert.h>
#include <limits.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_1_1_0_RTM
c_static_assert(CRYPTO_EX_INDEX_X509 == 3);
#else
c_static_assert(CRYPTO_EX_INDEX_X509 == 10);
#endif
// See X509NameType.SimpleName
#define NAME_TYPE_SIMPLE 0
// See X509NameType.EmailName
#define NAME_TYPE_EMAIL 1
// See X509NameType.UpnName
#define NAME_TYPE_UPN 2
// See X509NameType.DnsName
#define NAME_TYPE_DNS 3
// See X509NameType.DnsFromAlternateName
#define NAME_TYPE_DNSALT 4
// See X509NameType.UrlName
#define NAME_TYPE_URL 5
/*
Function:
MakeTimeT
Used to convert the constituent elements of a struct tm into a time_t. As time_t does not have
a guaranteed blitting size, this function is static and cannot be p/invoked. It is here merely
as a utility.
Return values:
A time_t representation of the input date. See also man mktime(3).
*/
static time_t
MakeTimeT(int32_t year, int32_t month, int32_t day, int32_t hour, int32_t minute, int32_t second, int32_t isDst)
{
struct tm currentTm;
currentTm.tm_year = year - 1900;
currentTm.tm_mon = month - 1;
currentTm.tm_mday = day;
currentTm.tm_hour = hour;
currentTm.tm_min = minute;
currentTm.tm_sec = second;
currentTm.tm_isdst = isDst;
return mktime(¤tTm);
}
/*
Function:
GetX509Thumbprint
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to copy the SHA1
digest of the certificate (the thumbprint) into a managed buffer.
Return values:
0: Invalid X509 pointer
1: Data was copied
Any negative value: The input buffer size was reported as insufficient. A buffer of size ABS(return) is required.
*/
int32_t CryptoNative_GetX509Thumbprint(X509* x509, uint8_t* pBuf, int32_t cBuf)
{
if (!x509)
{
return 0;
}
if (cBuf < SHA_DIGEST_LENGTH)
{
return -SHA_DIGEST_LENGTH;
}
ERR_clear_error();
if (!X509_digest(x509, EVP_sha1(), pBuf, NULL))
{
return 0;
}
return 1;
}
/*
Function:
GetX509NotBefore
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to identify the
beginning of the validity period of the certificate in question.
Return values:
NULL if the validity cannot be determined, a pointer to the ASN1_TIME structure for the NotBefore value
otherwise.
*/
const ASN1_TIME* CryptoNative_GetX509NotBefore(X509* x509)
{
// No error queue impact.
if (x509)
{
return X509_get0_notBefore(x509);
}
return NULL;
}
/*
Function:
GetX509NotAfter
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to identify the
end of the validity period of the certificate in question.
Return values:
NULL if the validity cannot be determined, a pointer to the ASN1_TIME structure for the NotAfter value
otherwise.
*/
const ASN1_TIME* CryptoNative_GetX509NotAfter(X509* x509)
{
// No error queue impact.
if (x509)
{
return X509_get0_notAfter(x509);
}
return NULL;
}
/*
Function:
GetX509CrlNextUpdate
Used by System.Security.Cryptography.X509Certificates' CrlCache to identify the
end of the validity period of the certificate revocation list in question.
Return values:
NULL if the validity cannot be determined, a pointer to the ASN1_TIME structure for the NextUpdate value
otherwise.
*/
const ASN1_TIME* CryptoNative_GetX509CrlNextUpdate(X509_CRL* crl)
{
// No error queue impact.
if (crl)
{
return X509_CRL_get0_nextUpdate(crl);
}
return NULL;
}
/*
Function:
GetX509Version
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to identify the
X509 data format version for this certificate.
Return values:
-1 if the value cannot be determined
The encoded value of the version, otherwise:
0: X509v1
1: X509v2
2: X509v3
*/
int32_t CryptoNative_GetX509Version(X509* x509)
{
// No errors are expected to be written to the queue on this call,
// and the managed caller doesn't check for one.
if (x509)
{
return (int32_t)X509_get_version(x509);
}
return -1;
}
/*
Function:
GetX509PublicKeyAlgorithm
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to identify the
algorithm the public key is associated with.
Return values:
NULL if the algorithm cannot be determined, otherwise a pointer to the OpenSSL ASN1_OBJECT structure
describing the object type.
*/
ASN1_OBJECT* CryptoNative_GetX509PublicKeyAlgorithm(X509* x509)
{
// No error queue impact, all of the called routines are just field accessors.
if (x509)
{
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
ASN1_OBJECT* algOid;
if (pubkey && X509_PUBKEY_get0_param(&algOid, NULL, NULL, NULL, pubkey))
{
return algOid;
}
}
return NULL;
}
/*
Function:
GetX509SignatureAlgorithm
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to identify the
algorithm used by the Certificate Authority for signing the certificate.
Return values:
NULL if the algorithm cannot be determined, otherwise a pointer to the OpenSSL ASN1_OBJECT structure
describing the object type.
*/
ASN1_OBJECT* CryptoNative_GetX509SignatureAlgorithm(X509* x509)
{
// No error queue impact.
if (x509)
{
const X509_ALGOR* sigAlg = X509_get0_tbs_sigalg(x509);
if (sigAlg)
{
return sigAlg->algorithm;
}
}
return NULL;
}
/*
Function:
GetX509PublicKeyParameterBytes
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to copy out the
parameters to the algorithm used by the certificate public key
Return values:
0: Invalid X509 pointer
1: Data was copied
Any negative value: The input buffer size was reported as insufficient. A buffer of size ABS(return) is required.
*/
int32_t CryptoNative_GetX509PublicKeyParameterBytes(X509* x509, uint8_t* pBuf, int32_t cBuf)
{
ERR_clear_error();
if (!x509)
{
return 0;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
if (!pubkey)
{
return 0;
}
X509_ALGOR* alg;
if (!X509_PUBKEY_get0_param(NULL, NULL, NULL, &alg, pubkey) || !alg)
{
return 0;
}
ASN1_TYPE* parameter = alg->parameter;
if (!parameter)
{
// If pBuf is NULL we're asking for the length, so return 0 (which is negative-zero)
// If pBuf is non-NULL we're asking to fill the data, in which case we return 1.
return pBuf != NULL;
}
int len = i2d_ASN1_TYPE(parameter, NULL);
if (cBuf < len)
{
return -len;
}
unsigned char* pBuf2 = pBuf;
len = i2d_ASN1_TYPE(parameter, &pBuf2);
if (len > 0)
{
return 1;
}
return 0;
}
/*
Function:
GetX509PublicKeyBytes
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to obtain the
raw bytes of the public key.
Return values:
NULL if the public key cannot be determined, a pointer to the ASN1_BIT_STRING structure representing
the public key.
*/
ASN1_BIT_STRING* CryptoNative_GetX509PublicKeyBytes(X509* x509)
{
// No error queue impact.
if (x509)
{
return X509_get0_pubkey_bitstr(x509);
}
return NULL;
}
/*
Function:
GetAsn1StringBytes
Used by the NativeCrypto shim type to extract byte[] data from OpenSSL ASN1_* types whenever a byte[] is called
for in managed code.
Return values:
0: Invalid X509 pointer
1: Data was copied
Any negative value: The input buffer size was reported as insufficient. A buffer of size ABS(return) is required.
Remarks:
Many ASN1 types are actually the same type in OpenSSL:
STRING
INTEGER
ENUMERATED
BIT_STRING
OCTET_STRING
PRINTABLESTRING
T61STRING
IA5STRING
GENERALSTRING
UNIVERSALSTRING
BMPSTRING
UTCTIME
TIME
GENERALIZEDTIME
VISIBLEStRING
UTF8STRING
So this function will really work on all of them.
*/
int32_t CryptoNative_GetAsn1StringBytes(ASN1_STRING* asn1, uint8_t* pBuf, int32_t cBuf)
{
// No error queue impact.
if (!asn1 || cBuf < 0)
{
return 0;
}
int length = asn1->length;
assert(length >= 0);
if (length < 0)
{
return 0;
}
if (!pBuf || cBuf < length)
{
return -length;
}
memcpy_s(pBuf, Int32ToSizeT(cBuf), asn1->data, Int32ToSizeT(length));
return 1;
}
/*
Function:
GetX509NameRawBytes
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader to obtain the
DER encoded value of an X500DistinguishedName.
Return values:
0: Invalid X509 pointer
1: Data was copied
Any negative value: The input buffer size was reported as insufficient. A buffer of size ABS(return) is required.
*/
int32_t CryptoNative_GetX509NameRawBytes(X509_NAME* x509Name, uint8_t* pBuf, int32_t cBuf)
{
ERR_clear_error();
const uint8_t* nameBuf;
size_t nameBufLen;
if (!x509Name || cBuf < 0 || !X509_NAME_get0_der(x509Name, &nameBuf, &nameBufLen))
{
return 0;
}
/*
* length is size_t on some platforms and int on others, so the comparisons
* are not tautological everywhere. We can let the compiler optimize away
* any part of the check that is. We split the size checks into two checks
* so we can get around the warnings on Linux where the Length is unsigned
* whereas Length is signed on OS X. The first check makes sure the variable
* value is less than INT_MAX in it's native format; once we know it is not
* too large, we can safely cast to an int to make sure it is not negative
*/
if (nameBufLen > INT_MAX)
{
assert(0 && "Huge length X509_NAME");
return 0;
}
int length = (int)(nameBufLen);
if (length < 0)
{
assert(0 && "Negative length X509_NAME");
return 0;
}
if (!pBuf || cBuf < length)
{
return -length;
}
memcpy_s(pBuf, Int32ToSizeT(cBuf), nameBuf, Int32ToSizeT(length));
return 1;
}
/*
Function:
GetX509EkuFieldCount
Used by System.Security.Cryptography.X509Certificates' OpenSslX509Encoder to identify the
number of Extended Key Usage OIDs present in the EXTENDED_KEY_USAGE structure.
Return values:
0 if the field count cannot be determined, or the count of OIDs present in the EKU.
Note that 0 does not always indicate an error, merely that GetX509EkuField should not be called.
*/
int32_t CryptoNative_GetX509EkuFieldCount(EXTENDED_KEY_USAGE* eku)
{
// No error queue impact.
return sk_ASN1_OBJECT_num(eku);
}
/*
Function:
GetX509EkuField
Used by System.Security.Cryptography.X509Certificates' OpenSslX509Encoder to get a pointer to the
ASN1_OBJECT structure which represents the OID in a particular spot in the EKU.
Return values:
NULL if eku is NULL or loc is out of bounds, otherwise a pointer to the ASN1_OBJECT structure encoding
that particular OID.
*/
ASN1_OBJECT* CryptoNative_GetX509EkuField(EXTENDED_KEY_USAGE* eku, int32_t loc)
{
// No error queue impact.
return sk_ASN1_OBJECT_value(eku, loc);
}
/*
Function:
GetX509NameInfo
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader as the entire
implementation of X509Certificate2.GetNameInfo.
Return values:
NULL if the certificate is invalid or no name information could be found, otherwise a pointer to a
memory-backed BIO structure which contains the answer to the GetNameInfo query
*/
BIO* CryptoNative_GetX509NameInfo(X509* x509, int32_t nameType, int32_t forIssuer)
{
static const char szOidUpn[] = "1.3.6.1.4.1.311.20.2.3";
ERR_clear_error();
if (!x509 || nameType < NAME_TYPE_SIMPLE || nameType > NAME_TYPE_URL)
{
return NULL;
}
// Algorithm behaviors (pseudocode). When forIssuer is true, replace "Subject" with "Issuer" and
// SAN (Subject Alternative Names) with IAN (Issuer Alternative Names).
//
// SimpleName: Subject[CN] ?? Subject[OU] ?? Subject[O] ?? Subject[E] ?? Subject.Rdns.FirstOrDefault() ??
// SAN.Entries.FirstOrDefault(type == GEN_EMAIL);
// EmailName: SAN.Entries.FirstOrDefault(type == GEN_EMAIL) ?? Subject[E];
// UpnName: SAN.Entries.FirsOrDefaultt(type == GEN_OTHER && entry.AsOther().OID == szOidUpn).AsOther().Value;
// DnsName: SAN.Entries.FirstOrDefault(type == GEN_DNS) ?? Subject[CN];
// DnsFromAlternativeName: SAN.Entries.FirstOrDefault(type == GEN_DNS);
// UrlName: SAN.Entries.FirstOrDefault(type == GEN_URI);
if (nameType == NAME_TYPE_SIMPLE)
{
X509_NAME* name = forIssuer ? X509_get_issuer_name(x509) : X509_get_subject_name(x509);
if (name)
{
ASN1_STRING* cn = NULL;
ASN1_STRING* ou = NULL;
ASN1_STRING* o = NULL;
ASN1_STRING* e = NULL;
ASN1_STRING* firstRdn = NULL;
// Walk the list backwards because it is stored in stack order
for (int i = X509_NAME_entry_count(name) - 1; i >= 0; --i)
{
X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, i);
if (!entry)
{
continue;
}
ASN1_OBJECT* oid = X509_NAME_ENTRY_get_object(entry);
ASN1_STRING* str = X509_NAME_ENTRY_get_data(entry);
if (!oid || !str)
{
continue;
}
int nid = OBJ_obj2nid(oid);
if (nid == NID_commonName)
{
// CN wins, so no need to keep looking.
cn = str;
break;
}
else if (nid == NID_organizationalUnitName)
{
ou = str;
}
else if (nid == NID_organizationName)
{
o = str;
}
else if (nid == NID_pkcs9_emailAddress)
{
e = str;
}
else if (!firstRdn)
{
firstRdn = str;
}
}
ASN1_STRING* answer = cn;
// If there was no CN, but there was something, then perform fallbacks.
if (!answer && firstRdn)
{
answer = ou;
if (!answer)
{
answer = o;
}
if (!answer)
{
answer = e;
}
if (!answer)
{
answer = firstRdn;
}
}
if (answer)
{
BIO* b = BIO_new(BIO_s_mem());
ASN1_STRING_print_ex(b, answer, ASN1_STRFLGS_UTF8_CONVERT);
return b;
}
}
}
if (nameType == NAME_TYPE_SIMPLE || nameType == NAME_TYPE_DNS || nameType == NAME_TYPE_DNSALT ||
nameType == NAME_TYPE_EMAIL || nameType == NAME_TYPE_UPN || nameType == NAME_TYPE_URL)
{
int expectedType = -1;
switch (nameType)
{
case NAME_TYPE_DNS:
case NAME_TYPE_DNSALT:
expectedType = GEN_DNS;
break;
case NAME_TYPE_SIMPLE:
case NAME_TYPE_EMAIL:
expectedType = GEN_EMAIL;
break;
case NAME_TYPE_UPN:
expectedType = GEN_OTHERNAME;
break;
case NAME_TYPE_URL:
expectedType = GEN_URI;
break;
}
STACK_OF(GENERAL_NAME)* altNames = (STACK_OF(GENERAL_NAME)*)(
X509_get_ext_d2i(x509, forIssuer ? NID_issuer_alt_name : NID_subject_alt_name, NULL, NULL));
if (altNames)
{
int i;
for (i = 0; i < sk_GENERAL_NAME_num(altNames); ++i)
{
GENERAL_NAME* altName = sk_GENERAL_NAME_value(altNames, i);
if (altName && altName->type == expectedType)
{
ASN1_STRING* str = NULL;
switch (nameType)
{
case NAME_TYPE_DNS:
case NAME_TYPE_DNSALT:
str = altName->d.dNSName;
break;
case NAME_TYPE_SIMPLE:
case NAME_TYPE_EMAIL:
str = altName->d.rfc822Name;
break;
case NAME_TYPE_URL:
str = altName->d.uniformResourceIdentifier;
break;
case NAME_TYPE_UPN:
{
OTHERNAME* value = altName->d.otherName;
if (value)
{
// Enough more padding than szOidUpn that a \0 won't accidentally align
char localOid[sizeof(szOidUpn) + 3];
int cchLocalOid = 1 + OBJ_obj2txt(localOid, sizeof(localOid), value->type_id, 1);
if (sizeof(szOidUpn) == cchLocalOid &&
0 == strncmp(localOid, szOidUpn, sizeof(szOidUpn)))
{
// OTHERNAME->ASN1_TYPE->union.field
if (!value->value)
{
return NULL;
}
str = value->value->value.asn1_string;
}
}
break;
}
}
if (str)
{
BIO* b = BIO_new(BIO_s_mem());
ASN1_STRING_print_ex(b, str, ASN1_STRFLGS_UTF8_CONVERT);
sk_GENERAL_NAME_free(altNames);
return b;
}
}
}
sk_GENERAL_NAME_free(altNames);
}
}
if (nameType == NAME_TYPE_EMAIL || nameType == NAME_TYPE_DNS)
{
X509_NAME* name = forIssuer ? X509_get_issuer_name(x509) : X509_get_subject_name(x509);
int expectedNid = NID_undef;
switch (nameType)
{
case NAME_TYPE_EMAIL:
expectedNid = NID_pkcs9_emailAddress;
break;
case NAME_TYPE_DNS:
expectedNid = NID_commonName;
break;
}
if (name)
{
// Walk the list backwards because it is stored in stack order
for (int i = X509_NAME_entry_count(name) - 1; i >= 0; --i)
{
X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, i);
if (!entry)
{
continue;
}
ASN1_OBJECT* oid = X509_NAME_ENTRY_get_object(entry);
ASN1_STRING* str = X509_NAME_ENTRY_get_data(entry);
if (!oid || !str)
{
continue;
}
int nid = OBJ_obj2nid(oid);
if (nid == expectedNid)
{
BIO* b = BIO_new(BIO_s_mem());
ASN1_STRING_print_ex(b, str, 0);
return b;
}
}
}
}
return NULL;
}
/*
Function:
CheckX509Hostname
Used by System.Net.Security's Unix CertModule to identify if the certificate presented by
the server is applicable to the hostname requested.
Return values:
1 if the hostname is a match
0 if the hostname is not a match
Any negative number indicates an error in the arguments.
*/
int32_t CryptoNative_CheckX509Hostname(X509* x509, const char* hostname, int32_t cchHostname)
{
// Input errors. OpenSSL might return -1 or -2, so skip those.
if (!x509)
return -3;
if (cchHostname > 0 && !hostname)
return -4;
if (cchHostname < 0)
return -5;
ERR_clear_error();
// OpenSSL will treat a target hostname starting with '.' as special.
// We don't expect target hostnames to start with '.', but if one gets in here, the fallback
// and the mainline won't be the same... so just make it report false.
if (cchHostname > 0 && hostname[0] == '.')
{
return 0;
}
return X509_check_host(
x509,
hostname,
(size_t)cchHostname,
X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS,
NULL);
}
/*
Function:
CheckX509IpAddress
Used by System.Net.Security's Unix CertModule to identify if the certificate presented by
the server is applicable to the hostname (an IP address) requested.
Return values:
1 if the hostname is a match
0 if the hostname is not a match
Any negative number indicates an error in the arguments.
*/
int32_t CryptoNative_CheckX509IpAddress(
X509* x509, const uint8_t* addressBytes, int32_t addressBytesLen, const char* hostname, int32_t cchHostname)
{
if (!x509)
return -2;
if (cchHostname > 0 && !hostname)
return -3;
if (cchHostname < 0)
return -4;
if (addressBytesLen < 0)
return -5;
if (!addressBytes)
return -6;
ERR_clear_error();
int subjectNid = NID_commonName;
int sanGenType = GEN_IPADD;
GENERAL_NAMES* san = (GENERAL_NAMES*)(X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL));
int success = 0;
if (san)
{
int i;
int count = sk_GENERAL_NAME_num(san);
for (i = 0; i < count; ++i)
{
GENERAL_NAME* sanEntry = sk_GENERAL_NAME_value(san, i);
ASN1_OCTET_STRING* ipAddr;
if (sanEntry->type != sanGenType)
{
continue;
}
ipAddr = sanEntry->d.iPAddress;
if (!ipAddr || !ipAddr->data || ipAddr->length != addressBytesLen)
{
continue;
}
if (!memcmp(addressBytes, ipAddr->data, (size_t)addressBytesLen))
{
success = 1;
break;
}
}
GENERAL_NAMES_free(san);
}
if (!success)
{
// This is a shared/interor pointer, do not free!
X509_NAME* subject = X509_get_subject_name(x509);
if (subject)
{
int i = -1;
while ((i = X509_NAME_get_index_by_NID(subject, subjectNid, i)) >= 0)
{
// Shared/interior pointers, do not free!
X509_NAME_ENTRY* nameEnt = X509_NAME_get_entry(subject, i);
ASN1_STRING* cn = X509_NAME_ENTRY_get_data(nameEnt);
if (cn->length == cchHostname &&
!strncasecmp((const char*)cn->data, hostname, (size_t)cchHostname))
{
success = 1;
break;
}
}
}
}
return success;
}
/*
Function:
GetX509StackFieldCount
Used by System.Security.Cryptography.X509Certificates' OpenSslX509ChainProcessor to identify the
number of certificates returned in the built chain.
Return values:
0 if the field count cannot be determined, or the count of certificates in STACK_OF(X509)
Note that 0 does not always indicate an error, merely that GetX509StackField should not be called.
*/
int32_t CryptoNative_GetX509StackFieldCount(STACK_OF(X509) * stack)
{
// No error queue impact.
return sk_X509_num(stack);
}
/*
Function:
GetX509StackField
Used by System.Security.Cryptography.X509Certificates' OpenSslX509ChainProcessor to get a pointer to
the indexed member of a chain.
Return values:
NULL if stack is NULL or loc is out of bounds, otherwise a pointer to the X509 structure encoding
that particular element.
*/
X509* CryptoNative_GetX509StackField(STACK_OF(X509) * stack, int loc)
{
// No error queue impact.
return sk_X509_value(stack, loc);
}
/*
Function:
RecursiveFreeX509Stack
Used by System.Security.Cryptography.X509Certificates' OpenSslX509ChainProcessor to free a stack
when done with it.
*/
void CryptoNative_RecursiveFreeX509Stack(STACK_OF(X509) * stack)
{
// No error queue impact.
sk_X509_pop_free(stack, X509_free);
}
/*
Function:
SetX509StoreVerifyTime
Used by System.Security.Cryptography.X509Certificates' OpenSslX509ChainProcessor to assign the
verification time to the chain building. The input is in LOCAL time, not UTC.
Return values:
0 if ctx is NULL, if ctx has no X509_VERIFY_PARAM, or the date inputs don't produce a valid time_t;
1 on success.
*/
int32_t CryptoNative_X509StoreSetVerifyTime(X509_STORE* ctx,
int32_t year,
int32_t month,
int32_t day,
int32_t hour,
int32_t minute,
int32_t second,
int32_t isDst)
{
ERR_clear_error();
if (!ctx)
{
return 0;
}
time_t verifyTime = MakeTimeT(year, month, day, hour, minute, second, isDst);
if (verifyTime == (time_t)-1)
{
return 0;
}
X509_VERIFY_PARAM* verifyParams = X509_STORE_get0_param(ctx);
if (!verifyParams)
{
return 0;
}
X509_VERIFY_PARAM_set_time(verifyParams, verifyTime);
return 1;
}
/*
Function:
ReadX509AsDerFromBio
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader when attempting
to turn the contents of a file into an ICertificatePal object.
Return values:
If bio contains a valid DER-encoded X509 object, a pointer to that X509 structure that was deserialized,
otherwise NULL.
*/
X509* CryptoNative_ReadX509AsDerFromBio(BIO* bio)
{
ERR_clear_error();
return d2i_X509_bio(bio, NULL);
}
/*
Function:
BioTell
Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader when attempting
to turn the contents of a file into an ICertificatePal object to allow seeking back to the start point
in the event of a deserialization failure.
Return values:
The current seek position of the BIO if it is a file-related BIO, -1 on NULL inputs, and has unspecified
behavior on non-file, non-null BIO objects.