using System.Formats.Asn1; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Khaemhat.Infrastructure.Tests.Security; /// How builds the envelope. internal sealed record CmsTestOptions { /// BER with indefinite lengths and the content split in chunks, as many signing programs write. public bool Ber { get; init; } /// Identify the signer by subject key identifier instead of issuer and serial number. public bool BySubjectKeyIdentifier { get; init; } /// Whether to sign attributes (contentType, messageDigest, signingTime) or the content directly. public bool SignedAttributes { get; init; } = true; /// Content put in the envelope instead of the signed one (to simulate tampering). public byte[]? TamperedContent { get; init; } /// Flip a bit of the signature. public bool BreakSignature { get; init; } } /// /// Builds CMS SignedData envelopes (CAdES .p7m) in the tests with and self-signed certificates: /// no fixture is downloaded and no package is needed. Shared with the tests of the FatturaPA reader. /// internal static class CmsTestSigner { public static readonly DateTimeOffset SigningTime = new(2026, 3, 15, 10, 30, 0, TimeSpan.Zero); private const string DataOid = "1.2.840.113549.1.7.1"; private const string SignedDataOid = "1.2.840.113549.1.7.2"; private const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; private static readonly Lazy RsaCertificate = new(() => Create(ecdsa: false)); private static readonly Lazy EcdsaCertificate = new(() => Create(ecdsa: true)); /// A self-signed RSA certificate of "Mario Rossi" with SERIALNUMBER=TINIT-RSSMRA80A01H501U. public static X509Certificate2 Rsa => RsaCertificate.Value; /// A self-signed ECDSA P-256 certificate of the same person. public static X509Certificate2 Ecdsa => EcdsaCertificate.Value; public static byte[] Sign(byte[] content, X509Certificate2 certificate, CmsTestOptions? options = null) { options ??= new CmsTestOptions(); var isEcdsa = certificate.GetECDsaPrivateKey() is not null; byte[]? signedAttributes = null; byte[] toSign = content; if (options.SignedAttributes) { var writer = new AsnWriter(AsnEncodingRules.DER); using (writer.PushSetOf()) { WriteAttribute(writer, "1.2.840.113549.1.9.3", w => w.WriteObjectIdentifier(DataOid)); WriteAttribute(writer, "1.2.840.113549.1.9.4", w => w.WriteOctetString(SHA256.HashData(content))); WriteAttribute(writer, "1.2.840.113549.1.9.5", w => w.WriteUtcTime(SigningTime)); } toSign = writer.Encode(); signedAttributes = (byte[])toSign.Clone(); signedAttributes[0] = 0xA0; } byte[] signature; if (isEcdsa) { using var key = certificate.GetECDsaPrivateKey()!; signature = key.SignData(toSign, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence); } else { using var key = certificate.GetRSAPrivateKey()!; signature = key.SignData(toSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } if (options.BreakSignature) { signature[^5] ^= 0x01; } var signerInfo = new AsnWriter(AsnEncodingRules.DER); using (signerInfo.PushSequence()) { if (options.BySubjectKeyIdentifier) { signerInfo.WriteInteger(3); var ski = certificate.Extensions.OfType().Single(); signerInfo.WriteOctetString(ski.SubjectKeyIdentifierBytes.Span, new Asn1Tag(TagClass.ContextSpecific, 0)); } else { signerInfo.WriteInteger(1); using (signerInfo.PushSequence()) { signerInfo.WriteEncodedValue(certificate.IssuerName.RawData); signerInfo.WriteInteger(certificate.SerialNumberBytes.Span); } } WriteAlgorithm(signerInfo, Sha256Oid, withNull: true); if (signedAttributes is not null) { signerInfo.WriteEncodedValue(signedAttributes); } WriteAlgorithm(signerInfo, isEcdsa ? "1.2.840.10045.4.3.2" : "1.2.840.113549.1.1.11", withNull: !isEcdsa); signerInfo.WriteOctetString(signature); } var version = Der(w => w.WriteInteger(1)); var digestAlgorithms = Der(w => { using (w.PushSetOf()) { WriteAlgorithm(w, Sha256Oid, withNull: true); } }); var certificates = Tlv(0xA0, certificate.RawData); var signerInfos = Tlv(0x31, signerInfo.Encode()); var signedDataOid = Der(w => w.WriteObjectIdentifier(SignedDataOid)); var dataOid = Der(w => w.WriteObjectIdentifier(DataOid)); var envelopeContent = options.TamperedContent ?? content; if (!options.Ber) { return Tlv(0x30, signedDataOid, Tlv(0xA0, Tlv(0x30, version, digestAlgorithms, Tlv(0x30, dataOid, Tlv(0xA0, Tlv(0x04, envelopeContent))), certificates, signerInfos))); } // BER: indefinite lengths everywhere around the content, which is a constructed OCTET STRING of small chunks. var chunks = envelopeContent.Chunk(100).Select(c => Tlv(0x04, c)).ToArray(); return Indefinite(0x30, signedDataOid, Indefinite(0xA0, Indefinite(0x30, version, digestAlgorithms, Indefinite(0x30, dataOid, Indefinite(0xA0, Indefinite(0x24, chunks))), certificates, signerInfos))); } private static X509Certificate2 Create(bool ecdsa) { var name = new X500DistinguishedNameBuilder(); name.AddCountryOrRegion("IT"); name.Add("2.5.4.42", "Mario"); name.Add("2.5.4.4", "Rossi"); name.Add("2.5.4.5", "TINIT-RSSMRA80A01H501U", UniversalTagNumber.PrintableString); name.AddCommonName("Mario Rossi"); var subject = name.Build(); var notBefore = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero); var notAfter = new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero); if (ecdsa) { using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); return request.CreateSelfSigned(notBefore, notAfter); } else { using var key = RSA.Create(2048); var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); return request.CreateSelfSigned(notBefore, notAfter); } } private static void WriteAttribute(AsnWriter writer, string oid, Action value) { using (writer.PushSequence()) { writer.WriteObjectIdentifier(oid); using (writer.PushSetOf()) { value(writer); } } } private static void WriteAlgorithm(AsnWriter writer, string oid, bool withNull) { using (writer.PushSequence()) { writer.WriteObjectIdentifier(oid); if (withNull) { writer.WriteNull(); } } } private static byte[] Der(Action write) { var writer = new AsnWriter(AsnEncodingRules.DER); write(writer); return writer.Encode(); } private static byte[] Tlv(byte tag, params byte[][] children) { var body = children.SelectMany(c => c).ToArray(); var length = body.Length; byte[] lengthBytes = length switch { < 0x80 => [(byte)length], <= 0xFF => [0x81, (byte)length], <= 0xFFFF => [0x82, (byte)(length >> 8), (byte)length], _ => [0x83, (byte)(length >> 16), (byte)(length >> 8), (byte)length], }; return [tag, .. lengthBytes, .. body]; } private static byte[] Indefinite(byte tag, params byte[][] children) => [tag, 0x80, .. children.SelectMany(c => c), 0x00, 0x00]; }