Session.cs 84 KB

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