| | 1 | | using System.Runtime.InteropServices; |
| | 2 | | using System.Runtime.Serialization; |
| | 3 | | using System.Text; |
| | 4 | | using System.Text.Json; |
| | 5 | | using NBitcoin; |
| | 6 | |
|
| | 7 | | namespace NLightning.Infrastructure.Bitcoin.Managers; |
| | 8 | |
|
| | 9 | | using Domain.Bitcoin.ValueObjects; |
| | 10 | | using Domain.Crypto.Constants; |
| | 11 | | using Domain.Crypto.ValueObjects; |
| | 12 | | using Domain.Protocol.Interfaces; |
| | 13 | | using Domain.Protocol.ValueObjects; |
| | 14 | | using Infrastructure.Crypto.Ciphers; |
| | 15 | | using Infrastructure.Crypto.Factories; |
| | 16 | | using Infrastructure.Crypto.Hashes; |
| | 17 | | using Node.Models; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Manages a securely stored private key using protected memory allocation. |
| | 21 | | /// This class ensures that the private key remains inaccessible from regular memory |
| | 22 | | /// and is securely wiped when no longer needed. |
| | 23 | | /// </summary> |
| | 24 | | public class SecureKeyManager : ISecureKeyManager, IDisposable |
| | 25 | | { |
| 0 | 26 | | private static readonly byte[] s_salt = |
| 0 | 27 | | [ |
| 0 | 28 | | 0xFF, 0x1D, 0x3B, 0xF5, 0x24, 0xA2, 0xB7, 0xA9, |
| 0 | 29 | | 0xC3, 0x1B, 0x1F, 0x58, 0xE9, 0x48, 0xB5, 0x69 |
| 0 | 30 | | ]; |
| | 31 | |
|
| | 32 | | private readonly string _filePath; |
| 0 | 33 | | private readonly object _lastUsedIndexLock = new(); |
| | 34 | | private readonly Network _network; |
| 0 | 35 | | private readonly KeyPath _keyPath = new("m/6425'/0'/0'/0"); |
| | 36 | |
|
| | 37 | | private uint _lastUsedIndex; |
| | 38 | | private ulong _privateKeyLength; |
| | 39 | | private IntPtr _securePrivateKeyPtr; |
| | 40 | |
|
| 0 | 41 | | public BitcoinKeyPath KeyPath => _keyPath.ToBytes(); |
| | 42 | |
|
| 0 | 43 | | public string OutputDescriptor { get; init; } |
| | 44 | |
|
| | 45 | | /// <summary> |
| | 46 | | /// Manages secure key operations for generating and managing cryptographic keys. |
| | 47 | | /// Provides functionality to safely store, load, and derive secure keys protected in memory. |
| | 48 | | /// </summary> |
| | 49 | | /// <param name="privateKey">The private key to be managed.</param> |
| | 50 | | /// <param name="network">The network associated with the private key.</param> |
| | 51 | | /// <param name="filePath">The file path for storing the key data.</param> |
| 0 | 52 | | public SecureKeyManager(byte[] privateKey, BitcoinNetwork network, string filePath) |
| | 53 | | { |
| 0 | 54 | | _privateKeyLength = (ulong)privateKey.Length; |
| | 55 | |
|
| 0 | 56 | | using var cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| | 57 | |
|
| | 58 | | // Allocate secure memory |
| 0 | 59 | | _securePrivateKeyPtr = cryptoProvider.MemoryAlloc(_privateKeyLength); |
| | 60 | |
|
| | 61 | | // Lock the memory to prevent swapping |
| 0 | 62 | | if (cryptoProvider.MemoryLock(_securePrivateKeyPtr, _privateKeyLength) == -1) |
| 0 | 63 | | throw new InvalidOperationException("Failed to lock memory."); |
| | 64 | |
|
| | 65 | | // Copy the private key to secure memory |
| 0 | 66 | | Marshal.Copy(privateKey, 0, _securePrivateKeyPtr, (int)_privateKeyLength); |
| | 67 | |
|
| | 68 | | // Get Output Descriptor |
| 0 | 69 | | _network = Network.GetNetwork(network) |
| 0 | 70 | | ?? throw new ArgumentException("Invalid network specified.", nameof(network)); |
| 0 | 71 | | var extKey = new ExtKey(new Key(privateKey), network.ChainHash); |
| 0 | 72 | | var xpub = extKey.Neuter().ToString(_network); |
| 0 | 73 | | var fingerprint = extKey.GetPublicKey().GetHDFingerPrint(); |
| | 74 | |
|
| 0 | 75 | | OutputDescriptor = $"wpkh([{fingerprint}/{KeyPath}/*]{xpub}/0/*)"; |
| | 76 | |
|
| | 77 | | // Securely wipe the original key from regular memory |
| 0 | 78 | | cryptoProvider.MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(privateKey, 0), _privateKeyLength); |
| | 79 | |
|
| 0 | 80 | | _filePath = filePath; |
| 0 | 81 | | } |
| | 82 | |
|
| | 83 | | public ExtPrivKey GetNextKey(out uint index) |
| | 84 | | { |
| 0 | 85 | | lock (_lastUsedIndexLock) |
| | 86 | | { |
| 0 | 87 | | _lastUsedIndex++; |
| 0 | 88 | | index = _lastUsedIndex; |
| 0 | 89 | | } |
| | 90 | |
|
| | 91 | | // Derive the key at m/6425'/0'/0'/0/index |
| 0 | 92 | | var masterKey = GetMasterKey(); |
| 0 | 93 | | var derivedKey = masterKey.Derive(_keyPath.Derive(index)); |
| | 94 | |
|
| 0 | 95 | | _ = UpdateLastUsedIndexOnFile().ContinueWith(task => |
| 0 | 96 | | { |
| 0 | 97 | | if (task.IsFaulted) |
| 0 | 98 | | Console.Error.WriteLine($"Failed to update last used index on file: {task.Exception.Message}"); |
| 0 | 99 | | }, TaskContinuationOptions.OnlyOnFaulted); |
| | 100 | |
|
| 0 | 101 | | return derivedKey.ToBytes(); |
| | 102 | | } |
| | 103 | |
|
| | 104 | | public ExtPrivKey GetKeyAtIndex(uint index) |
| | 105 | | { |
| 0 | 106 | | var masterKey = GetMasterKey(); |
| 0 | 107 | | return masterKey.Derive(_keyPath.Derive(index)).ToBytes(); |
| | 108 | | } |
| | 109 | |
|
| | 110 | | public CryptoKeyPair GetNodeKeyPair() |
| | 111 | | { |
| 0 | 112 | | var masterKey = GetMasterKey(); |
| 0 | 113 | | return new CryptoKeyPair(masterKey.PrivateKey.ToBytes(), masterKey.PrivateKey.PubKey.ToBytes()); |
| | 114 | | } |
| | 115 | |
|
| | 116 | | public CompactPubKey GetNodePubKey() |
| | 117 | | { |
| 0 | 118 | | var masterKey = GetMasterKey(); |
| 0 | 119 | | return masterKey.PrivateKey.PubKey.ToBytes(); |
| | 120 | | } |
| | 121 | |
|
| | 122 | | public async Task UpdateLastUsedIndexOnFile() |
| | 123 | | { |
| 0 | 124 | | var jsonString = await File.ReadAllTextAsync(_filePath); |
| 0 | 125 | | var data = JsonSerializer.Deserialize<KeyFileData>(jsonString) |
| 0 | 126 | | ?? throw new SerializationException("Invalid key file"); |
| | 127 | |
|
| 0 | 128 | | lock (_lastUsedIndexLock) |
| | 129 | | { |
| 0 | 130 | | data.LastUsedIndex = _lastUsedIndex; |
| 0 | 131 | | } |
| | 132 | |
|
| 0 | 133 | | jsonString = JsonSerializer.Serialize(data); |
| | 134 | |
|
| 0 | 135 | | await File.WriteAllTextAsync(_filePath, jsonString); |
| 0 | 136 | | } |
| | 137 | |
|
| | 138 | | public void SaveToFile(string password) |
| | 139 | | { |
| 0 | 140 | | lock (_lastUsedIndexLock) |
| | 141 | | { |
| 0 | 142 | | var extKey = GetMasterKey(); |
| 0 | 143 | | var extKeyBytes = Encoding.UTF8.GetBytes(extKey.ToString(_network)); |
| | 144 | |
|
| 0 | 145 | | Span<byte> key = stackalloc byte[CryptoConstants.PrivkeyLen]; |
| 0 | 146 | | Span<byte> nonce = stackalloc byte[CryptoConstants.Xchacha20Poly1305NonceLen]; |
| 0 | 147 | | Span<byte> cipherText = stackalloc byte[extKeyBytes.Length + CryptoConstants.Xchacha20Poly1305TagLen]; |
| | 148 | |
|
| 0 | 149 | | using var argon2Id = new Argon2Id(); |
| 0 | 150 | | argon2Id.DeriveKeyFromPasswordAndSalt(password, s_salt, key); |
| | 151 | |
|
| 0 | 152 | | using var xChaCha20Poly1305 = new XChaCha20Poly1305(); |
| 0 | 153 | | xChaCha20Poly1305.Encrypt(key, nonce, ReadOnlySpan<byte>.Empty, extKeyBytes, cipherText); |
| | 154 | |
|
| 0 | 155 | | var data = new KeyFileData |
| 0 | 156 | | { |
| 0 | 157 | | Network = _network.ToString(), |
| 0 | 158 | | LastUsedIndex = _lastUsedIndex, |
| 0 | 159 | | Descriptor = OutputDescriptor, |
| 0 | 160 | | EncryptedExtKey = Convert.ToBase64String(cipherText) |
| 0 | 161 | | }; |
| 0 | 162 | | var json = JsonSerializer.Serialize(data); |
| 0 | 163 | | File.WriteAllText(_filePath, json); |
| | 164 | | } |
| 0 | 165 | | } |
| | 166 | |
|
| | 167 | | public static SecureKeyManager FromMnemonic(string mnemonic, string passphrase, BitcoinNetwork network, |
| | 168 | | string? filePath = null) |
| | 169 | | { |
| 0 | 170 | | if (string.IsNullOrWhiteSpace(filePath)) |
| 0 | 171 | | filePath = GetKeyFilePath(network); |
| | 172 | |
|
| 0 | 173 | | var mnemonicObj = new Mnemonic(mnemonic, Wordlist.English); |
| 0 | 174 | | var extKey = mnemonicObj.DeriveExtKey(passphrase); |
| 0 | 175 | | return new SecureKeyManager(extKey.PrivateKey.ToBytes(), network, filePath); |
| | 176 | | } |
| | 177 | |
|
| | 178 | | public static SecureKeyManager FromFilePath(string filePath, BitcoinNetwork expectedNetwork, string password) |
| | 179 | | { |
| 0 | 180 | | var jsonString = File.ReadAllText(filePath); |
| 0 | 181 | | var data = JsonSerializer.Deserialize<KeyFileData>(jsonString) |
| 0 | 182 | | ?? throw new SerializationException("Invalid key file"); |
| | 183 | |
|
| 0 | 184 | | if (expectedNetwork != data.Network.ToLowerInvariant()) |
| 0 | 185 | | throw new Exception($"Invalid network. Expected {expectedNetwork}, but got {data.Network}"); |
| | 186 | |
|
| 0 | 187 | | var network = Network.GetNetwork(expectedNetwork) |
| 0 | 188 | | ?? throw new ArgumentException("Invalid network specified.", nameof(expectedNetwork)); |
| | 189 | |
|
| 0 | 190 | | var encryptedExtKey = Convert.FromBase64String(data.EncryptedExtKey); |
| 0 | 191 | | Span<byte> nonce = stackalloc byte[CryptoConstants.Xchacha20Poly1305NonceLen]; |
| | 192 | |
|
| 0 | 193 | | Span<byte> key = stackalloc byte[CryptoConstants.PrivkeyLen]; |
| 0 | 194 | | using var argon2Id = new Argon2Id(); |
| 0 | 195 | | argon2Id.DeriveKeyFromPasswordAndSalt(password, s_salt, key); |
| | 196 | |
|
| 0 | 197 | | Span<byte> extKeyBytes = stackalloc byte[encryptedExtKey.Length - CryptoConstants.Xchacha20Poly1305TagLen]; |
| 0 | 198 | | using var xChaCha20Poly1305 = new XChaCha20Poly1305(); |
| 0 | 199 | | xChaCha20Poly1305.Decrypt(key, nonce, ReadOnlySpan<byte>.Empty, encryptedExtKey, extKeyBytes); |
| | 200 | |
|
| 0 | 201 | | var extKeyStr = Encoding.UTF8.GetString(extKeyBytes); |
| 0 | 202 | | var extKey = ExtKey.Parse(extKeyStr, network); |
| | 203 | |
|
| 0 | 204 | | return new SecureKeyManager(extKey.PrivateKey.ToBytes(), expectedNetwork, filePath) |
| 0 | 205 | | { |
| 0 | 206 | | _lastUsedIndex = data.LastUsedIndex, |
| 0 | 207 | | OutputDescriptor = data.Descriptor |
| 0 | 208 | | }; |
| 0 | 209 | | } |
| | 210 | |
|
| | 211 | | /// <summary> |
| | 212 | | /// Gets the path for the Key file |
| | 213 | | /// </summary> |
| | 214 | | public static string GetKeyFilePath(string network) |
| | 215 | | { |
| 0 | 216 | | var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 0 | 217 | | var networkDir = Path.Combine(homeDir, ".nltg", network); |
| 0 | 218 | | Directory.CreateDirectory(networkDir); // Ensure directory exists |
| 0 | 219 | | return Path.Combine(networkDir, "nltg.key.json"); //DaemonConstants.KeyFile); |
| | 220 | | } |
| | 221 | |
|
| | 222 | | private ExtKey GetMasterKey() |
| | 223 | | { |
| 0 | 224 | | return new ExtKey(new Key(GetPrivateKeyBytes()), _network.GenesisHash.ToBytes()); |
| | 225 | | } |
| | 226 | |
|
| | 227 | | private void ReleaseUnmanagedResources() |
| | 228 | | { |
| 0 | 229 | | if (_securePrivateKeyPtr == IntPtr.Zero) |
| 0 | 230 | | return; |
| | 231 | |
|
| 0 | 232 | | using var cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| | 233 | |
|
| | 234 | | // Securely wipe the memory before freeing it |
| 0 | 235 | | cryptoProvider.MemoryZero(_securePrivateKeyPtr, _privateKeyLength); |
| | 236 | |
|
| | 237 | | // Unlock the memory |
| 0 | 238 | | cryptoProvider.MemoryUnlock(_securePrivateKeyPtr, _privateKeyLength); |
| | 239 | |
|
| | 240 | | // MemoryFree the memory |
| 0 | 241 | | cryptoProvider.MemoryFree(_securePrivateKeyPtr); |
| | 242 | |
|
| 0 | 243 | | _privateKeyLength = 0; |
| 0 | 244 | | _securePrivateKeyPtr = IntPtr.Zero; |
| 0 | 245 | | } |
| | 246 | |
|
| | 247 | | /// <summary> |
| | 248 | | /// Retrieves the private key stored in secure memory. |
| | 249 | | /// </summary> |
| | 250 | | /// <returns>The private key as a byte array.</returns> |
| | 251 | | /// <exception cref="InvalidOperationException">Thrown if the key is not initialized.</exception> |
| | 252 | | private byte[] GetPrivateKeyBytes() |
| | 253 | | { |
| 0 | 254 | | if (_securePrivateKeyPtr == IntPtr.Zero) |
| 0 | 255 | | throw new InvalidOperationException("Secure key is not initialized."); |
| | 256 | |
|
| 0 | 257 | | var privateKey = new byte[_privateKeyLength]; |
| 0 | 258 | | Marshal.Copy(_securePrivateKeyPtr, privateKey, 0, (int)_privateKeyLength); |
| | 259 | |
|
| 0 | 260 | | return privateKey; |
| | 261 | | } |
| | 262 | |
|
| | 263 | | public void Dispose() |
| | 264 | | { |
| 0 | 265 | | ReleaseUnmanagedResources(); |
| 0 | 266 | | GC.SuppressFinalize(this); |
| 0 | 267 | | } |
| | 268 | |
|
| | 269 | | ~SecureKeyManager() |
| | 270 | | { |
| 0 | 271 | | ReleaseUnmanagedResources(); |
| 0 | 272 | | } |
| | 273 | | } |