Session.cs 93 KB

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