Session.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Renci.SshNet.Channels;
  13. using Renci.SshNet.Common;
  14. using Renci.SshNet.Compression;
  15. using Renci.SshNet.Messages;
  16. using Renci.SshNet.Messages.Authentication;
  17. using Renci.SshNet.Messages.Connection;
  18. using Renci.SshNet.Messages.Transport;
  19. using Renci.SshNet.Security;
  20. using System.Globalization;
  21. namespace Renci.SshNet
  22. {
  23. /// <summary>
  24. /// Provides functionality to connect and interact with SSH server.
  25. /// </summary>
  26. public class Session : IDisposable
  27. {
  28. /// <summary>
  29. /// Specifies maximum packet size defined by the protocol.
  30. /// </summary>
  31. protected const int MAXIMUM_PACKET_SIZE = 35000;
  32. /// <summary>
  33. /// Specifies maximum payload size defined by the protocol.
  34. /// </summary>
  35. protected const int MAXIMUM_PAYLOAD_SIZE = 1024 * 32;
  36. private static RNGCryptoServiceProvider _randomizer = new System.Security.Cryptography.RNGCryptoServiceProvider();
  37. private static Regex _serverVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$", RegexOptions.Compiled);
  38. /// <summary>
  39. /// Controls how many authentication attempts can take place at the same time.
  40. /// </summary>
  41. /// <remarks>
  42. /// Some server may restrict number to prevent authentication attacks
  43. /// </remarks>
  44. private static SemaphoreSlim _authenticationConnection = new SemaphoreSlim(3);
  45. /// <summary>
  46. /// Holds metada about session messages
  47. /// </summary>
  48. private IEnumerable<MessageMetadata> _messagesMetadata;
  49. /// <summary>
  50. /// Holds connection socket.
  51. /// </summary>
  52. private Socket _socket;
  53. /// <summary>
  54. /// Holds reference to task that listens for incoming messages
  55. /// </summary>
  56. private Task _messageListener;
  57. /// <summary>
  58. /// Specifies outbound packet number
  59. /// </summary>
  60. private volatile UInt32 _outboundPacketSequence = 0;
  61. /// <summary>
  62. /// Specifies incoming packet number
  63. /// </summary>
  64. private UInt32 _inboundPacketSequence = 0;
  65. /// <summary>
  66. /// WaitHandle to signal that last service request was accepted
  67. /// </summary>
  68. private EventWaitHandle _serviceAccepted = new AutoResetEvent(false);
  69. /// <summary>
  70. /// WaitHandle to signal that exception was thrown by another thread.
  71. /// </summary>
  72. private EventWaitHandle _exceptionWaitHandle = new AutoResetEvent(false);
  73. /// <summary>
  74. /// WaitHandle to signal that key exchange was completed.
  75. /// </summary>
  76. private EventWaitHandle _keyExchangeCompletedWaitHandle = new ManualResetEvent(false);
  77. /// <summary>
  78. /// Exception that need to be thrown by waiting thread
  79. /// </summary>
  80. private Exception _exception;
  81. /// <summary>
  82. /// Specifies whether connection is authenticated
  83. /// </summary>
  84. private bool _isAuthenticated;
  85. /// <summary>
  86. /// Specifies whether user issued Disconnect command or not
  87. /// </summary>
  88. private bool _isDisconnecting;
  89. private KeyExchange _keyExchange;
  90. private HMac _serverMac;
  91. private HMac _clientMac;
  92. private Cipher _clientCipher;
  93. private Cipher _serverCipher;
  94. private Compressor _serverDecompression;
  95. private Compressor _clientCompression;
  96. private SemaphoreSlim _sessionSemaphore;
  97. /// <summary>
  98. /// Gets the session semaphore that controls session channels.
  99. /// </summary>
  100. /// <value>The session semaphore.</value>
  101. public SemaphoreSlim SessionSemaphore
  102. {
  103. get
  104. {
  105. if (this._sessionSemaphore == null)
  106. {
  107. lock (this)
  108. {
  109. if (this._sessionSemaphore == null)
  110. {
  111. this._sessionSemaphore = new SemaphoreSlim(this.ConnectionInfo.MaxSessions);
  112. }
  113. }
  114. }
  115. return this._sessionSemaphore;
  116. }
  117. }
  118. private bool _isDisconnectMessageSent;
  119. private uint _nextChannelNumber;
  120. /// <summary>
  121. /// Gets the next channel number.
  122. /// </summary>
  123. /// <value>The next channel number.</value>
  124. internal uint NextChannelNumber
  125. {
  126. get
  127. {
  128. uint result;
  129. lock (this)
  130. {
  131. result = this._nextChannelNumber++;
  132. }
  133. return result;
  134. }
  135. }
  136. /// <summary>
  137. /// Gets a value indicating whether socket connected.
  138. /// </summary>
  139. /// <value>
  140. /// <c>true</c> if socket connected; otherwise, <c>false</c>.
  141. /// </value>
  142. public bool IsConnected
  143. {
  144. get
  145. {
  146. return this._socket != null && this._socket.Connected && this._isAuthenticated && this._messageListener.Status == TaskStatus.Running;
  147. }
  148. }
  149. /// <summary>
  150. /// Gets or sets the session id.
  151. /// </summary>
  152. /// <value>The session id.</value>
  153. public byte[] SessionId { get; private set; }
  154. private Message _clientInitMessage;
  155. /// <summary>
  156. /// Gets the client init message.
  157. /// </summary>
  158. /// <value>The client init message.</value>
  159. public Message ClientInitMessage
  160. {
  161. get
  162. {
  163. if (this._clientInitMessage == null)
  164. {
  165. this._clientInitMessage = new KeyExchangeInitMessage()
  166. {
  167. KeyExchangeAlgorithms = this.ConnectionInfo.KeyExchangeAlgorithms.Keys,
  168. ServerHostKeyAlgorithms = this.ConnectionInfo.HostKeyAlgorithms.Keys,
  169. EncryptionAlgorithmsClientToServer = this.ConnectionInfo.Encryptions.Keys,
  170. EncryptionAlgorithmsServerToClient = this.ConnectionInfo.Encryptions.Keys,
  171. MacAlgorithmsClientToServer = this.ConnectionInfo.HmacAlgorithms.Keys,
  172. MacAlgorithmsServerToClient = this.ConnectionInfo.HmacAlgorithms.Keys,
  173. CompressionAlgorithmsClientToServer = this.ConnectionInfo.CompressionAlgorithms.Keys,
  174. CompressionAlgorithmsServerToClient = this.ConnectionInfo.CompressionAlgorithms.Keys,
  175. LanguagesClientToServer = new string[] { string.Empty },
  176. LanguagesServerToClient = new string[] { string.Empty },
  177. FirstKexPacketFollows = false,
  178. Reserved = 0,
  179. };
  180. }
  181. return this._clientInitMessage;
  182. }
  183. }
  184. /// <summary>
  185. /// Gets or sets the server version string.
  186. /// </summary>
  187. /// <value>The server version.</value>
  188. public string ServerVersion { get; private set; }
  189. /// <summary>
  190. /// Gets or sets the client version string.
  191. /// </summary>
  192. /// <value>The client version.</value>
  193. public string ClientVersion { get; private set; }
  194. /// <summary>
  195. /// Gets or sets the connection info.
  196. /// </summary>
  197. /// <value>The connection info.</value>
  198. public ConnectionInfo ConnectionInfo { get; private set; }
  199. /// <summary>
  200. /// Occurs when an error occurred.
  201. /// </summary>
  202. public event EventHandler<ExceptionEventArgs> ErrorOccured;
  203. /// <summary>
  204. /// Occurs when session has been disconnected form the server.
  205. /// </summary>
  206. public event EventHandler<EventArgs> Disconnected;
  207. #region Message events
  208. /// <summary>
  209. /// Occurs when <see cref="DisconnectMessage"/> message received
  210. /// </summary>
  211. internal event EventHandler<MessageEventArgs<DisconnectMessage>> DisconnectReceived;
  212. /// <summary>
  213. /// Occurs when <see cref="IgnoreMessage"/> message received
  214. /// </summary>
  215. internal event EventHandler<MessageEventArgs<IgnoreMessage>> IgnoreReceived;
  216. /// <summary>
  217. /// Occurs when <see cref="UnimplementedMessage"/> message received
  218. /// </summary>
  219. internal event EventHandler<MessageEventArgs<UnimplementedMessage>> UnimplementedReceived;
  220. /// <summary>
  221. /// Occurs when <see cref="DebugMessage"/> message received
  222. /// </summary>
  223. internal event EventHandler<MessageEventArgs<DebugMessage>> DebugReceived;
  224. /// <summary>
  225. /// Occurs when <see cref="ServiceRequestMessage"/> message received
  226. /// </summary>
  227. internal event EventHandler<MessageEventArgs<ServiceRequestMessage>> ServiceRequestReceived;
  228. /// <summary>
  229. /// Occurs when <see cref="ServiceAcceptMessage"/> message received
  230. /// </summary>
  231. internal event EventHandler<MessageEventArgs<ServiceAcceptMessage>> ServiceAcceptReceived;
  232. /// <summary>
  233. /// Occurs when <see cref="KeyExchangeInitMessage"/> message received
  234. /// </summary>
  235. internal event EventHandler<MessageEventArgs<KeyExchangeInitMessage>> KeyExchangeInitReceived;
  236. /// <summary>
  237. /// Occurs when <see cref="NewKeysMessage"/> message received
  238. /// </summary>
  239. internal event EventHandler<MessageEventArgs<NewKeysMessage>> NewKeysReceived;
  240. /// <summary>
  241. /// Occurs when <see cref="RequestMessage"/> message received
  242. /// </summary>
  243. internal event EventHandler<MessageEventArgs<RequestMessage>> UserAuthenticationRequestReceived;
  244. /// <summary>
  245. /// Occurs when <see cref="FailureMessage"/> message received
  246. /// </summary>
  247. internal event EventHandler<MessageEventArgs<FailureMessage>> UserAuthenticationFailureReceived;
  248. /// <summary>
  249. /// Occurs when <see cref="SuccessMessage"/> message received
  250. /// </summary>
  251. internal event EventHandler<MessageEventArgs<SuccessMessage>> UserAuthenticationSuccessReceived;
  252. /// <summary>
  253. /// Occurs when <see cref="BannerMessage"/> message received
  254. /// </summary>
  255. internal event EventHandler<MessageEventArgs<BannerMessage>> UserAuthenticationBannerReceived;
  256. /// <summary>
  257. /// Occurs when <see cref="GlobalRequestMessage"/> message received
  258. /// </summary>
  259. internal event EventHandler<MessageEventArgs<GlobalRequestMessage>> GlobalRequestReceived;
  260. /// <summary>
  261. /// Occurs when <see cref="RequestSuccessMessage"/> message received
  262. /// </summary>
  263. internal event EventHandler<MessageEventArgs<RequestSuccessMessage>> RequestSuccessReceived;
  264. /// <summary>
  265. /// Occurs when <see cref="RequestFailureMessage"/> message received
  266. /// </summary>
  267. internal event EventHandler<MessageEventArgs<RequestFailureMessage>> RequestFailureReceived;
  268. /// <summary>
  269. /// Occurs when <see cref="ChannelOpenMessage"/> message received
  270. /// </summary>
  271. internal event EventHandler<MessageEventArgs<ChannelOpenMessage>> ChannelOpenReceived;
  272. /// <summary>
  273. /// Occurs when <see cref="ChannelOpenConfirmationMessage"/> message received
  274. /// </summary>
  275. internal event EventHandler<MessageEventArgs<ChannelOpenConfirmationMessage>> ChannelOpenConfirmationReceived;
  276. /// <summary>
  277. /// Occurs when <see cref="ChannelOpenFailureMessage"/> message received
  278. /// </summary>
  279. internal event EventHandler<MessageEventArgs<ChannelOpenFailureMessage>> ChannelOpenFailureReceived;
  280. /// <summary>
  281. /// Occurs when <see cref="ChannelWindowAdjustMessage"/> message received
  282. /// </summary>
  283. internal event EventHandler<MessageEventArgs<ChannelWindowAdjustMessage>> ChannelWindowAdjustReceived;
  284. /// <summary>
  285. /// Occurs when <see cref="ChannelDataMessage"/> message received
  286. /// </summary>
  287. internal event EventHandler<MessageEventArgs<ChannelDataMessage>> ChannelDataReceived;
  288. /// <summary>
  289. /// Occurs when <see cref="ChannelExtendedDataMessage"/> message received
  290. /// </summary>
  291. internal event EventHandler<MessageEventArgs<ChannelExtendedDataMessage>> ChannelExtendedDataReceived;
  292. /// <summary>
  293. /// Occurs when <see cref="ChannelEofMessage"/> message received
  294. /// </summary>
  295. internal event EventHandler<MessageEventArgs<ChannelEofMessage>> ChannelEofReceived;
  296. /// <summary>
  297. /// Occurs when <see cref="ChannelCloseMessage"/> message received
  298. /// </summary>
  299. internal event EventHandler<MessageEventArgs<ChannelCloseMessage>> ChannelCloseReceived;
  300. /// <summary>
  301. /// Occurs when <see cref="ChannelRequestMessage"/> message received
  302. /// </summary>
  303. internal event EventHandler<MessageEventArgs<ChannelRequestMessage>> ChannelRequestReceived;
  304. /// <summary>
  305. /// Occurs when <see cref="ChannelSuccessMessage"/> message received
  306. /// </summary>
  307. internal event EventHandler<MessageEventArgs<ChannelSuccessMessage>> ChannelSuccessReceived;
  308. /// <summary>
  309. /// Occurs when <see cref="ChannelFailureMessage"/> message received
  310. /// </summary>
  311. internal event EventHandler<MessageEventArgs<ChannelFailureMessage>> ChannelFailureReceived;
  312. /// <summary>
  313. /// Occurs when message received and is not handled by any of the event handlers
  314. /// </summary>
  315. internal event EventHandler<MessageEventArgs<Message>> MessageReceived;
  316. #endregion
  317. /// <summary>
  318. /// Initializes a new instance of the <see cref="Session"/> class.
  319. /// </summary>
  320. /// <param name="connectionInfo">The connection info.</param>
  321. internal Session(ConnectionInfo connectionInfo)
  322. {
  323. this.ConnectionInfo = connectionInfo;
  324. this.ClientVersion = string.Format(CultureInfo.CurrentCulture, "SSH-2.0-Renci.SshNet.SshClient.{0}", this.GetType().Assembly.GetName().Version);
  325. }
  326. /// <summary>
  327. /// Connects to the server.
  328. /// </summary>
  329. public void Connect()
  330. {
  331. if (this.ConnectionInfo == null)
  332. {
  333. throw new ArgumentNullException("connectionInfo");
  334. }
  335. if (this.IsConnected)
  336. return;
  337. try
  338. {
  339. _authenticationConnection.Wait();
  340. if (this.IsConnected)
  341. return;
  342. lock (this)
  343. {
  344. // If connected don't connect again
  345. if (this.IsConnected)
  346. return;
  347. var ep = new IPEndPoint(Dns.GetHostAddresses(this.ConnectionInfo.Host)[0], this.ConnectionInfo.Port);
  348. this._socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  349. var socketBufferSize = 2 * MAXIMUM_PACKET_SIZE;
  350. this._socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  351. this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, socketBufferSize);
  352. this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, socketBufferSize);
  353. // Connect socket with 5 seconds timeout
  354. var connectResult = this._socket.BeginConnect(ep, null, null);
  355. connectResult.AsyncWaitHandle.WaitOne(this.ConnectionInfo.Timeout);
  356. // Build list of available messages while connecting
  357. this._messagesMetadata = (from type in this.GetType().Assembly.GetTypes()
  358. from messageAttribute in type.GetCustomAttributes(false).OfType<MessageAttribute>()
  359. select new MessageMetadata
  360. {
  361. Name = messageAttribute.Name,
  362. Number = messageAttribute.Number,
  363. Enabled = false,
  364. Activated = false,
  365. Type = type,
  366. }).ToList();
  367. this._socket.EndConnect(connectResult);
  368. Match versionMatch = null;
  369. // Get server version from the server,
  370. // ignore text lines which are sent before if any
  371. using (var ns = new NetworkStream(this._socket))
  372. {
  373. using (var sr = new StreamReader(ns))
  374. {
  375. while (true)
  376. {
  377. this.ServerVersion = sr.ReadLine();
  378. if (string.IsNullOrEmpty(this.ServerVersion))
  379. {
  380. throw new InvalidOperationException("Server string is null or empty.");
  381. }
  382. versionMatch = _serverVersionRe.Match(this.ServerVersion);
  383. if (versionMatch.Success)
  384. {
  385. break;
  386. }
  387. }
  388. }
  389. }
  390. // Get server SSH version
  391. var version = versionMatch.Result("${protoversion}");
  392. if (!(version.Equals("2.0") || version.Equals("1.99")))
  393. {
  394. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", version), DisconnectReason.ProtocolVersionNotSupported);
  395. }
  396. this.Write(Encoding.ASCII.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}\x0D\x0A", this.ClientVersion)));
  397. // Register Transport response messages
  398. this.RegisterMessage("SSH_MSG_DISCONNECT");
  399. this.RegisterMessage("SSH_MSG_IGNORE");
  400. this.RegisterMessage("SSH_MSG_UNIMPLEMENTED");
  401. this.RegisterMessage("SSH_MSG_DEBUG");
  402. this.RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
  403. this.RegisterMessage("SSH_MSG_KEXINIT");
  404. this.RegisterMessage("SSH_MSG_NEWKEYS");
  405. // Some server implementations might sent this message first, prior establishing encryption algorithm
  406. this.RegisterMessage("SSH_MSG_USERAUTH_BANNER");
  407. // Start incoming request listener
  408. this._messageListener = Task.Factory.StartNew(() => { this.MessageListener(); }, TaskCreationOptions.LongRunning);
  409. // Wait for key exchange to be completed
  410. this.WaitHandle(this._keyExchangeCompletedWaitHandle);
  411. // If sessionId is not set then its not connected
  412. if (this.SessionId == null)
  413. {
  414. this.Disconnect();
  415. return;
  416. }
  417. // Request user authorization service
  418. this.SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
  419. // Wait for service to be accepted
  420. this.WaitHandle(this._serviceAccepted);
  421. if (string.IsNullOrEmpty(this.ConnectionInfo.Username))
  422. {
  423. throw new SshException("Username is not specified.");
  424. }
  425. // Try authenticate using none method
  426. using (var noneConnectionInfo = new NoneConnectionInfo(this.ConnectionInfo.Host, this.ConnectionInfo.Port, this.ConnectionInfo.Username))
  427. {
  428. noneConnectionInfo.Authenticate(this);
  429. this._isAuthenticated = noneConnectionInfo.IsAuthenticated;
  430. if (!this._isAuthenticated)
  431. {
  432. // Ensure that authentication method is allowed
  433. if (!noneConnectionInfo.AllowedAuthentications.Contains(this.ConnectionInfo.Name))
  434. {
  435. throw new SshAuthenticationException("User authentication method is not supported.");
  436. }
  437. // In future, if more then one authentication methods are supported perform the check here.
  438. // Authenticate using provided connection info object
  439. this.ConnectionInfo.Authenticate(this);
  440. this._isAuthenticated = this.ConnectionInfo.IsAuthenticated;
  441. }
  442. }
  443. if (!this._isAuthenticated)
  444. {
  445. throw new SshAuthenticationException("User cannot be authenticated.");
  446. }
  447. // Register Connection messages
  448. this.RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
  449. this.RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
  450. this.RegisterMessage("SSH_MSG_REQUEST_FAILURE");
  451. this.RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
  452. this.RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
  453. this.RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
  454. this.RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
  455. this.RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
  456. this.RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
  457. this.RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
  458. this.RegisterMessage("SSH_MSG_CHANNEL_DATA");
  459. this.RegisterMessage("SSH_MSG_CHANNEL_EOF");
  460. this.RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
  461. Monitor.Pulse(this);
  462. }
  463. }
  464. finally
  465. {
  466. _authenticationConnection.Release();
  467. }
  468. }
  469. /// <summary>
  470. /// Disconnects from the server
  471. /// </summary>
  472. public void Disconnect()
  473. {
  474. this.Dispose();
  475. }
  476. internal T CreateChannel<T>() where T : Channel, new()
  477. {
  478. return CreateChannel<T>(0, 0x100000, 0x8000);
  479. }
  480. internal T CreateChannel<T>(uint serverChannelNumber, uint windowSize, uint packetSize) where T : Channel, new()
  481. {
  482. T channel = new T();
  483. lock (this)
  484. {
  485. channel.Initialize(this, serverChannelNumber, windowSize, packetSize);
  486. }
  487. return channel;
  488. }
  489. /// <summary>
  490. /// Sends "keep alive" message to keep connection alive.
  491. /// </summary>
  492. internal void SendKeepAlive()
  493. {
  494. this.SendMessage(new IgnoreMessage());
  495. }
  496. /// <summary>
  497. /// Waits for handle to signal while checking other handles as well including timeout check to prevent waiting for ever
  498. /// </summary>
  499. /// <param name="waitHandle">The wait handle.</param>
  500. internal void WaitHandle(WaitHandle waitHandle)
  501. {
  502. var waitHandles = new WaitHandle[]
  503. {
  504. this._exceptionWaitHandle,
  505. waitHandle,
  506. };
  507. var index = EventWaitHandle.WaitAny(waitHandles, this.ConnectionInfo.Timeout);
  508. if (index < 1)
  509. {
  510. throw this._exception;
  511. }
  512. else if (index > 1)
  513. {
  514. this.SendDisconnect(DisconnectReason.ByApplication, "Operation timeout");
  515. throw new SshOperationTimeoutException("Session operation has timed out");
  516. }
  517. }
  518. /// <summary>
  519. /// Sends packet message to the server.
  520. /// </summary>
  521. /// <param name="message">The message.</param>
  522. internal void SendMessage(Message message)
  523. {
  524. if (this._socket == null || !this._socket.Connected)
  525. return;
  526. // Messages can be sent by different thread so we need to synchronize it
  527. var paddingMultiplier = this._clientCipher == null ? (byte)8 : (byte)this._clientCipher.BlockSize; // Should be recalculate base on cipher min length if cipher specified
  528. var messageData = message.GetBytes();
  529. if (messageData.Length > Session.MAXIMUM_PAYLOAD_SIZE)
  530. {
  531. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Payload cannot be more then {0} bytes.", Session.MAXIMUM_PAYLOAD_SIZE));
  532. }
  533. if (this._clientCompression != null)
  534. {
  535. messageData = this._clientCompression.Compress(messageData);
  536. }
  537. var packetLength = messageData.Length + 4 + 1; // add length bytes and padding byte
  538. byte paddingLength = (byte)((-packetLength) & (paddingMultiplier - 1));
  539. if (paddingLength < paddingMultiplier)
  540. {
  541. paddingLength += paddingMultiplier;
  542. }
  543. // Build Packet data
  544. var packetData = new byte[4 + 1 + messageData.Length + paddingLength];
  545. // Add packet length
  546. ((uint)packetData.Length - 4).GetBytes().CopyTo(packetData, 0);
  547. // Add packet padding length
  548. packetData[4] = paddingLength;
  549. // Add packet payload
  550. messageData.CopyTo(packetData, 4 + 1);
  551. // Add random padding
  552. var paddingBytes = new byte[paddingLength];
  553. _randomizer.GetBytes(paddingBytes);
  554. paddingBytes.CopyTo(packetData, 4 + 1 + messageData.Length);
  555. // Lock handling of _outboundPacketSequence since it must be sent sequently to server
  556. lock (this._socket)
  557. {
  558. // Calculate packet hash
  559. var hashData = new byte[4 + packetData.Length];
  560. this._outboundPacketSequence.GetBytes().CopyTo(hashData, 0);
  561. packetData.CopyTo(hashData, 4);
  562. // Encrypt packet data
  563. if (this._clientCipher != null)
  564. {
  565. packetData = this._clientCipher.Encrypt(packetData);
  566. }
  567. if (packetData.Length > Session.MAXIMUM_PACKET_SIZE)
  568. {
  569. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Packet is too big. Maximum packet size is {0} bytes.", Session.MAXIMUM_PACKET_SIZE));
  570. }
  571. if (this._clientMac == null)
  572. {
  573. this.Write(packetData);
  574. }
  575. else
  576. {
  577. var hash = this._clientMac.ComputeHash(hashData.ToArray());
  578. var data = new byte[packetData.Length + this._clientMac.HashSize / 8];
  579. packetData.CopyTo(data, 0);
  580. hash.CopyTo(data, packetData.Length);
  581. this.Write(data);
  582. }
  583. this._outboundPacketSequence++;
  584. Monitor.Pulse(this._socket);
  585. }
  586. }
  587. /// <summary>
  588. /// Receives the message from the server.
  589. /// </summary>
  590. /// <returns></returns>
  591. private Message ReceiveMessage()
  592. {
  593. if (!this._socket.Connected)
  594. return null;
  595. // No lock needed since all messages read by only one thread
  596. var blockSize = this._serverCipher == null ? (byte)8 : (byte)this._serverCipher.BlockSize;
  597. // Read packet length first
  598. var firstBlock = this.Read(blockSize);
  599. if (this._serverCipher != null)
  600. {
  601. firstBlock = this._serverCipher.Decrypt(firstBlock);
  602. }
  603. var packetLength = (uint)(firstBlock[0] << 24 | firstBlock[1] << 16 | firstBlock[2] << 8 | firstBlock[3]);
  604. // Test packet minimum and maximum boundaries
  605. if (packetLength < Math.Max((byte)16, blockSize) - 4 || packetLength > Session.MAXIMUM_PACKET_SIZE - 4)
  606. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length {0}", packetLength), DisconnectReason.ProtocolError);
  607. // Read rest of the packet data
  608. int bytesToRead = (int)(packetLength - (blockSize - 4));
  609. var data = new byte[bytesToRead + blockSize];
  610. firstBlock.CopyTo(data, 0);
  611. byte[] serverHash = null;
  612. if (this._serverMac != null)
  613. {
  614. serverHash = new byte[this._serverMac.HashSize / 8];
  615. bytesToRead += serverHash.Length;
  616. }
  617. if (bytesToRead > 0)
  618. {
  619. var nextBlocks = this.Read(bytesToRead);
  620. if (serverHash != null)
  621. {
  622. Array.Copy(nextBlocks, nextBlocks.Length - serverHash.Length, serverHash, 0, serverHash.Length);
  623. nextBlocks = nextBlocks.Take(nextBlocks.Length - serverHash.Length).ToArray();
  624. }
  625. if (nextBlocks.Length > 0)
  626. {
  627. if (this._serverCipher != null)
  628. {
  629. nextBlocks = this._serverCipher.Decrypt(nextBlocks);
  630. }
  631. nextBlocks.CopyTo(data, blockSize);
  632. }
  633. }
  634. var paddingLength = data[4];
  635. var messagePayload = new byte[packetLength - paddingLength - 1];
  636. Array.Copy(data, 5, messagePayload, 0, messagePayload.Length);
  637. if (this._serverDecompression != null)
  638. {
  639. messagePayload = this._serverDecompression.Decompress(messagePayload);
  640. }
  641. // Validate message against MAC
  642. if (this._serverMac != null)
  643. {
  644. var clientHashData = new byte[4 + data.Length];
  645. var lengthBytes = this._inboundPacketSequence.GetBytes();
  646. lengthBytes.CopyTo(clientHashData, 0);
  647. data.CopyTo(clientHashData, 4);
  648. // Calculate packet hash
  649. var clientHash = this._serverMac.ComputeHash(clientHashData);
  650. if (!serverHash.SequenceEqual(clientHash))
  651. {
  652. throw new SshConnectionException("MAC error", DisconnectReason.MacError);
  653. }
  654. }
  655. this._inboundPacketSequence++;
  656. return this.LoadMessage(messagePayload);
  657. }
  658. private void SendDisconnect(DisconnectReason reasonCode, string message)
  659. {
  660. // If disconnect message was sent already dont send it again
  661. if (this._isDisconnectMessageSent)
  662. return;
  663. var disconnectMessage = new DisconnectMessage(reasonCode, message);
  664. this.SendMessage(disconnectMessage);
  665. this._isDisconnectMessageSent = true;
  666. }
  667. /// <summary>
  668. /// Handles the message.
  669. /// </summary>
  670. /// <typeparam name="T"></typeparam>
  671. /// <param name="message">The message.</param>
  672. private void HandleMessage<T>(T message) where T : Message
  673. {
  674. this.OnMessageReceived(message);
  675. }
  676. #region Handle transport messages
  677. private void HandleMessage(DisconnectMessage message)
  678. {
  679. this.OnDisconnectReceived(message);
  680. // Shutdown and disconnect from the socket
  681. if (this._socket != null)
  682. {
  683. lock (this._socket)
  684. {
  685. if (this._socket != null)
  686. {
  687. this._socket.Disconnect(true);
  688. // When socket is disconnected wait for listener to finish
  689. if (this._messageListener != null)
  690. {
  691. // Wait for listener task to finish
  692. this._messageListener.Wait();
  693. this._messageListener = null;
  694. }
  695. this._socket.Dispose();
  696. this._socket = null;
  697. }
  698. }
  699. }
  700. }
  701. private void HandleMessage(IgnoreMessage message)
  702. {
  703. this.OnIgnoreReceived(message);
  704. }
  705. private void HandleMessage(UnimplementedMessage message)
  706. {
  707. this.OnUnimplementedReceived(message);
  708. }
  709. private void HandleMessage(DebugMessage message)
  710. {
  711. this.OnDebugReceived(message);
  712. }
  713. private void HandleMessage(ServiceRequestMessage message)
  714. {
  715. this.OnServiceRequestReceived(message);
  716. }
  717. private void HandleMessage(ServiceAcceptMessage message)
  718. {
  719. // TODO: Refactor to avoid this method here
  720. this.OnServiceAcceptReceived(message);
  721. this._serviceAccepted.Set();
  722. }
  723. private void HandleMessage(KeyExchangeInitMessage message)
  724. {
  725. this.OnKeyExchangeInitReceived(message);
  726. }
  727. private void HandleMessage(NewKeysMessage message)
  728. {
  729. this.OnNewKeysReceived(message);
  730. }
  731. #endregion
  732. #region Handle User Authentication messages
  733. private void HandleMessage(RequestMessage message)
  734. {
  735. this.OnUserAuthenticationRequestReceived(message);
  736. }
  737. private void HandleMessage(FailureMessage message)
  738. {
  739. this.OnUserAuthenticationFailureReceived(message);
  740. }
  741. private void HandleMessage(SuccessMessage message)
  742. {
  743. this.OnUserAuthenticationSuccessReceived(message);
  744. }
  745. private void HandleMessage(BannerMessage message)
  746. {
  747. this.OnUserAuthenticationBannerReceived(message);
  748. }
  749. #endregion
  750. #region Handle connection messages
  751. private void HandleMessage(GlobalRequestMessage message)
  752. {
  753. this.OnGlobalRequestReceived(message);
  754. }
  755. private void HandleMessage(RequestSuccessMessage message)
  756. {
  757. this.OnRequestSuccessReceived(message);
  758. }
  759. private void HandleMessage(RequestFailureMessage message)
  760. {
  761. this.OnRequestFailureReceived(message);
  762. }
  763. private void HandleMessage(ChannelOpenMessage message)
  764. {
  765. this.OnChannelOpenReceived(message);
  766. }
  767. private void HandleMessage(ChannelOpenConfirmationMessage message)
  768. {
  769. this.OnChannelOpenConfirmationReceived(message);
  770. }
  771. private void HandleMessage(ChannelOpenFailureMessage message)
  772. {
  773. this.OnChannelOpenFailureReceived(message);
  774. }
  775. private void HandleMessage(ChannelWindowAdjustMessage message)
  776. {
  777. this.OnChannelWindowAdjustReceived(message);
  778. }
  779. private void HandleMessage(ChannelDataMessage message)
  780. {
  781. this.OnChannelDataReceived(message);
  782. }
  783. private void HandleMessage(ChannelExtendedDataMessage message)
  784. {
  785. this.OnChannelExtendedDataReceived(message);
  786. }
  787. private void HandleMessage(ChannelEofMessage message)
  788. {
  789. this.OnChannelEofReceived(message);
  790. }
  791. private void HandleMessage(ChannelCloseMessage message)
  792. {
  793. this.OnChannelCloseReceived(message);
  794. }
  795. private void HandleMessage(ChannelRequestMessage message)
  796. {
  797. this.OnChannelRequestReceived(message);
  798. }
  799. private void HandleMessage(ChannelSuccessMessage message)
  800. {
  801. this.OnChannelSuccessReceived(message);
  802. }
  803. private void HandleMessage(ChannelFailureMessage message)
  804. {
  805. this.OnChannelFailureReceived(message);
  806. }
  807. #endregion
  808. #region Handle received message events
  809. /// <summary>
  810. /// Called when <see cref="DisconnectMessage"/> received.
  811. /// </summary>
  812. /// <param name="message"><see cref="DisconnectMessage"/> message.</param>
  813. protected virtual void OnDisconnectReceived(DisconnectMessage message)
  814. {
  815. if (this.DisconnectReceived != null)
  816. {
  817. this.DisconnectReceived(this, new MessageEventArgs<DisconnectMessage>(message));
  818. }
  819. if (this.Disconnected != null)
  820. {
  821. this.Disconnected(this, new EventArgs());
  822. }
  823. }
  824. /// <summary>
  825. /// Called when <see cref="IgnoreMessage"/> received.
  826. /// </summary>
  827. /// <param name="message"><see cref="IgnoreMessage"/> message.</param>
  828. protected virtual void OnIgnoreReceived(IgnoreMessage message)
  829. {
  830. if (this.IgnoreReceived != null)
  831. {
  832. this.IgnoreReceived(this, new MessageEventArgs<IgnoreMessage>(message));
  833. }
  834. }
  835. /// <summary>
  836. /// Called when <see cref="UnimplementedMessage"/> message received.
  837. /// </summary>
  838. /// <param name="message"><see cref="UnimplementedMessage"/> message.</param>
  839. protected virtual void OnUnimplementedReceived(UnimplementedMessage message)
  840. {
  841. if (this.UnimplementedReceived != null)
  842. {
  843. this.UnimplementedReceived(this, new MessageEventArgs<UnimplementedMessage>(message));
  844. }
  845. }
  846. /// <summary>
  847. /// Called when <see cref="DebugMessage"/> message received.
  848. /// </summary>
  849. /// <param name="message"><see cref="DebugMessage"/> message.</param>
  850. protected virtual void OnDebugReceived(DebugMessage message)
  851. {
  852. if (this.DebugReceived != null)
  853. {
  854. this.DebugReceived(this, new MessageEventArgs<DebugMessage>(message));
  855. }
  856. }
  857. /// <summary>
  858. /// Called when <see cref="ServiceRequestMessage"/> message received.
  859. /// </summary>
  860. /// <param name="message"><see cref="ServiceRequestMessage"/> message.</param>
  861. protected virtual void OnServiceRequestReceived(ServiceRequestMessage message)
  862. {
  863. if (this.ServiceRequestReceived != null)
  864. {
  865. this.ServiceRequestReceived(this, new MessageEventArgs<ServiceRequestMessage>(message));
  866. }
  867. }
  868. /// <summary>
  869. /// Called when <see cref="ServiceAcceptMessage"/> message received.
  870. /// </summary>
  871. /// <param name="message"><see cref="ServiceAcceptMessage"/> message.</param>
  872. protected virtual void OnServiceAcceptReceived(ServiceAcceptMessage message)
  873. {
  874. if (this.ServiceAcceptReceived != null)
  875. {
  876. this.ServiceAcceptReceived(this, new MessageEventArgs<ServiceAcceptMessage>(message));
  877. }
  878. }
  879. /// <summary>
  880. /// Called when <see cref="KeyExchangeInitMessage"/> message received.
  881. /// </summary>
  882. /// <param name="message"><see cref="KeyExchangeInitMessage"/> message.</param>
  883. protected virtual void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
  884. {
  885. this._keyExchangeCompletedWaitHandle.Reset();
  886. // Disable all registered messages except key exchange related
  887. foreach (var messageMetadata in this._messagesMetadata)
  888. {
  889. if (messageMetadata.Activated == true && messageMetadata.Number > 2 && (messageMetadata.Number < 20 || messageMetadata.Number > 30))
  890. messageMetadata.Enabled = false;
  891. }
  892. var keyExchangeAlgorithmName = (from c in this.ConnectionInfo.KeyExchangeAlgorithms.Keys
  893. from s in message.KeyExchangeAlgorithms
  894. where s == c
  895. select c).FirstOrDefault();
  896. if (keyExchangeAlgorithmName == null)
  897. {
  898. throw new SshConnectionException("Failed to negotiate key exchange algorithm.", DisconnectReason.KeyExchangeFailed);
  899. }
  900. // Create instance of key exchange algorithm that will be used
  901. this._keyExchange = this.ConnectionInfo.KeyExchangeAlgorithms[keyExchangeAlgorithmName].CreateInstance<KeyExchange>();
  902. // Start the algorithm implementation
  903. this._keyExchange.Start(this, message);
  904. if (this.KeyExchangeInitReceived != null)
  905. {
  906. this.KeyExchangeInitReceived(this, new MessageEventArgs<KeyExchangeInitMessage>(message));
  907. }
  908. }
  909. /// <summary>
  910. /// Called when <see cref="NewKeysMessage"/> message received.
  911. /// </summary>
  912. /// <param name="message"><see cref="NewKeysMessage"/> message.</param>
  913. protected virtual void OnNewKeysReceived(NewKeysMessage message)
  914. {
  915. // Update sessionId
  916. if (this.SessionId == null)
  917. {
  918. this.SessionId = this._keyExchange.ExchangeHash;
  919. }
  920. // Dispose of old ciphers and hash algorithms
  921. if (this._serverCipher != null)
  922. {
  923. this._serverCipher.Dispose();
  924. this._serverCipher = null;
  925. }
  926. if (this._clientCipher != null)
  927. {
  928. this._clientCipher.Dispose();
  929. this._clientCipher = null;
  930. }
  931. if (this._serverMac != null)
  932. {
  933. this._serverMac.Dispose();
  934. this._serverMac = null;
  935. }
  936. if (this._clientMac != null)
  937. {
  938. this._clientMac.Dispose();
  939. this._clientMac = null;
  940. }
  941. // Update negotiated algorithms
  942. this._serverCipher = this._keyExchange.CreateServerCipher();
  943. this._clientCipher = this._keyExchange.CreateClientCipher();
  944. this._serverMac = this._keyExchange.CreateServerHash();
  945. this._clientMac = this._keyExchange.CreateClientHash();
  946. this._clientCompression = this._keyExchange.CreateCompressor();
  947. this._serverDecompression = this._keyExchange.CreateDecompressor();
  948. // Dispose of old KeyExchange object as it is no longer needed.
  949. if (this._keyExchange != null)
  950. {
  951. this._keyExchange.Dispose();
  952. this._keyExchange = null;
  953. }
  954. // Enable all active registered messages
  955. foreach (var messageMetadata in this._messagesMetadata)
  956. {
  957. if (messageMetadata.Activated == true)
  958. messageMetadata.Enabled = true;
  959. }
  960. if (this.NewKeysReceived != null)
  961. {
  962. this.NewKeysReceived(this, new MessageEventArgs<NewKeysMessage>(message));
  963. }
  964. // Signal that key exchange completed
  965. this._keyExchangeCompletedWaitHandle.Set();
  966. }
  967. /// <summary>
  968. /// Called when <see cref="RequestMessage"/> message received.
  969. /// </summary>
  970. /// <param name="message"><see cref="RequestMessage"/> message.</param>
  971. protected virtual void OnUserAuthenticationRequestReceived(RequestMessage message)
  972. {
  973. if (this.UserAuthenticationRequestReceived != null)
  974. {
  975. this.UserAuthenticationRequestReceived(this, new MessageEventArgs<RequestMessage>(message));
  976. }
  977. }
  978. /// <summary>
  979. /// Called when <see cref="FailureMessage"/> message received.
  980. /// </summary>
  981. /// <param name="message"><see cref="FailureMessage"/> message.</param>
  982. protected virtual void OnUserAuthenticationFailureReceived(FailureMessage message)
  983. {
  984. if (this.UserAuthenticationFailureReceived != null)
  985. {
  986. this.UserAuthenticationFailureReceived(this, new MessageEventArgs<FailureMessage>(message));
  987. }
  988. }
  989. /// <summary>
  990. /// Called when <see cref="SuccessMessage"/> message received.
  991. /// </summary>
  992. /// <param name="message"><see cref="SuccessMessage"/> message.</param>
  993. protected virtual void OnUserAuthenticationSuccessReceived(SuccessMessage message)
  994. {
  995. if (this.UserAuthenticationSuccessReceived != null)
  996. {
  997. this.UserAuthenticationSuccessReceived(this, new MessageEventArgs<SuccessMessage>(message));
  998. }
  999. }
  1000. /// <summary>
  1001. /// Called when <see cref="BannerMessage"/> message received.
  1002. /// </summary>
  1003. /// <param name="message"><see cref="BannerMessage"/> message.</param>
  1004. protected virtual void OnUserAuthenticationBannerReceived(BannerMessage message)
  1005. {
  1006. if (this.UserAuthenticationBannerReceived != null)
  1007. {
  1008. this.UserAuthenticationBannerReceived(this, new MessageEventArgs<BannerMessage>(message));
  1009. }
  1010. }
  1011. /// <summary>
  1012. /// Called when <see cref="GlobalRequestMessage"/> message received.
  1013. /// </summary>
  1014. /// <param name="message"><see cref="GlobalRequestMessage"/> message.</param>
  1015. protected virtual void OnGlobalRequestReceived(GlobalRequestMessage message)
  1016. {
  1017. if (this.GlobalRequestReceived != null)
  1018. {
  1019. this.GlobalRequestReceived(this, new MessageEventArgs<GlobalRequestMessage>(message));
  1020. }
  1021. }
  1022. /// <summary>
  1023. /// Called when <see cref="RequestSuccessMessage"/> message received.
  1024. /// </summary>
  1025. /// <param name="message"><see cref="RequestSuccessMessage"/> message.</param>
  1026. protected virtual void OnRequestSuccessReceived(RequestSuccessMessage message)
  1027. {
  1028. if (this.RequestSuccessReceived != null)
  1029. {
  1030. this.RequestSuccessReceived(this, new MessageEventArgs<RequestSuccessMessage>(message));
  1031. }
  1032. }
  1033. /// <summary>
  1034. /// Called when <see cref="RequestFailureMessage"/> message received.
  1035. /// </summary>
  1036. /// <param name="message"><see cref="RequestFailureMessage"/> message.</param>
  1037. protected virtual void OnRequestFailureReceived(RequestFailureMessage message)
  1038. {
  1039. if (this.RequestFailureReceived != null)
  1040. {
  1041. this.RequestFailureReceived(this, new MessageEventArgs<RequestFailureMessage>(message));
  1042. }
  1043. }
  1044. /// <summary>
  1045. /// Called when <see cref="ChannelOpenMessage"/> message received.
  1046. /// </summary>
  1047. /// <param name="message"><see cref="ChannelOpenMessage"/> message.</param>
  1048. protected virtual void OnChannelOpenReceived(ChannelOpenMessage message)
  1049. {
  1050. if (this.ChannelOpenReceived != null)
  1051. {
  1052. this.ChannelOpenReceived(this, new MessageEventArgs<ChannelOpenMessage>(message));
  1053. }
  1054. }
  1055. /// <summary>
  1056. /// Called when <see cref="ChannelOpenConfirmationMessage"/> message received.
  1057. /// </summary>
  1058. /// <param name="message"><see cref="ChannelOpenConfirmationMessage"/> message.</param>
  1059. protected virtual void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage message)
  1060. {
  1061. if (this.ChannelOpenConfirmationReceived != null)
  1062. {
  1063. this.ChannelOpenConfirmationReceived(this, new MessageEventArgs<ChannelOpenConfirmationMessage>(message));
  1064. }
  1065. }
  1066. /// <summary>
  1067. /// Called when <see cref="ChannelOpenFailureMessage"/> message received.
  1068. /// </summary>
  1069. /// <param name="message"><see cref="ChannelOpenFailureMessage"/> message.</param>
  1070. protected virtual void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
  1071. {
  1072. if (this.ChannelOpenFailureReceived != null)
  1073. {
  1074. this.ChannelOpenFailureReceived(this, new MessageEventArgs<ChannelOpenFailureMessage>(message));
  1075. }
  1076. }
  1077. /// <summary>
  1078. /// Called when <see cref="ChannelWindowAdjustMessage"/> message received.
  1079. /// </summary>
  1080. /// <param name="message"><see cref="ChannelWindowAdjustMessage"/> message.</param>
  1081. protected virtual void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
  1082. {
  1083. if (this.ChannelWindowAdjustReceived != null)
  1084. {
  1085. this.ChannelWindowAdjustReceived(this, new MessageEventArgs<ChannelWindowAdjustMessage>(message));
  1086. }
  1087. }
  1088. /// <summary>
  1089. /// Called when <see cref="ChannelDataMessage"/> message received.
  1090. /// </summary>
  1091. /// <param name="message"><see cref="ChannelDataMessage"/> message.</param>
  1092. protected virtual void OnChannelDataReceived(ChannelDataMessage message)
  1093. {
  1094. if (this.ChannelDataReceived != null)
  1095. {
  1096. this.ChannelDataReceived(this, new MessageEventArgs<ChannelDataMessage>(message));
  1097. }
  1098. }
  1099. /// <summary>
  1100. /// Called when <see cref="ChannelExtendedDataMessage"/> message received.
  1101. /// </summary>
  1102. /// <param name="message"><see cref="ChannelExtendedDataMessage"/> message.</param>
  1103. protected virtual void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
  1104. {
  1105. if (this.ChannelExtendedDataReceived != null)
  1106. {
  1107. this.ChannelExtendedDataReceived(this, new MessageEventArgs<ChannelExtendedDataMessage>(message));
  1108. }
  1109. }
  1110. /// <summary>
  1111. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1112. /// </summary>
  1113. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1114. protected virtual void OnChannelEofReceived(ChannelEofMessage message)
  1115. {
  1116. if (this.ChannelEofReceived != null)
  1117. {
  1118. this.ChannelEofReceived(this, new MessageEventArgs<ChannelEofMessage>(message));
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1123. /// </summary>
  1124. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1125. protected virtual void OnChannelCloseReceived(ChannelCloseMessage message)
  1126. {
  1127. if (this.ChannelCloseReceived != null)
  1128. {
  1129. this.ChannelCloseReceived(this, new MessageEventArgs<ChannelCloseMessage>(message));
  1130. }
  1131. }
  1132. /// <summary>
  1133. /// Called when <see cref="ChannelRequestMessage"/> message received.
  1134. /// </summary>
  1135. /// <param name="message"><see cref="ChannelRequestMessage"/> message.</param>
  1136. protected virtual void OnChannelRequestReceived(ChannelRequestMessage message)
  1137. {
  1138. if (this.ChannelRequestReceived != null)
  1139. {
  1140. this.ChannelRequestReceived(this, new MessageEventArgs<ChannelRequestMessage>(message));
  1141. }
  1142. }
  1143. /// <summary>
  1144. /// Called when <see cref="ChannelSuccessMessage"/> message received.
  1145. /// </summary>
  1146. /// <param name="message"><see cref="ChannelSuccessMessage"/> message.</param>
  1147. protected virtual void OnChannelSuccessReceived(ChannelSuccessMessage message)
  1148. {
  1149. if (this.ChannelSuccessReceived != null)
  1150. {
  1151. this.ChannelSuccessReceived(this, new MessageEventArgs<ChannelSuccessMessage>(message));
  1152. }
  1153. }
  1154. /// <summary>
  1155. /// Called when <see cref="ChannelFailureMessage"/> message received.
  1156. /// </summary>
  1157. /// <param name="message"><see cref="ChannelFailureMessage"/> message.</param>
  1158. protected virtual void OnChannelFailureReceived(ChannelFailureMessage message)
  1159. {
  1160. if (this.ChannelFailureReceived != null)
  1161. {
  1162. this.ChannelFailureReceived(this, new MessageEventArgs<ChannelFailureMessage>(message));
  1163. }
  1164. }
  1165. /// <summary>
  1166. /// Called when <see cref="Message"/> message received.
  1167. /// </summary>
  1168. /// <param name="message"><see cref="Message"/> message.</param>
  1169. protected virtual void OnMessageReceived(Message message)
  1170. {
  1171. if (this.MessageReceived != null)
  1172. {
  1173. this.MessageReceived(this, new MessageEventArgs<Message>(message));
  1174. }
  1175. }
  1176. #endregion
  1177. #region Read & Write operations
  1178. /// <summary>
  1179. /// Reads the specified length of bytes from the server
  1180. /// </summary>
  1181. /// <param name="length">The length.</param>
  1182. /// <returns></returns>
  1183. private byte[] Read(int length)
  1184. {
  1185. var buffer = new byte[length];
  1186. var offset = 0;
  1187. int receivedTotal = 0; // how many bytes is already received
  1188. do
  1189. {
  1190. try
  1191. {
  1192. var receivedBytes = this._socket.Receive(buffer, offset + receivedTotal, length - receivedTotal, SocketFlags.None);
  1193. if (receivedBytes > 0)
  1194. {
  1195. receivedTotal += receivedBytes;
  1196. continue;
  1197. }
  1198. else
  1199. {
  1200. throw new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
  1201. }
  1202. }
  1203. catch (SocketException exp)
  1204. {
  1205. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  1206. exp.SocketErrorCode == SocketError.IOPending ||
  1207. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  1208. {
  1209. // socket buffer is probably empty, wait and try again
  1210. Thread.Sleep(30);
  1211. }
  1212. else
  1213. throw; // any serious error occurred
  1214. }
  1215. } while (receivedTotal < length);
  1216. return buffer;
  1217. }
  1218. /// <summary>
  1219. /// Writes the specified data to the server.
  1220. /// </summary>
  1221. /// <param name="data">The data.</param>
  1222. private void Write(byte[] data)
  1223. {
  1224. int sent = 0; // how many bytes is already sent
  1225. int length = data.Length;
  1226. do
  1227. {
  1228. try
  1229. {
  1230. sent += this._socket.Send(data, sent, length - sent, SocketFlags.None);
  1231. }
  1232. catch (SocketException ex)
  1233. {
  1234. if (ex.SocketErrorCode == SocketError.WouldBlock ||
  1235. ex.SocketErrorCode == SocketError.IOPending ||
  1236. ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  1237. {
  1238. // socket buffer is probably full, wait and try again
  1239. Thread.Sleep(30);
  1240. }
  1241. else
  1242. throw; // any serious error occurr
  1243. }
  1244. } while (sent < length);
  1245. }
  1246. #endregion
  1247. #region Message loading functions
  1248. /// <summary>
  1249. /// Registers SSH Message with the session.
  1250. /// </summary>
  1251. /// <param name="messageName">Name of the message.</param>
  1252. public void RegisterMessage(string messageName)
  1253. {
  1254. lock (this._messagesMetadata)
  1255. {
  1256. Parallel.ForEach(
  1257. from m in this._messagesMetadata where m.Name == messageName select m,
  1258. (item) => { item.Enabled = true; item.Activated = true; });
  1259. }
  1260. }
  1261. /// <summary>
  1262. /// Removes SSH message from the session
  1263. /// </summary>
  1264. /// <param name="messageName">Name of the message.</param>
  1265. public void UnRegisterMessage(string messageName)
  1266. {
  1267. lock (this._messagesMetadata)
  1268. {
  1269. Parallel.ForEach(
  1270. from m in this._messagesMetadata where m.Name == messageName select m,
  1271. (item) => { item.Enabled = false; item.Activated = false; });
  1272. }
  1273. }
  1274. /// <summary>
  1275. /// Loads the message.
  1276. /// </summary>
  1277. /// <param name="data">Message data.</param>
  1278. /// <returns>New message</returns>
  1279. private Message LoadMessage(byte[] data)
  1280. {
  1281. var messageType = data[0];
  1282. var messageMetadata = (from m in this._messagesMetadata where m.Number == messageType && m.Enabled && m.Activated select m).SingleOrDefault();
  1283. if (messageMetadata == null)
  1284. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Message type {0} is not valid.", messageType));
  1285. var message = messageMetadata.Type.CreateInstance<Message>();
  1286. message.Load(data);
  1287. return message;
  1288. }
  1289. #endregion
  1290. /// <summary>
  1291. /// Listens for incoming message from the server and handles them. This method run as a task on separate thread.
  1292. /// </summary>
  1293. private void MessageListener()
  1294. {
  1295. try
  1296. {
  1297. while (this._socket.Connected)
  1298. {
  1299. var message = this.ReceiveMessage();
  1300. if (message == null)
  1301. {
  1302. throw new NullReferenceException("The 'message' variable cannot be null");
  1303. }
  1304. else
  1305. {
  1306. this.HandleMessage((dynamic)message);
  1307. }
  1308. }
  1309. }
  1310. catch (Exception exp)
  1311. {
  1312. this.RaiseError(exp);
  1313. }
  1314. }
  1315. /// <summary>
  1316. /// Raises the <see cref="ErrorOccured"/> event.
  1317. /// </summary>
  1318. /// <param name="exp">The exp.</param>
  1319. private void RaiseError(Exception exp)
  1320. {
  1321. var connectionException = exp as SshConnectionException;
  1322. // If connection exception was raised while isDisconnecting is true then this is expected
  1323. // case and should be ignore
  1324. if (connectionException != null && this._isDisconnecting)
  1325. return;
  1326. this._exception = exp;
  1327. this._exceptionWaitHandle.Set();
  1328. if (this.ErrorOccured != null)
  1329. {
  1330. this.ErrorOccured(this, new ExceptionEventArgs(exp));
  1331. }
  1332. if (connectionException != null && connectionException.DisconnectReason != DisconnectReason.ConnectionLost)
  1333. {
  1334. this.SendDisconnect(connectionException.DisconnectReason, exp.ToString());
  1335. }
  1336. }
  1337. #region IDisposable Members
  1338. private bool _disposed = false;
  1339. /// <summary>
  1340. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  1341. /// </summary>
  1342. public void Dispose()
  1343. {
  1344. Dispose(true);
  1345. GC.SuppressFinalize(this);
  1346. }
  1347. /// <summary>
  1348. /// Releases unmanaged and - optionally - managed resources
  1349. /// </summary>
  1350. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1351. protected virtual void Dispose(bool disposing)
  1352. {
  1353. // Check to see if Dispose has already been called.
  1354. if (!this._disposed)
  1355. {
  1356. // If disposing equals true, dispose all managed
  1357. // and unmanaged ResourceMessages.
  1358. if (disposing)
  1359. {
  1360. this._isDisconnecting = true;
  1361. if (this._socket != null)
  1362. {
  1363. // If socket still open try to send disconnect message to the server
  1364. this.SendDisconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
  1365. this._socket.Dispose();
  1366. this._socket = null;
  1367. }
  1368. if (this._messageListener != null)
  1369. {
  1370. // Wait for socket to be closed and for task to complete before disposing a task
  1371. this._messageListener.Wait();
  1372. this._messageListener.Dispose();
  1373. this._messageListener = null;
  1374. }
  1375. if (this._serviceAccepted != null)
  1376. {
  1377. this._serviceAccepted.Dispose();
  1378. this._serviceAccepted = null;
  1379. }
  1380. if (this._exceptionWaitHandle != null)
  1381. {
  1382. this._exceptionWaitHandle.Dispose();
  1383. this._exceptionWaitHandle = null;
  1384. }
  1385. if (this._sessionSemaphore != null)
  1386. {
  1387. this._sessionSemaphore.Dispose();
  1388. this._sessionSemaphore = null;
  1389. }
  1390. if (this._keyExchangeCompletedWaitHandle != null)
  1391. {
  1392. this._keyExchangeCompletedWaitHandle.Dispose();
  1393. this._keyExchangeCompletedWaitHandle = null;
  1394. }
  1395. if (this._serverCipher != null)
  1396. {
  1397. this._serverCipher.Dispose();
  1398. this._serverCipher = null;
  1399. }
  1400. if (this._clientCipher != null)
  1401. {
  1402. this._clientCipher.Dispose();
  1403. this._clientCipher = null;
  1404. }
  1405. if (this._serverMac != null)
  1406. {
  1407. this._serverMac.Dispose();
  1408. this._serverMac = null;
  1409. }
  1410. if (this._clientMac != null)
  1411. {
  1412. this._clientMac.Dispose();
  1413. this._clientMac = null;
  1414. }
  1415. if (this._keyExchange != null)
  1416. {
  1417. this._keyExchange.Dispose();
  1418. this._keyExchange = null;
  1419. }
  1420. }
  1421. // Note disposing has been done.
  1422. this._disposed = true;
  1423. }
  1424. }
  1425. /// <summary>
  1426. /// Releases unmanaged resources and performs other cleanup operations before the
  1427. /// <see cref="Session"/> is reclaimed by garbage collection.
  1428. /// </summary>
  1429. ~Session()
  1430. {
  1431. // Do not re-create Dispose clean-up code here.
  1432. // Calling Dispose(false) is optimal in terms of
  1433. // readability and maintainability.
  1434. Dispose(false);
  1435. }
  1436. #endregion
  1437. private class MessageMetadata
  1438. {
  1439. public string Name { get; set; }
  1440. public byte Number { get; set; }
  1441. public bool Enabled { get; set; }
  1442. public bool Activated { get; set; }
  1443. public Type Type { get; set; }
  1444. }
  1445. }
  1446. }