Session.cs 63 KB

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