-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathClient.cs
More file actions
639 lines (520 loc) · 26.6 KB
/
Client.cs
File metadata and controls
639 lines (520 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using KSSHServer.KexAlgorithms;
using KSSHServer.Packets;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Security.Cryptography;
using System.Linq;
using KSSHServer.Packets.SSHServer.Packets;
namespace KSSHServer
{
public class Client
{
private ILogger _Logger;
private Socket _Socket;
private bool _ProtocolVersionExchangeComplete = false;
private string _ProtocolVersionExchange;
private Packets.KexInit _KexInitServerToClient = new Packets.KexInit();
private Packets.KexInit _KexInitClientToServer = null;
private ExchangeContext _ActiveExchangeContext = new ExchangeContext();
private ExchangeContext _PendingExchangeContext = new ExchangeContext();
private byte[] _SessionId = null;
private int _CurrentSentPacketNumber = -1;
private int _CurrentReceivedPacketNumber = -1;
private long _TotalBytesTransferred = 0;
private DateTime _KeyTimeout = DateTime.UtcNow.AddHours(1);
public Client(Socket socket, ILogger logger)
{
_Socket = socket;
_Logger = logger;
_KexInitServerToClient.KexAlgorithms.AddRange(Server.GetNames(Server.SupportedKexAlgorithms));
_KexInitServerToClient.ServerHostKeyAlgorithms.AddRange(Server.GetNames(Server.SupportedHostKeyAlgorithms));
_KexInitServerToClient.EncryptionAlgorithmsClientToServer.AddRange(Server.GetNames(Server.SupportedCiphers));
_KexInitServerToClient.EncryptionAlgorithmsServerToClient.AddRange(Server.GetNames(Server.SupportedCiphers));
_KexInitServerToClient.MacAlgorithmsClientToServer.AddRange(Server.GetNames(Server.SupportedMACAlgorithms));
_KexInitServerToClient.MacAlgorithmsServerToClient.AddRange(Server.GetNames(Server.SupportedMACAlgorithms));
_KexInitServerToClient.CompressionAlgorithmsClientToServer.AddRange(Server.GetNames(Server.SupportedCompressions));
_KexInitServerToClient.CompressionAlgorithmsServerToClient.AddRange(Server.GetNames(Server.SupportedCompressions));
const int socketBufferSize = 2 * Packets.Packet.MaxPacketSize;
_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, socketBufferSize);
_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, socketBufferSize);
_Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
Send($"{ServerConstants.ProtocolVersionExchange}\r\n");
// 7.1. Algorithm Negotiation - https://tools.ietf.org/html/rfc4253#section-7.1
Send(_KexInitServerToClient);
}
private void Send(Packet packet)
{
packet.PacketSequence = GetSentPacketNumber();
byte[] payload = _ActiveExchangeContext.CompressionServerToClient.Compress(packet.GetBytes());
uint blockSize = _ActiveExchangeContext.CipherServerToClient.BlockSize;
byte paddingLength = (byte)(blockSize - (payload.Length + 5) % blockSize);
if (paddingLength < 4)
paddingLength += (byte)blockSize;
byte[] padding = new byte[paddingLength];
RandomNumberGenerator.Create().GetBytes(padding);
uint packetLength = (uint)(payload.Length + paddingLength + 1);
using (ByteWriter writer = new ByteWriter())
{
writer.WriteUInt32(packetLength);
writer.WriteByte(paddingLength);
writer.WriteRawBytes(payload);
writer.WriteRawBytes(padding);
payload = writer.ToByteArray();
}
byte[] encryptedPayload = _ActiveExchangeContext.CipherServerToClient.Encrypt(payload);
if (_ActiveExchangeContext.MACAlgorithmServerToClient != null)
{
byte[] mac = _ActiveExchangeContext.MACAlgorithmServerToClient.ComputeHash(packet.PacketSequence, payload);
encryptedPayload = encryptedPayload.Concat(mac).ToArray();
}
Send(encryptedPayload);
this.ConsiderReExchange();
}
private void Send(string message)
{
_Logger.LogDebug($"Sending raw string: {message.Trim()}");
Send(Encoding.UTF8.GetBytes(message));
}
private void Send(byte[] message)
{
if (!IsConnected())
return;
// Increase bytes transferred
_TotalBytesTransferred += message.Length;
_Socket.Send(message);
}
public bool IsConnected()
{
return (_Socket != null);
}
public void Poll()
{
if (!IsConnected())
return;
bool dataAvailable = _Socket.Poll(0, SelectMode.SelectRead);
if (dataAvailable)
{
int read = _Socket.Available;
if (read < 1)
{
Disconnect(DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "The client disconnected.");
return;
}
if (!_ProtocolVersionExchangeComplete)
{
try
{
ReadProtocolVersionExchange();
if (_ProtocolVersionExchangeComplete)
{
_Logger.LogDebug($"Received ProtocolVersionExchange:{_ProtocolVersionExchange}");
ValidateProtocolVersionExchange();
}
}
catch (System.Exception)
{
Disconnect(DisconnectReason.SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, "Failed to get the protocol version exchange.");
return;
}
}
if (_ProtocolVersionExchangeComplete)
{
try
{
Packets.Packet packet = ReadPacket();
while (packet != null)
{
_Logger.LogDebug($"Received Packet: {packet.PacketType}");
// Handle specific packet
HandlePacket(packet);
// Read next packet
packet = ReadPacket();
}
ConsiderReExchange();
}
catch (KSSHServerException ex)
{
_Logger.LogError(ex.Message);
Disconnect(ex.Reason, ex.Message);
return;
}
}
}
}
private uint GetSentPacketNumber()
{
return (uint)Interlocked.Increment(ref _CurrentSentPacketNumber);
}
private uint GetReceivedPacketNumber()
{
return (uint)Interlocked.Increment(ref _CurrentReceivedPacketNumber);
}
// Read 1 byte from the socket until \r\n
private void ReadProtocolVersionExchange()
{
NetworkStream stream = new NetworkStream(_Socket, false);
string result = null;
List<byte> data = new List<byte>();
bool foundCR = false;
int val = stream.ReadByte();
while (val != -1)
{
if (foundCR && (val == '\n'))
{
result = Encoding.UTF8.GetString(data.ToArray());
_ProtocolVersionExchangeComplete = true;
break;
}
if (val == '\r')
{
foundCR = true;
}
else
{
foundCR = false;
data.Add((byte)val);
}
val = stream.ReadByte();
}
_ProtocolVersionExchange += result;
}
private void HandlePacket(Packet packet)
{
try
{
HandleSpecificPacket((dynamic)packet);
}
catch (RuntimeBinderException)
{
_Logger.LogWarning($"Unhandled packet type: {packet.PacketType}");
Unimplemented unimplemented = new Unimplemented()
{
RejectedPacketNumber = packet.PacketSequence
};
Send(unimplemented);
}
}
private void HandleSpecificPacket(KexDHInit packet)
{
_Logger.LogDebug("Received KexDHInit");
if ((_PendingExchangeContext == null) || (_PendingExchangeContext.KexAlgorithm == null))
{
throw new KSSHServerException(DisconnectReason.SSH_DISCONNECT_PROTOCOL_ERROR, "Server did not receive SSH_MSG_KEX_INIT as expected.");
}
// 1. C generates a random number x (1 < x < q) and computes e = g ^ x mod p. C sends e to S.
// 2. S receives e. It computes K = e^y mod p
byte[] sharedSecret = _PendingExchangeContext.KexAlgorithm.DecryptKeyExchange(packet.ClientValue);
// 2. S generates a random number y (0 < y < q) and computes f = g ^ y mod p.
byte[] serverKeyExchange = _PendingExchangeContext.KexAlgorithm.CreateKeyExchange();
byte[] hostKey = _PendingExchangeContext.HostKeyAlgorithm.CreateKeyAndCertificatesData();
// H = hash(V_C || V_S || I_C || I_S || K_S || e || f || K)
byte[] exchangeHash = ComputeExchangeHash(
_PendingExchangeContext.KexAlgorithm,
hostKey,
packet.ClientValue,
serverKeyExchange,
sharedSecret);
if (_SessionId == null)
_SessionId = exchangeHash;
// https://tools.ietf.org/html/rfc4253#section-7.2
// Initial IV client to server: HASH(K || H || "A" || session_id)
// (Here K is encoded as mpint and "A" as byte and session_id as raw
// data. "A" means the single character A, ASCII 65).
byte[] clientCipherIV = ComputeEncryptionKey(
_PendingExchangeContext.KexAlgorithm,
exchangeHash,
_PendingExchangeContext.CipherClientToServer.BlockSize,
sharedSecret, 'A');
// Initial IV server to client: HASH(K || H || "B" || session_id)
byte[] serverCipherIV = ComputeEncryptionKey(
_PendingExchangeContext.KexAlgorithm,
exchangeHash,
_PendingExchangeContext.CipherServerToClient.BlockSize,
sharedSecret, 'B');
// Encryption key client to server: HASH(K || H || "C" || session_id)
byte[] clientCipherKey = ComputeEncryptionKey(
_PendingExchangeContext.KexAlgorithm,
exchangeHash,
_PendingExchangeContext.CipherClientToServer.KeySize,
sharedSecret, 'C');
// Encryption key server to client: HASH(K || H || "D" || session_id)
byte[] serverCipherKey = ComputeEncryptionKey(
_PendingExchangeContext.KexAlgorithm,
exchangeHash,
_PendingExchangeContext.CipherServerToClient.KeySize,
sharedSecret, 'D');
// Integrity key client to server: HASH(K || H || "E" || session_id)
byte[] clientHmacKey = ComputeEncryptionKey(
_PendingExchangeContext.KexAlgorithm,
exchangeHash,
_PendingExchangeContext.MACAlgorithmClientToServer.KeySize,
sharedSecret, 'E');
// Integrity key server to client: HASH(K || H || "F" || session_id)
byte[] serverHmacKey = ComputeEncryptionKey(
_PendingExchangeContext.KexAlgorithm,
exchangeHash,
_PendingExchangeContext.MACAlgorithmServerToClient.KeySize,
sharedSecret, 'F');
// Set all keys we just generated
_PendingExchangeContext.CipherClientToServer.SetKey(clientCipherKey, clientCipherIV);
_PendingExchangeContext.CipherServerToClient.SetKey(serverCipherKey, serverCipherIV);
_PendingExchangeContext.MACAlgorithmClientToServer.SetKey(clientHmacKey);
_PendingExchangeContext.MACAlgorithmServerToClient.SetKey(serverHmacKey);
// Send reply to client!
KexDHReply reply = new KexDHReply()
{
ServerHostKey = hostKey,
ServerValue = serverKeyExchange,
Signature = _PendingExchangeContext.HostKeyAlgorithm.CreateSignatureData(exchangeHash)
};
Send(reply);
Send(new NewKeys());
}
private void HandleSpecificPacket(KexInit packet)
{
_Logger.LogDebug("Received KexInit packet.");
if (_PendingExchangeContext == null)
{
_Logger.LogDebug("Re-exchanging keys!");
_PendingExchangeContext = new ExchangeContext();
Send(_KexInitServerToClient);
}
_KexInitClientToServer = packet;
_PendingExchangeContext.KexAlgorithm = packet.PickKexAlgorithm();
_PendingExchangeContext.HostKeyAlgorithm = packet.PickHostKeyAlgorithm();
_PendingExchangeContext.CipherClientToServer = packet.PickCipherClientToServer();
_PendingExchangeContext.CipherServerToClient = packet.PickCipherServerToClient();
_PendingExchangeContext.MACAlgorithmClientToServer = packet.PickMACAlgorithmClientToServer();
_PendingExchangeContext.MACAlgorithmServerToClient = packet.PickMACAlgorithmServerToClient();
_PendingExchangeContext.CompressionClientToServer = packet.PickCompressionAlgorithmClientToServer();
_PendingExchangeContext.CompressionServerToClient = packet.PickCompressionAlgorithmServerToClient();
_Logger.LogDebug($"Selected KexAlgorithm: {_PendingExchangeContext.KexAlgorithm.Name}");
_Logger.LogDebug($"Selected HostKeyAlgorithm: {_PendingExchangeContext.HostKeyAlgorithm.Name}");
_Logger.LogDebug($"Selected CipherClientToServer: {_PendingExchangeContext.CipherClientToServer.Name}");
_Logger.LogDebug($"Selected CipherServerToClient: {_PendingExchangeContext.CipherServerToClient.Name}");
_Logger.LogDebug($"Selected MACAlgorithmClientToServer: {_PendingExchangeContext.MACAlgorithmClientToServer.Name}");
_Logger.LogDebug($"Selected MACAlgorithmServerToClient: {_PendingExchangeContext.MACAlgorithmServerToClient.Name}");
_Logger.LogDebug($"Selected CompressionClientToServer: {_PendingExchangeContext.CompressionClientToServer.Name}");
_Logger.LogDebug($"Selected CompressionServerToClient: {_PendingExchangeContext.CompressionServerToClient.Name}");
}
private void HandleSpecificPacket(NewKeys packet)
{
_Logger.LogDebug("Received NewKeys");
_ActiveExchangeContext = _PendingExchangeContext;
_PendingExchangeContext = null;
// Reset re-exchange values
_TotalBytesTransferred = 0;
_KeyTimeout = DateTime.UtcNow.AddHours(1);
}
private byte[] ComputeExchangeHash(IKexAlgorithm kexAlgorithm, byte[] hostKeyAndCerts, byte[] clientExchangeValue, byte[] serverExchangeValue, byte[] sharedSecret)
{
// H = hash(V_C || V_S || I_C || I_S || K_S || e || f || K)
using (ByteWriter writer = new ByteWriter())
{
writer.WriteString(_ProtocolVersionExchange);
writer.WriteString(ServerConstants.ProtocolVersionExchange);
writer.WriteBytes(_KexInitClientToServer.GetBytes());
writer.WriteBytes(_KexInitServerToClient.GetBytes());
writer.WriteBytes(hostKeyAndCerts);
writer.WriteMPInt(clientExchangeValue);
writer.WriteMPInt(serverExchangeValue);
writer.WriteMPInt(sharedSecret);
return kexAlgorithm.ComputeHash(writer.ToByteArray());
}
}
private byte[] ComputeEncryptionKey(IKexAlgorithm kexAlgorithm, byte[] exchangeHash, uint keySize, byte[] sharedSecret, char letter)
{
// K(X) = HASH(K || H || X || session_id)
// Prepare the buffer
byte[] keyBuffer = new byte[keySize];
int keyBufferIndex = 0;
int currentHashLength = 0;
byte[] currentHash = null;
// We can stop once we fill the key buffer
while (keyBufferIndex < keySize)
{
using (ByteWriter writer = new ByteWriter())
{
// Write "K"
writer.WriteMPInt(sharedSecret);
// Write "H"
writer.WriteRawBytes(exchangeHash);
if (currentHash == null)
{
// If we haven't done this yet, add the "X" and session_id
writer.WriteByte((byte)letter);
writer.WriteRawBytes(_SessionId);
}
else
{
// If the key isn't long enough after the first pass, we need to
// write the current hash as described here:
// K1 = HASH(K || H || X || session_id) (X is e.g., "A")
// K2 = HASH(K || H || K1)
// K3 = HASH(K || H || K1 || K2)
// ...
// key = K1 || K2 || K3 || ...
writer.WriteRawBytes(currentHash);
}
currentHash = kexAlgorithm.ComputeHash(writer.ToByteArray());
}
currentHashLength = Math.Min(currentHash.Length, (int)(keySize - keyBufferIndex));
Array.Copy(currentHash, 0, keyBuffer, keyBufferIndex, currentHashLength);
keyBufferIndex += currentHashLength;
}
return keyBuffer;
}
public Packet ReadPacket()
{
if (_Socket == null)
return null;
uint blockSize = _ActiveExchangeContext.CipherClientToServer.BlockSize;
// We must have at least 1 block to read
if (_Socket.Available < blockSize)
return null; // Packet not here
byte[] firstBlock = new byte[blockSize];
int bytesRead = _Socket.Receive(firstBlock);
if (bytesRead != blockSize)
throw new KSSHServerException(DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "Failed to read from socket.");
firstBlock = _ActiveExchangeContext.CipherClientToServer.Decrypt(firstBlock);
uint packetLength = 0;
byte paddingLength = 0;
using (ByteReader reader = new ByteReader(firstBlock))
{
// uint32 packet_length
// packet_length
// The length of the packet in bytes, not including 'mac' or the
// 'packet_length' field itself.
packetLength = reader.GetUInt32();
if (packetLength > Packet.MaxPacketSize)
throw new KSSHServerException(DisconnectReason.SSH_DISCONNECT_PROTOCOL_ERROR, $"Client tried to send a packet bigger than MaxPacketSize ({Packet.MaxPacketSize} bytes): {packetLength} bytes");
// byte padding_length
// padding_length
// Length of 'random padding' (bytes).
paddingLength = reader.GetByte();
}
// byte[n1] payload; n1 = packet_length - padding_length - 1
// payload
// The useful contents of the packet. If compression has been
// negotiated, this field is compressed. Initially, compression
// MUST be "none".
uint bytesToRead = packetLength - blockSize + 4;
byte[] restOfPacket = new byte[bytesToRead];
bytesRead = _Socket.Receive(restOfPacket);
if (bytesRead != bytesToRead)
throw new KSSHServerException(DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "Failed to read from socket.");
restOfPacket = _ActiveExchangeContext.CipherClientToServer.Decrypt(restOfPacket);
uint payloadLength = packetLength - paddingLength - 1;
byte[] fullPacket = firstBlock.Concat(restOfPacket).ToArray();
// Track total bytes read
_TotalBytesTransferred += fullPacket.Length;
byte[] payload = fullPacket.Skip(Packet._PacketHeaderSize).Take((int)(packetLength - paddingLength - 1)).ToArray();
// byte[n2] random padding; n2 = padding_length
// random padding
// Arbitrary-length padding, such that the total length of
// (packet_length || padding_length || payload || random padding)
// is a multiple of the cipher block size or 8, whichever is
// larger. There MUST be at least four bytes of padding. The
// padding SHOULD consist of random bytes. The maximum amount of
// padding is 255 bytes.
// byte[m] mac (Message Authentication Code - MAC); m = mac_length
// mac
// Message Authentication Code. If message authentication has
// been negotiated, this field contains the MAC bytes. Initially,
// the MAC algorithm MUST be "none".
uint packetNumber = GetReceivedPacketNumber();
if (_ActiveExchangeContext.MACAlgorithmClientToServer != null)
{
byte[] clientMac = new byte[_ActiveExchangeContext.MACAlgorithmClientToServer.DigestLength];
bytesRead = _Socket.Receive(clientMac);
if (bytesRead != _ActiveExchangeContext.MACAlgorithmClientToServer.DigestLength)
throw new KSSHServerException(DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "Failed to read from socket.");
var mac = _ActiveExchangeContext.MACAlgorithmClientToServer.ComputeHash(packetNumber, fullPacket);
if (!clientMac.SequenceEqual(mac))
{
throw new KSSHServerException(DisconnectReason.SSH_DISCONNECT_MAC_ERROR, "MAC from client is invalid");
}
}
payload = _ActiveExchangeContext.CompressionClientToServer.Decompress(payload);
using (ByteReader packetReader = new ByteReader(payload))
{
PacketType type = (PacketType)packetReader.GetByte();
if (Packet._PacketTypes.ContainsKey(type))
{
Packet packet = Activator.CreateInstance(Packet._PacketTypes[type]) as Packet;
packet.Load(packetReader);
packet.PacketSequence = packetNumber;
return packet;
}
_Logger.LogWarning($"Unimplemented packet type: {type}");
Unimplemented unimplemented = new Unimplemented()
{
RejectedPacketNumber = packetNumber
};
Send(unimplemented);
}
return null;
}
private void ConsiderReExchange()
{
const long OneGB = (1024 * 1024 * 1024);
if ((_TotalBytesTransferred > OneGB) || (_KeyTimeout < DateTime.UtcNow))
{
// Time to get new keys!
_TotalBytesTransferred = 0;
_KeyTimeout = DateTime.UtcNow.AddHours(1);
_Logger.LogDebug("Trigger re-exchange from server");
_PendingExchangeContext = new ExchangeContext();
Send(_KexInitServerToClient);
}
}
private void ValidateProtocolVersionExchange()
{
// https://tools.ietf.org/html/rfc4253#section-4.2
//SSH-protoversion-softwareversion SP comments
string[] pveParts = _ProtocolVersionExchange.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (pveParts.Length == 0)
throw new UnauthorizedAccessException("Invalid Protocol Version Exchange was received - No Data");
string[] versionParts = pveParts[0].Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
if (versionParts.Length < 3)
throw new UnauthorizedAccessException($"Invalid Protocol Version Exchange was received - Not enough dashes - {pveParts[0]}");
if (versionParts[1] != "2.0")
throw new UnauthorizedAccessException($"Invalid Protocol Version Exchange was received - Unsupported Version - {versionParts[1]}");
// If we get here, all is well!
}
public void Disconnect(DisconnectReason reason, string message)
{
_Logger.LogDebug($"Disconnected - {reason} - {message}");
if (_Socket != null)
{
if (reason != DisconnectReason.None)
{
try
{
Disconnect disconnect = new Disconnect()
{
Reason = reason,
Description = message
};
Send(disconnect);
}
catch (Exception) { }
}
try
{
_Socket.Shutdown(SocketShutdown.Both);
}
catch (Exception) { }
_Socket = null;
}
}
};
}