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/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/CertificateIssuanceService.cs b/Sigyll.Common/Services/CertificateIssuanceService.cs index 87475b9..d505d56 100644 --- a/Sigyll.Common/Services/CertificateIssuanceService.cs +++ b/Sigyll.Common/Services/CertificateIssuanceService.cs @@ -20,6 +20,7 @@ using Sigyll.Common.Services.Publishing; using Sigyll.Common.Services.Pqc; using Sigyll.Common.Services.Signing; +using Sigyll.Common.Services.Tefca; using Sigyll.Common.Validators; using Sigyll.Common.ViewModels; @@ -47,8 +48,10 @@ public CertificateIssuanceService( ISigningProvider? signingProvider = null, IssuanceValidator? validator = null, AuditTrail? audit = null, - PublishingPathPolicy? publishingPaths = null) + PublishingPathPolicy? publishingPaths = null, + Microsoft.Extensions.Options.IOptions? tefcaSettings = null) { + _tefcaQueryParameter = tefcaSettings?.Value.ExchangePurposeQueryParameter; _dbFactory = dbFactory; _operator = operatorContext; _logger = logger; @@ -59,6 +62,7 @@ public CertificateIssuanceService( } private readonly PublishingPathPolicy _publishingPaths; + private readonly string? _tefcaQueryParameter; public IssuanceValidator Validator => _validator; @@ -79,9 +83,40 @@ public async Task IssueCertificateAsync(CertificateIs await RecordIssuanceAsync(identity, result.Success, result.EntityType, result.EntityId, result.SerialNumber, request.IssuingCaCertificateId is int issuer ? $"Issued by CA #{issuer}" : "Self-signed", request.SubjectDn, result.Error); + await AttachTefcaConformanceAsync(result, request.ProfileId); return result; } + /// + /// After an end-entity certificate is issued from a TEFCA profile, checks it against the TEFCA FHIR profile and + /// puts the results on . Offline only: CDP/AIA reachability is left to the Explorer. + /// A failed check is logged and reported; it never undoes the issuance. + /// + private async Task AttachTefcaConformanceAsync(CertificateIssuanceResult result, int profileId) + { + if (!result.Success || result.EntityType != "IssuedCertificate" || result.EntityId is not int issuedId) + return; + + try + { + await using var db = await _dbFactory.CreateDbContextAsync(); + var profile = await db.CertificateProfiles.FindAsync(profileId); + if (!TefcaConformanceService.IsTefcaProfile(profile)) + return; + + result.ConformanceResults = await TefcaConformanceService.CheckAsync(db, issuedId, + new TefcaConformanceOptions { ExchangePurposeQueryParameter = _tefcaQueryParameter }); + var failed = result.ConformanceResults?.Where(r => r.Outcome == ConformanceOutcome.Fail).Select(r => r.Name).ToList(); + if (failed is { Count: > 0 }) + _logger.LogWarning("Certificate #{CertificateId} from TEFCA profile '{Profile}' fails TEFCA checks: {Checks}", + issuedId, profile!.Name, string.Join("; ", failed)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "TEFCA conformance check of certificate #{CertificateId} could not run", issuedId); + } + } + private async Task RecordIssuanceAsync(OperatorIdentity identity, bool success, string? entityType, int? entityId, string? serialNumber, string how, string? requestedSubject, string? error) { @@ -129,11 +164,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 +504,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 +544,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); } @@ -509,6 +565,7 @@ public async Task IssueCertificateFromCsrAsync(CsrIssuanceReq var result = await IssueFromCsrAsync(request); await RecordIssuanceAsync(identity, result.Success, result.EntityType, result.EntityId, result.SerialNumber, $"Issued from a CSR by CA #{request.IssuingCaCertificateId}", request.CertificateName, result.Error); + await AttachTefcaConformanceAsync(result, request.ProfileId); return result; } @@ -557,9 +614,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 +1426,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 +1588,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/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/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/Tefca/TefcaConformanceChecker.cs b/Sigyll.Common/Services/Tefca/TefcaConformanceChecker.cs new file mode 100644 index 0000000..ba50161 --- /dev/null +++ b/Sigyll.Common/Services/Tefca/TefcaConformanceChecker.cs @@ -0,0 +1,567 @@ +#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; + +namespace Sigyll.Common.Services.Tefca; + +/// The outcome of one conformance check. +public enum ConformanceOutcome +{ + Pass, + Fail, + + /// Not a failure: the requirement is unsettled or advisory. + Warning, + + /// The check did not run (it does not apply, or it was not asked for). + Skipped, +} + +/// One named check and what it found. +public sealed record ConformanceCheckResult(string Name, ConformanceOutcome Outcome, string Detail) +{ + public static ConformanceCheckResult Pass(string name, string detail) => new(name, ConformanceOutcome.Pass, detail); + public static ConformanceCheckResult Fail(string name, string detail) => new(name, ConformanceOutcome.Fail, detail); + public static ConformanceCheckResult Warning(string name, string detail) => new(name, ConformanceOutcome.Warning, detail); + public static ConformanceCheckResult Skipped(string name, string detail) => new(name, ConformanceOutcome.Skipped, detail); +} + +/// The TEFCA environment a certificate is issued for, which sets its OU and whether policies are required. +public enum TefcaEnvironment +{ + /// OU=RCE-FHIR; the DirectTrust policy OIDs are required. + Production, + + /// OU=RCE-FHIR-TEST. + Validation, +} + +/// +/// Checks whether a URL answers. Injected so the conformance check can confirm CDP/AIA reachability online, and so +/// unit tests never touch the network. +/// +public interface IUrlReachabilityProbe +{ + /// Returns null when answers successfully, otherwise why it did not. + Task ProbeAsync(Uri url, CancellationToken cancellationToken = default); +} + +/// +/// The rule for the exchange purpose carried in a TEFCA client certificate's SAN URI. The SAN form is not settled, +/// so the rule is replaceable; its result should be a warning, never a failure, until the form is published. +/// +public interface ITefcaSanFormatRule +{ + ConformanceCheckResult Evaluate(IReadOnlyList sanUris); +} + +/// +/// Accepts a SAN URI carrying an authorized exchange purpose code in a candidate form: a fragment +/// (#T-TRTMNT), the last path segment (/T-TRTMNT) or, only when a parameter name is configured, a +/// query parameter (?{name}=T-TRTMNT). Anything else, or a parameter repeated with conflicting values, is +/// a warning. The SAN is read as a raw, case-sensitive string with no normalization (HL7 SSRAA 3.0.0). +/// +public sealed class TefcaSanFormatRule : ITefcaSanFormatRule +{ + public const string CheckName = "SAN exchange purpose format"; + + /// + /// The query parameter that carries the exchange purpose, compared case-sensitively; null leaves the query + /// form unrecognized. There is no default because the TEFCA form is not settled. + /// + public TefcaSanFormatRule(string? queryParameterName = null) + { + QueryParameterName = string.IsNullOrEmpty(queryParameterName) ? null : queryParameterName; + } + + /// The configured query parameter name, or null when the query form is not recognized. + public string? QueryParameterName { get; } + + public ConformanceCheckResult Evaluate(IReadOnlyList sanUris) + { + var ambiguous = new List(); + foreach (var uri in sanUris) + { + switch (TefcaExchangePurpose.FromSanUri(uri, QueryParameterName, out var code, out var form)) + { + case TefcaExchangePurpose.Outcome.Found: + return ConformanceCheckResult.Pass(CheckName, + $"'{uri}' carries exchange purpose {code} as a {Describe(form)}. The TEFCA client SAN form is not settled."); + case TefcaExchangePurpose.Outcome.Ambiguous: + ambiguous.Add(uri); + break; + } + } + + if (ambiguous.Count > 0) + return ConformanceCheckResult.Warning(CheckName, + $"Ambiguous: the query parameter '{QueryParameterName}' appears with conflicting values in {string.Join(", ", ambiguous)}."); + + return ConformanceCheckResult.Warning(CheckName, + $"{(sanUris.Count == 0 ? "No SAN URI" : $"None of the SAN URIs ({string.Join(", ", sanUris)})")} carries an " + + $"authorized exchange purpose code as {AcceptedForms()}. The TEFCA client SAN form is not settled."); + } + + private string AcceptedForms() => QueryParameterName == null + ? "a fragment or last path segment (no query parameter is configured)" + : $"a fragment, last path segment or '{QueryParameterName}' query parameter"; + + private string Describe(TefcaExchangePurpose.SanForm form) => form switch + { + TefcaExchangePurpose.SanForm.Fragment => "fragment", + TefcaExchangePurpose.SanForm.PathSegment => "path segment", + _ => $"'{QueryParameterName}' query parameter", + }; +} + +/// Which kind of TEFCA end-entity certificate is being checked. +public enum TefcaCertificateRole +{ + /// Not known (for example an imported certificate); server-only checks warn instead of failing. + Unknown, + Client, + + /// A FHIR server certificate: its URI SANs are FHIR base URLs. + Server, +} + +/// Settings for . +public sealed class TefcaConformanceOptions +{ + /// + /// The environment to check against. Null infers it from the subject OU (RCE-FHIR or RCE-FHIR-TEST); when the OU + /// names neither, the production rules apply. + /// + public TefcaEnvironment? Environment { get; init; } + + /// Client, server or unknown; sets which role-specific checks fail. + public TefcaCertificateRole Role { get; init; } + + /// + /// The query parameter name that carries the exchange purpose in a client SAN URI (for example + /// ?{name}=T-TRTMNT), compared case-sensitively. No default: unset, the query form is not recognized + /// and only the fragment and last-path-segment forms are. Ignored when is set. + /// + public string? ExchangePurposeQueryParameter { get; init; } + + /// + /// The rule for the exchange purpose in the SAN URI. Null uses with + /// . + /// + public ITefcaSanFormatRule? SanFormatRule { get; init; } + + /// When set, every CDP and AIA URL is probed; otherwise the reachability check is skipped. + public IUrlReachabilityProbe? ReachabilityProbe { get; init; } +} + +/// +/// Checks an end-entity certificate against the TEFCA FHIR certificate profile and returns one named result per +/// requirement: the subject OU, a root → intermediate → leaf chain, keyUsage and basicConstraints, SANs and CN, +/// the DirectTrust certificate policies (production), http CDP/AIA (and optionally their reachability), the key, +/// signature algorithm and validity period, and the SAN exchange purpose form (a warning only; skipped for servers). +/// The CN-equals-SAN-URI check applies to every role: for a server certificate the SAN URIs are its FHIR base URLs. +/// +public static class TefcaConformanceChecker +{ + public const string ProductionOu = "RCE-FHIR"; + public const string ValidationOu = "RCE-FHIR-TEST"; + + /// DirectTrust certificate policy OIDs a production TEFCA FHIR certificate must carry. + public static readonly IReadOnlyList ProductionPolicyOids = + [ + "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", + ]; + + public const int MaxCommonNameLength = 64; + public const int MinRsaKeySize = 2048; + public const int MaxValidityYears = 3; + + private const string Sha256WithRsaOid = "1.2.840.113549.1.1.11"; + private const string SanOid = "2.5.29.17"; + private const string CdpOid = "2.5.29.31"; + private const string AiaOid = "1.3.6.1.5.5.7.1.1"; + private const string CaIssuersOid = "1.3.6.1.5.5.7.48.2"; + + /// + /// Runs every check. is the issuing chain, nearest first (intermediate, then root). + /// Reachability is probed only when is set. + /// + public static async Task> CheckAsync( + X509Certificate2 leaf, IReadOnlyList issuers, TefcaConformanceOptions? options = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(leaf); + ArgumentNullException.ThrowIfNull(issuers); + options ??= new TefcaConformanceOptions(); + + var ous = ReadOrganizationalUnits(leaf); + var environment = options.Environment ?? InferEnvironment(ous) ?? TefcaEnvironment.Production; + var sanUris = ReadSanUris(leaf, out var dnsNames); + var cdpUrls = ReadCdpUrls(leaf); + var aiaUrls = ReadAiaUrls(leaf); + + var results = new List + { + CheckOu(ous, options.Environment), + CheckChain(leaf, issuers), + CheckKeyUsage(leaf), + CheckBasicConstraints(leaf), + CheckNoDnsNames(dnsNames), + CheckCommonName(leaf, sanUris), + CheckNoTrailingSlash(sanUris, options.Role), + CheckPolicies(leaf, environment), + CheckHttpUrls("CRL distribution point", cdpUrls), + CheckHttpUrls("AIA caIssuers", aiaUrls), + await CheckReachabilityAsync(cdpUrls.Concat(aiaUrls).ToList(), options.ReachabilityProbe, cancellationToken), + CheckKey(leaf), + CheckSignatureAlgorithm(leaf), + CheckValidity(leaf), + CheckSanFormat(sanUris, options), + }; + + return results; + } + + /// + /// The client exchange purpose form. A server certificate's URI SANs are FHIR base URLs and never carry an + /// exchange purpose, so the check is skipped for a server; for a client or an unknown role the rule decides + /// (a warning at worst). + /// + private static ConformanceCheckResult CheckSanFormat(IReadOnlyList sanUris, TefcaConformanceOptions options) => + options.Role == TefcaCertificateRole.Server + ? ConformanceCheckResult.Skipped(TefcaSanFormatRule.CheckName, + "Server certificate: its URI SANs are FHIR base URLs, which carry no exchange purpose.") + : (options.SanFormatRule ?? new TefcaSanFormatRule(options.ExchangePurposeQueryParameter)).Evaluate(sanUris); + + public const string TrailingSlashCheckName = "Server SAN URIs have no trailing slash"; + + /// + /// A FHIR server certificate's URI SANs are FHIR base URLs, and HL7 SSRAA 3.0.0 says a FHIR base URL SHALL + /// NOT have a trailing slash; URIs compare as case-sensitive strings, so /fhir/ never matches + /// /fhir. Fails for a server certificate, warns when the role is unknown, skipped for a client. + /// + private static ConformanceCheckResult CheckNoTrailingSlash(IReadOnlyList sanUris, TefcaCertificateRole role) + { + if (role == TefcaCertificateRole.Client) + return ConformanceCheckResult.Skipped(TrailingSlashCheckName, "Applies to server certificates (FHIR base URLs)."); + + var slashed = sanUris.Where(u => u.EndsWith('/')).ToList(); + if (slashed.Count == 0) + return ConformanceCheckResult.Pass(TrailingSlashCheckName, sanUris.Count == 0 + ? "The certificate has no URI SANs." + : "No URI SAN ends with '/'."); + + var detail = $"{string.Join(", ", slashed)} ends with '/'. HL7 SSRAA 3.0.0: a FHIR base URL SHALL NOT have a " + + "trailing slash, and URIs are compared as case-sensitive strings with no normalization."; + return role == TefcaCertificateRole.Server + ? ConformanceCheckResult.Fail(TrailingSlashCheckName, detail) + : ConformanceCheckResult.Warning(TrailingSlashCheckName, $"{detail} Fails for a server certificate."); + } + + /// The environment named by the subject OU, or null when it names neither. + public static TefcaEnvironment? InferEnvironment(IReadOnlyList organizationalUnits) => + organizationalUnits.Contains(ProductionOu, StringComparer.Ordinal) ? TefcaEnvironment.Production + : organizationalUnits.Contains(ValidationOu, StringComparer.Ordinal) ? TefcaEnvironment.Validation + : null; + + /// Whether any result failed (warnings and skipped checks do not count). + public static bool HasFailures(IEnumerable results) => + results.Any(r => r.Outcome == ConformanceOutcome.Fail); + + private static ConformanceCheckResult CheckOu(IReadOnlyList ous, TefcaEnvironment? expected) + { + const string name = "Subject OU"; + var shown = ous.Count == 0 ? "none" : string.Join(", ", ous); + + if (expected is TefcaEnvironment env) + { + var want = env == TefcaEnvironment.Production ? ProductionOu : ValidationOu; + return ous.Contains(want, StringComparer.Ordinal) + ? ConformanceCheckResult.Pass(name, $"OU={want} ({env.ToString().ToLowerInvariant()}).") + : ConformanceCheckResult.Fail(name, $"Expected OU={want} for {env.ToString().ToLowerInvariant()}; found {shown}."); + } + + return InferEnvironment(ous) switch + { + TefcaEnvironment.Production => ConformanceCheckResult.Pass(name, $"OU={ProductionOu} (production)."), + TefcaEnvironment.Validation => ConformanceCheckResult.Pass(name, $"OU={ValidationOu} (validation)."), + _ => ConformanceCheckResult.Fail(name, + $"Expected OU={ProductionOu} (production) or OU={ValidationOu} (validation); found {shown}."), + }; + } + + private static ConformanceCheckResult CheckChain(X509Certificate2 leaf, IReadOnlyList issuers) + { + const string name = "Chain root → intermediate → leaf"; + if (issuers.Count != 2) + return ConformanceCheckResult.Fail(name, + $"Expected exactly one intermediate and a root above the leaf (3 certificates); found {issuers.Count + 1}."); + + var intermediate = issuers[0]; + var root = issuers[1]; + + if (!IsCa(intermediate)) + return ConformanceCheckResult.Fail(name, $"The issuer '{intermediate.Subject}' is not a CA."); + if (!IsCa(root)) + return ConformanceCheckResult.Fail(name, $"The root '{root.Subject}' is not a CA."); + if (!root.SubjectName.RawData.AsSpan().SequenceEqual(root.IssuerName.RawData)) + return ConformanceCheckResult.Fail(name, $"The top certificate '{root.Subject}' is not self-signed, so it is not a root."); + if (intermediate.SubjectName.RawData.AsSpan().SequenceEqual(intermediate.IssuerName.RawData)) + return ConformanceCheckResult.Fail(name, $"The issuer '{intermediate.Subject}' is self-signed; the leaf must be issued by an intermediate."); + + var leafError = CertificateIssuanceService.VerifyIssuedBy(leaf, intermediate); + if (leafError != null) + return ConformanceCheckResult.Fail(name, $"Leaf → intermediate: {leafError}"); + var intermediateError = CertificateIssuanceService.VerifyIssuedBy(intermediate, root); + if (intermediateError != null) + return ConformanceCheckResult.Fail(name, $"Intermediate → root: {intermediateError}"); + + return ConformanceCheckResult.Pass(name, $"{root.GetNameInfo(X509NameType.SimpleName, false)} → " + + $"{intermediate.GetNameInfo(X509NameType.SimpleName, false)} → {leaf.GetNameInfo(X509NameType.SimpleName, false)}."); + } + + private static ConformanceCheckResult CheckKeyUsage(X509Certificate2 leaf) + { + const string name = "keyUsage digitalSignature only, critical"; + if (leaf.Extensions["2.5.29.15"] is not X509KeyUsageExtension ku) + return ConformanceCheckResult.Fail(name, "The keyUsage extension is missing."); + + var problems = new List(); + if (ku.KeyUsages != X509KeyUsageFlags.DigitalSignature) + problems.Add($"key usages are {ku.KeyUsages}"); + if (!ku.Critical) + problems.Add("the extension is not critical"); + + return problems.Count == 0 + ? ConformanceCheckResult.Pass(name, "digitalSignature, critical.") + : ConformanceCheckResult.Fail(name, $"Expected only digitalSignature, critical; {string.Join(" and ", problems)}."); + } + + private static ConformanceCheckResult CheckBasicConstraints(X509Certificate2 leaf) + { + const string name = "basicConstraints cA=false, critical"; + if (leaf.Extensions["2.5.29.19"] is not X509BasicConstraintsExtension bc) + return ConformanceCheckResult.Fail(name, "The basicConstraints extension is missing."); + + var problems = new List(); + if (bc.CertificateAuthority) + problems.Add("cA is true"); + if (!bc.Critical) + problems.Add("the extension is not critical"); + + return problems.Count == 0 + ? ConformanceCheckResult.Pass(name, "cA=false, critical.") + : ConformanceCheckResult.Fail(name, $"Expected cA=false, critical; {string.Join(" and ", problems)}."); + } + + private static ConformanceCheckResult CheckNoDnsNames(IReadOnlyList dnsNames) + { + const string name = "No dNSName SANs"; + return dnsNames.Count == 0 + ? ConformanceCheckResult.Pass(name, "The certificate has no dNSName SANs.") + : ConformanceCheckResult.Fail(name, $"dNSName SANs are not allowed; found {string.Join(", ", dnsNames)}."); + } + + private static ConformanceCheckResult CheckCommonName(X509Certificate2 leaf, IReadOnlyList sanUris) + { + const string name = "CN ≤ 64 characters and equal to a SAN URI"; + var cn = ReadAttribute(leaf, "2.5.4.3").FirstOrDefault(); + if (string.IsNullOrEmpty(cn)) + return ConformanceCheckResult.Fail(name, "The subject has no CN."); + + var problems = new List(); + if (cn.Length > MaxCommonNameLength) + problems.Add($"the CN is {cn.Length} characters"); + // Ordinal and untrimmed: URIs compare as case-sensitive strings with no normalization (HL7 SSRAA 3.0.0). + if (!sanUris.Contains(cn, StringComparer.Ordinal)) + problems.Add(sanUris.Count == 0 ? "there are no SAN URIs" : "no SAN URI equals the CN"); + + return problems.Count == 0 + ? ConformanceCheckResult.Pass(name, $"CN '{cn}' ({cn.Length} characters) matches a SAN URI.") + : ConformanceCheckResult.Fail(name, $"CN '{cn}': {string.Join(" and ", problems)}."); + } + + private static ConformanceCheckResult CheckPolicies(X509Certificate2 leaf, TefcaEnvironment environment) + { + const string name = "DirectTrust certificate policies"; + IReadOnlyList present; + try + { + present = CertificatePolicyExtension.Read(leaf); + } + catch (System.Formats.Asn1.AsnContentException ex) + { + return ConformanceCheckResult.Fail(name, $"The certificatePolicies extension cannot be read: {ex.Message}"); + } + + if (environment != TefcaEnvironment.Production) + return ConformanceCheckResult.Skipped(name, "Required for production certificates only."); + + var missing = ProductionPolicyOids.Where(oid => !present.Contains(oid, StringComparer.Ordinal)).ToList(); + return missing.Count == 0 + ? ConformanceCheckResult.Pass(name, $"Carries {string.Join(", ", ProductionPolicyOids)}.") + : ConformanceCheckResult.Fail(name, $"Missing {string.Join(", ", missing)}."); + } + + private static ConformanceCheckResult CheckHttpUrls(string what, IReadOnlyList urls) + { + var name = $"{what} uses http"; + if (urls.Count == 0) + return ConformanceCheckResult.Fail(name, $"The certificate has no {what} URL."); + + var notHttp = urls.Where(u => !u.StartsWith("http://", StringComparison.OrdinalIgnoreCase)).ToList(); + return notHttp.Count == 0 + ? ConformanceCheckResult.Pass(name, string.Join(", ", urls)) + : ConformanceCheckResult.Fail(name, $"Not plain http: {string.Join(", ", notHttp)}."); + } + + private static async Task CheckReachabilityAsync( + IReadOnlyList urls, IUrlReachabilityProbe? probe, CancellationToken cancellationToken) + { + const string name = "CDP/AIA reachable"; + if (probe == null) + return ConformanceCheckResult.Skipped(name, "Not checked; run the check online to probe the URLs."); + if (urls.Count == 0) + return ConformanceCheckResult.Skipped(name, "There are no CDP or AIA URLs to probe."); + + var failures = new List(); + foreach (var url in urls.Distinct(StringComparer.Ordinal)) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + failures.Add($"{url}: not an absolute URL"); + continue; + } + + var error = await probe.ProbeAsync(uri, cancellationToken); + if (error != null) + failures.Add($"{url}: {error}"); + } + + return failures.Count == 0 + ? ConformanceCheckResult.Pass(name, $"All {urls.Distinct(StringComparer.Ordinal).Count()} URL(s) answered.") + : ConformanceCheckResult.Fail(name, string.Join("; ", failures)); + } + + private static ConformanceCheckResult CheckKey(X509Certificate2 leaf) + { + const string name = "RSA key ≥ 2048 bits"; + using var rsa = leaf.GetRSAPublicKey(); + if (rsa == null) + return ConformanceCheckResult.Fail(name, $"The key is not RSA ({leaf.PublicKey.Oid.FriendlyName ?? leaf.PublicKey.Oid.Value})."); + + return rsa.KeySize >= MinRsaKeySize + ? ConformanceCheckResult.Pass(name, $"RSA {rsa.KeySize}.") + : ConformanceCheckResult.Fail(name, $"RSA {rsa.KeySize} is shorter than {MinRsaKeySize} bits."); + } + + private static ConformanceCheckResult CheckSignatureAlgorithm(X509Certificate2 leaf) + { + const string name = "Signature SHA-256 with RSA"; + return leaf.SignatureAlgorithm.Value == Sha256WithRsaOid + ? ConformanceCheckResult.Pass(name, "sha256WithRSAEncryption.") + : ConformanceCheckResult.Fail(name, + $"Signed with {leaf.SignatureAlgorithm.FriendlyName ?? leaf.SignatureAlgorithm.Value}; expected sha256WithRSAEncryption."); + } + + private static ConformanceCheckResult CheckValidity(X509Certificate2 leaf) + { + const string name = "Validity ≤ 3 years"; + var notBefore = leaf.NotBefore.ToUniversalTime(); + var notAfter = leaf.NotAfter.ToUniversalTime(); + var days = (notAfter - notBefore).TotalDays; + + return notAfter <= notBefore.AddYears(MaxValidityYears) + ? ConformanceCheckResult.Pass(name, $"{days:0} days.") + : ConformanceCheckResult.Fail(name, $"{days:0} days is longer than {MaxValidityYears} years."); + } + + private static bool IsCa(X509Certificate2 cert) => + cert.Extensions["2.5.29.19"] is X509BasicConstraintsExtension { CertificateAuthority: true }; + + internal static IReadOnlyList ReadOrganizationalUnits(X509Certificate2 cert) => ReadAttribute(cert, "2.5.4.11"); + + private static IReadOnlyList ReadAttribute(X509Certificate2 cert, string attributeOid) + { + var values = new List(); + foreach (var rdn in cert.SubjectName.EnumerateRelativeDistinguishedNames()) + { + if (!rdn.HasMultipleElements && rdn.GetSingleElementType().Value == attributeOid + && rdn.GetSingleElementValue() is { } value) + values.Add(value); + } + + return values; + } + + internal static IReadOnlyList ReadSanUris(X509Certificate2 cert, out IReadOnlyList dnsNames) + { + var uris = new List(); + var dns = new List(); + dnsNames = dns; + + var ext = cert.Extensions[SanOid]; + if (ext == null) + return uris; + + foreach (var gn in GeneralNames.GetInstance(Asn1Object.FromByteArray(ext.RawData)).GetNames()) + { + if (gn.TagNo == GeneralName.UniformResourceIdentifier) + uris.Add(gn.Name.ToString()!); + else if (gn.TagNo == GeneralName.DnsName) + dns.Add(gn.Name.ToString()!); + } + + return uris; + } + + internal static IReadOnlyList ReadCdpUrls(X509Certificate2 cert) + { + var urls = new List(); + var ext = cert.Extensions[CdpOid]; + if (ext == null) + return urls; + + foreach (var dp in CrlDistPoint.GetInstance(Asn1Object.FromByteArray(ext.RawData)).GetDistributionPoints()) + { + if (dp.DistributionPointName?.Type != DistributionPointName.FullName) + continue; + foreach (var gn in GeneralNames.GetInstance(dp.DistributionPointName.Name).GetNames()) + { + if (gn.TagNo == GeneralName.UniformResourceIdentifier) + urls.Add(gn.Name.ToString()!); + } + } + + return urls; + } + + internal static IReadOnlyList ReadAiaUrls(X509Certificate2 cert) + { + var urls = new List(); + var ext = cert.Extensions[AiaOid]; + if (ext == null) + return urls; + + foreach (var ad in AuthorityInformationAccess.GetInstance(Asn1Object.FromByteArray(ext.RawData)).GetAccessDescriptions()) + { + if (ad.AccessMethod.Id == CaIssuersOid && ad.AccessLocation.TagNo == GeneralName.UniformResourceIdentifier) + urls.Add(ad.AccessLocation.Name.ToString()!); + } + + return urls; + } +} diff --git a/Sigyll.Common/Services/Tefca/TefcaConformanceService.cs b/Sigyll.Common/Services/Tefca/TefcaConformanceService.cs new file mode 100644 index 0000000..21a5227 --- /dev/null +++ b/Sigyll.Common/Services/Tefca/TefcaConformanceService.cs @@ -0,0 +1,183 @@ +#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 Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Sigyll.Common.Data; +using Sigyll.Common.Data.Entities; +using Sigyll.Common.Security; + +namespace Sigyll.Common.Services.Tefca; + +/// Configuration for the TEFCA conformance check (configuration section TefcaConformance). +public sealed class TefcaConformanceSettings +{ + public const string SectionName = "TefcaConformance"; + + /// + /// The query parameter name that carries the exchange purpose in a client SAN URI (?{name}=T-TRTMNT), + /// compared case-sensitively. No default: unset, only the fragment and last-path-segment forms are recognized. + /// + public string? ExchangePurposeQueryParameter { get; set; } +} + +/// +/// Runs on a certificate stored in Sigyll: an end-entity certificate issued here +/// or imported, with its issuing chain taken from the stored CAs. +/// +public class TefcaConformanceService +{ + private readonly IDbContextFactory _dbFactory; + private readonly IOperatorContext _operator; + private readonly IUrlReachabilityProbe? _probe; + private readonly string? _queryParameter; + + public TefcaConformanceService( + IDbContextFactory dbFactory, + IOperatorContext operatorContext, + IUrlReachabilityProbe? probe = null, + IOptions? settings = null) + { + _dbFactory = dbFactory; + _operator = operatorContext; + _probe = probe; + _queryParameter = settings?.Value.ExchangePurposeQueryParameter; + } + + /// Whether CDP/AIA reachability can be probed (a probe is configured). + public bool CanProbeReachability => _probe != null; + + /// + /// Whether issues TEFCA certificates, so its certificates are checked after + /// issuance. A profile is TEFCA when its name contains "TEFCA" (any case). + /// + public static bool IsTefcaProfile(CertificateProfile? profile) => + profile?.Name?.Contains("TEFCA", StringComparison.OrdinalIgnoreCase) == true; + + /// + /// Checks the stored end-entity certificate . With + /// and a configured probe, every CDP and AIA URL is fetched. + /// Returns null when the certificate is not found. + /// + public async Task?> CheckIssuedCertificateAsync( + int issuedCertificateId, bool probeReachability = false, CancellationToken cancellationToken = default) + { + await _operator.DemandAsync(Permission.View); + + await using var db = await _dbFactory.CreateDbContextAsync(cancellationToken); + return await CheckAsync(db, issuedCertificateId, + new TefcaConformanceOptions + { + ReachabilityProbe = probeReachability ? _probe : null, + ExchangePurposeQueryParameter = _queryParameter, + }, cancellationToken); + } + + /// The role a profile's certificate type implies: client, server, or unknown for no profile. + public static TefcaCertificateRole RoleOf(CertificateType? type) => type switch + { + CertificateType.EndEntityClient => TefcaCertificateRole.Client, + CertificateType.EndEntityServer => TefcaCertificateRole.Server, + _ => TefcaCertificateRole.Unknown, + }; + + /// + /// Loads the end-entity certificate and its stored issuing chain (nearest first) and checks it. Used by + /// issuance, which has already checked the operator. Returns null when the certificate is not found. + /// + internal static async Task?> CheckAsync( + SigyllDbContext db, int issuedCertificateId, TefcaConformanceOptions options, CancellationToken cancellationToken = default) + { + var issued = await db.IssuedCertificates.AsNoTracking() + .Where(c => c.Id == issuedCertificateId) + .Select(c => new + { + c.X509CertificatePem, + c.IssuingCaCertificateId, + ProfileType = c.Profile == null ? (CertificateType?)null : c.Profile.CertificateType, + }) + .FirstOrDefaultAsync(cancellationToken); + if (issued == null) + return null; + + if (options.Role == TefcaCertificateRole.Unknown) + options = new TefcaConformanceOptions + { + Environment = options.Environment, + Role = RoleOf(issued.ProfileType), + ExchangePurposeQueryParameter = options.ExchangePurposeQueryParameter, + SanFormatRule = options.SanFormatRule, + ReachabilityProbe = options.ReachabilityProbe, + }; + + using var leaf = X509Certificate2.CreateFromPem(issued.X509CertificatePem); + var issuers = new List(); + try + { + int? nextId = issued.IssuingCaCertificateId; + var seen = new HashSet(); + while (nextId is int id && seen.Add(id) && seen.Count <= 16) + { + var ca = await db.CaCertificates.AsNoTracking() + .Where(c => c.Id == id) + .Select(c => new { c.X509CertificatePem, c.ParentId }) + .FirstOrDefaultAsync(cancellationToken); + if (ca == null) + break; + issuers.Add(X509Certificate2.CreateFromPem(ca.X509CertificatePem)); + nextId = ca.ParentId; + } + + return await TefcaConformanceChecker.CheckAsync(leaf, issuers, options, cancellationToken); + } + finally + { + foreach (var issuer in issuers) + issuer.Dispose(); + } + } +} + +/// +/// Probes a CDP or AIA URL with an HTTP GET through a named client. +/// +public sealed class HttpUrlReachabilityProbe : IUrlReachabilityProbe +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private readonly IHttpClientFactory _httpClientFactory; + private readonly string _clientName; + + public HttpUrlReachabilityProbe(IHttpClientFactory httpClientFactory, string clientName = "SigyllCrl") + { + _httpClientFactory = httpClientFactory; + _clientName = clientName; + } + + public async Task ProbeAsync(Uri url, CancellationToken cancellationToken = default) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(Timeout); + try + { + var client = _httpClientFactory.CreateClient(_clientName); + using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token); + return response.IsSuccessStatusCode ? null : $"HTTP {(int)response.StatusCode} {response.ReasonPhrase}"; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return $"no answer within {Timeout.TotalSeconds:0} seconds"; + } + catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException) + { + return ex.Message; + } + } +} diff --git a/Sigyll.Common/Services/Tefca/TefcaExchangePurpose.cs b/Sigyll.Common/Services/Tefca/TefcaExchangePurpose.cs new file mode 100644 index 0000000..8aea692 --- /dev/null +++ b/Sigyll.Common/Services/Tefca/TefcaExchangePurpose.cs @@ -0,0 +1,121 @@ +#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 + +namespace Sigyll.Common.Services.Tefca; + +/// +/// TEFCA Exchange Purpose (XP) codes and the ways a client certificate's SAN URI may carry one. Kept internal: the +/// SAN form for TEFCA client certificates is not settled, so this is a conformance aid, not an API. +/// +/// +/// URIs follow the HL7 SSRAA 3.0.0 rules: a SAN is compared as a case-sensitive string with no normalization. The +/// raw SAN text is split on its delimiters only; nothing is percent-decoded, case-folded or trimmed, and an XP +/// code must match exactly. +/// +internal static class TefcaExchangePurpose +{ + /// The OID of the TEFCA Exchange Purpose code system. + public const string CodeSystemOid = "2.16.840.1.113883.3.7204.1.5.2.1"; + + /// The authorized XP codes (Exchange Purposes (XPs) SOP v5.1, Table 1). + public static readonly IReadOnlySet Codes = new HashSet(StringComparer.Ordinal) + { + "T-TREAT", "T-TRTMNT", "T-PYMNT", + "T-HCO", "T-HCO-CC", "T-HCO-HED", "T-HCO-QAI", "T-HCO-POP", "T-HCO-PTSAFETY", "T-HCO-PERF", + "T-PH", "T-PH-ECR", "T-PH-ELR", + "T-IAS", + "T-GOVDTRM", "T-GOVDTRM-SSD", "T-GOVDTRM-ACP", + }; + + /// Where in a SAN URI an exchange purpose code was found. + public enum SanForm + { + /// ...#T-TRTMNT + Fragment, + + /// .../T-TRTMNT (the last path segment) + PathSegment, + + /// ...?{name}=T-TRTMNT, where {name} is configured + Query, + } + + /// What a SAN URI says about its exchange purpose. + public enum Outcome + { + Found, + NotFound, + + /// The configured query parameter appears more than once with different values. + Ambiguous, + } + + /// + /// Looks for an authorized XP code in the raw : the fragment, then a query parameter + /// named (only when one is configured), then the last path segment. + /// The parameter name compares ordinally and values are taken verbatim. + /// + public static Outcome FromSanUri(string? sanUri, string? queryParameterName, out string code, out SanForm form) + { + code = string.Empty; + form = default; + if (string.IsNullOrEmpty(sanUri)) + return Outcome.NotFound; + + // Split the raw text: fragment after the first '#', query after the first '?' before it, path before that. + var hash = sanUri.IndexOf('#'); + var fragment = hash >= 0 ? sanUri[(hash + 1)..] : null; + var beforeFragment = hash >= 0 ? sanUri[..hash] : sanUri; + var question = beforeFragment.IndexOf('?'); + var query = question >= 0 ? beforeFragment[(question + 1)..] : null; + var path = question >= 0 ? beforeFragment[..question] : beforeFragment; + + // Values of the configured query parameter, taken verbatim. Conflicting duplicates make the SAN ambiguous, + // whatever else it carries. + var values = new List(); + if (query != null && !string.IsNullOrEmpty(queryParameterName)) + { + foreach (var pair in query.Split('&')) + { + var equals = pair.IndexOf('='); + if (equals > 0 && string.Equals(pair[..equals], queryParameterName, StringComparison.Ordinal) + && !values.Contains(pair[(equals + 1)..], StringComparer.Ordinal)) + values.Add(pair[(equals + 1)..]); + } + } + + if (values.Count > 1) + return Outcome.Ambiguous; + + if (fragment != null && Codes.Contains(fragment)) + { + code = fragment; + form = SanForm.Fragment; + return Outcome.Found; + } + + if (values.Count == 1 && Codes.Contains(values[0])) + { + code = values[0]; + form = SanForm.Query; + return Outcome.Found; + } + + var slash = path.LastIndexOf('/'); + if (slash >= 0 && slash < path.Length - 1 && Codes.Contains(path[(slash + 1)..])) + { + code = path[(slash + 1)..]; + form = SanForm.PathSegment; + return Outcome.Found; + } + + return Outcome.NotFound; + } +} diff --git a/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs b/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs index ad97625..43da024 100644 --- a/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs +++ b/Sigyll.Common/ViewModels/CertificateIssuanceRequest.cs @@ -165,6 +165,13 @@ public class CertificateIssuanceResult public string? Thumbprint { get; set; } public string? SerialNumber { get; set; } + /// + /// The TEFCA conformance check of an end-entity certificate issued from a TEFCA profile (see + /// ); null for other issuances. Failures + /// are reported, not enforced: the certificate is issued either way. + /// + public IReadOnlyList? ConformanceResults { get; set; } + public static CertificateIssuanceResult Failure(string error) => new() { Success = false, Error = error }; } diff --git a/Sigyll.UI/Components/Pages/CertificateExplorer.Tefca.cs b/Sigyll.UI/Components/Pages/CertificateExplorer.Tefca.cs new file mode 100644 index 0000000..4b7187c --- /dev/null +++ b/Sigyll.UI/Components/Pages/CertificateExplorer.Tefca.cs @@ -0,0 +1,83 @@ +#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 Microsoft.AspNetCore.Components; +using Microsoft.FluentUI.AspNetCore.Components; +using Sigyll.Common.Services.Tefca; +using Sigyll.UI.Services; + +namespace Sigyll.UI.Components.Pages; + +/// TEFCA conformance check of the selected end-entity certificate, on demand. +public partial class CertificateExplorer +{ + [Inject] private TefcaConformanceService TefcaConformance { get; set; } = null!; + + private IReadOnlyList? tefcaResults; + private bool tefcaResultsOnline; + private bool isCheckingTefca; + + private bool SelectedIsEndEntity => selectedNode?.EntityType == "IssuedCertificate"; + + private async Task RunTefcaCheckAsync(bool online) + { + if (selectedNode == null || !SelectedIsEndEntity) return; + + isCheckingTefca = true; + StateHasChanged(); + try + { + tefcaResults = await TefcaConformance.CheckIssuedCertificateAsync(selectedNode.Id, probeReachability: online); + tefcaResultsOnline = online && TefcaConformance.CanProbeReachability; + if (tefcaResults == null) + ToastService.ShowCopyableError("The certificate was not found."); + } + catch (Exception ex) + { + ToastService.ShowCopyableError($"TEFCA check failed: {ex.Message}"); + } + finally + { + isCheckingTefca = false; + StateHasChanged(); + } + } + + /// After issuance from a TEFCA profile: a toast summarizing the automatic check. + private void ReportTefcaConformance(IReadOnlyList? results) + { + if (results == null) return; + + var failed = results.Where(r => r.Outcome == ConformanceOutcome.Fail).Select(r => r.Name).ToList(); + var warned = results.Count(r => r.Outcome == ConformanceOutcome.Warning); + if (failed.Count > 0) + ToastService.ShowWarning($"TEFCA check: {failed.Count} failed ({string.Join("; ", failed)}). Select the certificate and run TEFCA Check for details."); + else + ToastService.ShowSuccess($"TEFCA check passed{(warned > 0 ? $" with {warned} warning(s)" : "")}."); + } + + private static string TefcaColor(ConformanceOutcome outcome) => outcome switch + { + ConformanceOutcome.Pass => "#4caf50", + ConformanceOutcome.Fail => "#e94560", + ConformanceOutcome.Warning => "#ff9800", + _ => "#666", + }; + + private string TefcaHeading() + { + if (tefcaResults == null) return "TEFCA Conformance"; + var failed = tefcaResults.Count(r => r.Outcome == ConformanceOutcome.Fail); + var warned = tefcaResults.Count(r => r.Outcome == ConformanceOutcome.Warning); + var summary = failed > 0 ? $"{failed} failed" : "passed"; + if (warned > 0) summary += $", {warned} warning(s)"; + return $"TEFCA Conformance ({summary})"; + } +} diff --git a/Sigyll.UI/Components/Pages/CertificateExplorer.razor b/Sigyll.UI/Components/Pages/CertificateExplorer.razor index 87c69cb..a972567 100644 --- a/Sigyll.UI/Components/Pages/CertificateExplorer.razor +++ b/Sigyll.UI/Components/Pages/CertificateExplorer.razor @@ -1375,6 +1375,43 @@ else if (treeNodes.Count > 0) } + @if (SelectedIsEndEntity) + { + + + + + @(isCheckingTefca ? "Checking..." : "TEFCA Check") + + + + Check Online + + + @if (tefcaResults != null) + { +
+ @(tefcaResultsOnline ? "CDP and AIA URLs were fetched." : "Offline check: CDP and AIA URLs were not fetched.") + The SAN exchange purpose form is not settled, so it is reported as a warning only. +
+ @foreach (var check in tefcaResults) + { +
+ + @check.Outcome + @check.Name + +
@check.Detail
+
+ } + } +
+ } + @if (chainValidation != null) { diff --git a/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs b/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs index 019d425..d1bbcb8 100644 --- a/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs +++ b/Sigyll.UI/Components/Pages/CertificateExplorer.razor.cs @@ -543,6 +543,7 @@ private async Task LoadTrustDomainTreeAsync(int trustDomainId) selectedCert = null; selectedCrl = null; chainValidation = null; + tefcaResults = null; asn1Root = null; subjectAltNames.Clear(); isLoadingTree = false; @@ -682,6 +683,7 @@ private async Task SelectNode(CertificateChainNodeViewModel node) selectedNodeVersion = 1; selectedNodeRenewalOfName = null; chainValidation = null; + tefcaResults = null; asn1Root = null; subjectAltNames.Clear(); CloseIssuerDetails(); @@ -1598,6 +1600,7 @@ private async Task ClearSelectionAndReloadTreeAsync() selectedCert = null; selectedCrl = null; chainValidation = null; + tefcaResults = null; asn1Root = null; CloseIssuerDetails(); @@ -2655,6 +2658,7 @@ private async Task IssueCertificateAsync() issuanceDialogHidden = true; ToastService.ShowCopyableSuccess($"Certificate issued: {result.Thumbprint}"); + ReportTefcaConformance(result.ConformanceResults); await LoadTrustDomainTreeAsync(TrustDomainId); } else diff --git a/Sigyll.UI/Components/Pages/CertificateProfiles.razor b/Sigyll.UI/Components/Pages/CertificateProfiles.razor index 7b27e4a..e3782ac 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. +
+ } +
@@ -213,7 +228,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..3b5f7de 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; @@ -146,6 +148,8 @@ private void ResetForm() editCustomEkuOids = string.Empty; editSelectedEkuOids.Clear(); editIsEkuCritical = false; + editCertificatePolicyOids = string.Empty; + certificatePolicyError = null; editIsBasicConstraintsCa = false; editIsBasicConstraintsCritical = true; editPathLengthConstraint = null; @@ -208,6 +212,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; @@ -259,6 +265,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; @@ -278,9 +285,19 @@ private CertificateProfile BuildEntityFromForm(CertificateProfile? existing = nu 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 +335,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/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..69b285c 100644 --- a/Sigyll/Program.cs +++ b/Sigyll/Program.cs @@ -91,6 +91,11 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddSingleton(sp => + new Sigyll.Common.Services.Tefca.HttpUrlReachabilityProbe(sp.GetRequiredService())); + builder.Services.Configure( + builder.Configuration.GetSection(Sigyll.Common.Services.Tefca.TefcaConformanceSettings.SectionName)); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); 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/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/TefcaConformanceTests.cs b/_tests/Sigyll.Signing.Tests/TefcaConformanceTests.cs new file mode 100644 index 0000000..7620b11 --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/TefcaConformanceTests.cs @@ -0,0 +1,683 @@ +#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.Services.Tefca; +using Sigyll.Common.ViewModels; +using Xunit; + +namespace Sigyll.Signing.Tests; + +public class TefcaConformanceTests +{ + private const string ClientUri = "https://client.example.org/fhir#T-TRTMNT"; + private const string Cdp = "http://crl.example.org/intermediate.crl"; + private const string Aia = "http://crl.example.org/intermediate.cer"; + + // ---- the checker ---- + + [Fact] + public async Task ConformingProductionCertificate_PassesEveryCheck() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec()); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers); + + results.Where(r => r.Outcome != ConformanceOutcome.Pass) + .ShouldAllBe(r => r.Name == "CDP/AIA reachable" && r.Outcome == ConformanceOutcome.Skipped); + TefcaConformanceChecker.HasFailures(results).ShouldBeFalse(); + results.Select(r => r.Name).ShouldBeUnique(); + results.Count.ShouldBe(15); + } + + [Fact] + public async Task ValidationOu_SkipsPolicies() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Ou = "RCE-FHIR-TEST", Policies = [] }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers); + + Result(results, "Subject OU").Outcome.ShouldBe(ConformanceOutcome.Pass); + Result(results, "DirectTrust certificate policies").Outcome.ShouldBe(ConformanceOutcome.Skipped); + TefcaConformanceChecker.HasFailures(results).ShouldBeFalse(); + } + + [Fact] + public async Task UnknownOu_Fails_AndPoliciesAreCheckedAsProduction() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Ou = "Engineering", Policies = [] }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers); + + Result(results, "Subject OU").Outcome.ShouldBe(ConformanceOutcome.Fail); + Result(results, "DirectTrust certificate policies").Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Fact] + public async Task ExplicitEnvironment_MustMatchOu() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Ou = "RCE-FHIR-TEST" }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { Environment = TefcaEnvironment.Production }); + + Result(results, "Subject OU").Detail.ShouldContain("RCE-FHIR for production"); + Result(results, "Subject OU").Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Fact] + public async Task MissingPolicy_IsNamed() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Policies = ["1.3.6.1.4.1.41179.0.2", "1.3.6.1.4.1.41179.1.5"] }); + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), "DirectTrust certificate policies"); + + result.Outcome.ShouldBe(ConformanceOutcome.Fail); + result.Detail.ShouldBe("Missing 1.3.6.1.4.1.41179.3.1."); + } + + [Fact] + public async Task LeafIssuedDirectlyByRoot_FailsChain() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec(), byRoot: true); + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, [chain.Root]), "Chain root → intermediate → leaf"); + + result.Outcome.ShouldBe(ConformanceOutcome.Fail); + result.Detail.ShouldContain("found 2"); + } + + [Fact] + public async Task ChainOutOfOrder_Fails() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec()); + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, [chain.Root, chain.Intermediate]), + "Chain root → intermediate → leaf"); + + result.Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Fact] + public async Task KeyUsage_MustBeDigitalSignatureOnly_AndCritical() + { + using var chain = TestChain.Create(); + using var extra = chain.IssueLeaf(new LeafSpec { KeyUsage = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment }); + using var notCritical = chain.IssueLeaf(new LeafSpec { KeyUsageCritical = false }); + + Result(await TefcaConformanceChecker.CheckAsync(extra, chain.Issuers), "keyUsage digitalSignature only, critical") + .Outcome.ShouldBe(ConformanceOutcome.Fail); + Result(await TefcaConformanceChecker.CheckAsync(notCritical, chain.Issuers), "keyUsage digitalSignature only, critical") + .Detail.ShouldContain("not critical"); + } + + [Fact] + public async Task BasicConstraints_MustBeCritical_AndPresent() + { + using var chain = TestChain.Create(); + using var notCritical = chain.IssueLeaf(new LeafSpec { BasicConstraints = BasicConstraintsSpec.NotCritical }); + using var missing = chain.IssueLeaf(new LeafSpec { BasicConstraints = BasicConstraintsSpec.Missing }); + + Result(await TefcaConformanceChecker.CheckAsync(notCritical, chain.Issuers), "basicConstraints cA=false, critical") + .Outcome.ShouldBe(ConformanceOutcome.Fail); + Result(await TefcaConformanceChecker.CheckAsync(missing, chain.Issuers), "basicConstraints cA=false, critical") + .Detail.ShouldContain("missing"); + } + + [Fact] + public async Task DnsNameSan_Fails() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { DnsName = "client.example.org" }); + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), "No dNSName SANs"); + + result.Outcome.ShouldBe(ConformanceOutcome.Fail); + result.Detail.ShouldContain("client.example.org"); + } + + [Fact] + public async Task CommonName_MustEqualASanUri_AndBeAtMost64Characters() + { + using var chain = TestChain.Create(); + using var mismatch = chain.IssueLeaf(new LeafSpec { Cn = "Example Client" }); + var longUri = "https://client.example.org/" + new string('a', 60) + "#T-TRTMNT"; + using var tooLong = chain.IssueLeaf(new LeafSpec { Cn = longUri, SanUri = longUri }); + + Result(await TefcaConformanceChecker.CheckAsync(mismatch, chain.Issuers), "CN ≤ 64 characters and equal to a SAN URI") + .Detail.ShouldContain("no SAN URI equals the CN"); + Result(await TefcaConformanceChecker.CheckAsync(tooLong, chain.Issuers), "CN ≤ 64 characters and equal to a SAN URI") + .Detail.ShouldContain($"the CN is {longUri.Length} characters"); + } + + [Fact] + public async Task CdpAndAia_MustBePresent_AndPlainHttp() + { + using var chain = TestChain.Create(); + using var https = chain.IssueLeaf(new LeafSpec { Cdp = "https://crl.example.org/i.crl" }); + using var noAia = chain.IssueLeaf(new LeafSpec { Aia = null }); + + Result(await TefcaConformanceChecker.CheckAsync(https, chain.Issuers), "CRL distribution point uses http") + .Outcome.ShouldBe(ConformanceOutcome.Fail); + Result(await TefcaConformanceChecker.CheckAsync(noAia, chain.Issuers), "AIA caIssuers uses http") + .Detail.ShouldContain("no AIA caIssuers URL"); + } + + [Fact] + public async Task Reachability_UsesTheInjectedProbe() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec()); + var probe = new FakeProbe { Unreachable = { Aia } }; + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { ReachabilityProbe = probe }), "CDP/AIA reachable"); + + probe.Probed.ShouldBe([Cdp, Aia]); + result.Outcome.ShouldBe(ConformanceOutcome.Fail); + result.Detail.ShouldBe($"{Aia}: HTTP 404"); + + probe.Unreachable.Clear(); + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { ReachabilityProbe = probe }), "CDP/AIA reachable") + .Outcome.ShouldBe(ConformanceOutcome.Pass); + } + + [Fact] + public async Task SmallRsaKey_LongValidity_Fail() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { RsaKeySize = 1024, Validity = TimeSpan.FromDays(365 * 3 + 2) }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers); + + Result(results, "RSA key ≥ 2048 bits").Outcome.ShouldBe(ConformanceOutcome.Fail); + Result(results, "Validity ≤ 3 years").Outcome.ShouldBe(ConformanceOutcome.Fail); + Result(results, "Signature SHA-256 with RSA").Outcome.ShouldBe(ConformanceOutcome.Pass); + } + + [Fact] + public async Task EcKey_FailsKeyCheck() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { UseEcKey = true }); + + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), "RSA key ≥ 2048 bits") + .Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Fact] + public async Task Sha384Signature_Fails() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Hash = HashAlgorithmName.SHA384 }); + + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), "Signature SHA-256 with RSA") + .Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + /// A placeholder: the query parameter name is configuration with no default. + private const string Param = "configuredName"; + + [Theory] + [InlineData("https://client.example.org/fhir#T-TRTMNT")] + [InlineData("https://client.example.org/fhir/T-IAS")] + [InlineData("https://client.example.org/fhir?configuredName=T-PH-ECR")] + [InlineData("urn:oid:2.999#T-TREAT")] + public async Task SanFormat_AnyCandidateFormPasses_WhenTheQueryParameterIsConfigured(string sanUri) + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = sanUri, SanUri = sanUri }); + + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { ExchangePurposeQueryParameter = Param }), TefcaSanFormatRule.CheckName) + .Outcome.ShouldBe(ConformanceOutcome.Pass); + } + + [Fact] + public async Task SanFormat_QueryFormIsNotRecognized_WithoutAConfiguredName() + { + using var chain = TestChain.Create(); + const string uri = "https://client.example.org/fhir?configuredName=T-PH-ECR"; + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = uri, SanUri = uri }); + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), TefcaSanFormatRule.CheckName); + + result.Outcome.ShouldBe(ConformanceOutcome.Warning); + result.Detail.ShouldContain("no query parameter is configured"); + } + + [Fact] + public async Task SanFormat_ConflictingDuplicateParameters_AreAmbiguous() + { + using var chain = TestChain.Create(); + const string uri = "https://c.example/f?configuredName=T-TRTMNT&configuredName=T-IAS"; // CN stays within 64 + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = uri, SanUri = uri }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { ExchangePurposeQueryParameter = Param }); + + Result(results, TefcaSanFormatRule.CheckName).Outcome.ShouldBe(ConformanceOutcome.Warning); + Result(results, TefcaSanFormatRule.CheckName).Detail.ShouldStartWith("Ambiguous"); + TefcaConformanceChecker.HasFailures(results).ShouldBeFalse(); + } + + [Fact] + public async Task SanFormat_WithoutAnExchangePurpose_IsOnlyAWarning() + { + using var chain = TestChain.Create(); + const string plain = "https://client.example.org/fhir"; + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = plain, SanUri = plain }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers); + + Result(results, TefcaSanFormatRule.CheckName).Outcome.ShouldBe(ConformanceOutcome.Warning); + TefcaConformanceChecker.HasFailures(results).ShouldBeFalse(); + } + + [Fact] + public async Task SanFormatRule_IsReplaceable() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec()); + var rule = new FixedRule(); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, new TefcaConformanceOptions { SanFormatRule = rule }); + + rule.Seen.ShouldBe([ClientUri]); + results.ShouldContain(r => r.Name == "custom rule"); + results.ShouldNotContain(r => r.Name == TefcaSanFormatRule.CheckName); + } + + [Theory] + // fragment and last path segment: recognized with or without a configured name + [InlineData("https://a.example/fhir#T-TRTMNT", null, "Found", "T-TRTMNT")] + [InlineData("https://a.example/fhir/T-HCO-QAI", null, "Found", "T-HCO-QAI")] + [InlineData("https://a.example/fhir#T-NOPE", Param, "NotFound", "")] + [InlineData("https://a.example/fhir/", Param, "NotFound", "")] + [InlineData("", Param, "NotFound", "")] + // exact, case-sensitive XP match; nothing trimmed + [InlineData("https://a.example/fhir#t-trtmnt", Param, "NotFound", "")] + [InlineData("https://a.example/fhir#T-TRTMNT ", Param, "NotFound", "")] + // no percent-decoding: %2D is not '-' + [InlineData("https://a.example/fhir#T%2DIAS", Param, "NotFound", "")] + [InlineData("https://a.example/fhir?configuredName=T%2DIAS", Param, "NotFound", "")] + // query: only the configured name, compared ordinally; value verbatim + [InlineData("https://a.example/fhir?foo=1&configuredName=T-PYMNT", Param, "Found", "T-PYMNT")] + [InlineData("https://a.example/fhir?configuredName=T-PYMNT", null, "NotFound", "")] + [InlineData("https://a.example/fhir?ConfiguredName=T-IAS", Param, "NotFound", "")] + [InlineData("https://a.example/fhir?configuredName=T-IAS#frag", Param, "Found", "T-IAS")] + // duplicates: identical values are fine, conflicting ones are ambiguous + [InlineData("https://a.example/fhir?configuredName=T-IAS&configuredName=T-IAS", Param, "Found", "T-IAS")] + [InlineData("https://a.example/fhir?configuredName=T-IAS&configuredName=T-PH", Param, "Ambiguous", "")] + [InlineData("https://a.example/fhir?configuredName=T-IAS&configuredName=T-PH#T-IAS", Param, "Ambiguous", "")] + public void ExchangePurpose_FromSanUri(string uri, string? parameter, string outcome, string code) + { + TefcaExchangePurpose.FromSanUri(uri, parameter, out var actual, out _).ToString().ShouldBe(outcome); + actual.ShouldBe(code); + } + + [Fact] + public async Task CommonName_ComparesOrdinally() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = "https://Client.example.org/fhir#T-TRTMNT" }); + + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), "CN ≤ 64 characters and equal to a SAN URI") + .Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Theory] + [InlineData(TefcaCertificateRole.Server, ConformanceOutcome.Fail)] + [InlineData(TefcaCertificateRole.Unknown, ConformanceOutcome.Warning)] + [InlineData(TefcaCertificateRole.Client, ConformanceOutcome.Skipped)] + public async Task ServerSanUri_WithTrailingSlash(TefcaCertificateRole role, ConformanceOutcome expected) + { + using var chain = TestChain.Create(); + const string baseUrl = "https://fhir.example.org/r4/"; + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = baseUrl, SanUri = baseUrl }); + + var result = Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { Role = role }), TefcaConformanceChecker.TrailingSlashCheckName); + + result.Outcome.ShouldBe(expected); + if (expected != ConformanceOutcome.Skipped) + result.Detail.ShouldContain("SSRAA 3.0.0"); + } + + [Fact] + public async Task ServerSanUri_WithoutTrailingSlash_Passes() + { + using var chain = TestChain.Create(); + const string baseUrl = "https://fhir.example.org/r4"; + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = baseUrl, SanUri = baseUrl }); + + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { Role = TefcaCertificateRole.Server }), TefcaConformanceChecker.TrailingSlashCheckName) + .Outcome.ShouldBe(ConformanceOutcome.Pass); + } + + [Fact] + public async Task ServerCertificate_SkipsTheSanFormat_AndPassesEveryOtherCheck() + { + using var chain = TestChain.Create(); + const string baseUrl = "https://fhir.example.org/r4"; + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = baseUrl, SanUri = baseUrl }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { Role = TefcaCertificateRole.Server, SanFormatRule = new FixedRule() }); + + Result(results, TefcaSanFormatRule.CheckName).Outcome.ShouldBe(ConformanceOutcome.Skipped); + Result(results, TefcaSanFormatRule.CheckName).Detail.ShouldContain("FHIR base URLs"); + results.ShouldNotContain(r => r.Name == "custom rule"); + Result(results, "CN ≤ 64 characters and equal to a SAN URI").Outcome.ShouldBe(ConformanceOutcome.Pass); + results.Where(r => r.Outcome != ConformanceOutcome.Pass).Select(r => r.Name) + .ShouldBe([TefcaSanFormatRule.CheckName, "CDP/AIA reachable"], ignoreOrder: true); + } + + [Fact] + public async Task ServerCertificate_CnMustEqualTheBaseUrlSan() + { + using var chain = TestChain.Create(); + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = "https://fhir.example.org/R4", SanUri = "https://fhir.example.org/r4" }); + + var results = await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers, + new TefcaConformanceOptions { Role = TefcaCertificateRole.Server }); + + Result(results, "CN ≤ 64 characters and equal to a SAN URI").Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Fact] + public async Task UnknownRole_KeepsTheSanFormatWarning() + { + using var chain = TestChain.Create(); + const string baseUrl = "https://fhir.example.org/r4"; + using var leaf = chain.IssueLeaf(new LeafSpec { Cn = baseUrl, SanUri = baseUrl }); + + Result(await TefcaConformanceChecker.CheckAsync(leaf, chain.Issuers), TefcaSanFormatRule.CheckName) + .Outcome.ShouldBe(ConformanceOutcome.Warning); + } + + // ---- issuance hook and the stored-certificate service ---- + + [Theory] + [InlineData("TEFCA FHIR Client", true)] + [InlineData("my tefca profile", true)] + [InlineData("UDAP Client", false)] + public void IsTefcaProfile_ByName(string name, bool expected) => + TefcaConformanceService.IsTefcaProfile(new CertificateProfile { Name = name }).ShouldBe(expected); + + [Fact] + public async Task IssuanceFromTefcaProfile_AttachesTheCheck() + { + var factory = new TestDbContextFactory(); + var seed = await SeedAsync(factory, "TEFCA FHIR Client"); + + var result = await IssueAsync(factory, seed); + + result.Success.ShouldBeTrue(result.Error); + result.ConformanceResults.ShouldNotBeNull(); + Result(result.ConformanceResults, "Subject OU").Outcome.ShouldBe(ConformanceOutcome.Pass); + Result(result.ConformanceResults, "Chain root → intermediate → leaf").Outcome.ShouldBe(ConformanceOutcome.Pass); + Result(result.ConformanceResults, "CDP/AIA reachable").Outcome.ShouldBe(ConformanceOutcome.Skipped); + } + + [Fact] + public async Task IssuanceFromOtherProfile_DoesNotCheck() + { + var factory = new TestDbContextFactory(); + var seed = await SeedAsync(factory, "UDAP Client"); + + var result = await IssueAsync(factory, seed); + + result.Success.ShouldBeTrue(result.Error); + result.ConformanceResults.ShouldBeNull(); + } + + [Fact] + public async Task Service_ChecksAStoredCertificate_AndProbesOnlyWhenAsked() + { + var factory = new TestDbContextFactory(); + var seed = await SeedAsync(factory, "UDAP Client"); + var issued = await IssueAsync(factory, seed); + var probe = new FakeProbe(); + var service = new TefcaConformanceService(factory, TestOperators.Full, probe); + + var offline = await service.CheckIssuedCertificateAsync(issued.EntityId!.Value); + probe.Probed.ShouldBeEmpty(); + Result(offline!, "CDP/AIA reachable").Outcome.ShouldBe(ConformanceOutcome.Skipped); + + var online = await service.CheckIssuedCertificateAsync(issued.EntityId!.Value, probeReachability: true); + probe.Probed.ShouldNotBeEmpty(); + Result(online!, "CDP/AIA reachable").Outcome.ShouldBe(ConformanceOutcome.Pass); + + (await service.CheckIssuedCertificateAsync(int.MaxValue)).ShouldBeNull(); + } + + [Fact] + public async Task IssuanceFromTefcaServerProfile_FailsATrailingSlashBaseUrl() + { + var factory = new TestDbContextFactory(); + var seed = await SeedAsync(factory, "TEFCA FHIR Server", CertificateType.EndEntityServer); + + var result = await IssueAsync(factory, seed, "https://fhir.example.org/r4/"); + + result.Success.ShouldBeTrue(result.Error); + Result(result.ConformanceResults!, TefcaConformanceChecker.TrailingSlashCheckName).Outcome.ShouldBe(ConformanceOutcome.Fail); + } + + [Fact] + public async Task Service_UsesTheConfiguredQueryParameter() + { + var factory = new TestDbContextFactory(); + var seed = await SeedAsync(factory, "UDAP Client"); + var issued = await IssueAsync(factory, seed, "https://client.example.org/fhir?configuredName=T-IAS"); + var settings = Microsoft.Extensions.Options.Options.Create(new TefcaConformanceSettings { ExchangePurposeQueryParameter = Param }); + + var unconfigured = await new TefcaConformanceService(factory, TestOperators.Full).CheckIssuedCertificateAsync(issued.EntityId!.Value); + var configured = await new TefcaConformanceService(factory, TestOperators.Full, settings: settings).CheckIssuedCertificateAsync(issued.EntityId!.Value); + + Result(unconfigured!, TefcaSanFormatRule.CheckName).Outcome.ShouldBe(ConformanceOutcome.Warning); + Result(configured!, TefcaSanFormatRule.CheckName).Outcome.ShouldBe(ConformanceOutcome.Pass); + Result(configured!, TefcaConformanceChecker.TrailingSlashCheckName).Outcome.ShouldBe(ConformanceOutcome.Skipped); + } + + private static ConformanceCheckResult Result(IEnumerable results, string name) => + results.Single(r => r.Name == name); + + private static Task IssueAsync(TestDbContextFactory factory, + (int IntermediateId, int ProfileId, int TrustDomainId) seed, string sanUri = ClientUri) + { + using var key = RSA.Create(2048); + var csr = new CertificateRequest($"CN={sanUri}, OU=RCE-FHIR, O=Example", key, HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1).CreateSigningRequestPem(); + var service = new CertificateIssuanceService(factory, TestOperators.Full, NullLogger.Instance); + return service.IssueCertificateFromCsrAsync(new CsrIssuanceRequest + { + IssuingCaCertificateId = seed.IntermediateId, + ProfileId = seed.ProfileId, + TrustDomainId = seed.TrustDomainId, + CsrPem = csr, + SubjectAltNames = [new SanEntry(SanType.Uri, sanUri)], + CdpUrls = [Cdp], + AiaUrls = [Aia], + }); + } + + private static async Task<(int IntermediateId, int ProfileId, int TrustDomainId)> SeedAsync( + TestDbContextFactory factory, string profileName, CertificateType type = CertificateType.EndEntityClient) + { + await using var db = factory.CreateDbContext(); + var trustDomain = new TrustDomain { Name = "TEFCA", Enabled = true }; + db.TrustDomains.Add(trustDomain); + var profile = new CertificateProfile + { + Name = profileName, + CertificateType = type, + KeyUsageFlags = (int)X509KeyUsageFlags.DigitalSignature, + IsKeyUsageCritical = true, + IsBasicConstraintsCritical = true, + CertificatePolicyOids = string.Join(";", TefcaConformanceChecker.ProductionPolicyOids), + IncludeCdp = true, + CdpUrlTemplate = Cdp, + IncludeAia = true, + AiaUrlTemplate = Aia, + SubjectAltNameTypes = "URI", + }; + db.CertificateProfiles.Add(profile); + await db.SaveChangesAsync(); + + using var chain = TestChain.Create(); + var root = Entity(chain.Root, trustDomain.Id, null, withKey: false); + db.CaCertificates.Add(root); + await db.SaveChangesAsync(); + var intermediate = Entity(chain.Intermediate, trustDomain.Id, root.Id, withKey: true); + db.CaCertificates.Add(intermediate); + await db.SaveChangesAsync(); + + return (intermediate.Id, profile.Id, trustDomain.Id); + } + + private static CaCertificate Entity(X509Certificate2 cert, int trustDomainId, int? parentId, bool withKey) => new() + { + TrustDomainId = trustDomainId, + ParentId = parentId, + Name = cert.GetNameInfo(X509NameType.SimpleName, false), + Subject = cert.Subject, + X509CertificatePem = cert.ExportCertificatePem(), + EncryptedPfxBytes = withKey ? cert.Export(X509ContentType.Pkcs12, "test") : null, + PfxPassword = withKey ? "test" : null, + Thumbprint = cert.Thumbprint, + SerialNumber = cert.SerialNumber, + KeyAlgorithm = "RSA", + KeySize = 2048, + NotBefore = cert.NotBefore.ToUniversalTime(), + NotAfter = cert.NotAfter.ToUniversalTime(), + }; + + // ---- test chain ---- + + private enum BasicConstraintsSpec { Critical, NotCritical, Missing } + + private sealed record LeafSpec + { + public string Ou { get; init; } = "RCE-FHIR"; + public string? Cn { get; init; } = ClientUri; + public string SanUri { get; init; } = ClientUri; + public string? DnsName { get; init; } + public X509KeyUsageFlags KeyUsage { get; init; } = X509KeyUsageFlags.DigitalSignature; + public bool KeyUsageCritical { get; init; } = true; + public BasicConstraintsSpec BasicConstraints { get; init; } = BasicConstraintsSpec.Critical; + public IReadOnlyList Policies { get; init; } = TefcaConformanceChecker.ProductionPolicyOids; + public string? Cdp { get; init; } = TefcaConformanceTests.Cdp; + public string? Aia { get; init; } = TefcaConformanceTests.Aia; + public int RsaKeySize { get; init; } = 2048; + public bool UseEcKey { get; init; } + public HashAlgorithmName Hash { get; init; } = HashAlgorithmName.SHA256; + public TimeSpan Validity { get; init; } = TimeSpan.FromDays(365); + } + + private sealed class TestChain : IDisposable + { + public required X509Certificate2 Root { get; init; } + public required X509Certificate2 Intermediate { get; init; } + public IReadOnlyList Issuers => [Intermediate, Root]; + + public static TestChain Create() + { + using var rootKey = RSA.Create(2048); + var rootReq = new CertificateRequest("CN=Test TEFCA Root", rootKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + rootReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + rootReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); + var root = rootReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-2), DateTimeOffset.UtcNow.AddYears(10)); + + using var intKey = RSA.Create(2048); + var intReq = new CertificateRequest("CN=Test TEFCA Intermediate", intKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + intReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 0, true)); + intReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); + using var intPublic = intReq.Create(root, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(8), RandomNumberGenerator.GetBytes(16)); + var intermediate = intPublic.CopyWithPrivateKey(intKey); + + return new TestChain { Root = root, Intermediate = intermediate }; + } + + public X509Certificate2 IssueLeaf(LeafSpec spec, bool byRoot = false) + { + var subject = spec.Cn == null ? $"OU={spec.Ou}, O=Example" : $"CN={spec.Cn}, OU={spec.Ou}, O=Example"; + using var rsa = spec.UseEcKey ? null : RSA.Create(spec.RsaKeySize); + using var ec = spec.UseEcKey ? ECDsa.Create(ECCurve.NamedCurves.nistP256) : null; + var req = rsa != null + ? new CertificateRequest(subject, rsa, spec.Hash, RSASignaturePadding.Pkcs1) + : new CertificateRequest(subject, ec!, spec.Hash); + + req.CertificateExtensions.Add(new X509KeyUsageExtension(spec.KeyUsage, spec.KeyUsageCritical)); + if (spec.BasicConstraints != BasicConstraintsSpec.Missing) + req.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, spec.BasicConstraints == BasicConstraintsSpec.Critical)); + + // Written verbatim (SubjectAlternativeNameBuilder would canonicalize the URI) + List sans = [new SanEntry(SanType.Uri, spec.SanUri)]; + if (spec.DnsName != null) sans.Add(new SanEntry(SanType.Dns, spec.DnsName)); + req.CertificateExtensions.Add(SanExtensionBuilder.Build(sans)!); + + if (CertificatePolicyExtension.Build(spec.Policies) is { } policies) + req.CertificateExtensions.Add(policies); + if (spec.Cdp != null) + req.CertificateExtensions.Add(CertificateExtensionHelpers.MakeCdp(spec.Cdp)); + if (spec.Aia != null) + req.CertificateExtensions.Add(CertificateExtensionHelpers.BuildAiaExtension(new Uri(spec.Aia))); + + var issuer = byRoot ? Root : Intermediate; + var notBefore = DateTimeOffset.UtcNow.AddMinutes(-5); + var generator = X509SignatureGenerator.CreateForRSA(issuer.GetRSAPrivateKey()!, RSASignaturePadding.Pkcs1); + return req.Create(issuer.SubjectName, generator, notBefore, notBefore + spec.Validity, RandomNumberGenerator.GetBytes(16)); + } + + public void Dispose() + { + Root.Dispose(); + Intermediate.Dispose(); + } + } + + private sealed class FakeProbe : IUrlReachabilityProbe + { + public HashSet Unreachable { get; } = []; + public List Probed { get; } = []; + + public Task ProbeAsync(Uri url, CancellationToken cancellationToken = default) + { + Probed.Add(url.OriginalString); + return Task.FromResult(Unreachable.Contains(url.OriginalString) ? "HTTP 404" : null); + } + } + + private sealed class FixedRule : ITefcaSanFormatRule + { + public List Seen { get; } = []; + + public ConformanceCheckResult Evaluate(IReadOnlyList sanUris) + { + Seen.AddRange(sanUris); + return ConformanceCheckResult.Warning("custom rule", "evaluated"); + } + } +} 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';