using System.Buffers.Text;
using System.Formats.Asn1;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Khaemhat.Infrastructure.Security;
/// A structure that is not a readable CMS SignedData, or whose content cannot be extracted.
public sealed class CmsFormatException : Exception
{
/// Creates the exception.
public CmsFormatException()
: base("Not a CMS SignedData structure.")
{
}
/// Creates the exception.
/// What went wrong.
public CmsFormatException(string message)
: base(message)
{
}
/// Creates the exception.
/// What went wrong.
/// The cause.
public CmsFormatException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// A signer of a CMS SignedData with what its certificate says and the result of the check.
/// The name of the signer: common name, else given name and surname, else organization, else
/// serial number of the subject.
/// The tax code of the signer, from the subject's SERIALNUMBER (OID 2.5.4.5) without
/// the TINIT- or IT: prefix, when present.
/// The subject of the certificate, or when it was not found.
/// The issuer of the certificate, or when it was not found.
/// The start of validity of the certificate.
/// The end of validity of the certificate.
/// The signingTime signed attribute: what the signer's clock said, not a trusted timestamp.
/// Whether the digest of the content and the signature match.
/// Why the signature is not verified, or .
/// The DER of the signer certificate, or when it was not found.
public sealed record CmsSigner(
string? Name, string? TaxCode, string? Subject, string? Issuer,
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime,
bool Verified, string? Problem, byte[]? Certificate);
/// The content of one or more nested CMS SignedData envelopes and their signers.
/// The content of the innermost envelope.
/// The signers, outermost envelope first.
/// How many envelopes were opened (two for .xml.p7m.p7m).
public sealed record CmsContent(byte[] Content, IReadOnlyList Signers, int Layers)
{
/// Whether there is at least one signer and every signer of every envelope is verified.
public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified);
/// The first problem found, or when .
public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem;
/// The signer of the outermost envelope, or when there is none.
public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null;
}
///
/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as .p7m,
/// written on System.Formats.Asn1 because System.Security.Cryptography.Pkcs is a separate package
/// (SPEC ยง1.2).
///
///
/// It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the
/// binary with or without line breaks and -----BEGIN armour, and nested envelopes (.p7m.p7m), opened
/// until the content is no longer CMS.
/// It checks integrity only: the messageDigest 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 not 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 false and the
/// problem; only unreadable structures throw . Detached signatures (no content) are
/// not supported.
///
public static class CmsSignedData
{
/// The largest envelope read, 50 MB.
public const int MaxSize = 50 * 1024 * 1024;
/// The most nested envelopes opened.
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);
/// Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at.
/// The content, or at least its first hundred bytes.
/// when is worth trying.
public static bool LooksLikeCms(ReadOnlySpan data)
{
if (LooksLikeBinaryCms(data))
{
return true;
}
// Base64 text: decode the first characters and look again.
Span 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 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]);
}
///
/// 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).
///
/// The envelope.
/// The content of the innermost envelope and the signers.
/// The data is not a CMS SignedData, is too large, nests too deep, has no
/// content, or cannot be decoded.
public static CmsContent Read(byte[] data)
{
ArgumentNullException.ThrowIfNull(data);
var current = data;
var signers = new List();
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);
}
}
///
/// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, -----BEGIN
/// and -----END lines dropped, a UTF-8 byte order mark ignored.
///
/// The text, as bytes.
/// The decoded bytes, or when the text is not base64.
public static byte[]? DecodeBase64Text(ReadOnlySpan 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 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 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();
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 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 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().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 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 SignedAttributesAsSet(byte[] signedAttributes)
{
var forms = new List();
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-; older Italian certificates use IT:.
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 SkipBom(ReadOnlySpan data) =>
data.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF]) ? data[3..] : data;
private static ReadOnlySpan SkipArmour(ReadOnlySpan data)
{
var trimmed = data.TrimStart((ReadOnlySpan)[(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';
}