| | 1 | | using System.Diagnostics; |
| | 2 | |
|
| | 3 | | namespace NLightning.Infrastructure.Transport.Handshake.States; |
| | 4 | |
|
| | 5 | | using Common.Utils; |
| | 6 | | using Crypto.Functions; |
| | 7 | | using Crypto.Interfaces; |
| | 8 | | using Crypto.Primitives; |
| | 9 | | using Domain.Crypto.Constants; |
| | 10 | | using Enums; |
| | 11 | | using Interfaces; |
| | 12 | | using MessagePatterns; |
| | 13 | | using Protocol.Constants; |
| | 14 | |
|
| | 15 | | /// <inheritdoc/> |
| | 16 | | /// <remarks> See <see href="https://github.com/lightning/bolts/blob/master/08-transport.md">Lightning Bolt8</see> for s |
| | 17 | | internal sealed class HandshakeState : IHandshakeState |
| | 18 | | { |
| | 19 | | private const byte HANDSHAKE_VERSION = 0x00; |
| 4 | 20 | | private static readonly HandshakePattern s_handshakePattern = HandshakePattern.XK; |
| | 21 | |
|
| | 22 | | private readonly SymmetricState _state; |
| | 23 | | private readonly Role _role; |
| | 24 | | private readonly Role _initiator; |
| | 25 | | private readonly KeyPair _s; |
| 96 | 26 | | private readonly Queue<MessagePattern> _messagePatterns = new(); |
| | 27 | |
|
| | 28 | | private readonly IEcdh _dh; |
| | 29 | | private KeyPair? _e; |
| | 30 | | private byte[]? _re; |
| | 31 | | private byte[] _rs; |
| | 32 | | private bool _turnToWrite; |
| | 33 | | private bool _disposed; |
| | 34 | |
|
| 0 | 35 | | public NBitcoin.PubKey RemoteStaticPublicKey => new(_rs); |
| | 36 | |
|
| | 37 | | /// <summary> |
| | 38 | | /// Creates a new HandshakeState instance. |
| | 39 | | /// </summary> |
| | 40 | | /// <param name="initiator">If we are the initiator</param> |
| | 41 | | /// <param name="s">Local Static Private Key</param> |
| | 42 | | /// <param name="rs">Remote Static Public Key</param> |
| | 43 | | /// <param name="ecdh">A specific DH Function, or null to use the <see cref="Ecdh">Protocol Default</see></param> |
| | 44 | | /// <exception cref="ArgumentException"></exception> |
| 96 | 45 | | public HandshakeState(bool initiator, ReadOnlySpan<byte> s, ReadOnlySpan<byte> rs, IEcdh? ecdh = null) |
| | 46 | | { |
| 96 | 47 | | _dh = ecdh ?? new Ecdh(); |
| | 48 | |
|
| 96 | 49 | | if (s.IsEmpty) |
| | 50 | | { |
| 0 | 51 | | throw new ArgumentException("Local static private key required, but not provided.", nameof(s)); |
| | 52 | | } |
| | 53 | |
|
| 96 | 54 | | if (s.Length != CryptoConstants.PRIVKEY_LEN) |
| | 55 | | { |
| 0 | 56 | | throw new ArgumentException("Invalid local static private key.", nameof(s)); |
| | 57 | | } |
| | 58 | |
|
| 96 | 59 | | if (rs.IsEmpty) |
| | 60 | | { |
| 0 | 61 | | throw new ArgumentException("Remote static public key required, but not provided.", nameof(rs)); |
| | 62 | | } |
| | 63 | |
|
| 96 | 64 | | if (rs.Length != CryptoConstants.PUBKEY_LEN) |
| | 65 | | { |
| 0 | 66 | | throw new ArgumentException("Invalid remote static public key.", nameof(rs)); |
| | 67 | | } |
| | 68 | |
|
| 96 | 69 | | _state = new SymmetricState(ProtocolConstants.NAME); |
| 96 | 70 | | _state.MixHash(ProtocolConstants.PROLOGUE); |
| | 71 | |
|
| 96 | 72 | | _role = initiator ? Role.ALICE : Role.BOB; |
| 96 | 73 | | _initiator = Role.ALICE; |
| 96 | 74 | | _turnToWrite = initiator; |
| 96 | 75 | | _s = _dh.GenerateKeyPair(s); |
| 96 | 76 | | _rs = rs.ToArray(); |
| | 77 | |
|
| 96 | 78 | | ProcessPreMessages(); |
| 96 | 79 | | EnqueueMessages(); |
| 96 | 80 | | } |
| | 81 | |
|
| | 82 | | /// <inheritdoc/> |
| | 83 | | /// <exception cref="ObjectDisposedException">Thrown if the current instance has already been disposed.</exception> |
| | 84 | | /// <exception cref="InvalidOperationException">Thrown if the call to <see cref="ReadMessage"/> was expected or the |
| | 85 | | /// <exception cref="ArgumentException">Thrown if the output was greater than <see cref="ProtocolConstants.MAX_MESSA |
| | 86 | | public (int, byte[]?, Encryption.Transport?) WriteMessage(ReadOnlySpan<byte> payload, Span<byte> messageBuffer) |
| | 87 | | { |
| 92 | 88 | | ExceptionUtils.ThrowIfDisposed(_disposed, nameof(HandshakeState)); |
| | 89 | |
|
| 92 | 90 | | if (_messagePatterns.Count == 0) |
| | 91 | | { |
| 0 | 92 | | throw new InvalidOperationException("Cannot call WriteMessage after the handshake has already been completed |
| | 93 | | } |
| | 94 | |
|
| 92 | 95 | | var overhead = _messagePatterns.Peek().Overhead(CryptoConstants.PUBKEY_LEN, _state.HasKeys()); |
| 92 | 96 | | var ciphertextSize = payload.Length + overhead; |
| | 97 | |
|
| 92 | 98 | | if (ciphertextSize > ProtocolConstants.MAX_MESSAGE_LENGTH) |
| | 99 | | { |
| 0 | 100 | | throw new ArgumentException($"Noise message must be less than or equal to {ProtocolConstants.MAX_MESSAGE_LEN |
| | 101 | | } |
| | 102 | |
|
| 92 | 103 | | if (ciphertextSize > messageBuffer.Length) |
| | 104 | | { |
| 0 | 105 | | throw new ArgumentException("Message buffer does not have enough space to hold the ciphertext."); |
| | 106 | | } |
| | 107 | |
|
| 92 | 108 | | if (!_turnToWrite) |
| | 109 | | { |
| 0 | 110 | | throw new InvalidOperationException("Unexpected call to WriteMessage (should be ReadMessage)."); |
| | 111 | | } |
| | 112 | |
|
| 92 | 113 | | var next = _messagePatterns.Dequeue(); |
| 92 | 114 | | var messageBufferLength = messageBuffer.Length; |
| | 115 | |
|
| | 116 | | // write version to message buffer |
| 92 | 117 | | messageBuffer[0] = HANDSHAKE_VERSION; |
| | 118 | |
|
| 552 | 119 | | foreach (var token in next.Tokens) |
| | 120 | | { |
| | 121 | | switch (token) |
| | 122 | | { |
| 152 | 123 | | case Token.E: messageBuffer = WriteE(messageBuffer); break; |
| 32 | 124 | | case Token.S: messageBuffer = WriteS(messageBuffer); break; |
| 72 | 125 | | case Token.EE: DhAndMixKey(_e, _re); break; |
| 80 | 126 | | case Token.ES: ProcessEs(); break; |
| 32 | 127 | | case Token.SE: ProcessSe(); break; |
| 0 | 128 | | case Token.SS: DhAndMixKey(_s, _rs); break; |
| | 129 | | } |
| | 130 | | } |
| | 131 | |
|
| 92 | 132 | | var bytesWritten = _state.EncryptAndHash(payload, messageBuffer); |
| 92 | 133 | | var size = messageBufferLength - messageBuffer.Length + bytesWritten; |
| | 134 | |
|
| | 135 | | Debug.Assert(ciphertextSize == size); |
| | 136 | |
|
| 92 | 137 | | byte[]? handshakeHash = null; |
| 92 | 138 | | Encryption.Transport? transport = null; |
| | 139 | |
|
| 92 | 140 | | if (_messagePatterns.Count == 0) |
| | 141 | | { |
| 16 | 142 | | (handshakeHash, transport) = Split(); |
| | 143 | | } |
| | 144 | |
|
| 92 | 145 | | _turnToWrite = false; |
| 92 | 146 | | return (ciphertextSize, handshakeHash, transport); |
| | 147 | | } |
| | 148 | |
|
| | 149 | | /// <inheritdoc/> |
| | 150 | | /// <exception cref="ObjectDisposedException">Thrown if the current instance has already been disposed.</exception> |
| | 151 | | /// <exception cref="InvalidOperationException">Thrown if the call to <see cref="WriteMessage"/> was expected or the |
| | 152 | | /// <exception cref="ArgumentException">Thrown if the message was greater than <see cref="ProtocolConstants.MAX_MESS |
| | 153 | | /// <exception cref="System.Security.Cryptography.CryptographicException">Thrown if the decryption of the message ha |
| | 154 | | public (int, byte[]?, Encryption.Transport?) ReadMessage(ReadOnlySpan<byte> message, Span<byte> payloadBuffer) |
| | 155 | | { |
| 124 | 156 | | ExceptionUtils.ThrowIfDisposed(_disposed, nameof(HandshakeState)); |
| | 157 | |
|
| 124 | 158 | | if (_messagePatterns.Count == 0) |
| | 159 | | { |
| 0 | 160 | | throw new InvalidOperationException("Cannot call WriteMessage after the handshake has already been completed |
| | 161 | | } |
| | 162 | |
|
| 124 | 163 | | var overhead = _messagePatterns.Peek().Overhead(CryptoConstants.PUBKEY_LEN, _state.HasKeys()); |
| 124 | 164 | | var plaintextSize = message.Length - overhead; |
| | 165 | |
|
| 124 | 166 | | if (message.Length > ProtocolConstants.MAX_MESSAGE_LENGTH) |
| | 167 | | { |
| 0 | 168 | | throw new ArgumentException($"Noise message must be less than or equal to {ProtocolConstants.MAX_MESSAGE_LEN |
| | 169 | | } |
| | 170 | |
|
| 124 | 171 | | if (message.Length != overhead) |
| | 172 | | { |
| 12 | 173 | | throw new ArgumentException($"Noise message must be equal to {overhead} bytes in length."); |
| | 174 | | } |
| | 175 | |
|
| 112 | 176 | | if (plaintextSize > payloadBuffer.Length) |
| | 177 | | { |
| 0 | 178 | | throw new ArgumentException("Payload buffer does not have enough space to hold the plaintext."); |
| | 179 | | } |
| | 180 | |
|
| 112 | 181 | | if (_turnToWrite) |
| | 182 | | { |
| 0 | 183 | | throw new InvalidOperationException("Unexpected call to ReadMessage (should be WriteMessage)."); |
| | 184 | | } |
| | 185 | |
|
| 112 | 186 | | var next = _messagePatterns.Dequeue(); |
| 624 | 187 | | foreach (var token in next.Tokens) |
| | 188 | | { |
| | 189 | | switch (token) |
| | 190 | | { |
| 160 | 191 | | case Token.E: message = ReadE(message); break; |
| 52 | 192 | | case Token.S: message = ReadS(message); break; |
| 52 | 193 | | case Token.EE: DhAndMixKey(_e, _re); break; |
| 92 | 194 | | case Token.ES: ProcessEs(); break; |
| 44 | 195 | | case Token.SE: ProcessSe(); break; |
| 0 | 196 | | case Token.SS: DhAndMixKey(_s, _rs); break; |
| | 197 | | } |
| | 198 | | } |
| | 199 | |
|
| 88 | 200 | | var bytesRead = _state.DecryptAndHash(message, payloadBuffer); |
| | 201 | | Debug.Assert(bytesRead == plaintextSize); |
| | 202 | |
|
| 76 | 203 | | byte[]? handshakeHash = null; |
| 76 | 204 | | Encryption.Transport? transport = null; |
| | 205 | |
|
| 76 | 206 | | if (_messagePatterns.Count == 0) |
| | 207 | | { |
| 16 | 208 | | (handshakeHash, transport) = Split(); |
| | 209 | | } |
| | 210 | |
|
| 76 | 211 | | _turnToWrite = true; |
| 76 | 212 | | return (plaintextSize, handshakeHash, transport); |
| | 213 | | } |
| | 214 | |
|
| | 215 | | private void ProcessPreMessages() |
| | 216 | | { |
| 192 | 217 | | foreach (var token in s_handshakePattern.Initiator.Tokens) |
| | 218 | | { |
| 0 | 219 | | if (token == Token.S) |
| | 220 | | { |
| 0 | 221 | | _state.MixHash(_role == Role.ALICE ? _s.PublicKeyBytes : _rs); |
| | 222 | | } |
| | 223 | | } |
| | 224 | |
|
| 384 | 225 | | foreach (var token in s_handshakePattern.Responder.Tokens) |
| | 226 | | { |
| 96 | 227 | | if (token == Token.S) |
| | 228 | | { |
| 96 | 229 | | _state.MixHash(_role == Role.ALICE ? _rs : _s.PublicKeyBytes); |
| | 230 | | } |
| | 231 | | } |
| 96 | 232 | | } |
| | 233 | |
|
| | 234 | | private void EnqueueMessages() |
| | 235 | | { |
| 768 | 236 | | foreach (var pattern in s_handshakePattern.Patterns) |
| | 237 | | { |
| 288 | 238 | | _messagePatterns.Enqueue(pattern); |
| | 239 | | } |
| 96 | 240 | | } |
| | 241 | |
|
| | 242 | | private Span<byte> WriteE(Span<byte> buffer) |
| | 243 | | { |
| | 244 | | Debug.Assert(_e == null); |
| | 245 | |
|
| 76 | 246 | | _e = _dh.GenerateKeyPair(); |
| | 247 | | // Start from position 1, since we need our version there |
| 76 | 248 | | _e.PublicKeyBytes.CopyTo(buffer[1..]); |
| 76 | 249 | | _state.MixHash(_e.PublicKeyBytes); |
| | 250 | |
|
| | 251 | | // Don't forget to add our version length to the resulting Span |
| 76 | 252 | | return buffer[(_e.PublicKeyBytes.Length + 1)..]; |
| | 253 | | } |
| | 254 | |
|
| | 255 | | private Span<byte> WriteS(Span<byte> buffer) |
| | 256 | | { |
| | 257 | | Debug.Assert(_s != null); |
| | 258 | |
|
| | 259 | | // Start from position 1, since we need our version there |
| 16 | 260 | | var bytesWritten = _state.EncryptAndHash(_s.PublicKeyBytes, buffer[1..]); |
| | 261 | |
|
| | 262 | | // Don't forget to add our version length to the resulting Span |
| 16 | 263 | | return buffer[(bytesWritten + 1)..]; |
| | 264 | | } |
| | 265 | |
|
| | 266 | | private ReadOnlySpan<byte> ReadE(ReadOnlySpan<byte> buffer) |
| | 267 | | { |
| | 268 | | Debug.Assert(_re == null); |
| | 269 | |
|
| | 270 | | // Check version |
| 84 | 271 | | if (buffer[0] != HANDSHAKE_VERSION) |
| | 272 | | { |
| 8 | 273 | | throw new InvalidOperationException("Invalid handshake version."); |
| | 274 | | } |
| 76 | 275 | | buffer = buffer[1..]; |
| | 276 | |
|
| | 277 | | // Skip the byte from the version and get all bytes from pubkey |
| 76 | 278 | | _re = buffer[..CryptoConstants.PUBKEY_LEN].ToArray(); |
| 76 | 279 | | _state.MixHash(_re); |
| | 280 | |
|
| 76 | 281 | | return buffer[_re.Length..]; |
| | 282 | | } |
| | 283 | |
|
| | 284 | | private ReadOnlySpan<byte> ReadS(ReadOnlySpan<byte> message) |
| | 285 | | { |
| | 286 | | // Check version |
| 28 | 287 | | if (message[0] != HANDSHAKE_VERSION) |
| | 288 | | { |
| 0 | 289 | | throw new InvalidOperationException("Invalid handshake version."); |
| | 290 | | } |
| 28 | 291 | | message = message[1..]; |
| | 292 | |
|
| 28 | 293 | | var length = _state.HasKeys() ? CryptoConstants.PUBKEY_LEN + CryptoConstants.CHACHA20_POLY1305_TAG_LEN : CryptoC |
| 28 | 294 | | var temp = message[..length]; |
| | 295 | |
|
| 28 | 296 | | _rs = new byte[CryptoConstants.PUBKEY_LEN]; |
| 28 | 297 | | _state.DecryptAndHash(temp, _rs); |
| | 298 | |
|
| 24 | 299 | | return message[length..]; |
| | 300 | | } |
| | 301 | |
|
| | 302 | | private void ProcessEs() |
| | 303 | | { |
| 88 | 304 | | if (_role == Role.ALICE) |
| | 305 | | { |
| 40 | 306 | | DhAndMixKey(_e, _rs); |
| | 307 | | } |
| | 308 | | else |
| | 309 | | { |
| 48 | 310 | | DhAndMixKey(_s, _re); |
| | 311 | | } |
| 44 | 312 | | } |
| | 313 | |
|
| | 314 | | private void ProcessSe() |
| | 315 | | { |
| 40 | 316 | | if (_role == Role.ALICE) |
| | 317 | | { |
| 16 | 318 | | DhAndMixKey(_s, _re); |
| | 319 | | } |
| | 320 | | else |
| | 321 | | { |
| 24 | 322 | | DhAndMixKey(_e, _rs); |
| | 323 | | } |
| 20 | 324 | | } |
| | 325 | |
|
| | 326 | | private (byte[], Encryption.Transport) Split() |
| | 327 | | { |
| 32 | 328 | | var (c1, c2) = _state.Split(); |
| | 329 | |
|
| 32 | 330 | | var handshakeHash = _state.GetHandshakeHash(); |
| 32 | 331 | | var transport = new Encryption.Transport(_role == _initiator, c1, c2); |
| | 332 | |
|
| 32 | 333 | | Clear(); |
| | 334 | |
|
| 32 | 335 | | return (handshakeHash, transport); |
| | 336 | | } |
| | 337 | |
|
| | 338 | | private void DhAndMixKey(KeyPair? keyPair, ReadOnlySpan<byte> publicKey) |
| | 339 | | { |
| | 340 | | Debug.Assert(keyPair != null); |
| | 341 | | Debug.Assert(!publicKey.IsEmpty); |
| | 342 | |
|
| 192 | 343 | | Span<byte> sharedKey = stackalloc byte[CryptoConstants.PRIVKEY_LEN]; |
| 192 | 344 | | _dh.SecP256K1Dh(keyPair.PrivateKey, publicKey, sharedKey); |
| 180 | 345 | | _state.MixKey(sharedKey); |
| 180 | 346 | | } |
| | 347 | |
|
| | 348 | | private void Clear() |
| | 349 | | { |
| 128 | 350 | | _state.Dispose(); |
| 128 | 351 | | _e?.Dispose(); |
| 128 | 352 | | _s.Dispose(); |
| 128 | 353 | | } |
| | 354 | |
|
| | 355 | | private enum Role |
| | 356 | | { |
| | 357 | | ALICE, |
| | 358 | | BOB |
| | 359 | | } |
| | 360 | |
|
| | 361 | | public void Dispose() |
| | 362 | | { |
| 96 | 363 | | if (_disposed) |
| | 364 | | { |
| 0 | 365 | | return; |
| | 366 | | } |
| | 367 | |
|
| 96 | 368 | | Clear(); |
| 96 | 369 | | GC.SuppressFinalize(this); |
| | 370 | |
|
| 96 | 371 | | _disposed = true; |
| 96 | 372 | | } |
| | 373 | |
|
| | 374 | | ~HandshakeState() |
| | 375 | | { |
| 0 | 376 | | Dispose(); |
| 0 | 377 | | } |
| | 378 | | } |