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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Sigyll.Common/Data/Entities/CertificateProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ public class CertificateProfile
public int? PathLengthConstraint { get; set; }
public bool IsExtendedKeyUsageCritical { get; set; }

/// <summary>
/// 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 <see cref="Services.CertificatePolicyExtension"/>.
/// </summary>
public string? CertificatePolicyOids { get; set; }

/// <summary>
/// "nistP256", "nistP384", or "nistP521". Only used when KeyAlgorithm is "ECDSA".
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions Sigyll.Common/Data/SigyllDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
81 changes: 76 additions & 5 deletions Sigyll.Common/Services/CertificateIssuanceService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<TefcaConformanceSettings>? tefcaSettings = null)
{
_tefcaQueryParameter = tefcaSettings?.Value.ExchangePurposeQueryParameter;
_dbFactory = dbFactory;
_operator = operatorContext;
_logger = logger;
Expand All @@ -59,6 +62,7 @@ public CertificateIssuanceService(
}

private readonly PublishingPathPolicy _publishingPaths;
private readonly string? _tefcaQueryParameter;

public IssuanceValidator Validator => _validator;

Expand All @@ -79,9 +83,40 @@ public async Task<CertificateIssuanceResult> 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;
}

/// <summary>
/// After an end-entity certificate is issued from a TEFCA profile, checks it against the TEFCA FHIR profile and
/// puts the results on <paramref name="result"/>. Offline only: CDP/AIA reachability is left to the Explorer.
/// A failed check is logged and reported; it never undoes the issuance.
/// </summary>
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)
{
Expand Down Expand Up @@ -129,11 +164,15 @@ private async Task<CertificateIssuanceResult> 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);

Expand Down Expand Up @@ -465,15 +504,26 @@ private async Task<CertificateIssuanceResult> IssueAsync(CertificateIssuanceRequ
_ => "in an HSM",
};

/// <summary>
/// An error naming the profile's certificate policy entries that are not OIDs, or null when all are valid.
/// </summary>
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)}.";
}

/// <summary>
/// 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 <see cref="RenewalIdentity"/>).
/// change its subject or SANs, or drop a certificate policy it carries (see <see cref="RenewalIdentity"/>).
/// </summary>
private static async Task<(int Version, int? RenewalOfId, string? Error)> ResolveRenewalLineageAsync(
SigyllDbContext db, int? renewalOfCertificateId, bool isCaLineage,
string subjectDn, IEnumerable<SanEntry> subjectAltNames)
string subjectDn, IEnumerable<SanEntry> subjectAltNames, CertificateProfile profile)
{
if (renewalOfCertificateId is not int predecessorId)
return (1, null, null);
Expand All @@ -494,6 +544,12 @@ private async Task<CertificateIssuanceResult> 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);
}

Expand All @@ -509,6 +565,7 @@ public async Task<CsrIssuanceResult> 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;
}

Expand Down Expand Up @@ -557,9 +614,13 @@ private async Task<CsrIssuanceResult> 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);

Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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)
{
Expand Down
Loading
Loading