Files
Khaemhat/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs
T
Alby96andClaude Opus 5.5 9a40adecfe feat: read FatturaPA invoices and signed p7m files (#57)
The import of supplier e-invoices needs a reading layer that turns a
received file into plain records, whatever form the file arrives in.

- Fiscal.Abstractions: IIncomingInvoiceReader, an optional pack feature,
  with the IncomingInvoiceFile records and the incoming.* error codes the
  import service and screens build on.
- Infrastructure: CmsSignedData, a minimal CMS SignedData (CAdES .p7m)
  reader on System.Formats.Asn1, since System.Security.Cryptography.Pkcs
  is a separate package. It accepts DER, BER with indefinite lengths and
  chunked content, base64 text and nested envelopes; it checks the
  message digest and the RSA (PKCS#1, PSS) or ECDSA signature with the
  embedded certificate and reports signer, tax code, validity and signing
  time. No trust chain or revocation check: no trusted list offline.
- Fiscal.Italy: FatturaPaReader for FPR12/FPA12 v1.2.x and FSM10, matched
  by local name, DTD prohibited and no resolver, BOM/windows-1252/missing
  declaration tolerated, batches as one invoice per body, attachments
  decoded; registered in ItalyFiscalPack.
- Tests build every sample and signed envelope in code (AsnWriter and
  self-signed certificates), nothing downloaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:08:29 +01:00

216 lines
8.6 KiB
C#

using System.Formats.Asn1;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Khaemhat.Infrastructure.Tests.Security;
/// <summary>How <see cref="CmsTestSigner.Sign"/> builds the envelope.</summary>
internal sealed record CmsTestOptions
{
/// <summary>BER with indefinite lengths and the content split in chunks, as many signing programs write.</summary>
public bool Ber { get; init; }
/// <summary>Identify the signer by subject key identifier instead of issuer and serial number.</summary>
public bool BySubjectKeyIdentifier { get; init; }
/// <summary>Whether to sign attributes (contentType, messageDigest, signingTime) or the content directly.</summary>
public bool SignedAttributes { get; init; } = true;
/// <summary>Content put in the envelope instead of the signed one (to simulate tampering).</summary>
public byte[]? TamperedContent { get; init; }
/// <summary>Flip a bit of the signature.</summary>
public bool BreakSignature { get; init; }
}
/// <summary>
/// Builds CMS SignedData envelopes (CAdES .p7m) in the tests with <see cref="AsnWriter"/> and self-signed certificates:
/// no fixture is downloaded and no package is needed. Shared with the tests of the FatturaPA reader.
/// </summary>
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<X509Certificate2> RsaCertificate = new(() => Create(ecdsa: false));
private static readonly Lazy<X509Certificate2> EcdsaCertificate = new(() => Create(ecdsa: true));
/// <summary>A self-signed RSA certificate of "Mario Rossi" with SERIALNUMBER=TINIT-RSSMRA80A01H501U.</summary>
public static X509Certificate2 Rsa => RsaCertificate.Value;
/// <summary>A self-signed ECDSA P-256 certificate of the same person.</summary>
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<X509SubjectKeyIdentifierExtension>().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<AsnWriter> 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<AsnWriter> 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];
}