Session.cs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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
  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 form 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. #region Message events
  262. /// <summary>
  263. /// Occurs when <see cref="DisconnectMessage"/> message received
  264. /// </summary>
  265. internal event EventHandler<MessageEventArgs<DisconnectMessage>> DisconnectReceived;
  266. /// <summary>
  267. /// Occurs when <see cref="IgnoreMessage"/> message received
  268. /// </summary>
  269. internal event EventHandler<MessageEventArgs<IgnoreMessage>> IgnoreReceived;
  270. /// <summary>
  271. /// Occurs when <see cref="UnimplementedMessage"/> message received
  272. /// </summary>
  273. internal event EventHandler<MessageEventArgs<UnimplementedMessage>> UnimplementedReceived;
  274. /// <summary>
  275. /// Occurs when <see cref="DebugMessage"/> message received
  276. /// </summary>
  277. internal event EventHandler<MessageEventArgs<DebugMessage>> DebugReceived;
  278. /// <summary>
  279. /// Occurs when <see cref="ServiceRequestMessage"/> message received
  280. /// </summary>
  281. internal event EventHandler<MessageEventArgs<ServiceRequestMessage>> ServiceRequestReceived;
  282. /// <summary>
  283. /// Occurs when <see cref="ServiceAcceptMessage"/> message received
  284. /// </summary>
  285. internal event EventHandler<MessageEventArgs<ServiceAcceptMessage>> ServiceAcceptReceived;
  286. /// <summary>
  287. /// Occurs when <see cref="KeyExchangeInitMessage"/> message received
  288. /// </summary>
  289. internal event EventHandler<MessageEventArgs<KeyExchangeInitMessage>> KeyExchangeInitReceived;
  290. /// <summary>
  291. /// Occurs when <see cref="NewKeysMessage"/> message received
  292. /// </summary>
  293. internal event EventHandler<MessageEventArgs<NewKeysMessage>> NewKeysReceived;
  294. /// <summary>
  295. /// Occurs when <see cref="RequestMessage"/> message received
  296. /// </summary>
  297. internal event EventHandler<MessageEventArgs<RequestMessage>> UserAuthenticationRequestReceived;
  298. /// <summary>
  299. /// Occurs when <see cref="FailureMessage"/> message received
  300. /// </summary>
  301. internal event EventHandler<MessageEventArgs<FailureMessage>> UserAuthenticationFailureReceived;
  302. /// <summary>
  303. /// Occurs when <see cref="SuccessMessage"/> message received
  304. /// </summary>
  305. internal event EventHandler<MessageEventArgs<SuccessMessage>> UserAuthenticationSuccessReceived;
  306. /// <summary>
  307. /// Occurs when <see cref="BannerMessage"/> message received
  308. /// </summary>
  309. internal event EventHandler<MessageEventArgs<BannerMessage>> UserAuthenticationBannerReceived;
  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);
  430. this.ServerVersion = serverVersion;
  431. if (string.IsNullOrEmpty(this.ServerVersion))
  432. {
  433. throw new InvalidOperationException("Server string is null or empty.");
  434. }
  435. versionMatch = ServerVersionRe.Match(this.ServerVersion);
  436. if (versionMatch.Success)
  437. {
  438. break;
  439. }
  440. }
  441. // Set connection versions
  442. this.ConnectionInfo.ServerVersion = this.ServerVersion;
  443. this.ConnectionInfo.ClientVersion = this.ClientVersion;
  444. // Get server SSH version
  445. var version = versionMatch.Result("${protoversion}");
  446. var softwareName = versionMatch.Result("${softwareversion}");
  447. this.Log(string.Format("Server version '{0}' on '{1}'.", version, softwareName));
  448. if (!(version.Equals("2.0") || version.Equals("1.99")))
  449. {
  450. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", version), DisconnectReason.ProtocolVersionNotSupported);
  451. }
  452. this.SocketWrite(Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}\x0D\x0A", this.ClientVersion)));
  453. // Register Transport response messages
  454. this.RegisterMessage("SSH_MSG_DISCONNECT");
  455. this.RegisterMessage("SSH_MSG_IGNORE");
  456. this.RegisterMessage("SSH_MSG_UNIMPLEMENTED");
  457. this.RegisterMessage("SSH_MSG_DEBUG");
  458. this.RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
  459. this.RegisterMessage("SSH_MSG_KEXINIT");
  460. this.RegisterMessage("SSH_MSG_NEWKEYS");
  461. // Some server implementations might sent this message first, prior establishing encryption algorithm
  462. this.RegisterMessage("SSH_MSG_USERAUTH_BANNER");
  463. // Start incoming request listener
  464. this._messageListenerCompleted = new ManualResetEvent(false);
  465. this.ExecuteThread(() =>
  466. {
  467. try
  468. {
  469. this.MessageListener();
  470. }
  471. finally
  472. {
  473. this._messageListenerCompleted.Set();
  474. }
  475. });
  476. // Wait for key exchange to be completed
  477. this.WaitOnHandle(this._keyExchangeCompletedWaitHandle);
  478. // If sessionId is not set then its not connected
  479. if (this.SessionId == null)
  480. {
  481. this.Disconnect();
  482. return;
  483. }
  484. // Request user authorization service
  485. this.SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
  486. // Wait for service to be accepted
  487. this.WaitOnHandle(this._serviceAccepted);
  488. if (string.IsNullOrEmpty(this.ConnectionInfo.Username))
  489. {
  490. throw new SshException("Username is not specified.");
  491. }
  492. this.ConnectionInfo.Authenticate(this);
  493. this._isAuthenticated = true;
  494. // Register Connection messages
  495. this.RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
  496. this.RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
  497. this.RegisterMessage("SSH_MSG_REQUEST_FAILURE");
  498. this.RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
  499. this.RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
  500. this.RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
  501. this.RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
  502. this.RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
  503. this.RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
  504. this.RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
  505. this.RegisterMessage("SSH_MSG_CHANNEL_DATA");
  506. this.RegisterMessage("SSH_MSG_CHANNEL_EOF");
  507. this.RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
  508. Monitor.Pulse(this);
  509. }
  510. }
  511. finally
  512. {
  513. AuthenticationConnection.Release();
  514. }
  515. }
  516. /// <summary>
  517. /// Disconnects from the server.
  518. /// </summary>
  519. /// <remarks>
  520. /// This sends a <b>SSH_MSG_DISCONNECT</b> message to the server, waits for the
  521. /// server to close the socket on its end and subsequently closes the client socket.
  522. /// </remarks>
  523. public void Disconnect()
  524. {
  525. Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
  526. }
  527. private void Disconnect(DisconnectReason reason, string message)
  528. {
  529. this._isDisconnecting = true;
  530. // send disconnect message to the server if the connection is still open
  531. // and the disconnect message has not yet been sent
  532. //
  533. // note that this should also cause the listener thread to be stopped as
  534. // the server should respond by closing the socket
  535. SendDisconnect(reason, message);
  536. // disconnect socket, and dispose it
  537. SocketDisconnectAndDispose();
  538. if (_messageListenerCompleted != null)
  539. {
  540. // at this point, we are sure that the listener thread will stop
  541. // as we've disconnected the socket
  542. _messageListenerCompleted.WaitOne();
  543. _messageListenerCompleted.Dispose();
  544. _messageListenerCompleted = null;
  545. }
  546. }
  547. internal T CreateClientChannel<T>() where T : ClientChannel, new()
  548. {
  549. var channel = new T();
  550. lock (this)
  551. {
  552. channel.Initialize(this, InitialLocalWindowSize, LocalChannelDataPacketSize);
  553. }
  554. return channel;
  555. }
  556. internal T CreateServerChannel<T>(uint remoteChannelNumber, uint remoteWindowSize, uint remoteChannelDataPacketSize) where T : ServerChannel, new()
  557. {
  558. var channel = new T();
  559. lock (this)
  560. {
  561. channel.Initialize(this, InitialLocalWindowSize, LocalChannelDataPacketSize, remoteChannelNumber, remoteWindowSize,
  562. remoteChannelDataPacketSize);
  563. }
  564. return channel;
  565. }
  566. /// <summary>
  567. /// Sends "keep alive" message to keep connection alive.
  568. /// </summary>
  569. internal void SendKeepAlive()
  570. {
  571. this.SendMessage(new IgnoreMessage());
  572. }
  573. /// <summary>
  574. /// Waits for the specified handle or the exception handle for the receive thread
  575. /// to signal within the connection timeout.
  576. /// </summary>
  577. /// <param name="waitHandle">The wait handle.</param>
  578. /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
  579. /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
  580. /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
  581. /// <remarks>
  582. /// When neither handles are signaled in time and the session is not closing, then the
  583. /// session is disconnected.
  584. ///
  585. /// </remarks>
  586. internal void WaitOnHandle(WaitHandle waitHandle)
  587. {
  588. var waitHandles = new[]
  589. {
  590. this._exceptionWaitHandle,
  591. this._messageListenerCompleted,
  592. waitHandle
  593. };
  594. switch (WaitHandle.WaitAny(waitHandles, ConnectionInfo.Timeout))
  595. {
  596. case 0:
  597. throw this._exception;
  598. case 1:
  599. // when the session is NOT disconnecting, the listener should actually
  600. // never complete without setting the exception wait handle and should
  601. // end up in case 0...
  602. //
  603. // when the session is disconnecting, the completion of the listener
  604. // should not be considered an error (quite the oppposite actually)
  605. if (!_isDisconnecting)
  606. {
  607. throw new SshConnectionException("Client not connected.");
  608. }
  609. break;
  610. case WaitHandle.WaitTimeout:
  611. // when the session is NOT disconnecting, then we want to disconnect
  612. // the session altogether in case of a timeout, and throw a
  613. // SshOperationTimeoutException
  614. //
  615. // when the session is disconnecting, a timeout is likely when no
  616. // network connectivity is available; depending on the configured
  617. // timeout either the WaitAny times out first or a SocketException
  618. // detailing a timeout thrown hereby completing the listener thread
  619. // (which makes us end up in case 1). Either way, we do not want to
  620. // disconnect while we're already disconnecting and we do not want
  621. // to report an exception to the client when we're disconnecting
  622. // anyway
  623. if (!_isDisconnecting)
  624. {
  625. this.Disconnect(DisconnectReason.ByApplication, "Operation timeout");
  626. throw new SshOperationTimeoutException("Session operation has timed out");
  627. }
  628. break;
  629. }
  630. }
  631. /// <summary>
  632. /// Sends packet message to the server.
  633. /// </summary>
  634. /// <param name="message">The message.</param>
  635. internal void SendMessage(Message message)
  636. {
  637. if (this._socket == null || !this._socket.CanWrite())
  638. throw new SshConnectionException("Client not connected.");
  639. if (this._keyExchangeInProgress && !(message is IKeyExchangedAllowed))
  640. {
  641. // Wait for key exchange to be completed
  642. this.WaitOnHandle(this._keyExchangeCompletedWaitHandle);
  643. }
  644. this.Log(string.Format("SendMessage to server '{0}': '{1}'.", message.GetType().Name, message));
  645. // Messages can be sent by different thread so we need to synchronize it
  646. 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
  647. var messageData = message.GetBytes();
  648. if (this._clientCompression != null)
  649. {
  650. messageData = this._clientCompression.Compress(messageData);
  651. }
  652. var packetLength = messageData.Length + 4 + 1; // add length bytes and padding byte
  653. var paddingLength = (byte)((-packetLength) & (paddingMultiplier - 1));
  654. if (paddingLength < paddingMultiplier)
  655. {
  656. paddingLength += paddingMultiplier;
  657. }
  658. // Build Packet data
  659. var packetData = new byte[4 + 1 + messageData.Length + paddingLength];
  660. // Add packet length
  661. ((uint)packetData.Length - 4).GetBytes().CopyTo(packetData, 0);
  662. // Add packet padding length
  663. packetData[4] = paddingLength;
  664. // Add packet payload
  665. messageData.CopyTo(packetData, 4 + 1);
  666. // Add random padding
  667. var paddingBytes = new byte[paddingLength];
  668. Randomizer.GetBytes(paddingBytes);
  669. paddingBytes.CopyTo(packetData, 4 + 1 + messageData.Length);
  670. // Lock handling of _outboundPacketSequence since it must be sent sequently to server
  671. lock (this._socketLock)
  672. {
  673. if (this._socket == null || !this._socket.Connected)
  674. throw new SshConnectionException("Client not connected.");
  675. // Calculate packet hash
  676. var hashData = new byte[4 + packetData.Length];
  677. this._outboundPacketSequence.GetBytes().CopyTo(hashData, 0);
  678. packetData.CopyTo(hashData, 4);
  679. // Encrypt packet data
  680. if (this._clientCipher != null)
  681. {
  682. packetData = this._clientCipher.Encrypt(packetData);
  683. }
  684. if (packetData.Length > MaximumSshPacketSize)
  685. {
  686. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Packet is too big. Maximum packet size is {0} bytes.", MaximumSshPacketSize));
  687. }
  688. if (this._clientMac == null)
  689. {
  690. this.SocketWrite(packetData);
  691. }
  692. else
  693. {
  694. var hash = this._clientMac.ComputeHash(hashData.ToArray());
  695. var data = new byte[packetData.Length + this._clientMac.HashSize / 8];
  696. packetData.CopyTo(data, 0);
  697. hash.CopyTo(data, packetData.Length);
  698. this.SocketWrite(data);
  699. }
  700. this._outboundPacketSequence++;
  701. Monitor.Pulse(this._socketLock);
  702. }
  703. }
  704. private static IEnumerable<MessageMetadata> GetMessagesMetadata()
  705. {
  706. return new []
  707. {
  708. new MessageMetadata { Name = "SSH_MSG_NEWKEYS", Number = 21, Type = typeof(NewKeysMessage) },
  709. new MessageMetadata { Name = "SSH_MSG_REQUEST_FAILURE", Number = 82, Type = typeof(RequestFailureMessage) },
  710. new MessageMetadata { Name = "SSH_MSG_KEXINIT", Number = 20, Type = typeof(KeyExchangeInitMessage) },
  711. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN_FAILURE", Number = 92, Type = typeof(ChannelOpenFailureMessage) },
  712. new MessageMetadata { Name = "SSH_MSG_CHANNEL_FAILURE", Number = 100, Type = typeof(ChannelFailureMessage) },
  713. new MessageMetadata { Name = "SSH_MSG_CHANNEL_EXTENDED_DATA", Number = 95, Type = typeof(ChannelExtendedDataMessage) },
  714. new MessageMetadata { Name = "SSH_MSG_CHANNEL_DATA", Number = 94, Type = typeof(ChannelDataMessage) },
  715. new MessageMetadata { Name = "SSH_MSG_USERAUTH_REQUEST", Number = 50, Type = typeof(RequestMessage) },
  716. new MessageMetadata { Name = "SSH_MSG_CHANNEL_REQUEST", Number = 98, Type = typeof(ChannelRequestMessage) },
  717. new MessageMetadata { Name = "SSH_MSG_USERAUTH_BANNER", Number = 53, Type = typeof(BannerMessage) },
  718. new MessageMetadata { Name = "SSH_MSG_USERAUTH_INFO_RESPONSE", Number = 61, Type = typeof(InformationResponseMessage) },
  719. new MessageMetadata { Name = "SSH_MSG_USERAUTH_FAILURE", Number = 51, Type = typeof(FailureMessage) },
  720. new MessageMetadata { Name = "SSH_MSG_DEBUG", Number = 4, Type = typeof(DebugMessage), },
  721. new MessageMetadata { Name = "SSH_MSG_KEXDH_INIT", Number = 30, Type = typeof(KeyExchangeDhInitMessage) },
  722. new MessageMetadata { Name = "SSH_MSG_GLOBAL_REQUEST", Number = 80, Type = typeof(GlobalRequestMessage) },
  723. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN", Number = 90, Type = typeof(ChannelOpenMessage) },
  724. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN_CONFIRMATION", Number = 91, Type = typeof(ChannelOpenConfirmationMessage) },
  725. new MessageMetadata { Name = "SSH_MSG_USERAUTH_INFO_REQUEST", Number = 60, Type = typeof(InformationRequestMessage) },
  726. new MessageMetadata { Name = "SSH_MSG_UNIMPLEMENTED", Number = 3, Type = typeof(UnimplementedMessage) },
  727. new MessageMetadata { Name = "SSH_MSG_REQUEST_SUCCESS", Number = 81, Type = typeof(RequestSuccessMessage) },
  728. new MessageMetadata { Name = "SSH_MSG_CHANNEL_SUCCESS", Number = 99, Type = typeof(ChannelSuccessMessage) },
  729. new MessageMetadata { Name = "SSH_MSG_USERAUTH_PASSWD_CHANGEREQ", Number = 60, Type = typeof(PasswordChangeRequiredMessage) },
  730. new MessageMetadata { Name = "SSH_MSG_DISCONNECT", Number = 1, Type = typeof(DisconnectMessage) },
  731. new MessageMetadata { Name = "SSH_MSG_SERVICE_REQUEST", Number = 5, Type = typeof(ServiceRequestMessage) },
  732. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_REQUEST", Number = 34, Type = typeof(KeyExchangeDhGroupExchangeRequest) },
  733. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_GROUP", Number = 31, Type = typeof(KeyExchangeDhGroupExchangeGroup) },
  734. new MessageMetadata { Name = "SSH_MSG_USERAUTH_SUCCESS", Number = 52, Type = typeof(SuccessMessage) },
  735. new MessageMetadata { Name = "SSH_MSG_USERAUTH_PK_OK", Number = 60, Type = typeof(PublicKeyMessage) },
  736. new MessageMetadata { Name = "SSH_MSG_IGNORE", Number = 2, Type = typeof(IgnoreMessage) },
  737. new MessageMetadata { Name = "SSH_MSG_CHANNEL_WINDOW_ADJUST", Number = 93, Type = typeof(ChannelWindowAdjustMessage) },
  738. new MessageMetadata { Name = "SSH_MSG_CHANNEL_EOF", Number = 96, Type = typeof(ChannelEofMessage) },
  739. new MessageMetadata { Name = "SSH_MSG_CHANNEL_CLOSE", Number = 97, Type = typeof(ChannelCloseMessage) },
  740. new MessageMetadata { Name = "SSH_MSG_SERVICE_ACCEPT", Number = 6, Type = typeof(ServiceAcceptMessage) },
  741. new MessageMetadata { Name = "SSH_MSG_KEXDH_REPLY", Number = 31, Type = typeof(KeyExchangeDhReplyMessage) },
  742. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_INIT", Number = 32, Type = typeof(KeyExchangeDhGroupExchangeInit) },
  743. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_REPLY", Number = 33, Type = typeof(KeyExchangeDhGroupExchangeReply) }
  744. };
  745. }
  746. /// <summary>
  747. /// Receives the message from the server.
  748. /// </summary>
  749. /// <returns>Incoming SSH message.</returns>
  750. /// <exception cref="SshConnectionException"></exception>
  751. private Message ReceiveMessage()
  752. {
  753. // No lock needed since all messages read by only one thread
  754. var blockSize = this._serverCipher == null ? (byte)8 : Math.Max((byte)8, this._serverCipher.MinimumSize);
  755. // Read packet length first
  756. var firstBlock = this.Read(blockSize);
  757. if (this._serverCipher != null)
  758. {
  759. firstBlock = this._serverCipher.Decrypt(firstBlock);
  760. }
  761. var packetLength = (uint)(firstBlock[0] << 24 | firstBlock[1] << 16 | firstBlock[2] << 8 | firstBlock[3]);
  762. // Test packet minimum and maximum boundaries
  763. if (packetLength < Math.Max((byte)16, blockSize) - 4 || packetLength > MaximumSshPacketSize - 4)
  764. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length {0}", packetLength), DisconnectReason.ProtocolError);
  765. // Read rest of the packet data
  766. var bytesToRead = (int)(packetLength - (blockSize - 4));
  767. var data = new byte[bytesToRead + blockSize];
  768. firstBlock.CopyTo(data, 0);
  769. byte[] serverHash = null;
  770. if (this._serverMac != null)
  771. {
  772. serverHash = new byte[this._serverMac.HashSize / 8];
  773. bytesToRead += serverHash.Length;
  774. }
  775. if (bytesToRead > 0)
  776. {
  777. var nextBlocks = this.Read(bytesToRead);
  778. if (serverHash != null)
  779. {
  780. Buffer.BlockCopy(nextBlocks, nextBlocks.Length - serverHash.Length, serverHash, 0, serverHash.Length);
  781. nextBlocks = nextBlocks.Take(nextBlocks.Length - serverHash.Length).ToArray();
  782. }
  783. if (nextBlocks.Length > 0)
  784. {
  785. if (this._serverCipher != null)
  786. {
  787. nextBlocks = this._serverCipher.Decrypt(nextBlocks);
  788. }
  789. nextBlocks.CopyTo(data, blockSize);
  790. }
  791. }
  792. var paddingLength = data[4];
  793. var messagePayload = new byte[packetLength - paddingLength - 1];
  794. Buffer.BlockCopy(data, 5, messagePayload, 0, messagePayload.Length);
  795. if (this._serverDecompression != null)
  796. {
  797. messagePayload = this._serverDecompression.Decompress(messagePayload);
  798. }
  799. // Validate message against MAC
  800. if (this._serverMac != null)
  801. {
  802. var clientHashData = new byte[4 + data.Length];
  803. var lengthBytes = this._inboundPacketSequence.GetBytes();
  804. lengthBytes.CopyTo(clientHashData, 0);
  805. data.CopyTo(clientHashData, 4);
  806. // Calculate packet hash
  807. var clientHash = this._serverMac.ComputeHash(clientHashData);
  808. if (!serverHash.SequenceEqual(clientHash))
  809. {
  810. throw new SshConnectionException("MAC error", DisconnectReason.MacError);
  811. }
  812. }
  813. this._inboundPacketSequence++;
  814. return this.LoadMessage(messagePayload);
  815. }
  816. private void SendDisconnect(DisconnectReason reasonCode, string message)
  817. {
  818. // only send a disconnect message if it wasn't already sent, and we're
  819. // still connected
  820. if (this._isDisconnectMessageSent || !IsConnected)
  821. return;
  822. var disconnectMessage = new DisconnectMessage(reasonCode, message);
  823. this.SendMessage(disconnectMessage);
  824. this._isDisconnectMessageSent = true;
  825. }
  826. partial void HandleMessageCore(Message message);
  827. /// <summary>
  828. /// Handles the message.
  829. /// </summary>
  830. /// <typeparam name="T"></typeparam>
  831. /// <param name="message">The message.</param>
  832. private void HandleMessage<T>(T message) where T : Message
  833. {
  834. this.OnMessageReceived(message);
  835. }
  836. #region Handle transport messages
  837. private void HandleMessage(DisconnectMessage message)
  838. {
  839. this.OnDisconnectReceived(message);
  840. // disconnect from the socket, and dispose it
  841. SocketDisconnectAndDispose();
  842. }
  843. private void HandleMessage(IgnoreMessage message)
  844. {
  845. this.OnIgnoreReceived(message);
  846. }
  847. private void HandleMessage(UnimplementedMessage message)
  848. {
  849. this.OnUnimplementedReceived(message);
  850. }
  851. private void HandleMessage(DebugMessage message)
  852. {
  853. this.OnDebugReceived(message);
  854. }
  855. private void HandleMessage(ServiceRequestMessage message)
  856. {
  857. this.OnServiceRequestReceived(message);
  858. }
  859. private void HandleMessage(ServiceAcceptMessage message)
  860. {
  861. // TODO: Refactor to avoid this method here
  862. this.OnServiceAcceptReceived(message);
  863. this._serviceAccepted.Set();
  864. }
  865. private void HandleMessage(KeyExchangeInitMessage message)
  866. {
  867. this.OnKeyExchangeInitReceived(message);
  868. }
  869. private void HandleMessage(NewKeysMessage message)
  870. {
  871. this.OnNewKeysReceived(message);
  872. }
  873. #endregion
  874. #region Handle User Authentication messages
  875. private void HandleMessage(RequestMessage message)
  876. {
  877. this.OnUserAuthenticationRequestReceived(message);
  878. }
  879. private void HandleMessage(FailureMessage message)
  880. {
  881. this.OnUserAuthenticationFailureReceived(message);
  882. }
  883. private void HandleMessage(SuccessMessage message)
  884. {
  885. this.OnUserAuthenticationSuccessReceived(message);
  886. }
  887. private void HandleMessage(BannerMessage message)
  888. {
  889. this.OnUserAuthenticationBannerReceived(message);
  890. }
  891. #endregion
  892. #region Handle connection messages
  893. private void HandleMessage(GlobalRequestMessage message)
  894. {
  895. this.OnGlobalRequestReceived(message);
  896. }
  897. private void HandleMessage(RequestSuccessMessage message)
  898. {
  899. this.OnRequestSuccessReceived(message);
  900. }
  901. private void HandleMessage(RequestFailureMessage message)
  902. {
  903. this.OnRequestFailureReceived(message);
  904. }
  905. private void HandleMessage(ChannelOpenMessage message)
  906. {
  907. this.OnChannelOpenReceived(message);
  908. }
  909. private void HandleMessage(ChannelOpenConfirmationMessage message)
  910. {
  911. this.OnChannelOpenConfirmationReceived(message);
  912. }
  913. private void HandleMessage(ChannelOpenFailureMessage message)
  914. {
  915. this.OnChannelOpenFailureReceived(message);
  916. }
  917. private void HandleMessage(ChannelWindowAdjustMessage message)
  918. {
  919. this.OnChannelWindowAdjustReceived(message);
  920. }
  921. private void HandleMessage(ChannelDataMessage message)
  922. {
  923. this.OnChannelDataReceived(message);
  924. }
  925. private void HandleMessage(ChannelExtendedDataMessage message)
  926. {
  927. this.OnChannelExtendedDataReceived(message);
  928. }
  929. private void HandleMessage(ChannelEofMessage message)
  930. {
  931. this.OnChannelEofReceived(message);
  932. }
  933. private void HandleMessage(ChannelCloseMessage message)
  934. {
  935. this.OnChannelCloseReceived(message);
  936. }
  937. private void HandleMessage(ChannelRequestMessage message)
  938. {
  939. this.OnChannelRequestReceived(message);
  940. }
  941. private void HandleMessage(ChannelSuccessMessage message)
  942. {
  943. this.OnChannelSuccessReceived(message);
  944. }
  945. private void HandleMessage(ChannelFailureMessage message)
  946. {
  947. this.OnChannelFailureReceived(message);
  948. }
  949. #endregion
  950. #region Handle received message events
  951. /// <summary>
  952. /// Called when <see cref="DisconnectMessage"/> received.
  953. /// </summary>
  954. /// <param name="message"><see cref="DisconnectMessage"/> message.</param>
  955. protected virtual void OnDisconnectReceived(DisconnectMessage message)
  956. {
  957. this.Log(string.Format("Disconnect received: {0} {1}", message.ReasonCode, message.Description));
  958. var disconnectReceived = DisconnectReceived;
  959. if (disconnectReceived != null)
  960. disconnectReceived(this, new MessageEventArgs<DisconnectMessage>(message));
  961. var disconnected = Disconnected;
  962. if (disconnected != null)
  963. disconnected(this, new EventArgs());
  964. }
  965. /// <summary>
  966. /// Called when <see cref="IgnoreMessage"/> received.
  967. /// </summary>
  968. /// <param name="message"><see cref="IgnoreMessage"/> message.</param>
  969. protected virtual void OnIgnoreReceived(IgnoreMessage message)
  970. {
  971. var handlers = IgnoreReceived;
  972. if (handlers != null)
  973. handlers(this, new MessageEventArgs<IgnoreMessage>(message));
  974. }
  975. /// <summary>
  976. /// Called when <see cref="UnimplementedMessage"/> message received.
  977. /// </summary>
  978. /// <param name="message"><see cref="UnimplementedMessage"/> message.</param>
  979. protected virtual void OnUnimplementedReceived(UnimplementedMessage message)
  980. {
  981. var handlers = UnimplementedReceived;
  982. if (handlers != null)
  983. handlers(this, new MessageEventArgs<UnimplementedMessage>(message));
  984. }
  985. /// <summary>
  986. /// Called when <see cref="DebugMessage"/> message received.
  987. /// </summary>
  988. /// <param name="message"><see cref="DebugMessage"/> message.</param>
  989. protected virtual void OnDebugReceived(DebugMessage message)
  990. {
  991. var handlers = DebugReceived;
  992. if (handlers != null)
  993. handlers(this, new MessageEventArgs<DebugMessage>(message));
  994. }
  995. /// <summary>
  996. /// Called when <see cref="ServiceRequestMessage"/> message received.
  997. /// </summary>
  998. /// <param name="message"><see cref="ServiceRequestMessage"/> message.</param>
  999. protected virtual void OnServiceRequestReceived(ServiceRequestMessage message)
  1000. {
  1001. var handlers = ServiceRequestReceived;
  1002. if (handlers != null)
  1003. handlers(this, new MessageEventArgs<ServiceRequestMessage>(message));
  1004. }
  1005. /// <summary>
  1006. /// Called when <see cref="ServiceAcceptMessage"/> message received.
  1007. /// </summary>
  1008. /// <param name="message"><see cref="ServiceAcceptMessage"/> message.</param>
  1009. protected virtual void OnServiceAcceptReceived(ServiceAcceptMessage message)
  1010. {
  1011. var handlers = ServiceAcceptReceived;
  1012. if (handlers != null)
  1013. handlers(this, new MessageEventArgs<ServiceAcceptMessage>(message));
  1014. }
  1015. /// <summary>
  1016. /// Called when <see cref="KeyExchangeInitMessage"/> message received.
  1017. /// </summary>
  1018. /// <param name="message"><see cref="KeyExchangeInitMessage"/> message.</param>
  1019. protected virtual void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
  1020. {
  1021. this._keyExchangeInProgress = true;
  1022. this._keyExchangeCompletedWaitHandle.Reset();
  1023. // Disable all registered messages except key exchange related
  1024. foreach (var messageMetadata in this._messagesMetadata)
  1025. {
  1026. if (messageMetadata.Activated && messageMetadata.Number > 2 && (messageMetadata.Number < 20 || messageMetadata.Number > 30))
  1027. messageMetadata.Enabled = false;
  1028. }
  1029. var keyExchangeAlgorithmName = (from c in this.ConnectionInfo.KeyExchangeAlgorithms.Keys
  1030. from s in message.KeyExchangeAlgorithms
  1031. where s == c
  1032. select c).FirstOrDefault();
  1033. if (keyExchangeAlgorithmName == null)
  1034. {
  1035. throw new SshConnectionException("Failed to negotiate key exchange algorithm.", DisconnectReason.KeyExchangeFailed);
  1036. }
  1037. // Create instance of key exchange algorithm that will be used
  1038. this._keyExchange = this.ConnectionInfo.KeyExchangeAlgorithms[keyExchangeAlgorithmName].CreateInstance<KeyExchange>();
  1039. this.ConnectionInfo.CurrentKeyExchangeAlgorithm = keyExchangeAlgorithmName;
  1040. this._keyExchange.HostKeyReceived += KeyExchange_HostKeyReceived;
  1041. // Start the algorithm implementation
  1042. this._keyExchange.Start(this, message);
  1043. var keyExchangeInitReceived = KeyExchangeInitReceived;
  1044. if (keyExchangeInitReceived != null)
  1045. keyExchangeInitReceived(this, new MessageEventArgs<KeyExchangeInitMessage>(message));
  1046. }
  1047. /// <summary>
  1048. /// Called when <see cref="NewKeysMessage"/> message received.
  1049. /// </summary>
  1050. /// <param name="message"><see cref="NewKeysMessage"/> message.</param>
  1051. protected virtual void OnNewKeysReceived(NewKeysMessage message)
  1052. {
  1053. // Update sessionId
  1054. if (this.SessionId == null)
  1055. {
  1056. this.SessionId = this._keyExchange.ExchangeHash;
  1057. }
  1058. // Dispose of old ciphers and hash algorithms
  1059. if (this._serverMac != null)
  1060. {
  1061. this._serverMac.Clear();
  1062. this._serverMac = null;
  1063. }
  1064. if (this._clientMac != null)
  1065. {
  1066. this._clientMac.Clear();
  1067. this._clientMac = null;
  1068. }
  1069. // Update negotiated algorithms
  1070. this._serverCipher = this._keyExchange.CreateServerCipher();
  1071. this._clientCipher = this._keyExchange.CreateClientCipher();
  1072. this._serverMac = this._keyExchange.CreateServerHash();
  1073. this._clientMac = this._keyExchange.CreateClientHash();
  1074. this._clientCompression = this._keyExchange.CreateCompressor();
  1075. this._serverDecompression = this._keyExchange.CreateDecompressor();
  1076. // Dispose of old KeyExchange object as it is no longer needed.
  1077. if (this._keyExchange != null)
  1078. {
  1079. this._keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1080. this._keyExchange.Dispose();
  1081. this._keyExchange = null;
  1082. }
  1083. // Enable all active registered messages
  1084. foreach (var messageMetadata in this._messagesMetadata)
  1085. {
  1086. if (messageMetadata.Activated)
  1087. messageMetadata.Enabled = true;
  1088. }
  1089. var newKeysReceived = NewKeysReceived;
  1090. if (newKeysReceived != null)
  1091. newKeysReceived(this, new MessageEventArgs<NewKeysMessage>(message));
  1092. // Signal that key exchange completed
  1093. this._keyExchangeCompletedWaitHandle.Set();
  1094. this._keyExchangeInProgress = false;
  1095. }
  1096. /// <summary>
  1097. /// Called when client is disconnecting from the server.
  1098. /// </summary>
  1099. internal void OnDisconnecting()
  1100. {
  1101. _isDisconnecting = true;
  1102. }
  1103. /// <summary>
  1104. /// Called when <see cref="RequestMessage"/> message received.
  1105. /// </summary>
  1106. /// <param name="message"><see cref="RequestMessage"/> message.</param>
  1107. protected virtual void OnUserAuthenticationRequestReceived(RequestMessage message)
  1108. {
  1109. var handlers = UserAuthenticationRequestReceived;
  1110. if (handlers != null)
  1111. handlers(this, new MessageEventArgs<RequestMessage>(message));
  1112. }
  1113. /// <summary>
  1114. /// Called when <see cref="FailureMessage"/> message received.
  1115. /// </summary>
  1116. /// <param name="message"><see cref="FailureMessage"/> message.</param>
  1117. protected virtual void OnUserAuthenticationFailureReceived(FailureMessage message)
  1118. {
  1119. var handlers = UserAuthenticationFailureReceived;
  1120. if (handlers != null)
  1121. handlers(this, new MessageEventArgs<FailureMessage>(message));
  1122. }
  1123. /// <summary>
  1124. /// Called when <see cref="SuccessMessage"/> message received.
  1125. /// </summary>
  1126. /// <param name="message"><see cref="SuccessMessage"/> message.</param>
  1127. protected virtual void OnUserAuthenticationSuccessReceived(SuccessMessage message)
  1128. {
  1129. var handlers = UserAuthenticationSuccessReceived;
  1130. if (handlers != null)
  1131. handlers(this, new MessageEventArgs<SuccessMessage>(message));
  1132. }
  1133. /// <summary>
  1134. /// Called when <see cref="BannerMessage"/> message received.
  1135. /// </summary>
  1136. /// <param name="message"><see cref="BannerMessage"/> message.</param>
  1137. protected virtual void OnUserAuthenticationBannerReceived(BannerMessage message)
  1138. {
  1139. var handlers = UserAuthenticationBannerReceived;
  1140. if (handlers != null)
  1141. handlers(this, new MessageEventArgs<BannerMessage>(message));
  1142. }
  1143. /// <summary>
  1144. /// Called when <see cref="GlobalRequestMessage"/> message received.
  1145. /// </summary>
  1146. /// <param name="message"><see cref="GlobalRequestMessage"/> message.</param>
  1147. protected virtual void OnGlobalRequestReceived(GlobalRequestMessage message)
  1148. {
  1149. var handlers = GlobalRequestReceived;
  1150. if (handlers != null)
  1151. handlers(this, new MessageEventArgs<GlobalRequestMessage>(message));
  1152. }
  1153. /// <summary>
  1154. /// Called when <see cref="RequestSuccessMessage"/> message received.
  1155. /// </summary>
  1156. /// <param name="message"><see cref="RequestSuccessMessage"/> message.</param>
  1157. protected virtual void OnRequestSuccessReceived(RequestSuccessMessage message)
  1158. {
  1159. var handlers = RequestSuccessReceived;
  1160. if (handlers != null)
  1161. handlers(this, new MessageEventArgs<RequestSuccessMessage>(message));
  1162. }
  1163. /// <summary>
  1164. /// Called when <see cref="RequestFailureMessage"/> message received.
  1165. /// </summary>
  1166. /// <param name="message"><see cref="RequestFailureMessage"/> message.</param>
  1167. protected virtual void OnRequestFailureReceived(RequestFailureMessage message)
  1168. {
  1169. var handlers = RequestFailureReceived;
  1170. if (handlers != null)
  1171. handlers(this, new MessageEventArgs<RequestFailureMessage>(message));
  1172. }
  1173. /// <summary>
  1174. /// Called when <see cref="ChannelOpenMessage"/> message received.
  1175. /// </summary>
  1176. /// <param name="message"><see cref="ChannelOpenMessage"/> message.</param>
  1177. protected virtual void OnChannelOpenReceived(ChannelOpenMessage message)
  1178. {
  1179. var handlers = ChannelOpenReceived;
  1180. if (handlers != null)
  1181. handlers(this, new MessageEventArgs<ChannelOpenMessage>(message));
  1182. }
  1183. /// <summary>
  1184. /// Called when <see cref="ChannelOpenConfirmationMessage"/> message received.
  1185. /// </summary>
  1186. /// <param name="message"><see cref="ChannelOpenConfirmationMessage"/> message.</param>
  1187. protected virtual void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage message)
  1188. {
  1189. var handlers = ChannelOpenConfirmationReceived;
  1190. if (handlers != null)
  1191. handlers(this, new MessageEventArgs<ChannelOpenConfirmationMessage>(message));
  1192. }
  1193. /// <summary>
  1194. /// Called when <see cref="ChannelOpenFailureMessage"/> message received.
  1195. /// </summary>
  1196. /// <param name="message"><see cref="ChannelOpenFailureMessage"/> message.</param>
  1197. protected virtual void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
  1198. {
  1199. var handlers = ChannelOpenFailureReceived;
  1200. if (handlers != null)
  1201. handlers(this, new MessageEventArgs<ChannelOpenFailureMessage>(message));
  1202. }
  1203. /// <summary>
  1204. /// Called when <see cref="ChannelWindowAdjustMessage"/> message received.
  1205. /// </summary>
  1206. /// <param name="message"><see cref="ChannelWindowAdjustMessage"/> message.</param>
  1207. protected virtual void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
  1208. {
  1209. var handlers = ChannelWindowAdjustReceived;
  1210. if (handlers != null)
  1211. handlers(this, new MessageEventArgs<ChannelWindowAdjustMessage>(message));
  1212. }
  1213. /// <summary>
  1214. /// Called when <see cref="ChannelDataMessage"/> message received.
  1215. /// </summary>
  1216. /// <param name="message"><see cref="ChannelDataMessage"/> message.</param>
  1217. protected virtual void OnChannelDataReceived(ChannelDataMessage message)
  1218. {
  1219. var handlers = ChannelDataReceived;
  1220. if (handlers != null)
  1221. handlers(this, new MessageEventArgs<ChannelDataMessage>(message));
  1222. }
  1223. /// <summary>
  1224. /// Called when <see cref="ChannelExtendedDataMessage"/> message received.
  1225. /// </summary>
  1226. /// <param name="message"><see cref="ChannelExtendedDataMessage"/> message.</param>
  1227. protected virtual void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
  1228. {
  1229. var handlers = ChannelExtendedDataReceived;
  1230. if (handlers != null)
  1231. handlers(this, new MessageEventArgs<ChannelExtendedDataMessage>(message));
  1232. }
  1233. /// <summary>
  1234. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1235. /// </summary>
  1236. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1237. protected virtual void OnChannelEofReceived(ChannelEofMessage message)
  1238. {
  1239. var handlers = ChannelEofReceived;
  1240. if (handlers != null)
  1241. handlers(this, new MessageEventArgs<ChannelEofMessage>(message));
  1242. }
  1243. /// <summary>
  1244. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1245. /// </summary>
  1246. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1247. protected virtual void OnChannelCloseReceived(ChannelCloseMessage message)
  1248. {
  1249. var handlers = ChannelCloseReceived;
  1250. if (handlers != null)
  1251. handlers(this, new MessageEventArgs<ChannelCloseMessage>(message));
  1252. }
  1253. /// <summary>
  1254. /// Called when <see cref="ChannelRequestMessage"/> message received.
  1255. /// </summary>
  1256. /// <param name="message"><see cref="ChannelRequestMessage"/> message.</param>
  1257. protected virtual void OnChannelRequestReceived(ChannelRequestMessage message)
  1258. {
  1259. var handlers = ChannelRequestReceived;
  1260. if (handlers != null)
  1261. handlers(this, new MessageEventArgs<ChannelRequestMessage>(message));
  1262. }
  1263. /// <summary>
  1264. /// Called when <see cref="ChannelSuccessMessage"/> message received.
  1265. /// </summary>
  1266. /// <param name="message"><see cref="ChannelSuccessMessage"/> message.</param>
  1267. protected virtual void OnChannelSuccessReceived(ChannelSuccessMessage message)
  1268. {
  1269. var handlers = ChannelSuccessReceived;
  1270. if (handlers != null)
  1271. handlers(this, new MessageEventArgs<ChannelSuccessMessage>(message));
  1272. }
  1273. /// <summary>
  1274. /// Called when <see cref="ChannelFailureMessage"/> message received.
  1275. /// </summary>
  1276. /// <param name="message"><see cref="ChannelFailureMessage"/> message.</param>
  1277. protected virtual void OnChannelFailureReceived(ChannelFailureMessage message)
  1278. {
  1279. var handlers = ChannelFailureReceived;
  1280. if (handlers != null)
  1281. handlers(this, new MessageEventArgs<ChannelFailureMessage>(message));
  1282. }
  1283. /// <summary>
  1284. /// Called when <see cref="Message"/> message received.
  1285. /// </summary>
  1286. /// <param name="message"><see cref="Message"/> message.</param>
  1287. protected virtual void OnMessageReceived(Message message)
  1288. {
  1289. var handlers = MessageReceived;
  1290. if (handlers != null)
  1291. handlers(this, new MessageEventArgs<Message>(message));
  1292. }
  1293. #endregion
  1294. private void KeyExchange_HostKeyReceived(object sender, HostKeyEventArgs e)
  1295. {
  1296. var handlers = HostKeyReceived;
  1297. if (handlers != null)
  1298. handlers(this, e);
  1299. }
  1300. /// <summary>
  1301. /// Reads the specified length of bytes from the server.
  1302. /// </summary>
  1303. /// <param name="length">The length.</param>
  1304. /// <returns>
  1305. /// The bytes read from the server.
  1306. /// </returns>
  1307. private byte[] Read(int length)
  1308. {
  1309. var buffer = new byte[length];
  1310. this.SocketRead(length, ref buffer);
  1311. return buffer;
  1312. }
  1313. #region Message loading functions
  1314. /// <summary>
  1315. /// Registers SSH Message with the session.
  1316. /// </summary>
  1317. /// <param name="messageName">Name of the message.</param>
  1318. public void RegisterMessage(string messageName)
  1319. {
  1320. this.InternalRegisterMessage(messageName);
  1321. }
  1322. /// <summary>
  1323. /// Removes SSH message from the session
  1324. /// </summary>
  1325. /// <param name="messageName">Name of the message.</param>
  1326. public void UnRegisterMessage(string messageName)
  1327. {
  1328. this.InternalUnRegisterMessage(messageName);
  1329. }
  1330. /// <summary>
  1331. /// Loads the message.
  1332. /// </summary>
  1333. /// <param name="data">Message data.</param>
  1334. /// <returns>New message</returns>
  1335. private Message LoadMessage(byte[] data)
  1336. {
  1337. var messageType = data[0];
  1338. var messageMetadata = (from m in this._messagesMetadata where m.Number == messageType && m.Enabled && m.Activated select m).SingleOrDefault();
  1339. if (messageMetadata == null)
  1340. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Message type {0} is not valid.", messageType));
  1341. var message = messageMetadata.Type.CreateInstance<Message>();
  1342. message.Load(data);
  1343. this.Log(string.Format("ReceiveMessage from server: '{0}': '{1}'.", message.GetType().Name, message));
  1344. return message;
  1345. }
  1346. partial void InternalRegisterMessage(string messageName);
  1347. partial void InternalUnRegisterMessage(string messageName);
  1348. #endregion
  1349. partial void ExecuteThread(Action action);
  1350. /// <summary>
  1351. /// Gets a value indicating whether the socket is connected.
  1352. /// </summary>
  1353. /// <value>
  1354. /// <c>true</c> if the socket is connected; otherwise, <c>false</c>.
  1355. /// </value>
  1356. partial void IsSocketConnected(ref bool isConnected);
  1357. partial void SocketConnect(string host, int port);
  1358. partial void SocketDisconnect();
  1359. partial void SocketRead(int length, ref byte[] buffer);
  1360. partial void SocketReadLine(ref string response);
  1361. partial void Log(string text);
  1362. /// <summary>
  1363. /// Writes the specified data to the server.
  1364. /// </summary>
  1365. /// <param name="data">The data.</param>
  1366. partial void SocketWrite(byte[] data);
  1367. /// <summary>
  1368. /// Disconnects and disposes the socket.
  1369. /// </summary>
  1370. private void SocketDisconnectAndDispose()
  1371. {
  1372. if (_socket != null)
  1373. {
  1374. lock (_socketLock)
  1375. {
  1376. if (_socket != null)
  1377. {
  1378. SocketDisconnect();
  1379. _socket.Dispose();
  1380. _socket = null;
  1381. }
  1382. }
  1383. }
  1384. }
  1385. /// <summary>
  1386. /// Listens for incoming message from the server and handles them. This method run as a task on separate thread.
  1387. /// </summary>
  1388. private void MessageListener()
  1389. {
  1390. try
  1391. {
  1392. while (this._socket != null && this._socket.Connected)
  1393. {
  1394. var message = this.ReceiveMessage();
  1395. this.HandleMessageCore(message);
  1396. }
  1397. }
  1398. catch (Exception exp)
  1399. {
  1400. this.RaiseError(exp);
  1401. }
  1402. }
  1403. private byte SocketReadByte()
  1404. {
  1405. var buffer = new byte[1];
  1406. this.SocketRead(1, ref buffer);
  1407. return buffer[0];
  1408. }
  1409. private void SocketWriteByte(byte data)
  1410. {
  1411. this.SocketWrite(new[] {data});
  1412. }
  1413. private void ConnectSocks4()
  1414. {
  1415. // Send socks version number
  1416. this.SocketWriteByte(0x04);
  1417. // Send command code
  1418. this.SocketWriteByte(0x01);
  1419. // Send port
  1420. this.SocketWriteByte((byte)(this.ConnectionInfo.Port / 0xFF));
  1421. this.SocketWriteByte((byte)(this.ConnectionInfo.Port % 0xFF));
  1422. // Send IP
  1423. IPAddress ipAddress = this.ConnectionInfo.Host.GetIPAddress();
  1424. this.SocketWrite(ipAddress.GetAddressBytes());
  1425. // Send username
  1426. var username = new Common.ASCIIEncoding().GetBytes(this.ConnectionInfo.ProxyUsername);
  1427. this.SocketWrite(username);
  1428. this.SocketWriteByte(0x00);
  1429. // Read 0
  1430. if (this.SocketReadByte() != 0)
  1431. {
  1432. throw new ProxyException("SOCKS4: Null is expected.");
  1433. }
  1434. // Read response code
  1435. var code = this.SocketReadByte();
  1436. switch (code)
  1437. {
  1438. case 0x5a:
  1439. break;
  1440. case 0x5b:
  1441. throw new ProxyException("SOCKS4: Connection rejected.");
  1442. case 0x5c:
  1443. throw new ProxyException("SOCKS4: Client is not running identd or not reachable from the server.");
  1444. case 0x5d:
  1445. throw new ProxyException("SOCKS4: Client's identd could not confirm the user ID string in the request.");
  1446. default:
  1447. throw new ProxyException("SOCKS4: Not valid response.");
  1448. }
  1449. var dummyBuffer = new byte[4];
  1450. // Read 2 bytes to be ignored
  1451. this.SocketRead(2, ref dummyBuffer);
  1452. // Read 4 bytes to be ignored
  1453. this.SocketRead(4, ref dummyBuffer);
  1454. }
  1455. private void ConnectSocks5()
  1456. {
  1457. // Send socks version number
  1458. this.SocketWriteByte(0x05);
  1459. // Send number of supported authentication methods
  1460. this.SocketWriteByte(0x02);
  1461. // Send supported authentication methods
  1462. this.SocketWriteByte(0x00); // No authentication
  1463. this.SocketWriteByte(0x02); // Username/Password
  1464. var socksVersion = this.SocketReadByte();
  1465. if (socksVersion != 0x05)
  1466. throw new ProxyException(string.Format("SOCKS Version '{0}' is not supported.", socksVersion));
  1467. var authenticationMethod = this.SocketReadByte();
  1468. switch (authenticationMethod)
  1469. {
  1470. case 0x00:
  1471. break;
  1472. case 0x02:
  1473. // Send version
  1474. this.SocketWriteByte(0x01);
  1475. var encoding = new Common.ASCIIEncoding();
  1476. var username = encoding.GetBytes(this.ConnectionInfo.ProxyUsername);
  1477. if (username.Length > byte.MaxValue)
  1478. throw new ProxyException("Proxy username is too long.");
  1479. // Send username length
  1480. this.SocketWriteByte((byte)username.Length);
  1481. // Send username
  1482. this.SocketWrite(username);
  1483. var password = encoding.GetBytes(this.ConnectionInfo.ProxyPassword);
  1484. if (password.Length > byte.MaxValue)
  1485. throw new ProxyException("Proxy password is too long.");
  1486. // Send username length
  1487. this.SocketWriteByte((byte)password.Length);
  1488. // Send username
  1489. this.SocketWrite(password);
  1490. var serverVersion = this.SocketReadByte();
  1491. if (serverVersion != 1)
  1492. throw new ProxyException("SOCKS5: Server authentication version is not valid.");
  1493. var statusCode = this.SocketReadByte();
  1494. if (statusCode != 0)
  1495. throw new ProxyException("SOCKS5: Username/Password authentication failed.");
  1496. break;
  1497. case 0xFF:
  1498. throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
  1499. }
  1500. // Send socks version number
  1501. this.SocketWriteByte(0x05);
  1502. // Send command code
  1503. this.SocketWriteByte(0x01); // establish a TCP/IP stream connection
  1504. // Send reserved, must be 0x00
  1505. this.SocketWriteByte(0x00);
  1506. IPAddress ip = this.ConnectionInfo.Host.GetIPAddress();
  1507. // Send address type and address
  1508. if (ip.AddressFamily == AddressFamily.InterNetwork)
  1509. {
  1510. this.SocketWriteByte(0x01);
  1511. var address = ip.GetAddressBytes();
  1512. this.SocketWrite(address);
  1513. }
  1514. else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
  1515. {
  1516. this.SocketWriteByte(0x04);
  1517. var address = ip.GetAddressBytes();
  1518. this.SocketWrite(address);
  1519. }
  1520. else
  1521. {
  1522. throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
  1523. }
  1524. // Send port
  1525. this.SocketWriteByte((byte)(this.ConnectionInfo.Port / 0xFF));
  1526. this.SocketWriteByte((byte)(this.ConnectionInfo.Port % 0xFF));
  1527. // Read Server SOCKS5 version
  1528. if (this.SocketReadByte() != 5)
  1529. {
  1530. throw new ProxyException("SOCKS5: Version 5 is expected.");
  1531. }
  1532. // Read response code
  1533. var status = this.SocketReadByte();
  1534. switch (status)
  1535. {
  1536. case 0x00:
  1537. break;
  1538. case 0x01:
  1539. throw new ProxyException("SOCKS5: General failure.");
  1540. case 0x02:
  1541. throw new ProxyException("SOCKS5: Connection not allowed by ruleset.");
  1542. case 0x03:
  1543. throw new ProxyException("SOCKS5: Network unreachable.");
  1544. case 0x04:
  1545. throw new ProxyException("SOCKS5: Host unreachable.");
  1546. case 0x05:
  1547. throw new ProxyException("SOCKS5: Connection refused by destination host.");
  1548. case 0x06:
  1549. throw new ProxyException("SOCKS5: TTL expired.");
  1550. case 0x07:
  1551. throw new ProxyException("SOCKS5: Command not supported or protocol error.");
  1552. case 0x08:
  1553. throw new ProxyException("SOCKS5: Address type not supported.");
  1554. default:
  1555. throw new ProxyException("SOCKS4: Not valid response.");
  1556. }
  1557. // Read 0
  1558. if (this.SocketReadByte() != 0)
  1559. {
  1560. throw new ProxyException("SOCKS5: 0 byte is expected.");
  1561. }
  1562. var addressType = this.SocketReadByte();
  1563. var responseIp = new byte[16];
  1564. switch (addressType)
  1565. {
  1566. case 0x01:
  1567. this.SocketRead(4, ref responseIp);
  1568. break;
  1569. case 0x04:
  1570. this.SocketRead(16, ref responseIp);
  1571. break;
  1572. default:
  1573. throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
  1574. }
  1575. var port = new byte[2];
  1576. // Read 2 bytes to be ignored
  1577. this.SocketRead(2, ref port);
  1578. }
  1579. private void ConnectHttp()
  1580. {
  1581. var httpResponseRe = new Regex(@"HTTP/(?<version>\d[.]\d) (?<statusCode>\d{3}) (?<reasonPhrase>.+)$");
  1582. var httpHeaderRe = new Regex(@"(?<fieldName>[^\[\]()<>@,;:\""/?={} \t]+):(?<fieldValue>.+)?");
  1583. var encoding = new Common.ASCIIEncoding();
  1584. this.SocketWrite(encoding.GetBytes(string.Format("CONNECT {0}:{1} HTTP/1.0\r\n", this.ConnectionInfo.Host, this.ConnectionInfo.Port)));
  1585. // Sent proxy authorization is specified
  1586. if (!string.IsNullOrEmpty(this.ConnectionInfo.ProxyUsername))
  1587. {
  1588. var authorization = string.Format("Proxy-Authorization: Basic {0}\r\n",
  1589. Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", this.ConnectionInfo.ProxyUsername, this.ConnectionInfo.ProxyPassword)))
  1590. );
  1591. this.SocketWrite(encoding.GetBytes(authorization));
  1592. }
  1593. this.SocketWrite(encoding.GetBytes("\r\n"));
  1594. HttpStatusCode? statusCode = null;
  1595. var response = string.Empty;
  1596. var contentLength = 0;
  1597. while (true)
  1598. {
  1599. this.SocketReadLine(ref response);
  1600. if (statusCode == null)
  1601. {
  1602. var statusMatch = httpResponseRe.Match(response);
  1603. if (statusMatch.Success)
  1604. {
  1605. var httpStatusCode = statusMatch.Result("${statusCode}");
  1606. statusCode = (HttpStatusCode) int.Parse(httpStatusCode);
  1607. if (statusCode != HttpStatusCode.OK)
  1608. {
  1609. var reasonPhrase = statusMatch.Result("${reasonPhrase}");
  1610. throw new ProxyException(string.Format("HTTP: Status code {0}, \"{1}\"", httpStatusCode,
  1611. reasonPhrase));
  1612. }
  1613. continue;
  1614. }
  1615. }
  1616. // continue on parsing message headers coming from the server
  1617. var headerMatch = httpHeaderRe.Match(response);
  1618. if (headerMatch.Success)
  1619. {
  1620. var fieldName = headerMatch.Result("${fieldName}");
  1621. if (fieldName.Equals("Content-Length", StringComparison.InvariantCultureIgnoreCase))
  1622. {
  1623. contentLength = int.Parse(headerMatch.Result("${fieldValue}"));
  1624. }
  1625. continue;
  1626. }
  1627. // check if we've reached the CRLF which separates request line and headers from the message body
  1628. if (response.Length == 0)
  1629. {
  1630. // read response body if specified
  1631. if (contentLength > 0)
  1632. {
  1633. var contentBody = new byte[contentLength];
  1634. SocketRead(contentLength, ref contentBody);
  1635. }
  1636. break;
  1637. }
  1638. }
  1639. }
  1640. /// <summary>
  1641. /// Raises the <see cref="ErrorOccured"/> event.
  1642. /// </summary>
  1643. /// <param name="exp">The exp.</param>
  1644. private void RaiseError(Exception exp)
  1645. {
  1646. var connectionException = exp as SshConnectionException;
  1647. if (_isDisconnecting)
  1648. {
  1649. // a connection exception which is raised while isDisconnecting is normal and
  1650. // should be ignored
  1651. if (connectionException != null)
  1652. return;
  1653. // any timeout while disconnecting can be caused by loss of connectivity
  1654. // altogether and should be ignored
  1655. var socketException = exp as SocketException;
  1656. if (socketException != null && socketException.SocketErrorCode == SocketError.TimedOut)
  1657. return;
  1658. }
  1659. this._exception = exp;
  1660. this._exceptionWaitHandle.Set();
  1661. var errorOccured = ErrorOccured;
  1662. if (errorOccured != null)
  1663. errorOccured(this, new ExceptionEventArgs(exp));
  1664. if (connectionException != null && connectionException.DisconnectReason != DisconnectReason.ConnectionLost)
  1665. {
  1666. this.Disconnect(connectionException.DisconnectReason, exp.ToString());
  1667. }
  1668. }
  1669. /// <summary>
  1670. /// Resets connection-specific information to ensure state of a previous connection
  1671. /// does not affect new connections.
  1672. /// </summary>
  1673. private void Reset()
  1674. {
  1675. if (_exceptionWaitHandle != null)
  1676. _exceptionWaitHandle.Reset();
  1677. if (_keyExchangeCompletedWaitHandle != null)
  1678. _keyExchangeCompletedWaitHandle.Reset();
  1679. if (_messageListenerCompleted != null)
  1680. _messageListenerCompleted.Reset();
  1681. SessionId = null;
  1682. _isDisconnectMessageSent = false;
  1683. _isDisconnecting = false;
  1684. _isAuthenticated = false;
  1685. _exception = null;
  1686. _keyExchangeInProgress = false;
  1687. }
  1688. #region IDisposable Members
  1689. private bool _disposed;
  1690. /// <summary>
  1691. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  1692. /// </summary>
  1693. public void Dispose()
  1694. {
  1695. Dispose(true);
  1696. GC.SuppressFinalize(this);
  1697. }
  1698. /// <summary>
  1699. /// Releases unmanaged and - optionally - managed resources
  1700. /// </summary>
  1701. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1702. protected virtual void Dispose(bool disposing)
  1703. {
  1704. // Check to see if Dispose has already been called.
  1705. if (!this._disposed)
  1706. {
  1707. // If disposing equals true, dispose all managed
  1708. // and unmanaged ResourceMessages.
  1709. if (disposing)
  1710. {
  1711. Disconnect();
  1712. if (this._serviceAccepted != null)
  1713. {
  1714. this._serviceAccepted.Dispose();
  1715. this._serviceAccepted = null;
  1716. }
  1717. if (this._exceptionWaitHandle != null)
  1718. {
  1719. this._exceptionWaitHandle.Dispose();
  1720. this._exceptionWaitHandle = null;
  1721. }
  1722. if (this._keyExchangeCompletedWaitHandle != null)
  1723. {
  1724. this._keyExchangeCompletedWaitHandle.Dispose();
  1725. this._keyExchangeCompletedWaitHandle = null;
  1726. }
  1727. if (this._serverMac != null)
  1728. {
  1729. this._serverMac.Clear();
  1730. this._serverMac = null;
  1731. }
  1732. if (this._clientMac != null)
  1733. {
  1734. this._clientMac.Clear();
  1735. this._clientMac = null;
  1736. }
  1737. if (this._keyExchange != null)
  1738. {
  1739. this._keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1740. this._keyExchange.Dispose();
  1741. this._keyExchange = null;
  1742. }
  1743. if (_bytesReadFromSocket != null)
  1744. {
  1745. _bytesReadFromSocket.Dispose();
  1746. _bytesReadFromSocket = null;
  1747. }
  1748. }
  1749. // Note disposing has been done.
  1750. this._disposed = true;
  1751. }
  1752. }
  1753. /// <summary>
  1754. /// Releases unmanaged resources and performs other cleanup operations before the
  1755. /// <see cref="Session"/> is reclaimed by garbage collection.
  1756. /// </summary>
  1757. ~Session()
  1758. {
  1759. // Do not re-create Dispose clean-up code here.
  1760. // Calling Dispose(false) is optimal in terms of
  1761. // readability and maintainability.
  1762. Dispose(false);
  1763. }
  1764. #endregion
  1765. private class MessageMetadata
  1766. {
  1767. public string Name { get; set; }
  1768. public byte Number { get; set; }
  1769. public bool Enabled { get; set; }
  1770. public bool Activated { get; set; }
  1771. public Type Type { get; set; }
  1772. }
  1773. }
  1774. }