Skip to content

Remove all SYSLIB0057 suppressions and replace obsolete X509Certificate2 constructors with X509CertificateLoader #62552

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

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
5 changes: 1 addition & 4 deletions eng/Workarounds.props
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@
<NoWarn>$(NoWarn);NETSDK1138;CS8969</NoWarn>
</PropertyGroup>

<!-- Workaround obsolete X509Certificate ctor: https://github.com/dotnet/docs/issues/41662 -->
<PropertyGroup>
<NoWarn>$(NoWarn);SYSLIB0057</NoWarn>
</PropertyGroup>


<PropertyGroup>
<!-- Ignore warning about calling the Pack target on Web SDK projects. Our build scripts call /t:pack on everything in this repo. -->
Expand Down
3 changes: 1 addition & 2 deletions eng/testing/linker/SupportFiles/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Enable NuGet static graph evaluation to optimize incremental restore -->
<RestoreUseStaticGraphEvaluation>true</RestoreUseStaticGraphEvaluation>
<!-- Workaround obsolete X509Certificate ctor: https://github.com/dotnet/docs/issues/41662 -->
<NoWarn>$(NoWarn);SYSLIB0057</NoWarn>


<TargetOsName Condition=" '$(TargetOsName)' == '' AND $([MSBuild]::IsOSPlatform('Windows'))">win</TargetOsName>
<TargetOsName Condition=" '$(TargetOsName)' == '' AND $([MSBuild]::IsOSPlatform('OSX'))">osx</TargetOsName>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class EncryptedXmlDecryptorTests
[Fact]
public void ThrowsIfCannotDecrypt()
{
var testCert1 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var testCert1 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var encryptor = new CertificateXmlEncryptor(testCert1, NullLoggerFactory.Instance);
var data = new XElement("SampleData", "Lorem ipsum");
var encryptedXml = encryptor.Encrypt(data);
Expand All @@ -29,8 +29,8 @@ public void ThrowsIfCannotDecrypt()
[Fact]
public void ThrowsIfProvidedCertificateDoesNotMatch()
{
var testCert1 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var testCert2 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password");
var testCert1 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var testCert2 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password");
var services = new ServiceCollection()
.Configure<XmlKeyDecryptionOptions>(o => o.AddKeyDecryptionCertificate(testCert2))
.BuildServiceProvider();
Expand All @@ -47,8 +47,8 @@ public void ThrowsIfProvidedCertificateDoesNotMatch()
[Fact]
public void ThrowsIfProvidedCertificateDoesHavePrivateKey()
{
var fullCert = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var publicKeyOnly = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.PublicKeyOnly.cer"), "");
var fullCert = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var publicKeyOnly = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.PublicKeyOnly.cer"));
var services = new ServiceCollection()
.Configure<XmlKeyDecryptionOptions>(o => o.AddKeyDecryptionCertificate(publicKeyOnly))
.BuildServiceProvider();
Expand All @@ -65,8 +65,8 @@ public void ThrowsIfProvidedCertificateDoesHavePrivateKey()
[Fact]
public void XmlCanRoundTrip()
{
var testCert1 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var testCert2 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password");
var testCert1 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password");
var testCert2 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password");
var services = new ServiceCollection()
.Configure<XmlKeyDecryptionOptions>(o =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;

var cert = new X509Certificate2(Convert.FromBase64String(Constants.Key), Constants.Password);
var cert = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(Constants.Key), Constants.Password);

var encryptor = new CertificateXmlEncryptor(cert, NullLoggerFactory.Instance);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;

var cert = new X509Certificate2(Convert.FromBase64String(Constants.Key), Constants.Password);
var cert = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(Constants.Key), Constants.Password);
var encryptedData = XElement.Parse(Constants.KeyRingXmlContents)
.Element("descriptor")
.Element("descriptor")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
var keyDirectory = new DirectoryInfo(AppContext.BaseDirectory);
File.WriteAllText(Path.Combine(keyDirectory.FullName, Constants.KeyRingXmlFileName), Constants.KeyRingXmlContents);

var cert = new X509Certificate2(Convert.FromBase64String(Constants.Key), Constants.Password);
var cert = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(Constants.Key), Constants.Password);
var dpProvider = DataProtectionProvider.Create(keyDirectory, cert);
var protector = dpProvider.CreateProtector(purpose: "Test trimming");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public void System_UsesProvidedDirectory_WithConfigurationCallback()
public void System_UsesProvidedDirectoryAndCertificate()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert.pfx");
using (var imported = new X509Certificate2(filePath, "password", X509KeyStorageFlags.Exportable))
using (var imported = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password", X509KeyStorageFlags.Exportable))
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
Expand All @@ -145,7 +145,7 @@ public void System_UsesProvidedDirectoryAndCertificate()
var data = protector.Protect("payload");

// add a cert without the private key to ensure the decryption will still fallback to the cert store
var certWithoutKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCertWithoutPrivateKey.pfx"), "password");
var certWithoutKey = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(GetTestFilesPath(), "TestCertWithoutPrivateKey.pfx"), "password");
var unprotector = DataProtectionProvider.Create(directory, o => o.UnprotectKeysWithAnyCertificate(certWithoutKey)).CreateProtector("purpose");
Assert.Equal("payload", unprotector.Unprotect(data));

Expand Down Expand Up @@ -173,7 +173,7 @@ public void System_UsesProvidedCertificateNotFromStore()
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
var certWithoutKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCert3WithoutPrivateKey.pfx"), "password3", X509KeyStorageFlags.Exportable);
var certWithoutKey = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(GetTestFilesPath(), "TestCert3WithoutPrivateKey.pfx"), "password3", X509KeyStorageFlags.Exportable);
Assert.False(certWithoutKey.HasPrivateKey, "Cert should not have private key");
store.Add(certWithoutKey);
store.Close();
Expand All @@ -190,7 +190,7 @@ public void System_UsesProvidedCertificateNotFromStore()

try
{
var certWithKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCert3.pfx"), "password3");
var certWithKey = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(GetTestFilesPath(), "TestCert3.pfx"), "password3");

var protector = DataProtectionProvider.Create(directory, certWithKey).CreateProtector("purpose");
var data = protector.Protect("payload");
Expand All @@ -214,7 +214,7 @@ public void System_UsesProvidedCertificateNotFromStore()
public void System_UsesInMemoryCertificate()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx");
var certificate = new X509Certificate2(filePath, "password");
var certificate = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password");

AssetStoreDoesNotContain(certificate);

Expand Down Expand Up @@ -243,7 +243,7 @@ public void System_UsesInMemoryCertificate()
public void System_UsesCertificate()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx");
var certificate = new X509Certificate2(filePath, "password");
var certificate = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password");

AssetStoreDoesNotContain(certificate);

Expand Down Expand Up @@ -285,7 +285,7 @@ private static void AssetStoreDoesNotContain(X509Certificate2 certificate)
public void System_CanUnprotectWithCert()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx");
var certificate = new X509Certificate2(filePath, "password");
var certificate = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password");

WithUniqueTempDirectory(directory =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ private async Task<IChannelWrapper> HttpClientCreateChannel()
{
var pem = File.ReadAllText("Certs/ca.pem");
var certData = GetBytesFromPem(pem, "CERTIFICATE");
var cert = new X509Certificate2(certData!);
var cert = X509CertificateLoader.LoadCertificate(certData!);

httpClientHandler.ClientCertificates.Add(cert);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ public async Task RequestDelegatePopulatesFromIFormFileParameterIfRequestHasClie
httpContext.TraceIdentifier = "my-trace-id";

#pragma warning disable SYSLIB0026 // Type or member is obsolete
var clientCertificate = new X509Certificate2();
var clientCertificate = X509CertificateLoader.LoadCertificate(Array.Empty<byte>());
#pragma warning restore SYSLIB0026 // Type or member is obsolete

httpContext.Features.Set<ITlsConnectionFeature>(new TlsConnectionFeature(clientCertificate));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ public class CertificateForwardingOptions
/// <remarks>
/// This defaults to a conversion from a base64 encoded string.
/// </remarks>
public Func<string, X509Certificate2> HeaderConverter = (headerValue) => new X509Certificate2(Convert.FromBase64String(headerValue));
public Func<string, X509Certificate2> HeaderConverter = (headerValue) => X509CertificateLoader.LoadCertificate(Convert.FromBase64String(headerValue));
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ private static X509Certificate2 LoadCertificate()
certificatePayload = memoryStream.ToArray();
}

return new X509Certificate2(certificatePayload, "testPassword");
return X509CertificateLoader.LoadPkcs12(certificatePayload, "testPassword");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ private static unsafe void IOCompleted(ClientCertLoader asyncResult, uint errorC
{
var certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
asyncResult.Complete((int)pClientCertInfo->CertFlags, new X509Certificate2(certEncoded));
asyncResult.Complete((int)pClientCertInfo->CertFlags, X509CertificateLoader.LoadCertificate(certEncoded));
}
catch (CryptographicException exception)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ unsafe X509Certificate2? ITlsConnectionFeature.ClientCertificate
// Based off of from https://referencesource.microsoft.com/#system/net/System/Net/HttpListenerRequest.cs,1037c8ec82879ba0,references
var rawCertificateCopy = new byte[NativeRequest->pSslInfo->pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)NativeRequest->pSslInfo->pClientCertInfo->pCertEncoded, rawCertificateCopy, 0, rawCertificateCopy.Length);
_certificate = new X509Certificate2(rawCertificateCopy);
_certificate = X509CertificateLoader.LoadCertificate(rawCertificateCopy);
}

return _certificate;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public X509Certificate2 GetOrCreateCertificate()
var imported = parentCert;

var export = parentCert.Export(X509ContentType.Pkcs12, "");
imported = new X509Certificate2(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
imported = X509CertificateLoader.LoadPkcs12(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
Array.Clear(export, 0, export.Length);

// Add the cert to the cert store
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public X509Certificate2? ClientCertificate
try
{
var bytes = Convert.FromBase64String(_header.ToString());
_certificate = new X509Certificate2(bytes);
_certificate = X509CertificateLoader.LoadCertificate(bytes);
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public CertificateConfigLoader(IHostEnvironment hostEnvironment, ILogger<Kestrel
throw new InvalidOperationException(CoreStrings.InvalidPemKey);
}

return (new X509Certificate2(Path.Combine(HostEnvironment.ContentRootPath, certInfo.Path!), certInfo.Password), fullChain);
return (X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(HostEnvironment.ContentRootPath, certInfo.Path!), certInfo.Password), fullChain);
}
else if (certInfo.IsStoreCert)
{
Expand All @@ -86,7 +86,7 @@ private static X509Certificate2 PersistKey(X509Certificate2 fullCertificate)
// We need to force the key to be persisted.
// See https://github.com/dotnet/runtime/issues/23749
var certificateBytes = fullCertificate.Export(X509ContentType.Pkcs12, "");
return new X509Certificate2(certificateBytes, "", X509KeyStorageFlags.DefaultKeySet);
return X509CertificateLoader.LoadPkcs12(certificateBytes, "", X509KeyStorageFlags.DefaultKeySet);
}

private static X509Certificate2 LoadCertificateKey(X509Certificate2 certificate, string keyPath, string? password)
Expand Down Expand Up @@ -156,7 +156,7 @@ private static InvalidOperationException CreateErrorGettingPrivateKeyException(s
{
if (X509Certificate2.GetCertContentType(certificatePath) == X509ContentType.Cert)
{
return new X509Certificate2(certificatePath);
return X509CertificateLoader.LoadCertificateFromFile(certificatePath);
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public X509Certificate2? ClientCertificate
{
null => null,
X509Certificate2 cert2 => cert2,
_ => new X509Certificate2(certificate),
_ => X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()),
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static class ListenOptionsHttpsExtensions
public static ListenOptions UseHttps(this ListenOptions listenOptions, string fileName)
{
var env = listenOptions.ApplicationServices.GetRequiredService<IHostEnvironment>();
return listenOptions.UseHttps(new X509Certificate2(Path.Combine(env.ContentRootPath, fileName)));
return listenOptions.UseHttps(X509CertificateLoader.LoadCertificateFromFile(Path.Combine(env.ContentRootPath, fileName)));
}

/// <summary>
Expand All @@ -50,7 +50,7 @@ public static ListenOptions UseHttps(this ListenOptions listenOptions, string fi
public static ListenOptions UseHttps(this ListenOptions listenOptions, string fileName, string? password)
{
var env = listenOptions.ApplicationServices.GetRequiredService<IHostEnvironment>();
return listenOptions.UseHttps(new X509Certificate2(Path.Combine(env.ContentRootPath, fileName), password));
return listenOptions.UseHttps(X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(env.ContentRootPath, fileName), password));
}

/// <summary>
Expand All @@ -65,7 +65,7 @@ public static ListenOptions UseHttps(this ListenOptions listenOptions, string fi
Action<HttpsConnectionAdapterOptions> configureOptions)
{
var env = listenOptions.ApplicationServices.GetRequiredService<IHostEnvironment>();
return listenOptions.UseHttps(new X509Certificate2(Path.Combine(env.ContentRootPath, fileName), password), configureOptions);
return listenOptions.UseHttps(X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(env.ContentRootPath, fileName), password), configureOptions);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ internal static void EnsureCertificateIsAllowedForServerAuth(X509Certificate2 ce
return cert2;
}

return new X509Certificate2(certificate);
return X509CertificateLoader.LoadCertificate(certificate.GetRawCertData());
}

internal static HttpProtocols ValidateAndNormalizeHttpProtocols(HttpProtocols httpProtocols, ILogger<HttpsConnectionMiddleware> logger)
Expand Down
2 changes: 1 addition & 1 deletion src/Servers/Kestrel/Core/src/TlsConfigurationLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public ListenOptions UseHttpsWithSni(
{
try
{
var certificate = new X509Certificate2(certificatePath, certificateConfig.Password);
var certificate = X509CertificateLoader.LoadPkcs12FromFile(certificatePath, certificateConfig.Password);

if (IsDevelopmentCertificate(certificate))
{
Expand Down
8 changes: 4 additions & 4 deletions src/Servers/Kestrel/Core/test/SniOptionsSelectorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ public void ClonesSslServerAuthenticationOptionsIfTheFallbackServerCertificateSe

var fallbackOptions = new HttpsConnectionAdapterOptions
{
ServerCertificate = new X509Certificate2(Array.Empty<byte>()),
ServerCertificate = X509CertificateLoader.LoadCertificate(Array.Empty<byte>()),
ServerCertificateSelector = (context, serverName) => selectorCertificate
};

Expand Down Expand Up @@ -531,7 +531,7 @@ public void FallsBackToHttpsConnectionAdapterCertificate()
};
var fallbackOptions = new HttpsConnectionAdapterOptions
{
ServerCertificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword")
ServerCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword")
};

var sniOptionsSelector = new SniOptionsSelector(
Expand All @@ -558,7 +558,7 @@ public void FallsBackToHttpsConnectionAdapterServerCertificateSelectorOverServer

var fallbackOptions = new HttpsConnectionAdapterOptions
{
ServerCertificate = new X509Certificate2(Array.Empty<byte>()),
ServerCertificate = X509CertificateLoader.LoadCertificate(Array.Empty<byte>()),
ServerCertificateSelector = (context, serverName) => selectorCertificate
};

Expand Down Expand Up @@ -849,7 +849,7 @@ public void CloneSslOptionsClonesAllProperties()
// Defaults to null
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
// Defaults to null
ServerCertificate = new X509Certificate2(Array.Empty<byte>()),
ServerCertificate = X509CertificateLoader.LoadCertificate(Array.Empty<byte>()),
// Defaults to null
ServerCertificateContext = SslStreamCertificateContext.Create(_x509Certificate2, additionalCertificates: null, offline: true),
// Defaults to null
Expand Down
Loading
Loading