Path: redb-route/redb.Route.As4/Security/SecurityTokenResolver.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As4/Security/SecurityTokenResolver.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Xml; using redb.Route.Serialization; namespace redb.Route.As4.Security; /// /// Finds the certificate a ds:KeyInfo points at, in any of the three WS-Security X.509 token /// references eDelivery asks for: a wsse:Reference to a wsse:BinarySecurityToken in the same /// message, a ds:X509IssuerSerial, or a wsse:KeyIdentifier with the Subject Key Identifier. /// /// A certificate carried in the message is material, not trust: the caller decides whether it is acceptable /// (the partner's certificate from the agreement, or one of ours for decryption). /// /// internal static class SecurityTokenResolver { /// /// The certificate references. A token in the message is returned as is; an /// issuer-serial or key-identifier reference is matched against . Null when /// nothing matches. /// public static X509Certificate2? Resolve(XmlElement keyInfo, XmlDocument envelope, IEnumerable candidates) { ArgumentNullException.ThrowIfNull(keyInfo); var str = FirstChild(keyInfo, "SecurityTokenReference", WsSecurityNames.Wsse) ?? throw new CryptographicException("ds:KeyInfo holds no wsse:SecurityTokenReference."); if (FirstChild(str, "Reference", WsSecurityNames.Wsse) is { } reference) { var uri = reference.GetAttribute("URI"); if (!uri.StartsWith('#')) throw new CryptographicException($"wsse:Reference '{uri}' does not point into the message."); var token = FindById(envelope, uri[1..], "BinarySecurityToken", WsSecurityNames.Wsse) ?? throw new CryptographicException($"No wsse:BinarySecurityToken carries the id '{uri[1..]}'."); return FromBinarySecurityToken(token); } if (FirstChild(str, "X509Data", WsSecurityNames.Ds) is { } x509Data && FirstChild(x509Data, "X509IssuerSerial", WsSecurityNames.Ds) is { } issuerSerial) { var issuer = FirstChild(issuerSerial, "X509IssuerName", WsSecurityNames.Ds)?.InnerText.Trim(); var serial = FirstChild(issuerSerial, "X509SerialNumber", WsSecurityNames.Ds)?.InnerText.Trim(); if (issuer is null || serial is null) throw new CryptographicException("ds:X509IssuerSerial lacks the issuer name or the serial number."); // The serial is decimal in XML Signature; the issuer is compared as a parsed name, because the // same name can be encoded with different ASN.1 string types. Both sides are rendered from their // encoding: X500DistinguishedName.Name of a parsed string returns that string as given, so // "CN=a,O=b" (RFC 2253, as WSS4J and Domibus write it) would never equal "CN=a, O=b". if (!System.Numerics.BigInteger.TryParse(serial, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var serialNumber)) throw new CryptographicException("ds:X509SerialNumber is not a decimal number."); var issuerName = new X500DistinguishedName(issuer).Decode(X500DistinguishedNameFlags.None); return candidates.FirstOrDefault(c => string.Equals(c.IssuerName.Decode(X500DistinguishedNameFlags.None), issuerName, StringComparison.OrdinalIgnoreCase) && new System.Numerics.BigInteger(c.GetSerialNumber(), isUnsigned: true, isBigEndian: false) == serialNumber); } if (FirstChild(str, "KeyIdentifier", WsSecurityNames.Wsse) is { } keyIdentifier) { if (keyIdentifier.GetAttribute("ValueType") != WsSecurityNames.X509SubjectKeyIdentifier) throw new CryptographicException($"wsse:KeyIdentifier of type '{keyIdentifier.GetAttribute("ValueType")}' is not supported."); var ski = Base64(keyIdentifier); return candidates.FirstOrDefault(c => c.Extensions.OfType().FirstOrDefault() is { } ext && Convert.FromHexString(ext.SubjectKeyIdentifier!).AsSpan().SequenceEqual(ski)); } throw new CryptographicException("wsse:SecurityTokenReference uses no supported reference form."); } /// /// The certification path a ds:KeyInfo references, when it points at a wsse:BinarySecurityToken of /// type X509PKIPathv1 in the same message; null for any other reference form or token type. /// public static IReadOnlyList? PkiPathOf(XmlElement keyInfo, XmlDocument envelope) { ArgumentNullException.ThrowIfNull(keyInfo); if (FirstChild(keyInfo, "SecurityTokenReference", WsSecurityNames.Wsse) is not { } str || FirstChild(str, "Reference", WsSecurityNames.Wsse) is not { } reference) return null; var uri = reference.GetAttribute("URI"); if (!uri.StartsWith('#')) throw new CryptographicException($"wsse:Reference '{uri}' does not point into the message."); var token = FindById(envelope, uri[1..], "BinarySecurityToken", WsSecurityNames.Wsse) ?? throw new CryptographicException($"No wsse:BinarySecurityToken carries the id '{uri[1..]}'."); return token.GetAttribute("ValueType") == PkiPath.ValueType ? PkiPath.Decode(Base64(token)) : null; } /// /// The certificate in a wsse:BinarySecurityToken: the token itself for the X.509 v3 type, the last /// certificate of the path — the one the path is for — for X509PKIPathv1. /// public static X509Certificate2 FromBinarySecurityToken(XmlElement token) { var valueType = token.GetAttribute("ValueType"); if (valueType == PkiPath.ValueType) { var path = PkiPath.Decode(Base64(token)); PkiPath.Release(path, keep: path[^1]); return path[^1]; } if (valueType != WsSecurityNames.X509V3) throw new CryptographicException($"wsse:BinarySecurityToken of type '{valueType}' is not an X.509 v3 certificate."); var der = Base64(token); return X509CertificateLoader.LoadCertificate(der); } /// /// Whether the certificate references is one this node trusts for another reason than /// the sender's agreement: one of itself, or issued by one of them that is a /// certification authority. /// Only chooses the ebMS code of a refusal; nothing is accepted on it, so a reference by issuer and serial number /// is judged by its issuer name. /// public static bool IsTrustedElsewhere(XmlElement keyInfo, XmlDocument envelope, IReadOnlyCollection trusted) { try { if (Resolve(keyInfo, envelope, trusted) is { } found && trusted.Any(c => c.Thumbprint == found.Thumbprint)) return true; var issuer = ReferencedIssuer(keyInfo, envelope); return issuer is not null && trusted.Any(c => c.Extensions.OfType().Any(b => b.CertificateAuthority) && string.Equals(c.SubjectName.Decode(X500DistinguishedNameFlags.None), issuer, StringComparison.OrdinalIgnoreCase)); } catch (CryptographicException) { return false; } } /// The issuer of the referenced certificate, rendered from its encoding; null for a key identifier. private static string? ReferencedIssuer(XmlElement keyInfo, XmlDocument envelope) { if (FirstChild(keyInfo, "SecurityTokenReference", WsSecurityNames.Wsse) is not { } str) return null; if (FirstChild(str, "X509Data", WsSecurityNames.Ds) is { } x509Data && FirstChild(x509Data, "X509IssuerSerial", WsSecurityNames.Ds) is { } issuerSerial && FirstChild(issuerSerial, "X509IssuerName", WsSecurityNames.Ds)?.InnerText.Trim() is { Length: > 0 } issuer) return new X500DistinguishedName(issuer).Decode(X500DistinguishedNameFlags.None); if (FirstChild(str, "Reference", WsSecurityNames.Wsse) is { } reference && reference.GetAttribute("URI") is ['#', .. var id] && FindById(envelope, id, "BinarySecurityToken", WsSecurityNames.Wsse) is { } token) return FromBinarySecurityToken(token).IssuerName.Decode(X500DistinguishedNameFlags.None); return null; } /// /// The base64 content of a security element. Malformed base64 is a security failure of the message, refused /// like any other (), not an unexpected failure of the receiver. /// /// A value whose last character carries non-zero unused bits (YR== where an encoder writes YQ==) is /// malformed too: XML Schema base64Binary forbids that spelling and .NET 11 refuses it, so it is refused on /// every runtime and the receiver answers the same whatever it runs on. /// /// public static byte[] Base64(XmlElement element) { var text = element.InnerText.Trim(); if (Base64Text.HasUnusedBitsSet(text)) throw NotBase64(element); try { return Convert.FromBase64String(text); } catch (FormatException) { throw NotBase64(element); } } private static CryptographicException NotBase64(XmlElement element) => new($"{element.Name} is not valid base64."); /// The element named in with wsu:Id (or Id) . public static XmlElement? FindById(XmlDocument document, string id, string localName, string ns) { XmlElement? found = null; foreach (XmlElement e in document.GetElementsByTagName(localName, ns)) { if (e.GetAttribute("Id", WsSecurityNames.Wsu) != id && e.GetAttribute("Id") != id) continue; if (found is not null) throw new CryptographicException($"Two {localName} elements carry the id '{id}'."); found = e; } return found; } /// /// Builds a ds:KeyInfo that references in the requested form. For /// the token itself is appended to /// — before when given — unless an identical /// one is there already, and referenced by id: a receiver meets the token before the reference to it. /// public static XmlElement CreateKeyInfo(XmlDocument doc, XmlElement security, X509Certificate2 certificate, As4KeyReference form, XmlNode? insertTokenBefore = null, IReadOnlyList? path = null) { var keyInfo = doc.CreateElement("ds", "KeyInfo", WsSecurityNames.Ds); var str = doc.CreateElement("wsse", "SecurityTokenReference", WsSecurityNames.Wsse); keyInfo.AppendChild(str); switch (form) { case As4KeyReference.BinarySecurityToken: { var tokenId = EnsureBinarySecurityToken(doc, security, Convert.ToBase64String(certificate.RawData), WsSecurityNames.X509V3, insertTokenBefore); var reference = doc.CreateElement("wsse", "Reference", WsSecurityNames.Wsse); reference.SetAttribute("URI", "#" + tokenId); reference.SetAttribute("ValueType", WsSecurityNames.X509V3); str.AppendChild(reference); break; } case As4KeyReference.PkiPath: { // The certificate with its authorities, outermost first (ITU-T X.509 PkiPath): ordered and checked once, // when the node is resolved (As4Node.SigningPath). A certificate that is its own authority is a path of one. var signingPath = path ?? [certificate]; if (signingPath.Count == 0 || signingPath[^1].Thumbprint != certificate.Thumbprint) throw new CryptographicException("The certification path does not end with the signing certificate."); var tokenId = EnsureBinarySecurityToken(doc, security, Convert.ToBase64String(PkiPath.Encode(signingPath)), PkiPath.ValueType, insertTokenBefore); var reference = doc.CreateElement("wsse", "Reference", WsSecurityNames.Wsse); reference.SetAttribute("URI", "#" + tokenId); reference.SetAttribute("ValueType", PkiPath.ValueType); str.AppendChild(reference); // WS-I Basic Security Profile 1.1 R5215: a reference to a PKIPath token names its type on the // wsse:SecurityTokenReference itself; WSS4J (Domibus, Holodeck) refuses the message without it. var tokenType = doc.CreateAttribute("wsse11", "TokenType", WsSecurityNames.Wsse11); tokenType.Value = PkiPath.ValueType; str.Attributes.Append(tokenType); break; } case As4KeyReference.IssuerSerial: { var x509Data = doc.CreateElement("ds", "X509Data", WsSecurityNames.Ds); var issuerSerial = doc.CreateElement("ds", "X509IssuerSerial", WsSecurityNames.Ds); var issuer = doc.CreateElement("ds", "X509IssuerName", WsSecurityNames.Ds); issuer.InnerText = certificate.IssuerName.Name; var serial = doc.CreateElement("ds", "X509SerialNumber", WsSecurityNames.Ds); serial.InnerText = new System.Numerics.BigInteger(certificate.GetSerialNumber(), isUnsigned: true, isBigEndian: false) .ToString(System.Globalization.CultureInfo.InvariantCulture); issuerSerial.AppendChild(issuer); issuerSerial.AppendChild(serial); x509Data.AppendChild(issuerSerial); str.AppendChild(x509Data); break; } case As4KeyReference.KeyIdentifier: { var ski = certificate.Extensions.OfType().FirstOrDefault()?.SubjectKeyIdentifier ?? throw new CryptographicException("The certificate has no Subject Key Identifier to reference."); var identifier = doc.CreateElement("wsse", "KeyIdentifier", WsSecurityNames.Wsse); identifier.SetAttribute("EncodingType", WsSecurityNames.Base64Binary); identifier.SetAttribute("ValueType", WsSecurityNames.X509SubjectKeyIdentifier); identifier.InnerText = Convert.ToBase64String(Convert.FromHexString(ski)); str.AppendChild(identifier); break; } default: throw new ArgumentOutOfRangeException(nameof(form), form, "Unknown key reference form."); } return keyInfo; } private static string EnsureBinarySecurityToken(XmlDocument doc, XmlElement security, string der, string valueType, XmlNode? insertBefore) { foreach (var existing in security.ChildNodes.OfType() .Where(e => e.LocalName == "BinarySecurityToken" && e.NamespaceURI == WsSecurityNames.Wsse)) { if (existing.InnerText.Trim() == der && existing.GetAttribute("ValueType") == valueType) return existing.GetAttribute("Id", WsSecurityNames.Wsu); } var token = doc.CreateElement("wsse", "BinarySecurityToken", WsSecurityNames.Wsse); token.SetAttribute("EncodingType", WsSecurityNames.Base64Binary); token.SetAttribute("ValueType", valueType); var id = doc.CreateAttribute("wsu", "Id", WsSecurityNames.Wsu); id.Value = "X509-" + Guid.NewGuid().ToString("N"); token.Attributes.Append(id); token.InnerText = der; if (insertBefore is null) security.AppendChild(token); else security.InsertBefore(token, insertBefore); return id.Value; } /// The first child element with the given name. public static XmlElement? FirstChild(XmlElement parent, string localName, string ns) => parent.ChildNodes.OfType().FirstOrDefault(e => e.LocalName == localName && e.NamespaceURI == ns); }