Session.cs 78 KB

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