| | 1 | | using System.Runtime.InteropServices; |
| | 2 | | using System.Security.Cryptography; |
| | 3 | |
|
| | 4 | | namespace NLightning.Infrastructure.Protocol.Services; |
| | 5 | |
|
| | 6 | | using Crypto.Factories; |
| | 7 | | using Crypto.Hashes; |
| | 8 | | using Crypto.Interfaces; |
| | 9 | | using Domain.Crypto.Constants; |
| | 10 | | using Domain.Crypto.ValueObjects; |
| | 11 | | using Domain.Protocol.Enums; |
| | 12 | | using Domain.Protocol.Interfaces; |
| | 13 | | using Models; |
| | 14 | |
|
| | 15 | | /// <summary> |
| | 16 | | /// Provides efficient storage of per-commitment secrets |
| | 17 | | /// </summary> |
| | 18 | | public class SecretStorageService : ISecretStorageService |
| | 19 | | { |
| 48 | 20 | | private readonly StoredSecret?[] _knownSecrets = new StoredSecret?[49]; |
| 48 | 21 | | private readonly ICryptoProvider _cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| 48 | 22 | | private IntPtr _perCommitmentSeedPtr = IntPtr.Zero; |
| 48 | 23 | | private readonly Dictionary<BasepointType, IntPtr> _basepointSecrets = new(); |
| | 24 | |
|
| | 25 | | /// <inheritdoc/> |
| | 26 | | public bool InsertSecret(Secret secret, ulong index) |
| | 27 | | { |
| | 28 | | // Find the bucket for this secret |
| 432 | 29 | | var bucket = GetBucketIndex(index); |
| | 30 | |
|
| 432 | 31 | | var storedSecret = new byte[CryptoConstants.SecretLen]; |
| 432 | 32 | | var derivedSecret = new byte[CryptoConstants.SecretLen]; |
| | 33 | | // Verify this secret can derive all previously known secrets |
| 10160 | 34 | | for (var b = 0; b < bucket; b++) |
| | 35 | | { |
| 4680 | 36 | | if (_knownSecrets[b] == null) |
| | 37 | | continue; |
| | 38 | |
|
| 4488 | 39 | | DeriveSecret(secret, bucket, _knownSecrets[b]!.Index, derivedSecret); |
| | 40 | |
|
| | 41 | | // Compare with stored secret (copied from secure memory) |
| 4488 | 42 | | Marshal.Copy(_knownSecrets[b]!.SecretPtr, storedSecret, 0, CryptoConstants.SecretLen); |
| | 43 | |
|
| 4488 | 44 | | if (!CryptographicOperations.FixedTimeEquals(derivedSecret, storedSecret)) |
| | 45 | | { |
| | 46 | | // Securely wipe the temporary copy |
| 32 | 47 | | _cryptoProvider.MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(storedSecret, 0), |
| 32 | 48 | | CryptoConstants.SecretLen); |
| 32 | 49 | | _cryptoProvider.MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(derivedSecret, 0), |
| 32 | 50 | | CryptoConstants.SecretLen); |
| 32 | 51 | | return false; // Secret verification failed |
| | 52 | | } |
| | 53 | |
|
| | 54 | | // Securely wipe the temporary copies |
| 4456 | 55 | | _cryptoProvider.MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(storedSecret, 0), |
| 4456 | 56 | | CryptoConstants.SecretLen); |
| 4456 | 57 | | _cryptoProvider.MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(derivedSecret, 0), |
| 4456 | 58 | | CryptoConstants.SecretLen); |
| | 59 | | } |
| | 60 | |
|
| 400 | 61 | | if (_knownSecrets[bucket] != null) |
| | 62 | | { |
| | 63 | | // Free previous secret in this bucket if it exists |
| 104 | 64 | | FreeSecret(_knownSecrets[bucket]!.SecretPtr); |
| | 65 | | } |
| | 66 | |
|
| | 67 | | // Allocate secure memory for the new secret |
| 400 | 68 | | var securePtr = _cryptoProvider.MemoryAlloc(CryptoConstants.SecretLen); |
| | 69 | |
|
| | 70 | | // Lock memory to prevent swapping |
| 400 | 71 | | _cryptoProvider.MemoryLock(securePtr, CryptoConstants.SecretLen); |
| | 72 | |
|
| | 73 | | // Copy secret to secure memory |
| 400 | 74 | | Marshal.Copy(secret, 0, securePtr, CryptoConstants.SecretLen); |
| | 75 | |
|
| | 76 | | // Store in the appropriate bucket |
| 400 | 77 | | _knownSecrets[bucket] = new StoredSecret(index, securePtr); |
| | 78 | |
|
| 400 | 79 | | return true; |
| | 80 | | } |
| | 81 | |
|
| | 82 | | /// <inheritdoc/> |
| | 83 | | /// <exception cref="InvalidOperationException">Thrown when the secret cannot be derived</exception> |
| | 84 | | public Secret DeriveOldSecret(ulong index) |
| | 85 | | { |
| 84 | 86 | | Span<byte> derivedSecret = stackalloc byte[CryptoConstants.SecretLen]; |
| | 87 | | // Try to find a base secret that can derive this one |
| 1120 | 88 | | for (var b = 0; b < _knownSecrets.Length; b++) |
| | 89 | | { |
| 556 | 90 | | if (_knownSecrets[b] == null) |
| | 91 | | continue; |
| | 92 | |
|
| | 93 | | // Check if this secret can derive the requested index |
| 288 | 94 | | var mask = ~((1UL << b) - 1); |
| 288 | 95 | | if ((index & mask) != (_knownSecrets[b]!.Index & mask)) |
| | 96 | | { |
| | 97 | | continue; |
| | 98 | | } |
| | 99 | |
|
| | 100 | | // Found a base secret that can derive the requested one |
| 80 | 101 | | var baseSecret = new byte[CryptoConstants.Sha256HashLen]; |
| 80 | 102 | | Marshal.Copy(_knownSecrets[b]!.SecretPtr, baseSecret, 0, CryptoConstants.Sha256HashLen); |
| | 103 | |
|
| 80 | 104 | | DeriveSecret(baseSecret, b, index, derivedSecret); |
| | 105 | |
|
| | 106 | | // Securely wipe the temporary base secret |
| 80 | 107 | | _cryptoProvider |
| 80 | 108 | | .MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(baseSecret, 0), CryptoConstants.Sha256HashLen); |
| | 109 | |
|
| 80 | 110 | | return new Secret(derivedSecret.ToArray()); // Success |
| | 111 | | } |
| | 112 | |
|
| 4 | 113 | | throw new InvalidOperationException($"Cannot derive secret for index {index}"); |
| | 114 | | } |
| | 115 | |
|
| | 116 | | /// <inheritdoc/> |
| | 117 | | public void StorePerCommitmentSeed(Secret secret) |
| | 118 | | { |
| | 119 | | // Free existing seed if any |
| 0 | 120 | | if (_perCommitmentSeedPtr != IntPtr.Zero) |
| 0 | 121 | | FreeSecret(_perCommitmentSeedPtr); |
| | 122 | |
|
| | 123 | | // Allocate secure memory for the seed |
| 0 | 124 | | _perCommitmentSeedPtr = _cryptoProvider.MemoryAlloc(CryptoConstants.SecretLen); |
| 0 | 125 | | _cryptoProvider.MemoryLock(_perCommitmentSeedPtr, CryptoConstants.SecretLen); |
| 0 | 126 | | Marshal.Copy(secret, 0, _perCommitmentSeedPtr, CryptoConstants.SecretLen); |
| 0 | 127 | | } |
| | 128 | |
|
| | 129 | | /// <inheritdoc/> |
| | 130 | | /// <exception cref="InvalidOperationException">Thrown when the per-commitment seed is not stored</exception> |
| | 131 | | public Secret GetPerCommitmentSeed() |
| | 132 | | { |
| 0 | 133 | | if (_perCommitmentSeedPtr == IntPtr.Zero) |
| 0 | 134 | | throw new InvalidOperationException("Per-commitment seed not stored"); |
| | 135 | |
|
| 0 | 136 | | var seed = new byte[CryptoConstants.SecretLen]; |
| 0 | 137 | | Marshal.Copy(_perCommitmentSeedPtr, seed, 0, CryptoConstants.SecretLen); |
| 0 | 138 | | return seed; |
| | 139 | | } |
| | 140 | |
|
| | 141 | | /// <inheritdoc/> |
| | 142 | | public void StoreBasepointPrivateKey(BasepointType type, PrivKey privKey) |
| | 143 | | { |
| | 144 | | // Free existing key if any |
| 0 | 145 | | if (_basepointSecrets.TryGetValue(type, out var existingPtr) && existingPtr != IntPtr.Zero) |
| 0 | 146 | | FreeSecret(existingPtr); |
| | 147 | |
|
| | 148 | | // Allocate secure memory for the private key |
| 0 | 149 | | var securePtr = _cryptoProvider.MemoryAlloc(CryptoConstants.SecretLen); |
| 0 | 150 | | _cryptoProvider.MemoryLock(securePtr, CryptoConstants.SecretLen); |
| 0 | 151 | | Marshal.Copy(privKey, 0, securePtr, CryptoConstants.SecretLen); |
| | 152 | |
|
| 0 | 153 | | _basepointSecrets[type] = securePtr; |
| 0 | 154 | | } |
| | 155 | |
|
| | 156 | | /// <inheritdoc/> |
| | 157 | | /// <exception cref="InvalidOperationException">Thrown when the basepoint private key is not stored</exception> |
| | 158 | | public PrivKey GetBasepointPrivateKey(uint keyIndex, BasepointType type) |
| | 159 | | { |
| 0 | 160 | | throw new NotImplementedException("Getting basepoint private keys is not implemented yet."); |
| | 161 | | } |
| | 162 | |
|
| | 163 | | /// <inheritdoc/> |
| | 164 | | public void LoadFromIndex(uint index) |
| | 165 | | { |
| 0 | 166 | | throw new NotImplementedException("Loading from index is not implemented yet."); |
| | 167 | | } |
| | 168 | |
|
| | 169 | | private static int GetBucketIndex(ulong index) |
| | 170 | | { |
| 10272 | 171 | | for (var b = 0; b < 48; b++) |
| | 172 | | { |
| 5136 | 173 | | if (((index >> b) & 1) == 1) |
| | 174 | | { |
| 432 | 175 | | return b; |
| | 176 | | } |
| | 177 | | } |
| | 178 | |
|
| 0 | 179 | | return 48; // For index 0 (seed) |
| | 180 | | } |
| | 181 | |
|
| | 182 | | private static void DeriveSecret(ReadOnlySpan<byte> baseSecret, int bits, ulong index, Span<byte> derivedSecret) |
| | 183 | | { |
| 4568 | 184 | | using var sha256 = new Sha256(); |
| | 185 | |
|
| 4568 | 186 | | baseSecret.CopyTo(derivedSecret); |
| | 187 | |
|
| 287040 | 188 | | for (var b = bits - 1; b >= 0; b--) |
| | 189 | | { |
| 138952 | 190 | | if (((index >> b) & 1) == 0) |
| | 191 | | { |
| | 192 | | continue; |
| | 193 | | } |
| | 194 | |
|
| 69468 | 195 | | derivedSecret[b / 8] ^= (byte)(1 << (b % 8)); |
| | 196 | |
|
| 69468 | 197 | | sha256.AppendData(derivedSecret); |
| 69468 | 198 | | sha256.GetHashAndReset(derivedSecret); |
| | 199 | | } |
| 9136 | 200 | | } |
| | 201 | |
|
| | 202 | | /// <summary> |
| | 203 | | /// Securely frees a secret from memory |
| | 204 | | /// </summary> |
| | 205 | | private void FreeSecret(IntPtr secretPtr) |
| | 206 | | { |
| 400 | 207 | | if (secretPtr == IntPtr.Zero) |
| 0 | 208 | | return; |
| | 209 | |
|
| | 210 | | // Wipe memory before freeing |
| 400 | 211 | | _cryptoProvider.MemoryZero(secretPtr, CryptoConstants.Sha256HashLen); |
| | 212 | |
|
| | 213 | | // Unlock memory |
| 400 | 214 | | _cryptoProvider.MemoryUnlock(secretPtr, CryptoConstants.Sha256HashLen); |
| | 215 | |
|
| | 216 | | // Free memory |
| 400 | 217 | | _cryptoProvider.MemoryFree(secretPtr); |
| 400 | 218 | | } |
| | 219 | |
|
| | 220 | | private void ReleaseUnmanagedResources() |
| | 221 | | { |
| | 222 | | // Free all secrets |
| 4800 | 223 | | for (var i = 0; i < _knownSecrets.Length; i++) |
| | 224 | | { |
| 2352 | 225 | | if (_knownSecrets[i] == null) |
| | 226 | | continue; |
| | 227 | |
|
| 296 | 228 | | FreeSecret(_knownSecrets[i]!.SecretPtr); |
| 296 | 229 | | _knownSecrets[i] = null; |
| | 230 | | } |
| | 231 | |
|
| | 232 | | // Free per-commitment seed |
| 48 | 233 | | if (_perCommitmentSeedPtr != IntPtr.Zero) |
| | 234 | | { |
| 0 | 235 | | FreeSecret(_perCommitmentSeedPtr); |
| 0 | 236 | | _perCommitmentSeedPtr = IntPtr.Zero; |
| | 237 | | } |
| | 238 | |
|
| | 239 | | // Free basepoint secrets |
| 96 | 240 | | foreach (var kvp in _basepointSecrets) |
| | 241 | | { |
| 0 | 242 | | if (kvp.Value != IntPtr.Zero) |
| 0 | 243 | | FreeSecret(kvp.Value); |
| | 244 | | } |
| | 245 | |
|
| 48 | 246 | | _basepointSecrets.Clear(); |
| 48 | 247 | | } |
| | 248 | |
|
| | 249 | | private void Dispose(bool disposing) |
| | 250 | | { |
| 48 | 251 | | ReleaseUnmanagedResources(); |
| 48 | 252 | | if (disposing) |
| 48 | 253 | | _cryptoProvider.Dispose(); |
| 48 | 254 | | } |
| | 255 | |
|
| | 256 | | public void Dispose() |
| | 257 | | { |
| 48 | 258 | | Dispose(true); |
| 48 | 259 | | GC.SuppressFinalize(this); |
| 48 | 260 | | } |
| | 261 | |
|
| | 262 | | ~SecretStorageService() |
| | 263 | | { |
| 0 | 264 | | Dispose(false); |
| 0 | 265 | | } |
| | 266 | | } |