Session.cs 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using Renci.SshNet.Channels;
  11. using Renci.SshNet.Common;
  12. using Renci.SshNet.Compression;
  13. using Renci.SshNet.Messages;
  14. using Renci.SshNet.Messages.Authentication;
  15. using Renci.SshNet.Messages.Connection;
  16. using Renci.SshNet.Messages.Transport;
  17. using Renci.SshNet.Security;
  18. using System.Globalization;
  19. using Renci.SshNet.Security.Cryptography;
  20. namespace Renci.SshNet
  21. {
  22. /// <summary>
  23. /// Provides functionality to connect and interact with SSH server.
  24. /// </summary>
  25. public partial class Session : IDisposable, ISession
  26. {
  27. /// <summary>
  28. /// Specifies maximum packet size defined by the protocol.
  29. /// </summary>
  30. private const int MaximumSshPacketSize = LocalChannelDataPacketSize + 3000;
  31. /// <summary>
  32. /// Holds the initial local window size for the channels.
  33. /// </summary>
  34. /// <value>
  35. /// 2 MB.
  36. /// </value>
  37. private const int InitialLocalWindowSize = LocalChannelDataPacketSize * 32;
  38. /// <summary>
  39. /// Holds the maximum size of channel data packets that we receive.
  40. /// </summary>
  41. /// <value>
  42. /// 64 KB.
  43. /// </value>
  44. private const int LocalChannelDataPacketSize = 1024*64;
  45. private static readonly RNGCryptoServiceProvider Randomizer = new RNGCryptoServiceProvider();
  46. #if SILVERLIGHT
  47. private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$");
  48. #else
  49. private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$", RegexOptions.Compiled);
  50. #endif
  51. /// <summary>
  52. /// Controls how many authentication attempts can take place at the same time.
  53. /// </summary>
  54. /// <remarks>
  55. /// Some server may restrict number to prevent authentication attacks
  56. /// </remarks>
  57. private static readonly SemaphoreLight AuthenticationConnection = new SemaphoreLight(3);
  58. /// <summary>
  59. /// Holds metada about session messages
  60. /// </summary>
  61. private IEnumerable<MessageMetadata> _messagesMetadata;
  62. /// <summary>
  63. /// Holds connection socket.
  64. /// </summary>
  65. private Socket _socket;
  66. /// <summary>
  67. /// Holds locker object for the socket
  68. /// </summary>
  69. private readonly object _socketLock = new object();
  70. /// <summary>
  71. /// Holds reference to task that listens for incoming messages
  72. /// </summary>
  73. private EventWaitHandle _messageListenerCompleted;
  74. /// <summary>
  75. /// Specifies outbound packet number
  76. /// </summary>
  77. private volatile UInt32 _outboundPacketSequence;
  78. /// <summary>
  79. /// Specifies incoming packet number
  80. /// </summary>
  81. private UInt32 _inboundPacketSequence;
  82. /// <summary>
  83. /// WaitHandle to signal that last service request was accepted
  84. /// </summary>
  85. private EventWaitHandle _serviceAccepted = new AutoResetEvent(false);
  86. /// <summary>
  87. /// WaitHandle to signal that exception was thrown by another thread.
  88. /// </summary>
  89. private EventWaitHandle _exceptionWaitHandle = new ManualResetEvent(false);
  90. /// <summary>
  91. /// WaitHandle to signal that key exchange was completed.
  92. /// </summary>
  93. private EventWaitHandle _keyExchangeCompletedWaitHandle = new ManualResetEvent(false);
  94. /// <summary>
  95. /// WaitHandle to signal that bytes have been read from the socket.
  96. /// </summary>
  97. private EventWaitHandle _bytesReadFromSocket = new ManualResetEvent(false);
  98. /// <summary>
  99. /// WaitHandle to signal that key exchange is in progress.
  100. /// </summary>
  101. private bool _keyExchangeInProgress;
  102. /// <summary>
  103. /// Exception that need to be thrown by waiting thread
  104. /// </summary>
  105. private Exception _exception;
  106. /// <summary>
  107. /// Specifies whether connection is authenticated
  108. /// </summary>
  109. private bool _isAuthenticated;
  110. /// <summary>
  111. /// Specifies whether user issued Disconnect command or not
  112. /// </summary>
  113. private bool _isDisconnecting;
  114. private KeyExchange _keyExchange;
  115. private HashAlgorithm _serverMac;
  116. private HashAlgorithm _clientMac;
  117. private Cipher _clientCipher;
  118. private Cipher _serverCipher;
  119. private Compressor _serverDecompression;
  120. private Compressor _clientCompression;
  121. private SemaphoreLight _sessionSemaphore;
  122. /// <summary>
  123. /// Gets the session semaphore that controls session channels.
  124. /// </summary>
  125. /// <value>The session semaphore.</value>
  126. public SemaphoreLight SessionSemaphore
  127. {
  128. get
  129. {
  130. if (this._sessionSemaphore == null)
  131. {
  132. lock (this)
  133. {
  134. if (this._sessionSemaphore == null)
  135. {
  136. this._sessionSemaphore = new SemaphoreLight(this.ConnectionInfo.MaxSessions);
  137. }
  138. }
  139. }
  140. return this._sessionSemaphore;
  141. }
  142. }
  143. private bool _isDisconnectMessageSent;
  144. private uint _nextChannelNumber;
  145. /// <summary>
  146. /// Gets the next channel number.
  147. /// </summary>
  148. /// <value>The next channel number.</value>
  149. internal uint NextChannelNumber
  150. {
  151. get
  152. {
  153. uint result;
  154. lock (this)
  155. {
  156. result = this._nextChannelNumber++;
  157. }
  158. return result;
  159. }
  160. }
  161. /// <summary>
  162. /// Gets a value indicating whether the session is connected.
  163. /// </summary>
  164. /// <value>
  165. /// <c>true</c> if the session is connected; otherwise, <c>false</c>.
  166. /// </value>
  167. /// <remarks>
  168. /// This methods returns true in all but the following cases:
  169. /// <list type="bullet">
  170. /// <item>
  171. /// <description>The SSH_MSG_DISCONNECT message - which is used to disconnect from the server - has been sent.</description>
  172. /// </item>
  173. /// <item>
  174. /// <description>The client has not been authenticated successfully.</description>
  175. /// </item>
  176. /// <item>
  177. /// <description>The listener thread - which is used to receive messages from the server - has stopped.</description>
  178. /// </item>
  179. /// <item>
  180. /// <description>The socket used to communicate with the server is no longer connected.</description>
  181. /// </item>
  182. /// </list>
  183. /// </remarks>
  184. public bool IsConnected
  185. {
  186. get
  187. {
  188. if (_isDisconnectMessageSent || !this._isAuthenticated)
  189. return false;
  190. if (_messageListenerCompleted == null || _messageListenerCompleted.WaitOne(0))
  191. return false;
  192. var isSocketConnected = false;
  193. IsSocketConnected(ref isSocketConnected);
  194. return isSocketConnected;
  195. }
  196. }
  197. /// <summary>
  198. /// Gets the session id.
  199. /// </summary>
  200. /// <value>
  201. /// The session id, or <c>null</c> if the client has not been authenticated.
  202. /// </value>
  203. public byte[] SessionId { get; private set; }
  204. private Message _clientInitMessage;
  205. /// <summary>
  206. /// Gets the client init message.
  207. /// </summary>
  208. /// <value>The client init message.</value>
  209. public Message ClientInitMessage
  210. {
  211. get
  212. {
  213. if (this._clientInitMessage == null)
  214. {
  215. this._clientInitMessage = new KeyExchangeInitMessage
  216. {
  217. KeyExchangeAlgorithms = this.ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(),
  218. ServerHostKeyAlgorithms = this.ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(),
  219. EncryptionAlgorithmsClientToServer = this.ConnectionInfo.Encryptions.Keys.ToArray(),
  220. EncryptionAlgorithmsServerToClient = this.ConnectionInfo.Encryptions.Keys.ToArray(),
  221. MacAlgorithmsClientToServer = this.ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
  222. MacAlgorithmsServerToClient = this.ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
  223. CompressionAlgorithmsClientToServer = this.ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
  224. CompressionAlgorithmsServerToClient = this.ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
  225. LanguagesClientToServer = new[] {string.Empty},
  226. LanguagesServerToClient = new[] {string.Empty},
  227. FirstKexPacketFollows = false,
  228. Reserved = 0
  229. };
  230. }
  231. return this._clientInitMessage;
  232. }
  233. }
  234. /// <summary>
  235. /// Gets or sets the server version string.
  236. /// </summary>
  237. /// <value>The server version.</value>
  238. public string ServerVersion { get; private set; }
  239. /// <summary>
  240. /// Gets or sets the client version string.
  241. /// </summary>
  242. /// <value>The client version.</value>
  243. public string ClientVersion { get; private set; }
  244. /// <summary>
  245. /// Gets or sets the connection info.
  246. /// </summary>
  247. /// <value>The connection info.</value>
  248. public ConnectionInfo ConnectionInfo { get; private set; }
  249. /// <summary>
  250. /// Occurs when an error occurred.
  251. /// </summary>
  252. public event EventHandler<ExceptionEventArgs> ErrorOccured;
  253. /// <summary>
  254. /// Occurs when session has been disconnected from the server.
  255. /// </summary>
  256. public event EventHandler<EventArgs> Disconnected;
  257. /// <summary>
  258. /// Occurs when host key received.
  259. /// </summary>
  260. public event EventHandler<HostKeyEventArgs> HostKeyReceived;
  261. /// <summary>
  262. /// Occurs when <see cref="BannerMessage"/> message is received from the server.
  263. /// </summary>
  264. public event EventHandler<MessageEventArgs<BannerMessage>> UserAuthenticationBannerReceived;
  265. #region Message events
  266. /// <summary>
  267. /// Occurs when <see cref="DisconnectMessage"/> message received
  268. /// </summary>
  269. internal event EventHandler<MessageEventArgs<DisconnectMessage>> DisconnectReceived;
  270. /// <summary>
  271. /// Occurs when <see cref="IgnoreMessage"/> message received
  272. /// </summary>
  273. internal event EventHandler<MessageEventArgs<IgnoreMessage>> IgnoreReceived;
  274. /// <summary>
  275. /// Occurs when <see cref="UnimplementedMessage"/> message received
  276. /// </summary>
  277. internal event EventHandler<MessageEventArgs<UnimplementedMessage>> UnimplementedReceived;
  278. /// <summary>
  279. /// Occurs when <see cref="DebugMessage"/> message received
  280. /// </summary>
  281. internal event EventHandler<MessageEventArgs<DebugMessage>> DebugReceived;
  282. /// <summary>
  283. /// Occurs when <see cref="ServiceRequestMessage"/> message received
  284. /// </summary>
  285. internal event EventHandler<MessageEventArgs<ServiceRequestMessage>> ServiceRequestReceived;
  286. /// <summary>
  287. /// Occurs when <see cref="ServiceAcceptMessage"/> message received
  288. /// </summary>
  289. internal event EventHandler<MessageEventArgs<ServiceAcceptMessage>> ServiceAcceptReceived;
  290. /// <summary>
  291. /// Occurs when <see cref="KeyExchangeInitMessage"/> message received
  292. /// </summary>
  293. internal event EventHandler<MessageEventArgs<KeyExchangeInitMessage>> KeyExchangeInitReceived;
  294. /// <summary>
  295. /// Occurs when <see cref="NewKeysMessage"/> message received
  296. /// </summary>
  297. internal event EventHandler<MessageEventArgs<NewKeysMessage>> NewKeysReceived;
  298. /// <summary>
  299. /// Occurs when <see cref="RequestMessage"/> message received
  300. /// </summary>
  301. internal event EventHandler<MessageEventArgs<RequestMessage>> UserAuthenticationRequestReceived;
  302. /// <summary>
  303. /// Occurs when <see cref="FailureMessage"/> message received
  304. /// </summary>
  305. internal event EventHandler<MessageEventArgs<FailureMessage>> UserAuthenticationFailureReceived;
  306. /// <summary>
  307. /// Occurs when <see cref="SuccessMessage"/> message received
  308. /// </summary>
  309. internal event EventHandler<MessageEventArgs<SuccessMessage>> UserAuthenticationSuccessReceived;
  310. /// <summary>
  311. /// Occurs when <see cref="GlobalRequestMessage"/> message received
  312. /// </summary>
  313. internal event EventHandler<MessageEventArgs<GlobalRequestMessage>> GlobalRequestReceived;
  314. /// <summary>
  315. /// Occurs when <see cref="RequestSuccessMessage"/> message received
  316. /// </summary>
  317. internal event EventHandler<MessageEventArgs<RequestSuccessMessage>> RequestSuccessReceived;
  318. /// <summary>
  319. /// Occurs when <see cref="RequestFailureMessage"/> message received
  320. /// </summary>
  321. internal event EventHandler<MessageEventArgs<RequestFailureMessage>> RequestFailureReceived;
  322. /// <summary>
  323. /// Occurs when <see cref="ChannelOpenMessage"/> message received
  324. /// </summary>
  325. internal event EventHandler<MessageEventArgs<ChannelOpenMessage>> ChannelOpenReceived;
  326. /// <summary>
  327. /// Occurs when <see cref="ChannelOpenConfirmationMessage"/> message received
  328. /// </summary>
  329. internal event EventHandler<MessageEventArgs<ChannelOpenConfirmationMessage>> ChannelOpenConfirmationReceived;
  330. /// <summary>
  331. /// Occurs when <see cref="ChannelOpenFailureMessage"/> message received
  332. /// </summary>
  333. internal event EventHandler<MessageEventArgs<ChannelOpenFailureMessage>> ChannelOpenFailureReceived;
  334. /// <summary>
  335. /// Occurs when <see cref="ChannelWindowAdjustMessage"/> message received
  336. /// </summary>
  337. internal event EventHandler<MessageEventArgs<ChannelWindowAdjustMessage>> ChannelWindowAdjustReceived;
  338. /// <summary>
  339. /// Occurs when <see cref="ChannelDataMessage"/> message received
  340. /// </summary>
  341. internal event EventHandler<MessageEventArgs<ChannelDataMessage>> ChannelDataReceived;
  342. /// <summary>
  343. /// Occurs when <see cref="ChannelExtendedDataMessage"/> message received
  344. /// </summary>
  345. internal event EventHandler<MessageEventArgs<ChannelExtendedDataMessage>> ChannelExtendedDataReceived;
  346. /// <summary>
  347. /// Occurs when <see cref="ChannelEofMessage"/> message received
  348. /// </summary>
  349. internal event EventHandler<MessageEventArgs<ChannelEofMessage>> ChannelEofReceived;
  350. /// <summary>
  351. /// Occurs when <see cref="ChannelCloseMessage"/> message received
  352. /// </summary>
  353. internal event EventHandler<MessageEventArgs<ChannelCloseMessage>> ChannelCloseReceived;
  354. /// <summary>
  355. /// Occurs when <see cref="ChannelRequestMessage"/> message received
  356. /// </summary>
  357. internal event EventHandler<MessageEventArgs<ChannelRequestMessage>> ChannelRequestReceived;
  358. /// <summary>
  359. /// Occurs when <see cref="ChannelSuccessMessage"/> message received
  360. /// </summary>
  361. internal event EventHandler<MessageEventArgs<ChannelSuccessMessage>> ChannelSuccessReceived;
  362. /// <summary>
  363. /// Occurs when <see cref="ChannelFailureMessage"/> message received
  364. /// </summary>
  365. internal event EventHandler<MessageEventArgs<ChannelFailureMessage>> ChannelFailureReceived;
  366. /// <summary>
  367. /// Occurs when message received and is not handled by any of the event handlers
  368. /// </summary>
  369. internal event EventHandler<MessageEventArgs<Message>> MessageReceived;
  370. #endregion
  371. /// <summary>
  372. /// Initializes a new instance of the <see cref="Session"/> class.
  373. /// </summary>
  374. /// <param name="connectionInfo">The connection info.</param>
  375. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
  376. internal Session(ConnectionInfo connectionInfo)
  377. {
  378. if (connectionInfo == null)
  379. throw new ArgumentNullException("connectionInfo");
  380. this.ConnectionInfo = connectionInfo;
  381. //this.ClientVersion = string.Format(CultureInfo.CurrentCulture, "SSH-2.0-Renci.SshNet.SshClient.{0}", this.GetType().Assembly.GetName().Version);
  382. this.ClientVersion = string.Format(CultureInfo.CurrentCulture, "SSH-2.0-Renci.SshNet.SshClient.0.0.1");
  383. }
  384. /// <summary>
  385. /// Connects to the server.
  386. /// </summary>
  387. public void Connect()
  388. {
  389. if (this.IsConnected)
  390. return;
  391. try
  392. {
  393. AuthenticationConnection.Wait();
  394. if (this.IsConnected)
  395. return;
  396. lock (this)
  397. {
  398. // If connected don't connect again
  399. if (this.IsConnected)
  400. return;
  401. // reset connection specific information
  402. Reset();
  403. // Build list of available messages while connecting
  404. this._messagesMetadata = GetMessagesMetadata();
  405. switch (this.ConnectionInfo.ProxyType)
  406. {
  407. case ProxyTypes.None:
  408. this.SocketConnect(this.ConnectionInfo.Host, this.ConnectionInfo.Port);
  409. break;
  410. case ProxyTypes.Socks4:
  411. this.SocketConnect(this.ConnectionInfo.ProxyHost, this.ConnectionInfo.ProxyPort);
  412. this.ConnectSocks4();
  413. break;
  414. case ProxyTypes.Socks5:
  415. this.SocketConnect(this.ConnectionInfo.ProxyHost, this.ConnectionInfo.ProxyPort);
  416. this.ConnectSocks5();
  417. break;
  418. case ProxyTypes.Http:
  419. this.SocketConnect(this.ConnectionInfo.ProxyHost, this.ConnectionInfo.ProxyPort);
  420. this.ConnectHttp();
  421. break;
  422. }
  423. Match versionMatch;
  424. // Get server version from the server,
  425. // ignore text lines which are sent before if any
  426. while (true)
  427. {
  428. string serverVersion = string.Empty;
  429. this.SocketReadLine(ref serverVersion, ConnectionInfo.Timeout);
  430. if (serverVersion == null)
  431. throw new SshConnectionException("Server response does not contain SSH protocol identification.");
  432. versionMatch = ServerVersionRe.Match(serverVersion);
  433. if (versionMatch.Success)
  434. {
  435. this.ServerVersion = serverVersion;
  436. break;
  437. }
  438. }
  439. // Set connection versions
  440. this.ConnectionInfo.ServerVersion = this.ServerVersion;
  441. this.ConnectionInfo.ClientVersion = this.ClientVersion;
  442. // Get server SSH version
  443. var version = versionMatch.Result("${protoversion}");
  444. var softwareName = versionMatch.Result("${softwareversion}");
  445. this.Log(string.Format("Server version '{0}' on '{1}'.", version, softwareName));
  446. if (!(version.Equals("2.0") || version.Equals("1.99")))
  447. {
  448. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", version), DisconnectReason.ProtocolVersionNotSupported);
  449. }
  450. this.SocketWrite(Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}\x0D\x0A", this.ClientVersion)));
  451. // Register Transport response messages
  452. this.RegisterMessage("SSH_MSG_DISCONNECT");
  453. this.RegisterMessage("SSH_MSG_IGNORE");
  454. this.RegisterMessage("SSH_MSG_UNIMPLEMENTED");
  455. this.RegisterMessage("SSH_MSG_DEBUG");
  456. this.RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
  457. this.RegisterMessage("SSH_MSG_KEXINIT");
  458. this.RegisterMessage("SSH_MSG_NEWKEYS");
  459. // Some server implementations might sent this message first, prior establishing encryption algorithm
  460. this.RegisterMessage("SSH_MSG_USERAUTH_BANNER");
  461. // Start incoming request listener
  462. this._messageListenerCompleted = new ManualResetEvent(false);
  463. this.ExecuteThread(() =>
  464. {
  465. try
  466. {
  467. this.MessageListener();
  468. }
  469. finally
  470. {
  471. this._messageListenerCompleted.Set();
  472. }
  473. });
  474. // Wait for key exchange to be completed
  475. this.WaitOnHandle(this._keyExchangeCompletedWaitHandle);
  476. // If sessionId is not set then its not connected
  477. if (this.SessionId == null)
  478. {
  479. this.Disconnect();
  480. return;
  481. }
  482. // Request user authorization service
  483. this.SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
  484. // Wait for service to be accepted
  485. this.WaitOnHandle(this._serviceAccepted);
  486. if (string.IsNullOrEmpty(this.ConnectionInfo.Username))
  487. {
  488. throw new SshException("Username is not specified.");
  489. }
  490. this.ConnectionInfo.Authenticate(this);
  491. this._isAuthenticated = true;
  492. // Register Connection messages
  493. this.RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
  494. this.RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
  495. this.RegisterMessage("SSH_MSG_REQUEST_FAILURE");
  496. this.RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
  497. this.RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
  498. this.RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
  499. this.RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
  500. this.RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
  501. this.RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
  502. this.RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
  503. this.RegisterMessage("SSH_MSG_CHANNEL_DATA");
  504. this.RegisterMessage("SSH_MSG_CHANNEL_EOF");
  505. this.RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
  506. Monitor.Pulse(this);
  507. }
  508. }
  509. finally
  510. {
  511. AuthenticationConnection.Release();
  512. }
  513. }
  514. /// <summary>
  515. /// Disconnects from the server.
  516. /// </summary>
  517. /// <remarks>
  518. /// This sends a <b>SSH_MSG_DISCONNECT</b> message to the server, waits for the
  519. /// server to close the socket on its end and subsequently closes the client socket.
  520. /// </remarks>
  521. public void Disconnect()
  522. {
  523. Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
  524. }
  525. private void Disconnect(DisconnectReason reason, string message)
  526. {
  527. this._isDisconnecting = true;
  528. // send disconnect message to the server if the connection is still open
  529. // and the disconnect message has not yet been sent
  530. //
  531. // note that this should also cause the listener thread to be stopped as
  532. // the server should respond by closing the socket
  533. SendDisconnect(reason, message);
  534. // disconnect socket, and dispose it
  535. SocketDisconnectAndDispose();
  536. if (_messageListenerCompleted != null)
  537. {
  538. // at this point, we are sure that the listener thread will stop
  539. // as we've disconnected the socket
  540. _messageListenerCompleted.WaitOne();
  541. _messageListenerCompleted.Dispose();
  542. _messageListenerCompleted = null;
  543. }
  544. }
  545. /// <summary>
  546. /// Create a new SSH session channel.
  547. /// </summary>
  548. /// <returns>
  549. /// A new SSH session channel.
  550. /// </returns>
  551. IChannelSession ISession.CreateChannelSession()
  552. {
  553. return CreateClientChannel<ChannelSession>();
  554. }
  555. /// <summary>
  556. /// Create a new client channel.
  557. /// </summary>
  558. /// <typeparam name="T">The type of the channel.</typeparam>
  559. /// <returns>
  560. /// A new client channel.
  561. /// </returns>
  562. internal T CreateClientChannel<T>() where T : ClientChannel, new()
  563. {
  564. var channel = new T();
  565. lock (this)
  566. {
  567. channel.Initialize(this, InitialLocalWindowSize, LocalChannelDataPacketSize);
  568. }
  569. return channel;
  570. }
  571. internal T CreateServerChannel<T>(uint remoteChannelNumber, uint remoteWindowSize, uint remoteChannelDataPacketSize) where T : ServerChannel, new()
  572. {
  573. var channel = new T();
  574. lock (this)
  575. {
  576. channel.Initialize(this, InitialLocalWindowSize, LocalChannelDataPacketSize, remoteChannelNumber, remoteWindowSize,
  577. remoteChannelDataPacketSize);
  578. }
  579. return channel;
  580. }
  581. /// <summary>
  582. /// Sends "keep alive" message to keep connection alive.
  583. /// </summary>
  584. internal void SendKeepAlive()
  585. {
  586. this.SendMessage(new IgnoreMessage());
  587. }
  588. /// <summary>
  589. /// Waits for the specified handle or the exception handle for the receive thread
  590. /// to signal within the connection timeout.
  591. /// </summary>
  592. /// <param name="waitHandle">The wait handle.</param>
  593. /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
  594. /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
  595. /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
  596. /// <remarks>
  597. /// When neither handles are signaled in time and the session is not closing, then the
  598. /// session is disconnected.
  599. /// </remarks>
  600. internal void WaitOnHandle(WaitHandle waitHandle)
  601. {
  602. WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
  603. }
  604. /// <summary>
  605. /// Waits for the specified handle or the exception handle for the receive thread
  606. /// to signal within the specified timeout.
  607. /// </summary>
  608. /// <param name="waitHandle">The wait handle.</param>
  609. /// <param name="timeout">The time to wait for any of the handles to become signaled.</param>
  610. /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
  611. /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
  612. /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
  613. /// <remarks>
  614. /// When neither handles are signaled in time and the session is not closing, then the
  615. /// session is disconnected.
  616. /// </remarks>
  617. internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
  618. {
  619. if (waitHandle == null)
  620. throw new ArgumentNullException("waitHandle");
  621. var waitHandles = new[]
  622. {
  623. this._exceptionWaitHandle,
  624. this._messageListenerCompleted,
  625. waitHandle
  626. };
  627. switch (WaitHandle.WaitAny(waitHandles, timeout))
  628. {
  629. case 0:
  630. throw this._exception;
  631. case 1:
  632. // when the session is NOT disconnecting, the listener should actually
  633. // never complete without setting the exception wait handle and should
  634. // end up in case 0...
  635. //
  636. // when the session is disconnecting, the completion of the listener
  637. // should not be considered an error (quite the oppposite actually)
  638. if (!_isDisconnecting)
  639. {
  640. throw new SshConnectionException("Client not connected.");
  641. }
  642. break;
  643. case WaitHandle.WaitTimeout:
  644. // when the session is NOT disconnecting, then we want to disconnect
  645. // the session altogether in case of a timeout, and throw a
  646. // SshOperationTimeoutException
  647. //
  648. // when the session is disconnecting, a timeout is likely when no
  649. // network connectivity is available; depending on the configured
  650. // timeout either the WaitAny times out first or a SocketException
  651. // detailing a timeout thrown hereby completing the listener thread
  652. // (which makes us end up in case 1). Either way, we do not want to
  653. // disconnect while we're already disconnecting and we do not want
  654. // to report an exception to the client when we're disconnecting
  655. // anyway
  656. if (!_isDisconnecting)
  657. {
  658. this.Disconnect(DisconnectReason.ByApplication, "Operation timeout");
  659. throw new SshOperationTimeoutException("Session operation has timed out");
  660. }
  661. break;
  662. }
  663. }
  664. /// <summary>
  665. /// Sends a message to the server.
  666. /// </summary>
  667. /// <param name="message">The message to send.</param>
  668. /// <exception cref="SshConnectionException">The client is not connected.</exception>
  669. /// <exception cref="SshOperationTimeoutException">The operation timed out.</exception>
  670. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  671. void ISession.SendMessage(Message message)
  672. {
  673. SendMessage(message);
  674. }
  675. /// <summary>
  676. /// Sends a message to the server.
  677. /// </summary>
  678. /// <param name="message">The message to send.</param>
  679. /// <exception cref="SshConnectionException">The client is not connected.</exception>
  680. /// <exception cref="SshOperationTimeoutException">The operation timed out.</exception>
  681. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  682. internal void SendMessage(Message message)
  683. {
  684. if (this._socket == null || !this._socket.CanWrite())
  685. throw new SshConnectionException("Client not connected.");
  686. if (this._keyExchangeInProgress && !(message is IKeyExchangedAllowed))
  687. {
  688. // Wait for key exchange to be completed
  689. this.WaitOnHandle(this._keyExchangeCompletedWaitHandle);
  690. }
  691. this.Log(string.Format("SendMessage to server '{0}': '{1}'.", message.GetType().Name, message));
  692. // Messages can be sent by different thread so we need to synchronize it
  693. var paddingMultiplier = this._clientCipher == null ? (byte)8 : Math.Max((byte)8, this._serverCipher.MinimumSize); // Should be recalculate base on cipher min length if cipher specified
  694. var messageData = message.GetBytes();
  695. if (this._clientCompression != null)
  696. {
  697. messageData = this._clientCompression.Compress(messageData);
  698. }
  699. var packetLength = messageData.Length + 4 + 1; // add length bytes and padding byte
  700. var paddingLength = (byte)((-packetLength) & (paddingMultiplier - 1));
  701. if (paddingLength < paddingMultiplier)
  702. {
  703. paddingLength += paddingMultiplier;
  704. }
  705. // Build Packet data
  706. var packetData = new byte[4 + 1 + messageData.Length + paddingLength];
  707. // Add packet length
  708. ((uint)packetData.Length - 4).GetBytes().CopyTo(packetData, 0);
  709. // Add packet padding length
  710. packetData[4] = paddingLength;
  711. // Add packet payload
  712. messageData.CopyTo(packetData, 4 + 1);
  713. // Add random padding
  714. var paddingBytes = new byte[paddingLength];
  715. Randomizer.GetBytes(paddingBytes);
  716. paddingBytes.CopyTo(packetData, 4 + 1 + messageData.Length);
  717. // Lock handling of _outboundPacketSequence since it must be sent sequently to server
  718. lock (this._socketLock)
  719. {
  720. if (this._socket == null || !this._socket.Connected)
  721. throw new SshConnectionException("Client not connected.");
  722. // Calculate packet hash
  723. var hashData = new byte[4 + packetData.Length];
  724. this._outboundPacketSequence.GetBytes().CopyTo(hashData, 0);
  725. packetData.CopyTo(hashData, 4);
  726. // Encrypt packet data
  727. if (this._clientCipher != null)
  728. {
  729. packetData = this._clientCipher.Encrypt(packetData);
  730. }
  731. if (packetData.Length > MaximumSshPacketSize)
  732. {
  733. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Packet is too big. Maximum packet size is {0} bytes.", MaximumSshPacketSize));
  734. }
  735. if (this._clientMac == null)
  736. {
  737. this.SocketWrite(packetData);
  738. }
  739. else
  740. {
  741. var hash = this._clientMac.ComputeHash(hashData.ToArray());
  742. var data = new byte[packetData.Length + this._clientMac.HashSize / 8];
  743. packetData.CopyTo(data, 0);
  744. hash.CopyTo(data, packetData.Length);
  745. this.SocketWrite(data);
  746. }
  747. this._outboundPacketSequence++;
  748. Monitor.Pulse(this._socketLock);
  749. }
  750. }
  751. private static IEnumerable<MessageMetadata> GetMessagesMetadata()
  752. {
  753. return new []
  754. {
  755. new MessageMetadata { Name = "SSH_MSG_NEWKEYS", Number = 21, Type = typeof(NewKeysMessage) },
  756. new MessageMetadata { Name = "SSH_MSG_REQUEST_FAILURE", Number = 82, Type = typeof(RequestFailureMessage) },
  757. new MessageMetadata { Name = "SSH_MSG_KEXINIT", Number = 20, Type = typeof(KeyExchangeInitMessage) },
  758. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN_FAILURE", Number = 92, Type = typeof(ChannelOpenFailureMessage) },
  759. new MessageMetadata { Name = "SSH_MSG_CHANNEL_FAILURE", Number = 100, Type = typeof(ChannelFailureMessage) },
  760. new MessageMetadata { Name = "SSH_MSG_CHANNEL_EXTENDED_DATA", Number = 95, Type = typeof(ChannelExtendedDataMessage) },
  761. new MessageMetadata { Name = "SSH_MSG_CHANNEL_DATA", Number = 94, Type = typeof(ChannelDataMessage) },
  762. new MessageMetadata { Name = "SSH_MSG_USERAUTH_REQUEST", Number = 50, Type = typeof(RequestMessage) },
  763. new MessageMetadata { Name = "SSH_MSG_CHANNEL_REQUEST", Number = 98, Type = typeof(ChannelRequestMessage) },
  764. new MessageMetadata { Name = "SSH_MSG_USERAUTH_BANNER", Number = 53, Type = typeof(BannerMessage) },
  765. new MessageMetadata { Name = "SSH_MSG_USERAUTH_INFO_RESPONSE", Number = 61, Type = typeof(InformationResponseMessage) },
  766. new MessageMetadata { Name = "SSH_MSG_USERAUTH_FAILURE", Number = 51, Type = typeof(FailureMessage) },
  767. new MessageMetadata { Name = "SSH_MSG_DEBUG", Number = 4, Type = typeof(DebugMessage), },
  768. new MessageMetadata { Name = "SSH_MSG_KEXDH_INIT", Number = 30, Type = typeof(KeyExchangeDhInitMessage) },
  769. new MessageMetadata { Name = "SSH_MSG_GLOBAL_REQUEST", Number = 80, Type = typeof(GlobalRequestMessage) },
  770. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN", Number = 90, Type = typeof(ChannelOpenMessage) },
  771. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN_CONFIRMATION", Number = 91, Type = typeof(ChannelOpenConfirmationMessage) },
  772. new MessageMetadata { Name = "SSH_MSG_USERAUTH_INFO_REQUEST", Number = 60, Type = typeof(InformationRequestMessage) },
  773. new MessageMetadata { Name = "SSH_MSG_UNIMPLEMENTED", Number = 3, Type = typeof(UnimplementedMessage) },
  774. new MessageMetadata { Name = "SSH_MSG_REQUEST_SUCCESS", Number = 81, Type = typeof(RequestSuccessMessage) },
  775. new MessageMetadata { Name = "SSH_MSG_CHANNEL_SUCCESS", Number = 99, Type = typeof(ChannelSuccessMessage) },
  776. new MessageMetadata { Name = "SSH_MSG_USERAUTH_PASSWD_CHANGEREQ", Number = 60, Type = typeof(PasswordChangeRequiredMessage) },
  777. new MessageMetadata { Name = "SSH_MSG_DISCONNECT", Number = 1, Type = typeof(DisconnectMessage) },
  778. new MessageMetadata { Name = "SSH_MSG_SERVICE_REQUEST", Number = 5, Type = typeof(ServiceRequestMessage) },
  779. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_REQUEST", Number = 34, Type = typeof(KeyExchangeDhGroupExchangeRequest) },
  780. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_GROUP", Number = 31, Type = typeof(KeyExchangeDhGroupExchangeGroup) },
  781. new MessageMetadata { Name = "SSH_MSG_USERAUTH_SUCCESS", Number = 52, Type = typeof(SuccessMessage) },
  782. new MessageMetadata { Name = "SSH_MSG_USERAUTH_PK_OK", Number = 60, Type = typeof(PublicKeyMessage) },
  783. new MessageMetadata { Name = "SSH_MSG_IGNORE", Number = 2, Type = typeof(IgnoreMessage) },
  784. new MessageMetadata { Name = "SSH_MSG_CHANNEL_WINDOW_ADJUST", Number = 93, Type = typeof(ChannelWindowAdjustMessage) },
  785. new MessageMetadata { Name = "SSH_MSG_CHANNEL_EOF", Number = 96, Type = typeof(ChannelEofMessage) },
  786. new MessageMetadata { Name = "SSH_MSG_CHANNEL_CLOSE", Number = 97, Type = typeof(ChannelCloseMessage) },
  787. new MessageMetadata { Name = "SSH_MSG_SERVICE_ACCEPT", Number = 6, Type = typeof(ServiceAcceptMessage) },
  788. new MessageMetadata { Name = "SSH_MSG_KEXDH_REPLY", Number = 31, Type = typeof(KeyExchangeDhReplyMessage) },
  789. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_INIT", Number = 32, Type = typeof(KeyExchangeDhGroupExchangeInit) },
  790. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_REPLY", Number = 33, Type = typeof(KeyExchangeDhGroupExchangeReply) }
  791. };
  792. }
  793. /// <summary>
  794. /// Receives the message from the server.
  795. /// </summary>
  796. /// <returns>Incoming SSH message.</returns>
  797. /// <exception cref="SshConnectionException"></exception>
  798. private Message ReceiveMessage()
  799. {
  800. // No lock needed since all messages read by only one thread
  801. var blockSize = this._serverCipher == null ? (byte)8 : Math.Max((byte)8, this._serverCipher.MinimumSize);
  802. // Read packet length first
  803. var firstBlock = this.Read(blockSize);
  804. if (this._serverCipher != null)
  805. {
  806. firstBlock = this._serverCipher.Decrypt(firstBlock);
  807. }
  808. var packetLength = (uint)(firstBlock[0] << 24 | firstBlock[1] << 16 | firstBlock[2] << 8 | firstBlock[3]);
  809. // Test packet minimum and maximum boundaries
  810. if (packetLength < Math.Max((byte)16, blockSize) - 4 || packetLength > MaximumSshPacketSize - 4)
  811. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length {0}", packetLength), DisconnectReason.ProtocolError);
  812. // Read rest of the packet data
  813. var bytesToRead = (int)(packetLength - (blockSize - 4));
  814. var data = new byte[bytesToRead + blockSize];
  815. firstBlock.CopyTo(data, 0);
  816. byte[] serverHash = null;
  817. if (this._serverMac != null)
  818. {
  819. serverHash = new byte[this._serverMac.HashSize / 8];
  820. bytesToRead += serverHash.Length;
  821. }
  822. if (bytesToRead > 0)
  823. {
  824. var nextBlocks = this.Read(bytesToRead);
  825. if (serverHash != null)
  826. {
  827. Buffer.BlockCopy(nextBlocks, nextBlocks.Length - serverHash.Length, serverHash, 0, serverHash.Length);
  828. nextBlocks = nextBlocks.Take(nextBlocks.Length - serverHash.Length).ToArray();
  829. }
  830. if (nextBlocks.Length > 0)
  831. {
  832. if (this._serverCipher != null)
  833. {
  834. nextBlocks = this._serverCipher.Decrypt(nextBlocks);
  835. }
  836. nextBlocks.CopyTo(data, blockSize);
  837. }
  838. }
  839. var paddingLength = data[4];
  840. var messagePayload = new byte[packetLength - paddingLength - 1];
  841. Buffer.BlockCopy(data, 5, messagePayload, 0, messagePayload.Length);
  842. if (this._serverDecompression != null)
  843. {
  844. messagePayload = this._serverDecompression.Decompress(messagePayload);
  845. }
  846. // Validate message against MAC
  847. if (this._serverMac != null)
  848. {
  849. var clientHashData = new byte[4 + data.Length];
  850. var lengthBytes = this._inboundPacketSequence.GetBytes();
  851. lengthBytes.CopyTo(clientHashData, 0);
  852. data.CopyTo(clientHashData, 4);
  853. // Calculate packet hash
  854. var clientHash = this._serverMac.ComputeHash(clientHashData);
  855. if (!serverHash.SequenceEqual(clientHash))
  856. {
  857. throw new SshConnectionException("MAC error", DisconnectReason.MacError);
  858. }
  859. }
  860. this._inboundPacketSequence++;
  861. return this.LoadMessage(messagePayload);
  862. }
  863. private void SendDisconnect(DisconnectReason reasonCode, string message)
  864. {
  865. // only send a disconnect message if it wasn't already sent, and we're
  866. // still connected
  867. if (this._isDisconnectMessageSent || !IsConnected)
  868. return;
  869. var disconnectMessage = new DisconnectMessage(reasonCode, message);
  870. SendMessage(disconnectMessage);
  871. this._isDisconnectMessageSent = true;
  872. }
  873. partial void HandleMessageCore(Message message);
  874. /// <summary>
  875. /// Handles the message.
  876. /// </summary>
  877. /// <typeparam name="T"></typeparam>
  878. /// <param name="message">The message.</param>
  879. private void HandleMessage<T>(T message) where T : Message
  880. {
  881. this.OnMessageReceived(message);
  882. }
  883. #region Handle transport messages
  884. private void HandleMessage(DisconnectMessage message)
  885. {
  886. this.OnDisconnectReceived(message);
  887. // disconnect from the socket, and dispose it
  888. SocketDisconnectAndDispose();
  889. }
  890. private void HandleMessage(IgnoreMessage message)
  891. {
  892. this.OnIgnoreReceived(message);
  893. }
  894. private void HandleMessage(UnimplementedMessage message)
  895. {
  896. this.OnUnimplementedReceived(message);
  897. }
  898. private void HandleMessage(DebugMessage message)
  899. {
  900. this.OnDebugReceived(message);
  901. }
  902. private void HandleMessage(ServiceRequestMessage message)
  903. {
  904. this.OnServiceRequestReceived(message);
  905. }
  906. private void HandleMessage(ServiceAcceptMessage message)
  907. {
  908. // TODO: Refactor to avoid this method here
  909. this.OnServiceAcceptReceived(message);
  910. this._serviceAccepted.Set();
  911. }
  912. private void HandleMessage(KeyExchangeInitMessage message)
  913. {
  914. this.OnKeyExchangeInitReceived(message);
  915. }
  916. private void HandleMessage(NewKeysMessage message)
  917. {
  918. this.OnNewKeysReceived(message);
  919. }
  920. #endregion
  921. #region Handle User Authentication messages
  922. private void HandleMessage(RequestMessage message)
  923. {
  924. this.OnUserAuthenticationRequestReceived(message);
  925. }
  926. private void HandleMessage(FailureMessage message)
  927. {
  928. this.OnUserAuthenticationFailureReceived(message);
  929. }
  930. private void HandleMessage(SuccessMessage message)
  931. {
  932. this.OnUserAuthenticationSuccessReceived(message);
  933. }
  934. private void HandleMessage(BannerMessage message)
  935. {
  936. this.OnUserAuthenticationBannerReceived(message);
  937. }
  938. #endregion
  939. #region Handle connection messages
  940. private void HandleMessage(GlobalRequestMessage message)
  941. {
  942. this.OnGlobalRequestReceived(message);
  943. }
  944. private void HandleMessage(RequestSuccessMessage message)
  945. {
  946. this.OnRequestSuccessReceived(message);
  947. }
  948. private void HandleMessage(RequestFailureMessage message)
  949. {
  950. this.OnRequestFailureReceived(message);
  951. }
  952. private void HandleMessage(ChannelOpenMessage message)
  953. {
  954. this.OnChannelOpenReceived(message);
  955. }
  956. private void HandleMessage(ChannelOpenConfirmationMessage message)
  957. {
  958. this.OnChannelOpenConfirmationReceived(message);
  959. }
  960. private void HandleMessage(ChannelOpenFailureMessage message)
  961. {
  962. this.OnChannelOpenFailureReceived(message);
  963. }
  964. private void HandleMessage(ChannelWindowAdjustMessage message)
  965. {
  966. this.OnChannelWindowAdjustReceived(message);
  967. }
  968. private void HandleMessage(ChannelDataMessage message)
  969. {
  970. this.OnChannelDataReceived(message);
  971. }
  972. private void HandleMessage(ChannelExtendedDataMessage message)
  973. {
  974. this.OnChannelExtendedDataReceived(message);
  975. }
  976. private void HandleMessage(ChannelEofMessage message)
  977. {
  978. this.OnChannelEofReceived(message);
  979. }
  980. private void HandleMessage(ChannelCloseMessage message)
  981. {
  982. this.OnChannelCloseReceived(message);
  983. }
  984. private void HandleMessage(ChannelRequestMessage message)
  985. {
  986. this.OnChannelRequestReceived(message);
  987. }
  988. private void HandleMessage(ChannelSuccessMessage message)
  989. {
  990. this.OnChannelSuccessReceived(message);
  991. }
  992. private void HandleMessage(ChannelFailureMessage message)
  993. {
  994. this.OnChannelFailureReceived(message);
  995. }
  996. #endregion
  997. #region Handle received message events
  998. /// <summary>
  999. /// Called when <see cref="DisconnectMessage"/> received.
  1000. /// </summary>
  1001. /// <param name="message"><see cref="DisconnectMessage"/> message.</param>
  1002. protected virtual void OnDisconnectReceived(DisconnectMessage message)
  1003. {
  1004. this.Log(string.Format("Disconnect received: {0} {1}", message.ReasonCode, message.Description));
  1005. var disconnectReceived = DisconnectReceived;
  1006. if (disconnectReceived != null)
  1007. disconnectReceived(this, new MessageEventArgs<DisconnectMessage>(message));
  1008. var disconnected = Disconnected;
  1009. if (disconnected != null)
  1010. disconnected(this, new EventArgs());
  1011. }
  1012. /// <summary>
  1013. /// Called when <see cref="IgnoreMessage"/> received.
  1014. /// </summary>
  1015. /// <param name="message"><see cref="IgnoreMessage"/> message.</param>
  1016. protected virtual void OnIgnoreReceived(IgnoreMessage message)
  1017. {
  1018. var handlers = IgnoreReceived;
  1019. if (handlers != null)
  1020. handlers(this, new MessageEventArgs<IgnoreMessage>(message));
  1021. }
  1022. /// <summary>
  1023. /// Called when <see cref="UnimplementedMessage"/> message received.
  1024. /// </summary>
  1025. /// <param name="message"><see cref="UnimplementedMessage"/> message.</param>
  1026. protected virtual void OnUnimplementedReceived(UnimplementedMessage message)
  1027. {
  1028. var handlers = UnimplementedReceived;
  1029. if (handlers != null)
  1030. handlers(this, new MessageEventArgs<UnimplementedMessage>(message));
  1031. }
  1032. /// <summary>
  1033. /// Called when <see cref="DebugMessage"/> message received.
  1034. /// </summary>
  1035. /// <param name="message"><see cref="DebugMessage"/> message.</param>
  1036. protected virtual void OnDebugReceived(DebugMessage message)
  1037. {
  1038. var handlers = DebugReceived;
  1039. if (handlers != null)
  1040. handlers(this, new MessageEventArgs<DebugMessage>(message));
  1041. }
  1042. /// <summary>
  1043. /// Called when <see cref="ServiceRequestMessage"/> message received.
  1044. /// </summary>
  1045. /// <param name="message"><see cref="ServiceRequestMessage"/> message.</param>
  1046. protected virtual void OnServiceRequestReceived(ServiceRequestMessage message)
  1047. {
  1048. var handlers = ServiceRequestReceived;
  1049. if (handlers != null)
  1050. handlers(this, new MessageEventArgs<ServiceRequestMessage>(message));
  1051. }
  1052. /// <summary>
  1053. /// Called when <see cref="ServiceAcceptMessage"/> message received.
  1054. /// </summary>
  1055. /// <param name="message"><see cref="ServiceAcceptMessage"/> message.</param>
  1056. protected virtual void OnServiceAcceptReceived(ServiceAcceptMessage message)
  1057. {
  1058. var handlers = ServiceAcceptReceived;
  1059. if (handlers != null)
  1060. handlers(this, new MessageEventArgs<ServiceAcceptMessage>(message));
  1061. }
  1062. /// <summary>
  1063. /// Called when <see cref="KeyExchangeInitMessage"/> message received.
  1064. /// </summary>
  1065. /// <param name="message"><see cref="KeyExchangeInitMessage"/> message.</param>
  1066. protected virtual void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
  1067. {
  1068. this._keyExchangeInProgress = true;
  1069. this._keyExchangeCompletedWaitHandle.Reset();
  1070. // Disable all registered messages except key exchange related
  1071. foreach (var messageMetadata in this._messagesMetadata)
  1072. {
  1073. if (messageMetadata.Activated && messageMetadata.Number > 2 && (messageMetadata.Number < 20 || messageMetadata.Number > 30))
  1074. messageMetadata.Enabled = false;
  1075. }
  1076. var keyExchangeAlgorithmName = (from c in this.ConnectionInfo.KeyExchangeAlgorithms.Keys
  1077. from s in message.KeyExchangeAlgorithms
  1078. where s == c
  1079. select c).FirstOrDefault();
  1080. if (keyExchangeAlgorithmName == null)
  1081. {
  1082. throw new SshConnectionException("Failed to negotiate key exchange algorithm.", DisconnectReason.KeyExchangeFailed);
  1083. }
  1084. // Create instance of key exchange algorithm that will be used
  1085. this._keyExchange = this.ConnectionInfo.KeyExchangeAlgorithms[keyExchangeAlgorithmName].CreateInstance<KeyExchange>();
  1086. this.ConnectionInfo.CurrentKeyExchangeAlgorithm = keyExchangeAlgorithmName;
  1087. this._keyExchange.HostKeyReceived += KeyExchange_HostKeyReceived;
  1088. // Start the algorithm implementation
  1089. this._keyExchange.Start(this, message);
  1090. var keyExchangeInitReceived = KeyExchangeInitReceived;
  1091. if (keyExchangeInitReceived != null)
  1092. keyExchangeInitReceived(this, new MessageEventArgs<KeyExchangeInitMessage>(message));
  1093. }
  1094. /// <summary>
  1095. /// Called when <see cref="NewKeysMessage"/> message received.
  1096. /// </summary>
  1097. /// <param name="message"><see cref="NewKeysMessage"/> message.</param>
  1098. protected virtual void OnNewKeysReceived(NewKeysMessage message)
  1099. {
  1100. // Update sessionId
  1101. if (this.SessionId == null)
  1102. {
  1103. this.SessionId = this._keyExchange.ExchangeHash;
  1104. }
  1105. // Dispose of old ciphers and hash algorithms
  1106. if (this._serverMac != null)
  1107. {
  1108. this._serverMac.Clear();
  1109. this._serverMac = null;
  1110. }
  1111. if (this._clientMac != null)
  1112. {
  1113. this._clientMac.Clear();
  1114. this._clientMac = null;
  1115. }
  1116. // Update negotiated algorithms
  1117. this._serverCipher = this._keyExchange.CreateServerCipher();
  1118. this._clientCipher = this._keyExchange.CreateClientCipher();
  1119. this._serverMac = this._keyExchange.CreateServerHash();
  1120. this._clientMac = this._keyExchange.CreateClientHash();
  1121. this._clientCompression = this._keyExchange.CreateCompressor();
  1122. this._serverDecompression = this._keyExchange.CreateDecompressor();
  1123. // Dispose of old KeyExchange object as it is no longer needed.
  1124. if (this._keyExchange != null)
  1125. {
  1126. this._keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1127. this._keyExchange.Dispose();
  1128. this._keyExchange = null;
  1129. }
  1130. // Enable all active registered messages
  1131. foreach (var messageMetadata in this._messagesMetadata)
  1132. {
  1133. if (messageMetadata.Activated)
  1134. messageMetadata.Enabled = true;
  1135. }
  1136. var newKeysReceived = NewKeysReceived;
  1137. if (newKeysReceived != null)
  1138. newKeysReceived(this, new MessageEventArgs<NewKeysMessage>(message));
  1139. // Signal that key exchange completed
  1140. this._keyExchangeCompletedWaitHandle.Set();
  1141. this._keyExchangeInProgress = false;
  1142. }
  1143. /// <summary>
  1144. /// Called when client is disconnecting from the server.
  1145. /// </summary>
  1146. internal void OnDisconnecting()
  1147. {
  1148. _isDisconnecting = true;
  1149. }
  1150. /// <summary>
  1151. /// Called when <see cref="RequestMessage"/> message received.
  1152. /// </summary>
  1153. /// <param name="message"><see cref="RequestMessage"/> message.</param>
  1154. protected virtual void OnUserAuthenticationRequestReceived(RequestMessage message)
  1155. {
  1156. var handlers = UserAuthenticationRequestReceived;
  1157. if (handlers != null)
  1158. handlers(this, new MessageEventArgs<RequestMessage>(message));
  1159. }
  1160. /// <summary>
  1161. /// Called when <see cref="FailureMessage"/> message received.
  1162. /// </summary>
  1163. /// <param name="message"><see cref="FailureMessage"/> message.</param>
  1164. protected virtual void OnUserAuthenticationFailureReceived(FailureMessage message)
  1165. {
  1166. var handlers = UserAuthenticationFailureReceived;
  1167. if (handlers != null)
  1168. handlers(this, new MessageEventArgs<FailureMessage>(message));
  1169. }
  1170. /// <summary>
  1171. /// Called when <see cref="SuccessMessage"/> message received.
  1172. /// </summary>
  1173. /// <param name="message"><see cref="SuccessMessage"/> message.</param>
  1174. protected virtual void OnUserAuthenticationSuccessReceived(SuccessMessage message)
  1175. {
  1176. var handlers = UserAuthenticationSuccessReceived;
  1177. if (handlers != null)
  1178. handlers(this, new MessageEventArgs<SuccessMessage>(message));
  1179. }
  1180. /// <summary>
  1181. /// Called when <see cref="BannerMessage"/> message received.
  1182. /// </summary>
  1183. /// <param name="message"><see cref="BannerMessage"/> message.</param>
  1184. protected virtual void OnUserAuthenticationBannerReceived(BannerMessage message)
  1185. {
  1186. var handlers = UserAuthenticationBannerReceived;
  1187. if (handlers != null)
  1188. handlers(this, new MessageEventArgs<BannerMessage>(message));
  1189. }
  1190. /// <summary>
  1191. /// Called when <see cref="GlobalRequestMessage"/> message received.
  1192. /// </summary>
  1193. /// <param name="message"><see cref="GlobalRequestMessage"/> message.</param>
  1194. protected virtual void OnGlobalRequestReceived(GlobalRequestMessage message)
  1195. {
  1196. var handlers = GlobalRequestReceived;
  1197. if (handlers != null)
  1198. handlers(this, new MessageEventArgs<GlobalRequestMessage>(message));
  1199. }
  1200. /// <summary>
  1201. /// Called when <see cref="RequestSuccessMessage"/> message received.
  1202. /// </summary>
  1203. /// <param name="message"><see cref="RequestSuccessMessage"/> message.</param>
  1204. protected virtual void OnRequestSuccessReceived(RequestSuccessMessage message)
  1205. {
  1206. var handlers = RequestSuccessReceived;
  1207. if (handlers != null)
  1208. handlers(this, new MessageEventArgs<RequestSuccessMessage>(message));
  1209. }
  1210. /// <summary>
  1211. /// Called when <see cref="RequestFailureMessage"/> message received.
  1212. /// </summary>
  1213. /// <param name="message"><see cref="RequestFailureMessage"/> message.</param>
  1214. protected virtual void OnRequestFailureReceived(RequestFailureMessage message)
  1215. {
  1216. var handlers = RequestFailureReceived;
  1217. if (handlers != null)
  1218. handlers(this, new MessageEventArgs<RequestFailureMessage>(message));
  1219. }
  1220. /// <summary>
  1221. /// Called when <see cref="ChannelOpenMessage"/> message received.
  1222. /// </summary>
  1223. /// <param name="message"><see cref="ChannelOpenMessage"/> message.</param>
  1224. protected virtual void OnChannelOpenReceived(ChannelOpenMessage message)
  1225. {
  1226. var handlers = ChannelOpenReceived;
  1227. if (handlers != null)
  1228. handlers(this, new MessageEventArgs<ChannelOpenMessage>(message));
  1229. }
  1230. /// <summary>
  1231. /// Called when <see cref="ChannelOpenConfirmationMessage"/> message received.
  1232. /// </summary>
  1233. /// <param name="message"><see cref="ChannelOpenConfirmationMessage"/> message.</param>
  1234. protected virtual void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage message)
  1235. {
  1236. var handlers = ChannelOpenConfirmationReceived;
  1237. if (handlers != null)
  1238. handlers(this, new MessageEventArgs<ChannelOpenConfirmationMessage>(message));
  1239. }
  1240. /// <summary>
  1241. /// Called when <see cref="ChannelOpenFailureMessage"/> message received.
  1242. /// </summary>
  1243. /// <param name="message"><see cref="ChannelOpenFailureMessage"/> message.</param>
  1244. protected virtual void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
  1245. {
  1246. var handlers = ChannelOpenFailureReceived;
  1247. if (handlers != null)
  1248. handlers(this, new MessageEventArgs<ChannelOpenFailureMessage>(message));
  1249. }
  1250. /// <summary>
  1251. /// Called when <see cref="ChannelWindowAdjustMessage"/> message received.
  1252. /// </summary>
  1253. /// <param name="message"><see cref="ChannelWindowAdjustMessage"/> message.</param>
  1254. protected virtual void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
  1255. {
  1256. var handlers = ChannelWindowAdjustReceived;
  1257. if (handlers != null)
  1258. handlers(this, new MessageEventArgs<ChannelWindowAdjustMessage>(message));
  1259. }
  1260. /// <summary>
  1261. /// Called when <see cref="ChannelDataMessage"/> message received.
  1262. /// </summary>
  1263. /// <param name="message"><see cref="ChannelDataMessage"/> message.</param>
  1264. protected virtual void OnChannelDataReceived(ChannelDataMessage message)
  1265. {
  1266. var handlers = ChannelDataReceived;
  1267. if (handlers != null)
  1268. handlers(this, new MessageEventArgs<ChannelDataMessage>(message));
  1269. }
  1270. /// <summary>
  1271. /// Called when <see cref="ChannelExtendedDataMessage"/> message received.
  1272. /// </summary>
  1273. /// <param name="message"><see cref="ChannelExtendedDataMessage"/> message.</param>
  1274. protected virtual void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
  1275. {
  1276. var handlers = ChannelExtendedDataReceived;
  1277. if (handlers != null)
  1278. handlers(this, new MessageEventArgs<ChannelExtendedDataMessage>(message));
  1279. }
  1280. /// <summary>
  1281. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1282. /// </summary>
  1283. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1284. protected virtual void OnChannelEofReceived(ChannelEofMessage message)
  1285. {
  1286. var handlers = ChannelEofReceived;
  1287. if (handlers != null)
  1288. handlers(this, new MessageEventArgs<ChannelEofMessage>(message));
  1289. }
  1290. /// <summary>
  1291. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1292. /// </summary>
  1293. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1294. protected virtual void OnChannelCloseReceived(ChannelCloseMessage message)
  1295. {
  1296. var handlers = ChannelCloseReceived;
  1297. if (handlers != null)
  1298. handlers(this, new MessageEventArgs<ChannelCloseMessage>(message));
  1299. }
  1300. /// <summary>
  1301. /// Called when <see cref="ChannelRequestMessage"/> message received.
  1302. /// </summary>
  1303. /// <param name="message"><see cref="ChannelRequestMessage"/> message.</param>
  1304. protected virtual void OnChannelRequestReceived(ChannelRequestMessage message)
  1305. {
  1306. var handlers = ChannelRequestReceived;
  1307. if (handlers != null)
  1308. handlers(this, new MessageEventArgs<ChannelRequestMessage>(message));
  1309. }
  1310. /// <summary>
  1311. /// Called when <see cref="ChannelSuccessMessage"/> message received.
  1312. /// </summary>
  1313. /// <param name="message"><see cref="ChannelSuccessMessage"/> message.</param>
  1314. protected virtual void OnChannelSuccessReceived(ChannelSuccessMessage message)
  1315. {
  1316. var handlers = ChannelSuccessReceived;
  1317. if (handlers != null)
  1318. handlers(this, new MessageEventArgs<ChannelSuccessMessage>(message));
  1319. }
  1320. /// <summary>
  1321. /// Called when <see cref="ChannelFailureMessage"/> message received.
  1322. /// </summary>
  1323. /// <param name="message"><see cref="ChannelFailureMessage"/> message.</param>
  1324. protected virtual void OnChannelFailureReceived(ChannelFailureMessage message)
  1325. {
  1326. var handlers = ChannelFailureReceived;
  1327. if (handlers != null)
  1328. handlers(this, new MessageEventArgs<ChannelFailureMessage>(message));
  1329. }
  1330. /// <summary>
  1331. /// Called when <see cref="Message"/> message received.
  1332. /// </summary>
  1333. /// <param name="message"><see cref="Message"/> message.</param>
  1334. protected virtual void OnMessageReceived(Message message)
  1335. {
  1336. var handlers = MessageReceived;
  1337. if (handlers != null)
  1338. handlers(this, new MessageEventArgs<Message>(message));
  1339. }
  1340. #endregion
  1341. private void KeyExchange_HostKeyReceived(object sender, HostKeyEventArgs e)
  1342. {
  1343. var handlers = HostKeyReceived;
  1344. if (handlers != null)
  1345. handlers(this, e);
  1346. }
  1347. /// <summary>
  1348. /// Reads the specified length of bytes from the server.
  1349. /// </summary>
  1350. /// <param name="length">The length.</param>
  1351. /// <returns>
  1352. /// The bytes read from the server.
  1353. /// </returns>
  1354. private byte[] Read(int length)
  1355. {
  1356. var buffer = new byte[length];
  1357. this.SocketRead(length, ref buffer);
  1358. return buffer;
  1359. }
  1360. #region Message loading functions
  1361. /// <summary>
  1362. /// Registers SSH message with the session.
  1363. /// </summary>
  1364. /// <param name="messageName">The name of the message to register with the session.</param>
  1365. public void RegisterMessage(string messageName)
  1366. {
  1367. this.InternalRegisterMessage(messageName);
  1368. }
  1369. /// <summary>
  1370. /// Unregister SSH message from the session.
  1371. /// </summary>
  1372. /// <param name="messageName">The name of the message to unregister with the session.</param>
  1373. public void UnRegisterMessage(string messageName)
  1374. {
  1375. this.InternalUnRegisterMessage(messageName);
  1376. }
  1377. /// <summary>
  1378. /// Loads the message.
  1379. /// </summary>
  1380. /// <param name="data">Message data.</param>
  1381. /// <returns>New message</returns>
  1382. private Message LoadMessage(byte[] data)
  1383. {
  1384. var messageType = data[0];
  1385. var messageMetadata = (from m in this._messagesMetadata where m.Number == messageType && m.Enabled && m.Activated select m).SingleOrDefault();
  1386. if (messageMetadata == null)
  1387. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Message type {0} is not valid.", messageType));
  1388. var message = messageMetadata.Type.CreateInstance<Message>();
  1389. message.Load(data);
  1390. this.Log(string.Format("ReceiveMessage from server: '{0}': '{1}'.", message.GetType().Name, message));
  1391. return message;
  1392. }
  1393. partial void InternalRegisterMessage(string messageName);
  1394. partial void InternalUnRegisterMessage(string messageName);
  1395. #endregion
  1396. partial void ExecuteThread(Action action);
  1397. /// <summary>
  1398. /// Gets a value indicating whether the socket is connected.
  1399. /// </summary>
  1400. /// <value>
  1401. /// <c>true</c> if the socket is connected; otherwise, <c>false</c>.
  1402. /// </value>
  1403. partial void IsSocketConnected(ref bool isConnected);
  1404. /// <summary>
  1405. /// Establishes a socket connection to the specified host and port.
  1406. /// </summary>
  1407. /// <param name="host">The host name of the server to connect to.</param>
  1408. /// <param name="port">The port to connect to.</param>
  1409. /// <exception cref="SshOperationTimeoutException">The connection failed to establish within the configured <see cref="Renci.SshNet.ConnectionInfo.Timeout"/>.</exception>
  1410. /// <exception cref="SocketException">An error occurred trying to establish the connection.</exception>
  1411. partial void SocketConnect(string host, int port);
  1412. /// <summary>
  1413. /// Closes the socket.
  1414. /// </summary>
  1415. /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
  1416. partial void SocketDisconnect();
  1417. /// <summary>
  1418. /// Performs a blocking read on the socket until <paramref name="length"/> bytes are received.
  1419. /// </summary>
  1420. /// <param name="length">The number of bytes to read.</param>
  1421. /// <param name="buffer">The buffer to read to.</param>
  1422. /// <exception cref="SshConnectionException">The socket is closed.</exception>
  1423. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  1424. private void SocketRead(int length, ref byte[] buffer)
  1425. {
  1426. SocketRead(length, ref buffer, ConnectionInfo.Timeout);
  1427. }
  1428. /// <summary>
  1429. /// Performs a blocking read on the socket until <paramref name="length"/> bytes are received.
  1430. /// </summary>
  1431. /// <param name="length">The number of bytes to read.</param>
  1432. /// <param name="buffer">The buffer to read to.</param>
  1433. /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until <paramref name="length"/> bytes a read.</param>
  1434. /// <exception cref="SshConnectionException">The socket is closed.</exception>
  1435. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  1436. partial void SocketRead(int length, ref byte[] buffer, TimeSpan timeout);
  1437. /// <summary>
  1438. /// Performs a blocking read on the socket until a line is read.
  1439. /// </summary>
  1440. /// <param name="response">The line read from the socket, or <c>null</c> when the remote server has shutdown and all data has been received.</param>
  1441. /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param>
  1442. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  1443. partial void SocketReadLine(ref string response, TimeSpan timeout);
  1444. partial void Log(string text);
  1445. /// <summary>
  1446. /// Writes the specified data to the server.
  1447. /// </summary>
  1448. /// <param name="data">The data to write to the server.</param>
  1449. /// <exception cref="SshOperationTimeoutException">The write has timed-out.</exception>
  1450. partial void SocketWrite(byte[] data);
  1451. /// <summary>
  1452. /// Disconnects and disposes the socket.
  1453. /// </summary>
  1454. private void SocketDisconnectAndDispose()
  1455. {
  1456. if (_socket != null)
  1457. {
  1458. lock (_socketLock)
  1459. {
  1460. if (_socket != null)
  1461. {
  1462. SocketDisconnect();
  1463. _socket.Dispose();
  1464. _socket = null;
  1465. }
  1466. }
  1467. }
  1468. }
  1469. /// <summary>
  1470. /// Listens for incoming message from the server and handles them. This method run as a task on separate thread.
  1471. /// </summary>
  1472. private void MessageListener()
  1473. {
  1474. try
  1475. {
  1476. while (this._socket != null && this._socket.Connected)
  1477. {
  1478. var message = this.ReceiveMessage();
  1479. this.HandleMessageCore(message);
  1480. }
  1481. }
  1482. catch (Exception exp)
  1483. {
  1484. this.RaiseError(exp);
  1485. }
  1486. }
  1487. private byte SocketReadByte()
  1488. {
  1489. var buffer = new byte[1];
  1490. this.SocketRead(1, ref buffer);
  1491. return buffer[0];
  1492. }
  1493. private void SocketWriteByte(byte data)
  1494. {
  1495. this.SocketWrite(new[] {data});
  1496. }
  1497. private void ConnectSocks4()
  1498. {
  1499. // Send socks version number
  1500. this.SocketWriteByte(0x04);
  1501. // Send command code
  1502. this.SocketWriteByte(0x01);
  1503. // Send port
  1504. this.SocketWriteByte((byte)(this.ConnectionInfo.Port / 0xFF));
  1505. this.SocketWriteByte((byte)(this.ConnectionInfo.Port % 0xFF));
  1506. // Send IP
  1507. IPAddress ipAddress = this.ConnectionInfo.Host.GetIPAddress();
  1508. this.SocketWrite(ipAddress.GetAddressBytes());
  1509. // Send username
  1510. var username = new Common.ASCIIEncoding().GetBytes(this.ConnectionInfo.ProxyUsername);
  1511. this.SocketWrite(username);
  1512. this.SocketWriteByte(0x00);
  1513. // Read 0
  1514. if (this.SocketReadByte() != 0)
  1515. {
  1516. throw new ProxyException("SOCKS4: Null is expected.");
  1517. }
  1518. // Read response code
  1519. var code = this.SocketReadByte();
  1520. switch (code)
  1521. {
  1522. case 0x5a:
  1523. break;
  1524. case 0x5b:
  1525. throw new ProxyException("SOCKS4: Connection rejected.");
  1526. case 0x5c:
  1527. throw new ProxyException("SOCKS4: Client is not running identd or not reachable from the server.");
  1528. case 0x5d:
  1529. throw new ProxyException("SOCKS4: Client's identd could not confirm the user ID string in the request.");
  1530. default:
  1531. throw new ProxyException("SOCKS4: Not valid response.");
  1532. }
  1533. var dummyBuffer = new byte[4];
  1534. // Read 2 bytes to be ignored
  1535. this.SocketRead(2, ref dummyBuffer);
  1536. // Read 4 bytes to be ignored
  1537. this.SocketRead(4, ref dummyBuffer);
  1538. }
  1539. private void ConnectSocks5()
  1540. {
  1541. // Send socks version number
  1542. this.SocketWriteByte(0x05);
  1543. // Send number of supported authentication methods
  1544. this.SocketWriteByte(0x02);
  1545. // Send supported authentication methods
  1546. this.SocketWriteByte(0x00); // No authentication
  1547. this.SocketWriteByte(0x02); // Username/Password
  1548. var socksVersion = this.SocketReadByte();
  1549. if (socksVersion != 0x05)
  1550. throw new ProxyException(string.Format("SOCKS Version '{0}' is not supported.", socksVersion));
  1551. var authenticationMethod = this.SocketReadByte();
  1552. switch (authenticationMethod)
  1553. {
  1554. case 0x00:
  1555. break;
  1556. case 0x02:
  1557. // Send version
  1558. this.SocketWriteByte(0x01);
  1559. var encoding = new Common.ASCIIEncoding();
  1560. var username = encoding.GetBytes(this.ConnectionInfo.ProxyUsername);
  1561. if (username.Length > byte.MaxValue)
  1562. throw new ProxyException("Proxy username is too long.");
  1563. // Send username length
  1564. this.SocketWriteByte((byte)username.Length);
  1565. // Send username
  1566. this.SocketWrite(username);
  1567. var password = encoding.GetBytes(this.ConnectionInfo.ProxyPassword);
  1568. if (password.Length > byte.MaxValue)
  1569. throw new ProxyException("Proxy password is too long.");
  1570. // Send username length
  1571. this.SocketWriteByte((byte)password.Length);
  1572. // Send username
  1573. this.SocketWrite(password);
  1574. var serverVersion = this.SocketReadByte();
  1575. if (serverVersion != 1)
  1576. throw new ProxyException("SOCKS5: Server authentication version is not valid.");
  1577. var statusCode = this.SocketReadByte();
  1578. if (statusCode != 0)
  1579. throw new ProxyException("SOCKS5: Username/Password authentication failed.");
  1580. break;
  1581. case 0xFF:
  1582. throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
  1583. }
  1584. // Send socks version number
  1585. this.SocketWriteByte(0x05);
  1586. // Send command code
  1587. this.SocketWriteByte(0x01); // establish a TCP/IP stream connection
  1588. // Send reserved, must be 0x00
  1589. this.SocketWriteByte(0x00);
  1590. IPAddress ip = this.ConnectionInfo.Host.GetIPAddress();
  1591. // Send address type and address
  1592. if (ip.AddressFamily == AddressFamily.InterNetwork)
  1593. {
  1594. this.SocketWriteByte(0x01);
  1595. var address = ip.GetAddressBytes();
  1596. this.SocketWrite(address);
  1597. }
  1598. else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
  1599. {
  1600. this.SocketWriteByte(0x04);
  1601. var address = ip.GetAddressBytes();
  1602. this.SocketWrite(address);
  1603. }
  1604. else
  1605. {
  1606. throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
  1607. }
  1608. // Send port
  1609. this.SocketWriteByte((byte)(this.ConnectionInfo.Port / 0xFF));
  1610. this.SocketWriteByte((byte)(this.ConnectionInfo.Port % 0xFF));
  1611. // Read Server SOCKS5 version
  1612. if (this.SocketReadByte() != 5)
  1613. {
  1614. throw new ProxyException("SOCKS5: Version 5 is expected.");
  1615. }
  1616. // Read response code
  1617. var status = this.SocketReadByte();
  1618. switch (status)
  1619. {
  1620. case 0x00:
  1621. break;
  1622. case 0x01:
  1623. throw new ProxyException("SOCKS5: General failure.");
  1624. case 0x02:
  1625. throw new ProxyException("SOCKS5: Connection not allowed by ruleset.");
  1626. case 0x03:
  1627. throw new ProxyException("SOCKS5: Network unreachable.");
  1628. case 0x04:
  1629. throw new ProxyException("SOCKS5: Host unreachable.");
  1630. case 0x05:
  1631. throw new ProxyException("SOCKS5: Connection refused by destination host.");
  1632. case 0x06:
  1633. throw new ProxyException("SOCKS5: TTL expired.");
  1634. case 0x07:
  1635. throw new ProxyException("SOCKS5: Command not supported or protocol error.");
  1636. case 0x08:
  1637. throw new ProxyException("SOCKS5: Address type not supported.");
  1638. default:
  1639. throw new ProxyException("SOCKS4: Not valid response.");
  1640. }
  1641. // Read 0
  1642. if (this.SocketReadByte() != 0)
  1643. {
  1644. throw new ProxyException("SOCKS5: 0 byte is expected.");
  1645. }
  1646. var addressType = this.SocketReadByte();
  1647. var responseIp = new byte[16];
  1648. switch (addressType)
  1649. {
  1650. case 0x01:
  1651. this.SocketRead(4, ref responseIp);
  1652. break;
  1653. case 0x04:
  1654. this.SocketRead(16, ref responseIp);
  1655. break;
  1656. default:
  1657. throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
  1658. }
  1659. var port = new byte[2];
  1660. // Read 2 bytes to be ignored
  1661. this.SocketRead(2, ref port);
  1662. }
  1663. private void ConnectHttp()
  1664. {
  1665. var httpResponseRe = new Regex(@"HTTP/(?<version>\d[.]\d) (?<statusCode>\d{3}) (?<reasonPhrase>.+)$");
  1666. var httpHeaderRe = new Regex(@"(?<fieldName>[^\[\]()<>@,;:\""/?={} \t]+):(?<fieldValue>.+)?");
  1667. var encoding = new Common.ASCIIEncoding();
  1668. this.SocketWrite(encoding.GetBytes(string.Format("CONNECT {0}:{1} HTTP/1.0\r\n", this.ConnectionInfo.Host, this.ConnectionInfo.Port)));
  1669. // Sent proxy authorization is specified
  1670. if (!string.IsNullOrEmpty(this.ConnectionInfo.ProxyUsername))
  1671. {
  1672. var authorization = string.Format("Proxy-Authorization: Basic {0}\r\n",
  1673. Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", this.ConnectionInfo.ProxyUsername, this.ConnectionInfo.ProxyPassword)))
  1674. );
  1675. this.SocketWrite(encoding.GetBytes(authorization));
  1676. }
  1677. this.SocketWrite(encoding.GetBytes("\r\n"));
  1678. HttpStatusCode? statusCode = null;
  1679. var response = string.Empty;
  1680. var contentLength = 0;
  1681. while (true)
  1682. {
  1683. this.SocketReadLine(ref response, ConnectionInfo.Timeout);
  1684. if (response == null)
  1685. // server shut down socket
  1686. break;
  1687. if (statusCode == null)
  1688. {
  1689. var statusMatch = httpResponseRe.Match(response);
  1690. if (statusMatch.Success)
  1691. {
  1692. var httpStatusCode = statusMatch.Result("${statusCode}");
  1693. statusCode = (HttpStatusCode) int.Parse(httpStatusCode);
  1694. if (statusCode != HttpStatusCode.OK)
  1695. {
  1696. var reasonPhrase = statusMatch.Result("${reasonPhrase}");
  1697. throw new ProxyException(string.Format("HTTP: Status code {0}, \"{1}\"", httpStatusCode,
  1698. reasonPhrase));
  1699. }
  1700. }
  1701. continue;
  1702. }
  1703. // continue on parsing message headers coming from the server
  1704. var headerMatch = httpHeaderRe.Match(response);
  1705. if (headerMatch.Success)
  1706. {
  1707. var fieldName = headerMatch.Result("${fieldName}");
  1708. if (fieldName.Equals("Content-Length", StringComparison.InvariantCultureIgnoreCase))
  1709. {
  1710. contentLength = int.Parse(headerMatch.Result("${fieldValue}"));
  1711. }
  1712. continue;
  1713. }
  1714. // check if we've reached the CRLF which separates request line and headers from the message body
  1715. if (response.Length == 0)
  1716. {
  1717. // read response body if specified
  1718. if (contentLength > 0)
  1719. {
  1720. var contentBody = new byte[contentLength];
  1721. SocketRead(contentLength, ref contentBody);
  1722. }
  1723. break;
  1724. }
  1725. }
  1726. if (statusCode == null)
  1727. throw new ProxyException("HTTP response does not contain status line.");
  1728. }
  1729. /// <summary>
  1730. /// Raises the <see cref="ErrorOccured"/> event.
  1731. /// </summary>
  1732. /// <param name="exp">The exp.</param>
  1733. private void RaiseError(Exception exp)
  1734. {
  1735. var connectionException = exp as SshConnectionException;
  1736. if (_isDisconnecting)
  1737. {
  1738. // a connection exception which is raised while isDisconnecting is normal and
  1739. // should be ignored
  1740. if (connectionException != null)
  1741. return;
  1742. // any timeout while disconnecting can be caused by loss of connectivity
  1743. // altogether and should be ignored
  1744. var socketException = exp as SocketException;
  1745. if (socketException != null && socketException.SocketErrorCode == SocketError.TimedOut)
  1746. return;
  1747. }
  1748. this._exception = exp;
  1749. this._exceptionWaitHandle.Set();
  1750. var errorOccured = ErrorOccured;
  1751. if (errorOccured != null)
  1752. errorOccured(this, new ExceptionEventArgs(exp));
  1753. if (connectionException != null && connectionException.DisconnectReason != DisconnectReason.ConnectionLost)
  1754. {
  1755. this.Disconnect(connectionException.DisconnectReason, exp.ToString());
  1756. }
  1757. }
  1758. /// <summary>
  1759. /// Resets connection-specific information to ensure state of a previous connection
  1760. /// does not affect new connections.
  1761. /// </summary>
  1762. private void Reset()
  1763. {
  1764. if (_exceptionWaitHandle != null)
  1765. _exceptionWaitHandle.Reset();
  1766. if (_keyExchangeCompletedWaitHandle != null)
  1767. _keyExchangeCompletedWaitHandle.Reset();
  1768. if (_messageListenerCompleted != null)
  1769. _messageListenerCompleted.Reset();
  1770. SessionId = null;
  1771. _isDisconnectMessageSent = false;
  1772. _isDisconnecting = false;
  1773. _isAuthenticated = false;
  1774. _exception = null;
  1775. _keyExchangeInProgress = false;
  1776. }
  1777. #region IDisposable Members
  1778. private bool _disposed;
  1779. /// <summary>
  1780. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  1781. /// </summary>
  1782. public void Dispose()
  1783. {
  1784. Dispose(true);
  1785. GC.SuppressFinalize(this);
  1786. }
  1787. /// <summary>
  1788. /// Releases unmanaged and - optionally - managed resources
  1789. /// </summary>
  1790. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1791. protected virtual void Dispose(bool disposing)
  1792. {
  1793. // Check to see if Dispose has already been called.
  1794. if (!this._disposed)
  1795. {
  1796. // If disposing equals true, dispose all managed
  1797. // and unmanaged ResourceMessages.
  1798. if (disposing)
  1799. {
  1800. Disconnect();
  1801. if (this._serviceAccepted != null)
  1802. {
  1803. this._serviceAccepted.Dispose();
  1804. this._serviceAccepted = null;
  1805. }
  1806. if (this._exceptionWaitHandle != null)
  1807. {
  1808. this._exceptionWaitHandle.Dispose();
  1809. this._exceptionWaitHandle = null;
  1810. }
  1811. if (this._keyExchangeCompletedWaitHandle != null)
  1812. {
  1813. this._keyExchangeCompletedWaitHandle.Dispose();
  1814. this._keyExchangeCompletedWaitHandle = null;
  1815. }
  1816. if (this._serverMac != null)
  1817. {
  1818. this._serverMac.Clear();
  1819. this._serverMac = null;
  1820. }
  1821. if (this._clientMac != null)
  1822. {
  1823. this._clientMac.Clear();
  1824. this._clientMac = null;
  1825. }
  1826. if (this._keyExchange != null)
  1827. {
  1828. this._keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1829. this._keyExchange.Dispose();
  1830. this._keyExchange = null;
  1831. }
  1832. if (_bytesReadFromSocket != null)
  1833. {
  1834. _bytesReadFromSocket.Dispose();
  1835. _bytesReadFromSocket = null;
  1836. }
  1837. }
  1838. // Note disposing has been done.
  1839. this._disposed = true;
  1840. }
  1841. }
  1842. /// <summary>
  1843. /// Releases unmanaged resources and performs other cleanup operations before the
  1844. /// <see cref="Session"/> is reclaimed by garbage collection.
  1845. /// </summary>
  1846. ~Session()
  1847. {
  1848. // Do not re-create Dispose clean-up code here.
  1849. // Calling Dispose(false) is optimal in terms of
  1850. // readability and maintainability.
  1851. Dispose(false);
  1852. }
  1853. #endregion
  1854. private class MessageMetadata
  1855. {
  1856. public string Name { get; set; }
  1857. public byte Number { get; set; }
  1858. public bool Enabled { get; set; }
  1859. public bool Activated { get; set; }
  1860. public Type Type { get; set; }
  1861. }
  1862. }
  1863. }