Skip to content
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

Messaging: Correct most warnings + suppress a few in auto-generated files #734

Merged
merged 7 commits into from
Jan 28, 2025
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<TargetFrameworks>net6.0;net8.0;net9.0</TargetFrameworks>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<NoWarn>CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions src/Helsenorge.Messaging/Helsenorge.Messaging.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<SignAssembly>false</SignAssembly>
<PackageId>Helsenorge.Messaging</PackageId>
<NoWarn>CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,32 @@
using System.Security.Cryptography.Pkcs;
using Helsenorge.Messaging.Abstractions;
using System.Security.Cryptography;
using Microsoft.Extensions.Logging;
using Helsenorge.Messaging.Amqp.Receivers;
using Microsoft.Extensions.Logging;
using Helsenorge.Messaging.Amqp.Receivers;

namespace Helsenorge.Messaging.Security
{
/// <summary>
/// Provides message protection that first signs the message, then encrypts it
/// </summary>
public class SignThenEncryptMessageProtection : MessageProtection
{
private readonly ILogger _logger;
{
private readonly ILogger _logger;
private readonly X509IncludeOption? _includeOption;
private readonly MessagingEncryptionType _messagingEncryptionType;
private readonly MessagingEncryptionType _rejectMessagingEncryptionTypes;
private readonly MessagingEncryptionType _messagingEncryptionType;
private readonly MessagingEncryptionType _rejectMessagingEncryptionTypes;

/// <summary>
/// Initializes a new instance of the <see cref="SignThenEncryptMessageProtection"/> class with the required certificates for signing and encrypting data.
/// </summary>
/// <param name="signingCertificate">Certificcate that will be used to sign data</param>
/// <param name="encryptionCertificate">Certificate that will be used to encrypt data</param>
/// <param name="encryptionCertificate">Certificate that will be used to encrypt data</param>
/// <param name="logger"></param>
/// <param name="legacyEncryptionCertificate">A legacy certificate that can be used when swapping certificates.</param>
/// <param name="includeOption">Controls how much of the signer certificate's certificate chain should be
/// embedded in the signed message. If not specified, the default <see cref="X509IncludeOption.ExcludeRoot"/>
/// is used.</param>
/// <param name="messagingEncryptionType">Controls which encryption type the Protect methods use.</param>
/// <param name="messagingEncryptionType">Controls which encryption type the Protect methods use.</param>
/// <param name="rejectMessagingEncryptionType">Controls which encryption type the Unprotect methods rejects.</param>
public SignThenEncryptMessageProtection(
X509Certificate2 signingCertificate,
Expand All @@ -49,11 +49,11 @@ public SignThenEncryptMessageProtection(
MessagingEncryptionType messagingEncryptionType = MessagingEncryptionType.AES256,
MessagingEncryptionType rejectMessagingEncryptionType = MessagingEncryptionType.None)
: base(signingCertificate, encryptionCertificate, legacyEncryptionCertificate)
{
_logger = logger;
{
_logger = logger;
_includeOption = includeOption;
_messagingEncryptionType = messagingEncryptionType;
_rejectMessagingEncryptionTypes = rejectMessagingEncryptionType;
_messagingEncryptionType = messagingEncryptionType;
_rejectMessagingEncryptionTypes = rejectMessagingEncryptionType;
}

/// <summary>
Expand All @@ -73,16 +73,19 @@ public override Stream Protect(Stream data, X509Certificate2 encryptionCertifica
}

/// <inheritdoc/>
public override Stream Protect(Stream data, X509Certificate2 encryptionCertificate, X509Certificate2 signingCertificate)
{
public override Stream Protect(Stream data, X509Certificate2 encryptionCertificate, X509Certificate2 signingCertificate)
{
if (data == null) throw new ArgumentNullException(nameof(data));
if (encryptionCertificate == null) throw new ArgumentNullException(nameof(encryptionCertificate));
if (signingCertificate == null) throw new ArgumentNullException(nameof(signingCertificate));

byte[] dataAsBytes = new byte[data.Length];
#if NET9_0_OR_GREATER
data.ReadExactly(dataAsBytes, 0, (int)data.Length);
#else
data.Read(dataAsBytes, 0, (int)data.Length);

return new MemoryStream(Protect(dataAsBytes, encryptionCertificate, signingCertificate));
#endif
return new MemoryStream(Protect(dataAsBytes, encryptionCertificate, signingCertificate));
}

private byte[] Protect(byte[] data, X509Certificate2 encryptionCertificate, X509Certificate2 signingCertificate)
Expand Down Expand Up @@ -117,7 +120,11 @@ public override Stream Unprotect(Stream data, X509Certificate2 signingCertificat
if (data == null) throw new ArgumentNullException(nameof(data));

byte[] dataAsBytes = new byte[data.Length];
#if NET9_0_OR_GREATER
data.ReadExactly(dataAsBytes, 0, (int)data.Length);
#else
data.Read(dataAsBytes, 0, (int)data.Length);
#endif

return new MemoryStream(Unprotect(dataAsBytes, signingCertificate));
}
Expand All @@ -133,13 +140,13 @@ private byte[] Unprotect(byte[] data, X509Certificate2 signingCertificate)
envelopedCms.Decode(data);
try
{
var encryptionOid = envelopedCms?.ContentEncryptionAlgorithm?.Oid;
var encryptionOid = envelopedCms?.ContentEncryptionAlgorithm?.Oid;
_logger.LogInformation($"Decrypting EnvelopedCms with ContentEncryptionAlgorithm: {encryptionOid?.FriendlyName ?? "null"} : {encryptionOid?.Value ?? "null"}");

if ((_rejectMessagingEncryptionTypes.HasFlag(MessagingEncryptionType.DES) && encryptionOid.Value == "1.3.14.3.2.7")
|| (_rejectMessagingEncryptionTypes.HasFlag(MessagingEncryptionType.TripleDES) && encryptionOid.Value == "1.2.840.113549.3.7"))
{
throw new UnsupportedMessageException($"EnvelopedCms was encrypted with disabled ContentEncryptionAlgorithm: {encryptionOid?.FriendlyName ?? "null"} : {encryptionOid?.Value ?? "null"}");
if ((_rejectMessagingEncryptionTypes.HasFlag(MessagingEncryptionType.DES) && encryptionOid.Value == "1.3.14.3.2.7")
|| (_rejectMessagingEncryptionTypes.HasFlag(MessagingEncryptionType.TripleDES) && encryptionOid.Value == "1.2.840.113549.3.7"))
{
throw new UnsupportedMessageException($"EnvelopedCms was encrypted with disabled ContentEncryptionAlgorithm: {encryptionOid?.FriendlyName ?? "null"} : {encryptionOid?.Value ?? "null"}");
}

envelopedCms.Decrypt(envelopedCms.RecipientInfos[0], encryptionCertificates);
Expand Down Expand Up @@ -187,15 +194,15 @@ private byte[] Unprotect(byte[] data, X509Certificate2 signingCertificate)

private EnvelopedCms GetEnvelope(byte[] rawContent)
{
if (_messagingEncryptionType.HasFlag(MessagingEncryptionType.AES256))
{
return new EnvelopedCms(new ContentInfo(rawContent), new AlgorithmIdentifier(new Oid("2.16.840.1.101.3.4.1.42")));
}
else if (_messagingEncryptionType.HasFlag(MessagingEncryptionType.TripleDES))
{
return new EnvelopedCms(new ContentInfo(rawContent), new AlgorithmIdentifier(new Oid("1.2.840.113549.3.7")));
}
if (_messagingEncryptionType.HasFlag(MessagingEncryptionType.AES256))
{
return new EnvelopedCms(new ContentInfo(rawContent), new AlgorithmIdentifier(new Oid("2.16.840.1.101.3.4.1.42")));
}
else if (_messagingEncryptionType.HasFlag(MessagingEncryptionType.TripleDES))
{
return new EnvelopedCms(new ContentInfo(rawContent), new AlgorithmIdentifier(new Oid("1.2.840.113549.3.7")));
}

throw new ArgumentException($"MessagingEncryptionType has been set to an unsupported type.: {_messagingEncryptionType}", nameof(_messagingEncryptionType));
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/Helsenorge.Registries/Abstractions/CertificateDetails.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ internal void OnDeserialized(StreamingContext context)
{
Certificate = string.IsNullOrWhiteSpace(_certificateBase64String)
? null
#if NET9_0_OR_GREATER
: X509CertificateLoader.LoadCertificate(Convert.FromBase64String(_certificateBase64String));
#else
: new X509Certificate2(Convert.FromBase64String(_certificateBase64String));
#endif
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ public static CollaborationProtocolProfile CreateFromPartyInfoElement(XElement p
foreach (var certificateElement in partyInfo.Elements(NameSpace + "Certificate"))
{
var base64 = certificateElement.Descendants(xmlSig + "X509Certificate").First().Value;
#if NET9_0_OR_GREATER
var certificate = X509CertificateLoader.LoadCertificate(Convert.FromBase64String(base64));
#else
var certificate = new X509Certificate2(Convert.FromBase64String(base64));
#endif

if (certificate.HasKeyUsage(X509KeyUsageFlags.KeyEncipherment))
{
Expand Down Expand Up @@ -99,10 +103,18 @@ internal void OnDeserialized(StreamingContext context)
{
EncryptionCertificate = string.IsNullOrWhiteSpace(_encryptionCertificateBase64String)
? null
#if NET9_0_OR_GREATER
: X509CertificateLoader.LoadCertificate(Convert.FromBase64String(_encryptionCertificateBase64String));
#else
: new X509Certificate2(Convert.FromBase64String(_encryptionCertificateBase64String));
#endif
SignatureCertificate = string.IsNullOrWhiteSpace(_signatureCertificateBase64String)
? null
#if NET9_0_OR_GREATER
: X509CertificateLoader.LoadCertificate(Convert.FromBase64String(_signatureCertificateBase64String));
#else
: new X509Certificate2(Convert.FromBase64String(_signatureCertificateBase64String));
#endif
}

/// <summary>
Expand Down
4 changes: 4 additions & 0 deletions src/Helsenorge.Registries/AddressRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,11 @@ private static CertificateDetails MapCertificateDetails(int herId, AddressServic
return new CertificateDetails
{
HerId = herId,
#if NET9_0_OR_GREATER
Certificate = X509CertificateLoader.LoadCertificate(certificateDetails.Certificate),
#else
Certificate = new X509Certificate2(certificateDetails.Certificate),
#endif
LdapUrl = certificateDetails.LdapUrl
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable CS0108

namespace Helsenorge.Registries.AddressService
{
using System.Runtime.Serialization;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable CS0108

namespace Helsenorge.Registries.CPAService
{
using System.Runtime.Serialization;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable CS0108

namespace Helsenorge.Registries
{
using System.Runtime.Serialization;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ public static class DummyCollaborationProtocolProfileFactory
/// <param name="logger">An instance of <see cref="ILogger"/>.</param>
/// <param name="herId">The HER-id to create a "dummy" <see cref="CollaborationProtocolProfile"/></param>
/// <param name="messageFunction"></param>
/// <param name="collaborationProtocolRegistry"></param>
/// <returns></returns>
public static async Task<CollaborationProtocolProfile> CreateAsync(
IAddressRegistry addressRegistry,
Expand Down
1 change: 1 addition & 0 deletions src/Helsenorge.Registries/Helsenorge.Registries.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<SignAssembly>false</SignAssembly>
<PackageId>Helsenorge.Registries</PackageId>
<NoWarn>CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
21 changes: 0 additions & 21 deletions src/Helsenorge.Registries/RegistriesException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,26 +54,5 @@ public RegistriesException(string message) : base(message)
public RegistriesException(string message, Exception inner) : base(message, inner)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected RegistriesException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{
}

/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
// ReSharper disable once RedundantOverridenMember
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<NoWarn>CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ public void Protect_And_Unprotect_UsingLegacy_OK()
public void Protect_And_Unprotect_WrongSigningCertificate()
{
const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CdXlwYXNzLGRjPU5PLENOPUJ1eXBhc3MlMjBDbGFzcyUyMDMlMjBDQSUyMDM/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdDB6BggrBgEFBQcBAQRuMGwwMwYIKwYBBQUHMAGGJ2h0dHA6Ly9vY3NwLmJ1eXBhc3Mubm8vb2NzcC9CUENsYXNzM0NBMzA1BggrBgEFBQcwAoYpaHR0cDovL2NydC5idXlwYXNzLm5vL2NydC9CUENsYXNzM0NBMy5jZXIwDQYJKoZIhvcNAQELBQADggEBALPuCmA93Mi9NZFUFOaQz3PasTFLeLmtSXtt4Qp0TVtJuhqrlDeWYXDCsffMQoCAZXE3569/hdEgHPBVALo8xKS9vdwZR5SgIF+IivsEdC4ZYsq8C5VX4qq2WxW7yHNy3GYU8RBdOaztTfUliv7uaAeooP6EOPa6m+R+dgGfGnb5rM8NRyGgcAKDvC1YUFwdWaIgqO0gBB6WnSkhkyk0iX4tksUkbemQFcyMi2XDog6IFpkYt85MvfBklwjjufCiIcpkzHmuZCcYSLdwqi40Cz4QM5FE8zQYJJLco35A7NVW3MusyFImTleOlL10NH3XnqeLM8loa1Ph7YPl0SpiSjY=";
#if NET9_0_OR_GREATER
var wrongCertificate = X509CertificateLoader.LoadCertificate(Convert.FromBase64String(wrongCertificateBase64));
#else
var wrongCertificate = new X509Certificate2(Convert.FromBase64String(wrongCertificateBase64));
#endif
MemoryStream contentStream = new MemoryStream(Encoding.UTF8.GetBytes(_content.ToString()));

var partyAProtection = new SignThenEncryptMessageProtection(TestCertificates.GetCertificate(TestCertificates.CounterpartySignatureThumbprint), TestCertificates.GetCertificate(TestCertificates.CounterpartyEncryptionThumbprint), _logger);
Expand Down
4 changes: 4 additions & 0 deletions test/Helsenorge.Registries.Tests/AddressRegistryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,11 @@ public void Serialize_AddressService_CertificateDetails()

var serialized = XmlCacheFormatter.Serialize(serviceDetails);
var deserialized = XmlCacheFormatter.DeserializeAsync<AddressService.CertificateDetails>(serialized).Result;
#if NET9_0_OR_GREATER
var deserializedCert = X509CertificateLoader.LoadCertificate(deserialized.Certificate);
#else
var deserializedCert = new X509Certificate2(deserialized.Certificate);
#endif
Assert.AreEqual(serviceDetails.LdapUrl, deserialized.LdapUrl);
Assert.AreEqual(cert.Thumbprint, deserializedCert.Thumbprint);
}
Expand Down