forked from microsoft/winget-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCertificates.cpp
More file actions
870 lines (726 loc) · 30.7 KB
/
Copy pathCertificates.cpp
File metadata and controls
870 lines (726 loc) · 30.7 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "winget/Certificates.h"
#include "AppInstallerDateTime.h"
#include "AppInstallerLogging.h"
#include "AppInstallerStrings.h"
#include "winget/JsonUtil.h"
#include "winget/Resources.h"
namespace AppInstaller::Certificates
{
namespace
{
// WTHelperProvDataFromStateData and WTHelperGetProvSignerFromChain are not in the wintrust import lib;
// resolve them at runtime via GetProcAddress.
using WTHelperProvDataFromStateDataPtr = decltype(&WTHelperProvDataFromStateData);
using WTHelperGetProvSignerFromChainPtr = decltype(&WTHelperGetProvSignerFromChain);
struct WinTrustHelpers
{
WinTrustHelpers()
{
m_module.reset(LoadLibraryExW(L"wintrust.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32));
if (!m_module)
{
AICLI_LOG(Core, Warning, << "Could not load wintrust.dll");
return;
}
m_provDataFromStateData = reinterpret_cast<WTHelperProvDataFromStateDataPtr>(
GetProcAddress(m_module.get(), "WTHelperProvDataFromStateData"));
if (!m_provDataFromStateData)
{
AICLI_LOG(Core, Warning, << "Could not get proc address of WTHelperProvDataFromStateData");
}
m_provSignerFromChain = reinterpret_cast<WTHelperGetProvSignerFromChainPtr>(
GetProcAddress(m_module.get(), "WTHelperGetProvSignerFromChain"));
if (!m_provSignerFromChain)
{
AICLI_LOG(Core, Warning, << "Could not get proc address of WTHelperGetProvSignerFromChain");
}
}
CRYPT_PROVIDER_DATA* ProvDataFromStateData(HANDLE stateData) const
{
return m_provDataFromStateData ? m_provDataFromStateData(stateData) : nullptr;
}
CRYPT_PROVIDER_SGNR* ProvSignerFromChain(CRYPT_PROVIDER_DATA* provData, DWORD signerIdx, BOOL counterSigner, DWORD counterSignerIdx) const
{
return m_provSignerFromChain ? m_provSignerFromChain(provData, signerIdx, counterSigner, counterSignerIdx) : nullptr;
}
private:
wil::unique_hmodule m_module;
WTHelperProvDataFromStateDataPtr m_provDataFromStateData = nullptr;
WTHelperGetProvSignerFromChainPtr m_provSignerFromChain = nullptr;
};
const WinTrustHelpers& GetWinTrustHelpers()
{
static WinTrustHelpers s_helpers;
return s_helpers;
}
std::string GetNameString(PCCERT_CONTEXT certContext, DWORD nameType, bool forIssuer, void* typeParam = nullptr)
{
if (!certContext)
{
return "<no certificate loaded>";
}
DWORD flags = forIssuer ? CERT_NAME_ISSUER_FLAG : 0;
DWORD characterCount = CertGetNameStringW(certContext, nameType, flags, typeParam, nullptr, 0);
std::wstring result(characterCount, L'\0');
characterCount = CertGetNameStringW(certContext, nameType, flags, typeParam, &result[0], characterCount);
if (static_cast<size_t>(characterCount) == result.size())
{
return Utility::ConvertToUTF8(static_cast<std::wstring_view>(result).substr(0, result.size() - 1));
}
else
{
return "<unknown>";
}
}
std::string GetSimpleDisplayName(PCCERT_CONTEXT certContext, bool forIssuer = false)
{
return GetNameString(certContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, forIssuer);
}
std::string GetX500Name(PCCERT_CONTEXT certContext, bool forIssuer = false)
{
DWORD stringType = CERT_X500_NAME_STR;
return GetNameString(certContext, CERT_NAME_RDN_TYPE, forIssuer, &stringType);
}
std::string GetCommonName(PCCERT_CONTEXT certContext, bool forIssuer = false)
{
std::string commonName = szOID_COMMON_NAME;
return GetNameString(certContext, CERT_NAME_ATTR_TYPE, forIssuer, &commonName[0]);
}
std::string GetDescriptionOfCertChain(PCCERT_CHAIN_CONTEXT chainContext)
{
PCCERT_SIMPLE_CHAIN chain = chainContext->rgpChain[0];
std::ostringstream stream;
std::string indent;
for (DWORD i = 0; i < chain->cElement; ++i)
{
PCCERT_CHAIN_ELEMENT element = chain->rgpElement[(chain->cElement - 1) - i];
if (!indent.empty())
{
stream << std::endl;
}
stream << indent;
stream << GetSimpleDisplayName(element->pCertContext);
indent.append(" ");
}
return std::move(stream).str();
}
std::optional<PinningVerificationType> GetTypeFromString(std::string_view value)
{
std::string lowerValue = Utility::ToLower(value);
if (lowerValue == "none")
{
return PinningVerificationType::None;
}
else if (lowerValue == "publickey")
{
return PinningVerificationType::PublicKey;
}
else if (lowerValue == "subject")
{
return PinningVerificationType::Subject;
}
else if (lowerValue == "issuer")
{
return PinningVerificationType::Issuer;
}
else if (lowerValue == "anyissuer")
{
return PinningVerificationType::AnyIssuer;
}
else if (lowerValue == "requirenonleaf")
{
return PinningVerificationType::RequireNonLeaf;
}
return {};
}
CertificateChainPosition GetCertificateChainPosition(DWORD index, DWORD count)
{
THROW_HR_IF(E_INVALIDARG, count == 0);
CertificateChainPosition position = CertificateChainPosition::Unknown;
if (index == 0)
{
position |= CertificateChainPosition::Root;
}
if (index > 0 && index < (count - 1))
{
position |= CertificateChainPosition::Intermediate;
}
if (index == (count - 1))
{
position |= CertificateChainPosition::Leaf;
}
return position;
}
}
std::ostream& operator<<(std::ostream& out, PinningVerificationType value)
{
if (value == PinningVerificationType::None)
{
out << "None";
}
else
{
bool prepend = false;
for (const auto& flag : std::initializer_list<std::pair<PinningVerificationType, std::string_view>>{
{ PinningVerificationType::PublicKey, "PublicKey" },
{ PinningVerificationType::Subject, "Subject" },
{ PinningVerificationType::Issuer, "Issuer" },
{ PinningVerificationType::AnyIssuer, "AnyIssuer" },
{ PinningVerificationType::RequireNonLeaf, "RequireNonLeaf" },
})
{
if (WI_IsAnyFlagSet(value, flag.first))
{
if (prepend)
{
out << " | ";
}
out << flag.second;
prepend = true;
}
}
}
return out;
}
std::ostream& operator<<(std::ostream& out, CertificateChainPosition value)
{
if (value == CertificateChainPosition::Unknown)
{
out << "Unknown";
}
else
{
bool prepend = false;
for (const auto& flag : std::initializer_list<std::pair<CertificateChainPosition, std::string_view>>{
{ CertificateChainPosition::Root, "Root" },
{ CertificateChainPosition::Intermediate, "Intermediate" },
{ CertificateChainPosition::Leaf, "Leaf" },
})
{
if (WI_IsAnyFlagSet(value, flag.first))
{
if (prepend)
{
out << " | ";
}
out << flag.second;
prepend = true;
}
}
}
return out;
}
PinningDetails& PinningDetails::LoadCertificate(int resource, int resourceType)
{
return LoadCertificate(Resource::GetResourceAsBytes(resource, resourceType));
}
PinningDetails& PinningDetails::LoadCertificate(const std::vector<BYTE>& certificateBytes)
{
return LoadCertificate(std::make_pair(&certificateBytes[0], certificateBytes.size()));
}
PinningDetails& PinningDetails::LoadCertificate(const std::pair<const BYTE*, size_t> certificateBytes)
{
m_certificateContext.reset(CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, certificateBytes.first, static_cast<DWORD>(certificateBytes.second)));
THROW_LAST_ERROR_IF(!m_certificateContext);
return *this;
}
PinningDetails& PinningDetails::SetPinning(PinningVerificationType type)
{
m_pinning = type;
return *this;
}
// The JSON is expected to look like:
// {
// "Validation":["publickey"],
// "EmbeddedCertificate":"<Hexadecimal string data for certificate>"
// }
bool PinningDetails::LoadFrom(const Json::Value& configuration)
{
const std::string validationName = "Validation";
if (!configuration.isMember(validationName))
{
AICLI_LOG(Core, Warning, << "Details JSON item has no member " << validationName);
return false;
}
auto validationValue = JSON::GetValue<std::vector<std::string>>(configuration[validationName]);
if (!validationValue)
{
AICLI_LOG(Core, Warning, << "Details JSON item member " << validationName << " was not an array of strings");
return false;
}
for (const std::string& singleValidation : validationValue.value())
{
auto validationType = GetTypeFromString(singleValidation);
if (!validationType)
{
AICLI_LOG(Core, Warning, << "Details JSON validation is unknown: " << singleValidation);
return false;
}
m_pinning |= validationType.value();
}
if (m_pinning == PinningVerificationType::None)
{
// No need to load a certificate if not doing any pinning
return true;
}
const std::string embeddedCertificateName = "EmbeddedCertificate";
if (!configuration.isMember(embeddedCertificateName))
{
AICLI_LOG(Core, Warning, << "Details JSON item has no member " << embeddedCertificateName);
return false;
}
auto embeddedCertificateValue = JSON::GetValue<std::string>(configuration[embeddedCertificateName]);
if (!validationValue)
{
AICLI_LOG(Core, Warning, << "Details JSON item member " << embeddedCertificateName << " was not a string");
return false;
}
auto embeddedCertificateBytes = Utility::ParseFromHexString(embeddedCertificateValue.value());
LoadCertificate(embeddedCertificateBytes);
return true;
}
CertificatePinningValidationResult PinningDetails::Validate(PCCERT_CONTEXT certContext, CertificateChainPosition position) const
{
CertificatePinningValidationResult failResult = WI_IsFlagSet(m_pinning, PinningVerificationType::AnyIssuer) ? CertificatePinningValidationResult::Skipped : CertificatePinningValidationResult::Rejected;
if (WI_IsFlagSet(m_pinning, PinningVerificationType::RequireNonLeaf) &&
WI_IsFlagSet(position, CertificateChainPosition::Leaf))
{
AICLI_LOG(Core, Verbose, << "Required non-leaf mismatch: Expected certificate [" << GetSimpleDisplayName(m_certificateContext.get()) << "], Actual certificate [" << GetSimpleDisplayName(certContext) << "] was " << position);
return CertificatePinningValidationResult::Rejected;
}
if (WI_IsFlagSet(m_pinning, PinningVerificationType::PublicKey))
{
THROW_HR_IF(E_NOT_VALID_STATE, !m_certificateContext);
if (!CertComparePublicKeyInfo(
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
&m_certificateContext.get()->pCertInfo->SubjectPublicKeyInfo,
&certContext->pCertInfo->SubjectPublicKeyInfo))
{
AICLI_LOG(Core, Verbose, << "Public key mismatch: Expected certificate [" << GetSimpleDisplayName(m_certificateContext.get()) << "], Actual certificate [" << GetSimpleDisplayName(certContext) << "]");
return failResult;
}
}
if (WI_IsFlagSet(m_pinning, PinningVerificationType::Subject))
{
THROW_HR_IF(E_NOT_VALID_STATE, !m_certificateContext);
if (!CertCompareCertificateName(
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
&m_certificateContext.get()->pCertInfo->Subject,
&certContext->pCertInfo->Subject))
{
AICLI_LOG(Core, Verbose, << "Subject mismatch: Expected certificate [" << GetSimpleDisplayName(m_certificateContext.get()) << "], Actual certificate [" << GetSimpleDisplayName(certContext) << "]");
return failResult;
}
}
if (WI_IsFlagSet(m_pinning, PinningVerificationType::Issuer))
{
THROW_HR_IF(E_NOT_VALID_STATE, !m_certificateContext);
if (!CertCompareCertificateName(
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
&m_certificateContext.get()->pCertInfo->Issuer,
&certContext->pCertInfo->Issuer))
{
AICLI_LOG(Core, Verbose, << "Issuer mismatch: Expected certificate [" << GetSimpleDisplayName(m_certificateContext.get()) << "], Actual certificate [" << GetSimpleDisplayName(certContext) << "]");
return failResult;
}
}
#ifndef AICLI_DISABLE_TEST_HOOKS
if (m_customValidation)
{
if (!m_customValidation(*this, certContext, position))
{
AICLI_LOG(Core, Verbose, << "Custom validation returned false: Expected certificate [" << GetSimpleDisplayName(m_certificateContext.get()) << "], Actual certificate [" << GetSimpleDisplayName(certContext) << "]");
return failResult;
}
}
#endif
return CertificatePinningValidationResult::Accepted;
}
void PinningDetails::OutputDescription(std::ostream& stream, std::string_view indent) const
{
stream << indent << GetSimpleDisplayName(m_certificateContext.get()) << " : " << m_pinning;
}
double PinningDetails::GetRemainingLifetimePercentage() const
{
THROW_HR_IF(E_NOT_VALID_STATE, !m_certificateContext);
auto notBefore = Utility::ConvertFiletimeToSystemClock(m_certificateContext.get()->pCertInfo->NotBefore);
auto notAfter = Utility::ConvertFiletimeToSystemClock(m_certificateContext.get()->pCertInfo->NotAfter);
THROW_HR_IF(E_NOT_VALID_STATE, notBefore > notAfter);
auto now = std::chrono::system_clock::now();
if (now < notBefore)
{
return 1.0;
}
else if (now > notAfter)
{
return 0.0;
}
auto totalTime = notAfter - notBefore;
auto remainingTime = notAfter - now;
return static_cast<double>(remainingTime.count()) / static_cast<double>(totalTime.count());
}
PinningChain::Node PinningChain::Node::Next()
{
if (!HasNext())
{
m_chain.get().emplace_back();
}
return { m_chain, m_index + 1 };
}
const PinningChain::Node PinningChain::Node::Next() const
{
THROW_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), !HasNext());
return { m_chain, m_index + 1 };
}
void PinningChain::Node::RemoveNext()
{
m_chain.get().erase(m_chain.get().begin() + m_index + 1, m_chain.get().end());
}
bool PinningChain::Node::HasNext() const
{
return (m_index + 1 < m_chain.get().size());
}
PinningChain::Node::Node(std::vector<PinningDetails>& chain, size_t index) :
m_chain(chain), m_index(index) {}
PinningChain::Node PinningChain::Root()
{
if (m_chain.empty())
{
m_chain.emplace_back();
}
return { m_chain, 0 };
}
const PinningChain::Node PinningChain::Root() const
{
THROW_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), m_chain.empty());
return { const_cast<std::vector<PinningDetails>&>(m_chain), 0 };
}
PinningChain& PinningChain::PartialChain(bool isPartial)
{
m_partial = isPartial;
return *this;
}
bool PinningChain::Validate(PCCERT_CHAIN_CONTEXT chainContext) const
{
if (m_chain.empty())
{
// An empty chain rejects all inputs.
AICLI_LOG(Core, Warning, << "Empty pinning chain blindly rejecting chain context");
return false;
}
THROW_HR_IF(E_INVALIDARG, chainContext->cChain == 0);
// Currently don't support chains bridged with CTLs; there must be only one simple chain that terminates in a trusted root.
if (chainContext->cChain > 1)
{
AICLI_LOG(Core, Verbose, << "Rejecting chain context with multiple chains");
return false;
}
PCCERT_SIMPLE_CHAIN chain = chainContext->rgpChain[0];
if (chain->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR)
{
AICLI_LOG(Core, Verbose, << "Rejecting simple chain context with bad TrustStatus: " << chain->TrustStatus.dwErrorStatus << " [" << chain->TrustStatus.dwInfoStatus << "]");
return false;
}
if (chain->pTrustListInfo)
{
// This should not happen as the only reason for pTrustListInfo to be set is when `chainContext->cChain > 1`, which is rejected above
AICLI_LOG(Core, Verbose, << "Rejecting simple chain context with CTL info");
return false;
}
if (!m_partial && static_cast<size_t>(chain->cElement) != m_chain.size())
{
AICLI_LOG(Core, Verbose, << "Rejecting simple chain context based on size: expected " << m_chain.size() << ", got " << chain->cElement);
return false;
}
size_t currentDetailsIndex = 0;
for (DWORD i = 0; i < chain->cElement; ++i)
{
PCCERT_CHAIN_ELEMENT element = chain->rgpElement[(chain->cElement - 1) - i];
if (element->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR)
{
AICLI_LOG(Core, Verbose, << "Rejecting chain element with bad TrustStatus: " << element->TrustStatus.dwErrorStatus << " [" << element->TrustStatus.dwInfoStatus << "]");
return false;
}
CertificatePinningValidationResult result = m_chain[currentDetailsIndex].Validate(element->pCertContext, GetCertificateChainPosition(i, chain->cElement));
if (result == CertificatePinningValidationResult::Rejected)
{
return false;
}
else if (result == CertificatePinningValidationResult::Accepted)
{
++currentDetailsIndex;
}
else
{
THROW_HR_IF(E_UNEXPECTED, !m_partial || result != CertificatePinningValidationResult::Skipped);
AICLI_LOG(Core, Verbose, << "Skipping [" << GetSimpleDisplayName(element->pCertContext) << "] in partial chain validation.");
}
if (m_partial && m_chain.size() == currentDetailsIndex)
{
break;
}
}
// Ensure that all chain elements have been accepted
return m_chain.size() == currentDetailsIndex;
}
std::string PinningChain::GetDescription() const
{
if (m_chain.empty())
{
return "<empty>";
}
std::ostringstream stream;
std::string indent;
for (const PinningDetails& details : m_chain)
{
if (!indent.empty())
{
stream << std::endl;
}
else if (m_partial)
{
stream << "[Partial Chain Validation]" << std::endl;
}
details.OutputDescription(stream, indent);
indent.append(" ");
}
return std::move(stream).str();
}
// The JSON is expected to look like:
// {
// "Chain":[
// { <See PinningDetails::LoadFrom>
// "Validation":["publickey"],
// "EmbeddedCertificate":"<Hexadecimal string data for certificate>"
// },
// {
// "Validation":["subject","issuer"],
// "EmbeddedCertificate":"<Hexadecimal string data for certificate>"
// },
// ...
// ]
// }
bool PinningChain::LoadFrom(const Json::Value& configuration)
{
const std::string chainName = "Chain";
if (!configuration.isMember(chainName))
{
AICLI_LOG(Core, Warning, << "Chains JSON item has no member " << chainName);
return false;
}
const auto& chain = configuration[chainName];
if (!chain.isArray())
{
AICLI_LOG(Core, Warning, << "Chain JSON input is not an array");
return false;
}
for (const auto& configItem : chain)
{
PinningDetails details;
if (!details.LoadFrom(configItem))
{
return false;
}
m_chain.emplace_back(std::move(details));
}
return true;
}
double PinningChain::GetRemainingLifetimePercentage() const
{
double result = 1.0;
for (const auto& details : m_chain)
{
result = std::min(result, details.GetRemainingLifetimePercentage());
}
return result;
}
CallbackPinningChainValidation::CallbackPinningChainValidation(std::function<bool(PCCERT_CONTEXT)> callback)
: m_callback(std::move(callback))
{
}
bool CallbackPinningChainValidation::Validate(PCCERT_CHAIN_CONTEXT chainContext) const
{
THROW_HR_IF(E_INVALIDARG, !chainContext || chainContext->cChain == 0);
PCCERT_SIMPLE_CHAIN simpleChain = chainContext->rgpChain[0];
THROW_HR_IF(E_INVALIDARG, !simpleChain || simpleChain->cElement == 0);
PCCERT_CHAIN_ELEMENT leafElement = simpleChain->rgpElement[0];
THROW_HR_IF(E_INVALIDARG, !leafElement || !leafElement->pCertContext);
return m_callback(leafElement->pCertContext);
}
std::string CallbackPinningChainValidation::GetDescription() const
{
return "<callback validation>";
}
PinningConfiguration::PinningConfiguration(std::string identifier) : m_identifier(identifier)
{
if (m_identifier.empty())
{
GUID guid;
LOG_IF_FAILED(CoCreateGuid(&guid));
wchar_t identifierBuffer[256] = {};
(void)StringFromGUID2(guid, identifierBuffer, ARRAYSIZE(identifierBuffer));
m_identifier = Utility::ConvertToUTF8(identifierBuffer);
}
}
void PinningConfiguration::AddChain(PinningChain chain)
{
AddChain(std::make_shared<PinningChain>(std::move(chain)));
}
void PinningConfiguration::AddChain(std::shared_ptr<IPinningChainValidation> chain)
{
AICLI_LOG(Core, Verbose, << "Adding chain to pinning configuration [" << m_identifier << "]:\n" << chain->GetDescription());
m_configuration.emplace_back(std::move(chain));
}
bool PinningConfiguration::Validate(PCCERT_CONTEXT certContext) const
{
if (m_configuration.empty())
{
// No pinning configured
return true;
}
const BYTE* encodedBegin = certContext->pbCertEncoded;
const BYTE* encodedEnd = encodedBegin + certContext->cbCertEncoded;
if (certContext->cbCertEncoded == m_cachedCertificate.size() &&
std::equal(encodedBegin, encodedEnd, m_cachedCertificate.begin()))
{
// We have seen this certificate and deemed it valid already.
return true;
}
// Get the chain for the given leaf certificate
wil::unique_cert_chain_context chainContext;
char oidPkixKpServerAuth[] = szOID_PKIX_KP_SERVER_AUTH;
std::array<char*, 1> chainUses = {
oidPkixKpServerAuth,
};
CERT_CHAIN_PARA chainParameters = {};
chainParameters.cbSize = sizeof(chainParameters);
chainParameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
chainParameters.RequestedUsage.Usage.cUsageIdentifier = static_cast<DWORD>(chainUses.size());
chainParameters.RequestedUsage.Usage.rgpszUsageIdentifier = chainUses.data();
THROW_IF_WIN32_BOOL_FALSE(CertGetCertificateChain(nullptr, certContext, nullptr, certContext->hCertStore, &chainParameters, CERT_CHAIN_REVOCATION_CHECK_CHAIN, nullptr, &chainContext));
bool result = false;
for (const auto& chain : m_configuration)
{
if (chain->Validate(chainContext.get()))
{
AICLI_LOG(Core, Verbose, << "Certificate `" << GetSimpleDisplayName(certContext) << "` accepted by pinning configuration:\n" << chain->GetDescription());
result = true;
break;
}
}
if (result)
{
// Only cache a successful validation.
m_cachedCertificate.assign(encodedBegin, encodedEnd);
}
else
{
AICLI_LOG(Core, Error, << "Rejecting certificate [" << GetSimpleDisplayName(certContext) << "] as it did not match anything in pinning configuration [" << m_identifier << "]:\n" << GetDescriptionOfCertChain(chainContext.get()));
}
return result;
}
// The JSON is expected to look like:
// {
// "Chains":[
// { <See PinningChain::LoadFrom>
// "Chain":[
// { <See PinningDetails::LoadFrom>
// "Validation":["publickey"],
// "EmbeddedCertificate":"<Hexadecimal string data for certificate>"
// },
// {
// "Validation":["subject","issuer"],
// "EmbeddedCertificate":"<Hexadecimal string data for certificate>"
// },
// ...
// ]
// }
// ]
// }
bool PinningConfiguration::LoadFrom(const Json::Value& configuration)
{
const std::string chainsName = "Chains";
if (!configuration.isMember(chainsName))
{
AICLI_LOG(Core, Warning, << "PinningConfiguration JSON item has no member " << chainsName);
return false;
}
const auto& chains = configuration[chainsName];
if (!chains.isArray())
{
AICLI_LOG(Core, Warning, << "PinningConfiguration.Chains is not an array");
return false;
}
std::vector<PinningChain> resultCache;
for (const auto& configItem : chains)
{
PinningChain chain;
if (!chain.LoadFrom(configItem))
{
return false;
}
resultCache.emplace_back(std::move(chain));
}
// Move all chains into the config now that we have succeeded
for (auto& result : resultCache)
{
AddChain(std::move(result));
}
return true;
}
double PinningConfiguration::GetRemainingLifetimePercentage() const
{
double result = 0.0;
for (const auto& chain : m_configuration)
{
result = std::max(result, chain->GetRemainingLifetimePercentage());
}
return result;
}
std::string GetAuthenticodeSubject(const std::filesystem::path& filePath)
{
const std::wstring& pathStr = filePath.wstring();
WINTRUST_FILE_INFO fileInfo = {};
fileInfo.cbStruct = sizeof(fileInfo);
fileInfo.pcwszFilePath = pathStr.c_str();
WINTRUST_DATA trustData = {};
trustData.cbStruct = sizeof(trustData);
trustData.dwUIChoice = WTD_UI_NONE;
trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
trustData.dwUnionChoice = WTD_CHOICE_FILE;
trustData.dwStateAction = WTD_STATEACTION_VERIFY;
trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
trustData.pFile = &fileInfo;
GUID actionId = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG trustResult = WinVerifyTrust(reinterpret_cast<HWND>(INVALID_HANDLE_VALUE), &actionId, &trustData);
auto cleanup = wil::scope_exit([&]()
{
trustData.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(reinterpret_cast<HWND>(INVALID_HANDLE_VALUE), &actionId, &trustData);
});
if (trustResult != 0)
{
return {};
}
CRYPT_PROVIDER_DATA* provData = GetWinTrustHelpers().ProvDataFromStateData(trustData.hWVTStateData);
if (!provData)
{
return {};
}
CRYPT_PROVIDER_SGNR* signer = GetWinTrustHelpers().ProvSignerFromChain(provData, 0, FALSE, 0);
if (!signer || signer->csCertChain == 0 || !signer->pasCertChain)
{
return {};
}
PCCERT_CONTEXT certContext = signer->pasCertChain[0].pCert;
if (!certContext)
{
return {};
}
DWORD strType = CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG;
return GetNameString(certContext, CERT_NAME_RDN_TYPE, false, &strType);
}
}