From 20344f7080241c177287abbc5da202b4178a2a28 Mon Sep 17 00:00:00 2001
From: Klaus Fischer <klaus.fischer@eloware.com>
Date: Mon, 5 Sep 2022 17:24:13 +0200
Subject: [PATCH] Added x500 bund certificate, problem still exists

---
 FitConnect/Encryption/CertificateHelper.cs | 19 ++++++++++++++-----
 FitConnect/Services/OAuthService.cs        |  2 --
 IntegrationTests/CertificateValidation.cs  |  9 ++++++---
 IntegrationTests/IntegrationTests.csproj   |  3 +++
 4 files changed, 23 insertions(+), 10 deletions(-)

diff --git a/FitConnect/Encryption/CertificateHelper.cs b/FitConnect/Encryption/CertificateHelper.cs
index c0c702e6..2076ebe0 100644
--- a/FitConnect/Encryption/CertificateHelper.cs
+++ b/FitConnect/Encryption/CertificateHelper.cs
@@ -15,13 +15,14 @@ public class CertificateHelper {
     }
 
     internal bool ValidateCertificate(string keyJson, LogLevel logLevel,
-        X509Certificate2? rootCertificate = null) =>
+        X509Certificate2[]? rootCertificate = null) =>
         ValidateCertificate(new JsonWebKey(keyJson), logLevel, rootCertificate);
 
     internal bool ValidateCertificate(JsonWebKey key, LogLevel logLevel = LogLevel.Error,
-        X509Certificate2? root = null) {
+        X509Certificate2[]? root = null) {
         var certificates = key.X5c.Select(s => new X509Certificate2(Convert.FromBase64String(s)))
             .ToList();
+
         // root ??= new X509Certificate2(Convert.FromBase64String(key.X5t));
 
         _logger?.LogTrace("Found {Count} certificate(s)", certificates.Count);
@@ -31,21 +32,22 @@ public class CertificateHelper {
                               && ValidateCertificate(cert, out _,
                                   root,
                                   logLevel)
-            //&& cert.Verify()
+                              && cert.Verify()
         );
         return valid;
     }
 
     internal bool ValidateCertificate(X509Certificate2 certificate,
         out X509ChainStatus[] chainStatus,
-        X509Certificate2? rootCertificate = null,
+        X509Certificate2[]? rootCertificate = null,
         LogLevel logLevel = LogLevel.Warning) {
         var certificateChain = new X509Chain();
 
 
         if (rootCertificate != null) {
             certificateChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
-            certificateChain.ChainPolicy.CustomTrustStore.Add(rootCertificate);
+            // certificateChain.ChainPolicy.ExtraStore.AddRange(rootCertificate);
+            certificateChain.ChainPolicy.CustomTrustStore.AddRange(rootCertificate);
             certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
             certificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
             certificateChain.ChainPolicy.DisableCertificateDownloads = true;
@@ -71,6 +73,13 @@ public class CertificateHelper {
         if (!result)
             _logger?.Log(logLevel, "Certificate status: {ObjStatusInformation}",
                 statusAggregation);
+#if DEBUG
+        if (certificate.Verify() != result) {
+            _logger?.LogError(
+                "Certificate verification failed. Verify does not match internal test {Result}",
+                result);
+        }
+#endif
         return result;
     }
 }
diff --git a/FitConnect/Services/OAuthService.cs b/FitConnect/Services/OAuthService.cs
index 19f91531..1df17608 100644
--- a/FitConnect/Services/OAuthService.cs
+++ b/FitConnect/Services/OAuthService.cs
@@ -38,8 +38,6 @@ internal class OAuthService : RestCallService, IOAuthService {
     ///         https://portal.auth-testing.fit-connect.fitko.dev
     ///     </para>
     /// </summary>
-    /// <param name="clientId">Your client Id</param>
-    /// <param name="clientSecret">Your client Secret</param>
     /// <param name="scope">Scope if needed</param>
     /// <returns>The received token or null</returns>
     public async Task AuthenticateAsync(
diff --git a/IntegrationTests/CertificateValidation.cs b/IntegrationTests/CertificateValidation.cs
index b4add4c7..eefce9cd 100644
--- a/IntegrationTests/CertificateValidation.cs
+++ b/IntegrationTests/CertificateValidation.cs
@@ -157,10 +157,12 @@ public class CertificateValidation {
 
             if (fileName.EndsWith(".json")) {
                 var shouldFail = !fileName.Contains("/valid");
-                var root = new X509Certificate2("./certificates/root.pem");
                 var jwk = new JsonWebKey(File.ReadAllText(fileName));
                 var valid = _certificateHelper.ValidateCertificate(jwk,
-                    shouldFail ? LogLevel.Trace : LogLevel.Critical, root);
+                    shouldFail ? LogLevel.Debug : LogLevel.Critical, new[] {
+                        new X509Certificate2("./certificates/root.pem"),
+                        new X509Certificate2("./certificates/ca.30244.der")
+                    });
 
                 if (shouldFail)
                     valid = !valid;
@@ -175,7 +177,8 @@ public class CertificateValidation {
             }
         }
 
-        _logger.LogWarning("Failed certificates: {certs}", failedCerts.Aggregate("\n", (a,b)=>a+"\n\t - "+b));
+        _logger.LogWarning("Failed certificates: {Certs}",
+            failedCerts.Aggregate("\n", (a, b) => a + "\t - " + b + "\n"));
         _logger.LogInformation("Success: {Success}, Failed: {Failed}", success, failed);
         failed.Should().Be(0);
     }
diff --git a/IntegrationTests/IntegrationTests.csproj b/IntegrationTests/IntegrationTests.csproj
index 341f9790..ee4d7ef4 100644
--- a/IntegrationTests/IntegrationTests.csproj
+++ b/IntegrationTests/IntegrationTests.csproj
@@ -54,6 +54,9 @@
         <None Update="certificates\root.pem">
           <CopyToOutputDirectory>Always</CopyToOutputDirectory>
         </None>
+        <None Update="certificates\ca.30244.der">
+          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+        </None>
     </ItemGroup>
 
 </Project>
-- 
GitLab