diff --git a/CryptoLib.Tests/src/Pkix/CertPathBuilderTests.pas b/CryptoLib.Tests/src/Pkix/CertPathBuilderTests.pas index 5850ab17..453924dc 100644 --- a/CryptoLib.Tests/src/Pkix/CertPathBuilderTests.pas +++ b/CryptoLib.Tests/src/Pkix/CertPathBuilderTests.pas @@ -46,6 +46,7 @@ interface ClpIX509Asn1Objects, ClpX509Asn1Objects, ClpX509ObjectIdentifiers, + ClpPkixCertPathValidatorReason, ClpBigInteger, ClpIAsymmetricCipherKeyPair, ClpIAsymmetricKeyParameter, @@ -63,9 +64,16 @@ interface /// TCertPathBuilderTest = class(TCryptoLibAlgorithmTestCase) strict private + var + FBuilder: IPkixCertPathBuilder; + function AnchorsOf(const ACert: IX509Certificate): TCryptoLibGenericArray; + /// Builds with FBuilder towards AAnchor and returns the reason of the failure. + function BuildFailureReason(const AAnchor: IX509Certificate; const ASubject: IX509Name; + const AStoreCerts: TCryptoLibGenericArray): TPkixCertPathValidatorReason; protected + procedure SetUp; override; procedure TearDown; override; published @@ -75,6 +83,14 @@ TCertPathBuilderTest = class(TCryptoLibAlgorithmTestCase) procedure TestBuildWithUnsignedTrustAnchor; procedure TestBuilderInstanceReuse; procedure TestNodeBudgetGuard; + procedure TestBuilderExceptionReasonDefaultsToUnspecified; + procedure TestBadSignatureUnderPooledIntermediate; + procedure TestBadSignatureDirectlyUnderAnchor; + procedure TestUnrecognizedCriticalExtensionOnLeaf; + procedure TestUnrecognizedCriticalExtensionOnIntermediate; + procedure TestExpiredOutranksCriticalExtension; + procedure TestInvalidSignatureOutranksCriticalExtension; + procedure TestCriticalExtensionOutranksNoIssuer; end; implementation @@ -87,6 +103,42 @@ function TCertPathBuilderTest.AnchorsOf(const ACert: IX509Certificate) Result := TCryptoLibGenericArray.Create(TTrustAnchor.Create(ACert, nil) as ITrustAnchor); end; +procedure TCertPathBuilderTest.SetUp; +begin + inherited SetUp; + FBuilder := TPkixCertPathBuilder.Create() as IPkixCertPathBuilder; +end; + +function TCertPathBuilderTest.BuildFailureReason(const AAnchor: IX509Certificate; const ASubject: IX509Name; + const AStoreCerts: TCryptoLibGenericArray): TPkixCertPathValidatorReason; +var + LSelector: IX509CertStoreSelector; + LTarget: ISelector; + LStore: IStore; + LParams: IPkixBuilderParameters; +begin + LSelector := TX509CertStoreSelector.Create(); + LSelector.Subject := ASubject; + LTarget := LSelector; + LStore := TCollectionStore.Create(AStoreCerts); + LParams := TPkixBuilderParameters.Create(AnchorsOf(AAnchor), LTarget) as IPkixBuilderParameters; + LParams.SetTargetConstraintsCert(LTarget); + LParams.AddStoreCert(LStore); + LParams.IsRevocationEnabled := False; + + Result := TPkixCertPathValidatorReason.Unspecified; + try + FBuilder.Build(LParams); + except + on E: EPkixCertPathBuilderCryptoLibException do + begin + Result := E.Reason; + Exit; + end; + end; + Fail('the build was expected to fail'); +end; + procedure TCertPathBuilderTest.TearDown; begin // the node budget is a process-wide switch; restore it so a lowered value cannot leak to later tests @@ -262,14 +314,12 @@ procedure TCertPathBuilderTest.TestBuildWithUnsignedTrustAnchor; procedure TCertPathBuilderTest.TestBuilderInstanceReuse; var LRootKp, LEeKp, LOtherKp: IAsymmetricCipherKeyPair; - LRoot, LEe, LOther: IX509Certificate; + LRoot, LEe, LOther, LBadSignature: IX509Certificate; LSelector: IX509CertStoreSelector; LTarget: ISelector; LStore: IStore; LParams: IPkixBuilderParameters; - LBuilder: IPkixCertPathBuilder; LResult: IPkixCertPathBuilderResult; - LRaised: Boolean; begin LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); @@ -278,29 +328,22 @@ procedure TCertPathBuilderTest.TestBuilderInstanceReuse; LRootKp.Private as IAsymmetricKeyParameter, LRoot); LOtherKp := TCertTestUtilities.GenerateRsaKeyPair(1024); LOther := TCertTestUtilities.GenerateRootCert(LOtherKp, TX509Name.Create('CN=Unrelated CA') as IX509Name); + LBadSignature := TCertTestUtilities.GenerateEndEntityCert(LEeKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Bad Signature') as IX509Name, LOtherKp.Private as IAsymmetricKeyParameter, LRoot); - // one builder instance is reused across two builds - LBuilder := TPkixCertPathBuilder.Create() as IPkixCertPathBuilder; + // one builder instance is reused across three builds - // 1) the end-entity does not chain to the (unrelated) trust anchor: no path - LSelector := TX509CertStoreSelector.Create(); - LSelector.Subject := LEe.SubjectDN; - LTarget := LSelector; - LStore := TCollectionStore.Create( - TCryptoLibGenericArray.Create(LEe)); - LParams := TPkixBuilderParameters.Create(AnchorsOf(LOther), LTarget) as IPkixBuilderParameters; - LParams.SetTargetConstraintsCert(LTarget); - LParams.AddStoreCert(LStore); - LParams.IsRevocationEnabled := False; + // 0) a leaf the anchor it names did not sign leaves an invalid-signature failure behind + CheckEquals(Ord(TPkixCertPathValidatorReason.InvalidSignature), + Ord(BuildFailureReason(LRoot, LBadSignature.SubjectDN, + TCryptoLibGenericArray.Create(LBadSignature))), + 'the first build reports the invalid signature'); - LRaised := False; - try - LBuilder.Build(LParams); - except - on E: EPkixCertPathBuilderCryptoLibException do - LRaised := True; - end; - CheckTrue(LRaised, 'the first build finds no chain to the unrelated trust anchor'); + // 1) the end-entity does not chain to the (unrelated) trust anchor: no path, and the earlier + // failure must not be reported + CheckEquals(Ord(TPkixCertPathValidatorReason.NoTrustAnchor), + Ord(BuildFailureReason(LOther, LEe.SubjectDN, TCryptoLibGenericArray.Create(LEe))), + 'the second build finds no issuer for the end-entity'); // 2) the SAME builder instance must still find a valid chain to the correct anchor LSelector := TX509CertStoreSelector.Create(); @@ -313,7 +356,7 @@ procedure TCertPathBuilderTest.TestBuilderInstanceReuse; LParams.AddStoreCert(LStore); LParams.IsRevocationEnabled := False; - LResult := LBuilder.Build(LParams); + LResult := FBuilder.Build(LParams); CheckNotNull(LResult, 'reusing the builder after a failed build still finds a valid chain'); CheckEquals(1, System.Length(LResult.CertPath.Certificates), 'the reused builder returns the single end-entity certificate below the trust anchor'); @@ -330,6 +373,7 @@ procedure TCertPathBuilderTest.TestNodeBudgetGuard; LBuilder: IPkixCertPathBuilder; LRaised: Boolean; LMessage: String; + LReason: TPkixCertPathValidatorReason; begin LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); @@ -356,6 +400,7 @@ procedure TCertPathBuilderTest.TestNodeBudgetGuard; LRaised := False; LMessage := ''; + LReason := TPkixCertPathValidatorReason.Unspecified; try LBuilder := TPkixCertPathBuilder.Create() as IPkixCertPathBuilder; LBuilder.Build(LParams); @@ -364,12 +409,190 @@ procedure TCertPathBuilderTest.TestNodeBudgetGuard; begin LRaised := True; LMessage := E.Message; + LReason := E.Reason; end; end; CheckTrue(LRaised, 'exceeding the node budget aborts the build'); CheckTrue(Pos('node limit', LMessage) > 0, Format('the failure names the node limit, got "%s"', [LMessage])); + CheckEquals(Ord(TPkixCertPathValidatorReason.LimitExceeded), Ord(LReason), + 'exceeding the node budget reports the limit'); +end; + +procedure TCertPathBuilderTest.TestBuilderExceptionReasonDefaultsToUnspecified; +var + LPlain, LWithReason: EPkixCertPathBuilderCryptoLibException; +begin + LPlain := EPkixCertPathBuilderCryptoLibException.Create('plain'); + try + CheckEquals(Ord(TPkixCertPathValidatorReason.Unspecified), Ord(LPlain.Reason), + 'an exception built without a reason reports Unspecified'); + finally + LPlain.Free; + end; + + LWithReason := EPkixCertPathBuilderCryptoLibException.CreateReason( + TPkixCertPathValidatorReason.Revoked, 'revoked'); + try + CheckEquals(Ord(TPkixCertPathValidatorReason.Revoked), Ord(LWithReason.Reason), + 'the reason given at construction is kept'); + CheckEquals('revoked', LWithReason.Message, 'the message is kept'); + finally + LWithReason.Free; + end; +end; + +procedure TCertPathBuilderTest.TestBadSignatureUnderPooledIntermediate; +var + LRootKp, LInterKp, LLeafKp, LOtherKp: IAsymmetricCipherKeyPair; + LRoot, LInter, LLeaf: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LInterKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LInter := TCertTestUtilities.GenerateEndEntityCert(LInterKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Intermediate') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LOtherKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + // the leaf names the intermediate as its issuer but is signed with another key + LLeaf := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LOtherKp.Private as IAsymmetricKeyParameter, LInter); + + CheckEquals(Ord(TPkixCertPathValidatorReason.InvalidSignature), + Ord(BuildFailureReason(LRoot, LLeaf.SubjectDN, + TCryptoLibGenericArray.Create(LInter, LLeaf))), + 'a leaf not signed by its pooled issuer reports an invalid signature'); +end; + +procedure TCertPathBuilderTest.TestBadSignatureDirectlyUnderAnchor; +var + LRootKp, LLeafKp, LOtherKp: IAsymmetricCipherKeyPair; + LRoot, LLeaf: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LOtherKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + // the leaf names the trust anchor as its issuer but is signed with another key + LLeaf := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LOtherKp.Private as IAsymmetricKeyParameter, LRoot); + + CheckEquals(Ord(TPkixCertPathValidatorReason.InvalidSignature), + Ord(BuildFailureReason(LRoot, LLeaf.SubjectDN, TCryptoLibGenericArray.Create(LLeaf))), + 'a leaf not signed by the anchor it names reports an invalid signature'); +end; + +procedure TCertPathBuilderTest.TestUnrecognizedCriticalExtensionOnLeaf; +var + LRootKp, LLeafKp: IAsymmetricCipherKeyPair; + LRoot, LLeaf: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LLeaf := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot, + '2.999.1', False); + + CheckEquals(Ord(TPkixCertPathValidatorReason.UnrecognizedCriticalExtension), + Ord(BuildFailureReason(LRoot, LLeaf.SubjectDN, TCryptoLibGenericArray.Create(LLeaf))), + 'an unprocessed critical extension on the leaf is reported'); +end; + +procedure TCertPathBuilderTest.TestUnrecognizedCriticalExtensionOnIntermediate; +var + LRootKp, LInterKp, LLeafKp: IAsymmetricCipherKeyPair; + LRoot, LInter, LLeaf: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LInterKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LInter := TCertTestUtilities.GenerateEndEntityCert(LInterKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Intermediate') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot, + '2.999.1', False); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LLeaf := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LInterKp.Private as IAsymmetricKeyParameter, LInter); + + CheckEquals(Ord(TPkixCertPathValidatorReason.UnrecognizedCriticalExtension), + Ord(BuildFailureReason(LRoot, LLeaf.SubjectDN, + TCryptoLibGenericArray.Create(LInter, LLeaf))), + 'an unprocessed critical extension on an intermediate is reported'); +end; + +procedure TCertPathBuilderTest.TestExpiredOutranksCriticalExtension; +var + LRootKp, LLeafKp: IAsymmetricCipherKeyPair; + LRoot, LExpired, LCritical: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LExpired := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot, '', True); + LCritical := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot, + '2.999.1', False); + + // the winner must not depend on which candidate is tried last + CheckEquals(Ord(TPkixCertPathValidatorReason.Expired), + Ord(BuildFailureReason(LRoot, LExpired.SubjectDN, + TCryptoLibGenericArray.Create(LExpired, LCritical))), + 'expired outranks an unprocessed critical extension when tried first'); + CheckEquals(Ord(TPkixCertPathValidatorReason.Expired), + Ord(BuildFailureReason(LRoot, LExpired.SubjectDN, + TCryptoLibGenericArray.Create(LCritical, LExpired))), + 'expired outranks an unprocessed critical extension when tried last'); +end; + +procedure TCertPathBuilderTest.TestInvalidSignatureOutranksCriticalExtension; +var + LRootKp, LLeafKp, LOtherKp: IAsymmetricCipherKeyPair; + LRoot, LBadSignature, LCritical: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LOtherKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LBadSignature := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LOtherKp.Private as IAsymmetricKeyParameter, LRoot); + LCritical := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot, + '2.999.1', False); + + CheckEquals(Ord(TPkixCertPathValidatorReason.InvalidSignature), + Ord(BuildFailureReason(LRoot, LBadSignature.SubjectDN, + TCryptoLibGenericArray.Create(LBadSignature, LCritical))), + 'an invalid signature outranks an unprocessed critical extension when tried first'); + CheckEquals(Ord(TPkixCertPathValidatorReason.InvalidSignature), + Ord(BuildFailureReason(LRoot, LBadSignature.SubjectDN, + TCryptoLibGenericArray.Create(LCritical, LBadSignature))), + 'an invalid signature outranks an unprocessed critical extension when tried last'); +end; + +procedure TCertPathBuilderTest.TestCriticalExtensionOutranksNoIssuer; +var + LRootKp, LLeafKp, LAbsentKp: IAsymmetricCipherKeyPair; + LRoot, LAbsent, LCritical, LOrphan: IX509Certificate; +begin + LRootKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LRoot := TCertTestUtilities.GenerateRootCert(LRootKp); + LLeafKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LAbsentKp := TCertTestUtilities.GenerateRsaKeyPair(1024); + LAbsent := TCertTestUtilities.GenerateRootCert(LAbsentKp, TX509Name.Create('CN=Absent CA') as IX509Name); + LCritical := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LRootKp.Private as IAsymmetricKeyParameter, LRoot, + '2.999.1', False); + // same subject, but its issuer is neither a trust anchor nor in the store + LOrphan := TCertTestUtilities.GenerateEndEntityCert(LLeafKp.Public as IAsymmetricKeyParameter, + TX509Name.Create('CN=Leaf') as IX509Name, LAbsentKp.Private as IAsymmetricKeyParameter, LAbsent); + + // the orphan is tried last, so only the ranking keeps the critical-extension failure + CheckEquals(Ord(TPkixCertPathValidatorReason.UnrecognizedCriticalExtension), + Ord(BuildFailureReason(LRoot, LCritical.SubjectDN, + TCryptoLibGenericArray.Create(LCritical, LOrphan))), + 'an unprocessed critical extension outranks a candidate with no issuer'); end; initialization diff --git a/CryptoLib.Tests/src/Utils/CertTestUtilities.pas b/CryptoLib.Tests/src/Utils/CertTestUtilities.pas index 85c358d5..9b896ce1 100644 --- a/CryptoLib.Tests/src/Utils/CertTestUtilities.pas +++ b/CryptoLib.Tests/src/Utils/CertTestUtilities.pas @@ -42,7 +42,9 @@ interface ClpAsn1SignatureFactory, ClpISignatureFactory, ClpIX509Certificate, + ClpIAsn1Core, ClpIAsn1Objects, + ClpAsn1Objects, ClpIX509Asn1Objects, ClpX509Asn1Objects, ClpX509ExtensionUtilities, @@ -68,7 +70,7 @@ TCertTestUtilities = class sealed(TObject) class function CreateCert(const ASignerName: IX509Name; const ASignerKey: IAsymmetricKeyParameter; const ADn: IX509Name; const ASigName: String; const AExtensions: IX509Extensions; - const APubKey: IAsymmetricKeyParameter): IX509Certificate; static; + const APubKey: IAsymmetricKeyParameter; AExpired: Boolean): IX509Certificate; static; public class constructor Create; @@ -90,6 +92,11 @@ TCertTestUtilities = class sealed(TObject) class function GenerateEndEntityCert(const AEntityKey: IAsymmetricKeyParameter; const ASubject: IX509Name; const ACaKey: IAsymmetricKeyParameter; const ACaCert: IX509Certificate): IX509Certificate; overload; static; + /// As above; ACriticalOid, when set, adds a critical extension nothing processes. + class function GenerateEndEntityCert(const AEntityKey: IAsymmetricKeyParameter; + const ASubject: IX509Name; const ACaKey: IAsymmetricKeyParameter; + const ACaCert: IX509Certificate; const ACriticalOid: String; AExpired: Boolean) + : IX509Certificate; overload; static; /// Generate an end-entity certificate with a single extended key usage. class function GenerateEndEntityCert(const AEntityKey: IAsymmetricKeyParameter; const ASubject: IX509Name; const AKeyPurpose: IDerObjectIdentifier; @@ -167,7 +174,7 @@ class function TCertTestUtilities.CreateSelfSignedCert(const ADn: IX509Name; con class function TCertTestUtilities.CreateCert(const ASignerName: IX509Name; const ASignerKey: IAsymmetricKeyParameter; const ADn: IX509Name; const ASigName: String; const AExtensions: IX509Extensions; - const APubKey: IAsymmetricKeyParameter): IX509Certificate; + const APubKey: IAsymmetricKeyParameter; AExpired: Boolean): IX509Certificate; var LGen: IX509V3CertificateGenerator; LUtcNow: TDateTime; @@ -178,8 +185,16 @@ class function TCertTestUtilities.CreateCert(const ASignerName: IX509Name; LGen := TX509V3CertificateGenerator.Create; LGen.SetSerialNumber(TBigInteger.ValueOf(NextSerialNumber)); LGen.SetIssuerDN(ASignerName); - LGen.SetNotBeforeUtc(IncSecond(LUtcNow, -5)); - LGen.SetNotAfterUtc(IncMinute(LUtcNow, 30)); + if AExpired then + begin + LGen.SetNotBeforeUtc(IncMinute(LUtcNow, -60)); + LGen.SetNotAfterUtc(IncMinute(LUtcNow, -10)); + end + else + begin + LGen.SetNotBeforeUtc(IncSecond(LUtcNow, -5)); + LGen.SetNotAfterUtc(IncMinute(LUtcNow, 30)); + end; LGen.SetSubjectDN(ADn); LGen.SetPublicKey(APubKey); LGen.AddExtensions(AExtensions); @@ -212,6 +227,13 @@ class function TCertTestUtilities.GenerateEndEntityCert(const AEntityKey, ACaKey class function TCertTestUtilities.GenerateEndEntityCert(const AEntityKey: IAsymmetricKeyParameter; const ASubject: IX509Name; const ACaKey: IAsymmetricKeyParameter; const ACaCert: IX509Certificate): IX509Certificate; +begin + Result := GenerateEndEntityCert(AEntityKey, ASubject, ACaKey, ACaCert, '', False); +end; + +class function TCertTestUtilities.GenerateEndEntityCert(const AEntityKey: IAsymmetricKeyParameter; + const ASubject: IX509Name; const ACaKey: IAsymmetricKeyParameter; + const ACaCert: IX509Certificate; const ACriticalOid: String; AExpired: Boolean): IX509Certificate; var LCaCertLw: IX509CertificateStructure; LExtGen: IX509ExtensionsGenerator; @@ -229,7 +251,11 @@ class function TCertTestUtilities.GenerateEndEntityCert(const AEntityKey: IAsymm LExtGen.AddExtension(TX509Extensions.BasicConstraints, True, TBasicConstraints.Create(0) as IBasicConstraints); LExtGen.AddExtension(TX509Extensions.KeyUsage, True, TKeyUsage.Create(TKeyUsage.DigitalSignature or TKeyUsage.KeyCertSign or TKeyUsage.CrlSign) as IKeyUsage); - Result := CreateCert(LCaCertLw.Subject, ACaKey, ASubject, 'SHA256withRSA', LExtGen.Generate, AEntityKey); + if ACriticalOid <> '' then + LExtGen.AddExtension(TDerObjectIdentifier.Create(ACriticalOid) as IDerObjectIdentifier, True, + TDerNull.Instance as IAsn1Encodable); + Result := CreateCert(LCaCertLw.Subject, ACaKey, ASubject, 'SHA256withRSA', LExtGen.Generate, AEntityKey, + AExpired); end; class function TCertTestUtilities.GenerateEndEntityCert(const AEntityKey: IAsymmetricKeyParameter; @@ -279,7 +305,8 @@ class function TCertTestUtilities.GenerateEndEntityCert(const AEntityKey: IAsymm TExtendedKeyUsage.Create(LUsages) as IExtendedKeyUsage); end; - Result := CreateCert(LCaCertLw.Subject, ACaKey, ASubject, 'SHA256withRSA', LExtGen.Generate, AEntityKey); + Result := CreateCert(LCaCertLw.Subject, ACaKey, ASubject, 'SHA256withRSA', LExtGen.Generate, AEntityKey, + False); end; class procedure TCertTestUtilities.AssertCertParses(const ACertId: string); diff --git a/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas b/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas index 337203a8..1778e1e0 100644 --- a/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas +++ b/CryptoLib/src/Misc/ClpCryptoLibExceptions.pas @@ -60,9 +60,30 @@ ECertificateCryptoLibException = class(ECryptoLibException); ECrlCryptoLibException = class(ECryptoLibException); EPkcsCryptoLibException = class(ECryptoLibException); EPkcsIOCryptoLibException = class(EIOCryptoLibException); - EPkixCertPathBuilderCryptoLibException = class(ECryptoLibException); EOcspCryptoLibException = class(ECryptoLibException); + /// + /// Raised when no certification path can be built. gives the most specific + /// cause among the candidate paths tried, Unspecified when none was set. + /// + EPkixCertPathBuilderCryptoLibException = class(ECryptoLibException) + + strict private + var + FReason: TPkixCertPathValidatorReason; + + public + /// As Create, but records a reason. + constructor CreateReason(AReason: TPkixCertPathValidatorReason; const AMsg: String); + /// As CreateRes, but records a reason. + constructor CreateResReason(AReason: TPkixCertPathValidatorReason; AResStringRec: PResStringRec); + /// As CreateResFmt, but records a reason. + constructor CreateResFmtReason(AReason: TPkixCertPathValidatorReason; + AResStringRec: PResStringRec; const AArgs: array of const); + + property Reason: TPkixCertPathValidatorReason read FReason; + end; + /// /// Raised when certification path validation fails. /// @@ -135,6 +156,30 @@ EBip327InvalidContributionCryptoLibException = class(ECryptoLibException) implementation +{ EPkixCertPathBuilderCryptoLibException } + +constructor EPkixCertPathBuilderCryptoLibException.CreateReason( + AReason: TPkixCertPathValidatorReason; const AMsg: String); +begin + inherited Create(AMsg); + FReason := AReason; +end; + +constructor EPkixCertPathBuilderCryptoLibException.CreateResReason( + AReason: TPkixCertPathValidatorReason; AResStringRec: PResStringRec); +begin + inherited CreateRes(AResStringRec); + FReason := AReason; +end; + +constructor EPkixCertPathBuilderCryptoLibException.CreateResFmtReason( + AReason: TPkixCertPathValidatorReason; AResStringRec: PResStringRec; + const AArgs: array of const); +begin + inherited CreateResFmt(AResStringRec, AArgs); + FReason := AReason; +end; + { EPkixCertPathValidatorCryptoLibException } constructor EPkixCertPathValidatorCryptoLibException.CreateAt(AIndex: Int32; const AMsg: String); diff --git a/CryptoLib/src/Pkix/ClpPkixCertPathBuilder.pas b/CryptoLib/src/Pkix/ClpPkixCertPathBuilder.pas index a37c8432..7718a849 100644 --- a/CryptoLib/src/Pkix/ClpPkixCertPathBuilder.pas +++ b/CryptoLib/src/Pkix/ClpPkixCertPathBuilder.pas @@ -28,6 +28,7 @@ interface ClpPkixCertPath, ClpPkixCertPathValidator, ClpPkixCertPathValidatorResult, + ClpPkixCertPathValidatorReason, ClpPkixCertPathValidatorUtilities, ClpCryptoLibConfig, ClpCryptoLibTypes, @@ -51,7 +52,7 @@ interface /// anchor, following the path building and validation algorithm of RFC 5280 6.1. /// /// - /// One instance carries the last build failure across its recursion, so it is neither reentrant + /// One instance carries the build's failure state across its recursion, so it is neither reentrant /// nor thread safe: callers sharing an instance must serialize access themselves. /// TPkixCertPathBuilder = class(TInterfacedObject, IPkixCertPathBuilder) @@ -59,8 +60,10 @@ TPkixCertPathBuilder = class(TInterfacedObject, IPkixCertPathBuilder) strict private var FIsForCrlCheck: Boolean; - /// The failure of the most recently tried chain, carried across the recursion. - FCertPathException: String; + /// The most specific failure of the chains tried so far, carried across the recursion. + FHasFailure: Boolean; + FFailureMessage: String; + FFailureReason: TPkixCertPathValidatorReason; /// Per-build node-visit budget (from config) and running count, bounding the DFS. FMaxNodes: Int32; FNodesVisited: Int32; @@ -73,6 +76,11 @@ TPkixCertPathBuilder = class(TInterfacedObject, IPkixCertPathBuilder) const ACert: IX509Certificate); static; class function ToCertArray(const ACerts: TList) : TCryptoLibGenericArray; static; + class function FailureRank(AReason: TPkixCertPathValidatorReason): Int32; static; + class function ReasonOf(const AException: Exception): TPkixCertPathValidatorReason; static; + + /// Keeps the failure unless one of higher rank is already remembered. + procedure RememberFailure(const AMessage: String; AReason: TPkixCertPathValidatorReason); /// Try to complete ATbvPath through ATbvCert; nil when no chain could be built. function BuildPath(const ATbvCert: IX509Certificate; const AParams: IPkixBuilderParameters; @@ -164,6 +172,53 @@ class function TPkixCertPathBuilder.ToCertArray(const ACerts: TList) : IPkixCertPathBuilderResult; @@ -173,6 +228,7 @@ function TPkixCertPathBuilder.BuildPath(const ATbvCert: IX509Certificate; LValidatorResult: IPkixCertPathValidatorResult; LIssuers: TCryptoLibGenericArray; LIdx: Int32; + LIsAnchored: Boolean; begin Result := nil; @@ -200,7 +256,19 @@ function TPkixCertPathBuilder.BuildPath(const ATbvCert: IX509Certificate; try try - if TPkixCertPathValidatorUtilities.IsIssuerTrustAnchor(ATbvCert, AParams.GetTrustAnchors()) then + LIsAnchored := False; + try + LIsAnchored := TPkixCertPathValidatorUtilities.FindTrustAnchor(ATbvCert, + AParams.GetTrustAnchors()) <> nil; + except + on E: EPkixCertPathValidatorCryptoLibException do + // a named anchor whose key does not verify the certificate; pooled issuers may still work + RememberFailure(E.Message, E.Reason); + on Exception do + ; + end; + + if LIsAnchored then begin try LCertPath := TPkixCertPath.Create(ToCertArray(ATbvPath)) as IPkixCertPath; @@ -215,8 +283,8 @@ function TPkixCertPathBuilder.BuildPath(const ATbvCert: IX509Certificate; LValidatorResult := LValidator.Validate(LCertPath, AParams); except on E: Exception do - raise EPkixCertPathBuilderCryptoLibException.CreateResFmt(@SCertPathValidationFailed, - [E.Message]); + raise EPkixCertPathBuilderCryptoLibException.CreateResFmtReason(ReasonOf(E), + @SCertPathValidationFailed, [E.Message]); end; // the path is kept: this chain is the answer @@ -241,7 +309,8 @@ function TPkixCertPathBuilder.BuildPath(const ATbvCert: IX509Certificate; end; if System.Length(LIssuers) < 1 then - raise EPkixCertPathBuilderCryptoLibException.CreateRes(@SNoIssuerCertFound); + raise EPkixCertPathBuilderCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.NoTrustAnchor, @SNoIssuerCertFound); for LIdx := 0 to System.High(LIssuers) do begin @@ -256,7 +325,7 @@ function TPkixCertPathBuilder.BuildPath(const ATbvCert: IX509Certificate; on E: Exception do begin // remembered for the caller; other candidate chains may still succeed - FCertPathException := E.Message; + RememberFailure(E.Message, ReasonOf(E)); Result := nil; end; end; @@ -274,7 +343,9 @@ function TPkixCertPathBuilder.Build(const AParams: IPkixBuilderParameters): IPki LIdx: Int32; begin Result := nil; - FCertPathException := ''; + FHasFailure := False; + FFailureMessage := ''; + FFailureReason := TPkixCertPathValidatorReason.Unspecified; FMaxNodes := TCryptoLibConfig.X509.MaxCertPathBuildNodes; FNodesVisited := 0; @@ -293,7 +364,8 @@ function TPkixCertPathBuilder.Build(const AParams: IPkixBuilderParameters): IPki end; except on E: ENodeBudgetExceededCryptoLibException do - raise EPkixCertPathBuilderCryptoLibException.Create(E.Message); + raise EPkixCertPathBuilderCryptoLibException.CreateReason( + TPkixCertPathValidatorReason.LimitExceeded, E.Message); end; finally LPath.Free; @@ -302,10 +374,11 @@ function TPkixCertPathBuilder.Build(const AParams: IPkixBuilderParameters): IPki if Result <> nil then Exit; - if FCertPathException <> '' then - raise EPkixCertPathBuilderCryptoLibException.Create(FCertPathException); + if FHasFailure then + raise EPkixCertPathBuilderCryptoLibException.CreateReason(FFailureReason, FFailureMessage); - raise EPkixCertPathBuilderCryptoLibException.CreateRes(@SCertPathNotFound); + raise EPkixCertPathBuilderCryptoLibException.CreateResReason( + TPkixCertPathValidatorReason.NoTrustAnchor, @SCertPathNotFound); end; end.