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>
757 lines
28 KiB
C#
757 lines
28 KiB
C#
using System.Buffers.Text;
|
|
using System.Formats.Asn1;
|
|
using System.Security.Cryptography;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
|
|
namespace Khaemhat.Infrastructure.Security;
|
|
|
|
/// <summary>A structure that is not a readable CMS SignedData, or whose content cannot be extracted.</summary>
|
|
public sealed class CmsFormatException : Exception
|
|
{
|
|
/// <summary>Creates the exception.</summary>
|
|
public CmsFormatException()
|
|
: base("Not a CMS SignedData structure.")
|
|
{
|
|
}
|
|
|
|
/// <summary>Creates the exception.</summary>
|
|
/// <param name="message">What went wrong.</param>
|
|
public CmsFormatException(string message)
|
|
: base(message)
|
|
{
|
|
}
|
|
|
|
/// <summary>Creates the exception.</summary>
|
|
/// <param name="message">What went wrong.</param>
|
|
/// <param name="innerException">The cause.</param>
|
|
public CmsFormatException(string message, Exception innerException)
|
|
: base(message, innerException)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>A signer of a CMS SignedData with what its certificate says and the result of the check.</summary>
|
|
/// <param name="Name">The name of the signer: common name, else given name and surname, else organization, else
|
|
/// serial number of the subject.</param>
|
|
/// <param name="TaxCode">The tax code of the signer, from the subject's <c>SERIALNUMBER</c> (OID 2.5.4.5) without
|
|
/// the <c>TINIT-</c> or <c>IT:</c> prefix, when present.</param>
|
|
/// <param name="Subject">The subject of the certificate, or <see langword="null"/> when it was not found.</param>
|
|
/// <param name="Issuer">The issuer of the certificate, or <see langword="null"/> when it was not found.</param>
|
|
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
|
|
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
|
|
/// <param name="SigningTime">The <c>signingTime</c> signed attribute: what the signer's clock said, not a trusted timestamp.</param>
|
|
/// <param name="Verified">Whether the digest of the content and the signature match.</param>
|
|
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
|
/// <param name="Certificate">The DER of the signer certificate, or <see langword="null"/> when it was not found.</param>
|
|
public sealed record CmsSigner(
|
|
string? Name, string? TaxCode, string? Subject, string? Issuer,
|
|
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime,
|
|
bool Verified, string? Problem, byte[]? Certificate);
|
|
|
|
/// <summary>The content of one or more nested CMS SignedData envelopes and their signers.</summary>
|
|
/// <param name="Content">The content of the innermost envelope.</param>
|
|
/// <param name="Signers">The signers, outermost envelope first.</param>
|
|
/// <param name="Layers">How many envelopes were opened (two for <c>.xml.p7m.p7m</c>).</param>
|
|
public sealed record CmsContent(byte[] Content, IReadOnlyList<CmsSigner> Signers, int Layers)
|
|
{
|
|
/// <summary>Whether there is at least one signer and every signer of every envelope is verified.</summary>
|
|
public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified);
|
|
|
|
/// <summary>The first problem found, or <see langword="null"/> when <see cref="Verified"/>.</summary>
|
|
public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem;
|
|
|
|
/// <summary>The signer of the outermost envelope, or <see langword="null"/> when there is none.</summary>
|
|
public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as <c>.p7m</c>,
|
|
/// written on <c>System.Formats.Asn1</c> because <c>System.Security.Cryptography.Pkcs</c> is a separate package
|
|
/// (SPEC §1.2).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the
|
|
/// binary with or without line breaks and <c>-----BEGIN</c> armour, and nested envelopes (<c>.p7m.p7m</c>), opened
|
|
/// until the content is no longer CMS.</para>
|
|
/// <para>It checks integrity only: the <c>messageDigest</c> attribute against the content (SHA-1, SHA-256, SHA-384,
|
|
/// SHA-512) and the signature with the public key of the embedded signer certificate (RSA PKCS #1 v1.5, RSA-PSS with
|
|
/// the salt as long as the hash, ECDSA). It does <b>not</b> check the trust chain, the qualified status of the
|
|
/// certificate or its revocation, because no trusted list is available offline; it never follows external
|
|
/// references. A broken signature still returns the content, with <see cref="CmsSigner.Verified"/> false and the
|
|
/// problem; only unreadable structures throw <see cref="CmsFormatException"/>. Detached signatures (no content) are
|
|
/// not supported.</para>
|
|
/// </remarks>
|
|
public static class CmsSignedData
|
|
{
|
|
/// <summary>The largest envelope read, 50 MB.</summary>
|
|
public const int MaxSize = 50 * 1024 * 1024;
|
|
|
|
/// <summary>The most nested envelopes opened.</summary>
|
|
public const int MaxLayers = 8;
|
|
|
|
private const string SignedDataOid = "1.2.840.113549.1.7.2";
|
|
private const string ContentTypeAttributeOid = "1.2.840.113549.1.9.3";
|
|
private const string MessageDigestAttributeOid = "1.2.840.113549.1.9.4";
|
|
private const string SigningTimeAttributeOid = "1.2.840.113549.1.9.5";
|
|
private const string RsaEncryptionOid = "1.2.840.113549.1.1.1";
|
|
private const string RsaPssOid = "1.2.840.113549.1.1.10";
|
|
private const string EcPublicKeyOid = "1.2.840.10045.2.1";
|
|
|
|
// DER of OBJECT IDENTIFIER 1.2.840.113549.1.7.2 (signedData): what follows the header of the outer SEQUENCE.
|
|
private static readonly byte[] SignedDataOidDer = [0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02];
|
|
|
|
private static readonly Asn1Tag Context0 = new(TagClass.ContextSpecific, 0);
|
|
private static readonly Asn1Tag Context0Constructed = new(TagClass.ContextSpecific, 0, isConstructed: true);
|
|
private static readonly Asn1Tag Context1 = new(TagClass.ContextSpecific, 1);
|
|
|
|
/// <summary>Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at.</summary>
|
|
/// <param name="data">The content, or at least its first hundred bytes.</param>
|
|
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
|
public static bool LooksLikeCms(ReadOnlySpan<byte> data)
|
|
{
|
|
if (LooksLikeBinaryCms(data))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
// Base64 text: decode the first characters and look again.
|
|
Span<byte> chars = stackalloc byte[96];
|
|
var count = 0;
|
|
foreach (var b in SkipArmour(SkipBom(data)))
|
|
{
|
|
if (IsBase64Whitespace(b))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (!IsBase64Char(b))
|
|
{
|
|
break;
|
|
}
|
|
|
|
chars[count++] = b;
|
|
if (count == chars.Length)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
count -= count % 4;
|
|
if (count < 24)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
Span<byte> decoded = stackalloc byte[72];
|
|
var status = Base64.DecodeFromUtf8(chars[..count], decoded, out _, out var written, isFinalBlock: false);
|
|
return status is System.Buffers.OperationStatus.Done or System.Buffers.OperationStatus.NeedMoreData
|
|
&& LooksLikeBinaryCms(decoded[..written]);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Opens a CMS SignedData and every envelope nested inside it, and checks the signatures. Accepts DER, BER and
|
|
/// base64 text (see the remarks of the class).
|
|
/// </summary>
|
|
/// <param name="data">The envelope.</param>
|
|
/// <returns>The content of the innermost envelope and the signers.</returns>
|
|
/// <exception cref="CmsFormatException">The data is not a CMS SignedData, is too large, nests too deep, has no
|
|
/// content, or cannot be decoded.</exception>
|
|
public static CmsContent Read(byte[] data)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(data);
|
|
var current = data;
|
|
var signers = new List<CmsSigner>();
|
|
var layers = 0;
|
|
while (true)
|
|
{
|
|
if (current.Length > MaxSize)
|
|
{
|
|
throw new CmsFormatException($"The envelope is larger than {MaxSize / (1024 * 1024)} MB.");
|
|
}
|
|
|
|
var binary = ToBinary(current);
|
|
if (binary is null)
|
|
{
|
|
if (layers == 0)
|
|
{
|
|
throw new CmsFormatException("Not a CMS SignedData structure.");
|
|
}
|
|
|
|
return new CmsContent(current, signers, layers);
|
|
}
|
|
|
|
if (++layers > MaxLayers)
|
|
{
|
|
throw new CmsFormatException($"More than {MaxLayers} nested envelopes.");
|
|
}
|
|
|
|
current = ReadLayer(binary, signers);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, <c>-----BEGIN</c>
|
|
/// and <c>-----END</c> lines dropped, a UTF-8 byte order mark ignored.
|
|
/// </summary>
|
|
/// <param name="text">The text, as bytes.</param>
|
|
/// <returns>The decoded bytes, or <see langword="null"/> when the text is not base64.</returns>
|
|
public static byte[]? DecodeBase64Text(ReadOnlySpan<byte> text)
|
|
{
|
|
var body = SkipBom(text);
|
|
var filtered = new byte[body.Length];
|
|
var count = 0;
|
|
var lineStart = true;
|
|
var skippingLine = false;
|
|
foreach (var b in body)
|
|
{
|
|
if (b is (byte)'\n' or (byte)'\r')
|
|
{
|
|
lineStart = true;
|
|
skippingLine = false;
|
|
continue;
|
|
}
|
|
|
|
if (lineStart && b == (byte)'-')
|
|
{
|
|
skippingLine = true;
|
|
}
|
|
|
|
lineStart = false;
|
|
if (skippingLine || IsBase64Whitespace(b))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (!IsBase64Char(b) && b != (byte)'=')
|
|
{
|
|
return null;
|
|
}
|
|
|
|
filtered[count++] = b;
|
|
}
|
|
|
|
if (count == 0 || count % 4 != 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var output = new byte[Base64.GetMaxDecodedFromUtf8Length(count)];
|
|
var status = Base64.DecodeFromUtf8(filtered.AsSpan(0, count), output, out _, out var written);
|
|
return status == System.Buffers.OperationStatus.Done ? output[..written] : null;
|
|
}
|
|
|
|
private static byte[]? ToBinary(byte[] data)
|
|
{
|
|
if (LooksLikeBinaryCms(data))
|
|
{
|
|
return data;
|
|
}
|
|
|
|
if (!LooksLikeCms(data))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var decoded = DecodeBase64Text(data);
|
|
return decoded is not null && LooksLikeBinaryCms(decoded) ? decoded : null;
|
|
}
|
|
|
|
private static bool LooksLikeBinaryCms(ReadOnlySpan<byte> data)
|
|
{
|
|
if (data.Length < 2 || data[0] != 0x30)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
int header;
|
|
if (data[1] <= 0x80)
|
|
{
|
|
header = 2;
|
|
}
|
|
else
|
|
{
|
|
var lengthBytes = data[1] & 0x7F;
|
|
if (lengthBytes > 4)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
header = 2 + lengthBytes;
|
|
}
|
|
|
|
return data.Length >= header + SignedDataOidDer.Length && data.Slice(header, SignedDataOidDer.Length).SequenceEqual(SignedDataOidDer);
|
|
}
|
|
|
|
private static byte[] ReadLayer(byte[] data, List<CmsSigner> signers)
|
|
{
|
|
try
|
|
{
|
|
var outer = new AsnReader(data, AsnEncodingRules.BER);
|
|
var contentInfo = outer.ReadSequence();
|
|
if (contentInfo.ReadObjectIdentifier() != SignedDataOid)
|
|
{
|
|
throw new CmsFormatException("The envelope is not SignedData.");
|
|
}
|
|
|
|
var signedData = contentInfo.ReadSequence(Context0Constructed).ReadSequence();
|
|
signedData.ReadInteger();
|
|
signedData.ReadSetOf(skipSortOrderValidation: true);
|
|
|
|
var encapsulated = signedData.ReadSequence();
|
|
encapsulated.ReadObjectIdentifier();
|
|
if (!encapsulated.HasData)
|
|
{
|
|
throw new CmsFormatException("The signature is detached: the envelope has no content.");
|
|
}
|
|
|
|
var content = encapsulated.ReadSequence(Context0Constructed).ReadOctetString();
|
|
|
|
var certificates = new List<byte[]>();
|
|
if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context0))
|
|
{
|
|
var set = signedData.ReadSetOf(skipSortOrderValidation: true, Context0);
|
|
while (set.HasData)
|
|
{
|
|
var tag = set.PeekTag();
|
|
var encoded = set.ReadEncodedValue();
|
|
if (tag.HasSameClassAndValue(Asn1Tag.Sequence))
|
|
{
|
|
certificates.Add(encoded.ToArray());
|
|
}
|
|
}
|
|
}
|
|
|
|
if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context1))
|
|
{
|
|
signedData.ReadEncodedValue();
|
|
}
|
|
|
|
var signerInfos = signedData.ReadSetOf(skipSortOrderValidation: true);
|
|
var found = 0;
|
|
while (signerInfos.HasData)
|
|
{
|
|
signers.Add(ReadSigner(signerInfos.ReadSequence(), content, certificates));
|
|
found++;
|
|
}
|
|
|
|
if (found == 0)
|
|
{
|
|
signers.Add(new CmsSigner(null, null, null, null, null, null, null, false, "The envelope has no signer.", null));
|
|
}
|
|
|
|
return content;
|
|
}
|
|
catch (AsnContentException ex)
|
|
{
|
|
throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex);
|
|
}
|
|
catch (CryptographicException ex)
|
|
{
|
|
throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex);
|
|
}
|
|
}
|
|
|
|
private static CmsSigner ReadSigner(AsnReader signerInfo, byte[] content, List<byte[]> certificates)
|
|
{
|
|
signerInfo.ReadInteger();
|
|
byte[]? issuer = null;
|
|
byte[]? serial = null;
|
|
byte[]? keyIdentifier = null;
|
|
if (signerInfo.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence))
|
|
{
|
|
var issuerAndSerial = signerInfo.ReadSequence();
|
|
issuer = issuerAndSerial.ReadEncodedValue().ToArray();
|
|
serial = issuerAndSerial.ReadIntegerBytes().ToArray();
|
|
}
|
|
else
|
|
{
|
|
keyIdentifier = signerInfo.ReadOctetString(Context0);
|
|
}
|
|
|
|
var (digestOid, _) = ReadAlgorithm(signerInfo);
|
|
byte[]? signedAttributes = null;
|
|
if (signerInfo.PeekTag().HasSameClassAndValue(Context0))
|
|
{
|
|
signedAttributes = signerInfo.ReadEncodedValue().ToArray();
|
|
}
|
|
|
|
var (signatureOid, signatureParameters) = ReadAlgorithm(signerInfo);
|
|
var signature = signerInfo.ReadOctetString();
|
|
|
|
DateTimeOffset? signingTime = null;
|
|
byte[]? messageDigest = null;
|
|
if (signedAttributes is not null)
|
|
{
|
|
ReadAttributes(signedAttributes, out messageDigest, out signingTime);
|
|
}
|
|
|
|
using var certificate = FindCertificate(certificates, issuer, serial, keyIdentifier);
|
|
var problem = Verify(certificate, content, digestOid, signedAttributes, messageDigest, signatureOid, signatureParameters, signature);
|
|
return Describe(certificate, signingTime, problem);
|
|
}
|
|
|
|
private static (string Oid, byte[]? Parameters) ReadAlgorithm(AsnReader reader)
|
|
{
|
|
var algorithm = reader.ReadSequence();
|
|
var oid = algorithm.ReadObjectIdentifier();
|
|
var parameters = algorithm.HasData ? algorithm.ReadEncodedValue().ToArray() : null;
|
|
return (oid, parameters);
|
|
}
|
|
|
|
private static void ReadAttributes(byte[] signedAttributes, out byte[]? messageDigest, out DateTimeOffset? signingTime)
|
|
{
|
|
messageDigest = null;
|
|
signingTime = null;
|
|
var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0);
|
|
while (set.HasData)
|
|
{
|
|
var attribute = set.ReadSequence();
|
|
var type = attribute.ReadObjectIdentifier();
|
|
var values = attribute.ReadSetOf(skipSortOrderValidation: true);
|
|
if (!values.HasData)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
switch (type)
|
|
{
|
|
case MessageDigestAttributeOid:
|
|
messageDigest = values.ReadOctetString();
|
|
break;
|
|
case SigningTimeAttributeOid:
|
|
signingTime = values.PeekTag().HasSameClassAndValue(Asn1Tag.UtcTime) ? values.ReadUtcTime() : values.ReadGeneralizedTime();
|
|
break;
|
|
case ContentTypeAttributeOid:
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static X509Certificate2? FindCertificate(List<byte[]> certificates, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier)
|
|
{
|
|
foreach (var der in certificates)
|
|
{
|
|
X509Certificate2 certificate;
|
|
try
|
|
{
|
|
certificate = X509CertificateLoader.LoadCertificate(der);
|
|
}
|
|
catch (CryptographicException)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (Matches(certificate, issuer, serial, keyIdentifier))
|
|
{
|
|
return certificate;
|
|
}
|
|
|
|
certificate.Dispose();
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static bool Matches(X509Certificate2 certificate, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier)
|
|
{
|
|
if (issuer is not null && serial is not null)
|
|
{
|
|
return certificate.IssuerName.RawData.AsSpan().SequenceEqual(issuer)
|
|
&& certificate.SerialNumberBytes.Span.SequenceEqual(serial);
|
|
}
|
|
|
|
return keyIdentifier is not null
|
|
&& certificate.Extensions.OfType<X509SubjectKeyIdentifierExtension>().FirstOrDefault() is { } extension
|
|
&& extension.SubjectKeyIdentifierBytes.Span.SequenceEqual(keyIdentifier);
|
|
}
|
|
|
|
private static string? Verify(
|
|
X509Certificate2? certificate, byte[] content, string digestOid, byte[]? signedAttributes, byte[]? messageDigest,
|
|
string signatureOid, byte[]? signatureParameters, byte[] signature)
|
|
{
|
|
if (certificate is null)
|
|
{
|
|
return "The signer certificate is not in the envelope.";
|
|
}
|
|
|
|
if (HashOf(digestOid) is not { } digest)
|
|
{
|
|
return $"Unsupported digest algorithm {digestOid}.";
|
|
}
|
|
|
|
List<byte[]> signedForms;
|
|
if (signedAttributes is null)
|
|
{
|
|
signedForms = [content];
|
|
}
|
|
else
|
|
{
|
|
if (messageDigest is null)
|
|
{
|
|
return "The signed attributes have no message digest.";
|
|
}
|
|
|
|
if (!CryptographicOperations.FixedTimeEquals(CryptographicOperations.HashData(digest, content), messageDigest))
|
|
{
|
|
return "The content does not match the signed digest: it was changed after signing.";
|
|
}
|
|
|
|
signedForms = SignedAttributesAsSet(signedAttributes);
|
|
}
|
|
|
|
try
|
|
{
|
|
foreach (var signed in signedForms)
|
|
{
|
|
var result = VerifySignature(certificate, signed, digest, signatureOid, signatureParameters, signature);
|
|
if (result is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (result.Length > 0)
|
|
{
|
|
return result;
|
|
}
|
|
}
|
|
}
|
|
catch (CryptographicException ex)
|
|
{
|
|
return "The signature cannot be checked: " + ex.Message;
|
|
}
|
|
|
|
return "The signature does not match the signer certificate.";
|
|
}
|
|
|
|
// The signature covers the DER of the attributes as a SET (tag 0x31), not the [0] implicit tag of the file. The
|
|
// bytes of the file are tried first (they are DER in every well-formed signature); a DER re-encoding after.
|
|
private static List<byte[]> SignedAttributesAsSet(byte[] signedAttributes)
|
|
{
|
|
var forms = new List<byte[]>();
|
|
if (signedAttributes.Length > 1 && signedAttributes[1] != 0x80)
|
|
{
|
|
var asSet = (byte[])signedAttributes.Clone();
|
|
asSet[0] = 0x31;
|
|
forms.Add(asSet);
|
|
}
|
|
|
|
try
|
|
{
|
|
var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0);
|
|
var writer = new AsnWriter(AsnEncodingRules.DER);
|
|
using (writer.PushSetOf())
|
|
{
|
|
while (set.HasData)
|
|
{
|
|
writer.WriteEncodedValue(set.ReadEncodedValue().Span);
|
|
}
|
|
}
|
|
|
|
var der = writer.Encode();
|
|
if (!forms.Exists(f => f.AsSpan().SequenceEqual(der)))
|
|
{
|
|
forms.Add(der);
|
|
}
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
// Attributes that are not DER inside cannot be re-encoded; the bytes of the file are all there is.
|
|
}
|
|
catch (AsnContentException)
|
|
{
|
|
// Same as above.
|
|
}
|
|
|
|
return forms;
|
|
}
|
|
|
|
// Null when verified, an empty string when the signature does not match, a message for an unsupported algorithm.
|
|
private static string? VerifySignature(
|
|
X509Certificate2 certificate, byte[] signed, HashAlgorithmName digest, string signatureOid, byte[]? signatureParameters, byte[] signature)
|
|
{
|
|
switch (signatureOid)
|
|
{
|
|
case RsaPssOid:
|
|
{
|
|
using var rsa = certificate.GetRSAPublicKey();
|
|
if (rsa is null)
|
|
{
|
|
return "The signer certificate has no RSA key.";
|
|
}
|
|
|
|
var pssHash = PssHash(signatureParameters) ?? digest;
|
|
return rsa.VerifyData(signed, signature, pssHash, RSASignaturePadding.Pss) ? null : string.Empty;
|
|
}
|
|
|
|
case EcPublicKeyOid:
|
|
case "1.2.840.10045.4.1":
|
|
case "1.2.840.10045.4.3.2":
|
|
case "1.2.840.10045.4.3.3":
|
|
case "1.2.840.10045.4.3.4":
|
|
{
|
|
using var ecdsa = certificate.GetECDsaPublicKey();
|
|
if (ecdsa is null)
|
|
{
|
|
return "The signer certificate has no ECDSA key.";
|
|
}
|
|
|
|
var hash = signatureOid == EcPublicKeyOid ? digest : HashOfSignature(signatureOid) ?? digest;
|
|
return ecdsa.VerifyData(signed, signature, hash, DSASignatureFormat.Rfc3279DerSequence) ? null : string.Empty;
|
|
}
|
|
|
|
case RsaEncryptionOid:
|
|
case "1.2.840.113549.1.1.5":
|
|
case "1.2.840.113549.1.1.11":
|
|
case "1.2.840.113549.1.1.12":
|
|
case "1.2.840.113549.1.1.13":
|
|
{
|
|
using var rsa = certificate.GetRSAPublicKey();
|
|
if (rsa is null)
|
|
{
|
|
return "The signer certificate has no RSA key.";
|
|
}
|
|
|
|
var hash = signatureOid == RsaEncryptionOid ? digest : HashOfSignature(signatureOid) ?? digest;
|
|
return rsa.VerifyData(signed, signature, hash, RSASignaturePadding.Pkcs1) ? null : string.Empty;
|
|
}
|
|
|
|
default:
|
|
return $"Unsupported signature algorithm {signatureOid}.";
|
|
}
|
|
}
|
|
|
|
private static HashAlgorithmName? HashOf(string digestOid) => digestOid switch
|
|
{
|
|
"1.3.14.3.2.26" => HashAlgorithmName.SHA1,
|
|
"2.16.840.1.101.3.4.2.1" => HashAlgorithmName.SHA256,
|
|
"2.16.840.1.101.3.4.2.2" => HashAlgorithmName.SHA384,
|
|
"2.16.840.1.101.3.4.2.3" => HashAlgorithmName.SHA512,
|
|
_ => null,
|
|
};
|
|
|
|
private static HashAlgorithmName? HashOfSignature(string signatureOid) => signatureOid switch
|
|
{
|
|
"1.2.840.113549.1.1.5" or "1.2.840.10045.4.1" => HashAlgorithmName.SHA1,
|
|
"1.2.840.113549.1.1.11" or "1.2.840.10045.4.3.2" => HashAlgorithmName.SHA256,
|
|
"1.2.840.113549.1.1.12" or "1.2.840.10045.4.3.3" => HashAlgorithmName.SHA384,
|
|
"1.2.840.113549.1.1.13" or "1.2.840.10045.4.3.4" => HashAlgorithmName.SHA512,
|
|
_ => null,
|
|
};
|
|
|
|
// RSASSA-PSS-params: hashAlgorithm [0] (default SHA-1), maskGenAlgorithm [1], saltLength [2], trailerField [3].
|
|
private static HashAlgorithmName? PssHash(byte[]? parameters)
|
|
{
|
|
if (parameters is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var sequence = new AsnReader(parameters, AsnEncodingRules.BER).ReadSequence();
|
|
if (!sequence.HasData || !sequence.PeekTag().HasSameClassAndValue(Context0))
|
|
{
|
|
return HashAlgorithmName.SHA1;
|
|
}
|
|
|
|
var (oid, _) = ReadAlgorithm(sequence.ReadSequence(Context0Constructed));
|
|
return HashOf(oid);
|
|
}
|
|
|
|
private static CmsSigner Describe(X509Certificate2? certificate, DateTimeOffset? signingTime, string? problem)
|
|
{
|
|
if (certificate is null)
|
|
{
|
|
return new CmsSigner(null, null, null, null, null, null, signingTime, false, problem, null);
|
|
}
|
|
|
|
string? commonName = null, givenName = null, surname = null, organization = null, serialNumber = null;
|
|
foreach (var rdn in certificate.SubjectName.EnumerateRelativeDistinguishedNames())
|
|
{
|
|
if (rdn.HasMultipleElements)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var value = rdn.GetSingleElementValue();
|
|
switch (rdn.GetSingleElementType().Value)
|
|
{
|
|
case "2.5.4.3":
|
|
commonName ??= value;
|
|
break;
|
|
case "2.5.4.42":
|
|
givenName ??= value;
|
|
break;
|
|
case "2.5.4.4":
|
|
surname ??= value;
|
|
break;
|
|
case "2.5.4.10":
|
|
organization ??= value;
|
|
break;
|
|
case "2.5.4.5":
|
|
serialNumber ??= value;
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
var personName = string.Join(' ', new[] { givenName, surname }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
|
var name = NullIfBlank(commonName) ?? NullIfBlank(personName) ?? NullIfBlank(organization) ?? NullIfBlank(serialNumber);
|
|
return new CmsSigner(
|
|
name,
|
|
TaxCodeOf(serialNumber),
|
|
certificate.Subject,
|
|
certificate.Issuer,
|
|
new DateTimeOffset(certificate.NotBefore.ToUniversalTime(), TimeSpan.Zero),
|
|
new DateTimeOffset(certificate.NotAfter.ToUniversalTime(), TimeSpan.Zero),
|
|
signingTime,
|
|
problem is null,
|
|
problem,
|
|
certificate.RawData);
|
|
}
|
|
|
|
// ETSI EN 319 412-1: SERIALNUMBER = TINIT-<tax code>; older Italian certificates use IT:<tax code>.
|
|
private static string? TaxCodeOf(string? serialNumber)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(serialNumber))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var value = serialNumber.Trim();
|
|
if (value.StartsWith("TINIT-", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return NullIfBlank(value["TINIT-".Length..].Trim());
|
|
}
|
|
|
|
if (value.StartsWith("IT:", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return NullIfBlank(value["IT:".Length..].Trim());
|
|
}
|
|
|
|
return value.Length is 11 or 16 && value.All(char.IsAsciiLetterOrDigit) ? value.ToUpperInvariant() : null;
|
|
}
|
|
|
|
private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value;
|
|
|
|
private static ReadOnlySpan<byte> SkipBom(ReadOnlySpan<byte> data) =>
|
|
data.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]) ? data[3..] : data;
|
|
|
|
private static ReadOnlySpan<byte> SkipArmour(ReadOnlySpan<byte> data)
|
|
{
|
|
var trimmed = data.TrimStart((ReadOnlySpan<byte>)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']);
|
|
if (!trimmed.StartsWith("-----"u8))
|
|
{
|
|
return trimmed;
|
|
}
|
|
|
|
var end = trimmed.IndexOf((byte)'\n');
|
|
return end < 0 ? [] : trimmed[(end + 1)..];
|
|
}
|
|
|
|
private static bool IsBase64Char(byte b) =>
|
|
b is (>= (byte)'A' and <= (byte)'Z') or (>= (byte)'a' and <= (byte)'z') or (>= (byte)'0' and <= (byte)'9') or (byte)'+' or (byte)'/';
|
|
|
|
private static bool IsBase64Whitespace(byte b) => b is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n';
|
|
}
|