Session.cs 90 KB

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