-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCAPI2Tools.psm1
More file actions
3519 lines (2978 loc) · 152 KB
/
CAPI2Tools.psm1
File metadata and controls
3519 lines (2978 loc) · 152 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
<#
.SYNOPSIS
CAPI2 Event Log Correlation Analysis Toolkit - PowerShell Module
.DESCRIPTION
A comprehensive PowerShell module for analyzing Windows certificate validation chains,
troubleshooting TLS/SSL connections, and diagnosing CAPI2 cryptographic errors.
.NOTES
Module Name: CAPI2Tools
Version: 2.12.0
Author: Jan Tiedemann
Copyright: (c) 2022-2025 Jan Tiedemann. Licensed under GNU GPL v3.
.LINK
https://github.com/BetaHydri/GetCapiCorrelationTask
#>
#region Error Code Mappings and Helper Functions
# CAPI2 Error Code Reference
$Script:CAPI2ErrorCodes = @{
'0x80092013' = @{
Code = '0x80092013'
HexCode = 'CRYPT_E_REVOCATION_OFFLINE'
Description = 'The revocation function was unable to check revocation because the revocation server was offline.'
CommonCause = 'Network connectivity issue, CRL/OCSP server unavailable, firewall blocking'
Resolution = 'Check network connectivity, verify CRL/OCSP URLs are accessible, check proxy settings'
Severity = 'Warning'
}
'0x80092012' = @{
Code = '0x80092012'
HexCode = 'CRYPT_E_REVOKED'
Description = 'The certificate has been explicitly revoked by its issuer.'
CommonCause = 'Certificate has been revoked (compromised, replaced, or no longer trusted)'
Resolution = 'Obtain a new certificate from the CA, investigate why certificate was revoked'
Severity = 'Critical'
}
'0x800B0101' = @{
Code = '0x800B0101'
HexCode = 'CERT_E_EXPIRED'
Description = 'A required certificate is not within its validity period.'
CommonCause = 'Certificate has expired, system time is incorrect'
Resolution = 'Renew the certificate, verify system time is correct'
Severity = 'Critical'
}
'0x800B010F' = @{
Code = '0x800B010F'
HexCode = 'CERT_E_CN_NO_MATCH'
Description = 'The certificate common name does not match the host name.'
CommonCause = 'Certificate issued for different hostname, wildcard mismatch'
Resolution = 'Obtain certificate with correct CN/SAN, verify hostname is correct'
Severity = 'Critical'
}
'0x800B0109' = @{
Code = '0x800B0109'
HexCode = 'CERT_E_UNTRUSTEDROOT'
Description = 'A certificate chain processed but terminated in a root certificate not trusted.'
CommonCause = 'Root CA not in trusted store, self-signed certificate'
Resolution = 'Install root CA certificate, verify certificate chain'
Severity = 'Critical'
}
'0x800B010A' = @{
Code = '0x800B010A'
HexCode = 'CERT_E_CHAINING'
Description = 'A certificate chain could not be built to a trusted root authority.'
CommonCause = 'Intermediate certificate missing, broken certificate chain'
Resolution = 'Install missing intermediate certificates, verify certificate chain'
Severity = 'Critical'
}
'0x80096004' = @{
Code = '0x80096004'
HexCode = 'TRUST_E_CERT_SIGNATURE'
Description = 'The signature of the certificate cannot be verified.'
CommonCause = 'Certificate has been tampered with, corrupted certificate'
Resolution = 'Re-download/re-install certificate, verify certificate source'
Severity = 'Critical'
}
'0x800B0111' = @{
Code = '0x800B0111'
HexCode = 'CERT_E_WRONG_USAGE'
Description = 'The certificate is not valid for the requested usage.'
CommonCause = 'Certificate used for wrong purpose (e.g., client auth vs server auth)'
Resolution = 'Obtain certificate with correct Extended Key Usage'
Severity = 'Error'
}
'0x80092010' = @{
Code = '0x80092010'
HexCode = 'CRYPT_E_NOT_FOUND'
Description = 'Cannot find object or property.'
CommonCause = 'Certificate not found in store, missing certificate property'
Resolution = 'Verify certificate is installed, check certificate store'
Severity = 'Error'
}
'0x000001EA' = @{
Code = '0x000001EA'
HexCode = 'ERROR_NOT_FOUND'
Description = 'Catalog security information not found for this file hash.'
CommonCause = 'File not in Windows catalog database (normal for non-system files), catalog lookup failed'
Resolution = 'Verify file signature directly if needed, check file source and integrity'
Severity = 'Info'
}
'0x800B0110' = @{
Code = '0x800B0110'
HexCode = 'CERT_E_PURPOSE'
Description = 'The certificate is not valid for the requested purpose.'
CommonCause = 'Certificate used for incorrect purpose, Extended Key Usage mismatch'
Resolution = 'Verify certificate Extended Key Usage (EKU) matches intended purpose'
Severity = 'Error'
}
'0x800B0112' = @{
Code = '0x800B0112'
HexCode = 'CERT_E_PATHLENCONST'
Description = 'A path length constraint in the certificate chain has been violated.'
CommonCause = 'CA certificate used beyond allowed path depth, intermediate CA chain too long'
Resolution = 'Review certificate chain path length constraints, obtain valid certificate chain'
Severity = 'Error'
}
'0x800B0113' = @{
Code = '0x800B0113'
HexCode = 'CERT_E_CRITICAL'
Description = 'A certificate contains an unknown critical extension.'
CommonCause = 'Certificate has unsupported critical extension, incompatible extension version'
Resolution = 'Obtain certificate without unsupported critical extensions, update certificate template'
Severity = 'Error'
}
'0x800B0114' = @{
Code = '0x800B0114'
HexCode = 'CERT_E_VALIDITYPERIODNESTING'
Description = 'The validity periods of the certification chain do not nest correctly.'
CommonCause = 'Certificate issued before CA certificate validity period, time synchronization issue'
Resolution = 'Verify certificate and CA validity periods, check system time, reissue certificate'
Severity = 'Error'
}
'0x800B0115' = @{
Code = '0x800B0115'
HexCode = 'CERT_E_INVALID_POLICY'
Description = 'A required certificate policy is not present or does not meet constraints.'
CommonCause = 'Certificate policy OID mismatch, policy constraints not satisfied'
Resolution = 'Obtain certificate with correct policy OID, review policy requirements'
Severity = 'Error'
}
'0x80090308' = @{
Code = '0x80090308'
HexCode = 'SEC_E_INVALID_TOKEN'
Description = 'The security token provided is invalid or malformed.'
CommonCause = 'Corrupted authentication token, protocol mismatch, unsupported cipher suite'
Resolution = 'Verify TLS/SSL configuration, check cipher suite compatibility, review security settings'
Severity = 'Error'
}
'0x80090325' = @{
Code = '0x80090325'
HexCode = 'SEC_E_UNTRUSTED_ROOT'
Description = 'The certificate chain was issued by an authority that is not trusted.'
CommonCause = 'Root CA certificate not in Trusted Root store, self-signed certificate'
Resolution = 'Install root CA certificate in Trusted Root Certification Authorities store'
Severity = 'Critical'
}
'0x80090326' = @{
Code = '0x80090326'
HexCode = 'SEC_E_WRONG_PRINCIPAL'
Description = 'The target principal name is incorrect (certificate name mismatch).'
CommonCause = 'Certificate CN/SAN does not match hostname, wildcard certificate mismatch'
Resolution = 'Obtain certificate with correct CN/SAN, verify hostname matches certificate'
Severity = 'Critical'
}
'0x80090327' = @{
Code = '0x80090327'
HexCode = 'SEC_E_CERT_EXPIRED'
Description = 'The received certificate has expired or is not yet valid.'
CommonCause = 'Certificate expired, system time incorrect, certificate not yet valid'
Resolution = 'Renew expired certificate, verify system time is correct'
Severity = 'Critical'
}
'0x8009030C' = @{
Code = '0x8009030C'
HexCode = 'SEC_E_LOGON_DENIED'
Description = 'The logon attempt failed due to authentication failure.'
CommonCause = 'Client certificate authentication failed, mutual TLS error, invalid credentials'
Resolution = 'Verify client certificate is valid and trusted, check certificate mapping'
Severity = 'Error'
}
'0x80092026' = @{
Code = '0x80092026'
HexCode = 'CRYPT_E_SECURITY_SETTINGS'
Description = 'Security settings prevent certificate verification or usage.'
CommonCause = 'Group Policy restrictions, weak signature algorithm blocked, disabled cryptographic provider'
Resolution = 'Review security policy settings, check signature algorithm requirements, verify cryptographic settings'
Severity = 'Warning'
}
'0x80096010' = @{
Code = '0x80096010'
HexCode = 'TRUST_E_BAD_DIGEST'
Description = 'The digital signature of the object did not verify correctly.'
CommonCause = 'File modified after signing, corrupted signature, hash algorithm mismatch'
Resolution = 'Re-download or obtain fresh copy of signed object, verify file integrity'
Severity = 'Critical'
}
'FBF' = @{
Code = 'FBF'
HexCode = 'CERT_E_CHAINING'
Description = 'A certificate chain could not be built to a trusted root authority.'
CommonCause = 'Intermediate certificate missing, broken certificate chain'
Resolution = 'Install missing intermediate certificates, verify certificate chain'
Severity = 'Error'
}
}
# CAPI2 TrustStatus Flag Reference
# ErrorStatus flags indicate trust chain validation errors
$Script:TrustStatusErrorFlags = @{
'0x00000001' = @{ Flag = 'CERT_TRUST_IS_NOT_TIME_VALID'; Description = 'Certificate is not within its validity period'; Severity = 'Critical' }
'0x00000002' = @{ Flag = 'CERT_TRUST_IS_NOT_TIME_NESTED'; Description = 'Certificate validity period does not nest correctly'; Severity = 'Error' }
'0x00000004' = @{ Flag = 'CERT_TRUST_IS_REVOKED'; Description = 'Certificate has been explicitly revoked'; Severity = 'Critical' }
'0x00000008' = @{ Flag = 'CERT_TRUST_IS_NOT_SIGNATURE_VALID'; Description = 'Certificate signature is not valid'; Severity = 'Critical' }
'0x00000010' = @{ Flag = 'CERT_TRUST_IS_NOT_VALID_FOR_USAGE'; Description = 'Certificate is not valid for requested usage'; Severity = 'Error' }
'0x00000020' = @{ Flag = 'CERT_TRUST_IS_UNTRUSTED_ROOT'; Description = 'Certificate chain terminated in untrusted root'; Severity = 'Critical' }
'0x00000040' = @{ Flag = 'CERT_TRUST_REVOCATION_STATUS_UNKNOWN'; Description = 'Revocation status could not be determined'; Severity = 'Warning' }
'0x00000080' = @{ Flag = 'CERT_TRUST_IS_CYCLIC'; Description = 'Certificate chain contains a cycle'; Severity = 'Error' }
'0x00000100' = @{ Flag = 'CERT_TRUST_INVALID_EXTENSION'; Description = 'Certificate has unsupported critical extension'; Severity = 'Error' }
'0x00000200' = @{ Flag = 'CERT_TRUST_INVALID_POLICY_CONSTRAINTS'; Description = 'Certificate policy constraints are invalid'; Severity = 'Error' }
'0x00000400' = @{ Flag = 'CERT_TRUST_INVALID_BASIC_CONSTRAINTS'; Description = 'Certificate basic constraints are invalid'; Severity = 'Error' }
'0x00000800' = @{ Flag = 'CERT_TRUST_INVALID_NAME_CONSTRAINTS'; Description = 'Certificate name constraints are invalid'; Severity = 'Error' }
'0x00001000' = @{ Flag = 'CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT'; Description = 'Certificate has unsupported name constraint'; Severity = 'Warning' }
'0x00002000' = @{ Flag = 'CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT'; Description = 'Certificate has undefined name constraint'; Severity = 'Warning' }
'0x00004000' = @{ Flag = 'CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT'; Description = 'Certificate has not permitted name constraint'; Severity = 'Error' }
'0x00008000' = @{ Flag = 'CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT'; Description = 'Certificate has excluded name constraint'; Severity = 'Error' }
'0x01000000' = @{ Flag = 'CERT_TRUST_IS_OFFLINE_REVOCATION'; Description = 'Revocation server was offline'; Severity = 'Warning' }
'0x02000000' = @{ Flag = 'CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY'; Description = 'No issuance chain policy found'; Severity = 'Warning' }
'0x04000000' = @{ Flag = 'CERT_TRUST_IS_EXPLICIT_DISTRUST'; Description = 'Certificate is explicitly distrusted'; Severity = 'Critical' }
'0x08000000' = @{ Flag = 'CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT'; Description = 'Certificate has unsupported critical extension'; Severity = 'Error' }
'0x10000000' = @{ Flag = 'CERT_TRUST_HAS_WEAK_SIGNATURE'; Description = 'Certificate has weak cryptographic signature'; Severity = 'Warning' }
}
# InfoStatus flags provide additional trust chain information
$Script:TrustStatusInfoFlags = @{
'0x00000001' = @{ Flag = 'CERT_TRUST_HAS_EXACT_MATCH_ISSUER'; Description = 'Exact match issuer certificate found' }
'0x00000002' = @{ Flag = 'CERT_TRUST_HAS_KEY_MATCH_ISSUER'; Description = 'Key match issuer certificate found' }
'0x00000004' = @{ Flag = 'CERT_TRUST_HAS_NAME_MATCH_ISSUER'; Description = 'Name match issuer certificate found' }
'0x00000008' = @{ Flag = 'CERT_TRUST_IS_SELF_SIGNED'; Description = 'Certificate is self-signed' }
'0x00000010' = @{ Flag = 'CERT_TRUST_AUTO_UPDATE_CA_REVOCATION'; Description = 'Auto update CA revocation enabled' }
'0x00000020' = @{ Flag = 'CERT_TRUST_AUTO_UPDATE_END_REVOCATION'; Description = 'Auto update end entity revocation enabled' }
'0x00000040' = @{ Flag = 'CERT_TRUST_NO_OCSP_FAILOVER_TO_CRL'; Description = 'No OCSP failover to CRL' }
'0x00000100' = @{ Flag = 'CERT_TRUST_HAS_PREFERRED_ISSUER'; Description = 'Preferred issuer certificate found' }
'0x00000200' = @{ Flag = 'CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY'; Description = 'Issuance chain policy present' }
'0x00000400' = @{ Flag = 'CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS'; Description = 'Valid name constraints present' }
'0x00010000' = @{ Flag = 'CERT_TRUST_IS_PEER_TRUSTED'; Description = 'Certificate is peer trusted' }
'0x00020000' = @{ Flag = 'CERT_TRUST_HAS_CRL_VALIDITY_EXTENDED'; Description = 'CRL validity period extended' }
'0x01000000' = @{ Flag = 'CERT_TRUST_IS_COMPLEX_CHAIN'; Description = 'Certificate chain is complex' }
}
function Get-CAPI2ErrorDetails {
<#
.SYNOPSIS
Translates CAPI2 error codes to human-readable descriptions with resolution steps.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ErrorCode
)
# Normalize error code format
# Remove any whitespace
$ErrorCode = $ErrorCode.Trim()
# If it's a hex string without 0x prefix, add it
if ($ErrorCode -match '^[0-9A-Fa-f]{8}$') {
$ErrorCode = "0x$ErrorCode"
}
# If it's a decimal number, convert to hex
elseif ($ErrorCode -match '^[0-9]+$') {
$ErrorCode = "0x{0:X8}" -f [int64]$ErrorCode
}
# Ensure 0x prefix is lowercase for consistency
$ErrorCode = $ErrorCode -replace '^0X', '0x'
if ($Script:CAPI2ErrorCodes.ContainsKey($ErrorCode)) {
return $Script:CAPI2ErrorCodes[$ErrorCode]
}
else {
return @{
Code = $ErrorCode
HexCode = 'UNKNOWN'
Description = 'Unknown error code'
CommonCause = 'Unknown'
Resolution = 'Search Microsoft documentation for error code'
Severity = 'Unknown'
}
}
}
function Get-TrustStatusDetails {
<#
.SYNOPSIS
Parses TrustStatus XML elements and returns detailed flag information.
.DESCRIPTION
Extracts ErrorStatus and InfoStatus values from TrustStatus elements in CAPI2 events,
parses the bit flags, and returns human-readable descriptions.
.PARAMETER TrustStatusNode
XML node containing TrustStatus element with ErrorStatus and InfoStatus children
.EXAMPLE
$TrustNode = $EventXml.SelectSingleNode("//TrustStatus")
Get-TrustStatusDetails -TrustStatusNode $TrustNode
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[System.Xml.XmlElement]$TrustStatusNode
)
$Result = [PSCustomObject]@{
ErrorFlags = @()
InfoFlags = @()
HasErrors = $false
Severity = 'Info'
}
# Parse ErrorStatus
$ErrorStatusNode = $TrustStatusNode.SelectSingleNode("*[local-name()='ErrorStatus' and @value]")
if ($ErrorStatusNode) {
$ErrorValue = $ErrorStatusNode.GetAttribute('value')
if ($ErrorValue -ne "0") {
$Result.HasErrors = $true
# Convert to integer for bit manipulation
$ErrorInt = if ($ErrorValue -match '^0x') {
[Convert]::ToInt64($ErrorValue, 16)
}
else {
[int64]$ErrorValue
}
# Check each error flag bit
foreach ($FlagEntry in $Script:TrustStatusErrorFlags.GetEnumerator()) {
$FlagValue = [Convert]::ToInt64($FlagEntry.Key, 16)
if (($ErrorInt -band $FlagValue) -eq $FlagValue) {
$FlagInfo = $FlagEntry.Value
$Result.ErrorFlags += [PSCustomObject]@{
Flag = $FlagInfo.Flag
Description = $FlagInfo.Description
Severity = $FlagInfo.Severity
}
# Track highest severity
if ($FlagInfo.Severity -eq 'Critical') {
$Result.Severity = 'Critical'
}
elseif ($FlagInfo.Severity -eq 'Error' -and $Result.Severity -ne 'Critical') {
$Result.Severity = 'Error'
}
elseif ($FlagInfo.Severity -eq 'Warning' -and $Result.Severity -notin @('Critical', 'Error')) {
$Result.Severity = 'Warning'
}
}
}
}
}
# Parse InfoStatus
$InfoStatusNode = $TrustStatusNode.SelectSingleNode("*[local-name()='InfoStatus' and @value]")
if ($InfoStatusNode) {
$InfoValue = $InfoStatusNode.GetAttribute('value')
# Convert to integer for bit manipulation
$InfoInt = if ($InfoValue -match '^0x') {
[Convert]::ToInt64($InfoValue, 16)
}
else {
[int64]$InfoValue
}
# Check each info flag bit
foreach ($FlagEntry in $Script:TrustStatusInfoFlags.GetEnumerator()) {
$FlagValue = [Convert]::ToInt64($FlagEntry.Key, 16)
if (($InfoInt -band $FlagValue) -eq $FlagValue) {
$FlagInfo = $FlagEntry.Value
$Result.InfoFlags += [PSCustomObject]@{
Flag = $FlagInfo.Flag
Description = $FlagInfo.Description
}
}
}
}
return $Result
}
#endregion
#region Helper Functions for Display Characters
function Get-DisplayChar {
<#
.SYNOPSIS
Returns display characters compatible with PowerShell 5.1 and 7.
.DESCRIPTION
Centralized function to get Unicode characters using hex encoding for cross-version compatibility.
.PARAMETER Name
The name of the character to retrieve.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('BoxTopLeft', 'BoxTopRight', 'BoxBottomLeft', 'BoxBottomRight',
'BoxVertical', 'BoxHorizontal', 'Checkmark', 'CheckmarkBold',
'Wrench', 'Flag', 'Lightbulb', 'Warning', 'Lock', 'Clipboard',
'RightArrow', 'Bullet')]
[string]$Name
)
switch ($Name) {
'BoxTopLeft' { return [char]0x2554 } # ╔
'BoxTopRight' { return [char]0x2557 } # ╗
'BoxBottomLeft' { return [char]0x255A } # ╚
'BoxBottomRight' { return [char]0x255D } # ╝
'BoxVertical' { return [char]0x2551 } # ║
'BoxHorizontal' { return [char]0x2550 } # ═
'Checkmark' { return [char]0x2713 } # ✓
'CheckmarkBold' { return [char]0x2713 } # ✓ (simplified for compatibility)
'Wrench' { return [char]0x2692 } # ⚒ (hammer and pick, compatible alternative)
'Flag' { return [char]0x2691 } # ⚑ (flag, compatible alternative)
'Lightbulb' { return [char]0x2600 } # ☀ (sun/bright idea, compatible alternative)
'Warning' { return [char]0x26A0 } # ⚠
'Lock' { return [char]0x2612 } # ☒ (ballot box, compatible alternative)
'Clipboard' { return [char]0x2630 } # ☰ (trigram, compatible alternative)
'RightArrow' { return [char]0x2192 } # →
'Bullet' { return '*' } # *
}
}
function Write-BoxHeader {
<#
.SYNOPSIS
Writes a formatted box header to the console.
.DESCRIPTION
Creates a consistent box-drawing header for workflow steps.
.PARAMETER Text
The text to display in the header.
.PARAMETER Icon
Optional icon name to display before the text.
.PARAMETER Color
Console color for the header (default: Cyan).
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Text,
[Parameter(Mandatory = $false)]
[string]$Icon,
[Parameter(Mandatory = $false)]
[string]$Color = 'Cyan'
)
$Width = 63
$Line = (Get-DisplayChar 'BoxHorizontal').ToString() * $Width
$DisplayText = if ($Icon) {
"$(Get-DisplayChar $Icon) $Text"
}
else {
$Text
}
# Calculate padding
$TextLength = $Text.Length + $(if ($Icon) { 2 } else { 0 })
$PaddingLeft = [Math]::Floor(($Width - $TextLength) / 2)
$PaddingRight = $Width - $TextLength - $PaddingLeft
$TopLine = "$(Get-DisplayChar 'BoxTopLeft')$Line$(Get-DisplayChar 'BoxTopRight')"
$MiddleLine = "$(Get-DisplayChar 'BoxVertical')$(' ' * $PaddingLeft)$DisplayText$(' ' * $PaddingRight)$(Get-DisplayChar 'BoxVertical')"
$BottomLine = "$(Get-DisplayChar 'BoxBottomLeft')$Line$(Get-DisplayChar 'BoxBottomRight')"
Write-Host "`n$TopLine" -ForegroundColor $Color
Write-Host $MiddleLine -ForegroundColor $Color
Write-Host "$BottomLine`n" -ForegroundColor $Color
}
#endregion
#region CAPI2 Event Log Management Functions
function Enable-CAPI2EventLog {
<#
.SYNOPSIS
Enables the CAPI2 Operational event log for certificate troubleshooting.
.DESCRIPTION
Enables detailed certificate validation logging in the Microsoft-Windows-CAPI2/Operational log.
Requires administrative privileges.
.EXAMPLE
Enable-CAPI2EventLog
.EXAMPLE
Enable-CAPI2EventLog -Verbose
#>
[CmdletBinding(SupportsShouldProcess)]
param()
try {
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $IsAdmin) {
Write-Warning "This function requires administrative privileges. Please run PowerShell as Administrator."
return
}
Write-Verbose "Checking current CAPI2 log status..."
$LogDetails = wevtutil.exe gl Microsoft-Windows-CAPI2/Operational
if ($LogDetails -match "enabled:\s+true") {
Write-Host "CAPI2 Event Log is already enabled." -ForegroundColor Green
return
}
if ($PSCmdlet.ShouldProcess("Microsoft-Windows-CAPI2/Operational", "Enable event log")) {
Write-Host "Enabling CAPI2 Operational Event Log..." -ForegroundColor Cyan
wevtutil.exe sl Microsoft-Windows-CAPI2/Operational /e:true
if ($LASTEXITCODE -eq 0) {
Write-Host "$(Get-DisplayChar 'Checkmark') CAPI2 Event Log successfully enabled." -ForegroundColor Green
Write-Host " Certificate validation events will now be logged." -ForegroundColor Gray
}
else {
Write-Error "Failed to enable CAPI2 Event Log. Exit code: $LASTEXITCODE"
}
}
}
catch {
Write-Error "Error enabling CAPI2 Event Log: $($_.Exception.Message)"
}
}
function Disable-CAPI2EventLog {
<#
.SYNOPSIS
Disables the CAPI2 Operational event log.
.DESCRIPTION
Disables certificate validation logging in the Microsoft-Windows-CAPI2/Operational log.
Requires administrative privileges. Use this to reduce log volume when troubleshooting is complete.
.EXAMPLE
Disable-CAPI2EventLog
.EXAMPLE
Disable-CAPI2EventLog -Verbose
#>
[CmdletBinding(SupportsShouldProcess)]
param()
try {
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $IsAdmin) {
Write-Warning "This function requires administrative privileges. Please run PowerShell as Administrator."
return
}
Write-Verbose "Checking current CAPI2 log status..."
$LogDetails = wevtutil.exe gl Microsoft-Windows-CAPI2/Operational
if ($LogDetails -match "enabled:\s+false") {
Write-Host "CAPI2 Event Log is already disabled." -ForegroundColor Yellow
return
}
if ($PSCmdlet.ShouldProcess("Microsoft-Windows-CAPI2/Operational", "Disable event log")) {
Write-Host "Disabling CAPI2 Operational Event Log..." -ForegroundColor Cyan
wevtutil.exe sl Microsoft-Windows-CAPI2/Operational /e:false
if ($LASTEXITCODE -eq 0) {
Write-Host "$(Get-DisplayChar 'Checkmark') CAPI2 Event Log successfully disabled." -ForegroundColor Green
Write-Host " Certificate validation events will no longer be logged." -ForegroundColor Gray
}
else {
Write-Error "Failed to disable CAPI2 Event Log. Exit code: $LASTEXITCODE"
}
}
}
catch {
Write-Error "Error disabling CAPI2 Event Log: $($_.Exception.Message)"
}
}
function Clear-CAPI2EventLog {
<#
.SYNOPSIS
Clears all events from the CAPI2 Operational event log.
.DESCRIPTION
Removes all existing events from the Microsoft-Windows-CAPI2/Operational log.
Requires administrative privileges. Useful for starting fresh troubleshooting sessions.
.PARAMETER Backup
If specified, backs up the log before clearing to the specified path.
.EXAMPLE
Clear-CAPI2EventLog
.EXAMPLE
Clear-CAPI2EventLog -Backup "C:\Logs\CAPI2_Backup_$(Get-Date -Format 'yyyyMMdd_HHmmss').evtx"
.EXAMPLE
Clear-CAPI2EventLog -WhatIf
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory = $false)]
[string]$Backup
)
try {
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $IsAdmin) {
Write-Warning "This function requires administrative privileges. Please run PowerShell as Administrator."
return
}
# Count current events
$EventCount = (Get-WinEvent -LogName Microsoft-Windows-CAPI2/Operational -ErrorAction SilentlyContinue | Measure-Object).Count
if ($EventCount -eq 0) {
Write-Host "CAPI2 Event Log is already empty." -ForegroundColor Yellow
return
}
Write-Host "Current CAPI2 Event Log contains $EventCount events." -ForegroundColor Cyan
# Backup if requested
if ($Backup) {
if ($PSCmdlet.ShouldProcess($Backup, "Backup CAPI2 Event Log")) {
Write-Host "Backing up CAPI2 Event Log to: $Backup" -ForegroundColor Cyan
wevtutil.exe epl Microsoft-Windows-CAPI2/Operational "$Backup"
if ($LASTEXITCODE -eq 0) {
Write-Host "$(Get-DisplayChar 'Checkmark') Backup completed successfully." -ForegroundColor Green
}
else {
Write-Error "Failed to backup CAPI2 Event Log. Exit code: $LASTEXITCODE"
return
}
}
}
# Clear the log
if ($PSCmdlet.ShouldProcess("Microsoft-Windows-CAPI2/Operational", "Clear event log ($EventCount events)")) {
Write-Host "Clearing CAPI2 Operational Event Log..." -ForegroundColor Cyan
wevtutil.exe cl Microsoft-Windows-CAPI2/Operational
if ($LASTEXITCODE -eq 0) {
Write-Host "$(Get-DisplayChar 'Checkmark') CAPI2 Event Log successfully cleared." -ForegroundColor Green
Write-Host " $EventCount events removed. Log is now empty." -ForegroundColor Gray
}
else {
Write-Error "Failed to clear CAPI2 Event Log. Exit code: $LASTEXITCODE"
}
}
}
catch {
Write-Error "Error clearing CAPI2 Event Log: $($_.Exception.Message)"
}
}
function Get-CAPI2EventLogStatus {
<#
.SYNOPSIS
Displays the current status of the CAPI2 Operational event log.
.DESCRIPTION
Shows whether CAPI2 logging is enabled, the number of events, and log file details.
.EXAMPLE
Get-CAPI2EventLogStatus
#>
[CmdletBinding()]
param()
try {
Write-Host "`n=== CAPI2 Event Log Status ===" -ForegroundColor Cyan
$LogDetails = wevtutil.exe gl Microsoft-Windows-CAPI2/Operational 2>&1 | Out-String
# Parse log details
$Enabled = if ($LogDetails -match "enabled:\s+(\w+)") { $matches[1] } else { "Unknown" }
$LogMode = if ($LogDetails -match "logFileName:\s+(.+)") { $matches[1].Trim() } else { "Unknown" }
$MaxSize = if ($LogDetails -match "maxSize:\s+(\d+)") { [math]::Round([int64]$matches[1] / 1MB, 2) } else { "Unknown" }
# Count events
$EventCount = (Get-WinEvent -LogName Microsoft-Windows-CAPI2/Operational -ErrorAction SilentlyContinue | Measure-Object).Count
# Get oldest and newest events
$OldestEvent = Get-WinEvent -LogName Microsoft-Windows-CAPI2/Operational -Oldest -MaxEvents 1 -ErrorAction SilentlyContinue
$NewestEvent = Get-WinEvent -LogName Microsoft-Windows-CAPI2/Operational -MaxEvents 1 -ErrorAction SilentlyContinue
Write-Host "Status: " -NoNewline
if ($Enabled -eq "true") {
Write-Host "ENABLED" -ForegroundColor Green
}
else {
Write-Host "DISABLED" -ForegroundColor Red
}
Write-Host "Event Count: $EventCount" -ForegroundColor White
Write-Host "Max Size: $MaxSize MB" -ForegroundColor White
if ($OldestEvent) {
Write-Host "Oldest Event: $($OldestEvent.TimeCreated)" -ForegroundColor Gray
}
if ($NewestEvent) {
Write-Host "Newest Event: $($NewestEvent.TimeCreated)" -ForegroundColor Gray
}
Write-Host "Log Location: $LogMode" -ForegroundColor Gray
Write-Host ""
if ($Enabled -eq "false") {
Write-Host "$(Get-DisplayChar 'Lightbulb') Tip: Run 'Enable-CAPI2EventLog' to enable certificate event logging." -ForegroundColor Yellow
}
if ($EventCount -eq 0) {
Write-Host "$(Get-DisplayChar 'Lightbulb') Tip: No events found. Perform certificate operations to generate events." -ForegroundColor Yellow
}
}
catch {
Write-Error "Error retrieving CAPI2 Event Log status: $($_.Exception.Message)"
}
}
#endregion
function Find-CapiEventsByName {
<#
.SYNOPSIS
Searches CAPI2 events by DNS name, certificate subject, or process name and retrieves all correlated events.
.DESCRIPTION
This function allows administrators to find certificate validation chains by searching for a DNS name,
certificate subject, or process name without needing to know the TaskID beforehand. It searches the CAPI2 log,
identifies all TaskIDs associated with the specified name, and retrieves all correlated events.
Searches in the following fields:
- subjectName attribute (certificate subject)
- CN (Common Name) elements
- SubjectAltName/DNSName elements (SAN)
- ProcessName attribute (from EventAuxInfo - useful for finding events by application)
- Full XML content (fallback)
.PARAMETER Name
The name to search for - can be:
- DNS name (e.g., "bing.com", "*.microsoft.com")
- Certificate subject or CN (e.g., "DigiCert", "VeriSign")
- Process name (e.g., "chrome.exe", "outlook.exe")
Supports wildcard matching.
.PARAMETER MaxEvents
Maximum number of events to retrieve for initial search (default: 1000)
.PARAMETER Hours
Number of hours to look back in the event log (default: 24)
.PARAMETER IncludePattern
If specified, only returns events matching this pattern in the certificate details.
For common scenarios, use -FilterType instead for autocomplete suggestions.
.PARAMETER FilterType
Pre-defined filters for common troubleshooting scenarios:
- Revocation: Events related to revocation checking (OCSP, CRL)
- Expired: Certificate expiration issues
- Untrusted: Trust chain and root certificate issues
- ChainBuilding: Certificate chain construction events
- PolicyValidation: Certificate policy validation events
- SignatureValidation: Certificate signature verification
- ErrorsOnly: Events containing Result errors
.EXAMPLE
Find-CapiEventsByName -Name "bing.com"
Finds all CAPI2 correlation chains for bing.com
.EXAMPLE
Find-CapiEventsByName -Name "*.microsoft.com" -Hours 48
Finds all Microsoft-related certificate chains in the last 48 hours
.EXAMPLE
Find-CapiEventsByName -Name "DigiCert" -FilterType Revocation
Finds DigiCert certificates with revocation-related events (uses predefined filter)
.EXAMPLE
Find-CapiEventsByName -Name "*.contoso.com" -FilterType Expired
Finds contoso.com certificates with expiration issues
.EXAMPLE
Find-CapiEventsByName -Name "site.com" -IncludePattern "OCSP"
Finds site.com events containing "OCSP" (custom pattern)
.EXAMPLE
Find-CapiEventsByName -Name "chrome.exe"
Finds all certificate validations performed by Chrome browser
.EXAMPLE
Find-CapiEventsByName -Name "outlook.exe" -Hours 4
Finds certificate events from Outlook in the last 4 hours
.OUTPUTS
Returns grouped objects with TaskID and all correlated events
#>
[CmdletBinding(DefaultParameterSetName = "Default")]
param (
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[int]
$MaxEvents = 1000,
[Parameter(Mandatory = $false)]
[int]
$Hours = 24,
[Parameter(Mandatory = $false)]
[string]
$IncludePattern,
[Parameter(Mandatory = $false)]
[ValidateSet('Revocation', 'Expired', 'Untrusted', 'ChainBuilding', 'PolicyValidation', 'SignatureValidation', 'ErrorsOnly')]
[string]
$FilterType
)
begin {
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
$StartTime = (Get-Date).AddHours(-$Hours)
# Map FilterType to actual search patterns
if ($FilterType) {
$IncludePattern = switch ($FilterType) {
'Revocation' { '*revocation*' }
'Expired' { '*expired*' }
'Untrusted' { '*untrusted*' }
'ChainBuilding' { '*CertGetCertificateChain*' }
'PolicyValidation' { '*CertVerifyCertificateChainPolicy*' }
'SignatureValidation' { '*signature*' }
'ErrorsOnly' { '*<Result value=*' }
}
Write-Verbose "FilterType '$FilterType' mapped to pattern: $IncludePattern"
}
}
process {
try {
Write-Host "Searching for certificate events containing '$Name' in the last $Hours hours..." -ForegroundColor Cyan
# Retrieve recent CAPI2 events
$FilterHash = @{
LogName = 'Microsoft-Windows-CAPI2/Operational'
StartTime = $StartTime
}
Write-Verbose "Retrieving events from CAPI2 log..."
$AllEvents = Get-WinEvent -FilterHashtable $FilterHash -MaxEvents $MaxEvents -ErrorAction SilentlyContinue
if ($null -eq $AllEvents) {
Write-Warning "No CAPI2 events found in the specified time range."
return
}
Write-Host "Retrieved $($AllEvents.Count) events. Searching for matching certificates..." -ForegroundColor Yellow
# Convert events and search for the name pattern
$ConvertedEvents = $AllEvents | Convert-EventLogRecord
# Create wildcard pattern for matching
$WildcardPattern = "*$Name*"
# Find matching events and extract TaskIDs
# Search in: subjectName, SubjectAltName/DNSName, CN, ProcessName
$MatchingTaskIDs = $ConvertedEvents | Where-Object {
$EventXml = $_.UserData
if ($null -ne $EventXml) {
$XmlString = $EventXml.ToString()
$IsMatch = $false
# Try to parse as XML for detailed field search
try {
[xml]$ParsedXml = $EventXml
# Search in subjectName attribute
$SubjectNameNodes = $ParsedXml.SelectNodes("//*[@subjectName]")
foreach ($node in $SubjectNameNodes) {
if ($node.subjectName -like $WildcardPattern) {
$IsMatch = $true
break
}
}
# Search in CN (Common Name) elements
if (-not $IsMatch) {
$CNNodes = $ParsedXml.SelectNodes("//CN")
foreach ($node in $CNNodes) {
if ($node.InnerText -like $WildcardPattern) {
$IsMatch = $true
break
}
}
}
# Search in SubjectAltName/DNSName elements
if (-not $IsMatch) {
$DNSNameNodes = $ParsedXml.SelectNodes("//SubjectAltName/DNSName")
foreach ($node in $DNSNameNodes) {
if ($node.InnerText -like $WildcardPattern) {
$IsMatch = $true
break
}
}
}
# Search in ProcessName attribute (EventAuxInfo)
if (-not $IsMatch) {
$ProcessNameNodes = $ParsedXml.SelectNodes("//*[@ProcessName]")
foreach ($node in $ProcessNameNodes) {
if ($node.ProcessName -like $WildcardPattern) {
$IsMatch = $true
break
}
}
}
# Fallback: search in entire XML string
if (-not $IsMatch -and $XmlString -like $WildcardPattern) {
$IsMatch = $true
}
}
catch {
# If XML parsing fails, fallback to string search
if ($XmlString -like $WildcardPattern) {
$IsMatch = $true
}
}
# Apply additional include pattern if specified
if ($IsMatch -and $IncludePattern) {
$IsMatch = $XmlString -like "*$IncludePattern*"
}
$IsMatch
}
} | ForEach-Object {
# Extract chainRef as TaskID from the event (modern CAPI2 correlation)
try {
[xml]$EventXml = $_.UserData
# Look for chainRef attribute in CertificateChain or Certificate elements
$ChainRefNode = $EventXml.SelectSingleNode("//*[@chainRef]")
if ($null -ne $ChainRefNode) {
$TaskId = $ChainRefNode.chainRef
if ($TaskId) {
# Remove curly braces if present
$TaskId = $TaskId.Trim('{}')
[PSCustomObject]@{
TaskID = $TaskId
TimeCreated = $_.TimeCreated
Preview = $_.Message.Substring(0, [Math]::Min(150, $_.Message.Length))
}
}
}
}
catch {
Write-Verbose "Could not extract chainRef from event: $_"
}
} | Select-Object -Property TaskID, TimeCreated, Preview -Unique | Sort-Object -Property TimeCreated -Descending
if ($null -eq $MatchingTaskIDs -or $MatchingTaskIDs.Count -eq 0) {
Write-Warning "No events found matching '$Name'."
Write-Host "Try:" -ForegroundColor Yellow
Write-Host " - Increasing the -Hours parameter" -ForegroundColor Yellow
Write-Host " - Using a broader search term" -ForegroundColor Yellow
Write-Host " - Checking if CAPI2 logging is enabled" -ForegroundColor Yellow
return
}