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/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/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/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/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/Validators/IssuanceValidator.cs b/Sigyll.Common/Validators/IssuanceValidator.cs index a805f75..dac4b1d 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(); @@ -119,7 +137,8 @@ public static List FindMissingSanTypes(string? subjectAltNameTypes, IEn SanType.Uri => "URI", SanType.Dns => "DNS", SanType.Email => "Email", - SanType.IpAddress => "IP", + SanType.IpAddress => "IP Address", + 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..7681d2b 100644 --- a/Sigyll.Portal/Components/Pages/Requests/NewRequest.razor +++ b/Sigyll.Portal/Components/Pages/Requests/NewRequest.razor @@ -63,7 +63,8 @@ else @foreach (var san in _sans) { - + @@ -90,7 +91,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.Portal/Services/CsrParser.cs b/Sigyll.Portal/Services/CsrParser.cs index f71bdf0..f32a924 100644 --- a/Sigyll.Portal/Services/CsrParser.cs +++ b/Sigyll.Portal/Services/CsrParser.cs @@ -8,6 +8,8 @@ // */ #endregion +using System.Formats.Asn1; +using System.Net; using System.Security.Cryptography.X509Certificates; using Sigyll.Contracts; @@ -15,12 +17,27 @@ namespace Sigyll.Portal.Services; /// /// Parses a caller-supplied PKCS#10 CSR for display/prefill in the request wizard — subject DN and -/// any DNS SANs. The portal only reads the CSR (public material); it never handles the private key. +/// the SANs the portal can request (DNS, URI, email, IP address and NPI otherName). The portal only +/// reads the CSR (public material); it never handles the private key. /// public static class CsrParser { + /// otherName type-id for a National Provider Identifier (DirectTrust certificate profiles). + public const string NpiOtherNameOid = "2.16.840.1.113883.4.6"; + public record ParsedCsr(string SubjectDn, List Sans); + /// Label shown for a SAN type token in the request form. + public static string SanTypeDisplayName(string type) => type switch + { + "Dns" => "DNS", + "Uri" => "URI", + "Email" => "Email", + "IpAddress" => "IP Address", + "Npi" => "NPI", + _ => type + }; + public static ParsedCsr Parse(string csrPem) { var req = CertificateRequest.LoadSigningRequestPem( @@ -30,13 +47,76 @@ public static ParsedCsr Parse(string csrPem) var sans = new List(); foreach (var ext in req.CertificateExtensions.OfType()) + sans.AddRange(ReadSubjectAltNames(ext.RawData)); + + return new ParsedCsr(req.SubjectName.Name, sans); + } + + /// + /// Reads the GeneralNames in a SAN extension value, in order. Name forms the portal cannot request + /// are skipped, and so is an otherName other than a 10-digit NPI. The CA validates every value + /// again (including the NPI check digit) when the request is issued. + /// + public static List ReadSubjectAltNames(ReadOnlyMemory sanExtensionValue) + { + var result = new List(); + var names = new AsnReader(sanExtensionValue, AsnEncodingRules.DER).ReadSequence(); + + while (names.HasData) { - foreach (var dns in ext.EnumerateDnsNames()) - sans.Add(new ApiSanEntry { Type = "Dns", Value = dns }); - foreach (var ip in ext.EnumerateIPAddresses()) - sans.Add(new ApiSanEntry { Type = "IpAddress", Value = ip.ToString() }); + var tag = names.PeekTag(); + if (tag.TagClass != TagClass.ContextSpecific) + { + names.ReadEncodedValue(); + continue; + } + + switch (tag.TagValue) + { + case 0 when TryReadNpi(names.ReadSequence(tag), out var npi): + result.Add(new ApiSanEntry { Type = "Npi", Value = npi }); + break; + case 1: + result.Add(new ApiSanEntry { Type = "Email", Value = names.ReadCharacterString(UniversalTagNumber.IA5String, tag) }); + break; + case 2: + result.Add(new ApiSanEntry { Type = "Dns", Value = names.ReadCharacterString(UniversalTagNumber.IA5String, tag) }); + break; + case 6: + result.Add(new ApiSanEntry { Type = "Uri", Value = names.ReadCharacterString(UniversalTagNumber.IA5String, tag) }); + break; + case 7: + var octets = names.ReadOctetString(tag); + if (octets.Length is 4 or 16) + result.Add(new ApiSanEntry { Type = "IpAddress", Value = new IPAddress(octets).ToString() }); + break; + case 0: + break; // otherName that is not an NPI: already consumed by the guard above + default: + names.ReadEncodedValue(); + break; + } } - return new ParsedCsr(req.SubjectName.Name, sans); + return result; + } + + // otherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY } + private static bool TryReadNpi(AsnReader otherName, out string npi) + { + npi = ""; + if (otherName.ReadObjectIdentifier() != NpiOtherNameOid || !otherName.HasData) + return false; + + var value = otherName.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true)); + if (value.PeekTag() != new Asn1Tag(UniversalTagNumber.UTF8String)) + return false; + + var text = value.ReadCharacterString(UniversalTagNumber.UTF8String).Trim(); + if (text.Length != 10 || !text.All(char.IsAsciiDigit)) + return false; + + npi = text; + return true; } } diff --git a/Sigyll.UI/Components/Pages/CertificateExplorer.razor b/Sigyll.UI/Components/Pages/CertificateExplorer.razor index 87c69cb..7da1411 100644 --- a/Sigyll.UI/Components/Pages/CertificateExplorer.razor +++ b/Sigyll.UI/Components/Pages/CertificateExplorer.razor @@ -541,7 +541,7 @@ 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..d5041a8 100644 --- a/Sigyll.UI/Components/Pages/CertificateProfiles.razor +++ b/Sigyll.UI/Components/Pages/CertificateProfiles.razor @@ -191,6 +191,7 @@ + @* SAN Lists *@ diff --git a/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs b/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs index 99dfab2..f134b51 100644 --- a/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs +++ b/Sigyll.UI/Components/Pages/CertificateProfiles.razor.cs @@ -63,6 +63,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(); @@ -158,6 +159,7 @@ private void ResetForm() editSanDns = false; editSanEmail = false; editSanIp = false; + editSanNpi = false; editSelectedSanListIds.Clear(); } @@ -222,6 +224,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)); } @@ -273,6 +276,7 @@ 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; diff --git a/Sigyll.UI/Components/Pages/ExternalRequests.razor b/Sigyll.UI/Components/Pages/ExternalRequests.razor index 744d7b1..e0e68b3 100644 --- a/Sigyll.UI/Components/Pages/ExternalRequests.razor +++ b/Sigyll.UI/Components/Pages/ExternalRequests.razor @@ -185,7 +185,7 @@ else @foreach (var san in newSans) { - "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 b/Sigyll.UI/Components/Shared/CsrBuilder.razor index 1fa4b8a..beb9715 100644 --- a/Sigyll.UI/Components/Shared/CsrBuilder.razor +++ b/Sigyll.UI/Components/Shared/CsrBuilder.razor @@ -84,7 +84,7 @@ 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/Program.cs b/Sigyll/Program.cs index 0bd4c8e..686f07d 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); 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/PortalCsrParserTests.cs b/_tests/Sigyll.Signing.Tests/PortalCsrParserTests.cs new file mode 100644 index 0000000..3f75fe7 --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/PortalCsrParserTests.cs @@ -0,0 +1,93 @@ +#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 Shouldly; +using Sigyll.Common.Services; +using Sigyll.Common.ViewModels; +using Sigyll.Portal.Services; + +namespace Sigyll.Signing.Tests; + +public class PortalCsrParserTests +{ + [Fact] + public void Parse_ReadsEverySanTypeThePortalCanRequest() + { + var pem = CsrWithSans( + new SanEntry(SanType.Uri, "https://fhir.example.org/fhir/r4"), + new SanEntry(SanType.Dns, "fhir.example.org"), + new SanEntry(SanType.Email, "ops@example.org"), + new SanEntry(SanType.IpAddress, "10.1.2.3"), + new SanEntry(SanType.Npi, "1234567893")); + + var parsed = CsrParser.Parse(pem); + + parsed.SubjectDn.ShouldBe("CN=fhir.example.org"); + parsed.Sans.Select(s => (s.Type, s.Value)).ShouldBe( + [ + ("Uri", "https://fhir.example.org/fhir/r4"), + ("Dns", "fhir.example.org"), + ("Email", "ops@example.org"), + ("IpAddress", "10.1.2.3"), + ("Npi", "1234567893"), + ]); + } + + [Fact] + public void Parse_KeepsUriSanVerbatim() + { + // SSRAA compares the SAN URI to the client's iss as an exact string, so no trailing slash may be added. + var parsed = CsrParser.Parse(CsrWithSans(new SanEntry(SanType.Uri, "https://client.example.org"))); + + parsed.Sans.ShouldHaveSingleItem().Value.ShouldBe("https://client.example.org"); + } + + [Fact] + public void ReadSubjectAltNames_SkipsOtherNamesThatAreNotNpi() + { + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSequence()) + { + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true))) + { + writer.WriteObjectIdentifier("1.3.6.1.4.1.311.20.2.3"); // Microsoft UPN + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true))) + writer.WriteCharacterString(UniversalTagNumber.UTF8String, "user@example.org"); + } + writer.WriteCharacterString(UniversalTagNumber.IA5String, "fhir.example.org", + new Asn1Tag(TagClass.ContextSpecific, 2)); + } + + var sans = CsrParser.ReadSubjectAltNames(writer.Encode()); + + sans.ShouldHaveSingleItem().Type.ShouldBe("Dns"); + } + + [Theory] + [InlineData("Dns", "DNS")] + [InlineData("Uri", "URI")] + [InlineData("IpAddress", "IP Address")] + [InlineData("Npi", "NPI")] + public void SanTypeDisplayName_ShowsFriendlyLabels(string token, string label) + { + CsrParser.SanTypeDisplayName(token).ShouldBe(label); + } + + private static string CsrWithSans(params SanEntry[] sans) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest("CN=fhir.example.org", key, HashAlgorithmName.SHA256); + request.CertificateExtensions.Add(SanExtensionBuilder.Build(sans)!); + return request.CreateSigningRequestPem(); + } +}