Session.cs 78 KB

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