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