Session.cs 61 KB

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