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