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>
This commit is contained in:
1 parent
2c56c0dff0
commit
9a40adecfe
8 files changed
+2516
No files matched your search
@@ -0,0 +1,269 @@
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
// The supplier invoices received as files of the country's e-invoice format (Italy: FatturaPA, also signed .p7m).
|
||||
// The records keep the file as it is, with the codes of the format; the import service maps them to documents.
|
||||
|
||||
/// <summary>
|
||||
/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like
|
||||
/// <see cref="IEInvoiceFormat"/>. The reader only reads: it never contacts a service and never resolves external
|
||||
/// references.
|
||||
/// </summary>
|
||||
public interface IIncomingInvoiceReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the file looks like one the reader understands (Italy: <c>.xml</c>, <c>.p7m</c> in DER or as base64
|
||||
/// text). The content is sniffed, not only the name.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file, extension included.</param>
|
||||
/// <param name="content">The content, or at least its first bytes.</param>
|
||||
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
||||
bool CanRead(string fileName, ReadOnlySpan<byte> content);
|
||||
|
||||
/// <summary>Reads a file.</summary>
|
||||
/// <param name="fileName">The name of the file, extension included.</param>
|
||||
/// <param name="content">The whole content.</param>
|
||||
/// <returns>The file with its invoices.</returns>
|
||||
/// <exception cref="IncomingInvoiceException">The file is not readable, not an invoice, or misses mandatory data;
|
||||
/// <see cref="IncomingInvoiceException.Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</exception>
|
||||
IncomingInvoiceFile Read(string fileName, byte[] content);
|
||||
}
|
||||
|
||||
/// <summary>A received e-invoice file that cannot be read; <see cref="Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</summary>
|
||||
public sealed class IncomingInvoiceException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public IncomingInvoiceException()
|
||||
: this(IncomingInvoiceErrors.NotReadable, "The file is not readable.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public IncomingInvoiceException(string message)
|
||||
: this(IncomingInvoiceErrors.NotReadable, message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public IncomingInvoiceException(string message, Exception innerException)
|
||||
: this(IncomingInvoiceErrors.NotReadable, message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a code.</summary>
|
||||
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public IncomingInvoiceException(string code, string message)
|
||||
: base(message) => Code = code;
|
||||
|
||||
/// <summary>Creates the exception with a code and its cause.</summary>
|
||||
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public IncomingInvoiceException(string code, string message, Exception? innerException)
|
||||
: base(message, innerException) => Code = code;
|
||||
|
||||
/// <summary>The text code of the error, one of <see cref="IncomingInvoiceErrors"/>.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>The codes of <see cref="IncomingInvoiceException"/>.</summary>
|
||||
public static class IncomingInvoiceErrors
|
||||
{
|
||||
/// <summary>Neither XML nor a signed envelope: garbage, an empty file, a truncated download.</summary>
|
||||
public const string NotReadable = "incoming.not-readable";
|
||||
|
||||
/// <summary>A well-formed XML document that is not an e-invoice.</summary>
|
||||
public const string NotInvoice = "incoming.not-invoice";
|
||||
|
||||
/// <summary>A signed envelope whose content cannot be extracted.</summary>
|
||||
public const string SignatureBroken = "incoming.signature-broken";
|
||||
|
||||
/// <summary>An e-invoice that misses mandatory data (date, number, document type...).</summary>
|
||||
public const string Invalid = "incoming.invalid";
|
||||
}
|
||||
|
||||
/// <summary>A received e-invoice file: the transmission header, the two parties and one or more invoices.</summary>
|
||||
/// <param name="FileName">The name of the file as received.</param>
|
||||
/// <param name="TransmissionFormat">The transmission format (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</param>
|
||||
/// <param name="ProgressiveNumber">The progressive number of the transmission given by the sender.</param>
|
||||
/// <param name="RecipientCode">The recipient code of the transmission.</param>
|
||||
/// <param name="Supplier">The supplier who issued the invoices.</param>
|
||||
/// <param name="Customer">The customer the invoices are addressed to (normally the company).</param>
|
||||
/// <param name="Invoices">The invoices, one per body of the file (a batch has more than one).</param>
|
||||
/// <param name="Signature">The signature of the envelope, or <see langword="null"/> for an unsigned file.</param>
|
||||
/// <param name="Xml">The XML of the invoice, taken out of the envelope when the file was signed.</param>
|
||||
public sealed record IncomingInvoiceFile(
|
||||
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
|
||||
IncomingParty Supplier, IncomingParty Customer, IReadOnlyList<IncomingInvoice> Invoices,
|
||||
IncomingSignature? Signature, byte[] Xml);
|
||||
|
||||
/// <summary>
|
||||
/// The signature of a signed file. <see cref="Verified"/> says only that the content is intact and signed by the key
|
||||
/// of the embedded certificate: the trust chain and the revocation of the certificate are not checked, because no
|
||||
/// trusted list is available offline.
|
||||
/// </summary>
|
||||
/// <param name="Verified">Whether the digest and the signature match the content.</param>
|
||||
/// <param name="Signer">The name of the signer, from the certificate.</param>
|
||||
/// <param name="SignerTaxCode">The tax code of the signer, when the certificate carries it.</param>
|
||||
/// <param name="SignedAt">The signing time declared by the signer, if any (not a trusted timestamp).</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="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
||||
public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
|
||||
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
|
||||
|
||||
/// <summary>A party of the invoice (supplier or customer) as written in the file.</summary>
|
||||
/// <param name="CountryCode">The country of the VAT number.</param>
|
||||
/// <param name="VatNumber">The VAT number without the country prefix.</param>
|
||||
/// <param name="TaxCode">The tax code.</param>
|
||||
/// <param name="Name">The company name, when the party is a company.</param>
|
||||
/// <param name="FirstName">The first name, when the party is a person.</param>
|
||||
/// <param name="LastName">The last name, when the party is a person.</param>
|
||||
/// <param name="Address">The street of the registered office.</param>
|
||||
/// <param name="StreetNumber">The street number.</param>
|
||||
/// <param name="PostalCode">The postal code.</param>
|
||||
/// <param name="City">The city.</param>
|
||||
/// <param name="Province">The province.</param>
|
||||
/// <param name="Country">The country of the registered office.</param>
|
||||
/// <param name="TaxRegime">The tax regime (supplier only).</param>
|
||||
/// <param name="Email">The e-mail address (supplier only).</param>
|
||||
/// <param name="Phone">The phone number (supplier only).</param>
|
||||
/// <param name="ReaOffice">The office of the companies register.</param>
|
||||
/// <param name="ReaNumber">The number in the companies register.</param>
|
||||
public sealed record IncomingParty(
|
||||
string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName,
|
||||
string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country,
|
||||
string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber)
|
||||
{
|
||||
/// <summary>The company name, or first and last name of a person.</summary>
|
||||
public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
}
|
||||
|
||||
/// <summary>An invoice of the file (one body).</summary>
|
||||
/// <param name="DocumentType">The document type (Italy: <c>TD01</c>, <c>TD04</c>...).</param>
|
||||
/// <param name="Currency">The currency code.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="Number">The number of the document.</param>
|
||||
/// <param name="Total">The total amount declared by the supplier, if any.</param>
|
||||
/// <param name="Rounding">The rounding on the total, if any.</param>
|
||||
/// <param name="Causals">The free-text causals.</param>
|
||||
/// <param name="Art73">Whether the document is issued under the rule that allows several documents with the same
|
||||
/// number in a year (Italy: art. 73 DPR 633/72).</param>
|
||||
/// <param name="Withholdings">The withholding taxes.</param>
|
||||
/// <param name="StampDuty">The stamp duty, if any.</param>
|
||||
/// <param name="SocialSecurity">The social security contributions.</param>
|
||||
/// <param name="Discounts">The discounts and surcharges on the whole document.</param>
|
||||
/// <param name="Orders">The purchase orders referred to.</param>
|
||||
/// <param name="Contracts">The contracts referred to.</param>
|
||||
/// <param name="RelatedInvoices">The invoices referred to (the invoice a credit note corrects).</param>
|
||||
/// <param name="DeliveryNotes">The delivery notes referred to.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
/// <param name="TaxSummary">The tax summary, one row per rate or nature.</param>
|
||||
/// <param name="Payments">The payment installments.</param>
|
||||
/// <param name="Attachments">The attached files.</param>
|
||||
public sealed record IncomingInvoice(
|
||||
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
|
||||
IReadOnlyList<string> Causals, bool Art73,
|
||||
IReadOnlyList<IncomingWithholding> Withholdings, IncomingStampDuty? StampDuty,
|
||||
IReadOnlyList<IncomingSocialSecurity> SocialSecurity, IReadOnlyList<IncomingDiscount> Discounts,
|
||||
IReadOnlyList<IncomingReference> Orders, IReadOnlyList<IncomingReference> Contracts,
|
||||
IReadOnlyList<IncomingReference> RelatedInvoices, IReadOnlyList<IncomingReference> DeliveryNotes,
|
||||
IReadOnlyList<IncomingLine> Lines, IReadOnlyList<IncomingTaxSummary> TaxSummary,
|
||||
IReadOnlyList<IncomingPayment> Payments, IReadOnlyList<IncomingAttachment> Attachments);
|
||||
|
||||
/// <summary>A line of an invoice.</summary>
|
||||
/// <param name="Number">The line number.</param>
|
||||
/// <param name="Codes">The item codes (type and value).</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Quantity">The quantity, if given.</param>
|
||||
/// <param name="Unit">The unit of measure, if given.</param>
|
||||
/// <param name="UnitPrice">The unit price.</param>
|
||||
/// <param name="TotalPrice">The total of the line, net of tax.</param>
|
||||
/// <param name="TaxRate">The tax rate in percent (zero with a nature).</param>
|
||||
/// <param name="Nature">The reason of a zero rate (Italy: <c>N2.2</c>...).</param>
|
||||
/// <param name="Discounts">The discounts and surcharges of the line.</param>
|
||||
/// <param name="Withheld">Whether the line is subject to withholding tax.</param>
|
||||
/// <param name="LineType">The kind of line (Italy: <c>SC</c> discount, <c>PR</c> premium, <c>AB</c> rebate,
|
||||
/// <c>AC</c> ancillary cost).</param>
|
||||
/// <param name="PeriodStart">The start of the period the line refers to.</param>
|
||||
/// <param name="PeriodEnd">The end of the period the line refers to.</param>
|
||||
/// <param name="AdministrativeReference">The administrative reference (cost centre, internal code).</param>
|
||||
public sealed record IncomingLine(
|
||||
int Number, IReadOnlyList<IncomingItemCode> Codes, string Description, decimal? Quantity, string? Unit,
|
||||
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<IncomingDiscount> Discounts,
|
||||
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference);
|
||||
|
||||
/// <summary>A code of the item of a line.</summary>
|
||||
/// <param name="Type">The kind of code (<c>EAN</c>, <c>SKU</c>, the supplier's code...).</param>
|
||||
/// <param name="Value">The code.</param>
|
||||
public sealed record IncomingItemCode(string Type, string Value);
|
||||
|
||||
/// <summary>A discount or surcharge.</summary>
|
||||
/// <param name="IsSurcharge">Whether it is a surcharge (Italy: <c>MG</c>) instead of a discount (<c>SC</c>).</param>
|
||||
/// <param name="Percent">The percentage, if given.</param>
|
||||
/// <param name="Amount">The amount, if given.</param>
|
||||
public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
|
||||
|
||||
/// <summary>A row of the tax summary.</summary>
|
||||
/// <param name="Rate">The tax rate in percent.</param>
|
||||
/// <param name="Nature">The reason of a zero rate.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="Tax">The tax.</param>
|
||||
/// <param name="Exigibility">When the tax is due (Italy: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment).</param>
|
||||
/// <param name="LegalReference">The law that justifies the nature.</param>
|
||||
/// <param name="ExpensesAmount">Ancillary expenses, if any.</param>
|
||||
/// <param name="Rounding">The rounding, if any.</param>
|
||||
public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
|
||||
string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
|
||||
|
||||
/// <summary>A payment installment.</summary>
|
||||
/// <param name="Conditions">The payment conditions (Italy: <c>TP01</c> installments, <c>TP02</c> full, <c>TP03</c> advance).</param>
|
||||
/// <param name="Method">The payment method (Italy: <c>MP05</c> bank transfer...).</param>
|
||||
/// <param name="DueDate">The due date, if given.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
/// <param name="Iban">The IBAN to pay to, if given.</param>
|
||||
/// <param name="Bic">The BIC, if given.</param>
|
||||
/// <param name="Beneficiary">The beneficiary, if different from the supplier.</param>
|
||||
public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
|
||||
string? Iban, string? Bic, string? Beneficiary);
|
||||
|
||||
/// <summary>A reference to another document (order, contract, invoice, delivery note).</summary>
|
||||
/// <param name="Id">The number of the document.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="LineNumbers">The lines of the invoice the reference applies to; empty when it applies to all.</param>
|
||||
/// <param name="Cig">The tender code, if any (public administration).</param>
|
||||
/// <param name="Cup">The project code, if any (public administration).</param>
|
||||
public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList<int> LineNumbers, string? Cig, string? Cup);
|
||||
|
||||
/// <summary>A withholding tax.</summary>
|
||||
/// <param name="Type">The kind of withholding (Italy: <c>RT01</c>...).</param>
|
||||
/// <param name="Amount">The amount withheld.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Reason">The payment reason (Italy: <c>A</c>...), if given.</param>
|
||||
public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
|
||||
|
||||
/// <summary>The stamp duty of an invoice.</summary>
|
||||
/// <param name="Virtual">Whether it is paid virtually by the issuer.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
public sealed record IncomingStampDuty(bool Virtual, decimal Amount);
|
||||
|
||||
/// <summary>A social security contribution added to the invoice.</summary>
|
||||
/// <param name="Fund">The fund (Italy: <c>TC01</c>...).</param>
|
||||
/// <param name="Rate">The rate of the contribution in percent.</param>
|
||||
/// <param name="Amount">The amount of the contribution.</param>
|
||||
/// <param name="Taxable">The amount the contribution is computed on, if given.</param>
|
||||
/// <param name="TaxRate">The tax rate applied to the contribution.</param>
|
||||
/// <param name="Withheld">Whether the contribution is subject to withholding tax.</param>
|
||||
/// <param name="Nature">The reason of a zero tax rate.</param>
|
||||
public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
|
||||
bool Withheld, string? Nature);
|
||||
|
||||
/// <summary>A file attached to the invoice.</summary>
|
||||
/// <param name="Name">The name of the attachment.</param>
|
||||
/// <param name="Format">The format declared by the supplier (such as <c>PDF</c>), if any.</param>
|
||||
/// <param name="Description">The description, if any.</param>
|
||||
/// <param name="Content">The decoded content.</param>
|
||||
public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);
|
||||
@@ -0,0 +1,517 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x
|
||||
/// (<c>FPR12</c>, <c>FPA12</c>), simplified invoices (<c>FSM10</c>), plain <c>.xml</c> or signed CAdES <c>.p7m</c>
|
||||
/// (binary or base64 text, also nested).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Elements are matched by local name, whatever the namespace or prefix (<c>p:</c>, <c>ns2:</c>, none). The XML
|
||||
/// is read with DTDs prohibited and no resolver, so nothing external is ever loaded. A UTF-8 byte order mark, a
|
||||
/// missing XML declaration, an ISO-8859-1 or windows-1252 declaration and leading whitespace are tolerated.</para>
|
||||
/// <para>Amounts use the invariant culture (<c>.</c> separator) and dates <c>yyyy-MM-dd</c>. The reader does not
|
||||
/// validate the file against the XSD nor recompute totals: it reports what the supplier wrote and rejects only files
|
||||
/// without the data an import cannot do without (document type, date, number, prices and rates of the lines, the
|
||||
/// rows of the tax summary, the amounts of withholdings and payments). A missing <c>Divisa</c> is read as
|
||||
/// <c>EUR</c>; an attachment whose content is not valid base64 is kept with an empty content.</para>
|
||||
/// <para>For signed files the signature is checked for integrity only (see <see cref="CmsSignedData"/>): no trust chain
|
||||
/// and no revocation check.</para>
|
||||
/// <para>Simplified invoices (<c>FSM10</c>): each <c>DatiBeniServizi</c> becomes a line with no quantity whose unit and
|
||||
/// total price are <c>Importo</c> minus the tax, because there <c>Importo</c> includes the tax. The tax is
|
||||
/// <c>DatiIVA/Imposta</c> or, when only the rate is given, the tax included in <c>Importo</c> at that rate; the rate is
|
||||
/// <c>DatiIVA/Aliquota</c> or, when only the tax is given, derived from it. The tax summary groups the lines by rate and
|
||||
/// nature, the total is the sum of <c>Importo</c> and <c>DatiFatturaRettificata</c> becomes the related invoice.</para>
|
||||
/// </remarks>
|
||||
public sealed class FatturaPaReader : IIncomingInvoiceReader
|
||||
{
|
||||
/// <summary>The largest file read, as for signed envelopes (50 MB).</summary>
|
||||
public const int MaxSize = CmsSignedData.MaxSize;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanRead(string fileName, ReadOnlySpan<byte> content) =>
|
||||
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
|
||||
|
||||
/// <inheritdoc />
|
||||
public IncomingInvoiceFile Read(string fileName, byte[] content)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fileName);
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
if (content.Length == 0)
|
||||
{
|
||||
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is empty.");
|
||||
}
|
||||
|
||||
if (content.Length > MaxSize)
|
||||
{
|
||||
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB.");
|
||||
}
|
||||
|
||||
IncomingSignature? signature = null;
|
||||
var xml = content;
|
||||
if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content))
|
||||
{
|
||||
CmsContent envelope;
|
||||
try
|
||||
{
|
||||
envelope = CmsSignedData.Read(content);
|
||||
}
|
||||
catch (CmsFormatException ex)
|
||||
{
|
||||
throw new IncomingInvoiceException(IncomingInvoiceErrors.SignatureBroken, "The content of the signed file cannot be extracted: " + ex.Message, ex);
|
||||
}
|
||||
|
||||
xml = envelope.Content;
|
||||
var signer = envelope.Signer;
|
||||
signature = new IncomingSignature(
|
||||
envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime,
|
||||
signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem);
|
||||
}
|
||||
|
||||
if (!LooksLikeXml(xml))
|
||||
{
|
||||
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is neither XML nor a signed envelope.");
|
||||
}
|
||||
|
||||
var root = Parse(xml).Root
|
||||
?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML has no root element.");
|
||||
return root.Name.LocalName switch
|
||||
{
|
||||
"FatturaElettronica" => ReadOrdinary(fileName, root, signature, xml),
|
||||
"FatturaElettronicaSemplificata" => ReadSimplified(fileName, root, signature, xml),
|
||||
_ => throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not an electronic invoice."),
|
||||
};
|
||||
}
|
||||
|
||||
// --- XML -------------------------------------------------------------------------------------------------------
|
||||
|
||||
private static bool LooksLikeXml(ReadOnlySpan<byte> content)
|
||||
{
|
||||
if (content.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
|
||||
{
|
||||
content = content[3..];
|
||||
}
|
||||
else if (content.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var trimmed = content.TrimStart((ReadOnlySpan<byte>)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']);
|
||||
return !trimmed.IsEmpty && trimmed[0] == (byte)'<';
|
||||
}
|
||||
|
||||
private static XDocument Parse(byte[] xml)
|
||||
{
|
||||
var text = Decode(xml).TrimStart('', ' ', '\t', '\r', '\n');
|
||||
var settings = new XmlReaderSettings
|
||||
{
|
||||
DtdProcessing = DtdProcessing.Prohibit,
|
||||
XmlResolver = null,
|
||||
IgnoreComments = true,
|
||||
IgnoreProcessingInstructions = true,
|
||||
};
|
||||
try
|
||||
{
|
||||
using var reader = XmlReader.Create(new StringReader(text), settings);
|
||||
return XDocument.Load(reader);
|
||||
}
|
||||
catch (XmlException ex)
|
||||
{
|
||||
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML is not well formed: " + ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
// The text is decoded here, then read from a string: the encoding of the declaration is honoured without the
|
||||
// reader having to know code pages (windows-1252 is common in files written by older programs).
|
||||
private static string Decode(byte[] xml)
|
||||
{
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
|
||||
{
|
||||
return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3);
|
||||
}
|
||||
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]))
|
||||
{
|
||||
return Encoding.Unicode.GetString(xml, 2, xml.Length - 2);
|
||||
}
|
||||
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
|
||||
{
|
||||
return Encoding.BigEndianUnicode.GetString(xml, 2, xml.Length - 2);
|
||||
}
|
||||
|
||||
return EncodingOfDeclaration(xml).GetString(xml);
|
||||
}
|
||||
|
||||
private static Encoding EncodingOfDeclaration(byte[] xml)
|
||||
{
|
||||
var head = Encoding.ASCII.GetString(xml, 0, Math.Min(xml.Length, 256));
|
||||
var start = head.IndexOf("<?xml", StringComparison.Ordinal);
|
||||
var end = start < 0 ? -1 : head.IndexOf("?>", start, StringComparison.Ordinal);
|
||||
if (end < 0)
|
||||
{
|
||||
return new UTF8Encoding(false);
|
||||
}
|
||||
|
||||
var declaration = head[start..end];
|
||||
var at = declaration.IndexOf("encoding", StringComparison.OrdinalIgnoreCase);
|
||||
if (at < 0)
|
||||
{
|
||||
return new UTF8Encoding(false);
|
||||
}
|
||||
|
||||
var quote = declaration.IndexOfAny(['"', '\''], at);
|
||||
var close = quote < 0 ? -1 : declaration.IndexOf(declaration[quote], quote + 1);
|
||||
if (close < 0)
|
||||
{
|
||||
return new UTF8Encoding(false);
|
||||
}
|
||||
|
||||
var name = declaration[(quote + 1)..close].Trim().ToUpperInvariant();
|
||||
return name switch
|
||||
{
|
||||
"UTF-8" or "UTF8" => new UTF8Encoding(false),
|
||||
"ISO-8859-1" or "LATIN1" or "ISO8859-1" => Encoding.Latin1,
|
||||
"WINDOWS-1252" or "CP1252" => CodePage(1252),
|
||||
"ISO-8859-15" => CodePage(28605),
|
||||
_ => new UTF8Encoding(false),
|
||||
};
|
||||
}
|
||||
|
||||
private static Encoding CodePage(int codePage) =>
|
||||
CodePagesEncodingProvider.Instance.GetEncoding(codePage) ?? Encoding.Latin1;
|
||||
|
||||
// --- Ordinary invoice --------------------------------------------------------------------------------------------
|
||||
|
||||
private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
|
||||
{
|
||||
var header = El(root, "FatturaElettronicaHeader")
|
||||
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
|
||||
var transmission = El(header, "DatiTrasmissione");
|
||||
var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore.");
|
||||
var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente.");
|
||||
var bodies = Els(root, "FatturaElettronicaBody").ToList();
|
||||
if (bodies.Count == 0)
|
||||
{
|
||||
throw Invalid("The invoice has no FatturaElettronicaBody.");
|
||||
}
|
||||
|
||||
return new IncomingInvoiceFile(
|
||||
fileName,
|
||||
Text(transmission, "FormatoTrasmissione"),
|
||||
Text(transmission, "ProgressivoInvio"),
|
||||
Text(transmission, "CodiceDestinatario"),
|
||||
ReadParty(supplier),
|
||||
ReadParty(customer),
|
||||
bodies.Select(ReadBody).ToList(),
|
||||
signature,
|
||||
xml);
|
||||
}
|
||||
|
||||
private static IncomingParty ReadParty(XElement party)
|
||||
{
|
||||
var personal = El(party, "DatiAnagrafici");
|
||||
var identifiers = El(party, "IdentificativiFiscali");
|
||||
var others = El(party, "AltriDatiIdentificativi");
|
||||
var vat = El(personal, "IdFiscaleIVA") ?? El(identifiers, "IdFiscaleIVA") ?? El(party, "IdFiscaleIVA");
|
||||
var names = El(personal, "Anagrafica") ?? others ?? party;
|
||||
var office = El(party, "Sede") ?? El(others, "Sede");
|
||||
var register = El(party, "IscrizioneREA");
|
||||
var contacts = El(party, "Contatti");
|
||||
return new IncomingParty(
|
||||
Text(vat, "IdPaese"),
|
||||
Text(vat, "IdCodice"),
|
||||
Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"),
|
||||
Text(names, "Denominazione"),
|
||||
Text(names, "Nome"),
|
||||
Text(names, "Cognome"),
|
||||
Text(office, "Indirizzo"),
|
||||
Text(office, "NumeroCivico"),
|
||||
Text(office, "CAP"),
|
||||
Text(office, "Comune"),
|
||||
Text(office, "Provincia"),
|
||||
Text(office, "Nazione"),
|
||||
Text(personal, "RegimeFiscale") ?? Text(party, "RegimeFiscale"),
|
||||
Text(contacts, "Email"),
|
||||
Text(contacts, "Telefono"),
|
||||
Text(register, "Ufficio"),
|
||||
Text(register, "NumeroREA"));
|
||||
}
|
||||
|
||||
private static IncomingInvoice ReadBody(XElement body, int index)
|
||||
{
|
||||
var general = El(body, "DatiGenerali");
|
||||
var document = El(general, "DatiGeneraliDocumento")
|
||||
?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento.");
|
||||
var goods = El(body, "DatiBeniServizi");
|
||||
var stamp = El(document, "DatiBollo");
|
||||
|
||||
return new IncomingInvoice(
|
||||
Required(document, "TipoDocumento", index),
|
||||
Text(document, "Divisa") ?? "EUR",
|
||||
RequiredDate(document, "Data", index),
|
||||
Required(document, "Numero", index),
|
||||
OptionalDecimal(document, "ImportoTotaleDocumento"),
|
||||
OptionalDecimal(document, "Arrotondamento"),
|
||||
Els(document, "Causale").Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList(),
|
||||
Flag(document, "Art73"),
|
||||
Els(document, "DatiRitenuta").Select(w => new IncomingWithholding(
|
||||
Required(w, "TipoRitenuta", index),
|
||||
RequiredDecimal(w, "ImportoRitenuta", index),
|
||||
RequiredDecimal(w, "AliquotaRitenuta", index),
|
||||
Text(w, "CausalePagamento"))).ToList(),
|
||||
stamp is null ? null : new IncomingStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m),
|
||||
Els(document, "DatiCassaPrevidenziale").Select(s => new IncomingSocialSecurity(
|
||||
Required(s, "TipoCassa", index),
|
||||
RequiredDecimal(s, "AlCassa", index),
|
||||
RequiredDecimal(s, "ImportoContributoCassa", index),
|
||||
OptionalDecimal(s, "ImponibileCassa"),
|
||||
RequiredDecimal(s, "AliquotaIVA", index),
|
||||
Flag(s, "Ritenuta"),
|
||||
Text(s, "Natura"))).ToList(),
|
||||
ReadDiscounts(document),
|
||||
ReadReferences(general, "DatiOrdineAcquisto"),
|
||||
ReadReferences(general, "DatiContratto"),
|
||||
ReadReferences(general, "DatiFattureCollegate"),
|
||||
Els(general, "DatiDDT").Select(d => new IncomingReference(
|
||||
Text(d, "NumeroDDT"), OptionalDate(d, "DataDDT"), LineNumbers(d), null, null)).ToList(),
|
||||
Els(goods, "DettaglioLinee").Select((l, i) => ReadLine(l, i, index)).ToList(),
|
||||
Els(goods, "DatiRiepilogo").Select(r => new IncomingTaxSummary(
|
||||
RequiredDecimal(r, "AliquotaIVA", index),
|
||||
Text(r, "Natura"),
|
||||
RequiredDecimal(r, "ImponibileImporto", index),
|
||||
RequiredDecimal(r, "Imposta", index),
|
||||
Text(r, "EsigibilitaIVA"),
|
||||
Text(r, "RiferimentoNormativo"),
|
||||
OptionalDecimal(r, "SpeseAccessorie"),
|
||||
OptionalDecimal(r, "Arrotondamento"))).ToList(),
|
||||
ReadPayments(body, index),
|
||||
ReadAttachments(body));
|
||||
}
|
||||
|
||||
private static IncomingLine ReadLine(XElement line, int position, int index) => new(
|
||||
OptionalInt(line, "NumeroLinea") ?? position + 1,
|
||||
Els(line, "CodiceArticolo")
|
||||
.Select(c => new IncomingItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty))
|
||||
.Where(c => c.Value.Length > 0)
|
||||
.ToList(),
|
||||
Text(line, "Descrizione") ?? string.Empty,
|
||||
OptionalDecimal(line, "Quantita"),
|
||||
Text(line, "UnitaMisura"),
|
||||
RequiredDecimal(line, "PrezzoUnitario", index),
|
||||
RequiredDecimal(line, "PrezzoTotale", index),
|
||||
RequiredDecimal(line, "AliquotaIVA", index),
|
||||
Text(line, "Natura"),
|
||||
ReadDiscounts(line),
|
||||
Flag(line, "Ritenuta"),
|
||||
Text(line, "TipoCessionePrestazione"),
|
||||
OptionalDate(line, "DataInizioPeriodo"),
|
||||
OptionalDate(line, "DataFinePeriodo"),
|
||||
Text(line, "RiferimentoAmministrazione"));
|
||||
|
||||
private static List<IncomingDiscount> ReadDiscounts(XElement? parent) =>
|
||||
Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount(
|
||||
string.Equals(Text(d, "Tipo"), "MG", StringComparison.OrdinalIgnoreCase),
|
||||
OptionalDecimal(d, "Percentuale"),
|
||||
OptionalDecimal(d, "Importo"))).ToList();
|
||||
|
||||
private static List<IncomingReference> ReadReferences(XElement? general, string name) =>
|
||||
Els(general, name).Select(r => new IncomingReference(
|
||||
Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList();
|
||||
|
||||
private static List<int> LineNumbers(XElement reference) =>
|
||||
Els(reference, "RiferimentoNumeroLinea")
|
||||
.Select(n => int.TryParse(n.Value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : 0)
|
||||
.Where(n => n > 0)
|
||||
.ToList();
|
||||
|
||||
private static List<IncomingPayment> ReadPayments(XElement body, int index) =>
|
||||
Els(body, "DatiPagamento").SelectMany(p =>
|
||||
{
|
||||
var conditions = Text(p, "CondizioniPagamento");
|
||||
return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment(
|
||||
conditions,
|
||||
Text(d, "ModalitaPagamento"),
|
||||
OptionalDate(d, "DataScadenzaPagamento"),
|
||||
RequiredDecimal(d, "ImportoPagamento", index),
|
||||
Text(d, "IBAN"),
|
||||
Text(d, "BIC"),
|
||||
Text(d, "Beneficiario")));
|
||||
}).ToList();
|
||||
|
||||
private static List<IncomingAttachment> ReadAttachments(XElement body) =>
|
||||
Els(body, "Allegati").Select(a => new IncomingAttachment(
|
||||
Text(a, "NomeAttachment") ?? "allegato",
|
||||
Text(a, "FormatoAttachment"),
|
||||
Text(a, "DescrizioneAttachment"),
|
||||
DecodeAttachment(El(a, "Attachment")?.Value))).ToList();
|
||||
|
||||
private static byte[] DecodeAttachment(string? base64)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(base64))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var compact = new StringBuilder(base64.Length);
|
||||
foreach (var c in base64)
|
||||
{
|
||||
if (!char.IsWhiteSpace(c))
|
||||
{
|
||||
compact.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
var text = compact.ToString();
|
||||
var buffer = new byte[text.Length / 4 * 3 + 3];
|
||||
return Convert.TryFromBase64String(text, buffer, out var written) ? buffer[..written] : [];
|
||||
}
|
||||
|
||||
// --- Simplified invoice ------------------------------------------------------------------------------------------
|
||||
|
||||
private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
|
||||
{
|
||||
var header = El(root, "FatturaElettronicaHeader")
|
||||
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
|
||||
var transmission = El(header, "DatiTrasmissione");
|
||||
var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore.");
|
||||
var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente.");
|
||||
var bodies = Els(root, "FatturaElettronicaBody").ToList();
|
||||
if (bodies.Count == 0)
|
||||
{
|
||||
throw Invalid("The invoice has no FatturaElettronicaBody.");
|
||||
}
|
||||
|
||||
return new IncomingInvoiceFile(
|
||||
fileName,
|
||||
Text(transmission, "FormatoTrasmissione"),
|
||||
Text(transmission, "ProgressivoInvio"),
|
||||
Text(transmission, "CodiceDestinatario"),
|
||||
ReadParty(supplier),
|
||||
ReadParty(customer),
|
||||
bodies.Select(ReadSimplifiedBody).ToList(),
|
||||
signature,
|
||||
xml);
|
||||
}
|
||||
|
||||
private static IncomingInvoice ReadSimplifiedBody(XElement body, int index)
|
||||
{
|
||||
var general = El(body, "DatiGenerali");
|
||||
var document = El(general, "DatiGeneraliDocumento")
|
||||
?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento.");
|
||||
var lines = Els(body, "DatiBeniServizi").Select((l, i) => ReadSimplifiedLine(l, i, index)).ToList();
|
||||
var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index));
|
||||
var summary = lines
|
||||
.GroupBy(l => (l.TaxRate, l.Nature))
|
||||
.Select(g => new IncomingTaxSummary(
|
||||
g.Key.TaxRate, g.Key.Nature, g.Sum(l => l.TotalPrice), g.Sum(l => l.Tax), null,
|
||||
g.Select(l => l.LegalReference).FirstOrDefault(r => r is not null), null, null))
|
||||
.ToList();
|
||||
var corrected = Els(general, "DatiFatturaRettificata")
|
||||
.Select(r => new IncomingReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null))
|
||||
.ToList();
|
||||
|
||||
return new IncomingInvoice(
|
||||
Required(document, "TipoDocumento", index),
|
||||
Text(document, "Divisa") ?? "EUR",
|
||||
RequiredDate(document, "Data", index),
|
||||
Required(document, "Numero", index),
|
||||
gross,
|
||||
null,
|
||||
[],
|
||||
false,
|
||||
[],
|
||||
Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null,
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
corrected,
|
||||
[],
|
||||
lines.Select(l => l.Line).ToList(),
|
||||
summary,
|
||||
[],
|
||||
ReadAttachments(body));
|
||||
}
|
||||
|
||||
private static SimplifiedLine ReadSimplifiedLine(XElement line, int position, int index)
|
||||
{
|
||||
var gross = RequiredDecimal(line, "Importo", index);
|
||||
var vat = El(line, "DatiIVA");
|
||||
var tax = OptionalDecimal(vat, "Imposta");
|
||||
var rate = OptionalDecimal(vat, "Aliquota");
|
||||
tax ??= rate is { } r && r != 0m ? Math.Round(gross * r / (100m + r), 2, MidpointRounding.AwayFromZero) : 0m;
|
||||
var net = gross - tax.Value;
|
||||
rate ??= net != 0m ? Math.Round(tax.Value / net * 100m, 2, MidpointRounding.AwayFromZero) : 0m;
|
||||
var nature = Text(line, "Natura");
|
||||
return new SimplifiedLine(
|
||||
new IncomingLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature,
|
||||
[], false, null, null, null, null),
|
||||
tax.Value,
|
||||
Text(line, "RiferimentoNormativo"));
|
||||
}
|
||||
|
||||
private sealed record SimplifiedLine(IncomingLine Line, decimal Tax, string? LegalReference)
|
||||
{
|
||||
public decimal TaxRate => Line.TaxRate;
|
||||
|
||||
public string? Nature => Line.Nature;
|
||||
|
||||
public decimal TotalPrice => Line.TotalPrice;
|
||||
}
|
||||
|
||||
// --- Helpers -----------------------------------------------------------------------------------------------------
|
||||
|
||||
private static XElement? El(XElement? parent, string localName) =>
|
||||
parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName);
|
||||
|
||||
private static IEnumerable<XElement> Els(XElement? parent, string localName) =>
|
||||
parent is null ? [] : parent.Elements().Where(e => e.Name.LocalName == localName);
|
||||
|
||||
private static string? Text(XElement? parent, string localName)
|
||||
{
|
||||
var value = El(parent, localName)?.Value.Trim();
|
||||
return string.IsNullOrEmpty(value) ? null : value;
|
||||
}
|
||||
|
||||
private static bool Flag(XElement? parent, string localName) =>
|
||||
string.Equals(Text(parent, localName), "SI", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Required(XElement parent, string localName, int index) =>
|
||||
Text(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing.");
|
||||
|
||||
private static decimal? OptionalDecimal(XElement? parent, string localName) =>
|
||||
Text(parent, localName) is { } text && decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)
|
||||
? value
|
||||
: null;
|
||||
|
||||
private static decimal RequiredDecimal(XElement parent, string localName, int index) =>
|
||||
OptionalDecimal(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a number.");
|
||||
|
||||
private static int? OptionalInt(XElement parent, string localName) =>
|
||||
Text(parent, localName) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;
|
||||
|
||||
private static DateOnly? OptionalDate(XElement? parent, string localName)
|
||||
{
|
||||
var text = Text(parent, localName);
|
||||
if (text is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// xs:date may carry a time zone (2026-03-15+01:00): the day is what counts.
|
||||
var day = text.Length > 10 ? text[..10] : text;
|
||||
return DateOnly.TryParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? date : null;
|
||||
}
|
||||
|
||||
private static DateOnly RequiredDate(XElement parent, string localName, int index) =>
|
||||
OptionalDate(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a date.");
|
||||
|
||||
private static IncomingInvoiceException Invalid(string message) => new(IncomingInvoiceErrors.Invalid, message);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
public ItalyFiscalPack()
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
|
||||
@@ -0,0 +1,756 @@
|
||||
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';
|
||||
}
|
||||
Reference in new issue
Block a user