Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Sigyll.Common/Data/Entities/SanList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public class SanList
public string? Description { get; set; }

/// <summary>
/// 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").
/// </summary>
public string Items { get; set; } = string.Empty;

Expand Down
7 changes: 7 additions & 0 deletions Sigyll.Common/Services/CertificateImportService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
var rawData = sanExt.RawData;

Expand Down
12 changes: 2 additions & 10 deletions Sigyll.Common/Services/CertificateParsingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 4 additions & 1 deletion Sigyll.Common/Services/CsrGenerationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ public CsrGenerationResult GenerateCsrFromCertificate(X509Certificate2 certifica

/// <summary>
/// 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.
/// </summary>
public static List<SanEntry> ExtractSubjectAltNames(X509Certificate2 certificate)
Expand Down Expand Up @@ -248,6 +248,9 @@ public static List<SanEntry> 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;
}
}
}
Expand Down
116 changes: 116 additions & 0 deletions Sigyll.Common/Services/NpiNumber.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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 <c>80840</c>. In a certificate it is
/// carried as an otherName whose type-id is <c>2.16.840.1.113883.4.6</c> and whose value is a
/// UTF8String holding the ten digits, as the DirectTrust certificate profiles allow for a
/// verified organization or individual covered entity.
/// </summary>
public static class NpiNumber
{
/// <summary>otherName type-id for an NPI (HL7 OID registry: National Provider Identifier).</summary>
public const string OtherNameOid = "2.16.840.1.113883.4.6";

/// <summary>Card-issuer prefix the NPI check digit is computed with.</summary>
private const string LuhnPrefix = "80840";

/// <summary>
/// True when <paramref name="value"/> is exactly ten ASCII digits with a valid check digit.
/// No trimming or separators are accepted; callers trim first.
/// </summary>
public static bool IsValid(string? value) => value is { Length: 10 } && Validate(value) is null;

/// <summary>
/// Returns an error message for an invalid NPI, or null when <paramref name="value"/> is valid.
/// </summary>
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;
}

/// <summary>Builds the otherName GeneralName carrying <paramref name="npi"/>.</summary>
public static GeneralName ToGeneralName(string npi) =>
new(GeneralName.OtherName, new DerSequence(
new DerObjectIdentifier(OtherNameOid),
new DerTaggedObject(true, 0, new DerUtf8String(npi))));

/// <summary>
/// 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.
/// </summary>
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;
}
}

/// <summary>
/// Splits an otherName into its type-id and the (explicitly tagged) value.
/// </summary>
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;
}
}
10 changes: 9 additions & 1 deletion Sigyll.Common/Services/SanExtensionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ public static class SanExtensionBuilder

/// <summary>
/// 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 <see cref="NpiNumber"/>); DNS and email are
/// taken as-is.
/// Returns null when there are no non-empty entries.
/// </summary>
public static X509Extension? Build(IEnumerable<SanEntry> entries, bool critical = false)
Expand Down Expand Up @@ -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;
}
}

Expand Down
109 changes: 109 additions & 0 deletions Sigyll.Common/Services/SubjectAltNameText.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Display text for a Subject Alternative Name extension.
/// </summary>
public static class SubjectAltNameText
{
/// <summary>
/// Describes each name in the SAN extension, one line per name.
///
/// .NET's <c>X509Extension.Format</c> is used as before, except when the extension holds an
/// otherName: the platform formatters render those as hex or "&lt;unsupported&gt;", so the
/// whole extension is described here instead, in the same <c>Type:value</c> form Sigyll
/// stores for certificates it issues (e.g. <c>Npi:1234567893</c>, <c>Dns:example.com</c>).
/// Returns an empty list when the extension cannot be read.
/// </summary>
public static List<string> 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 [];
}
}

/// <summary>
/// Returns the BouncyCastle-decoded description when the extension contains at least one
/// otherName; null otherwise (or when it cannot be decoded).
/// </summary>
private static List<string>? 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<string>();
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}]";
}
}
}
43 changes: 31 additions & 12 deletions Sigyll.Common/Validators/IssuanceValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#endregion

using Sigyll.Common.Data.Entities;
using Sigyll.Common.Services;
using Sigyll.Common.ViewModels;

namespace Sigyll.Common.Validators;
Expand Down Expand Up @@ -42,25 +43,32 @@ public HashSet<int> FindSupersededCaIds(List<CaCertificate> allCas)
}

/// <summary>
/// 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.
/// </summary>
public static List<SanType> 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();

/// <summary>
/// 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.
/// </summary>
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
};

/// <summary>
/// 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
Expand Down Expand Up @@ -89,11 +97,21 @@ public static List<SanType> FindMissingSanTypes(string? subjectAltNameTypes, IEn
/// <summary>
/// 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.
/// </summary>
public string? ValidateSanValues(IEnumerable<SanEntry> 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();

Expand All @@ -119,7 +137,8 @@ public static List<SanType> 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()
};

Expand Down
Loading
Loading