-
-
Notifications
You must be signed in to change notification settings - Fork 940
/
Copy pathSession.cs
2357 lines (2020 loc) · 98.9 KB
/
Session.cs
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Renci.SshNet.Abstractions;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
using Renci.SshNet.Compression;
using Renci.SshNet.Connection;
using Renci.SshNet.Messages;
using Renci.SshNet.Messages.Authentication;
using Renci.SshNet.Messages.Connection;
using Renci.SshNet.Messages.Transport;
using Renci.SshNet.Security;
using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet
{
/// <summary>
/// Provides functionality to connect and interact with SSH server.
/// </summary>
public class Session : ISession
{
internal const byte CarriageReturn = 0x0d;
internal const byte LineFeed = 0x0a;
/// <summary>
/// Specifies maximum packet size defined by the protocol.
/// </summary>
/// <value>
/// 68536 (64 KB + 3000 bytes).
/// </value>
internal const int MaximumSshPacketSize = LocalChannelDataPacketSize + 3000;
/// <summary>
/// Holds the initial local window size for the channels.
/// </summary>
/// <value>
/// 2147483647 (2^31 - 1) bytes.
/// </value>
/// <remarks>
/// We currently do not define a maximum (remote) window size.
/// </remarks>
private const int InitialLocalWindowSize = 0x7FFFFFFF;
/// <summary>
/// Holds the maximum size of channel data packets that we receive.
/// </summary>
/// <value>
/// 64 KB.
/// </value>
/// <remarks>
/// <para>
/// This is the maximum size (in bytes) we support for the data (payload) of a
/// <c>SSH_MSG_CHANNEL_DATA</c> message we receive.
/// </para>
/// <para>
/// We currently do not enforce this limit.
/// </para>
/// </remarks>
private const int LocalChannelDataPacketSize = 1024 * 64;
/// <summary>
/// Holds the factory to use for creating new services.
/// </summary>
private readonly IServiceFactory _serviceFactory;
private readonly ISocketFactory _socketFactory;
/// <summary>
/// Holds an object that is used to ensure only a single thread can read from
/// <see cref="_socket"/> at any given time.
/// </summary>
private readonly object _socketReadLock = new object();
/// <summary>
/// Holds an object that is used to ensure only a single thread can write to
/// <see cref="_socket"/> at any given time.
/// </summary>
/// <remarks>
/// This is also used to ensure that <see cref="_outboundPacketSequence"/> is
/// incremented atomatically.
/// </remarks>
private readonly object _socketWriteLock = new object();
/// <summary>
/// Holds an object that is used to ensure only a single thread can dispose
/// <see cref="_socket"/> at any given time.
/// </summary>
/// <remarks>
/// This is also used to ensure that <see cref="_socket"/> will not be disposed
/// while performing a given operation or set of operations on <see cref="_socket"/>.
/// </remarks>
private readonly SemaphoreSlim _socketDisposeLock = new SemaphoreSlim(1, 1);
/// <summary>
/// Holds an object that is used to ensure only a single thread can connect
/// at any given time.
/// </summary>
private readonly SemaphoreSlim _connectLock = new SemaphoreSlim(1, 1);
/// <summary>
/// Holds metadata about session messages.
/// </summary>
private SshMessageFactory _sshMessageFactory;
/// <summary>
/// Holds a <see cref="WaitHandle"/> that is signaled when the message listener loop has completed.
/// </summary>
private ManualResetEvent _messageListenerCompleted;
/// <summary>
/// Specifies outbound packet number.
/// </summary>
private volatile uint _outboundPacketSequence;
/// <summary>
/// Specifies incoming packet number.
/// </summary>
private uint _inboundPacketSequence;
/// <summary>
/// WaitHandle to signal that last service request was accepted.
/// </summary>
private EventWaitHandle _serviceAccepted = new AutoResetEvent(initialState: false);
/// <summary>
/// WaitHandle to signal that exception was thrown by another thread.
/// </summary>
private EventWaitHandle _exceptionWaitHandle = new ManualResetEvent(initialState: false);
/// <summary>
/// WaitHandle to signal that key exchange was completed.
/// </summary>
private ManualResetEventSlim _keyExchangeCompletedWaitHandle = new ManualResetEventSlim(initialState: false);
/// <summary>
/// Exception that need to be thrown by waiting thread.
/// </summary>
private Exception _exception;
/// <summary>
/// Specifies whether connection is authenticated.
/// </summary>
private bool _isAuthenticated;
/// <summary>
/// Specifies whether user issued Disconnect command or not.
/// </summary>
private bool _isDisconnecting;
/// <summary>
/// Indicates whether it is the init kex.
/// </summary>
private bool _isInitialKex;
/// <summary>
/// Indicates whether server supports strict key exchange.
/// <see href="https://github.com/openssh/openssh-portable/blob/master/PROTOCOL"/> 1.10.
/// </summary>
private bool _isStrictKex;
private IKeyExchange _keyExchange;
private HashAlgorithm _serverMac;
private HashAlgorithm _clientMac;
private bool _serverEtm;
private bool _clientEtm;
private Cipher _serverCipher;
private Cipher _clientCipher;
private bool _serverAead;
private bool _clientAead;
private Compressor _serverDecompression;
private Compressor _clientCompression;
private SemaphoreSlim _sessionSemaphore;
private bool _isDisconnectMessageSent;
private int _nextChannelNumber;
/// <summary>
/// Holds connection socket.
/// </summary>
private Socket _socket;
/// <summary>
/// Gets the session semaphore that controls session channels.
/// </summary>
/// <value>
/// The session semaphore.
/// </value>
public SemaphoreSlim SessionSemaphore
{
get
{
if (_sessionSemaphore is SemaphoreSlim sessionSemaphore)
{
return sessionSemaphore;
}
sessionSemaphore = new SemaphoreSlim(ConnectionInfo.MaxSessions);
if (Interlocked.CompareExchange(ref _sessionSemaphore, sessionSemaphore, comparand: null) is not null)
{
// Another thread has set _sessionSemaphore. Dispose our one.
Debug.Assert(_sessionSemaphore != sessionSemaphore);
sessionSemaphore.Dispose();
}
return _sessionSemaphore;
}
}
/// <summary>
/// Gets the next channel number.
/// </summary>
/// <value>
/// The next channel number.
/// </value>
private uint NextChannelNumber
{
get
{
return (uint)Interlocked.Increment(ref _nextChannelNumber);
}
}
/// <summary>
/// Gets a value indicating whether the session is connected.
/// </summary>
/// <value>
/// <see langword="true"/> if the session is connected; otherwise, <see langword="false"/>.
/// </value>
/// <remarks>
/// This methods returns <see langword="true"/> in all but the following cases:
/// <list type="bullet">
/// <item>
/// <description>The <see cref="Session"/> is disposed.</description>
/// </item>
/// <item>
/// <description>The <c>SSH_MSG_DISCONNECT</c> message - which is used to disconnect from the server - has been sent.</description>
/// </item>
/// <item>
/// <description>The client has not been authenticated successfully.</description>
/// </item>
/// <item>
/// <description>The listener thread - which is used to receive messages from the server - has stopped.</description>
/// </item>
/// <item>
/// <description>The socket used to communicate with the server is no longer connected.</description>
/// </item>
/// </list>
/// </remarks>
public bool IsConnected
{
get
{
if (_disposed || _isDisconnectMessageSent || !_isAuthenticated)
{
return false;
}
if (_messageListenerCompleted is null || _messageListenerCompleted.WaitOne(0))
{
return false;
}
return IsSocketConnected();
}
}
/// <summary>
/// Gets the session id.
/// </summary>
/// <value>
/// The session id, or <see langword="null"/> if the client has not been authenticated.
/// </value>
public byte[] SessionId { get; private set; }
/// <summary>
/// Gets the client init message.
/// </summary>
/// <value>The client init message.</value>
public Message ClientInitMessage { get; private set; }
/// <summary>
/// Gets the server version string.
/// </summary>
/// <value>
/// The server version.
/// </value>
public string ServerVersion { get; private set; }
/// <summary>
/// Gets the client version string.
/// </summary>
/// <value>
/// The client version.
/// </value>
public string ClientVersion { get; private set; }
/// <summary>
/// Gets the connection info.
/// </summary>
/// <value>
/// The connection info.
/// </value>
public ConnectionInfo ConnectionInfo { get; private set; }
/// <summary>
/// Occurs when an error occurred.
/// </summary>
public event EventHandler<ExceptionEventArgs> ErrorOccured;
/// <summary>
/// Occurs when session has been disconnected from the server.
/// </summary>
public event EventHandler<EventArgs> Disconnected;
/// <summary>
/// Occurs when server identification received.
/// </summary>
public event EventHandler<SshIdentificationEventArgs> ServerIdentificationReceived;
/// <summary>
/// Occurs when host key received.
/// </summary>
public event EventHandler<HostKeyEventArgs> HostKeyReceived;
/// <summary>
/// Occurs when <see cref="BannerMessage"/> message is received from the server.
/// </summary>
public event EventHandler<MessageEventArgs<BannerMessage>> UserAuthenticationBannerReceived;
/// <summary>
/// Occurs when <see cref="InformationRequestMessage"/> message is received from the server.
/// </summary>
internal event EventHandler<MessageEventArgs<InformationRequestMessage>> UserAuthenticationInformationRequestReceived;
/// <summary>
/// Occurs when <see cref="PasswordChangeRequiredMessage"/> message is received from the server.
/// </summary>
internal event EventHandler<MessageEventArgs<PasswordChangeRequiredMessage>> UserAuthenticationPasswordChangeRequiredReceived;
/// <summary>
/// Occurs when <see cref="PublicKeyMessage"/> message is received from the server.
/// </summary>
internal event EventHandler<MessageEventArgs<PublicKeyMessage>> UserAuthenticationPublicKeyReceived;
/// <summary>
/// Occurs when <see cref="KeyExchangeDhGroupExchangeGroup"/> message is received from the server.
/// </summary>
internal event EventHandler<MessageEventArgs<KeyExchangeDhGroupExchangeGroup>> KeyExchangeDhGroupExchangeGroupReceived;
/// <summary>
/// Occurs when <see cref="KeyExchangeDhGroupExchangeReply"/> message is received from the server.
/// </summary>
internal event EventHandler<MessageEventArgs<KeyExchangeDhGroupExchangeReply>> KeyExchangeDhGroupExchangeReplyReceived;
/// <summary>
/// Occurs when <see cref="DisconnectMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<DisconnectMessage>> DisconnectReceived;
/// <summary>
/// Occurs when <see cref="IgnoreMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<IgnoreMessage>> IgnoreReceived;
/// <summary>
/// Occurs when <see cref="UnimplementedMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<UnimplementedMessage>> UnimplementedReceived;
/// <summary>
/// Occurs when <see cref="DebugMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<DebugMessage>> DebugReceived;
/// <summary>
/// Occurs when <see cref="ServiceRequestMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<ServiceRequestMessage>> ServiceRequestReceived;
/// <summary>
/// Occurs when <see cref="ServiceAcceptMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<ServiceAcceptMessage>> ServiceAcceptReceived;
/// <summary>
/// Occurs when <see cref="KeyExchangeInitMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<KeyExchangeInitMessage>> KeyExchangeInitReceived;
/// <summary>
/// Occurs when a <see cref="KeyExchangeDhReplyMessage"/> message is received from the SSH server.
/// </summary>
internal event EventHandler<MessageEventArgs<KeyExchangeDhReplyMessage>> KeyExchangeDhReplyMessageReceived;
/// <summary>
/// Occurs when a <see cref="KeyExchangeEcdhReplyMessage"/> message is received from the SSH server.
/// </summary>
internal event EventHandler<MessageEventArgs<KeyExchangeEcdhReplyMessage>> KeyExchangeEcdhReplyMessageReceived;
/// <summary>
/// Occurs when <see cref="NewKeysMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<NewKeysMessage>> NewKeysReceived;
/// <summary>
/// Occurs when <see cref="RequestMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<RequestMessage>> UserAuthenticationRequestReceived;
/// <summary>
/// Occurs when <see cref="FailureMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<FailureMessage>> UserAuthenticationFailureReceived;
/// <summary>
/// Occurs when <see cref="SuccessMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<SuccessMessage>> UserAuthenticationSuccessReceived;
/// <summary>
/// Occurs when <see cref="GlobalRequestMessage"/> message received
/// </summary>
internal event EventHandler<MessageEventArgs<GlobalRequestMessage>> GlobalRequestReceived;
/// <summary>
/// Occurs when <see cref="RequestSuccessMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<RequestSuccessMessage>> RequestSuccessReceived;
/// <summary>
/// Occurs when <see cref="RequestFailureMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<RequestFailureMessage>> RequestFailureReceived;
/// <summary>
/// Occurs when <see cref="ChannelOpenMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelOpenMessage>> ChannelOpenReceived;
/// <summary>
/// Occurs when <see cref="ChannelOpenConfirmationMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelOpenConfirmationMessage>> ChannelOpenConfirmationReceived;
/// <summary>
/// Occurs when <see cref="ChannelOpenFailureMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelOpenFailureMessage>> ChannelOpenFailureReceived;
/// <summary>
/// Occurs when <see cref="ChannelWindowAdjustMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelWindowAdjustMessage>> ChannelWindowAdjustReceived;
/// <summary>
/// Occurs when <see cref="ChannelDataMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelDataMessage>> ChannelDataReceived;
/// <summary>
/// Occurs when <see cref="ChannelExtendedDataMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelExtendedDataMessage>> ChannelExtendedDataReceived;
/// <summary>
/// Occurs when <see cref="ChannelEofMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelEofMessage>> ChannelEofReceived;
/// <summary>
/// Occurs when <see cref="ChannelCloseMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelCloseMessage>> ChannelCloseReceived;
/// <summary>
/// Occurs when <see cref="ChannelRequestMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelRequestMessage>> ChannelRequestReceived;
/// <summary>
/// Occurs when <see cref="ChannelSuccessMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelSuccessMessage>> ChannelSuccessReceived;
/// <summary>
/// Occurs when <see cref="ChannelFailureMessage"/> message received
/// </summary>
public event EventHandler<MessageEventArgs<ChannelFailureMessage>> ChannelFailureReceived;
/// <summary>
/// Initializes a new instance of the <see cref="Session"/> class.
/// </summary>
/// <param name="connectionInfo">The connection info.</param>
/// <param name="serviceFactory">The factory to use for creating new services.</param>
/// <param name="socketFactory">A factory to create <see cref="Socket"/> instances.</param>
/// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="socketFactory"/> is <see langword="null"/>.</exception>
internal Session(ConnectionInfo connectionInfo, IServiceFactory serviceFactory, ISocketFactory socketFactory)
{
if (connectionInfo is null)
{
throw new ArgumentNullException(nameof(connectionInfo));
}
if (serviceFactory is null)
{
throw new ArgumentNullException(nameof(serviceFactory));
}
if (socketFactory is null)
{
throw new ArgumentNullException(nameof(socketFactory));
}
ClientVersion = "SSH-2.0-Renci.SshNet.SshClient.0.0.1";
ConnectionInfo = connectionInfo;
_serviceFactory = serviceFactory;
_socketFactory = socketFactory;
_messageListenerCompleted = new ManualResetEvent(initialState: true);
}
/// <summary>
/// Connects to the server.
/// </summary>
/// <exception cref="SocketException">Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.</exception>
/// <exception cref="SshConnectionException">SSH session could not be established.</exception>
/// <exception cref="SshAuthenticationException">Authentication of SSH session failed.</exception>
/// <exception cref="ProxyException">Failed to establish proxy connection.</exception>
public void Connect()
{
if (IsConnected)
{
return;
}
_connectLock.Wait();
try
{
if (IsConnected)
{
return;
}
// Reset connection specific information
Reset();
// Build list of available messages while connecting
_sshMessageFactory = new SshMessageFactory();
_socket = _serviceFactory.CreateConnector(ConnectionInfo, _socketFactory)
.Connect(ConnectionInfo);
var serverIdentification = _serviceFactory.CreateProtocolVersionExchange()
.Start(ClientVersion, _socket, ConnectionInfo.Timeout);
// Set connection versions
ServerVersion = ConnectionInfo.ServerVersion = serverIdentification.ToString();
ConnectionInfo.ClientVersion = ClientVersion;
DiagnosticAbstraction.Log(string.Format("Server version '{0}'.", serverIdentification));
if (!(serverIdentification.ProtocolVersion.Equals("2.0") || serverIdentification.ProtocolVersion.Equals("1.99")))
{
throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", serverIdentification.ProtocolVersion),
DisconnectReason.ProtocolVersionNotSupported);
}
ServerIdentificationReceived?.Invoke(this, new SshIdentificationEventArgs(serverIdentification));
// Register Transport response messages
RegisterMessage("SSH_MSG_DISCONNECT");
RegisterMessage("SSH_MSG_IGNORE");
RegisterMessage("SSH_MSG_UNIMPLEMENTED");
RegisterMessage("SSH_MSG_DEBUG");
RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
RegisterMessage("SSH_MSG_KEXINIT");
RegisterMessage("SSH_MSG_NEWKEYS");
// Some server implementations might sent this message first, prior to establishing encryption algorithm
RegisterMessage("SSH_MSG_USERAUTH_BANNER");
// Send our key exchange init.
// We need to do this before starting the message listener to avoid the case where we receive the server
// key exchange init and we continue the key exchange before having sent our own init.
_isInitialKex = true;
ClientInitMessage = BuildClientInitMessage(includeStrictKexPseudoAlgorithm: true);
SendMessage(ClientInitMessage);
// Mark the message listener threads as started
_ = _messageListenerCompleted.Reset();
// Start incoming request listener
// ToDo: Make message pump async, to not consume a thread for every session
_ = ThreadAbstraction.ExecuteThreadLongRunning(MessageListener);
// Wait for key exchange to be completed
WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
// If sessionId is not set then its not connected
if (SessionId is null)
{
Disconnect();
return;
}
// Request user authorization service
SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
// Wait for service to be accepted
WaitOnHandle(_serviceAccepted);
if (string.IsNullOrEmpty(ConnectionInfo.Username))
{
throw new SshException("Username is not specified.");
}
// Some servers send a global request immediately after successful authentication
// Avoid race condition by already enabling SSH_MSG_GLOBAL_REQUEST before authentication
RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
ConnectionInfo.Authenticate(this, _serviceFactory);
_isAuthenticated = true;
// Register Connection messages
RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
RegisterMessage("SSH_MSG_REQUEST_FAILURE");
RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
RegisterMessage("SSH_MSG_CHANNEL_DATA");
RegisterMessage("SSH_MSG_CHANNEL_EOF");
RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
}
finally
{
_ = _connectLock.Release();
}
}
/// <summary>
/// Asynchronously connects to the server.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous connect operation.</returns>
/// <exception cref="SocketException">Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.</exception>
/// <exception cref="SshConnectionException">SSH session could not be established.</exception>
/// <exception cref="SshAuthenticationException">Authentication of SSH session failed.</exception>
/// <exception cref="ProxyException">Failed to establish proxy connection.</exception>
public async Task ConnectAsync(CancellationToken cancellationToken)
{
// If connected don't connect again
if (IsConnected)
{
return;
}
await _connectLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (IsConnected)
{
return;
}
// Reset connection specific information
Reset();
// Build list of available messages while connecting
_sshMessageFactory = new SshMessageFactory();
_socket = await _serviceFactory.CreateConnector(ConnectionInfo, _socketFactory)
.ConnectAsync(ConnectionInfo, cancellationToken).ConfigureAwait(false);
var serverIdentification = await _serviceFactory.CreateProtocolVersionExchange()
.StartAsync(ClientVersion, _socket, cancellationToken).ConfigureAwait(false);
// Set connection versions
ServerVersion = ConnectionInfo.ServerVersion = serverIdentification.ToString();
ConnectionInfo.ClientVersion = ClientVersion;
DiagnosticAbstraction.Log(string.Format("Server version '{0}'.", serverIdentification));
if (!(serverIdentification.ProtocolVersion.Equals("2.0") || serverIdentification.ProtocolVersion.Equals("1.99")))
{
throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", serverIdentification.ProtocolVersion),
DisconnectReason.ProtocolVersionNotSupported);
}
ServerIdentificationReceived?.Invoke(this, new SshIdentificationEventArgs(serverIdentification));
// Register Transport response messages
RegisterMessage("SSH_MSG_DISCONNECT");
RegisterMessage("SSH_MSG_IGNORE");
RegisterMessage("SSH_MSG_UNIMPLEMENTED");
RegisterMessage("SSH_MSG_DEBUG");
RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
RegisterMessage("SSH_MSG_KEXINIT");
RegisterMessage("SSH_MSG_NEWKEYS");
// Some server implementations might sent this message first, prior to establishing encryption algorithm
RegisterMessage("SSH_MSG_USERAUTH_BANNER");
// Send our key exchange init.
// We need to do this before starting the message listener to avoid the case where we receive the server
// key exchange init and we continue the key exchange before having sent our own init.
_isInitialKex = true;
ClientInitMessage = BuildClientInitMessage(includeStrictKexPseudoAlgorithm: true);
SendMessage(ClientInitMessage);
// Mark the message listener threads as started
_ = _messageListenerCompleted.Reset();
// Start incoming request listener
// ToDo: Make message pump async, to not consume a thread for every session
_ = ThreadAbstraction.ExecuteThreadLongRunning(MessageListener);
// Wait for key exchange to be completed
WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
// If sessionId is not set then its not connected
if (SessionId is null)
{
Disconnect();
return;
}
// Request user authorization service
SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
// Wait for service to be accepted
WaitOnHandle(_serviceAccepted);
if (string.IsNullOrEmpty(ConnectionInfo.Username))
{
throw new SshException("Username is not specified.");
}
// Some servers send a global request immediately after successful authentication
// Avoid race condition by already enabling SSH_MSG_GLOBAL_REQUEST before authentication
RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
ConnectionInfo.Authenticate(this, _serviceFactory);
_isAuthenticated = true;
// Register Connection messages
RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
RegisterMessage("SSH_MSG_REQUEST_FAILURE");
RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
RegisterMessage("SSH_MSG_CHANNEL_DATA");
RegisterMessage("SSH_MSG_CHANNEL_EOF");
RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
}
finally
{
_ = _connectLock.Release();
}
}
/// <summary>
/// Disconnects from the server.
/// </summary>
/// <remarks>
/// This sends a <b>SSH_MSG_DISCONNECT</b> message to the server, waits for the
/// server to close the socket on its end and subsequently closes the client socket.
/// </remarks>
public void Disconnect()
{
DiagnosticAbstraction.Log(string.Format("[{0}] Disconnecting session.", ToHex(SessionId)));
// send SSH_MSG_DISCONNECT message, clear socket read buffer and dispose it
Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
// at this point, we are sure that the listener thread will stop as we've
// disconnected the socket, so lets wait until the message listener thread
// has completed
if (_messageListenerCompleted != null)
{
_ = _messageListenerCompleted.WaitOne();
}
}
private void Disconnect(DisconnectReason reason, string message)
{
// transition to disconnecting state to avoid throwing exceptions while cleaning up, and to
// ensure any exceptions that are raised do not overwrite the exception that is set
_isDisconnecting = true;
// send disconnect message to the server if the connection is still open
// and the disconnect message has not yet been sent
//
// note that this should also cause the listener loop to be interrupted as
// the server should respond by closing the socket
if (IsConnected)
{
TrySendDisconnect(reason, message);
}
// disconnect socket, and dispose it
SocketDisconnectAndDispose();
}
/// <summary>
/// Waits for the specified handle or the exception handle for the receive thread
/// to signal within the connection timeout.
/// </summary>
/// <param name="waitHandle">The wait handle.</param>
/// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
/// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
/// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
/// <remarks>
/// When neither handles are signaled in time and the session is not closing, then the
/// session is disconnected.
/// </remarks>
void ISession.WaitOnHandle(WaitHandle waitHandle)
{
WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
}
/// <summary>
/// Waits for the specified handle or the exception handle for the receive thread
/// to signal within the specified timeout.
/// </summary>
/// <param name="waitHandle">The wait handle.</param>
/// <param name="timeout">The time to wait for any of the handles to become signaled.</param>
/// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
/// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
/// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
/// <remarks>
/// When neither handles are signaled in time and the session is not closing, then the
/// session is disconnected.
/// </remarks>
void ISession.WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
{
WaitOnHandle(waitHandle, timeout);
}
/// <summary>
/// Waits for the specified <seec ref="WaitHandle"/> to receive a signal, using a <see cref="TimeSpan"/>
/// to specify the time interval.
/// </summary>
/// <param name="waitHandle">The <see cref="WaitHandle"/> that should be signaled.</param>
/// <param name="timeout">A <see cref="TimeSpan"/> that represents the number of milliseconds to wait, or a <see cref="TimeSpan"/> that represents <c>-1</c> milliseconds to wait indefinitely.</param>
/// <returns>
/// A <see cref="WaitResult"/>.
/// </returns>
WaitResult ISession.TryWait(WaitHandle waitHandle, TimeSpan timeout)
{
return TryWait(waitHandle, timeout, out _);
}
/// <summary>
/// Waits for the specified <seec ref="WaitHandle"/> to receive a signal, using a <see cref="TimeSpan"/>
/// to specify the time interval.
/// </summary>
/// <param name="waitHandle">The <see cref="WaitHandle"/> that should be signaled.</param>
/// <param name="timeout">A <see cref="TimeSpan"/> that represents the number of milliseconds to wait, or a <see cref="TimeSpan"/> that represents <c>-1</c> milliseconds to wait indefinitely.</param>
/// <param name="exception">When this method returns <see cref="WaitResult.Failed"/>, contains the <see cref="Exception"/>.</param>
/// <returns>
/// A <see cref="WaitResult"/>.
/// </returns>
WaitResult ISession.TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exception exception)
{
return TryWait(waitHandle, timeout, out exception);
}
/// <summary>
/// Waits for the specified <seec ref="WaitHandle"/> to receive a signal, using a <see cref="TimeSpan"/>
/// to specify the time interval.
/// </summary>
/// <param name="waitHandle">The <see cref="WaitHandle"/> that should be signaled.</param>
/// <param name="timeout">A <see cref="TimeSpan"/> that represents the number of milliseconds to wait, or a <see cref="TimeSpan"/> that represents <c>-1</c> milliseconds to wait indefinitely.</param>
/// <param name="exception">When this method returns <see cref="WaitResult.Failed"/>, contains the <see cref="Exception"/>.</param>
/// <returns>
/// A <see cref="WaitResult"/>.
/// </returns>
private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exception exception)
{
if (waitHandle is null)
{
throw new ArgumentNullException(nameof(waitHandle));
}
var waitHandles = new[]
{
_exceptionWaitHandle,
_messageListenerCompleted,
waitHandle
};
switch (WaitHandle.WaitAny(waitHandles, timeout))
{
case 0:
if (_exception is SshConnectionException)
{
exception = null;
return WaitResult.Disconnected;
}
exception = _exception;
return WaitResult.Failed;
case 1:
exception = null;
return WaitResult.Disconnected;
case 2:
exception = null;
return WaitResult.Success;
case WaitHandle.WaitTimeout:
exception = null;
return WaitResult.TimedOut;
default:
throw new InvalidOperationException("Unexpected result.");
}
}
/// <summary>
/// Waits for the specified handle or the exception handle for the receive thread
/// to signal within the connection timeout.
/// </summary>
/// <param name="waitHandle">The wait handle.</param>
/// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
/// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
/// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
/// <remarks>
/// When neither handles are signaled in time and the session is not closing, then the
/// session is disconnected.
/// </remarks>
internal void WaitOnHandle(WaitHandle waitHandle)
{
WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
}
/// <summary>
/// Waits for the specified handle or the exception handle for the receive thread
/// to signal within the specified timeout.
/// </summary>
/// <param name="waitHandle">The wait handle.</param>
/// <param name="timeout">The time to wait for any of the handles to become signaled.</param>
/// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
/// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
/// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
{
if (waitHandle is null)
{
throw new ArgumentNullException(nameof(waitHandle));
}
var waitHandles = new[]
{
_exceptionWaitHandle,
_messageListenerCompleted,
waitHandle
};
var signaledElement = WaitHandle.WaitAny(waitHandles, timeout);
switch (signaledElement)
{
case 0:
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(_exception).Throw();
break;
case 1:
throw new SshConnectionException("Client not connected.");
case 2:
// Specified waithandle was signaled
break;
case WaitHandle.WaitTimeout: