From f056b164c144c737b793bab3cfc714de3f327935 Mon Sep 17 00:00:00 2001 From: Ugochukwu Mmaduekwe Date: Wed, 28 Oct 2026 21:38:18 +0100 Subject: [PATCH 1/2] Match indirect CRL entries by issuer and report a validation failure reason Indirect CRLs may list the same serial number under more than one issuer, so a certificate's entry is now found by issuer as well as serial number; X509Crl.IsRevoked no longer stops at another issuer's entry sharing the serial number. Revocation status now keeps the CRL reason code apart from whether the certificate is revoked, so a reason value can never be mistaken for a status, and the CRL checks are more defensive about missing revocation dates and undefined reason codes. Path validation failures now carry a machine-readable reason (expired, revoked, no trust anchor, path too long, and so on) alongside the message, preserved when a failure is re-wrapped against a position in the path. --- .../Delphi/CryptoLib.BenchmarkConsole.dpr | 1 + .../Delphi.Examples/CryptoLib.Examples.dpr | 1 + .../Delphi.Tests/CryptoLib.Tests.Mobile.dpr | 1 + .../Delphi.Tests/CryptoLib.Tests.Mobile.dproj | 1 + .../Delphi.Tests/CryptoLib.Tests.dpr | 1 + .../src/Pkix/CertPathHardeningTests.pas | 97 +++++++++++++ .../src/Pkix/CertPathValidatorTests.pas | 6 + .../src/Pkix/PkixFoundationTests.pas | 22 ++- .../src/Interfaces/Pkix/ClpIPkixTypes.pas | 30 ++-- CryptoLib/src/Interfaces/X509/ClpIX509Crl.pas | 6 +- CryptoLib/src/Misc/ClpCryptoLibExceptions.pas | 50 ++++++- .../Delphi/CryptoLib4PascalPackage.dpk | 3 +- .../Packages/FPC/CryptoLib4PascalPackage.lpk | 6 +- .../Packages/FPC/CryptoLib4PascalPackage.pas | 3 +- CryptoLib/src/Pkix/ClpCertStatus.pas | 80 ++++++++--- .../src/Pkix/ClpPkixCertPathValidator.pas | 13 +- .../Pkix/ClpPkixCertPathValidatorReason.pas | 32 +++++ .../ClpPkixCertPathValidatorUtilities.pas | 130 ++++++++++++++---- .../src/Pkix/ClpPkixCrlRevocationChecker.pas | 2 +- .../src/Pkix/ClpRfc3280CertPathUtilities.pas | 109 +++++++-------- .../src/Pkix/ClpRfc3281CertPathUtilities.pas | 31 ++--- CryptoLib/src/X509/ClpX509Crl.pas | 62 ++++++--- CryptoLib/src/X509/ClpX509CrlEntry.pas | 16 ++- 23 files changed, 537 insertions(+), 166 deletions(-) create mode 100644 CryptoLib/src/Pkix/ClpPkixCertPathValidatorReason.pas diff --git a/CryptoLib.Benchmark/Delphi/CryptoLib.BenchmarkConsole.dpr b/CryptoLib.Benchmark/Delphi/CryptoLib.BenchmarkConsole.dpr index 0981d709..3b9b8724 100644 --- a/CryptoLib.Benchmark/Delphi/CryptoLib.BenchmarkConsole.dpr +++ b/CryptoLib.Benchmark/Delphi/CryptoLib.BenchmarkConsole.dpr @@ -712,6 +712,7 @@ uses ClpIX509TrustedCertificateBlock in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIX509TrustedCertificateBlock.pas', ClpCertificateTrustBlock in '..\..\CryptoLib\src\OpenSsl\ClpCertificateTrustBlock.pas', ClpX509TrustedCertificateBlock in '..\..\CryptoLib\src\OpenSsl\ClpX509TrustedCertificateBlock.pas', + ClpPkixCertPathValidatorReason in '..\..\CryptoLib\src\Pkix\ClpPkixCertPathValidatorReason.pas', ClpIOpenSslPemReader in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIOpenSslPemReader.pas', ClpIPemParser in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemParser.pas', ClpIPemReader in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemReader.pas', diff --git a/CryptoLib.Examples/Delphi.Examples/CryptoLib.Examples.dpr b/CryptoLib.Examples/Delphi.Examples/CryptoLib.Examples.dpr index 6f0239d4..d2963d86 100644 --- a/CryptoLib.Examples/Delphi.Examples/CryptoLib.Examples.dpr +++ b/CryptoLib.Examples/Delphi.Examples/CryptoLib.Examples.dpr @@ -729,6 +729,7 @@ uses ClpIX509TrustedCertificateBlock in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIX509TrustedCertificateBlock.pas', ClpCertificateTrustBlock in '..\..\CryptoLib\src\OpenSsl\ClpCertificateTrustBlock.pas', ClpX509TrustedCertificateBlock in '..\..\CryptoLib\src\OpenSsl\ClpX509TrustedCertificateBlock.pas', + ClpPkixCertPathValidatorReason in '..\..\CryptoLib\src\Pkix\ClpPkixCertPathValidatorReason.pas', ClpIOpenSslPemReader in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIOpenSslPemReader.pas', ClpIPemParser in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemParser.pas', ClpIPemReader in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemReader.pas', diff --git a/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dpr b/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dpr index a78eb5ae..d0338d3f 100644 --- a/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dpr +++ b/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dpr @@ -705,6 +705,7 @@ uses ClpIX509TrustedCertificateBlock in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIX509TrustedCertificateBlock.pas', ClpCertificateTrustBlock in '..\..\CryptoLib\src\OpenSsl\ClpCertificateTrustBlock.pas', ClpX509TrustedCertificateBlock in '..\..\CryptoLib\src\OpenSsl\ClpX509TrustedCertificateBlock.pas', + ClpPkixCertPathValidatorReason in '..\..\CryptoLib\src\Pkix\ClpPkixCertPathValidatorReason.pas', ClpIOpenSslPemReader in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIOpenSslPemReader.pas', ClpIPemParser in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemParser.pas', ClpIPemReader in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemReader.pas', diff --git a/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dproj b/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dproj index edcfd4dd..f84359fc 100644 --- a/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dproj +++ b/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.Mobile.dproj @@ -1047,6 +1047,7 @@ + diff --git a/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.dpr b/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.dpr index e3cda04f..1feef276 100644 --- a/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.dpr +++ b/CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.dpr @@ -724,6 +724,7 @@ uses ClpIX509TrustedCertificateBlock in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIX509TrustedCertificateBlock.pas', ClpCertificateTrustBlock in '..\..\CryptoLib\src\OpenSsl\ClpCertificateTrustBlock.pas', ClpX509TrustedCertificateBlock in '..\..\CryptoLib\src\OpenSsl\ClpX509TrustedCertificateBlock.pas', + ClpPkixCertPathValidatorReason in '..\..\CryptoLib\src\Pkix\ClpPkixCertPathValidatorReason.pas', ClpIOpenSslPemReader in '..\..\CryptoLib\src\Interfaces\OpenSsl\ClpIOpenSslPemReader.pas', ClpIPemParser in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemParser.pas', ClpIPemReader in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemReader.pas', diff --git a/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas b/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas index ee93dd0f..63d03695 100644 --- a/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas +++ b/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas @@ -48,6 +48,8 @@ interface ClpX509Generators, ClpX509Asn1Objects, ClpIX509Asn1Objects, + ClpX509Asn1Generators, + ClpIX509Asn1Generators, ClpAsn1SignatureFactory, ClpISignatureFactory, ClpX509ExtensionUtilities, @@ -158,6 +160,24 @@ TAnchorNameConstraintsTest = class(TCryptoLibAlgorithmTestCase) procedure TestExplicitConstraintsCannotWidenTheCertificate; end; + /// + /// An indirect CRL that revokes a serial number under one issuer must not report a certificate + /// sharing that serial number under a different issuer as revoked. + /// + TIndirectCrlSerialCollisionTest = class(TCryptoLibAlgorithmTestCase) + strict private + const + SigAlgorithm = 'SHA256WITHRSA'; + var + FRandom: ISecureRandom; + function MakeCert(const ASerial: TBigInteger; const AIssuer, ASubject: IX509Name; + const AKey: IAsymmetricCipherKeyPair): IX509Certificate; + protected + procedure SetUp; override; + published + procedure TestSameSerialUnderDifferentIssuerIsNotMasked; + end; + implementation { TCertPathLoopTest } @@ -741,16 +761,93 @@ procedure TAnchorNameConstraintsTest.TestExplicitConstraintsCannotWidenTheCertif 'explicit constraints do not lift the certificate''s own constraints'); end; +{ TIndirectCrlSerialCollisionTest } + +procedure TIndirectCrlSerialCollisionTest.SetUp; +begin + inherited SetUp; + FRandom := TSecureRandom.Create() as ISecureRandom; +end; + +function TIndirectCrlSerialCollisionTest.MakeCert(const ASerial: TBigInteger; + const AIssuer, ASubject: IX509Name; const AKey: IAsymmetricCipherKeyPair): IX509Certificate; +var + LGen: IX509V3CertificateGenerator; + LNow: TDateTime; +begin + // IsRevoked matches on issuer and serial only, so a minimally-populated certificate is enough + LNow := Now.ToUniversalTime(); + LGen := TX509V3CertificateGenerator.Create; + LGen.SetIssuerDN(AIssuer); + LGen.SetSerialNumber(ASerial); + LGen.SetNotBeforeUtc(IncDay(LNow, -1)); + LGen.SetNotAfterUtc(IncYear(LNow, 1)); + LGen.SetSubjectDN(ASubject); + LGen.SetPublicKey(AKey.Public as IAsymmetricKeyParameter); + Result := LGen.Generate(TAsn1SignatureFactory.Create(SigAlgorithm, + AKey.Private as IAsymmetricKeyParameter, FRandom) as ISignatureFactory); +end; + +procedure TIndirectCrlSerialCollisionTest.TestSameSerialUnderDifferentIssuerIsNotMasked; +var + LKeyA, LKeyB, LSignerKey: IAsymmetricCipherKeyPair; + LDnA, LDnB, LSignerDn, LSubject: IX509Name; + LSerial: TBigInteger; + LCertA, LCertB: IX509Certificate; + LCrlGen: IX509V2CrlGenerator; + LExtGen: IX509ExtensionsGenerator; + LCrl: IX509Crl; + LNow: TDateTime; +begin + LKeyA := TCertTestUtilities.GenerateRsaKeyPair(1024); + LKeyB := TCertTestUtilities.GenerateRsaKeyPair(1024); + LSignerKey := TCertTestUtilities.GenerateRsaKeyPair(1024); + + LDnA := TX509Name.Create('CN=CA-A, O=Test-PKI, C=DE'); + LDnB := TX509Name.Create('CN=CA-B, O=Test-PKI, C=DE'); + LSignerDn := TX509Name.Create('CN=Indirect-CRL-Signer, O=Test-PKI, C=DE'); + LSubject := TX509Name.Create('CN=EU, O=Test-PKI, C=DE'); + + // the same serial number issued independently by two different CAs + LSerial := TBigInteger.ValueOf(4660); + LCertA := MakeCert(LSerial, LDnA, LSubject, LKeyA); + LCertB := MakeCert(LSerial, LDnB, LSubject, LKeyB); + + // an indirect CRL that revokes the serial, naming CA-A as the entry's certificate issuer + LNow := Now.ToUniversalTime(); + LCrlGen := TX509V2CrlGenerator.Create() as IX509V2CrlGenerator; + LCrlGen.SetIssuerDN(LSignerDn); + LCrlGen.SetThisUpdateUtc(IncHour(LNow, -1)); + LCrlGen.SetNextUpdateUtc(IncMonth(LNow, 1)); + LCrlGen.AddExtension(TX509Extensions.IssuingDistributionPoint, True, + TIssuingDistributionPoint.Create(nil, False, False, nil, True, False) as IIssuingDistributionPoint); + + LExtGen := TX509ExtensionsGenerator.Create() as IX509ExtensionsGenerator; + LExtGen.AddExtension(TX509Extensions.CertificateIssuer, True, + TGeneralNames.Create(TGeneralName.Create(TGeneralName.DirectoryName, LDnA as IAsn1Encodable) + as IGeneralName) as IGeneralNames as IAsn1Encodable); + LCrlGen.AddCrlEntryUtc(LSerial, IncHour(LNow, -1), LExtGen.Generate()); + + LCrl := LCrlGen.Generate(TAsn1SignatureFactory.Create(SigAlgorithm, + LSignerKey.Private as IAsymmetricKeyParameter, FRandom) as ISignatureFactory); + + CheckTrue(LCrl.IsRevoked(LCertA), 'the certificate from the named issuer is revoked'); + CheckFalse(LCrl.IsRevoked(LCertB), + 'a certificate sharing the serial number under a different issuer is not masked as revoked'); +end; + initialization {$IFDEF FPC} RegisterTest(TCertPathLoopTest); RegisterTest(TIndirectCrlSignerTest); RegisterTest(TAnchorNameConstraintsTest); + RegisterTest(TIndirectCrlSerialCollisionTest); {$ELSE} RegisterTest(TCertPathLoopTest.Suite); RegisterTest(TIndirectCrlSignerTest.Suite); RegisterTest(TAnchorNameConstraintsTest.Suite); + RegisterTest(TIndirectCrlSerialCollisionTest.Suite); {$ENDIF FPC} end. diff --git a/CryptoLib.Tests/src/Pkix/CertPathValidatorTests.pas b/CryptoLib.Tests/src/Pkix/CertPathValidatorTests.pas index f3a20084..21da930e 100644 --- a/CryptoLib.Tests/src/Pkix/CertPathValidatorTests.pas +++ b/CryptoLib.Tests/src/Pkix/CertPathValidatorTests.pas @@ -51,6 +51,7 @@ interface ClpNullable, ClpCryptoLibTypes, ClpCryptoLibExceptions, + ClpPkixCertPathValidatorReason, ClpCryptoLibConfig, CertVectors, CryptoLibTestBase; @@ -268,6 +269,7 @@ procedure TCertPathValidatorTest.TestInvalidPathContainingAValidOne; LValidator: IPkixCertPathValidator; LRejected: Boolean; LIndex: Int32; + LReason: TPkixCertPathValidatorReason; begin // the end entity is not issued by the intermediate, so its signature cannot verify LRootCert := ReadCert('PkixBrokenChainRootCa'); @@ -287,6 +289,7 @@ procedure TCertPathValidatorTest.TestInvalidPathContainingAValidOne; LRejected := False; LIndex := -1; + LReason := TPkixCertPathValidatorReason.Unspecified; LValidator := TPkixCertPathValidator.Create() as IPkixCertPathValidator; try LValidator.Validate(LPath, LParams); @@ -295,12 +298,15 @@ procedure TCertPathValidatorTest.TestInvalidPathContainingAValidOne; begin LRejected := True; LIndex := E.Index; + LReason := E.Reason; end; end; CheckTrue(LRejected, 'a path whose end entity signature does not verify is rejected'); if LIndex >= 0 then CheckEquals(0, LIndex, 'the end entity certificate is blamed'); + CheckTrue(LReason = TPkixCertPathValidatorReason.InvalidSignature, + 'the failure is reported as an invalid signature'); end; procedure TCertPathValidatorTest.TestCircularCrlIssuerProcessing; diff --git a/CryptoLib.Tests/src/Pkix/PkixFoundationTests.pas b/CryptoLib.Tests/src/Pkix/PkixFoundationTests.pas index de2c1bdf..a9bde1d7 100644 --- a/CryptoLib.Tests/src/Pkix/PkixFoundationTests.pas +++ b/CryptoLib.Tests/src/Pkix/PkixFoundationTests.pas @@ -326,13 +326,27 @@ procedure TPkixFoundationTest.TestCertStatusAndReasonsMask; LMask, LOther: IReasonsMask; begin LStatus := TCertStatus.Create(); - CheckEquals(TCertStatus.Unrevoked, LStatus.Status, 'a fresh status is unrevoked'); + CheckFalse(LStatus.IsRevoked, 'a fresh status is not revoked'); CheckFalse(LStatus.RevocationDate.HasValue, 'a fresh status has no revocation date'); + CheckFalse(LStatus.ReasonCode.HasValue, 'a fresh status has no reason code'); - LStatus.Status := TCertStatus.Undetermined; - LStatus.RevocationDate := TNullable.Some(FRootCert.NotBefore); - CheckEquals(TCertStatus.Undetermined, LStatus.Status, 'the status round-trips'); + // a known reason code round-trips and maps to its name + LStatus.SetRevoked(FRootCert.NotBefore, TNullable.Some(Int32(TCrlReason.KeyCompromise))); + CheckTrue(LStatus.IsRevoked, 'the revocation is recorded'); CheckTrue(LStatus.RevocationDate.HasValue, 'the revocation date round-trips'); + CheckEquals(TCrlReason.KeyCompromise, LStatus.Reason, 'the effective reason is the given code'); + CheckEquals('keyCompromise', LStatus.GetReasonText, 'a known reason maps to its name'); + + // an out-of-range reason code is processed as unspecified but reported verbatim, so it can never + // be mistaken for a status + LStatus.SetRevoked(FRootCert.NotBefore, TNullable.Some(Int32(99))); + CheckTrue(LStatus.IsRevoked, 'an unknown reason code is still a revocation'); + CheckEquals(TCrlReason.Unspecified, LStatus.Reason, 'an unknown code is processed as unspecified'); + CheckEquals('(unknown code: 99)', LStatus.GetReasonText, 'an unknown code is reported verbatim'); + + LStatus.SetUnrevoked(); + CheckFalse(LStatus.IsRevoked, 'a removeFromCRL entry can clear the revocation'); + CheckFalse(LStatus.RevocationDate.HasValue, 'clearing drops the revocation date'); LMask := TReasonsMask.Create(); CheckFalse(LMask.IsAllReasons, 'an empty mask does not cover every reason'); diff --git a/CryptoLib/src/Interfaces/Pkix/ClpIPkixTypes.pas b/CryptoLib/src/Interfaces/Pkix/ClpIPkixTypes.pas index e7829c77..2806904a 100644 --- a/CryptoLib/src/Interfaces/Pkix/ClpIPkixTypes.pas +++ b/CryptoLib/src/Interfaces/Pkix/ClpIPkixTypes.pas @@ -136,19 +136,31 @@ interface property Parent: IPkixPolicyNode read GetParent write SetParent; end; - /// - /// Mutable revocation status carried through path validation. - /// + /// Revocation status accumulated over the CRLs checked for a certificate. The reason code + /// is kept apart from whether the certificate is revoked. "Undetermined" is not stored: it is + /// concluded when processing ends with the certificate not revoked and not all reasons covered. ICertStatus = interface(IInterface) ['{B2016D68-7C59-4FA3-8E4B-1D8F26C593E7}'] - function GetStatus: Int32; - procedure SetStatus(AValue: Int32); + function GetIsRevoked: Boolean; function GetRevocationDate: TNullable; - procedure SetRevocationDate(const AValue: TNullable); - - property Status: Int32 read GetStatus write SetStatus; - property RevocationDate: TNullable read GetRevocationDate write SetRevocationDate; + function GetReasonCode: TNullable; + function GetReason: Int32; + function GetReasonText: String; + + /// Record a revocation. is the entry's reason code as + /// given, or None if absent. + procedure SetRevoked(const ARevocationDate: TDateTime; const AReasonCode: TNullable); + /// Clear a removeFromCRL revocation (RFC 5280 6.3.3 (k)). + procedure SetUnrevoked(); + + property IsRevoked: Boolean read GetIsRevoked; + property RevocationDate: TNullable read GetRevocationDate; + /// The entry's reason code as given, or None if absent, out of range, or not revoked. + property ReasonCode: TNullable read GetReasonCode; + /// The effective CRLReason to process the revocation by: the reason code if defined, + /// else unspecified. + property Reason: Int32 read GetReason; end; /// diff --git a/CryptoLib/src/Interfaces/X509/ClpIX509Crl.pas b/CryptoLib/src/Interfaces/X509/ClpIX509Crl.pas index ae9451cb..5828a0a7 100644 --- a/CryptoLib/src/Interfaces/X509/ClpIX509Crl.pas +++ b/CryptoLib/src/Interfaces/X509/ClpIX509Crl.pas @@ -40,7 +40,8 @@ interface function GetIssuerDN: IX509Name; function GetThisUpdate: TDateTime; function GetNextUpdate: TNullable; - function GetRevokedCertificate(const ASerialNumber: TBigInteger): IX509CrlEntry; + function GetRevokedCertificate(const ASerialNumber: TBigInteger): IX509CrlEntry; overload; + function GetRevokedCertificate(const ACert: IX509Certificate): IX509CrlEntry; overload; function GetRevokedCertificates: TCryptoLibGenericArray; function GetTbsCertList: TCryptoLibByteArray; function GetNonCriticalExtensionOids: TCryptoLibStringArray; @@ -60,6 +61,7 @@ interface procedure Verify(const AVerifierProvider: IVerifierFactoryProvider); overload; procedure VerifyAltSignature(const AVerifierProvider: IVerifierFactoryProvider); + function GetIsIndirect: Boolean; function IsRevoked(const ACert: IX509Certificate): Boolean; function Equals(const AOther: TObject): Boolean; overload; /// Value equality on the encoded CRL. @@ -72,6 +74,8 @@ interface property IssuerDN: IX509Name read GetIssuerDN; property ThisUpdate: TDateTime read GetThisUpdate; property NextUpdate: TNullable read GetNextUpdate; + /// Whether this is an indirect CRL (its IssuingDistributionPoint says so). + property IsIndirect: Boolean read GetIsIndirect; property SigAlgName: String read GetSigAlgName; property SigAlgOid: String read GetSigAlgOid; property SignatureAlgorithm: IAlgorithmIdentifier read GetSignatureAlgorithm; diff --git a/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas b/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas index cd12e7a2..337203a8 100644 --- a/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas +++ b/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas @@ -21,7 +21,8 @@ interface uses - SysUtils; + SysUtils, + ClpPkixCertPathValidatorReason; type ECryptoLibException = class(Exception); @@ -69,6 +70,7 @@ EOcspCryptoLibException = class(ECryptoLibException); /// is the position in the path of the certificate that failed, counted from /// the end entity, and is -1 when no single certificate is to blame or the raise site does not /// know its position. It is deliberately not defaulted to 0, which is a real position. + /// gives the machine-readable cause, Unspecified when none was set. /// EPkixCertPathValidatorCryptoLibException = class(ECryptoLibException) @@ -76,8 +78,10 @@ EPkixCertPathValidatorCryptoLibException = class(ECryptoLibException) var FIndex: Int32; FHasIndex: Boolean; + FReason: TPkixCertPathValidatorReason; function GetIndex: Int32; + function GetReason: TPkixCertPathValidatorReason; public /// @@ -90,8 +94,19 @@ EPkixCertPathValidatorCryptoLibException = class(ECryptoLibException) /// As CreateResFmt, but records the position in the path that failed. constructor CreateResFmtAt(AIndex: Int32; AResStringRec: PResStringRec; const AArgs: array of const); + /// As CreateAt, but records a reason instead of only a position. A position of + /// AIndex < 0 means none, so a raise site re-wrapping another can preserve its reason. + constructor CreateReason(AReason: TPkixCertPathValidatorReason; AIndex: Int32; + const AMsg: String); + /// As CreateResAt, but records a reason (AIndex < 0 means no position). + constructor CreateResReason(AReason: TPkixCertPathValidatorReason; AIndex: Int32; + AResStringRec: PResStringRec); + /// As CreateResFmtAt, but records a reason (AIndex < 0 means no position). + constructor CreateResFmtReason(AReason: TPkixCertPathValidatorReason; AIndex: Int32; + AResStringRec: PResStringRec; const AArgs: array of const); property Index: Int32 read GetIndex; + property Reason: TPkixCertPathValidatorReason read GetReason; end; /// /// Raised when a revocation mechanism could not settle the status of a certificate, so a peer @@ -145,6 +160,39 @@ constructor EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex: Int3 FHasIndex := True; end; +constructor EPkixCertPathValidatorCryptoLibException.CreateReason( + AReason: TPkixCertPathValidatorReason; AIndex: Int32; const AMsg: String); +begin + inherited Create(AMsg); + FReason := AReason; + FIndex := AIndex; + FHasIndex := AIndex >= 0; +end; + +constructor EPkixCertPathValidatorCryptoLibException.CreateResReason( + AReason: TPkixCertPathValidatorReason; AIndex: Int32; AResStringRec: PResStringRec); +begin + inherited CreateRes(AResStringRec); + FReason := AReason; + FIndex := AIndex; + FHasIndex := AIndex >= 0; +end; + +constructor EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + AReason: TPkixCertPathValidatorReason; AIndex: Int32; AResStringRec: PResStringRec; + const AArgs: array of const); +begin + inherited CreateResFmt(AResStringRec, AArgs); + FReason := AReason; + FIndex := AIndex; + FHasIndex := AIndex >= 0; +end; + +function EPkixCertPathValidatorCryptoLibException.GetReason: TPkixCertPathValidatorReason; +begin + Result := FReason; +end; + function EPkixCertPathValidatorCryptoLibException.GetIndex: Int32; begin // the inherited constructors leave the fields zeroed, and 0 is a real position diff --git a/CryptoLib/src/Packages/Delphi/CryptoLib4PascalPackage.dpk b/CryptoLib/src/Packages/Delphi/CryptoLib4PascalPackage.dpk index e85e9229..467387c2 100644 --- a/CryptoLib/src/Packages/Delphi/CryptoLib4PascalPackage.dpk +++ b/CryptoLib/src/Packages/Delphi/CryptoLib4PascalPackage.dpk @@ -974,6 +974,7 @@ contains ClpICertificateTrustBlock in '..\..\Interfaces\OpenSsl\ClpICertificateTrustBlock.pas', ClpIX509TrustedCertificateBlock in '..\..\Interfaces\OpenSsl\ClpIX509TrustedCertificateBlock.pas', ClpCertificateTrustBlock in '..\..\OpenSsl\ClpCertificateTrustBlock.pas', - ClpX509TrustedCertificateBlock in '..\..\OpenSsl\ClpX509TrustedCertificateBlock.pas'; + ClpX509TrustedCertificateBlock in '..\..\OpenSsl\ClpX509TrustedCertificateBlock.pas', + ClpPkixCertPathValidatorReason in '..\..\Pkix\ClpPkixCertPathValidatorReason.pas'; end. diff --git a/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.lpk b/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.lpk index 3ae744db..6922d8b5 100644 --- a/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.lpk +++ b/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.lpk @@ -31,7 +31,7 @@ Acknowledgements: Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring the development of this library "/> - + @@ -3769,6 +3769,10 @@ Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring the devel + + + + diff --git a/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.pas b/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.pas index d4b5d850..b25946c5 100644 --- a/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.pas +++ b/CryptoLib/src/Packages/FPC/CryptoLib4PascalPackage.pas @@ -305,7 +305,8 @@ interface ClpHpkeKdf, ClpHpkeAead, ClpHpkeContext, ClpDhKem, ClpHpke, ClpIHpkeKdf, ClpIHpkeAead, ClpIHpkeContext, ClpIHpkeKem, ClpIHpke, ClpICertificateTrustBlock, ClpIX509TrustedCertificateBlock, - ClpCertificateTrustBlock, ClpX509TrustedCertificateBlock; + ClpCertificateTrustBlock, ClpX509TrustedCertificateBlock, + ClpPkixCertPathValidatorReason; implementation diff --git a/CryptoLib/src/Pkix/ClpCertStatus.pas b/CryptoLib/src/Pkix/ClpCertStatus.pas index 8098969d..e1bf725a 100644 --- a/CryptoLib/src/Pkix/ClpCertStatus.pas +++ b/CryptoLib/src/Pkix/ClpCertStatus.pas @@ -26,50 +26,67 @@ interface ClpNullable; type - /// - /// Revocation status of a certificate, carried through path validation. Values other than - /// and are CRL reason codes. - /// + /// Revocation status accumulated over the CRLs checked for a certificate; keeps the reason + /// code apart from whether the certificate is revoked. TCertStatus = class(TInterfacedObject, ICertStatus) - public const - Unrevoked = Int32(11); - Undetermined = Int32(12); - strict private var - FStatus: Int32; FRevocationDate: TNullable; + FReasonCode: TNullable; strict protected - function GetStatus: Int32; - procedure SetStatus(AValue: Int32); + function GetIsRevoked: Boolean; function GetRevocationDate: TNullable; - procedure SetRevocationDate(const AValue: TNullable); + function GetReasonCode: TNullable; + function GetReason: Int32; overload; + function GetReasonText: String; + procedure SetRevoked(const ARevocationDate: TDateTime; const AReasonCode: TNullable); + procedure SetUnrevoked(); public constructor Create(); + + /// Whether is a CRLReason defined by RFC 5280 5.3.1. + class function IsReasonCodeKnown(AReasonCode: Int32): Boolean; static; + /// The CRLReason to process an entry by: its reason code if defined, else unspecified. + class function GetReason(const AReasonCode: TNullable): Int32; overload; static; end; implementation +const + // indexed by CRLReason value (RFC 5280 5.3.1); 7 is unused + ReasonNames: array [0 .. 10] of String = ('unspecified', 'keyCompromise', 'cACompromise', + 'affiliationChanged', 'superseded', 'cessationOfOperation', 'certificateHold', 'unknown', + 'removeFromCRL', 'privilegeWithdrawn', 'aACompromise'); + { TCertStatus } constructor TCertStatus.Create(); begin inherited Create(); - FStatus := Unrevoked; FRevocationDate := TNullable.None; + FReasonCode := TNullable.None; +end; + +class function TCertStatus.IsReasonCodeKnown(AReasonCode: Int32): Boolean; +begin + // value 7 is not used (RFC 5280 5.3.1) + Result := (AReasonCode >= 0) and (AReasonCode <= 10) and (AReasonCode <> 7); end; -function TCertStatus.GetStatus: Int32; +class function TCertStatus.GetReason(const AReasonCode: TNullable): Int32; begin - Result := FStatus; + if AReasonCode.HasValue and IsReasonCodeKnown(AReasonCode.Value) then + Result := AReasonCode.Value + else + Result := 0; // unspecified end; -procedure TCertStatus.SetStatus(AValue: Int32); +function TCertStatus.GetIsRevoked: Boolean; begin - FStatus := AValue; + Result := FRevocationDate.HasValue; end; function TCertStatus.GetRevocationDate: TNullable; @@ -77,9 +94,34 @@ function TCertStatus.GetRevocationDate: TNullable; Result := FRevocationDate; end; -procedure TCertStatus.SetRevocationDate(const AValue: TNullable); +function TCertStatus.GetReasonCode: TNullable; begin - FRevocationDate := AValue; + Result := FReasonCode; +end; + +function TCertStatus.GetReason: Int32; +begin + Result := GetReason(FReasonCode); +end; + +function TCertStatus.GetReasonText: String; +begin + if FReasonCode.HasValue and (not IsReasonCodeKnown(FReasonCode.Value)) then + Result := Format('(unknown code: %d)', [FReasonCode.Value]) + else + Result := ReasonNames[GetReason(FReasonCode)]; +end; + +procedure TCertStatus.SetRevoked(const ARevocationDate: TDateTime; const AReasonCode: TNullable); +begin + FRevocationDate := TNullable.Some(ARevocationDate); + FReasonCode := AReasonCode; +end; + +procedure TCertStatus.SetUnrevoked(); +begin + FRevocationDate := TNullable.None; + FReasonCode := TNullable.None; end; end. diff --git a/CryptoLib/src/Pkix/ClpPkixCertPathValidator.pas b/CryptoLib/src/Pkix/ClpPkixCertPathValidator.pas index d9ccb96c..f495c6a2 100644 --- a/CryptoLib/src/Pkix/ClpPkixCertPathValidator.pas +++ b/CryptoLib/src/Pkix/ClpPkixCertPathValidator.pas @@ -37,6 +37,7 @@ interface ClpPkixRevocationChecker, ClpDateTimeHelper, ClpCryptoLibTypes, + ClpPkixCertPathValidatorReason, ClpCryptoLibExceptions; resourcestring @@ -192,7 +193,8 @@ function TPkixCertPathValidator.Validate(const ACertPath: IPkixCertPath; const A end; if LTrust = nil then - raise EPkixCertPathValidatorCryptoLibException.CreateRes(@STrustAnchorNotFound); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.NoTrustAnchor, -1, @STrustAnchorNotFound); // the anchor that CRL checking is restricted to below must be one of the supplied ones, not one // reached out-of-band @@ -206,7 +208,8 @@ function TPkixCertPathValidator.Validate(const ACertPath: IPkixCertPath; const A end; end; if not LTrustFound then - raise EPkixCertPathValidatorCryptoLibException.CreateRes(@STrustAnchorNotSupplied); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.NoTrustAnchor, -1, @STrustAnchorNotSupplied); // RFC 5280 sec. 6.3.3(f): CRLs must be anchored at the same trust anchor as the certificate, so with // several anchors supplied, narrow the parameters to the resolved one for the checking that follows @@ -358,7 +361,8 @@ function TPkixCertPathValidator.Validate(const ACertPath: IPkixCertPath; const A if (LIndex = (LN - 1)) and LCert.Equals(LTrust.TrustedCert) then Continue; - raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SVersion1CACertificate, [LIndex]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.NotCACertificate, -1, @SVersion1CACertificate, [LIndex]); end; TRfc3280CertPathUtilities.PrepareNextCertA(ACertPath, LIndex); @@ -450,7 +454,8 @@ function TPkixCertPathValidator.Validate(const ACertPath: IPkixCertPath; const A Exit; end; - raise EPkixCertPathValidatorCryptoLibException.CreateRes(@SPolicyProcessingFailed); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.InvalidPolicy, -1, @SPolicyProcessingFailed); finally LCriticalExtensions.Free; LAcceptablePolicies.Free; diff --git a/CryptoLib/src/Pkix/ClpPkixCertPathValidatorReason.pas b/CryptoLib/src/Pkix/ClpPkixCertPathValidatorReason.pas new file mode 100644 index 00000000..aeb696b2 --- /dev/null +++ b/CryptoLib/src/Pkix/ClpPkixCertPathValidatorReason.pas @@ -0,0 +1,32 @@ +{ *********************************************************************************** } +{ * CryptoLib Library * } +{ * Author - Ugochukwu Mmaduekwe * } +{ * Github Repository * } +{ * * } +{ * Distributed under the MIT software license, see the accompanying file LICENSE * } +{ * or visit http://www.opensource.org/licenses/mit-license.php. * } +{ * * } +{ * Acknowledgements: * } +{ * * } +{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } +{ * the development of this library * } +{ * ******************************************************************************* * } + +(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) + +unit ClpPkixCertPathValidatorReason; + +{$I ..\Include\CryptoLib.inc} + +interface + +type + /// Why certification path validation failed (RFC 5280), for programmatic handling. + TPkixCertPathValidatorReason = (Unspecified, Expired, NotYetValid, Revoked, + UndeterminedRevocationStatus, InvalidSignature, AlgorithmConstrained, NameChaining, + InvalidKeyUsage, InvalidPolicy, NoTrustAnchor, UnrecognizedCriticalExtension, NotCACertificate, + PathTooLong, InvalidName, LimitExceeded); + +implementation + +end. diff --git a/CryptoLib/src/Pkix/ClpPkixCertPathValidatorUtilities.pas b/CryptoLib/src/Pkix/ClpPkixCertPathValidatorUtilities.pas index 5eab1dfe..6ed8bf62 100644 --- a/CryptoLib/src/Pkix/ClpPkixCertPathValidatorUtilities.pas +++ b/CryptoLib/src/Pkix/ClpPkixCertPathValidatorUtilities.pas @@ -41,6 +41,8 @@ interface ClpDsaParameters, ClpSubjectPublicKeyInfoFactory, ClpIPkixTypes, + ClpCertStatus, + ClpPkixCertPathValidatorReason, ClpPkixPolicyNode, ClpPkixParameters, ClpPkixCrlUtilities, @@ -86,6 +88,17 @@ TPkixCertPathValidatorUtilities = class sealed(TObject) class function GetCrlExtensions(const ACrl: IX509Crl): IX509Extensions; static; class procedure DoGetCertStatus(AValidDate: TDateTime; const ACrl: IX509Crl; const AIssuer: IX509Name; const ASerialNumber: TBigInteger; const ACertStatus: ICertStatus); static; + /// The CRL entry for (AIssuer, ASerialNumber), honouring indirect CRLs; nil if none. + class function GetCrlEntry(const ACrl: IX509Crl; const AIssuer: IX509Name; + const ASerialNumber: TBigInteger): IX509CrlEntry; static; + class function GetIndirectCrlEntry(const ACrl: IX509Crl; const ASerialNumber: TBigInteger; + const ACertIssuer: IX509Name): IX509CrlEntry; static; + /// An entry's certificate issuer, defaulting to the CRL issuer when absent. + class function GetEntryIssuer(const ACrl: IX509Crl; const AEntry: IX509CrlEntry): IX509Name; static; + /// RFC 5280 6.3.3: a revocation takes effect at its date, or at once for the + /// irreversible reasons. + class function IsRevocationEffective(AValidDate, ARevocationDate: TDateTime; + ACrlReason: Int32): Boolean; static; class function DoGetCompleteCrls(const ADistributionPoint: IDistributionPoint; const AIssuer: IX509Name; const ACrlSelect: IX509CrlStoreSelector; const APkixParams: IPkixParameters; AValidityDate: TDateTime): TCryptoLibGenericArray; static; @@ -333,7 +346,8 @@ class function TPkixCertPathValidatorUtilities.FindTrustAnchor(const ACert: IX50 end; if LHaveFailure then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@STrustAnchorValidationFailed, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.InvalidSignature, -1, @STrustAnchorValidationFailed, [LInvalidKeyMessage]); end; @@ -590,7 +604,9 @@ class procedure TPkixCertPathValidatorUtilities.CheckPolicyTreeSize(const APolic begin LTotal := LTotal + APolicyNodes[LIdx].Count; if LTotal > TCryptoLibConfig.X509.MaxPolicyNodes then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SPolicyTreeTooLarge, [TCryptoLibConfig.X509.MaxPolicyNodes]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.LimitExceeded, -1, @SPolicyTreeTooLarge, + [TCryptoLibConfig.X509.MaxPolicyNodes]); end; end; @@ -606,30 +622,94 @@ class procedure TPkixCertPathValidatorUtilities.GetCertStatus(AValidDate: TDateT DoGetCertStatus(AValidDate, ACrl, GetIssuerPrincipal(AAttrCert), AAttrCert.SerialNumber, ACertStatus); end; +class function TPkixCertPathValidatorUtilities.GetEntryIssuer(const ACrl: IX509Crl; + const AEntry: IX509CrlEntry): IX509Name; +begin + Result := AEntry.GetCertificateIssuer(); + if Result = nil then + Result := ACrl.IssuerDN; +end; + +class function TPkixCertPathValidatorUtilities.GetIndirectCrlEntry(const ACrl: IX509Crl; + const ASerialNumber: TBigInteger; const ACertIssuer: IX509Name): IX509CrlEntry; +var + LEntry: IX509CrlEntry; + LEntries: TCryptoLibGenericArray; + LIdx: Int32; +begin + // fast path: the first entry with this serial, accepted only if its issuer matches + LEntry := ACrl.GetRevokedCertificate(ASerialNumber); + if (LEntry <> nil) and EquivalentName(ACertIssuer, GetEntryIssuer(ACrl, LEntry)) then + begin + Result := LEntry; + Exit; + end; + + // the same serial may appear under another issuer, so scan for a full serial-and-issuer match + LEntries := ACrl.GetRevokedCertificates(); + for LIdx := 0 to System.High(LEntries) do + begin + LEntry := LEntries[LIdx]; + if LEntry.GetSerialNumber().Equals(ASerialNumber) and + EquivalentName(ACertIssuer, GetEntryIssuer(ACrl, LEntry)) then + begin + Result := LEntry; + Exit; + end; + end; + + Result := nil; +end; + +class function TPkixCertPathValidatorUtilities.GetCrlEntry(const ACrl: IX509Crl; + const AIssuer: IX509Name; const ASerialNumber: TBigInteger): IX509CrlEntry; +begin + if ACrl.IsIndirect then + begin + Result := GetIndirectCrlEntry(ACrl, ASerialNumber, AIssuer); + Exit; + end; + + // a direct CRL only covers certificates issued by the CRL issuer + if not EquivalentName(AIssuer, ACrl.IssuerDN) then + Result := nil + else + Result := ACrl.GetRevokedCertificate(ASerialNumber); +end; + +class function TPkixCertPathValidatorUtilities.IsRevocationEffective(AValidDate, + ARevocationDate: TDateTime; ACrlReason: Int32): Boolean; +begin + if AValidDate >= ARevocationDate then + begin + Result := True; + Exit; + end; + + // a revocation dated after the checked time still counts for the irreversible reasons + case ACrlReason of + TCrlReason.Unspecified, TCrlReason.KeyCompromise, TCrlReason.CACompromise, TCrlReason.AACompromise: + Result := True; + else + Result := False; + end; +end; + class procedure TPkixCertPathValidatorUtilities.DoGetCertStatus(AValidDate: TDateTime; const ACrl: IX509Crl; const AIssuer: IX509Name; const ASerialNumber: TBigInteger; const ACertStatus: ICertStatus); var LCrlEntry: IX509CrlEntry; - LIssuer: IX509Name; - LReasonCodeValue: Int32; + LReasonCode: TNullable; LExtensions: IX509Extensions; LParsed: IAsn1Object; LRevocationDate: TDateTime; begin - LCrlEntry := ACrl.GetRevokedCertificate(ASerialNumber); + LCrlEntry := GetCrlEntry(ACrl, AIssuer, ASerialNumber); if LCrlEntry = nil then Exit; - LIssuer := AIssuer; - - if (not EquivalentName(LIssuer, LCrlEntry.GetCertificateIssuer())) and - (not EquivalentName(LIssuer, ACrl.IssuerDN)) then - begin - Exit; - end; - - LReasonCodeValue := TCrlReason.Unspecified; + LReasonCode := TNullable.None; if LCrlEntry.HasExtensions then begin @@ -641,7 +721,7 @@ class procedure TPkixCertPathValidatorUtilities.DoGetCertStatus(AValidDate: TDat begin LParsed := LExtensions.GetExtensionParsedValue(TX509Extensions.ReasonCode); if LParsed <> nil then - LReasonCodeValue := TDerEnumerated.GetInstance(LParsed).IntValueExact; + LReasonCode := TNullable.Some(TDerEnumerated.GetInstance(LParsed).IntValueExact); end; except on E: Exception do @@ -650,21 +730,10 @@ class procedure TPkixCertPathValidatorUtilities.DoGetCertStatus(AValidDate: TDat end; end; - LRevocationDate := LCrlEntry.RevocationDate; - if AValidDate < LRevocationDate then - begin - // a revocation dated after the checked time still counts only for the irreversible reasons - case LReasonCodeValue of - TCrlReason.Unspecified, TCrlReason.KeyCompromise, TCrlReason.CACompromise, TCrlReason.AACompromise: - ; - else - Exit; - end; - end; - // RFC 5280 6.3.3 (i) or (j) - ACertStatus.Status := LReasonCodeValue; - ACertStatus.RevocationDate := TNullable.Some(LRevocationDate); + LRevocationDate := LCrlEntry.RevocationDate; + if IsRevocationEffective(AValidDate, LRevocationDate, TCertStatus.GetReason(LReasonCode)) then + ACertStatus.SetRevoked(LRevocationDate, LReasonCode); end; class function TPkixCertPathValidatorUtilities.GetNextWorkingKey(const ACerts @@ -849,7 +918,8 @@ class procedure TPkixCertPathValidatorUtilities.CheckCrlsNotEmpty( begin // an empty result is recoverable: another distribution point or mechanism may still settle the status if System.Length(ACrls) < 1 then - raise ERecoverablePkixCertPathValidatorCryptoLibException.CreateResFmt(@SNoCrlsFound, + raise ERecoverablePkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.UndeterminedRevocationStatus, -1, @SNoCrlsFound, [AIssuer.ToString()]); end; diff --git a/CryptoLib/src/Pkix/ClpPkixCrlRevocationChecker.pas b/CryptoLib/src/Pkix/ClpPkixCrlRevocationChecker.pas index 03f5a11c..d295803d 100644 --- a/CryptoLib/src/Pkix/ClpPkixCrlRevocationChecker.pas +++ b/CryptoLib/src/Pkix/ClpPkixCrlRevocationChecker.pas @@ -91,7 +91,7 @@ procedure TPkixCrlRevocationChecker.Check(const ACert: IX509Certificate); begin if E.Index >= 0 then raise; - raise EPkixCertPathValidatorCryptoLibException.CreateAt(LParameters.Index, E.Message); + raise EPkixCertPathValidatorCryptoLibException.CreateReason(E.Reason, LParameters.Index, E.Message); end; end; end; diff --git a/CryptoLib/src/Pkix/ClpRfc3280CertPathUtilities.pas b/CryptoLib/src/Pkix/ClpRfc3280CertPathUtilities.pas index 8d76e891..2593aa02 100644 --- a/CryptoLib/src/Pkix/ClpRfc3280CertPathUtilities.pas +++ b/CryptoLib/src/Pkix/ClpRfc3280CertPathUtilities.pas @@ -47,6 +47,7 @@ interface ClpPkixCertPathValidatorUtilities, ClpPkixCertRevocationCheckerParameters, ClpCertStatus, + ClpPkixCertPathValidatorReason, ClpReasonsMask, ClpArrayUtilities, ClpBigInteger, @@ -187,13 +188,6 @@ TRfc3280CertPathUtilities = class sealed(TObject) /// The anyPolicy policy identifier of RFC 5280 4.2.1.4. const AnyPolicy = TPkixCertPathValidatorUtilities.AnyPolicy; - /// - /// The RFC 5280 5.3.1 CRL reason code as its ASN.1 identifier, or 'unknown' when the code is - /// outside that enumeration. Public so the attribute certificate path (RFC 3281) reports - /// revocation with the same wording rather than carrying a second copy of the table. - /// - class function CrlReasonName(AReason: Int32): String; static; - /// /// RFC 5280 6.3.3 (b)(1): the CRL issuer must match the cRLIssuer field of the distribution /// point, and the CRL must then be an indirect CRL; otherwise it must match the certificate issuer. @@ -373,21 +367,8 @@ implementation uses ClpPkixCertPathBuilder; -const - CrlReasonNames: array [0 .. 10] of String = ('unspecified', 'keyCompromise', 'cACompromise', - 'affiliationChanged', 'superseded', 'cessationOfOperation', 'certificateHold', 'unknown', - 'removeFromCRL', 'privilegeWithdrawn', 'aACompromise'); - { TRfc3280CertPathUtilities } -class function TRfc3280CertPathUtilities.CrlReasonName(AReason: Int32): String; -begin - if (AReason >= 0) and (AReason <= System.High(CrlReasonNames)) then - Result := CrlReasonNames[AReason] - else - Result := 'unknown'; -end; - class function TRfc3280CertPathUtilities.ParseExtension(const AExtensionValue: IAsn1OctetString): IAsn1Object; begin if AExtensionValue = nil then @@ -1108,14 +1089,14 @@ class procedure TRfc3280CertPathUtilities.ProcessCrlI(AValidDate: TDateTime; con class procedure TRfc3280CertPathUtilities.ProcessCrlJ(AValidDate: TDateTime; const ACompleteCrl: IX509Crl; const ACert: IX509Certificate; const ACertStatus: ICertStatus); begin - if ACertStatus.Status = TCertStatus.Unrevoked then + if not ACertStatus.IsRevoked then TPkixCertPathValidatorUtilities.GetCertStatus(AValidDate, ACompleteCrl, ACert, ACertStatus); end; class procedure TRfc3280CertPathUtilities.ProcessCrlJ(AValidDate: TDateTime; const ACompleteCrl: IX509Crl; const AAttrCert: IX509V2AttributeCertificate; const ACertStatus: ICertStatus); begin - if ACertStatus.Status = TCertStatus.Unrevoked then + if not ACertStatus.IsRevoked then TPkixCertPathValidatorUtilities.GetCertStatus(AValidDate, ACompleteCrl, AAttrCert, ACertStatus); end; @@ -1147,7 +1128,7 @@ class procedure TRfc3280CertPathUtilities.CheckCrl(const ADistributionPoint: IDi for LIdx := 0 to System.High(LCrls) do begin - if (ACertStatus.Status <> TCertStatus.Unrevoked) or AReasonsMask.IsAllReasons then + if ACertStatus.IsRevoked or AReasonsMask.IsAllReasons then Break; LCrl := LCrls[LIdx]; @@ -1205,9 +1186,9 @@ class procedure TRfc3280CertPathUtilities.CheckCrl(const ADistributionPoint: IDi // (j) ProcessCrlJ(AValidityDate, LCrl, ACert, ACertStatus); - // (k) - if ACertStatus.Status = TCrlReason.RemoveFromCrl then - ACertStatus.Status := TCertStatus.Unrevoked; + // (k) a removeFromCRL entry lifts a revocation carried from a delta CRL + if ACertStatus.IsRevoked and (ACertStatus.Reason = TCrlReason.RemoveFromCrl) then + ACertStatus.SetUnrevoked(); AReasonsMask.AddReasons(LInterimReasonsMask); LValidCrlFound := True; @@ -1281,8 +1262,8 @@ class procedure TRfc3280CertPathUtilities.CheckCrls(const APkixParams: IPkixPara end; LIdx := 0; - while (LIdx <= System.High(LDistributionPoints)) and - (LCertStatus.Status = TCertStatus.Unrevoked) and (not LReasonsMask.IsAllReasons) do + while (LIdx <= System.High(LDistributionPoints)) and (not LCertStatus.IsRevoked) and + (not LReasonsMask.IsAllReasons) do begin try CheckCrl(LDistributionPoints[LIdx], LPkixParamsCrlDp, ACurrentDate, AValidityDate, ACert, @@ -1298,7 +1279,7 @@ class procedure TRfc3280CertPathUtilities.CheckCrls(const APkixParams: IPkixPara // when the status is still undetermined, repeat with any CRL issued by the certificate issuer // that no distribution point names - if (LCertStatus.Status = TCertStatus.Unrevoked) and (not LReasonsMask.IsAllReasons) then + if (not LCertStatus.IsRevoked) and (not LReasonsMask.IsAllReasons) then begin try // assume a distribution point with the reasons and cRLIssuer fields omitted and a @@ -1327,26 +1308,29 @@ class procedure TRfc3280CertPathUtilities.CheckCrls(const APkixParams: IPkixPara if not LValidCrlFound then begin if LLastMessage = '' then - raise EPkixCertPathValidatorCryptoLibException.CreateRes(@SNoValidCrlFound); - raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SCrlCheckFailed, [LLastMessage]); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.UndeterminedRevocationStatus, -1, @SNoValidCrlFound); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.UndeterminedRevocationStatus, -1, @SCrlCheckFailed, [LLastMessage]); end; - if LCertStatus.Status <> TCertStatus.Unrevoked then + // the certificate is undetermined when it was not found revoked and the CRLs checked did not + // cover all revocation reasons + if (not LCertStatus.IsRevoked) and (not LReasonsMask.IsAllReasons) then + raise EPkixCertPathValidatorCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.UndeterminedRevocationStatus, -1, @SCertStatusUndetermined); + + if LCertStatus.IsRevoked then begin - LFormattedDate := ''; + LFormattedDate := '(NO DATE)'; if LCertStatus.RevocationDate.HasValue then LFormattedDate := TPkixCertPathValidatorUtilities.FormatUtcInstant (LCertStatus.RevocationDate.Value); - raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SCertificateRevoked, - [LFormattedDate, CrlReasonName(LCertStatus.Status)]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.Revoked, -1, @SCertificateRevoked, + [LFormattedDate, LCertStatus.GetReasonText]); end; - - if (LCertStatus.Status = TCertStatus.Unrevoked) and (not LReasonsMask.IsAllReasons) then - LCertStatus.Status := TCertStatus.Undetermined; - - if LCertStatus.Status = TCertStatus.Undetermined then - raise EPkixCertPathValidatorCryptoLibException.CreateRes(@SCertStatusUndetermined); end; class procedure TRfc3280CertPathUtilities.ProcessCertA(const ACertPath: IPkixCertPath; @@ -1370,7 +1354,7 @@ class procedure TRfc3280CertPathUtilities.ProcessCertA(const ACertPath: IPkixCer LCert.Verify(AWorkingPublicKey); except on E: Exception do - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SSignatureValidationFailed, [E.Message]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.InvalidSignature, AIndex, @SSignatureValidationFailed, [E.Message]); end; end; @@ -1387,7 +1371,12 @@ class procedure TRfc3280CertPathUtilities.ProcessCertA(const ACertPath: IPkixCer LCert.CheckValidity(LValidityDate); except on E: Exception do - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SCertificateValidityFailed, [E.Message]); + if LValidityDate > LCert.NotAfter then + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.Expired, AIndex, @SCertificateValidityFailed, [E.Message]) + else + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason( + TPkixCertPathValidatorReason.NotYetValid, AIndex, @SCertificateValidityFailed, [E.Message]); end; // (a)(3) revocation status, settled by whatever mechanisms the checker holds. The checker @@ -1403,7 +1392,7 @@ class procedure TRfc3280CertPathUtilities.ProcessCertA(const ACertPath: IPkixCer // (a)(4) name chaining LIssuer := TPkixCertPathValidatorUtilities.GetIssuerPrincipal(LCert); if not LIssuer.Equivalent(AWorkingIssuerName, True) then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SNameChainingFailed, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.NameChaining, AIndex, @SNameChainingFailed, [LIssuer.ToString(), AWorkingIssuerName.ToString()]); end; @@ -1458,7 +1447,7 @@ class procedure TRfc3280CertPathUtilities.ProcessCertBC(const ACertPath: IPkixCe ANameConstraintValidator.CheckDN(LPrincipal); except on E: Exception do - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SSubtreeCheckFailed, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.InvalidName, AIndex, @SSubtreeCheckFailed, ['subject', E.Message]); end; @@ -1482,7 +1471,7 @@ class procedure TRfc3280CertPathUtilities.ProcessCertBC(const ACertPath: IPkixCe ANameConstraintValidator.CheckEmail(LEmails[LIdx]); except on E: Exception do - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SSubtreeCheckFailed, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.InvalidName, AIndex, @SSubtreeCheckFailed, ['subject alternative email', E.Message]); end; end; @@ -1504,7 +1493,7 @@ class procedure TRfc3280CertPathUtilities.ProcessCertBC(const ACertPath: IPkixCe ANameConstraintValidator.CheckName(LGenNames[LIdx]); except on E: Exception do - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SSubtreeCheckFailed, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.InvalidName, AIndex, @SSubtreeCheckFailed, ['subject alternative name', E.Message]); end; end; @@ -1546,10 +1535,10 @@ class procedure TRfc3280CertPathUtilities.PrepareNextCertA(const ACertPath: IPki end; if LIssuerDomainPolicy.GetID() = AnyPolicy then - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SIssuerDomainPolicyIsAnyPolicy); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.InvalidPolicy, AIndex, @SIssuerDomainPolicyIsAnyPolicy); if LSubjectDomainPolicy.GetID() = AnyPolicy then - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SSubjectDomainPolicyIsAnyPolicy); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.InvalidPolicy, AIndex, @SSubjectDomainPolicyIsAnyPolicy); end; end; @@ -1719,7 +1708,7 @@ class procedure TRfc3280CertPathUtilities.ProcessCertF(AIndex: Int32; begin // (f) if (AExplicitPolicy <= 0) and (AValidPolicyTree = nil) then - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SNoValidPolicyTree); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.InvalidPolicy, AIndex, @SNoValidPolicyTree); end; class function TRfc3280CertPathUtilities.PrepareCertB(const ACertPath: IPkixCertPath; AIndex: Int32; @@ -1963,7 +1952,7 @@ class procedure TRfc3280CertPathUtilities.ApplyNameConstraints( if AIndex < 0 then raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SPermittedSubtreesFailed, [E.Message]) else - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SPermittedSubtreesFailed, [E.Message]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.InvalidName, AIndex, @SPermittedSubtreesFailed, [E.Message]); end; end; end; @@ -1984,7 +1973,7 @@ class procedure TRfc3280CertPathUtilities.ApplyNameConstraints( if AIndex < 0 then raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SExcludedSubtreesFailed, [E.Message]) else - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SExcludedSubtreesFailed, [E.Message]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.InvalidName, AIndex, @SExcludedSubtreesFailed, [E.Message]); end; end; end; @@ -2141,7 +2130,7 @@ class function TRfc3280CertPathUtilities.PrepareNextCertK(const ACertPath: IPkix // (k) LParsed := GetCertExtension(LCert, TX509Extensions.BasicConstraints, 'basic constraints'); if LParsed = nil then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SIntermediateLacksBasicConstraints, [AIndex]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.NotCACertificate, AIndex, @SIntermediateLacksBasicConstraints, [AIndex]); try Result := TBasicConstraints.GetInstance(LParsed); @@ -2152,7 +2141,7 @@ class function TRfc3280CertPathUtilities.PrepareNextCertK(const ACertPath: IPkix end; if not Result.IsCA() then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SNotACACertificate, [AIndex]); + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.NotCACertificate, AIndex, @SNotACACertificate, [AIndex]); end; class function TRfc3280CertPathUtilities.PrepareNextCertL(const ACertPath: IPkixCertPath; AIndex: Int32; @@ -2166,7 +2155,7 @@ class function TRfc3280CertPathUtilities.PrepareNextCertL(const ACertPath: IPkix end; if AMaxPathLength <= 0 then - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SMaxPathLengthExhausted); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.PathTooLong, AIndex, @SMaxPathLengthExhausted); Result := AMaxPathLength - 1; end; @@ -2209,7 +2198,7 @@ class procedure TRfc3280CertPathUtilities.PrepareNextCertN(const ACertPath: IPki if (LKeyUsage <> nil) and ((System.Length(LKeyUsage) <= TPkixCertPathValidatorUtilities.KeyCertSign) or (not LKeyUsage[TPkixCertPathValidatorUtilities.KeyCertSign])) then begin - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SKeyUsageNoKeyCertSign); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.InvalidKeyUsage, AIndex, @SKeyUsageNoKeyCertSign); end; end; @@ -2267,7 +2256,7 @@ class procedure TRfc3280CertPathUtilities.PrepareNextCertO(const ACertPath: IPki end; if ACriticalExtensions.Count > 0 then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SUnsupportedCriticalExtensions, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.UnrecognizedCriticalExtension, AIndex, @SUnsupportedCriticalExtensions, [AIndex, JoinCriticalExtensions(ACriticalExtensions)]); end; @@ -2341,7 +2330,7 @@ class procedure TRfc3280CertPathUtilities.WrapupCertF(const ACertPath: IPkixCert end; if ACriticalExtensions.Count > 0 then - raise EPkixCertPathValidatorCryptoLibException.CreateResFmtAt(AIndex, @SUnsupportedCriticalExtensions, + raise EPkixCertPathValidatorCryptoLibException.CreateResFmtReason(TPkixCertPathValidatorReason.UnrecognizedCriticalExtension, AIndex, @SUnsupportedCriticalExtensions, [AIndex, JoinCriticalExtensions(ACriticalExtensions)]); end; @@ -2363,7 +2352,7 @@ class function TRfc3280CertPathUtilities.WrapupCertG(const ACertPath: IPkixCertP if LValidPolicyTree = nil then begin if APkixParams.IsExplicitPolicyRequired then - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SExplicitPolicyUnavailable); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.InvalidPolicy, AIndex, @SExplicitPolicyUnavailable); Result := nil; Exit; @@ -2375,7 +2364,7 @@ class function TRfc3280CertPathUtilities.WrapupCertG(const ACertPath: IPkixCertP if APkixParams.IsExplicitPolicyRequired then begin if AAcceptablePolicies.Count < 1 then - raise EPkixCertPathValidatorCryptoLibException.CreateResAt(AIndex, @SExplicitPolicyUnavailable); + raise EPkixCertPathValidatorCryptoLibException.CreateResReason(TPkixCertPathValidatorReason.InvalidPolicy, AIndex, @SExplicitPolicyUnavailable); // nodes outside the acceptable policies are not pruned here; the childless sweep below is // what constrains the tree diff --git a/CryptoLib/src/Pkix/ClpRfc3281CertPathUtilities.pas b/CryptoLib/src/Pkix/ClpRfc3281CertPathUtilities.pas index 4b8c68f8..f8af5c31 100644 --- a/CryptoLib/src/Pkix/ClpRfc3281CertPathUtilities.pas +++ b/CryptoLib/src/Pkix/ClpRfc3281CertPathUtilities.pas @@ -501,7 +501,7 @@ class procedure TRfc3281CertPathUtilities.CheckCrl(const ADistributionPoint: IDi for LIdx := 0 to System.High(LCrls) do begin - if (ACertStatus.Status <> TCertStatus.Unrevoked) or AReasonsMask.IsAllReasons then + if ACertStatus.IsRevoked or AReasonsMask.IsAllReasons then Break; LCrl := LCrls[LIdx]; @@ -559,9 +559,9 @@ class procedure TRfc3281CertPathUtilities.CheckCrl(const ADistributionPoint: IDi // (j) TRfc3280CertPathUtilities.ProcessCrlJ(AValidityDate, LCrl, AAttrCert, ACertStatus); - // (k) - if ACertStatus.Status = TCrlReason.RemoveFromCrl then - ACertStatus.Status := TCertStatus.Unrevoked; + // (k) a removeFromCRL entry lifts a revocation carried from a delta CRL + if ACertStatus.IsRevoked and (ACertStatus.Reason = TCrlReason.RemoveFromCrl) then + ACertStatus.SetUnrevoked(); AReasonsMask.AddReasons(LInterimReasonsMask); LValidCrlFound := True; @@ -648,8 +648,8 @@ class procedure TRfc3281CertPathUtilities.CheckCrls(const AAttrCert: IX509V2Attr end; LIdx := 0; - while (LIdx <= System.High(LDistributionPoints)) and - (LCertStatus.Status = TCertStatus.Unrevoked) and (not LReasonsMask.IsAllReasons) do + while (LIdx <= System.High(LDistributionPoints)) and (not LCertStatus.IsRevoked) and + (not LReasonsMask.IsAllReasons) do begin try CheckCrl(LDistributionPoints[LIdx], AAttrCert, LPkixParamsCrlDp, ACurrentDate, AValidityDate, @@ -665,7 +665,7 @@ class procedure TRfc3281CertPathUtilities.CheckCrls(const AAttrCert: IX509V2Attr // when the status is still undetermined, repeat with any CRL issued by the AC issuer that no // distribution point names - if (LCertStatus.Status = TCertStatus.Unrevoked) and (not LReasonsMask.IsAllReasons) then + if (not LCertStatus.IsRevoked) and (not LReasonsMask.IsAllReasons) then begin try // assume a distribution point with the reasons and cRLIssuer fields omitted and a @@ -692,21 +692,20 @@ class procedure TRfc3281CertPathUtilities.CheckCrls(const AAttrCert: IX509V2Attr raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SCrlCheckFailed, [LLastMessage]); end; - if LCertStatus.Status <> TCertStatus.Unrevoked then + // the attribute certificate is undetermined when it was not found revoked and the CRLs checked + // did not cover all revocation reasons + if (not LCertStatus.IsRevoked) and (not LReasonsMask.IsAllReasons) then + raise EPkixCertPathValidatorCryptoLibException.CreateRes(@SAttrCertStatusUndetermined); + + if LCertStatus.IsRevoked then begin - LFormattedDate := ''; + LFormattedDate := '(NO DATE)'; if LCertStatus.RevocationDate.HasValue then LFormattedDate := TPkixCertPathValidatorUtilities.FormatUtcInstant(LCertStatus.RevocationDate.Value); raise EPkixCertPathValidatorCryptoLibException.CreateResFmt(@SAttrCertRevoked, - [LFormattedDate, TRfc3280CertPathUtilities.CrlReasonName(LCertStatus.Status)]); + [LFormattedDate, LCertStatus.GetReasonText]); end; - - if (LCertStatus.Status = TCertStatus.Unrevoked) and (not LReasonsMask.IsAllReasons) then - LCertStatus.Status := TCertStatus.Undetermined; - - if LCertStatus.Status = TCertStatus.Undetermined then - raise EPkixCertPathValidatorCryptoLibException.CreateRes(@SAttrCertStatusUndetermined); end; end. diff --git a/CryptoLib/src/X509/ClpX509Crl.pas b/CryptoLib/src/X509/ClpX509Crl.pas index 0b0e0c8f..f265b34c 100644 --- a/CryptoLib/src/X509/ClpX509Crl.pas +++ b/CryptoLib/src/X509/ClpX509Crl.pas @@ -111,7 +111,8 @@ TCachedEncoding = class(TInterfacedObject, ICachedEncoding) function GetIssuerDN: IX509Name; function GetThisUpdate: TDateTime; function GetNextUpdate: TNullable; - function GetRevokedCertificate(const ASerialNumber: TBigInteger): IX509CrlEntry; + function GetRevokedCertificate(const ASerialNumber: TBigInteger): IX509CrlEntry; overload; + function GetRevokedCertificate(const ACert: IX509Certificate): IX509CrlEntry; overload; function GetRevokedCertificates: TCryptoLibGenericArray; function GetTbsCertList: TCryptoLibByteArray; function GetSignature: TCryptoLibByteArray; @@ -128,6 +129,7 @@ TCachedEncoding = class(TInterfacedObject, ICachedEncoding) procedure Verify(const AVerifierProvider: IVerifierFactoryProvider); overload; procedure VerifyAltSignature(const AVerifierProvider: IVerifierFactoryProvider); + function GetIsIndirect: Boolean; function IsRevoked(const ACert: IX509Certificate): Boolean; function Equals(const AOther: TObject): Boolean; reintroduce; overload; function Equals(const AOther: IX509Crl): Boolean; reintroduce; overload; @@ -330,6 +332,40 @@ function TX509Crl.GetRevokedCertificate(const ASerialNumber: TBigInteger): IX509 Result := nil; end; +function TX509Crl.GetRevokedCertificate(const ACert: IX509Certificate): IX509CrlEntry; +var + LRevoked: TCryptoLibGenericArray; + LPreviousIssuer, LCertIssuer: IX509Name; + LSerial: TBigInteger; + LI: Int32; + LEntry: IX509CrlEntry; +begin + LRevoked := FCertificateList.GetRevokedCertificates(); + if LRevoked = nil then + begin + Result := nil; + Exit; + end; + + // An indirect CRL may list the same serial number under more than one issuer, + // so a match requires both the serial number and the entry's effective issuer. + LSerial := ACert.SerialNumber; + LCertIssuer := ACert.IssuerDN; + LPreviousIssuer := GetIssuerDN(); + for LI := 0 to System.High(LRevoked) do + begin + LEntry := TX509CrlEntry.Create(LRevoked[LI], FIsIndirect, LPreviousIssuer); + if LRevoked[LI].UserCertificate.Value.Equals(LSerial) and + LCertIssuer.Equivalent(LEntry.GetCertificateIssuer(), True) then + begin + Result := LEntry; + Exit; + end; + LPreviousIssuer := LEntry.GetCertificateIssuer(); + end; + Result := nil; +end; + function TX509Crl.GetRevokedCertificates: TCryptoLibGenericArray; var LEntries: TCryptoLibGenericArray; @@ -461,24 +497,16 @@ function TX509Crl.CheckSignatureValid(const AVerifier: IVerifierFactory): Boolea Result := TX509Utilities.VerifySignature(AVerifier, LTbsCertList as IAsn1Encodable, FCertificateList.Signature); end; +function TX509Crl.GetIsIndirect: Boolean; +begin + Result := FIsIndirect; +end; + function TX509Crl.IsRevoked(const ACert: IX509Certificate): Boolean; -var - LRevoked: TCryptoLibGenericArray; - LSerial: TBigInteger; - LI: Int32; begin - LRevoked := FCertificateList.GetRevokedCertificates(); - if LRevoked <> nil then - begin - LSerial := ACert.GetSerialNumber(); - for LI := 0 to System.High(LRevoked) do - if LRevoked[LI].UserCertificate.Value.Equals(LSerial) then - begin - Result := True; - Exit; - end; - end; - Result := False; + // Match by issuer as well as serial number so an indirect CRL does not stop at + // another issuer's entry sharing the serial number. + Result := GetRevokedCertificate(ACert) <> nil; end; function TX509Crl.Equals(const AOther: TObject): Boolean; diff --git a/CryptoLib/src/X509/ClpX509CrlEntry.pas b/CryptoLib/src/X509/ClpX509CrlEntry.pas index 18124449..184d362e 100644 --- a/CryptoLib/src/X509/ClpX509CrlEntry.pas +++ b/CryptoLib/src/X509/ClpX509CrlEntry.pas @@ -178,6 +178,7 @@ function TX509CrlEntry.Equals(const AOther: IX509CrlEntry): Boolean; LSelfIntf: IX509CrlEntry; LThat: IX509CrlEntry; LThatObj: TX509CrlEntry; + LThisIssuer, LThatIssuer: IX509Name; begin LSelfIntf := Self; if AOther = LSelfIntf then @@ -202,7 +203,20 @@ function TX509CrlEntry.Equals(const AOther: IX509CrlEntry): Boolean; end; end; - Result := FCrlEntry.Equals(AOther.CrlEntry); + if not FCrlEntry.Equals(AOther.CrlEntry) then + begin + Result := False; + Exit; + end; + + // The same raw entry can carry a different inherited certificate issuer in an + // indirect CRL, so the effective issuer is part of identity. + LThisIssuer := GetCertificateIssuer(); + LThatIssuer := LThat.GetCertificateIssuer(); + if (LThisIssuer = nil) <> (LThatIssuer = nil) then + Result := False + else + Result := (LThisIssuer = nil) or LThisIssuer.Equivalent(LThatIssuer, True); end; function TX509CrlEntry.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} From 1c6e4cc2784194ff790661bb98f4051a6143455a Mon Sep 17 00:00:00 2001 From: Ugochukwu Mmaduekwe Date: Wed, 28 Oct 2026 23:28:08 +0100 Subject: [PATCH 2/2] Default a revoked entry's issuer to the CRL issuer when it has none A direct CRL carries no per-entry certificate issuer, so matching on issuer skipped every entry and X509Crl.IsRevoked reported direct-CRL revocations as not revoked. The entry issuer now falls back to the CRL issuer when absent. A regression test covers direct-CRL revocation by serial number. --- .../src/Pkix/CertPathHardeningTests.pas | 36 +++++++++++++++++++ CryptoLib/src/X509/ClpX509Crl.pas | 12 ++++--- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas b/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas index 63d03695..9e957f9f 100644 --- a/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas +++ b/CryptoLib.Tests/src/Pkix/CertPathHardeningTests.pas @@ -176,6 +176,7 @@ TIndirectCrlSerialCollisionTest = class(TCryptoLibAlgorithmTestCase) procedure SetUp; override; published procedure TestSameSerialUnderDifferentIssuerIsNotMasked; + procedure TestDirectCrlRevokesBySerial; end; implementation @@ -836,6 +837,41 @@ procedure TIndirectCrlSerialCollisionTest.TestSameSerialUnderDifferentIssuerIsNo 'a certificate sharing the serial number under a different issuer is not masked as revoked'); end; +procedure TIndirectCrlSerialCollisionTest.TestDirectCrlRevokesBySerial; +var + LCaKey, LSubjectKey: IAsymmetricCipherKeyPair; + LCaDn, LSubject: IX509Name; + LRevokedSerial, LOtherSerial: TBigInteger; + LCertRevoked, LCertOther: IX509Certificate; + LCrlGen: IX509V2CrlGenerator; + LCrl: IX509Crl; + LNow: TDateTime; +begin + LCaKey := TCertTestUtilities.GenerateRsaKeyPair(1024); + LSubjectKey := TCertTestUtilities.GenerateRsaKeyPair(1024); + LCaDn := TX509Name.Create('CN=CA, O=Test-PKI, C=DE'); + LSubject := TX509Name.Create('CN=EU, O=Test-PKI, C=DE'); + + LRevokedSerial := TBigInteger.ValueOf(4660); + LOtherSerial := TBigInteger.ValueOf(4661); + LCertRevoked := MakeCert(LRevokedSerial, LCaDn, LSubject, LSubjectKey); + LCertOther := MakeCert(LOtherSerial, LCaDn, LSubject, LSubjectKey); + + // an ordinary (direct) CRL issued by the CA; its entries carry no per-entry issuer + LNow := Now.ToUniversalTime(); + LCrlGen := TX509V2CrlGenerator.Create() as IX509V2CrlGenerator; + LCrlGen.SetIssuerDN(LCaDn); + LCrlGen.SetThisUpdateUtc(IncHour(LNow, -1)); + LCrlGen.SetNextUpdateUtc(IncMonth(LNow, 1)); + LCrlGen.AddCrlEntryUtc(LRevokedSerial, IncHour(LNow, -1), TCrlReason.KeyCompromise); + LCrl := LCrlGen.Generate(TAsn1SignatureFactory.Create(SigAlgorithm, + LCaKey.Private as IAsymmetricKeyParameter, FRandom) as ISignatureFactory); + + CheckTrue(LCrl.IsRevoked(LCertRevoked), 'a direct CRL reports its revoked certificate as revoked'); + CheckFalse(LCrl.IsRevoked(LCertOther), + 'a direct CRL does not report an unrevoked serial as revoked'); +end; + initialization {$IFDEF FPC} diff --git a/CryptoLib/src/X509/ClpX509Crl.pas b/CryptoLib/src/X509/ClpX509Crl.pas index f265b34c..9f7d390e 100644 --- a/CryptoLib/src/X509/ClpX509Crl.pas +++ b/CryptoLib/src/X509/ClpX509Crl.pas @@ -335,7 +335,7 @@ function TX509Crl.GetRevokedCertificate(const ASerialNumber: TBigInteger): IX509 function TX509Crl.GetRevokedCertificate(const ACert: IX509Certificate): IX509CrlEntry; var LRevoked: TCryptoLibGenericArray; - LPreviousIssuer, LCertIssuer: IX509Name; + LPreviousIssuer, LCertIssuer, LEntryIssuer: IX509Name; LSerial: TBigInteger; LI: Int32; LEntry: IX509CrlEntry; @@ -347,16 +347,20 @@ function TX509Crl.GetRevokedCertificate(const ACert: IX509Certificate): IX509Crl Exit; end; - // An indirect CRL may list the same serial number under more than one issuer, - // so a match requires both the serial number and the entry's effective issuer. + // An indirect CRL may list the same serial number under more than one issuer, so a match requires + // both the serial number and the entry's effective issuer, which defaults to the CRL issuer (a + // direct CRL has no per-entry issuer). LSerial := ACert.SerialNumber; LCertIssuer := ACert.IssuerDN; LPreviousIssuer := GetIssuerDN(); for LI := 0 to System.High(LRevoked) do begin LEntry := TX509CrlEntry.Create(LRevoked[LI], FIsIndirect, LPreviousIssuer); + LEntryIssuer := LEntry.GetCertificateIssuer(); + if LEntryIssuer = nil then + LEntryIssuer := GetIssuerDN(); if LRevoked[LI].UserCertificate.Value.Equals(LSerial) and - LCertIssuer.Equivalent(LEntry.GetCertificateIssuer(), True) then + LCertIssuer.Equivalent(LEntryIssuer, True) then begin Result := LEntry; Exit;