| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using AsiBackbone.Core.Signing; |
| | | 4 | | |
| | | 5 | | namespace AsiBackbone.Signing.LocalDevelopment; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Provides local-development RSA signing and verification for AsiBackbone signing abstractions. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// This service generates an in-process RSA key for samples and tests. It is not a production managed-key provider. |
| | | 12 | | /// </remarks> |
| | | 13 | | public sealed class LocalDevelopmentSigningService : IAsiBackboneSigningService, IAsiBackboneSignatureVerificationServic |
| | | 14 | | { |
| | | 15 | | private const string SupportedHashAlgorithm = "SHA-256"; |
| | 1 | 16 | | private static readonly Encoding SigningEncoding = Encoding.UTF8; |
| | | 17 | | |
| | | 18 | | private readonly LocalDevelopmentSigningOptions options; |
| | | 19 | | private readonly RSA rsa; |
| | | 20 | | private bool disposed; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Initializes a new instance of the <see cref="LocalDevelopmentSigningService" /> class with default local-develop |
| | | 24 | | /// </summary> |
| | | 25 | | public LocalDevelopmentSigningService() |
| | 2 | 26 | | : this(LocalDevelopmentSigningOptions.Create()) |
| | | 27 | | { |
| | 2 | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Initializes a new instance of the <see cref="LocalDevelopmentSigningService" /> class. |
| | | 32 | | /// </summary> |
| | 5 | 33 | | public LocalDevelopmentSigningService(LocalDevelopmentSigningOptions options) |
| | | 34 | | { |
| | 5 | 35 | | ArgumentNullException.ThrowIfNull(options); |
| | | 36 | | |
| | 5 | 37 | | this.options = options; |
| | 5 | 38 | | rsa = RSA.Create(); |
| | 5 | 39 | | rsa.KeySize = NormalizeKeySize(options.KeySizeBits); |
| | 5 | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <inheritdoc /> |
| | | 43 | | public ValueTask<SigningResult> SignAsync( |
| | | 44 | | SigningRequest request, |
| | | 45 | | CancellationToken cancellationToken = default) |
| | | 46 | | { |
| | 5 | 47 | | ArgumentNullException.ThrowIfNull(request); |
| | 5 | 48 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 49 | | |
| | 5 | 50 | | string? validationFailure = ValidateSigningRequest(request); |
| | 5 | 51 | | if (validationFailure is not null) |
| | | 52 | | { |
| | 1 | 53 | | return ValueTask.FromResult(CreateUnsignedFailureResult(request, validationFailure, validationFailure)); |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | try |
| | | 57 | | { |
| | 4 | 58 | | ThrowIfDisposed(); |
| | | 59 | | |
| | 4 | 60 | | byte[] data = SigningEncoding.GetBytes(request.SigningHash); |
| | 4 | 61 | | byte[] signature = rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); |
| | | 62 | | |
| | 4 | 63 | | Dictionary<string, string> metadata = CreateBaseMetadata(request); |
| | 4 | 64 | | metadata["signing_status"] = "signed"; |
| | | 65 | | |
| | 4 | 66 | | var signingMetadata = SigningMetadata.Create( |
| | 4 | 67 | | signingHash: request.SigningHash, |
| | 4 | 68 | | hashAlgorithm: NormalizeHashAlgorithm(request.HashAlgorithm), |
| | 4 | 69 | | signature: Convert.ToBase64String(signature), |
| | 4 | 70 | | signatureAlgorithm: NormalizeRequired(options.SignatureAlgorithm, LocalDevelopmentSigningOptions.Default |
| | 4 | 71 | | keyId: NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId), |
| | 4 | 72 | | keyVersion: NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.DefaultKeyVersion), |
| | 4 | 73 | | provider: NormalizeRequired(options.ProviderName, LocalDevelopmentSigningOptions.DefaultProviderName), |
| | 4 | 74 | | signedUtc: DateTimeOffset.UtcNow, |
| | 4 | 75 | | metadata: metadata); |
| | | 76 | | |
| | 4 | 77 | | return ValueTask.FromResult(SigningResult.FromMetadata(signingMetadata)); |
| | | 78 | | } |
| | 0 | 79 | | catch (Exception exception) when (exception is CryptographicException or ObjectDisposedException or InvalidOpera |
| | | 80 | | { |
| | 0 | 81 | | if (!options.ReturnUnsignedOnFailure) |
| | | 82 | | { |
| | 0 | 83 | | throw; |
| | | 84 | | } |
| | | 85 | | |
| | 0 | 86 | | return ValueTask.FromResult(CreateUnsignedFailureResult(request, "localdev.signing.failed", exception.GetTyp |
| | | 87 | | } |
| | 4 | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <inheritdoc /> |
| | | 91 | | public ValueTask<SignatureVerificationResult> VerifyAsync( |
| | | 92 | | SignatureVerificationRequest request, |
| | | 93 | | CancellationToken cancellationToken = default) |
| | | 94 | | { |
| | 3 | 95 | | ArgumentNullException.ThrowIfNull(request); |
| | 3 | 96 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 97 | | |
| | 3 | 98 | | SigningMetadata metadata = request.SigningMetadata; |
| | | 99 | | |
| | 3 | 100 | | if (!metadata.HasSignature) |
| | | 101 | | { |
| | 0 | 102 | | return ValueTask.FromResult(SignatureVerificationResult.MissingSignature("The local-development verifier rec |
| | | 103 | | } |
| | | 104 | | |
| | 3 | 105 | | if (!string.Equals(request.SigningHash, metadata.SigningHash, StringComparison.Ordinal)) |
| | | 106 | | { |
| | 1 | 107 | | return ValueTask.FromResult(SignatureVerificationResult.Failed("localdev.signature.hash-mismatch", "The veri |
| | | 108 | | } |
| | | 109 | | |
| | 2 | 110 | | if (!IsSupportedHashAlgorithm(metadata.HashAlgorithm)) |
| | | 111 | | { |
| | 0 | 112 | | return ValueTask.FromResult(SignatureVerificationResult.Failed("localdev.signature.hash-algorithm-unsupporte |
| | | 113 | | } |
| | | 114 | | |
| | 2 | 115 | | if (!string.Equals(metadata.SignatureAlgorithm, NormalizeRequired(options.SignatureAlgorithm, LocalDevelopmentSi |
| | | 116 | | { |
| | 0 | 117 | | return ValueTask.FromResult(SignatureVerificationResult.Failed("localdev.signature.algorithm-mismatch", "The |
| | | 118 | | } |
| | | 119 | | |
| | 2 | 120 | | if (!string.Equals(metadata.KeyId, NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId) |
| | 2 | 121 | | || !string.Equals(metadata.KeyVersion, NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions. |
| | | 122 | | { |
| | 0 | 123 | | return ValueTask.FromResult(SignatureVerificationResult.Failed("localdev.signature.key-mismatch", "The signa |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | try |
| | | 127 | | { |
| | 2 | 128 | | ThrowIfDisposed(); |
| | | 129 | | |
| | 2 | 130 | | byte[] signature = Convert.FromBase64String(metadata.Signature!); |
| | 2 | 131 | | byte[] data = SigningEncoding.GetBytes(request.SigningHash); |
| | 2 | 132 | | bool verified = rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); |
| | | 133 | | |
| | 2 | 134 | | return ValueTask.FromResult(verified |
| | 2 | 135 | | ? SignatureVerificationResult.Verified() |
| | 2 | 136 | | : SignatureVerificationResult.Failed("localdev.signature.invalid", "The local-development signature did |
| | | 137 | | } |
| | 0 | 138 | | catch (FormatException) |
| | | 139 | | { |
| | 0 | 140 | | return ValueTask.FromResult(SignatureVerificationResult.Failed("localdev.signature.malformed", "The signatur |
| | | 141 | | } |
| | 0 | 142 | | catch (Exception exception) when (exception is CryptographicException or ObjectDisposedException or InvalidOpera |
| | | 143 | | { |
| | 0 | 144 | | return ValueTask.FromResult(SignatureVerificationResult.Failed("localdev.verification.failed", exception.Get |
| | | 145 | | } |
| | 2 | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <inheritdoc /> |
| | | 149 | | public void Dispose() |
| | | 150 | | { |
| | 5 | 151 | | if (disposed) |
| | | 152 | | { |
| | 0 | 153 | | return; |
| | | 154 | | } |
| | | 155 | | |
| | 5 | 156 | | rsa.Dispose(); |
| | 5 | 157 | | disposed = true; |
| | 5 | 158 | | } |
| | | 159 | | |
| | | 160 | | private static int NormalizeKeySize(int keySizeBits) |
| | | 161 | | { |
| | 5 | 162 | | return keySizeBits >= 2048 |
| | 5 | 163 | | ? keySizeBits |
| | 5 | 164 | | : LocalDevelopmentSigningOptions.DefaultKeySizeBits; |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | private static string NormalizeRequired(string? value, string fallback) |
| | | 168 | | { |
| | 33 | 169 | | return string.IsNullOrWhiteSpace(value) |
| | 33 | 170 | | ? fallback |
| | 33 | 171 | | : value.Trim(); |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | private static string NormalizeHashAlgorithm(string? hashAlgorithm) |
| | | 175 | | { |
| | 12 | 176 | | return string.IsNullOrWhiteSpace(hashAlgorithm) |
| | 12 | 177 | | ? SupportedHashAlgorithm |
| | 12 | 178 | | : hashAlgorithm.Trim().Equals("SHA256", StringComparison.OrdinalIgnoreCase) |
| | 12 | 179 | | ? SupportedHashAlgorithm |
| | 12 | 180 | | : hashAlgorithm.Trim(); |
| | | 181 | | } |
| | | 182 | | |
| | | 183 | | private static bool IsSupportedHashAlgorithm(string? hashAlgorithm) |
| | | 184 | | { |
| | 7 | 185 | | string normalized = NormalizeHashAlgorithm(hashAlgorithm); |
| | | 186 | | |
| | 7 | 187 | | return normalized.Equals(SupportedHashAlgorithm, StringComparison.OrdinalIgnoreCase); |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | private string? ValidateSigningRequest(SigningRequest request) |
| | | 191 | | { |
| | 5 | 192 | | if (disposed) |
| | | 193 | | { |
| | 0 | 194 | | return "localdev.signing.disposed"; |
| | | 195 | | } |
| | | 196 | | |
| | 5 | 197 | | if (!IsSupportedHashAlgorithm(request.HashAlgorithm)) |
| | | 198 | | { |
| | 1 | 199 | | return "localdev.signing.hash-algorithm-unsupported"; |
| | | 200 | | } |
| | | 201 | | |
| | 4 | 202 | | string configuredKeyId = NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId); |
| | 4 | 203 | | if (request.KeyId is not null && !string.Equals(request.KeyId, configuredKeyId, StringComparison.Ordinal)) |
| | | 204 | | { |
| | 0 | 205 | | return "localdev.signing.key-mismatch"; |
| | | 206 | | } |
| | | 207 | | |
| | 4 | 208 | | string configuredKeyVersion = NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.DefaultKeyVer |
| | 4 | 209 | | return request.KeyVersion is not null && !string.Equals(request.KeyVersion, configuredKeyVersion, StringComparis |
| | 4 | 210 | | ? "localdev.signing.key-version-mismatch" |
| | 4 | 211 | | : null; |
| | | 212 | | } |
| | | 213 | | |
| | | 214 | | private SigningResult CreateUnsignedFailureResult(SigningRequest request, string failureCode, string failureMessage) |
| | | 215 | | { |
| | 1 | 216 | | Dictionary<string, string> metadata = CreateBaseMetadata(request); |
| | 1 | 217 | | metadata["signing_status"] = "failed"; |
| | 1 | 218 | | metadata["failure_code"] = failureCode; |
| | 1 | 219 | | metadata["failure_message"] = failureMessage; |
| | | 220 | | |
| | 1 | 221 | | var signingMetadata = SigningMetadata.Create( |
| | 1 | 222 | | signingHash: request.SigningHash, |
| | 1 | 223 | | hashAlgorithm: NormalizeHashAlgorithm(request.HashAlgorithm), |
| | 1 | 224 | | keyId: NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId), |
| | 1 | 225 | | keyVersion: NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.DefaultKeyVersion), |
| | 1 | 226 | | provider: NormalizeRequired(options.ProviderName, LocalDevelopmentSigningOptions.DefaultProviderName), |
| | 1 | 227 | | metadata: metadata); |
| | | 228 | | |
| | 1 | 229 | | return SigningResult.FromMetadata(signingMetadata); |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | private Dictionary<string, string> CreateBaseMetadata(SigningRequest request) |
| | | 233 | | { |
| | 5 | 234 | | Dictionary<string, string> metadata = new(StringComparer.Ordinal) |
| | 5 | 235 | | { |
| | 5 | 236 | | ["provider_kind"] = "local-development", |
| | 5 | 237 | | ["provider_warning"] = "local-development-only", |
| | 5 | 238 | | ["key_algorithm"] = "RSA", |
| | 5 | 239 | | ["key_size_bits"] = rsa.KeySize.ToString(System.Globalization.CultureInfo.InvariantCulture) |
| | 5 | 240 | | }; |
| | | 241 | | |
| | 5 | 242 | | if (request.Purpose is not null) |
| | | 243 | | { |
| | 4 | 244 | | metadata["purpose"] = request.Purpose; |
| | | 245 | | } |
| | | 246 | | |
| | 18 | 247 | | foreach (KeyValuePair<string, string> item in request.Metadata) |
| | | 248 | | { |
| | 4 | 249 | | if (string.IsNullOrWhiteSpace(item.Key)) |
| | | 250 | | { |
| | | 251 | | continue; |
| | | 252 | | } |
| | | 253 | | |
| | 4 | 254 | | metadata[item.Key.Trim()] = item.Value?.Trim() ?? string.Empty; |
| | | 255 | | } |
| | | 256 | | |
| | 5 | 257 | | return metadata; |
| | | 258 | | } |
| | | 259 | | |
| | | 260 | | private void ThrowIfDisposed() |
| | | 261 | | { |
| | 6 | 262 | | ObjectDisposedException.ThrowIf(disposed, this); |
| | 6 | 263 | | } |
| | | 264 | | } |