diff --git a/Sigyll.Common/Data/Entities/CertificateProfile.cs b/Sigyll.Common/Data/Entities/CertificateProfile.cs index 4b68f97..f454a18 100644 --- a/Sigyll.Common/Data/Entities/CertificateProfile.cs +++ b/Sigyll.Common/Data/Entities/CertificateProfile.cs @@ -42,6 +42,13 @@ public class CertificateProfile public int? PathLengthConstraint { get; set; } public bool IsExtendedKeyUsageCritical { get; set; } + /// + /// Semicolon-delimited certificate policy OIDs written into the certificatePolicies extension (2.5.29.32), + /// e.g. a trust framework's policy identifiers. Null or empty leaves the extension out. + /// See . + /// + public string? CertificatePolicyOids { get; set; } + /// /// "nistP256", "nistP384", or "nistP521". Only used when KeyAlgorithm is "ECDSA". /// diff --git a/Sigyll.Common/Data/Entities/SanList.cs b/Sigyll.Common/Data/Entities/SanList.cs index d5e3af8..2b5b85a 100644 --- a/Sigyll.Common/Data/Entities/SanList.cs +++ b/Sigyll.Common/Data/Entities/SanList.cs @@ -17,7 +17,8 @@ public class SanList public string? Description { get; set; } /// - /// Semicolon-delimited SAN entries: "URI:urn:oid:...#T-TRTMNT;URI:urn:oid:...#T-TREAT;DNS:example.com" + /// Semicolon-delimited SAN entries: "URI:urn:oid:...#T-TRTMNT;URI:urn:oid:...#T-TREAT;DNS:example.com". + /// Type tokens are URI, DNS, Email, IP and NPI (a 10-digit NPI, e.g. "NPI:1234567893"). /// public string Items { get; set; } = string.Empty; diff --git a/Sigyll.Common/Data/SigyllDbContext.cs b/Sigyll.Common/Data/SigyllDbContext.cs index 788e73f..b03c4e4 100644 --- a/Sigyll.Common/Data/SigyllDbContext.cs +++ b/Sigyll.Common/Data/SigyllDbContext.cs @@ -238,6 +238,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entity.Property(e => e.CdpUrlTemplate).HasMaxLength(500); entity.Property(e => e.AiaUrlTemplate).HasMaxLength(500); entity.Property(e => e.SubjectAltNameTypes).HasMaxLength(100); + entity.Property(e => e.CertificatePolicyOids).HasMaxLength(2000); entity.HasMany(e => e.SanLists) .WithMany(s => s.Profiles) diff --git a/Sigyll.Common/Services/CertificateImportService.cs b/Sigyll.Common/Services/CertificateImportService.cs index 9fa1fe9..3770a6a 100644 --- a/Sigyll.Common/Services/CertificateImportService.cs +++ b/Sigyll.Common/Services/CertificateImportService.cs @@ -1084,6 +1084,13 @@ private static int GetCrlReason(X509CrlEntry entry) var sanExt = cert.Extensions["2.5.29.17"]; if (sanExt == null) return null; + // An NPI otherName needs real ASN.1 decoding (its OID bytes would also confuse the tag scan + // below), so such a SAN is described from the decoded names: the viewer shows the NPI and + // re-issue keeps it. + var decoded = CsrGenerationService.ExtractSubjectAltNames(cert); + if (decoded.Any(s => s.Type == SanType.Npi)) + return string.Join("; ", decoded.Select(s => $"{s.Type}:{s.Value}")); + var sans = new List(); var rawData = sanExt.RawData; diff --git a/Sigyll.Common/Services/CertificateIssuanceService.cs b/Sigyll.Common/Services/CertificateIssuanceService.cs index 87475b9..af87211 100644 --- a/Sigyll.Common/Services/CertificateIssuanceService.cs +++ b/Sigyll.Common/Services/CertificateIssuanceService.cs @@ -129,11 +129,15 @@ private async Task IssueAsync(CertificateIssuanceRequ if (missingSanError != null) return CertificateIssuanceResult.Failure(missingSanError); + var badPolicyError = InvalidPolicyError(profile); + if (badPolicyError != null) + return CertificateIssuanceResult.Failure(badPolicyError); + // Renewal lineage: the predecessor determines the new certificate's version var (renewalVersion, renewalOfId, lineageError) = await ResolveRenewalLineageAsync( db, request.RenewalOfCertificateId, isCaLineage: profile.CertificateType is CertificateType.RootCa or CertificateType.IntermediateCa, - request.SubjectDn, request.SubjectAltNames); + request.SubjectDn, request.SubjectAltNames, profile); if (lineageError != null) return CertificateIssuanceResult.Failure(lineageError); @@ -465,15 +469,26 @@ private async Task IssueAsync(CertificateIssuanceRequ _ => "in an HSM", }; + /// + /// An error naming the profile's certificate policy entries that are not OIDs, or null when all are valid. + /// + private static string? InvalidPolicyError(CertificateProfile profile) + { + var invalid = CertificatePolicyExtension.FindInvalid(profile.CertificatePolicyOids); + return invalid.Count == 0 + ? null + : $"Profile '{profile.Name}' lists certificate policies that are not valid OIDs: {string.Join(", ", invalid)}."; + } + /// /// Resolves renewal lineage for an issuance request: the new certificate's Version is the /// predecessor's + 1 and RenewalOfId links back to it. Returns an error when the /// referenced predecessor doesn't exist in the expected table, or when the request would - /// change its subject or SANs (see ). + /// change its subject or SANs, or drop a certificate policy it carries (see ). /// private static async Task<(int Version, int? RenewalOfId, string? Error)> ResolveRenewalLineageAsync( SigyllDbContext db, int? renewalOfCertificateId, bool isCaLineage, - string subjectDn, IEnumerable subjectAltNames) + string subjectDn, IEnumerable subjectAltNames, CertificateProfile profile) { if (renewalOfCertificateId is not int predecessorId) return (1, null, null); @@ -494,6 +509,12 @@ private async Task IssueAsync(CertificateIssuanceRequ $"A renewal or re-key keeps the certificate's subject and SANs, but {change}. " + "To issue under different names, issue a new certificate instead."); + var droppedPolicies = RenewalIdentity.FindDroppedPolicies(profile, predecessorCert); + if (droppedPolicies.Count > 0) + return (1, null, + $"A renewal or re-key keeps the certificate's policies, but profile '{profile.Name}' does not include " + + $"{string.Join(", ", droppedPolicies)}. Choose a profile that lists them, or add them to this profile."); + return (predecessor.Version + 1, predecessorId, null); } @@ -557,9 +578,13 @@ private async Task IssueFromCsrAsync(CsrIssuanceRequest reque if (missingSanError != null) return CsrIssuanceResult.Failure(missingSanError); + var badPolicyError = InvalidPolicyError(profile); + if (badPolicyError != null) + return CsrIssuanceResult.Failure(badPolicyError); + // Renewal lineage: the predecessor determines the new certificate's version var (renewalVersion, renewalOfId, lineageError) = await ResolveRenewalLineageAsync( - db, request.RenewalOfCertificateId, isCaLineage: false, csr.SubjectName.Name, request.SubjectAltNames); + db, request.RenewalOfCertificateId, isCaLineage: false, csr.SubjectName.Name, request.SubjectAltNames, profile); if (lineageError != null) return CsrIssuanceResult.Failure(lineageError); @@ -1365,6 +1390,11 @@ private static X509Extension[] BuildExtensionsForRemote( extensions.Add(new X509EnhancedKeyUsageExtension(oids, profile.IsExtendedKeyUsageCritical)); } + // Certificate Policies + var policies = CertificatePolicyExtension.Build(profile.CertificatePolicyOids); + if (policies != null) + extensions.Add(policies); + // CDP if (profile.IncludeCdp && request.CdpUrls.Count > 0) extensions.Add(CertificateExtensionHelpers.MakeCdp(request.CdpUrls)); @@ -1522,6 +1552,11 @@ private static void AddExtensions( } } + // Certificate Policies + var policies = CertificatePolicyExtension.Build(profile.CertificatePolicyOids); + if (policies != null) + certRequest.CertificateExtensions.Add(policies); + // CRL Distribution Points if (profile.IncludeCdp && request.CdpUrls.Count > 0) { diff --git a/Sigyll.Common/Services/CertificateParsingService.cs b/Sigyll.Common/Services/CertificateParsingService.cs index ce6b679..a3407ea 100644 --- a/Sigyll.Common/Services/CertificateParsingService.cs +++ b/Sigyll.Common/Services/CertificateParsingService.cs @@ -205,16 +205,8 @@ private static DetectedCertRole DetectRole(X509Certificate2 cert) var sanExt = cert.Extensions["2.5.29.17"]; if (sanExt == null) return null; - try - { - var formatted = sanExt.Format(multiLine: true); - var lines = formatted.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - return string.Join("; ", lines); - } - catch - { - return null; - } + var lines = SubjectAltNameText.Describe(sanExt); + return lines.Count > 0 ? string.Join("; ", lines) : null; } private static (string algorithm, int keySize) GetKeyInfo(X509Certificate2 cert) diff --git a/Sigyll.Common/Services/CertificatePolicyExtension.cs b/Sigyll.Common/Services/CertificatePolicyExtension.cs new file mode 100644 index 0000000..d09be31 --- /dev/null +++ b/Sigyll.Common/Services/CertificatePolicyExtension.cs @@ -0,0 +1,210 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Formats.Asn1; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.RegularExpressions; + +namespace Sigyll.Common.Services; + +/// +/// The certificatePolicies extension (RFC 5280 §4.2.1.4, OID 2.5.29.32): the policy OIDs a certificate is issued +/// under. Trust frameworks such as DirectTrust require specific policy OIDs on the certificates they accept. +/// A profile stores its policies as semicolon-delimited OIDs, like its extended key usages; the helpers here +/// parse that text, build the extension from it, and read the policies back from a certificate. +/// +public static partial class CertificatePolicyExtension +{ + public const string CertificatePoliciesOid = "2.5.29.32"; + + /// The special policy that stands for every policy (RFC 5280 §4.2.1.4). + public const string AnyPolicyOid = "2.5.29.32.0"; + + private const string CpsQualifierOid = "1.3.6.1.5.5.7.2.1"; + private const string UserNoticeQualifierOid = "1.3.6.1.5.5.7.2.2"; + + private static readonly char[] Separators = [';', ',', ' ', '\t', '\r', '\n']; + + /// + /// Splits policy text into OIDs. Semicolons, commas, spaces and line breaks all separate entries; blanks + /// and repeats are dropped and the order is kept. + /// + public static IReadOnlyList Parse(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return []; + + return text.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Distinct(StringComparer.Ordinal) + .ToList(); + } + + /// + /// The stored form of policy text: the OIDs joined with semicolons, or null when there are none. + /// + public static string? Normalize(string? text) + { + var oids = Parse(text); + return oids.Count == 0 ? null : string.Join(";", oids); + } + + /// The entries in that are not dotted-decimal OIDs. + public static IReadOnlyList FindInvalid(string? text) => + Parse(text).Where(oid => !IsValidOid(oid)).ToList(); + + /// + /// Whether is a dotted-decimal object identifier: at least two arcs, the first 0, 1 + /// or 2, the second at most 39 under 0 and 1, and no leading zeros. + /// + public static bool IsValidOid(string? oid) + { + if (string.IsNullOrEmpty(oid) || !OidPattern().IsMatch(oid)) + return false; + + var arcs = oid.Split('.'); + return arcs[0] == "2" || (arcs[1].Length <= 2 && int.Parse(arcs[1]) <= 39); + } + + /// + /// Builds the extension listing , without qualifiers, or returns null when there + /// are none. RFC 5280 lets the extension be critical or not; it is non-critical unless asked otherwise. + /// + /// An entry is not a dotted-decimal OID. + public static X509Extension? Build(IEnumerable policyOids, bool critical = false) + { + var oids = policyOids + .Select(o => o.Trim()) + .Where(o => o.Length > 0) + .Distinct(StringComparer.Ordinal) + .ToList(); + if (oids.Count == 0) + return null; + + var invalid = oids.FirstOrDefault(o => !IsValidOid(o)); + if (invalid != null) + throw new ArgumentException($"'{invalid}' is not a valid certificate policy OID.", nameof(policyOids)); + + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSequence()) + { + foreach (var oid in oids) + { + using (writer.PushSequence()) + writer.WriteObjectIdentifier(oid); + } + } + + return new X509Extension(new Oid(CertificatePoliciesOid, "Certificate Policies"), writer.Encode(), critical); + } + + /// Builds the extension from policy text in the stored form (see ). + public static X509Extension? Build(string? policyText, bool critical = false) => + Build(Parse(policyText), critical); + + /// The policy OIDs in , or an empty list when it has none. + public static IReadOnlyList Read(X509Certificate2 certificate) + { + var extension = certificate.Extensions[CertificatePoliciesOid]; + return extension == null ? [] : Decode(extension).Select(p => p.PolicyOid).ToList(); + } + + /// + /// Decodes the extension into its policies and their qualifiers (CPS URIs and user notice text). + /// + /// The extension is not a valid certificatePolicies value. + public static IReadOnlyList Decode(X509Extension extension) + { + var policies = new List(); + var reader = new AsnReader(extension.RawData, AsnEncodingRules.DER); + var sequence = reader.ReadSequence(); + reader.ThrowIfNotEmpty(); + + while (sequence.HasData) + { + var info = sequence.ReadSequence(); + var oid = info.ReadObjectIdentifier(); + var qualifiers = new List(); + + if (info.HasData) + { + var qualifierSequence = info.ReadSequence(); + while (qualifierSequence.HasData) + { + var qualifier = qualifierSequence.ReadSequence(); + var qualifierId = qualifier.ReadObjectIdentifier(); + qualifiers.Add(qualifierId switch + { + CpsQualifierOid => $"CPS: {qualifier.ReadCharacterString(UniversalTagNumber.IA5String)}", + UserNoticeQualifierOid => $"User notice: {ReadUserNotice(qualifier)}", + _ => $"{qualifierId}: {Convert.ToHexString(qualifier.ReadEncodedValue().Span)}", + }); + } + } + + policies.Add(new CertificatePolicy(oid, qualifiers)); + } + + return policies; + } + + /// + /// Text for the certificate viewer: one line per policy OID, with any qualifiers indented beneath it. Falls + /// back to the hex of the extension when it cannot be decoded. + /// + public static string Describe(X509Extension extension) + { + try + { + var text = new StringBuilder(); + foreach (var policy in Decode(extension)) + { + if (text.Length > 0) text.Append('\n'); + text.Append(policy.PolicyOid); + if (policy.PolicyOid == AnyPolicyOid) text.Append(" (anyPolicy)"); + foreach (var qualifier in policy.Qualifiers) + text.Append("\n ").Append(qualifier); + } + + return text.ToString(); + } + catch (Exception ex) when (ex is AsnContentException or ArgumentException) + { + return Convert.ToHexString(extension.RawData); + } + } + + private static string ReadUserNotice(AsnReader qualifier) + { + // UserNotice ::= SEQUENCE { noticeRef NoticeReference OPTIONAL, explicitText DisplayText OPTIONAL } + var notice = qualifier.ReadSequence(); + string? explicitText = null; + while (notice.HasData) + { + var tag = notice.PeekTag(); + if (tag.TagClass == TagClass.Universal && tag.TagValue == (int)UniversalTagNumber.Sequence) + { + notice.ReadEncodedValue(); // noticeRef: organization and notice numbers, not shown + continue; + } + + explicitText = notice.ReadCharacterString((UniversalTagNumber)tag.TagValue); + } + + return explicitText ?? "(notice reference only)"; + } + + [GeneratedRegex(@"^[0-2](\.(0|[1-9][0-9]*))+$")] + private static partial Regex OidPattern(); +} + +/// One entry of a certificatePolicies extension: the policy OID and its qualifiers as display text. +public sealed record CertificatePolicy(string PolicyOid, IReadOnlyList Qualifiers); diff --git a/Sigyll.Common/Services/CertificateProfileService.cs b/Sigyll.Common/Services/CertificateProfileService.cs index 445eb11..fbc3523 100644 --- a/Sigyll.Common/Services/CertificateProfileService.cs +++ b/Sigyll.Common/Services/CertificateProfileService.cs @@ -45,10 +45,18 @@ public async Task> GetAllAsync(CancellationToken ct = d .ToListAsync(ct); } + /// A certificate policy entry is not a dotted-decimal OID. public async Task SaveAsync(CertificateProfile entity, CancellationToken ct = default) { await _operator.DemandAsync(Permission.Administer); + var invalidPolicies = CertificatePolicyExtension.FindInvalid(entity.CertificatePolicyOids); + if (invalidPolicies.Count > 0) + throw new ArgumentException( + $"Certificate policies must be dotted-decimal OIDs such as 2.23.140.1.2.1; not valid:{string.Join(", ", invalidPolicies)}", + nameof(entity)); + entity.CertificatePolicyOids = CertificatePolicyExtension.Normalize(entity.CertificatePolicyOids); + await using var db = await _dbFactory.CreateDbContextAsync(ct); if (entity.Id > 0) diff --git a/Sigyll.Common/Services/CsrGenerationService.cs b/Sigyll.Common/Services/CsrGenerationService.cs index 5c2873e..b0f0d34 100644 --- a/Sigyll.Common/Services/CsrGenerationService.cs +++ b/Sigyll.Common/Services/CsrGenerationService.cs @@ -219,7 +219,7 @@ public CsrGenerationResult GenerateCsrFromCertificate(X509Certificate2 certifica /// /// Reads the certificate's Subject Alternative Names as editable entries. Only the name forms - /// Sigyll can rebuild (URI, DNS, email, IP) are returned; anything else (otherName etc.) is + /// Sigyll can rebuild (URI, DNS, email, IP, NPI otherName) are returned; anything else is /// preserved only when the SAN extension is copied verbatim. /// public static List ExtractSubjectAltNames(X509Certificate2 certificate) @@ -248,6 +248,9 @@ public static List ExtractSubjectAltNames(X509Certificate2 certificate result.Add(new SanEntry(SanType.IpAddress, new IPAddress(Asn1OctetString.GetInstance(gn.Name).GetOctets()).ToString())); break; + case GeneralName.OtherName when NpiNumber.TryRead(gn, out var npi): + result.Add(new SanEntry(SanType.Npi, npi)); + break; } } } diff --git a/Sigyll.Common/Services/NpiNumber.cs b/Sigyll.Common/Services/NpiNumber.cs new file mode 100644 index 0000000..f635ff5 --- /dev/null +++ b/Sigyll.Common/Services/NpiNumber.cs @@ -0,0 +1,116 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Asn1.X509; + +namespace Sigyll.Common.Services; + +/// +/// National Provider Identifier (NPI) handling for Subject Alternative Names. +/// +/// An NPI is ten digits; the last is a Luhn (ISO/IEC 7812) check digit computed over the +/// first nine digits prefixed with the card-issuer constant 80840. In a certificate it is +/// carried as an otherName whose type-id is 2.16.840.1.113883.4.6 and whose value is a +/// UTF8String holding the ten digits, as the DirectTrust certificate profiles allow for a +/// verified organization or individual covered entity. +/// +public static class NpiNumber +{ + /// otherName type-id for an NPI (HL7 OID registry: National Provider Identifier). + public const string OtherNameOid = "2.16.840.1.113883.4.6"; + + /// Card-issuer prefix the NPI check digit is computed with. + private const string LuhnPrefix = "80840"; + + /// + /// True when is exactly ten ASCII digits with a valid check digit. + /// No trimming or separators are accepted; callers trim first. + /// + public static bool IsValid(string? value) => value is { Length: 10 } && Validate(value) is null; + + /// + /// Returns an error message for an invalid NPI, or null when is valid. + /// + public static string? Validate(string? value) + { + var npi = value?.Trim() ?? string.Empty; + + if (npi.Length != 10 || !npi.All(c => c is >= '0' and <= '9')) + return $"NPI SAN '{value}' must be exactly 10 digits."; + + if (!LuhnIsValid(LuhnPrefix + npi)) + return $"NPI SAN '{value}' has an invalid check digit."; + + return null; + } + + /// Builds the otherName GeneralName carrying . + public static GeneralName ToGeneralName(string npi) => + new(GeneralName.OtherName, new DerSequence( + new DerObjectIdentifier(OtherNameOid), + new DerTaggedObject(true, 0, new DerUtf8String(npi)))); + + /// + /// Reads the NPI from an otherName GeneralName. Returns false when the name is not an + /// otherName, its type-id is not the NPI OID, or the value is not a string. + /// + public static bool TryRead(GeneralName name, out string npi) + { + npi = string.Empty; + if (name.TagNo != GeneralName.OtherName) return false; + + try + { + var (oid, value) = ReadOtherName(name); + if (oid != OtherNameOid || value is not IAsn1String text) return false; + npi = text.GetString(); + return true; + } + catch + { + return false; + } + } + + /// + /// Splits an otherName into its type-id and the (explicitly tagged) value. + /// + internal static (string Oid, Asn1Encodable? Value) ReadOtherName(GeneralName name) + { + var seq = Asn1Sequence.GetInstance(name.Name); + var oid = DerObjectIdentifier.GetInstance(seq[0]).Id; + Asn1Encodable? value = null; + if (seq.Count > 1) + { + var tagged = Asn1TaggedObject.GetInstance(seq[1]); + value = tagged.GetExplicitBaseObject(); + } + return (oid, value); + } + + private static bool LuhnIsValid(string digits) + { + var sum = 0; + var doubleIt = false; + for (var i = digits.Length - 1; i >= 0; i--) + { + var d = digits[i] - '0'; + if (doubleIt) + { + d *= 2; + if (d > 9) d -= 9; + } + sum += d; + doubleIt = !doubleIt; + } + return sum % 10 == 0; + } +} diff --git a/Sigyll.Common/Services/RenewalIdentity.cs b/Sigyll.Common/Services/RenewalIdentity.cs index eb1a8be..19ccbed 100644 --- a/Sigyll.Common/Services/RenewalIdentity.cs +++ b/Sigyll.Common/Services/RenewalIdentity.cs @@ -58,7 +58,8 @@ public static class RenewalIdentity /// /// Whether a profile issues the same kind of certificate as : the same CA flag, - /// key usages and extended key usages, with every SAN type it requires present in + /// key usages and extended key usages, every certificate policy the predecessor carries (see + /// ), and every SAN type it requires present in /// . Algorithm, key size and validity may differ; that is what a re-key is for. /// public static bool IsCompatibleProfile(CertificateProfile profile, X509Certificate2 predecessor, IEnumerable subjectAltNames) @@ -81,10 +82,34 @@ public static bool IsCompatibleProfile(CertificateProfile profile, X509Certifica if (!ekus.SetEquals(profileEkus)) return false; + if (FindDroppedPolicies(profile, predecessor).Count > 0) + return false; + return IssuanceValidator.FindMissingSanTypes(profile.SubjectAltNameTypes, subjectAltNames.Where(s => !string.IsNullOrWhiteSpace(s.Value)).Select(s => s.Type)).Count == 0; } + /// + /// The certificate policy OIDs in that would not + /// write into its renewal. A renewal or re-key keeps the policies the certificate was issued under; the profile + /// may add policies, but it may not drop any. Returns an empty list when nothing would be dropped. + /// + public static IReadOnlyList FindDroppedPolicies(CertificateProfile profile, X509Certificate2 predecessor) + { + IReadOnlyList before; + try + { + before = CertificatePolicyExtension.Read(predecessor); + } + catch (System.Formats.Asn1.AsnContentException) + { + return []; // an undecodable extension was not written by a profile; nothing to carry forward + } + + var after = CertificatePolicyExtension.Parse(profile.CertificatePolicyOids).ToHashSet(StringComparer.Ordinal); + return before.Where(oid => !after.Contains(oid)).ToList(); + } + private static List<(string Oid, string Value)> Rdns(X500DistinguishedName name) => name.EnumerateRelativeDistinguishedNames() .Select(r => r.HasMultipleElements diff --git a/Sigyll.Common/Services/SanExtensionBuilder.cs b/Sigyll.Common/Services/SanExtensionBuilder.cs index 88be668..747a516 100644 --- a/Sigyll.Common/Services/SanExtensionBuilder.cs +++ b/Sigyll.Common/Services/SanExtensionBuilder.cs @@ -31,7 +31,9 @@ public static class SanExtensionBuilder /// /// Builds a non-critical SAN extension from the entries. Values are trimmed but otherwise - /// untouched. URIs must be absolute and IP addresses must parse; DNS and email are taken as-is. + /// untouched. URIs must be absolute, IP addresses must parse and NPIs must be 10 digits with a + /// valid check digit (encoded as an otherName, see ); DNS and email are + /// taken as-is. /// Returns null when there are no non-empty entries. /// public static X509Extension? Build(IEnumerable entries, bool critical = false) @@ -64,6 +66,12 @@ public static class SanExtensionBuilder throw new ArgumentException($"'{value}' is not a valid IP address."); names.Add(new GeneralName(GeneralName.IPAddress, new Org.BouncyCastle.Asn1.DerOctetString(ip.GetAddressBytes()))); break; + + case SanType.Npi: + if (NpiNumber.Validate(value) is string npiError) + throw new ArgumentException(npiError); + names.Add(NpiNumber.ToGeneralName(value)); + break; } } diff --git a/Sigyll.Common/Services/SubjectAltNameText.cs b/Sigyll.Common/Services/SubjectAltNameText.cs new file mode 100644 index 0000000..4052497 --- /dev/null +++ b/Sigyll.Common/Services/SubjectAltNameText.cs @@ -0,0 +1,109 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Net; +using System.Security.Cryptography.X509Certificates; +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Asn1.X509; +using Sigyll.Common.ViewModels; +using X509Extension = System.Security.Cryptography.X509Certificates.X509Extension; + +namespace Sigyll.Common.Services; + +/// +/// Display text for a Subject Alternative Name extension. +/// +public static class SubjectAltNameText +{ + /// + /// Describes each name in the SAN extension, one line per name. + /// + /// .NET's X509Extension.Format is used as before, except when the extension holds an + /// otherName: the platform formatters render those as hex or "<unsupported>", so the + /// whole extension is described here instead, in the same Type:value form Sigyll + /// stores for certificates it issues (e.g. Npi:1234567893, Dns:example.com). + /// Returns an empty list when the extension cannot be read. + /// + public static List Describe(X509Extension sanExtension) + { + var decoded = TryDescribeOtherNames(sanExtension.RawData); + if (decoded != null) return decoded; + + try + { + return sanExtension.Format(multiLine: true) + .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .ToList(); + } + catch + { + return []; + } + } + + /// + /// Returns the BouncyCastle-decoded description when the extension contains at least one + /// otherName; null otherwise (or when it cannot be decoded). + /// + private static List? TryDescribeOtherNames(byte[] rawData) + { + GeneralName[] names; + try + { + names = GeneralNames.GetInstance(Asn1Object.FromByteArray(rawData)).GetNames(); + } + catch + { + return null; + } + + if (!names.Any(n => n.TagNo == GeneralName.OtherName)) return null; + + var lines = new List(); + foreach (var gn in names) + { + try + { + lines.Add(DescribeName(gn)); + } + catch + { + lines.Add($"[{gn.TagNo}]: (unreadable)"); + } + } + return lines; + } + + private static string DescribeName(GeneralName gn) + { + switch (gn.TagNo) + { + case GeneralName.OtherName: + if (NpiNumber.TryRead(gn, out var npi)) + return $"{SanType.Npi}:{npi}"; + var (oid, value) = NpiNumber.ReadOtherName(gn); + return value is IAsn1String text + ? $"OtherName:{oid}={text.GetString()}" + : $"OtherName:{oid}"; + case GeneralName.UniformResourceIdentifier: + return $"{SanType.Uri}:{DerIA5String.GetInstance(gn.Name).GetString()}"; + case GeneralName.DnsName: + return $"{SanType.Dns}:{DerIA5String.GetInstance(gn.Name).GetString()}"; + case GeneralName.Rfc822Name: + return $"{SanType.Email}:{DerIA5String.GetInstance(gn.Name).GetString()}"; + case GeneralName.IPAddress: + return $"{SanType.IpAddress}:{new IPAddress(Asn1OctetString.GetInstance(gn.Name).GetOctets())}"; + case GeneralName.DirectoryName: + return $"DirName:{X509Name.GetInstance(gn.Name)}"; + default: + return $"[{gn.TagNo}]"; + } + } +} diff --git a/Sigyll.Common/Services/TefcaCertificateProfiles.cs b/Sigyll.Common/Services/TefcaCertificateProfiles.cs new file mode 100644 index 0000000..7962df6 --- /dev/null +++ b/Sigyll.Common/Services/TefcaCertificateProfiles.cs @@ -0,0 +1,119 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography.X509Certificates; +using Sigyll.Common.Data.Entities; + +namespace Sigyll.Common.Services; + +/// +/// Preset certificate profiles for TEFCA FHIR (RCE UDAP) certificates, following DirectTrust Certificate +/// Profiles v2.1, Worksheet 4-4 (TEFCA RCE (UDAP)) and its Appendix validation profile. +/// Production and validation leaves differ in the subject OU and in the certificate policies; validation +/// certificates chain to a different root and intermediate than production ones, so issue them from a +/// separate trust domain. +/// +public static class TefcaCertificateProfiles +{ + public const string IntermediateName = "TEFCA Intermediate CA"; + public const string ClientName = "TEFCA FHIR Client"; + public const string ServerName = "TEFCA FHIR Server"; + public const string ValidationClientName = "TEFCA FHIR Client (Validation)"; + public const string ValidationServerName = "TEFCA FHIR Server (Validation)"; + + /// Subject OU of production TEFCA FHIR certificates. + public const string ProductionOu = "RCE-FHIR"; + + /// Subject OU of validation (test) TEFCA FHIR certificates. + public const string ValidationOu = "RCE-FHIR-TEST"; + + /// DirectTrust Certificate Policy. + public const string DirectTrustCpOid = "1.3.6.1.4.1.41179.0.2"; + + /// DirectTrust identity assurance level IAL2. + public const string Ial2Oid = "1.3.6.1.4.1.41179.1.5"; + + /// DirectTrust Device certificate. + public const string DeviceOid = "1.3.6.1.4.1.41179.3.1"; + + /// + /// The certificate policies of production client and server leaves. A healthcare category policy is + /// added on top when the certificate asserts an organization; clone the preset to add it. + /// + public const string ProductionPolicyOids = DirectTrustCpOid + ";" + Ial2Oid + ";" + DeviceOid; + + /// Leaf validity: three years is the maximum. + public const int LeafValidityDays = 1095; + + public static IEnumerable All() + { + yield return Intermediate(); + yield return Leaf(ClientName, CertificateType.EndEntityClient, ProductionOu, ProductionPolicyOids, + "TEFCA FHIR (RCE UDAP) client certificate, production. CN must be one of the UDAP URI SANs " + + "(at most 64 characters). Add a healthcare category policy when the certificate asserts an organization."); + yield return Leaf(ServerName, CertificateType.EndEntityServer, ProductionOu, ProductionPolicyOids, + "TEFCA FHIR (RCE UDAP) server certificate, production. CN must be one of the UDAP URI SANs " + + "(at most 64 characters), such as the FHIR base URL. Add a healthcare category policy when the " + + "certificate asserts an organization."); + yield return Leaf(ValidationClientName, CertificateType.EndEntityClient, ValidationOu, policyOids: null, + "TEFCA FHIR (RCE UDAP) client certificate for validation. Issue from a validation trust domain " + + "(its own root and intermediate). Certificate policies may be added but are not required."); + yield return Leaf(ValidationServerName, CertificateType.EndEntityServer, ValidationOu, policyOids: null, + "TEFCA FHIR (RCE UDAP) server certificate for validation. Issue from a validation trust domain " + + "(its own root and intermediate). Certificate policies may be added but are not required."); + } + + private static CertificateProfile Intermediate() => new() + { + Name = IntermediateName, + Description = "TEFCA FHIR intermediate CA, issued by a root; issues TEFCA FHIR client and server " + + "certificates. Path length 0. CRL distribution point and AIA must be http URLs, so " + + "the trust domain's base URL (or the URL templates) must use http.", + CertificateType = CertificateType.IntermediateCa, + KeyAlgorithm = "RSA", + KeySize = 4096, + ValidityDays = 1825, + KeyUsageFlags = (int)(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign), + IsKeyUsageCritical = true, + IsBasicConstraintsCa = true, + IsBasicConstraintsCritical = true, + PathLengthConstraint = 0, + HashAlgorithm = "SHA256", + IncludeCdp = true, + IncludeAia = true, + SubjectAltNameTypes = null, + IsPreset = true, + }; + + private static CertificateProfile Leaf(string name, CertificateType type, string ou, string? policyOids, + string description) => new() + { + Name = name, + Description = description, + CertificateType = type, + KeyAlgorithm = "RSA", + KeySize = 2048, + ValidityDays = LeafValidityDays, + KeyUsageFlags = (int)X509KeyUsageFlags.DigitalSignature, + IsKeyUsageCritical = true, + ExtendedKeyUsageOids = null, + IsBasicConstraintsCa = false, + IsBasicConstraintsCritical = true, + CertificatePolicyOids = policyOids, + HashAlgorithm = "SHA256", + SubjectTemplate = $"CN={{UDAP URI}}, OU={ou}, O={{Organization}}, ST={{State}}, C=US", + IncludeCdp = true, + IncludeAia = true, + // URIs only. An NPI otherName is optional, so NPI is not listed (listed SAN types are required). + SubjectAltNameTypes = "URI", + IsPreset = true, + RequiresRaApproval = true, + }; +} diff --git a/Sigyll.Common/Validators/IssuanceValidator.cs b/Sigyll.Common/Validators/IssuanceValidator.cs index a805f75..703a3e9 100644 --- a/Sigyll.Common/Validators/IssuanceValidator.cs +++ b/Sigyll.Common/Validators/IssuanceValidator.cs @@ -9,6 +9,7 @@ #endregion using Sigyll.Common.Data.Entities; +using Sigyll.Common.Services; using Sigyll.Common.ViewModels; namespace Sigyll.Common.Validators; @@ -42,25 +43,32 @@ public HashSet FindSupersededCaIds(List allCas) } /// - /// Parses a profile's semicolon-delimited SubjectAltNameTypes ("URI;DNS;Email;IP") + /// Parses a profile's semicolon-delimited SubjectAltNameTypes ("URI;DNS;Email;IP;NPI") /// into SanType values. Unknown tokens are ignored. /// public static List ParseSanTypes(string? subjectAltNameTypes) => (subjectAltNameTypes ?? string.Empty) .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(t => t.ToUpperInvariant() switch - { - "URI" => (SanType?)SanType.Uri, - "DNS" => SanType.Dns, - "EMAIL" => SanType.Email, - "IP" => SanType.IpAddress, - _ => null - }) + .Select(ParseSanTypeToken) .Where(t => t != null) .Select(t => t!.Value) .Distinct() .ToList(); + /// + /// Maps a SAN type token as written in profiles and SAN lists ("URI", "DNS", "Email", "IP", + /// "NPI"; case-insensitive) to its SanType, or null when the token is unknown. + /// + public static SanType? ParseSanTypeToken(string? token) => token?.Trim().ToUpperInvariant() switch + { + "URI" => SanType.Uri, + "DNS" => SanType.Dns, + "EMAIL" => SanType.Email, + "IP" => SanType.IpAddress, + "NPI" => SanType.Npi, + _ => null + }; + /// /// A SAN type declared on a profile is a requirement: every declared type must have at /// least one non-empty SAN entry in the request. Returns an error message naming the @@ -89,11 +97,21 @@ public static List FindMissingSanTypes(string? subjectAltNameTypes, IEn /// /// Validates individual SAN values. A DNS SAN (dNSName, RFC 5280) must be a bare host /// name — no port, scheme, or path; ports are fine in URI SANs. Wildcard prefixes - /// ("*.example.com") are allowed. Returns an error for the first invalid entry, or null. + /// ("*.example.com") are allowed. An NPI SAN must be 10 digits whose last digit is the Luhn + /// check digit (computed with the 80840 prefix). Returns an error for the first invalid + /// entry, or null. /// public string? ValidateSanValues(IEnumerable subjectAltNames) { - foreach (var san in subjectAltNames.Where(s => s.Type == SanType.Dns)) + var sans = subjectAltNames.ToList(); + + foreach (var san in sans.Where(s => s.Type == SanType.Npi)) + { + if (NpiNumber.Validate(san.Value) is string npiError) + return npiError; + } + + foreach (var san in sans.Where(s => s.Type == SanType.Dns)) { var host = san.Value.Trim(); @@ -120,6 +138,7 @@ public static List FindMissingSanTypes(string? subjectAltNameTypes, IEn SanType.Dns => "DNS", SanType.Email => "Email", SanType.IpAddress => "IP", + SanType.Npi => "NPI", _ => type.ToString() }; diff --git a/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs b/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs index ad97625..89c7be1 100644 --- a/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs +++ b/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs @@ -141,7 +141,13 @@ public enum SanType Uri, Dns, Email, - IpAddress + IpAddress, + + /// + /// A National Provider Identifier carried as an otherName (OID 2.16.840.1.113883.4.6, UTF8String). + /// The value is the 10-digit NPI; see . + /// + Npi } /// diff --git a/Sigyll.Portal/Components/Pages/Requests/NewRequest.razor b/Sigyll.Portal/Components/Pages/Requests/NewRequest.razor index 457a466..03b7d96 100644 --- a/Sigyll.Portal/Components/Pages/Requests/NewRequest.razor +++ b/Sigyll.Portal/Components/Pages/Requests/NewRequest.razor @@ -90,7 +90,7 @@ else private CatalogResponse? _catalog; private List _trustDomainNames = new(); private List _profileNames = new(); - private readonly List _sanTypes = new() { "Dns", "Uri", "Email", "IpAddress" }; + private readonly List _sanTypes = new() { "Dns", "Uri", "Email", "IpAddress", "Npi" }; private string? _trustDomain; private string? _profileName; diff --git a/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs b/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs index 019d425..4868480 100644 --- a/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs +++ b/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs @@ -426,7 +426,8 @@ public async Task OnDragDropRenew(int certId, string entityType, int targetCaId, TryParseSan(trimmed, "Email:", SanType.Email, out entry) || TryParseSan(trimmed, "IP Address=", SanType.IpAddress, out entry) || TryParseSan(trimmed, "IP:", SanType.IpAddress, out entry) || - TryParseSan(trimmed, "IpAddress:", SanType.IpAddress, out entry)) + TryParseSan(trimmed, "IpAddress:", SanType.IpAddress, out entry) || + TryParseSan(trimmed, "Npi:", SanType.Npi, out entry)) { renewalSans.Add(entry); } @@ -771,15 +772,7 @@ private async Task SelectNode(CertificateChainNodeViewModel node) { var sanExt = selectedCert.Extensions["2.5.29.17"]; if (sanExt != null) - { - try - { - subjectAltNames = sanExt.Format(multiLine: true) - .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .ToList(); - } - catch { } - } + subjectAltNames = SubjectAltNameText.Describe(sanExt); } await UpdateTreeHighlightsAsync(); @@ -2104,6 +2097,7 @@ private void CancelCaAssignment() SanType.Dns => "example.com", SanType.Email => "admin@example.com", SanType.IpAddress => "192.168.1.1", + SanType.Npi => "1234567893 (10-digit NPI)", _ => "" }; @@ -2443,14 +2437,7 @@ private void OnProfileSelected(CertificateProfile? profile) { foreach (var sanType in profile.SubjectAltNameTypes.Split(';', StringSplitOptions.RemoveEmptyEntries)) { - var type = sanType.Trim().ToUpperInvariant() switch - { - "URI" => SanType.Uri, - "DNS" => SanType.Dns, - "EMAIL" => SanType.Email, - "IP" => SanType.IpAddress, - _ => SanType.Uri - }; + var type = IssuanceValidator.ParseSanTypeToken(sanType) ?? SanType.Uri; issuanceSans.Add(new IssuanceSanEntry { Type = type, Value = string.Empty }); } } @@ -2489,14 +2476,7 @@ private void ShowSanListPickerDialog(SanList list) { var typeName = part[..colonIdx]; var value = part[(colonIdx + 1)..]; - var sanType = typeName.ToUpperInvariant() switch - { - "URI" => SanType.Uri, - "DNS" => SanType.Dns, - "EMAIL" => SanType.Email, - "IP" => SanType.IpAddress, - _ => SanType.Uri - }; + var sanType = IssuanceValidator.ParseSanTypeToken(typeName) ?? SanType.Uri; var alreadyAdded = issuanceSans.Any(s => s.Type == sanType && s.Value == value); sanPickerItems.Add(new SanListPickerItem { Type = sanType, Value = value, Selected = alreadyAdded }); } @@ -2724,7 +2704,8 @@ private async Task ShowSimilarDialog() TryParseSan(trimmed, "Email:", SanType.Email, out entry) || TryParseSan(trimmed, "IP Address=", SanType.IpAddress, out entry) || TryParseSan(trimmed, "IP:", SanType.IpAddress, out entry) || - TryParseSan(trimmed, "IpAddress:", SanType.IpAddress, out entry)) + TryParseSan(trimmed, "IpAddress:", SanType.IpAddress, out entry) || + TryParseSan(trimmed, "Npi:", SanType.Npi, out entry)) { renewalSans.Add(entry); } @@ -2922,7 +2903,8 @@ private async Task ShowRenewDialog() TryParseSan(trimmed, "Email:", SanType.Email, out entry) || TryParseSan(trimmed, "IP Address=", SanType.IpAddress, out entry) || TryParseSan(trimmed, "IP:", SanType.IpAddress, out entry) || - TryParseSan(trimmed, "IpAddress:", SanType.IpAddress, out entry)) + TryParseSan(trimmed, "IpAddress:", SanType.IpAddress, out entry) || + TryParseSan(trimmed, "Npi:", SanType.Npi, out entry)) { renewalSans.Add(entry); } diff --git a/Sigyll.UI/Components/Pages/CertificateProfiles.razor b/Sigyll.UI/Components/Pages/CertificateProfiles.razor index 7b27e4a..ea84be4 100644 --- a/Sigyll.UI/Components/Pages/CertificateProfiles.razor +++ b/Sigyll.UI/Components/Pages/CertificateProfiles.razor @@ -156,6 +156,21 @@ } + + @if (certificatePolicyError != null) + { +
@certificatePolicyError
+ } + else + { +
+ Written into the certificatePolicies extension (2.5.29.32, non-critical). Leave empty to omit it. +
+ } +
@@ -191,6 +206,7 @@ +
@* SAN Lists *@ @@ -213,7 +229,7 @@ + Disabled="@(string.IsNullOrWhiteSpace(editName) || certificatePolicyError != null || !Access.CanAdminister)"> @(isEditing ? "Save" : "Create") diff --git a/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs b/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs index 99dfab2..f79395b 100644 --- a/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs +++ b/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs @@ -51,6 +51,8 @@ public partial class CertificateProfiles private string editCustomEkuOids = string.Empty; private HashSet editSelectedEkuOids = new(); private bool editIsEkuCritical; + private string editCertificatePolicyOids = string.Empty; + private string? certificatePolicyError; private bool editIsBasicConstraintsCa; private bool editIsBasicConstraintsCritical = true; private int? editPathLengthConstraint; @@ -63,6 +65,7 @@ public partial class CertificateProfiles private bool editSanDns; private bool editSanEmail; private bool editSanIp; + private bool editSanNpi; private List availableSanLists = new(); private HashSet editSelectedSanListIds = new(); @@ -146,6 +149,8 @@ private void ResetForm() editCustomEkuOids = string.Empty; editSelectedEkuOids.Clear(); editIsEkuCritical = false; + editCertificatePolicyOids = string.Empty; + certificatePolicyError = null; editIsBasicConstraintsCa = false; editIsBasicConstraintsCritical = true; editPathLengthConstraint = null; @@ -158,6 +163,7 @@ private void ResetForm() editSanDns = false; editSanEmail = false; editSanIp = false; + editSanNpi = false; editSelectedSanListIds.Clear(); } @@ -208,6 +214,8 @@ private void PopulateForm(CertificateProfile t) editCustomEkuOids = string.Join(";", customParts); } editIsEkuCritical = t.IsExtendedKeyUsageCritical; + editCertificatePolicyOids = t.CertificatePolicyOids ?? string.Empty; + ValidateCertificatePolicies(); editIsBasicConstraintsCa = t.IsBasicConstraintsCa; editIsBasicConstraintsCritical = t.IsBasicConstraintsCritical; editPathLengthConstraint = t.PathLengthConstraint; @@ -222,6 +230,7 @@ private void PopulateForm(CertificateProfile t) editSanDns = sanTypes.Contains("DNS", StringComparer.OrdinalIgnoreCase); editSanEmail = sanTypes.Contains("Email", StringComparer.OrdinalIgnoreCase); editSanIp = sanTypes.Contains("IP", StringComparer.OrdinalIgnoreCase); + editSanNpi = sanTypes.Contains("NPI", StringComparer.OrdinalIgnoreCase); editSelectedSanListIds = new HashSet(t.SanLists.Select(s => s.Id)); } @@ -259,6 +268,7 @@ private CertificateProfile BuildEntityFromForm(CertificateProfile? existing = nu entity.IsKeyUsageCritical = editIsKeyUsageCritical; entity.ExtendedKeyUsageOids = string.IsNullOrWhiteSpace(editEkuOids) ? null : editEkuOids.Trim(); entity.IsExtendedKeyUsageCritical = editIsEkuCritical; + entity.CertificatePolicyOids = CertificatePolicyExtension.Normalize(editCertificatePolicyOids); entity.IsBasicConstraintsCa = editIsBasicConstraintsCa; entity.IsBasicConstraintsCritical = editIsBasicConstraintsCritical; entity.PathLengthConstraint = editIsBasicConstraintsCa ? editPathLengthConstraint : null; @@ -273,14 +283,25 @@ private CertificateProfile BuildEntityFromForm(CertificateProfile? existing = nu if (editSanDns) sanParts.Add("DNS"); if (editSanEmail) sanParts.Add("Email"); if (editSanIp) sanParts.Add("IP"); + if (editSanNpi) sanParts.Add("NPI"); entity.SubjectAltNameTypes = sanParts.Count > 0 ? string.Join(";", sanParts) : null; return entity; } + private void ValidateCertificatePolicies() + { + var invalid = CertificatePolicyExtension.FindInvalid(editCertificatePolicyOids); + certificatePolicyError = invalid.Count == 0 + ? null + : $"Not a valid OID: {string.Join(", ", invalid)}"; + } + private async Task SaveProfileAsync() { if (string.IsNullOrWhiteSpace(editName)) return; + ValidateCertificatePolicies(); + if (certificatePolicyError != null) return; CertificateProfile entity; @@ -318,6 +339,7 @@ private void CloneProfileAsync(CertificateProfile source) IsKeyUsageCritical = source.IsKeyUsageCritical, ExtendedKeyUsageOids = source.ExtendedKeyUsageOids, IsExtendedKeyUsageCritical = source.IsExtendedKeyUsageCritical, + CertificatePolicyOids = source.CertificatePolicyOids, IsBasicConstraintsCa = source.IsBasicConstraintsCa, IsBasicConstraintsCritical = source.IsBasicConstraintsCritical, PathLengthConstraint = source.PathLengthConstraint, diff --git a/Sigyll.UI/Components/Pages/ExternalRequests.razor.cs b/Sigyll.UI/Components/Pages/ExternalRequests.razor.cs index a868c23..548e81e 100644 --- a/Sigyll.UI/Components/Pages/ExternalRequests.razor.cs +++ b/Sigyll.UI/Components/Pages/ExternalRequests.razor.cs @@ -130,6 +130,7 @@ public class ModelOption SanType.Dns => "example.com", SanType.Email => "admin@example.com", SanType.IpAddress => "192.168.1.1", + SanType.Npi => "1234567893 (10-digit NPI)", _ => string.Empty }; @@ -268,6 +269,7 @@ private void OnKeyAlgorithmChanged(string? algorithm) SanType.Uri => Uri.TryCreate(san.Value.Trim(), UriKind.Absolute, out _), SanType.IpAddress => System.Net.IPAddress.TryParse(san.Value.Trim(), out _), SanType.Email => san.Value.Contains('@'), + SanType.Npi => NpiNumber.Validate(san.Value) is null, _ => true }; diff --git a/Sigyll.UI/Components/Pages/SanLists.razor b/Sigyll.UI/Components/Pages/SanLists.razor index d93c258..aecf72c 100644 --- a/Sigyll.UI/Components/Pages/SanLists.razor +++ b/Sigyll.UI/Components/Pages/SanLists.razor @@ -70,7 +70,7 @@ } + Placeholder="@(entry.Type == "NPI" ? "1234567893 (10-digit NPI)" : "urn:oid:2.16.840.1.113883.3.7204.1.5.2.1#T-TRTMNT")" /> diff --git a/Sigyll.UI/Components/Pages/SanLists.razor.cs b/Sigyll.UI/Components/Pages/SanLists.razor.cs index fb22acd..d9aa6fd 100644 --- a/Sigyll.UI/Components/Pages/SanLists.razor.cs +++ b/Sigyll.UI/Components/Pages/SanLists.razor.cs @@ -32,7 +32,7 @@ public partial class SanLists private string editDescription = string.Empty; private List editEntries = new(); - private static readonly string[] sanTypeNames = ["URI", "DNS", "Email", "IP"]; + private static readonly string[] sanTypeNames = ["URI", "DNS", "Email", "IP", "NPI"]; protected override async Task OnInitializedAsync() { diff --git a/Sigyll.UI/Components/Shared/CsrBuilder.razor.cs b/Sigyll.UI/Components/Shared/CsrBuilder.razor.cs index f0072e9..d861f9b 100644 --- a/Sigyll.UI/Components/Shared/CsrBuilder.razor.cs +++ b/Sigyll.UI/Components/Shared/CsrBuilder.razor.cs @@ -127,6 +127,7 @@ private void OnKeyAlgorithmChanged(string? algorithm) SanType.Uri => Uri.TryCreate(san.Value.Trim(), UriKind.Absolute, out _), SanType.IpAddress => System.Net.IPAddress.TryParse(san.Value.Trim(), out _), SanType.Email => san.Value.Contains('@'), + SanType.Npi => NpiNumber.Validate(san.Value) is null, _ => true }; @@ -136,6 +137,7 @@ private void OnKeyAlgorithmChanged(string? algorithm) SanType.Dns => "example.com", SanType.Email => "admin@example.com", SanType.IpAddress => "192.168.1.1", + SanType.Npi => "1234567893 (10-digit NPI)", _ => string.Empty }; diff --git a/Sigyll.UI/Components/Shared/ExtensionTable.razor b/Sigyll.UI/Components/Shared/ExtensionTable.razor index 89784f4..20cf8a2 100644 --- a/Sigyll.UI/Components/Shared/ExtensionTable.razor +++ b/Sigyll.UI/Components/Shared/ExtensionTable.razor @@ -88,6 +88,19 @@ continue; } + // Decoded here so the policy OIDs read the same on every OS; X509Extension.Format depends on the platform. + if (ext.Oid?.Value == Sigyll.Common.Services.CertificatePolicyExtension.CertificatePoliciesOid) + { + extensions.Add(new ExtensionRow + { + Oid = ext.Oid.Value, + FriendlyName = "Certificate Policies", + Critical = ext.Critical, + Value = Sigyll.Common.Services.CertificatePolicyExtension.Describe(ext) + }); + continue; + } + extensions.Add(new ExtensionRow { Oid = ext.Oid?.Value ?? "Unknown", diff --git a/Sigyll/Program.cs b/Sigyll/Program.cs index 0bd4c8e..a50867f 100644 --- a/Sigyll/Program.cs +++ b/Sigyll/Program.cs @@ -483,6 +483,7 @@ "dns" => SanType.Dns, "email" => SanType.Email, "ipaddress" or "ip" => SanType.IpAddress, + "npi" => SanType.Npi, _ => SanType.Dns }, s.Value); @@ -676,6 +677,10 @@ static IEnumerable PresetProfiles() AllowAutoIssue = true, }; + // TEFCA FHIR (RCE UDAP): intermediate, plus production and validation client/server leaves. + foreach (var tefca in TefcaCertificateProfiles.All()) + yield return tefca; + // Post-quantum presets. Pure ML-DSA / SLH-DSA do not use the profile hash. // ML-DSA-87 and ML-KEM-1024 are the CNSA 2.0 parameter sets. yield return PqcCa("Root CA (ML-DSA-87)", diff --git a/_tests/Sigyll.Signing.Tests/CertificatePolicyExtensionTests.cs b/_tests/Sigyll.Signing.Tests/CertificatePolicyExtensionTests.cs new file mode 100644 index 0000000..440024c --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/CertificatePolicyExtensionTests.cs @@ -0,0 +1,157 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Extensions.Logging.Abstractions; +using Org.BouncyCastle.Asn1; +using Shouldly; +using Sigyll.Common.Data.Entities; +using Sigyll.Common.Services; +using Xunit; +using BcCertificatePolicies = Org.BouncyCastle.Asn1.X509.CertificatePolicies; +using BcPolicyInformation = Org.BouncyCastle.Asn1.X509.PolicyInformation; +using BcPolicyQualifierInfo = Org.BouncyCastle.Asn1.X509.PolicyQualifierInfo; + +namespace Sigyll.Signing.Tests; + +public class CertificatePolicyExtensionTests +{ + private const string PolicyA = "1.3.6.1.4.1.99999.1.2"; + private const string PolicyB = "2.23.140.1.2.1"; + + [Theory] + [InlineData(PolicyA, true)] + [InlineData(PolicyB, true)] + [InlineData("2.5.29.32.0", true)] + [InlineData("2.999", true)] + [InlineData("1.39.1", true)] + [InlineData("1.40.1", false)] + [InlineData("3.1", false)] + [InlineData("1", false)] + [InlineData("1.3.06.1", false)] + [InlineData("1.3.", false)] + [InlineData("anyPolicy", false)] + [InlineData("", false)] + public void IsValidOid(string oid, bool expected) => + CertificatePolicyExtension.IsValidOid(oid).ShouldBe(expected); + + [Fact] + public void Parse_AcceptsCommonSeparators_DropsBlanksAndRepeats_KeepsOrder() + { + CertificatePolicyExtension.Parse($" {PolicyB} ;{PolicyA}, {PolicyB}\n;; ") + .ShouldBe([PolicyB, PolicyA]); + CertificatePolicyExtension.Parse(null).ShouldBeEmpty(); + CertificatePolicyExtension.Parse(" ").ShouldBeEmpty(); + } + + [Fact] + public void Normalize_JoinsWithSemicolons_OrNullWhenEmpty() + { + CertificatePolicyExtension.Normalize($"{PolicyA}, {PolicyB}").ShouldBe($"{PolicyA};{PolicyB}"); + CertificatePolicyExtension.Normalize(" ; ").ShouldBeNull(); + } + + [Fact] + public void FindInvalid_NamesTheEntriesThatAreNotOids() + { + CertificatePolicyExtension.FindInvalid($"{PolicyA};nope;1.40.2").ShouldBe(["nope", "1.40.2"]); + CertificatePolicyExtension.FindInvalid(PolicyA).ShouldBeEmpty(); + } + + [Fact] + public void Build_NoPolicies_ReturnsNull() + { + CertificatePolicyExtension.Build((string?)null).ShouldBeNull(); + CertificatePolicyExtension.Build(Array.Empty()).ShouldBeNull(); + } + + [Fact] + public void Build_InvalidOid_Throws() + { + Should.Throw(() => CertificatePolicyExtension.Build([PolicyA, "not-an-oid"])); + } + + [Fact] + public void Build_WritesDerThatBouncyCastleReadsBack() + { + var extension = CertificatePolicyExtension.Build($"{PolicyA};{PolicyB}")!; + + extension.Oid!.Value.ShouldBe("2.5.29.32"); + extension.Critical.ShouldBeFalse(); + + var parsed = BcCertificatePolicies.GetInstance(Asn1Object.FromByteArray(extension.RawData)); + parsed.GetPolicyInformation().Select(p => p.PolicyIdentifier.Id).ShouldBe([PolicyA, PolicyB]); + parsed.GetPolicyInformation().ShouldAllBe(p => p.PolicyQualifiers == null); + + CertificatePolicyExtension.Build(PolicyA, critical: true)!.Critical.ShouldBeTrue(); + } + + [Fact] + public void Decode_ReadsQualifiers_AndDescribeListsThem() + { + var cps = new BcPolicyQualifierInfo("https://example.com/cps"); + var policies = new BcCertificatePolicies( + [ + new BcPolicyInformation(new DerObjectIdentifier(PolicyA), new DerSequence(cps)), + new BcPolicyInformation(new DerObjectIdentifier(CertificatePolicyExtension.AnyPolicyOid)), + ]); + var extension = new X509Extension(CertificatePolicyExtension.CertificatePoliciesOid, policies.GetDerEncoded(), false); + + var decoded = CertificatePolicyExtension.Decode(extension); + decoded.Select(p => p.PolicyOid).ShouldBe([PolicyA, CertificatePolicyExtension.AnyPolicyOid]); + decoded[0].Qualifiers.ShouldBe(["CPS: https://example.com/cps"]); + + var text = CertificatePolicyExtension.Describe(extension); + text.ShouldContain(PolicyA); + text.ShouldContain("CPS: https://example.com/cps"); + text.ShouldContain("2.5.29.32.0 (anyPolicy)"); + } + + [Fact] + public void Describe_UndecodableExtension_FallsBackToHex() + { + var extension = new X509Extension(CertificatePolicyExtension.CertificatePoliciesOid, [0x04, 0x01, 0x00], false); + CertificatePolicyExtension.Describe(extension).ShouldBe("040100"); + } + + [Fact] + public async Task ProfileService_Save_NormalizesPolicies_AndRefusesInvalidOnes() + { + var service = new CertificateProfileService(new TestDbContextFactory(), TestOperators.Full, + NullLogger.Instance); + + var saved = await service.SaveAsync(new CertificateProfile + { + Name = "Policies", + CertificateType = CertificateType.EndEntityClient, + CertificatePolicyOids = $" {PolicyA}, {PolicyB} ", + }); + saved.CertificatePolicyOids.ShouldBe($"{PolicyA};{PolicyB}"); + + var ex = await Should.ThrowAsync(() => service.SaveAsync(new CertificateProfile + { + Name = "Bad policies", + CertificateType = CertificateType.EndEntityClient, + CertificatePolicyOids = "policy-one", + })); + ex.Message.ShouldContain("policy-one"); + } + + [Fact] + public void Read_CertificateWithoutPolicies_ReturnsEmpty() + { + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=No policies", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1)); + + CertificatePolicyExtension.Read(cert).ShouldBeEmpty(); + } +} diff --git a/_tests/Sigyll.Signing.Tests/CsrIssuanceTests.cs b/_tests/Sigyll.Signing.Tests/CsrIssuanceTests.cs index 49dfe7c..3176e93 100644 --- a/_tests/Sigyll.Signing.Tests/CsrIssuanceTests.cs +++ b/_tests/Sigyll.Signing.Tests/CsrIssuanceTests.cs @@ -188,6 +188,61 @@ public async Task IssueFromCsr_DnsSanWithPort_Fails() result.Error.ShouldContain("port"); } + [Fact] + public async Task IssueFromCsr_NpiSan_IsEncodedAsOtherNameAndStored() + { + var (caId, profileId, trustDomainId) = await SeedAsync(); + + using var subjectKey = RSA.Create(2048); + var result = await CreateService().IssueCertificateFromCsrAsync(new CsrIssuanceRequest + { + IssuingCaCertificateId = caId, + ProfileId = profileId, + TrustDomainId = trustDomainId, + CsrPem = BuildCsrPem(subjectKey, "CN=api.example.com"), + SubjectAltNames = + [ + new SanEntry(SanType.Dns, "api.example.com"), + new SanEntry(SanType.Npi, "1234567893"), + ], + }); + + result.Success.ShouldBeTrue(result.Error); + using var issued = X509Certificate2.CreateFromPem(result.CertificatePem!); + CsrGenerationService.ExtractSubjectAltNames(issued).ShouldBe( + [ + new SanEntry(SanType.Dns, "api.example.com"), + new SanEntry(SanType.Npi, "1234567893"), + ]); + + await using var db = _dbFactory.CreateDbContext(); + var entity = await db.IssuedCertificates.FindAsync(result.EntityId); + entity!.SubjectAltNames.ShouldBe("Dns:api.example.com;Npi:1234567893"); + } + + [Fact] + public async Task IssueFromCsr_NpiWithBadCheckDigit_IsRejected() + { + var (caId, profileId, trustDomainId) = await SeedAsync(); + + using var subjectKey = RSA.Create(2048); + var result = await CreateService().IssueCertificateFromCsrAsync(new CsrIssuanceRequest + { + IssuingCaCertificateId = caId, + ProfileId = profileId, + TrustDomainId = trustDomainId, + CsrPem = BuildCsrPem(subjectKey, "CN=api.example.com"), + SubjectAltNames = + [ + new SanEntry(SanType.Dns, "api.example.com"), + new SanEntry(SanType.Npi, "1234567890"), + ], + }); + + result.Success.ShouldBeFalse(); + result.Error.ShouldContain("check digit"); + } + [Fact] public async Task IssueFromCsr_FirstIssuance_IsVersion1WithNoLineage() { diff --git a/_tests/Sigyll.Signing.Tests/NpiSanTests.cs b/_tests/Sigyll.Signing.Tests/NpiSanTests.cs new file mode 100644 index 0000000..499c20c --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/NpiSanTests.cs @@ -0,0 +1,148 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Asn1.X509; +using Shouldly; +using Sigyll.Common.Services; +using Sigyll.Common.Validators; +using Sigyll.Common.ViewModels; +using X509Extension = System.Security.Cryptography.X509Certificates.X509Extension; + +namespace Sigyll.Signing.Tests; + +public class NpiSanTests +{ + private readonly IssuanceValidator _validator = new(); + + [Theory] + [InlineData("1234567893")] // the worked example in the NPI check-digit standard + [InlineData("1245319599")] + [InlineData("1003000126")] + public void IsValid_AcceptsNpisWithCorrectCheckDigit(string npi) + { + NpiNumber.IsValid(npi).ShouldBeTrue(); + NpiNumber.Validate(npi).ShouldBeNull(); + } + + [Theory] + [InlineData("1234567890")] + [InlineData("1234567894")] + [InlineData("1245319590")] + public void Validate_RejectsWrongCheckDigit(string npi) + { + NpiNumber.IsValid(npi).ShouldBeFalse(); + NpiNumber.Validate(npi)!.ShouldContain("check digit"); + } + + [Theory] + [InlineData("")] + [InlineData("123456789")] + [InlineData("12345678930")] + [InlineData("12345a7893")] + [InlineData("123-456-78")] + public void Validate_RejectsAnythingButTenDigits(string npi) + { + NpiNumber.IsValid(npi).ShouldBeFalse(); + NpiNumber.Validate(npi)!.ShouldContain("10 digits"); + } + + [Fact] + public void ValidateSanValues_ChecksNpiEntries() + { + _validator.ValidateSanValues([new SanEntry(SanType.Npi, "1234567893")]).ShouldBeNull(); + _validator.ValidateSanValues([new SanEntry(SanType.Npi, " 1234567893 ")]).ShouldBeNull(); + _validator.ValidateSanValues([new SanEntry(SanType.Npi, "1234567890")])!.ShouldContain("NPI"); + } + + [Fact] + public void ParseSanTypes_KnowsNpi() + { + IssuanceValidator.ParseSanTypes("DNS;NPI").ShouldBe([SanType.Dns, SanType.Npi]); + IssuanceValidator.ParseSanTypeToken("npi").ShouldBe(SanType.Npi); + IssuanceValidator.SanTypeDisplayName(SanType.Npi).ShouldBe("NPI"); + } + + [Fact] + public void Build_EncodesNpiAsUtf8OtherName() + { + var ext = SanExtensionBuilder.Build([new SanEntry(SanType.Npi, " 1234567893 ")])!; + + var name = GeneralNames.GetInstance(Asn1Object.FromByteArray(ext.RawData)).GetNames().Single(); + name.TagNo.ShouldBe(GeneralName.OtherName); + + var seq = Asn1Sequence.GetInstance(name.Name); + DerObjectIdentifier.GetInstance(seq[0]).Id.ShouldBe("2.16.840.1.113883.4.6"); + var tagged = Asn1TaggedObject.GetInstance(seq[1]); + tagged.TagNo.ShouldBe(0); + tagged.IsExplicit().ShouldBeTrue(); + var value = tagged.GetExplicitBaseObject().ShouldBeOfType(); + value.GetString().ShouldBe("1234567893"); + } + + [Fact] + public void Build_RejectsInvalidNpi() + { + Should.Throw(() => SanExtensionBuilder.Build([new SanEntry(SanType.Npi, "1234567890")])); + } + + [Fact] + public void Certificate_NpiSan_IsReadBackForReissueAndDisplay() + { + using var cert = SelfSigned( + [ + new SanEntry(SanType.Uri, "https://host.example"), + new SanEntry(SanType.Npi, "1245319599"), + ]); + + CsrGenerationService.ExtractSubjectAltNames(cert).ShouldBe( + [ + new SanEntry(SanType.Uri, "https://host.example"), + new SanEntry(SanType.Npi, "1245319599"), + ]); + + SubjectAltNameText.Describe(cert.Extensions[SanExtensionBuilder.SubjectAltNameOid]!) + .ShouldBe(["Uri:https://host.example", "Npi:1245319599"]); + } + + [Fact] + public void Describe_WithoutOtherName_KeepsPlatformFormatting() + { + using var cert = SelfSigned([new SanEntry(SanType.Dns, "api.example.com")]); + var ext = cert.Extensions[SanExtensionBuilder.SubjectAltNameOid]!; + + var expected = ext.Format(multiLine: true) + .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + SubjectAltNameText.Describe(ext).ShouldBe(expected); + } + + [Fact] + public void Describe_OtherNameThatIsNotNpi_ShowsItsOid() + { + var other = new GeneralName(GeneralName.OtherName, new DerSequence( + new DerObjectIdentifier("1.3.6.1.4.1.311.20.2.3"), + new DerTaggedObject(true, 0, new DerUtf8String("user@example.com")))); + var raw = new GeneralNames([other, new GeneralName(GeneralName.DnsName, "a.example")]).GetDerEncoded(); + + var lines = SubjectAltNameText.Describe(new X509Extension(SanExtensionBuilder.SubjectAltNameOid, raw, false)); + + lines.ShouldBe(["OtherName:1.3.6.1.4.1.311.20.2.3=user@example.com", "Dns:a.example"]); + } + + private static X509Certificate2 SelfSigned(List sans) + { + using var key = RSA.Create(2048); + var req = new CertificateRequest("CN=npi.example", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + req.CertificateExtensions.Add(SanExtensionBuilder.Build(sans)!); + return req.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddDays(1)); + } +} diff --git a/_tests/Sigyll.Signing.Tests/RenewalIdentityTests.cs b/_tests/Sigyll.Signing.Tests/RenewalIdentityTests.cs index a9e284a..7c6aba1 100644 --- a/_tests/Sigyll.Signing.Tests/RenewalIdentityTests.cs +++ b/_tests/Sigyll.Signing.Tests/RenewalIdentityTests.cs @@ -127,6 +127,102 @@ public async Task CompatibleProfile_MatchesCaFlagKeyUsageEkuAndRequiredSanTypes( RenewalIdentity.IsCompatibleProfile(profile, cert, sans).ShouldBeFalse("different key usages"); } + [Fact] + public async Task ProfilePolicies_AreWrittenIntoTheCertificate_AndKeptOnRenewal() + { + const string policyA = "1.3.6.1.4.1.99999.1.2"; + const string policyB = "1.3.6.1.4.1.99999.1.3"; + var (seed, first) = await IssueFirstAsync(policies: $"{policyA};{policyB}"); + + await using (var db = _dbFactory.CreateDbContext()) + { + var issued = await db.IssuedCertificates.FindAsync(first); + using var cert = X509Certificate2.CreateFromPem(issued!.X509CertificatePem); + CertificatePolicyExtension.Read(cert).ShouldBe([policyA, policyB]); + cert.Extensions[CertificatePolicyExtension.CertificatePoliciesOid]!.Critical.ShouldBeFalse(); + } + + var second = await CreateService().IssueCertificateAsync(Renewal(seed, first, + "CN=api.example.com", new SanEntry(SanType.Dns, "api.example.com"))); + second.Success.ShouldBeTrue(second.Error); + + await using (var db = _dbFactory.CreateDbContext()) + { + var renewed = await db.IssuedCertificates.FindAsync(second.EntityId); + using var cert = X509Certificate2.CreateFromPem(renewed!.X509CertificatePem); + CertificatePolicyExtension.Read(cert).ShouldBe([policyA, policyB]); + } + } + + [Fact] + public async Task Renewal_WithAProfileThatDropsAPolicy_IsRefused() + { + const string policyA = "1.3.6.1.4.1.99999.1.2"; + const string policyB = "1.3.6.1.4.1.99999.1.3"; + var (seed, first) = await IssueFirstAsync(policies: $"{policyA};{policyB}"); + await SetProfilePoliciesAsync(seed.ProfileId, policyA); + + var second = await CreateService().IssueCertificateAsync(Renewal(seed, first, + "CN=api.example.com", new SanEntry(SanType.Dns, "api.example.com"))); + + second.Success.ShouldBeFalse(); + second.Error!.ShouldContain($"does not include {policyB}"); + } + + [Fact] + public async Task Issuance_WithAnInvalidPolicyOnTheProfile_IsRefused() + { + var seed = await SeedAsync(); + await SetProfilePoliciesAsync(seed.ProfileId, "1.3.6.1.4.1.99999.1.2;not-an-oid"); + + var result = await CreateService().IssueCertificateAsync(new CertificateIssuanceRequest + { + IssuingCaCertificateId = seed.CaId, + ProfileId = seed.ProfileId, + TrustDomainId = seed.TrustDomainId, + SubjectDn = "CN=api.example.com", + CertificateName = "api", + PfxPassword = "test-password", + SubjectAltNames = [new SanEntry(SanType.Dns, "api.example.com")], + }); + + result.Success.ShouldBeFalse(); + result.Error!.ShouldContain("not-an-oid"); + } + + [Fact] + public async Task CompatibleProfile_MustKeepEveryPolicy_ButMayAddOne() + { + const string policyA = "1.3.6.1.4.1.99999.1.2"; + const string policyB = "1.3.6.1.4.1.99999.1.3"; + var (seed, first) = await IssueFirstAsync(policies: policyA); + await using var db = _dbFactory.CreateDbContext(); + var issued = await db.IssuedCertificates.FindAsync(first); + using var cert = X509Certificate2.CreateFromPem(issued!.X509CertificatePem); + var profile = (await db.CertificateProfiles.FindAsync(seed.ProfileId))!; + List sans = [new(SanType.Dns, "api.example.com")]; + + RenewalIdentity.IsCompatibleProfile(profile, cert, sans).ShouldBeTrue(); + + profile.CertificatePolicyOids = $"{policyA};{policyB}"; + RenewalIdentity.IsCompatibleProfile(profile, cert, sans).ShouldBeTrue("a profile may add a policy"); + + profile.CertificatePolicyOids = policyB; + RenewalIdentity.IsCompatibleProfile(profile, cert, sans).ShouldBeFalse("drops the certificate's policy"); + RenewalIdentity.FindDroppedPolicies(profile, cert).ShouldBe([policyA]); + + profile.CertificatePolicyOids = null; + RenewalIdentity.IsCompatibleProfile(profile, cert, sans).ShouldBeFalse("drops the certificate's policy"); + } + + private async Task SetProfilePoliciesAsync(int profileId, string? policies) + { + await using var db = _dbFactory.CreateDbContext(); + var profile = (await db.CertificateProfiles.FindAsync(profileId))!; + profile.CertificatePolicyOids = policies; + await db.SaveChangesAsync(); + } + private sealed record Seed(int CaId, int ProfileId, int TrustDomainId); private static CertificateIssuanceRequest Renewal(Seed seed, int predecessorId, string subjectDn, params SanEntry[] sans) => new() @@ -141,9 +237,14 @@ private sealed record Seed(int CaId, int ProfileId, int TrustDomainId); RenewalOfCertificateId = predecessorId, }; - private async Task<(Seed Seed, int FirstId)> IssueFirstAsync(params SanEntry[] extraSans) + private Task<(Seed Seed, int FirstId)> IssueFirstAsync(params SanEntry[] extraSans) => + IssueFirstAsync(null, extraSans); + + private async Task<(Seed Seed, int FirstId)> IssueFirstAsync(string? policies, params SanEntry[] extraSans) { var seed = await SeedAsync(); + if (policies != null) + await SetProfilePoliciesAsync(seed.ProfileId, policies); var first = await CreateService().IssueCertificateAsync(new CertificateIssuanceRequest { IssuingCaCertificateId = seed.CaId, diff --git a/_tests/Sigyll.Signing.Tests/TefcaCertificateProfilesTests.cs b/_tests/Sigyll.Signing.Tests/TefcaCertificateProfilesTests.cs new file mode 100644 index 0000000..266ce64 --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/TefcaCertificateProfilesTests.cs @@ -0,0 +1,199 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Sigyll.Common.Data.Entities; +using Sigyll.Common.Services; +using Sigyll.Common.Validators; +using Sigyll.Common.ViewModels; +using Xunit; + +namespace Sigyll.Signing.Tests; + +public class TefcaCertificateProfilesTests +{ + private readonly TestDbContextFactory _dbFactory = new(); + + private static CertificateProfile Preset(string name) => + TefcaCertificateProfiles.All().Single(p => p.Name == name); + + [Fact] + public void All_FivePresets_WithUniqueNames() + { + var names = TefcaCertificateProfiles.All().Select(p => p.Name).ToList(); + names.ShouldBe( + [ + TefcaCertificateProfiles.IntermediateName, + TefcaCertificateProfiles.ClientName, + TefcaCertificateProfiles.ServerName, + TefcaCertificateProfiles.ValidationClientName, + TefcaCertificateProfiles.ValidationServerName, + ]); + TefcaCertificateProfiles.All().ShouldAllBe(p => p.IsPreset); + } + + [Fact] + public void Intermediate_PathLengthZero_WithCdpAndAia() + { + var p = Preset(TefcaCertificateProfiles.IntermediateName); + p.CertificateType.ShouldBe(CertificateType.IntermediateCa); + p.IsBasicConstraintsCa.ShouldBeTrue(); + p.IsBasicConstraintsCritical.ShouldBeTrue(); + p.PathLengthConstraint.ShouldBe(0); + p.KeyUsageFlags.ShouldBe((int)(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign)); + p.IncludeCdp.ShouldBeTrue(); + p.IncludeAia.ShouldBeTrue(); + p.HashAlgorithm.ShouldBe("SHA256"); + } + + [Theory] + [InlineData(TefcaCertificateProfiles.ClientName, CertificateType.EndEntityClient, "RCE-FHIR", true)] + [InlineData(TefcaCertificateProfiles.ServerName, CertificateType.EndEntityServer, "RCE-FHIR", true)] + [InlineData(TefcaCertificateProfiles.ValidationClientName, CertificateType.EndEntityClient, "RCE-FHIR-TEST", false)] + [InlineData(TefcaCertificateProfiles.ValidationServerName, CertificateType.EndEntityServer, "RCE-FHIR-TEST", false)] + public void Leaf_FollowsTheTefcaProfile(string name, CertificateType type, string ou, bool policies) + { + var p = Preset(name); + p.CertificateType.ShouldBe(type); + p.KeyAlgorithm.ShouldBe("RSA"); + p.KeySize.ShouldBeGreaterThanOrEqualTo(2048); + p.HashAlgorithm.ShouldBe("SHA256"); + p.ValidityDays.ShouldBeLessThanOrEqualTo(3 * 365); + p.KeyUsageFlags.ShouldBe((int)X509KeyUsageFlags.DigitalSignature); + p.IsKeyUsageCritical.ShouldBeTrue(); + p.IsBasicConstraintsCa.ShouldBeFalse(); + p.IsBasicConstraintsCritical.ShouldBeTrue(); + p.ExtendedKeyUsageOids.ShouldBeNull(); + IssuanceValidator.ParseSanTypes(p.SubjectAltNameTypes).ShouldBe([SanType.Uri]); + p.SubjectTemplate.ShouldContain($"OU={ou},"); + p.SubjectTemplate.ShouldContain("C=US"); + p.RequiresRaApproval.ShouldBeTrue(); + p.AllowAutoIssue.ShouldBeFalse(); + + if (policies) + CertificatePolicyExtension.Parse(p.CertificatePolicyOids).ShouldBe( + ["1.3.6.1.4.1.41179.0.2", "1.3.6.1.4.1.41179.1.5", "1.3.6.1.4.1.41179.3.1"]); + else + p.CertificatePolicyOids.ShouldBeNull(); + } + + [Theory] + [InlineData(TefcaCertificateProfiles.ClientName, "RCE-FHIR", true)] + [InlineData(TefcaCertificateProfiles.ServerName, "RCE-FHIR", true)] + [InlineData(TefcaCertificateProfiles.ValidationClientName, "RCE-FHIR-TEST", false)] + public async Task IssueFromCsr_WithLeafPreset_WritesTheTefcaExtensions(string name, string ou, bool policies) + { + var (caId, profileId, trustDomainId) = await SeedAsync(Preset(name)); + const string uri = "https://fhir.example.org/r4"; + + using var subjectKey = RSA.Create(2048); + var subject = $"CN={uri}, OU={ou}, O=Example Health, ST=CA, C=US"; + var csr = new CertificateRequest(subject, subjectKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1) + .CreateSigningRequestPem(); + + var result = await new CertificateIssuanceService(_dbFactory, TestOperators.Full, + NullLogger.Instance) + .IssueCertificateFromCsrAsync(new CsrIssuanceRequest + { + IssuingCaCertificateId = caId, + ProfileId = profileId, + TrustDomainId = trustDomainId, + CsrPem = csr, + SubjectAltNames = [new SanEntry(SanType.Uri, uri), new SanEntry(SanType.Npi, "1234567893")], + CdpUrls = ["http://crl.example.org/tefca.crl"], + AiaUrls = ["http://crl.example.org/tefca.cer"], + }); + + result.Success.ShouldBeTrue(result.Error); + using var issued = X509Certificate2.CreateFromPem(result.CertificatePem!); + + var ku = issued.Extensions.OfType().Single(); + ku.Critical.ShouldBeTrue(); + ku.KeyUsages.ShouldBe(X509KeyUsageFlags.DigitalSignature); + + var bc = issued.Extensions.OfType().Single(); + bc.Critical.ShouldBeTrue(); + bc.CertificateAuthority.ShouldBeFalse(); + + issued.Extensions.OfType().ShouldBeEmpty(); + issued.SignatureAlgorithm.Value.ShouldBe("1.2.840.113549.1.1.11"); // sha256WithRSAEncryption + CsrGenerationService.ExtractSubjectAltNames(issued).ShouldBe( + [new SanEntry(SanType.Uri, uri), new SanEntry(SanType.Npi, "1234567893")]); + + var issuedPolicies = CertificatePolicyExtension.Read(issued); + if (policies) + issuedPolicies.ShouldBe(CertificatePolicyExtension.Parse(TefcaCertificateProfiles.ProductionPolicyOids)); + else + issuedPolicies.ShouldBeEmpty(); + } + + [Fact] + public async Task IssueFromCsr_WithLeafPreset_WithoutUriSan_IsRejected() + { + var (caId, profileId, trustDomainId) = await SeedAsync(Preset(TefcaCertificateProfiles.ClientName)); + + using var subjectKey = RSA.Create(2048); + var csr = new CertificateRequest("CN=no-uri", subjectKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1) + .CreateSigningRequestPem(); + + var result = await new CertificateIssuanceService(_dbFactory, TestOperators.Full, + NullLogger.Instance) + .IssueCertificateFromCsrAsync(new CsrIssuanceRequest + { + IssuingCaCertificateId = caId, + ProfileId = profileId, + TrustDomainId = trustDomainId, + CsrPem = csr, + SubjectAltNames = [new SanEntry(SanType.Npi, "1234567893")], + }); + + result.Success.ShouldBeFalse(); + result.Error.ShouldContain("URI"); + } + + private async Task<(int caId, int profileId, int trustDomainId)> SeedAsync(CertificateProfile profile) + { + await using var db = _dbFactory.CreateDbContext(); + + var trustDomain = new TrustDomain { Name = "TEFCA TD", Enabled = true }; + db.TrustDomains.Add(trustDomain); + db.CertificateProfiles.Add(profile); + + using var caKey = RSA.Create(2048); + var caReq = new CertificateRequest("CN=TEFCA Test Intermediate", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + caReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 0, true)); + caReq.CertificateExtensions.Add(new X509KeyUsageExtension( + X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); + using var caCert = caReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5)); + + var ca = new CaCertificate + { + TrustDomainId = trustDomain.Id, + Name = "TEFCA Test Intermediate", + Subject = "CN=TEFCA Test Intermediate", + X509CertificatePem = caCert.ExportCertificatePem(), + EncryptedPfxBytes = caCert.Export(X509ContentType.Pkcs12, "test"), + PfxPassword = "test", + Thumbprint = caCert.Thumbprint, + SerialNumber = caCert.SerialNumber, + KeyAlgorithm = "RSA", + KeySize = 2048, + NotBefore = caCert.NotBefore, + NotAfter = caCert.NotAfter, + }; + db.CaCertificates.Add(ca); + + await db.SaveChangesAsync(); + return (ca.Id, profile.Id, trustDomain.Id); + } +} diff --git a/dist/AlloyDB/sigil/sigil/tables/V11__certificate_policies.sql b/dist/AlloyDB/sigil/sigil/tables/V11__certificate_policies.sql new file mode 100644 index 0000000..b6ca201 --- /dev/null +++ b/dist/AlloyDB/sigil/sigil/tables/V11__certificate_policies.sql @@ -0,0 +1,6 @@ +-- A certificate profile can list certificate policy OIDs, which issued certificates carry in the certificatePolicies +-- extension (RFC 5280 section 4.2.1.4). Existing profiles list none, so their certificates are unchanged. + +ALTER TABLE "CertificateProfiles" ADD COLUMN "CertificatePolicyOids" CHARACTER VARYING(2000); + +COMMENT ON COLUMN "CertificateProfiles"."CertificatePolicyOids" IS 'Semicolon-delimited certificate policy OIDs written into the certificatePolicies extension (2.5.29.32); null leaves the extension out';