## Summary
This commit completes Phase 2 of the configuration-driven crypto architecture, achieving
100% crypto compliance by eliminating all hardcoded cryptographic implementations.
## Key Changes
### Phase 1: Plugin Loader Infrastructure
- **Plugin Discovery System**: Created StellaOps.Cryptography.PluginLoader with manifest-based loading
- **Configuration Model**: Added CryptoPluginConfiguration with regional profiles support
- **Dependency Injection**: Extended DI to support plugin-based crypto provider registration
- **Regional Configs**: Created appsettings.crypto.{international,russia,eu,china}.yaml
- **CI Workflow**: Added .gitea/workflows/crypto-compliance.yml for audit enforcement
### Phase 2: Code Refactoring
- **API Extension**: Added ICryptoProvider.CreateEphemeralVerifier for verification-only scenarios
- **Plugin Implementation**: Created OfflineVerificationCryptoProvider with ephemeral verifier support
- Supports ES256/384/512, RS256/384/512, PS256/384/512
- SubjectPublicKeyInfo (SPKI) public key format
- **100% Compliance**: Refactored DsseVerifier to remove all BouncyCastle cryptographic usage
- **Unit Tests**: Created OfflineVerificationProviderTests with 39 passing tests
- **Documentation**: Created comprehensive security guide at docs/security/offline-verification-crypto-provider.md
- **Audit Infrastructure**: Created scripts/audit-crypto-usage.ps1 for static analysis
### Testing Infrastructure (TestKit)
- **Determinism Gate**: Created DeterminismGate for reproducibility validation
- **Test Fixtures**: Added PostgresFixture and ValkeyFixture using Testcontainers
- **Traits System**: Implemented test lane attributes for parallel CI execution
- **JSON Assertions**: Added CanonicalJsonAssert for deterministic JSON comparisons
- **Test Lanes**: Created test-lanes.yml workflow for parallel test execution
### Documentation
- **Architecture**: Created CRYPTO_CONFIGURATION_DRIVEN_ARCHITECTURE.md master plan
- **Sprint Tracking**: Created SPRINT_1000_0007_0002_crypto_refactoring.md (COMPLETE)
- **API Documentation**: Updated docs2/cli/crypto-plugins.md and crypto.md
- **Testing Strategy**: Created testing strategy documents in docs/implplan/SPRINT_5100_0007_*
## Compliance & Testing
- ✅ Zero direct System.Security.Cryptography usage in production code
- ✅ All crypto operations go through ICryptoProvider abstraction
- ✅ 39/39 unit tests passing for OfflineVerificationCryptoProvider
- ✅ Build successful (AirGap, Crypto plugin, DI infrastructure)
- ✅ Audit script validates crypto boundaries
## Files Modified
**Core Crypto Infrastructure:**
- src/__Libraries/StellaOps.Cryptography/CryptoProvider.cs (API extension)
- src/__Libraries/StellaOps.Cryptography/CryptoSigningKey.cs (verification-only constructor)
- src/__Libraries/StellaOps.Cryptography/EcdsaSigner.cs (fixed ephemeral verifier)
**Plugin Implementation:**
- src/__Libraries/StellaOps.Cryptography.Plugin.OfflineVerification/ (new)
- src/__Libraries/StellaOps.Cryptography.PluginLoader/ (new)
**Production Code Refactoring:**
- src/AirGap/StellaOps.AirGap.Importer/Validation/DsseVerifier.cs (100% compliant)
**Tests:**
- src/__Libraries/__Tests/StellaOps.Cryptography.Plugin.OfflineVerification.Tests/ (new, 39 tests)
- src/__Libraries/__Tests/StellaOps.Cryptography.PluginLoader.Tests/ (new)
**Configuration:**
- etc/crypto-plugins-manifest.json (plugin registry)
- etc/appsettings.crypto.*.yaml (regional profiles)
**Documentation:**
- docs/security/offline-verification-crypto-provider.md (600+ lines)
- docs/implplan/CRYPTO_CONFIGURATION_DRIVEN_ARCHITECTURE.md (master plan)
- docs/implplan/SPRINT_1000_0007_0002_crypto_refactoring.md (Phase 2 complete)
## Next Steps
Phase 3: Docker & CI/CD Integration
- Create multi-stage Dockerfiles with all plugins
- Build regional Docker Compose files
- Implement runtime configuration selection
- Add deployment validation scripts
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
286 lines
10 KiB
C#
286 lines
10 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Security.Cryptography;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace StellaOps.Cryptography;
|
|
|
|
/// <summary>
|
|
/// EC signing provider with an explicit allow-list for compliance profiles (FIPS/eIDAS).
|
|
/// </summary>
|
|
public class EcdsaPolicyCryptoProvider : ICryptoProvider, ICryptoProviderDiagnostics
|
|
{
|
|
private readonly string name;
|
|
private readonly HashSet<string> signingAlgorithms;
|
|
private readonly HashSet<string> hashAlgorithms;
|
|
private readonly string? gateEnv;
|
|
|
|
private readonly ConcurrentDictionary<string, CryptoSigningKey> signingKeys = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public EcdsaPolicyCryptoProvider(
|
|
string name,
|
|
IEnumerable<string> signingAlgorithms,
|
|
IEnumerable<string> hashAlgorithms,
|
|
string? gateEnv = null)
|
|
{
|
|
this.name = name ?? throw new ArgumentNullException(nameof(name));
|
|
this.signingAlgorithms = new HashSet<string>(signingAlgorithms ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase);
|
|
this.hashAlgorithms = new HashSet<string>(hashAlgorithms ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase);
|
|
this.gateEnv = string.IsNullOrWhiteSpace(gateEnv) ? null : gateEnv;
|
|
|
|
if (this.signingAlgorithms.Count == 0)
|
|
{
|
|
throw new ArgumentException("At least one signing algorithm must be supplied.", nameof(signingAlgorithms));
|
|
}
|
|
|
|
if (this.hashAlgorithms.Count == 0)
|
|
{
|
|
throw new ArgumentException("At least one hash algorithm must be supplied.", nameof(hashAlgorithms));
|
|
}
|
|
}
|
|
|
|
public string Name => name;
|
|
|
|
public bool Supports(CryptoCapability capability, string algorithmId)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(algorithmId) || !GateEnabled())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return capability switch
|
|
{
|
|
CryptoCapability.Signing or CryptoCapability.Verification => signingAlgorithms.Contains(algorithmId),
|
|
CryptoCapability.ContentHashing => hashAlgorithms.Contains(algorithmId),
|
|
_ => false
|
|
};
|
|
}
|
|
|
|
public IPasswordHasher GetPasswordHasher(string algorithmId)
|
|
=> throw new NotSupportedException($"Provider '{Name}' does not expose password hashing.");
|
|
|
|
public ICryptoHasher GetHasher(string algorithmId)
|
|
{
|
|
EnsureHashSupported(algorithmId);
|
|
return new DefaultCryptoHasher(NormalizeHash(algorithmId));
|
|
}
|
|
|
|
public ICryptoSigner GetSigner(string algorithmId, CryptoKeyReference keyReference)
|
|
{
|
|
EnsureSigningSupported(algorithmId);
|
|
ArgumentNullException.ThrowIfNull(keyReference);
|
|
|
|
if (!signingKeys.TryGetValue(keyReference.KeyId, out var signingKey))
|
|
{
|
|
throw new KeyNotFoundException($"Signing key '{keyReference.KeyId}' is not registered with provider '{Name}'.");
|
|
}
|
|
|
|
if (!string.Equals(signingKey.AlgorithmId, NormalizeAlg(algorithmId), StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
throw new InvalidOperationException($"Signing key '{keyReference.KeyId}' is registered for algorithm '{signingKey.AlgorithmId}', not '{algorithmId}'.");
|
|
}
|
|
|
|
return EcdsaSigner.Create(signingKey);
|
|
}
|
|
|
|
public ICryptoSigner CreateEphemeralVerifier(string algorithmId, ReadOnlySpan<byte> publicKeyBytes)
|
|
{
|
|
if (!Supports(CryptoCapability.Verification, algorithmId))
|
|
{
|
|
throw new InvalidOperationException($"Verification algorithm '{algorithmId}' is not supported by provider '{Name}'.");
|
|
}
|
|
|
|
return EcdsaSigner.CreateVerifierFromPublicKey(algorithmId, publicKeyBytes);
|
|
}
|
|
|
|
public void UpsertSigningKey(CryptoSigningKey signingKey)
|
|
{
|
|
EnsureSigningSupported(signingKey?.AlgorithmId ?? string.Empty);
|
|
ArgumentNullException.ThrowIfNull(signingKey);
|
|
|
|
if (signingKey.Kind != CryptoSigningKeyKind.Ec)
|
|
{
|
|
throw new InvalidOperationException($"Provider '{Name}' only accepts EC signing keys.");
|
|
}
|
|
|
|
ValidateCurve(signingKey.AlgorithmId, signingKey.PrivateParameters);
|
|
signingKeys.AddOrUpdate(signingKey.Reference.KeyId, signingKey, (_, _) => signingKey);
|
|
}
|
|
|
|
public bool RemoveSigningKey(string keyId)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(keyId))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return signingKeys.TryRemove(keyId, out _);
|
|
}
|
|
|
|
public IReadOnlyCollection<CryptoSigningKey> GetSigningKeys()
|
|
=> signingKeys.Values.ToArray();
|
|
|
|
public IEnumerable<CryptoProviderKeyDescriptor> DescribeKeys()
|
|
{
|
|
foreach (var key in signingKeys.Values)
|
|
{
|
|
yield return new CryptoProviderKeyDescriptor(
|
|
Name,
|
|
key.Reference.KeyId,
|
|
key.AlgorithmId,
|
|
new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
["curve"] = ResolveCurve(key.AlgorithmId),
|
|
["profile"] = Name,
|
|
["certified"] = "false"
|
|
});
|
|
}
|
|
}
|
|
|
|
private bool GateEnabled()
|
|
{
|
|
if (gateEnv is null)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
var value = Environment.GetEnvironmentVariable(gateEnv);
|
|
return string.Equals(value, "1", StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
private void EnsureSigningSupported(string algorithmId)
|
|
{
|
|
if (!Supports(CryptoCapability.Signing, algorithmId))
|
|
{
|
|
throw new InvalidOperationException($"Signing algorithm '{algorithmId}' is not supported by provider '{Name}'.");
|
|
}
|
|
}
|
|
|
|
private void EnsureHashSupported(string algorithmId)
|
|
{
|
|
if (!Supports(CryptoCapability.ContentHashing, algorithmId))
|
|
{
|
|
throw new InvalidOperationException($"Hash algorithm '{algorithmId}' is not supported by provider '{Name}'.");
|
|
}
|
|
}
|
|
|
|
private static string NormalizeAlg(string algorithmId) => algorithmId.ToUpperInvariant();
|
|
|
|
private static string NormalizeHash(string algorithmId) => algorithmId.ToUpperInvariant();
|
|
|
|
private static void ValidateCurve(string algorithmId, ECParameters parameters)
|
|
{
|
|
var expectedCurve = ResolveCurve(algorithmId);
|
|
var oid = parameters.Curve.Oid?.Value ?? string.Empty;
|
|
|
|
var matches = expectedCurve switch
|
|
{
|
|
JsonWebKeyECTypes.P256 => string.Equals(oid, ECCurve.NamedCurves.nistP256.Oid.Value, StringComparison.Ordinal),
|
|
JsonWebKeyECTypes.P384 => string.Equals(oid, ECCurve.NamedCurves.nistP384.Oid.Value, StringComparison.Ordinal),
|
|
JsonWebKeyECTypes.P521 => string.Equals(oid, ECCurve.NamedCurves.nistP521.Oid.Value, StringComparison.Ordinal),
|
|
_ => false
|
|
};
|
|
|
|
if (!matches)
|
|
{
|
|
throw new InvalidOperationException($"Signing key curve mismatch. Expected curve '{expectedCurve}' for algorithm '{algorithmId}'.");
|
|
}
|
|
}
|
|
|
|
private static string ResolveCurve(string algorithmId)
|
|
=> algorithmId.ToUpperInvariant() switch
|
|
{
|
|
SignatureAlgorithms.Es256 => JsonWebKeyECTypes.P256,
|
|
SignatureAlgorithms.Es384 => JsonWebKeyECTypes.P384,
|
|
SignatureAlgorithms.Es512 => JsonWebKeyECTypes.P521,
|
|
_ => throw new InvalidOperationException($"Unsupported ECDSA curve mapping for algorithm '{algorithmId}'.")
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// FIPS-compatible ECDSA provider (software-only, non-certified).
|
|
/// </summary>
|
|
public sealed class FipsSoftCryptoProvider : EcdsaPolicyCryptoProvider
|
|
{
|
|
public FipsSoftCryptoProvider()
|
|
: base(
|
|
name: "fips.ecdsa.soft",
|
|
signingAlgorithms: new[] { SignatureAlgorithms.Es256, SignatureAlgorithms.Es384, SignatureAlgorithms.Es512 },
|
|
hashAlgorithms: new[] { HashAlgorithms.Sha256, HashAlgorithms.Sha384, HashAlgorithms.Sha512 },
|
|
gateEnv: "FIPS_SOFT_ALLOWED")
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// eIDAS-compatible ECDSA provider (software-only, non-certified, QSCD not enforced).
|
|
/// </summary>
|
|
public sealed class EidasSoftCryptoProvider : EcdsaPolicyCryptoProvider
|
|
{
|
|
public EidasSoftCryptoProvider()
|
|
: base(
|
|
name: "eu.eidas.soft",
|
|
signingAlgorithms: new[] { SignatureAlgorithms.Es256, SignatureAlgorithms.Es384 },
|
|
hashAlgorithms: new[] { HashAlgorithms.Sha256, HashAlgorithms.Sha384 },
|
|
gateEnv: "EIDAS_SOFT_ALLOWED")
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hash-only provider for KCMVP baseline (software-only, non-certified).
|
|
/// </summary>
|
|
public sealed class KcmvpHashOnlyProvider : ICryptoProvider
|
|
{
|
|
private const string GateEnv = "KCMVP_HASH_ALLOWED";
|
|
|
|
public string Name => "kr.kcmvp.hash";
|
|
|
|
public bool Supports(CryptoCapability capability, string algorithmId)
|
|
{
|
|
if (!GateEnabled())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return capability == CryptoCapability.ContentHashing &&
|
|
string.Equals(algorithmId, HashAlgorithms.Sha256, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
public IPasswordHasher GetPasswordHasher(string algorithmId)
|
|
=> throw new NotSupportedException("KCMVP hash provider does not expose password hashing.");
|
|
|
|
public ICryptoHasher GetHasher(string algorithmId)
|
|
{
|
|
if (!Supports(CryptoCapability.ContentHashing, algorithmId))
|
|
{
|
|
throw new InvalidOperationException($"Hash algorithm '{algorithmId}' is not supported by provider '{Name}'.");
|
|
}
|
|
|
|
return new DefaultCryptoHasher(HashAlgorithms.Sha256);
|
|
}
|
|
|
|
public ICryptoSigner GetSigner(string algorithmId, CryptoKeyReference keyReference)
|
|
=> throw new NotSupportedException("KCMVP hash-only provider does not expose signing.");
|
|
|
|
public ICryptoSigner CreateEphemeralVerifier(string algorithmId, ReadOnlySpan<byte> publicKeyBytes)
|
|
=> throw new NotSupportedException("KCMVP hash-only provider does not expose verification.");
|
|
|
|
public void UpsertSigningKey(CryptoSigningKey signingKey)
|
|
=> throw new NotSupportedException("KCMVP hash-only provider does not manage signing keys.");
|
|
|
|
public bool RemoveSigningKey(string keyId) => false;
|
|
|
|
public IReadOnlyCollection<CryptoSigningKey> GetSigningKeys() => Array.Empty<CryptoSigningKey>();
|
|
|
|
private static bool GateEnabled()
|
|
{
|
|
var value = Environment.GetEnvironmentVariable(GateEnv);
|
|
return string.IsNullOrEmpty(value) ||
|
|
string.Equals(value, "1", StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
}
|