Skip to content

Avoid expensive work for CertificateManager logging when not enabled #27956

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
1 commit merged into from
Nov 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 106 additions & 38 deletions src/Shared/CertificateGeneration/CertificateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ public IList<X509Certificate2> ListCertificates(
matchingCertificates = matchingCertificates
.Where(c => HasOid(c, AspNetHttpsOid));

Log.DescribeFoundCertificates(ToCertificateDescription(matchingCertificates));
if (Log.IsEnabled())
{
Log.DescribeFoundCertificates(ToCertificateDescription(matchingCertificates));
}

if (isValid)
{
Expand All @@ -93,10 +96,12 @@ public IList<X509Certificate2> ListCertificates(
.OrderByDescending(c => GetCertificateVersion(c))
.ToArray();

var invalidCertificates = matchingCertificates.Except(validCertificates);

Log.DescribeValidCertificates(ToCertificateDescription(validCertificates));
Log.DescribeInvalidValidCertificates(ToCertificateDescription(invalidCertificates));
if (Log.IsEnabled())
{
var invalidCertificates = matchingCertificates.Except(validCertificates);
Log.DescribeValidCertificates(ToCertificateDescription(validCertificates));
Log.DescribeInvalidValidCertificates(ToCertificateDescription(invalidCertificates));
}

matchingCertificates = validCertificates;
}
Expand All @@ -114,7 +119,10 @@ public IList<X509Certificate2> ListCertificates(
}
catch (Exception e)
{
Log.ListCertificatesError(e.ToString());
if (Log.IsEnabled())
{
Log.ListCertificatesError(e.ToString());
}
DisposeCertificates(certificates);
certificates.Clear();
return certificates;
Expand Down Expand Up @@ -170,10 +178,13 @@ public EnsureCertificateResult EnsureAspNetCoreHttpsDevelopmentCertificate(
var certificates = currentUserCertificates.Concat(trustedCertificates);

var filteredCertificates = certificates.Where(c => c.Subject == Subject);
var excludedCertificates = certificates.Except(filteredCertificates);

Log.FilteredCertificates(ToCertificateDescription(filteredCertificates));
Log.ExcludedCertificates(ToCertificateDescription(excludedCertificates));
if (Log.IsEnabled())
{
var excludedCertificates = certificates.Except(filteredCertificates);
Log.FilteredCertificates(ToCertificateDescription(filteredCertificates));
Log.ExcludedCertificates(ToCertificateDescription(excludedCertificates));
}

certificates = filteredCertificates;

Expand All @@ -194,13 +205,19 @@ public EnsureCertificateResult EnsureAspNetCoreHttpsDevelopmentCertificate(
{
try
{
Log.CorrectCertificateStateStart(GetDescription(candidate));
if (Log.IsEnabled())
{
Log.CorrectCertificateStateStart(GetDescription(candidate));
}
CorrectCertificateState(candidate);
Log.CorrectCertificateStateEnd();
}
catch (Exception e)
{
Log.CorrectCertificateStateError(e.ToString());
if (Log.IsEnabled())
{
Log.CorrectCertificateStateError(e.ToString());
}
result = EnsureCertificateResult.FailedToMakeKeyAccessible;
// We don't return early on this type of failure to allow for tooling to
// export or trust the certificate even in this situation, as that enables
Expand All @@ -213,9 +230,15 @@ public EnsureCertificateResult EnsureAspNetCoreHttpsDevelopmentCertificate(

if (!failedToFixCertificateState)
{
Log.ValidCertificatesFound(ToCertificateDescription(certificates));
if (Log.IsEnabled())
{
Log.ValidCertificatesFound(ToCertificateDescription(certificates));
}
certificate = certificates.First();
Log.SelectedCertificate(GetDescription(certificate));
if (Log.IsEnabled())
{
Log.SelectedCertificate(GetDescription(certificate));
}
result = EnsureCertificateResult.ValidCertificatePresent;
}
}
Expand All @@ -230,7 +253,10 @@ public EnsureCertificateResult EnsureAspNetCoreHttpsDevelopmentCertificate(
}
catch (Exception e)
{
Log.CreateDevelopmentCertificateError(e.ToString());
if (Log.IsEnabled())
{
Log.CreateDevelopmentCertificateError(e.ToString());
}
result = EnsureCertificateResult.ErrorCreatingTheCertificate;
return result;
}
Expand All @@ -251,13 +277,20 @@ public EnsureCertificateResult EnsureAspNetCoreHttpsDevelopmentCertificate(
{
try
{
Log.CorrectCertificateStateStart(GetDescription(certificate));
if (Log.IsEnabled())
{
Log.CorrectCertificateStateStart(GetDescription(certificate));
}
CorrectCertificateState(certificate);
Log.CorrectCertificateStateEnd();
}
catch (Exception e)
{
Log.CorrectCertificateStateError(e.ToString());
if (Log.IsEnabled())
{
Log.CorrectCertificateStateError(e.ToString());
}

// We don't return early on this type of failure to allow for tooling to
// export or trust the certificate even in this situation, as that enables
// exporting the certificate to perform any necessary fix with native tooling.
Expand All @@ -274,7 +307,11 @@ public EnsureCertificateResult EnsureAspNetCoreHttpsDevelopmentCertificate(
}
catch (Exception e)
{
Log.ExportCertificateError(e.ToString());
if (Log.IsEnabled())
{
Log.ExportCertificateError(e.ToString());
}

// We don't want to mask the original source of the error here.
result = result != EnsureCertificateResult.Succeeded && result != EnsureCertificateResult.ValidCertificatePresent ?
result :
Expand Down Expand Up @@ -318,7 +355,10 @@ internal ImportCertificateResult ImportCertificate(string certificatePath, strin
var certificates = ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false, requireExportable: false);
if (certificates.Any())
{
Log.ImportCertificateExistingCertificates(ToCertificateDescription(certificates));
if (Log.IsEnabled())
{
Log.ImportCertificateExistingCertificates(ToCertificateDescription(certificates));
}
return ImportCertificateResult.ExistingCertificatesPresent;
}

Expand All @@ -327,17 +367,26 @@ internal ImportCertificateResult ImportCertificate(string certificatePath, strin
{
Log.LoadCertificateStart(certificatePath);
certificate = new X509Certificate2(certificatePath, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet);
Log.LoadCertificateEnd(GetDescription(certificate));
if (Log.IsEnabled())
{
Log.LoadCertificateEnd(GetDescription(certificate));
}
}
catch (Exception e)
{
Log.LoadCertificateError(e.ToString());
if (Log.IsEnabled())
{
Log.LoadCertificateError(e.ToString());
}
return ImportCertificateResult.InvalidCertificate;
}

if (!IsHttpsDevelopmentCertificate(certificate))
{
Log.NoHttpsDevelopmentCertificate(GetDescription(certificate));
if (Log.IsEnabled())
{
Log.NoHttpsDevelopmentCertificate(GetDescription(certificate));
}
return ImportCertificateResult.NoDevelopmentHttpsCertificate;
}

Expand All @@ -347,7 +396,10 @@ internal ImportCertificateResult ImportCertificate(string certificatePath, strin
}
catch (Exception e)
{
Log.SaveCertificateInStoreError(e.ToString());
if (Log.IsEnabled())
{
Log.SaveCertificateInStoreError(e.ToString());
}
return ImportCertificateResult.ErrorSavingTheCertificateIntoTheCurrentUserPersonalStore;
}

Expand All @@ -365,10 +417,13 @@ public void CleanupHttpsCertificates()
// we remove the certificates from the local user store to finish up the cleanup.
var certificates = ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false);
var filteredCertificates = certificates.Where(c => c.Subject == Subject);
var excludedCertificates = certificates.Except(filteredCertificates);

Log.FilteredCertificates(ToCertificateDescription(filteredCertificates));
Log.ExcludedCertificates(ToCertificateDescription(excludedCertificates));
if (Log.IsEnabled())
{
var excludedCertificates = certificates.Except(filteredCertificates);
Log.FilteredCertificates(ToCertificateDescription(filteredCertificates));
Log.ExcludedCertificates(ToCertificateDescription(excludedCertificates));
}

foreach (var certificate in filteredCertificates)
{
Expand All @@ -390,7 +445,11 @@ public void CleanupHttpsCertificates()

internal void ExportCertificate(X509Certificate2 certificate, string path, bool includePrivateKey, string password, CertificateKeyExportFormat format)
{
Log.ExportCertificateStart(GetDescription(certificate), path, includePrivateKey);
if (Log.IsEnabled())
{
Log.ExportCertificateStart(GetDescription(certificate), path, includePrivateKey);
}

if (includePrivateKey && password == null)
{
Log.NoPasswordForCertificate();
Expand Down Expand Up @@ -465,7 +524,7 @@ internal void ExportCertificate(X509Certificate2 certificate, string path, bool
}
}
}
catch (Exception e)
catch (Exception e) when (Log.IsEnabled())
{
Log.ExportCertificateError(e.ToString());
throw;
Expand All @@ -480,7 +539,7 @@ internal void ExportCertificate(X509Certificate2 certificate, string path, bool
Log.WriteCertificateToDisk(path);
File.WriteAllBytes(path, bytes);
}
catch (Exception ex)
catch (Exception ex) when (Log.IsEnabled())
{
Log.WriteCertificateToDiskError(ex.ToString());
throw;
Expand All @@ -498,7 +557,7 @@ internal void ExportCertificate(X509Certificate2 certificate, string path, bool
Log.WritePemKeyToDisk(keyPath);
File.WriteAllBytes(keyPath, pemEnvelope);
}
catch (Exception ex)
catch (Exception ex) when (Log.IsEnabled())
{
Log.WritePemKeyToDiskError(ex.ToString());
throw;
Expand Down Expand Up @@ -565,7 +624,10 @@ internal X509Certificate2 SaveCertificate(X509Certificate2 certificate)
var name = StoreName.My;
var location = StoreLocation.CurrentUser;

Log.SaveCertificateInStoreStart(GetDescription(certificate), name, location);
if (Log.IsEnabled())
{
Log.SaveCertificateInStoreStart(GetDescription(certificate), name, location);
}

certificate = SaveCertificateCore(certificate);

Expand All @@ -577,11 +639,14 @@ internal void TrustCertificate(X509Certificate2 certificate)
{
try
{
Log.TrustCertificateStart(GetDescription(certificate));
if (Log.IsEnabled())
{
Log.TrustCertificateStart(GetDescription(certificate));
}
TrustCertificateCore(certificate);
Log.TrustCertificateEnd();
}
catch (Exception ex)
catch (Exception ex) when (Log.IsEnabled())
{
Log.TrustCertificateError(ex.ToString());
throw;
Expand Down Expand Up @@ -676,7 +741,10 @@ private static void RemoveCertificateFromUserStore(X509Certificate2 certificate)
{
try
{
Log.RemoveCertificateFromUserStoreStart(GetDescription(certificate));
if (Log.IsEnabled())
{
Log.RemoveCertificateFromUserStoreStart(GetDescription(certificate));
}
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
var matching = store.Certificates
Expand All @@ -687,18 +755,18 @@ private static void RemoveCertificateFromUserStore(X509Certificate2 certificate)
store.Close();
Log.RemoveCertificateFromUserStoreEnd();
}
catch (Exception ex)
catch (Exception ex) when (Log.IsEnabled())
{
Log.RemoveCertificateFromUserStoreError(ex.ToString());
throw;
}
}

internal static string ToCertificateDescription(IEnumerable<X509Certificate2> matchingCertificates) =>
string.Join(Environment.NewLine, matchingCertificates
.OrderBy(c => c.Thumbprint)
.Select(c => GetDescription(c))
.ToArray());
string.Join(Environment.NewLine, matchingCertificates
.OrderBy(c => c.Thumbprint)
.Select(c => GetDescription(c))
.ToArray());

internal static string GetDescription(X509Certificate2 c) =>
$"{c.Thumbprint[0..6]} - {c.Subject} - {c.GetEffectiveDateString()} - {c.GetExpirationDateString()} - {Instance.IsHttpsDevelopmentCertificate(c)} - {Instance.IsExportable(c)}";
Expand Down
17 changes: 14 additions & 3 deletions src/Shared/CertificateGeneration/MacOSCertificateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ protected override void TrustCertificateCore(X509Certificate2 publicCertificate)
try
{
ExportCertificate(publicCertificate, tmpFile, includePrivateKey: false, password: null, CertificateKeyExportFormat.Pfx);
Log.MacOSTrustCommandStart($"{MacOSTrustCertificateCommandLine} {MacOSTrustCertificateCommandLineArguments}{tmpFile}");
if (Log.IsEnabled())
{
Log.MacOSTrustCommandStart($"{MacOSTrustCertificateCommandLine} {MacOSTrustCertificateCommandLineArguments}{tmpFile}");
}
using (var process = Process.Start(MacOSTrustCertificateCommandLine, MacOSTrustCertificateCommandLineArguments + tmpFile))
{
process.WaitForExit();
Expand Down Expand Up @@ -238,7 +241,11 @@ private static void RemoveCertificateFromKeyChain(string keyChain, X509Certifica
RedirectStandardError = true
};

Log.MacOSRemoveCertificateFromKeyChainStart(keyChain, GetDescription(certificate));
if (Log.IsEnabled())
{
Log.MacOSRemoveCertificateFromKeyChainStart(keyChain, GetDescription(certificate));
}

using (var process = Process.Start(processInfo))
{
var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
Expand Down Expand Up @@ -282,7 +289,11 @@ protected override X509Certificate2 SaveCertificateCore(X509Certificate2 certifi
RedirectStandardError = true
};

Log.MacOSAddCertificateToKeyChainStart(MacOSUserKeyChain, GetDescription(certificate));
if (Log.IsEnabled())
{
Log.MacOSAddCertificateToKeyChainStart(MacOSUserKeyChain, GetDescription(certificate));
}

using (var process = Process.Start(processInfo))
{
var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
Expand Down