Session.cs 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  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. using ASCIIEncoding = Renci.SshNet.Common.ASCIIEncoding;
  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. /// <summary>
  29. /// Specifies an infinite waiting period.
  30. /// </summary>
  31. /// <remarks>
  32. /// The value of this field is <c>-1</c> millisecond.
  33. /// </remarks>
  34. internal static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);
  35. /// <summary>
  36. /// Specifies an infinite waiting period.
  37. /// </summary>
  38. /// <remarks>
  39. /// The value of this field is <c>-1</c>.
  40. /// </remarks>
  41. internal static readonly int Infinite = -1;
  42. /// <summary>
  43. /// Specifies maximum packet size defined by the protocol.
  44. /// </summary>
  45. private const int MaximumSshPacketSize = LocalChannelDataPacketSize + 3000;
  46. /// <summary>
  47. /// Holds the initial local window size for the channels.
  48. /// </summary>
  49. /// <value>
  50. /// 2 MB.
  51. /// </value>
  52. private const int InitialLocalWindowSize = LocalChannelDataPacketSize * 32;
  53. /// <summary>
  54. /// Holds the maximum size of channel data packets that we receive.
  55. /// </summary>
  56. /// <value>
  57. /// 64 KB.
  58. /// </value>
  59. private const int LocalChannelDataPacketSize = 1024*64;
  60. #if !TUNING
  61. private static readonly RNGCryptoServiceProvider Randomizer = new RNGCryptoServiceProvider();
  62. #endif
  63. #if SILVERLIGHT
  64. private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$");
  65. #else
  66. private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$", RegexOptions.Compiled);
  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 IEnumerable<MessageMetadata> _messagesMetadata;
  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 UInt32 _outboundPacketSequence;
  95. /// <summary>
  96. /// Specifies incoming packet number
  97. /// </summary>
  98. private UInt32 _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. _messagesMetadata = GetMessagesMetadata();
  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 = string.Empty;
  466. SocketReadLine(ref serverVersion, ConnectionInfo.Timeout);
  467. if (serverVersion == null)
  468. throw new SshConnectionException("Server response does not contain SSH protocol identification.", DisconnectReason.ProtocolError);
  469. versionMatch = ServerVersionRe.Match(serverVersion);
  470. if (versionMatch.Success)
  471. {
  472. ServerVersion = serverVersion;
  473. break;
  474. }
  475. }
  476. // Set connection versions
  477. ConnectionInfo.ServerVersion = ServerVersion;
  478. ConnectionInfo.ClientVersion = ClientVersion;
  479. // Get server SSH version
  480. var version = versionMatch.Result("${protoversion}");
  481. var softwareName = versionMatch.Result("${softwareversion}");
  482. Log(string.Format("Server version '{0}' on '{1}'.", version, softwareName));
  483. if (!(version.Equals("2.0") || version.Equals("1.99")))
  484. {
  485. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", version), DisconnectReason.ProtocolVersionNotSupported);
  486. }
  487. SocketWrite(Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}\x0D\x0A", ClientVersion)));
  488. // Register Transport response messages
  489. RegisterMessage("SSH_MSG_DISCONNECT");
  490. RegisterMessage("SSH_MSG_IGNORE");
  491. RegisterMessage("SSH_MSG_UNIMPLEMENTED");
  492. RegisterMessage("SSH_MSG_DEBUG");
  493. RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
  494. RegisterMessage("SSH_MSG_KEXINIT");
  495. RegisterMessage("SSH_MSG_NEWKEYS");
  496. // Some server implementations might sent this message first, prior establishing encryption algorithm
  497. RegisterMessage("SSH_MSG_USERAUTH_BANNER");
  498. // mark the message listener threads as started
  499. _messageListenerCompleted.Reset();
  500. // Start incoming request listener
  501. ExecuteThread(MessageListener);
  502. // Wait for key exchange to be completed
  503. WaitOnHandle(_keyExchangeCompletedWaitHandle);
  504. // If sessionId is not set then its not connected
  505. if (SessionId == null)
  506. {
  507. Disconnect();
  508. return;
  509. }
  510. // Request user authorization service
  511. SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
  512. // Wait for service to be accepted
  513. WaitOnHandle(_serviceAccepted);
  514. if (string.IsNullOrEmpty(ConnectionInfo.Username))
  515. {
  516. throw new SshException("Username is not specified.");
  517. }
  518. ConnectionInfo.Authenticate(this, _serviceFactory);
  519. _isAuthenticated = true;
  520. // Register Connection messages
  521. RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
  522. RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
  523. RegisterMessage("SSH_MSG_REQUEST_FAILURE");
  524. RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
  525. RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
  526. RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
  527. RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
  528. RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
  529. RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
  530. RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
  531. RegisterMessage("SSH_MSG_CHANNEL_DATA");
  532. RegisterMessage("SSH_MSG_CHANNEL_EOF");
  533. RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
  534. Monitor.Pulse(this);
  535. }
  536. }
  537. finally
  538. {
  539. AuthenticationConnection.Release();
  540. }
  541. }
  542. /// <summary>
  543. /// Disconnects from the server.
  544. /// </summary>
  545. /// <remarks>
  546. /// This sends a <b>SSH_MSG_DISCONNECT</b> message to the server, waits for the
  547. /// server to close the socket on its end and subsequently closes the client socket.
  548. /// </remarks>
  549. public void Disconnect()
  550. {
  551. Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
  552. // at this point, we are sure that the listener thread will stop as we've
  553. // disconnected the socket, so lets wait until the message listener thread
  554. // has completed
  555. if (_messageListenerCompleted != null)
  556. {
  557. _messageListenerCompleted.WaitOne();
  558. }
  559. }
  560. private void Disconnect(DisconnectReason reason, string message)
  561. {
  562. _isDisconnecting = true;
  563. // send disconnect message to the server if the connection is still open
  564. // and the disconnect message has not yet been sent
  565. //
  566. // note that this should also cause the listener thread to be stopped as
  567. // the server should respond by closing the socket
  568. if (reason == DisconnectReason.ByApplication)
  569. {
  570. SendDisconnect(reason, message);
  571. }
  572. // disconnect socket, and dispose it
  573. SocketDisconnectAndDispose();
  574. }
  575. /// <summary>
  576. /// Waits for the specified handle or the exception handle for the receive thread
  577. /// to signal within the connection timeout.
  578. /// </summary>
  579. /// <param name="waitHandle">The wait handle.</param>
  580. /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
  581. /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
  582. /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
  583. /// <remarks>
  584. /// When neither handles are signaled in time and the session is not closing, then the
  585. /// session is disconnected.
  586. /// </remarks>
  587. void ISession.WaitOnHandle(WaitHandle waitHandle)
  588. {
  589. WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
  590. }
  591. /// <summary>
  592. /// Waits for the specified handle or the exception handle for the receive thread
  593. /// to signal within the connection timeout.
  594. /// </summary>
  595. /// <param name="waitHandle">The wait handle.</param>
  596. /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
  597. /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
  598. /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
  599. /// <remarks>
  600. /// When neither handles are signaled in time and the session is not closing, then the
  601. /// session is disconnected.
  602. /// </remarks>
  603. internal void WaitOnHandle(WaitHandle waitHandle)
  604. {
  605. WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
  606. }
  607. /// <summary>
  608. /// Waits for the specified handle or the exception handle for the receive thread
  609. /// to signal within the specified timeout.
  610. /// </summary>
  611. /// <param name="waitHandle">The wait handle.</param>
  612. /// <param name="timeout">The time to wait for any of the handles to become signaled.</param>
  613. /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
  614. /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
  615. /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
  616. internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
  617. {
  618. if (waitHandle == null)
  619. throw new ArgumentNullException("waitHandle");
  620. var waitHandles = new[]
  621. {
  622. _exceptionWaitHandle,
  623. _messageListenerCompleted,
  624. waitHandle
  625. };
  626. switch (WaitHandle.WaitAny(waitHandles, timeout))
  627. {
  628. case 0:
  629. throw _exception;
  630. case 1:
  631. throw new SshConnectionException("Client not connected.");
  632. case WaitHandle.WaitTimeout:
  633. // when the session is disconnecting, a timeout is likely when no
  634. // network connectivity is available; depending on the configured
  635. // timeout either the WaitAny times out first or a SocketException
  636. // detailing a timeout thrown hereby completing the listener thread
  637. // (which makes us end up in case 1). Either way, we do not want to
  638. // report an exception to the client when we're disconnecting anyway
  639. if (!_isDisconnecting)
  640. {
  641. throw new SshOperationTimeoutException("Session operation has timed out");
  642. }
  643. break;
  644. }
  645. }
  646. /// <summary>
  647. /// Sends a message to the server.
  648. /// </summary>
  649. /// <param name="message">The message to send.</param>
  650. /// <exception cref="SshConnectionException">The client is not connected.</exception>
  651. /// <exception cref="SshOperationTimeoutException">The operation timed out.</exception>
  652. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  653. internal void SendMessage(Message message)
  654. {
  655. if (_socket == null || !_socket.CanWrite())
  656. throw new SshConnectionException("Client not connected.");
  657. if (_keyExchangeInProgress && !(message is IKeyExchangedAllowed))
  658. {
  659. // Wait for key exchange to be completed
  660. WaitOnHandle(_keyExchangeCompletedWaitHandle);
  661. }
  662. Log(string.Format("SendMessage to server '{0}': '{1}'.", message.GetType().Name, message));
  663. // Messages can be sent by different thread so we need to synchronize it
  664. var paddingMultiplier = _clientCipher == null ? (byte)8 : Math.Max((byte)8, _serverCipher.MinimumSize); // Should be recalculate base on cipher min length if cipher specified
  665. #if TUNING
  666. var packetData = message.GetPacket(paddingMultiplier, _clientCompression);
  667. #else
  668. var messageData = message.GetBytes();
  669. if (_clientCompression != null)
  670. {
  671. messageData = _clientCompression.Compress(messageData);
  672. }
  673. var packetLength = messageData.Length + 4 + 1; // add length bytes and padding byte
  674. var paddingLength = (byte)((-packetLength) & (paddingMultiplier - 1));
  675. if (paddingLength < paddingMultiplier)
  676. {
  677. paddingLength += paddingMultiplier;
  678. }
  679. // Build Packet data
  680. var packetData = new byte[4 + 1 + messageData.Length + paddingLength];
  681. // Add packet length
  682. ((uint)packetData.Length - 4).GetBytes().CopyTo(packetData, 0);
  683. // Add packet padding length
  684. packetData[4] = paddingLength;
  685. // Add packet payload
  686. messageData.CopyTo(packetData, 4 + 1);
  687. // Add random padding
  688. var paddingBytes = new byte[paddingLength];
  689. Randomizer.GetBytes(paddingBytes);
  690. paddingBytes.CopyTo(packetData, 4 + 1 + messageData.Length);
  691. #endif
  692. // Lock handling of _outboundPacketSequence since it must be sent sequently to server
  693. lock (_socketLock)
  694. {
  695. if (_socket == null || !_socket.Connected)
  696. throw new SshConnectionException("Client not connected.");
  697. #if TUNING
  698. byte[] hash = null;
  699. var packetDataOffset = 4; // first four bytes are reserved for outbound packet sequence
  700. if (_clientMac != null)
  701. {
  702. // write outbound packet sequence to start of packet data
  703. _outboundPacketSequence.Write(packetData, 0);
  704. // calculate packet hash
  705. hash = _clientMac.ComputeHash(packetData);
  706. }
  707. #else
  708. // Calculate packet hash
  709. var hashData = new byte[4 + packetData.Length];
  710. _outboundPacketSequence.GetBytes().CopyTo(hashData, 0);
  711. packetData.CopyTo(hashData, 4);
  712. #endif
  713. // Encrypt packet data
  714. if (_clientCipher != null)
  715. {
  716. #if TUNING
  717. packetData = _clientCipher.Encrypt(packetData, packetDataOffset, (packetData.Length - packetDataOffset));
  718. packetDataOffset = 0;
  719. #else
  720. packetData = _clientCipher.Encrypt(packetData);
  721. #endif
  722. }
  723. if (packetData.Length > MaximumSshPacketSize)
  724. {
  725. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Packet is too big. Maximum packet size is {0} bytes.", MaximumSshPacketSize));
  726. }
  727. #if TUNING
  728. var packetLength = packetData.Length - packetDataOffset;
  729. if (hash == null)
  730. {
  731. SocketWrite(packetData, packetDataOffset, packetLength);
  732. }
  733. #else
  734. if (_clientMac == null)
  735. {
  736. SocketWrite(packetData);
  737. }
  738. #endif
  739. else
  740. {
  741. #if TUNING
  742. var data = new byte[packetLength + (_clientMac.HashSize / 8)];
  743. Buffer.BlockCopy(packetData, packetDataOffset, data, 0, packetLength);
  744. Buffer.BlockCopy(hash, 0, data, packetLength, hash.Length);
  745. #else
  746. var hash = _clientMac.ComputeHash(hashData.ToArray());
  747. var data = new byte[packetData.Length + _clientMac.HashSize / 8];
  748. packetData.CopyTo(data, 0);
  749. hash.CopyTo(data, packetData.Length);
  750. #endif
  751. SocketWrite(data);
  752. }
  753. _outboundPacketSequence++;
  754. Monitor.Pulse(_socketLock);
  755. }
  756. }
  757. /// <summary>
  758. /// Sends a message to the server.
  759. /// </summary>
  760. /// <param name="message">The message to send.</param>
  761. /// <returns>
  762. /// <c>true</c> if the message was sent to the server; otherwise, <c>false</c>.
  763. /// </returns>
  764. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  765. /// <remarks>
  766. /// This methods returns <c>false</c> when the attempt to send the message results in a
  767. /// <see cref="SocketException"/> or a <see cref="SshException"/>.
  768. /// </remarks>
  769. private bool TrySendMessage(Message message)
  770. {
  771. try
  772. {
  773. SendMessage(message);
  774. return true;
  775. }
  776. catch (SshException ex)
  777. {
  778. Log(string.Format("Failure sending message server '{0}': '{1}' => {2}", message.GetType().Name, message, ex));
  779. return false;
  780. }
  781. catch (SocketException ex)
  782. {
  783. Log(string.Format("Failure sending message server '{0}': '{1}' => {2}", message.GetType().Name, message, ex));
  784. return false;
  785. }
  786. }
  787. private static IEnumerable<MessageMetadata> GetMessagesMetadata()
  788. {
  789. return new []
  790. {
  791. new MessageMetadata { Name = "SSH_MSG_NEWKEYS", Number = 21, Type = typeof(NewKeysMessage) },
  792. new MessageMetadata { Name = "SSH_MSG_REQUEST_FAILURE", Number = 82, Type = typeof(RequestFailureMessage) },
  793. new MessageMetadata { Name = "SSH_MSG_KEXINIT", Number = 20, Type = typeof(KeyExchangeInitMessage) },
  794. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN_FAILURE", Number = 92, Type = typeof(ChannelOpenFailureMessage) },
  795. new MessageMetadata { Name = "SSH_MSG_CHANNEL_FAILURE", Number = 100, Type = typeof(ChannelFailureMessage) },
  796. new MessageMetadata { Name = "SSH_MSG_CHANNEL_EXTENDED_DATA", Number = 95, Type = typeof(ChannelExtendedDataMessage) },
  797. new MessageMetadata { Name = "SSH_MSG_CHANNEL_DATA", Number = 94, Type = typeof(ChannelDataMessage) },
  798. new MessageMetadata { Name = "SSH_MSG_USERAUTH_REQUEST", Number = 50, Type = typeof(RequestMessage) },
  799. new MessageMetadata { Name = "SSH_MSG_CHANNEL_REQUEST", Number = 98, Type = typeof(ChannelRequestMessage) },
  800. new MessageMetadata { Name = "SSH_MSG_USERAUTH_BANNER", Number = 53, Type = typeof(BannerMessage) },
  801. new MessageMetadata { Name = "SSH_MSG_USERAUTH_INFO_RESPONSE", Number = 61, Type = typeof(InformationResponseMessage) },
  802. new MessageMetadata { Name = "SSH_MSG_USERAUTH_FAILURE", Number = 51, Type = typeof(FailureMessage) },
  803. new MessageMetadata { Name = "SSH_MSG_DEBUG", Number = 4, Type = typeof(DebugMessage), },
  804. new MessageMetadata { Name = "SSH_MSG_KEXDH_INIT", Number = 30, Type = typeof(KeyExchangeDhInitMessage) },
  805. new MessageMetadata { Name = "SSH_MSG_GLOBAL_REQUEST", Number = 80, Type = typeof(GlobalRequestMessage) },
  806. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN", Number = 90, Type = typeof(ChannelOpenMessage) },
  807. new MessageMetadata { Name = "SSH_MSG_CHANNEL_OPEN_CONFIRMATION", Number = 91, Type = typeof(ChannelOpenConfirmationMessage) },
  808. new MessageMetadata { Name = "SSH_MSG_USERAUTH_INFO_REQUEST", Number = 60, Type = typeof(InformationRequestMessage) },
  809. new MessageMetadata { Name = "SSH_MSG_UNIMPLEMENTED", Number = 3, Type = typeof(UnimplementedMessage) },
  810. new MessageMetadata { Name = "SSH_MSG_REQUEST_SUCCESS", Number = 81, Type = typeof(RequestSuccessMessage) },
  811. new MessageMetadata { Name = "SSH_MSG_CHANNEL_SUCCESS", Number = 99, Type = typeof(ChannelSuccessMessage) },
  812. new MessageMetadata { Name = "SSH_MSG_USERAUTH_PASSWD_CHANGEREQ", Number = 60, Type = typeof(PasswordChangeRequiredMessage) },
  813. new MessageMetadata { Name = "SSH_MSG_DISCONNECT", Number = 1, Type = typeof(DisconnectMessage) },
  814. new MessageMetadata { Name = "SSH_MSG_SERVICE_REQUEST", Number = 5, Type = typeof(ServiceRequestMessage) },
  815. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_REQUEST", Number = 34, Type = typeof(KeyExchangeDhGroupExchangeRequest) },
  816. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_GROUP", Number = 31, Type = typeof(KeyExchangeDhGroupExchangeGroup) },
  817. new MessageMetadata { Name = "SSH_MSG_USERAUTH_SUCCESS", Number = 52, Type = typeof(SuccessMessage) },
  818. new MessageMetadata { Name = "SSH_MSG_USERAUTH_PK_OK", Number = 60, Type = typeof(PublicKeyMessage) },
  819. new MessageMetadata { Name = "SSH_MSG_IGNORE", Number = 2, Type = typeof(IgnoreMessage) },
  820. new MessageMetadata { Name = "SSH_MSG_CHANNEL_WINDOW_ADJUST", Number = 93, Type = typeof(ChannelWindowAdjustMessage) },
  821. new MessageMetadata { Name = "SSH_MSG_CHANNEL_EOF", Number = 96, Type = typeof(ChannelEofMessage) },
  822. new MessageMetadata { Name = "SSH_MSG_CHANNEL_CLOSE", Number = 97, Type = typeof(ChannelCloseMessage) },
  823. new MessageMetadata { Name = "SSH_MSG_SERVICE_ACCEPT", Number = 6, Type = typeof(ServiceAcceptMessage) },
  824. new MessageMetadata { Name = "SSH_MSG_KEXDH_REPLY", Number = 31, Type = typeof(KeyExchangeDhReplyMessage) },
  825. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_INIT", Number = 32, Type = typeof(KeyExchangeDhGroupExchangeInit) },
  826. new MessageMetadata { Name = "SSH_MSG_KEX_DH_GEX_REPLY", Number = 33, Type = typeof(KeyExchangeDhGroupExchangeReply) }
  827. };
  828. }
  829. /// <summary>
  830. /// Receives the message from the server.
  831. /// </summary>
  832. /// <returns>Incoming SSH message.</returns>
  833. /// <exception cref="SshConnectionException"></exception>
  834. private Message ReceiveMessage()
  835. {
  836. #if TUNING
  837. const int inboundPacketSequenceLength = 4;
  838. #endif
  839. // No lock needed since all messages read by only one thread
  840. var blockSize = _serverCipher == null ? (byte)8 : Math.Max((byte)8, _serverCipher.MinimumSize);
  841. // Read packet length first
  842. var firstBlock = Read(blockSize);
  843. if (_serverCipher != null)
  844. {
  845. firstBlock = _serverCipher.Decrypt(firstBlock);
  846. }
  847. var packetLength = (uint)(firstBlock[0] << 24 | firstBlock[1] << 16 | firstBlock[2] << 8 | firstBlock[3]);
  848. // Test packet minimum and maximum boundaries
  849. if (packetLength < Math.Max((byte)16, blockSize) - 4 || packetLength > MaximumSshPacketSize - 4)
  850. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length: {0}.", packetLength), DisconnectReason.ProtocolError);
  851. // Read rest of the packet data
  852. var bytesToRead = (int)(packetLength - (blockSize - 4));
  853. #if TUNING
  854. var data = new byte[bytesToRead + blockSize + inboundPacketSequenceLength];
  855. _inboundPacketSequence.Write(data, 0);
  856. Buffer.BlockCopy(firstBlock, 0, data, inboundPacketSequenceLength, firstBlock.Length);
  857. #else
  858. var data = new byte[bytesToRead + blockSize];
  859. firstBlock.CopyTo(data, 0);
  860. #endif
  861. byte[] serverHash = null;
  862. if (_serverMac != null)
  863. {
  864. serverHash = new byte[_serverMac.HashSize / 8];
  865. bytesToRead += serverHash.Length;
  866. }
  867. if (bytesToRead > 0)
  868. {
  869. var nextBlocks = Read(bytesToRead);
  870. if (serverHash != null)
  871. {
  872. Buffer.BlockCopy(nextBlocks, nextBlocks.Length - serverHash.Length, serverHash, 0, serverHash.Length);
  873. nextBlocks = nextBlocks.Take(nextBlocks.Length - serverHash.Length).ToArray();
  874. }
  875. if (nextBlocks.Length > 0)
  876. {
  877. if (_serverCipher != null)
  878. {
  879. nextBlocks = _serverCipher.Decrypt(nextBlocks);
  880. }
  881. #if TUNING
  882. nextBlocks.CopyTo(data, blockSize + inboundPacketSequenceLength);
  883. #else
  884. nextBlocks.CopyTo(data, blockSize);
  885. #endif
  886. }
  887. }
  888. #if TUNING
  889. var paddingLength = data[inboundPacketSequenceLength + 4];
  890. #else
  891. var paddingLength = data[4];
  892. #endif
  893. var messagePayloadLength = (int) (packetLength - paddingLength - 1);
  894. #if TUNING
  895. const int messagePayloadOffset = inboundPacketSequenceLength + 4 + 1;
  896. #else
  897. var messagePayload = new byte[messagePayloadLength];
  898. Buffer.BlockCopy(data, 5, messagePayload, 0, messagePayload.Length);
  899. #endif
  900. // Validate message against MAC
  901. if (_serverMac != null)
  902. {
  903. #if TUNING
  904. var clientHash = _serverMac.ComputeHash(data);
  905. #else
  906. var clientHashData = new byte[4 + data.Length];
  907. var lengthBytes = _inboundPacketSequence.GetBytes();
  908. lengthBytes.CopyTo(clientHashData, 0);
  909. data.CopyTo(clientHashData, 4);
  910. // Calculate packet hash
  911. var clientHash = _serverMac.ComputeHash(clientHashData);
  912. #endif
  913. if (!serverHash.SequenceEqual(clientHash))
  914. {
  915. throw new SshConnectionException("MAC error", DisconnectReason.MacError);
  916. }
  917. }
  918. if (_serverDecompression != null)
  919. {
  920. #if TUNING
  921. data = _serverDecompression.Decompress(data, inboundPacketSequenceLength + 4 + 1, messagePayloadLength);
  922. #else
  923. messagePayload = _serverDecompression.Decompress(messagePayload);
  924. #endif
  925. }
  926. _inboundPacketSequence++;
  927. #if TUNING
  928. return LoadMessage(data, messagePayloadOffset);
  929. #else
  930. return LoadMessage(messagePayload);
  931. #endif
  932. }
  933. private void SendDisconnect(DisconnectReason reasonCode, string message)
  934. {
  935. // only send a disconnect message if it wasn't already sent, and we're
  936. // still connected
  937. if (_isDisconnectMessageSent || !IsConnected)
  938. return;
  939. var disconnectMessage = new DisconnectMessage(reasonCode, message);
  940. // send the disconnect message, but ignore the outcome
  941. TrySendMessage(disconnectMessage);
  942. _isDisconnectMessageSent = true;
  943. }
  944. partial void HandleMessageCore(Message message);
  945. /// <summary>
  946. /// Handles the message.
  947. /// </summary>
  948. /// <typeparam name="T"></typeparam>
  949. /// <param name="message">The message.</param>
  950. private void HandleMessage<T>(T message) where T : Message
  951. {
  952. OnMessageReceived(message);
  953. }
  954. #region Handle transport messages
  955. private void HandleMessage(DisconnectMessage message)
  956. {
  957. OnDisconnectReceived(message);
  958. Disconnect(message.ReasonCode, message.Description);
  959. }
  960. private void HandleMessage(IgnoreMessage message)
  961. {
  962. OnIgnoreReceived(message);
  963. }
  964. private void HandleMessage(UnimplementedMessage message)
  965. {
  966. OnUnimplementedReceived(message);
  967. }
  968. private void HandleMessage(DebugMessage message)
  969. {
  970. OnDebugReceived(message);
  971. }
  972. private void HandleMessage(ServiceRequestMessage message)
  973. {
  974. OnServiceRequestReceived(message);
  975. }
  976. private void HandleMessage(ServiceAcceptMessage message)
  977. {
  978. // TODO: Refactor to avoid this method here
  979. OnServiceAcceptReceived(message);
  980. _serviceAccepted.Set();
  981. }
  982. private void HandleMessage(KeyExchangeInitMessage message)
  983. {
  984. OnKeyExchangeInitReceived(message);
  985. }
  986. private void HandleMessage(NewKeysMessage message)
  987. {
  988. OnNewKeysReceived(message);
  989. }
  990. #endregion
  991. #region Handle User Authentication messages
  992. private void HandleMessage(RequestMessage message)
  993. {
  994. OnUserAuthenticationRequestReceived(message);
  995. }
  996. private void HandleMessage(FailureMessage message)
  997. {
  998. OnUserAuthenticationFailureReceived(message);
  999. }
  1000. private void HandleMessage(SuccessMessage message)
  1001. {
  1002. OnUserAuthenticationSuccessReceived(message);
  1003. }
  1004. private void HandleMessage(BannerMessage message)
  1005. {
  1006. OnUserAuthenticationBannerReceived(message);
  1007. }
  1008. #endregion
  1009. #region Handle connection messages
  1010. private void HandleMessage(GlobalRequestMessage message)
  1011. {
  1012. OnGlobalRequestReceived(message);
  1013. }
  1014. private void HandleMessage(RequestSuccessMessage message)
  1015. {
  1016. OnRequestSuccessReceived(message);
  1017. }
  1018. private void HandleMessage(RequestFailureMessage message)
  1019. {
  1020. OnRequestFailureReceived(message);
  1021. }
  1022. private void HandleMessage(ChannelOpenMessage message)
  1023. {
  1024. OnChannelOpenReceived(message);
  1025. }
  1026. private void HandleMessage(ChannelOpenConfirmationMessage message)
  1027. {
  1028. OnChannelOpenConfirmationReceived(message);
  1029. }
  1030. private void HandleMessage(ChannelOpenFailureMessage message)
  1031. {
  1032. OnChannelOpenFailureReceived(message);
  1033. }
  1034. private void HandleMessage(ChannelWindowAdjustMessage message)
  1035. {
  1036. OnChannelWindowAdjustReceived(message);
  1037. }
  1038. private void HandleMessage(ChannelDataMessage message)
  1039. {
  1040. OnChannelDataReceived(message);
  1041. }
  1042. private void HandleMessage(ChannelExtendedDataMessage message)
  1043. {
  1044. OnChannelExtendedDataReceived(message);
  1045. }
  1046. private void HandleMessage(ChannelEofMessage message)
  1047. {
  1048. OnChannelEofReceived(message);
  1049. }
  1050. private void HandleMessage(ChannelCloseMessage message)
  1051. {
  1052. OnChannelCloseReceived(message);
  1053. }
  1054. private void HandleMessage(ChannelRequestMessage message)
  1055. {
  1056. OnChannelRequestReceived(message);
  1057. }
  1058. private void HandleMessage(ChannelSuccessMessage message)
  1059. {
  1060. OnChannelSuccessReceived(message);
  1061. }
  1062. private void HandleMessage(ChannelFailureMessage message)
  1063. {
  1064. OnChannelFailureReceived(message);
  1065. }
  1066. #endregion
  1067. #region Handle received message events
  1068. /// <summary>
  1069. /// Called when <see cref="DisconnectMessage"/> received.
  1070. /// </summary>
  1071. /// <param name="message"><see cref="DisconnectMessage"/> message.</param>
  1072. protected virtual void OnDisconnectReceived(DisconnectMessage message)
  1073. {
  1074. Log(string.Format("Disconnect received: {0} {1}", message.ReasonCode, message.Description));
  1075. _exception = new SshConnectionException(string.Format(CultureInfo.InvariantCulture, "The connection was closed by the server: {0} ({1}).", message.Description, message.ReasonCode), message.ReasonCode);
  1076. _exceptionWaitHandle.Set();
  1077. var disconnectReceived = DisconnectReceived;
  1078. if (disconnectReceived != null)
  1079. disconnectReceived(this, new MessageEventArgs<DisconnectMessage>(message));
  1080. var disconnected = Disconnected;
  1081. if (disconnected != null)
  1082. disconnected(this, new EventArgs());
  1083. }
  1084. /// <summary>
  1085. /// Called when <see cref="IgnoreMessage"/> received.
  1086. /// </summary>
  1087. /// <param name="message"><see cref="IgnoreMessage"/> message.</param>
  1088. protected virtual void OnIgnoreReceived(IgnoreMessage message)
  1089. {
  1090. var handlers = IgnoreReceived;
  1091. if (handlers != null)
  1092. handlers(this, new MessageEventArgs<IgnoreMessage>(message));
  1093. }
  1094. /// <summary>
  1095. /// Called when <see cref="UnimplementedMessage"/> message received.
  1096. /// </summary>
  1097. /// <param name="message"><see cref="UnimplementedMessage"/> message.</param>
  1098. protected virtual void OnUnimplementedReceived(UnimplementedMessage message)
  1099. {
  1100. var handlers = UnimplementedReceived;
  1101. if (handlers != null)
  1102. handlers(this, new MessageEventArgs<UnimplementedMessage>(message));
  1103. }
  1104. /// <summary>
  1105. /// Called when <see cref="DebugMessage"/> message received.
  1106. /// </summary>
  1107. /// <param name="message"><see cref="DebugMessage"/> message.</param>
  1108. protected virtual void OnDebugReceived(DebugMessage message)
  1109. {
  1110. var handlers = DebugReceived;
  1111. if (handlers != null)
  1112. handlers(this, new MessageEventArgs<DebugMessage>(message));
  1113. }
  1114. /// <summary>
  1115. /// Called when <see cref="ServiceRequestMessage"/> message received.
  1116. /// </summary>
  1117. /// <param name="message"><see cref="ServiceRequestMessage"/> message.</param>
  1118. protected virtual void OnServiceRequestReceived(ServiceRequestMessage message)
  1119. {
  1120. var handlers = ServiceRequestReceived;
  1121. if (handlers != null)
  1122. handlers(this, new MessageEventArgs<ServiceRequestMessage>(message));
  1123. }
  1124. /// <summary>
  1125. /// Called when <see cref="ServiceAcceptMessage"/> message received.
  1126. /// </summary>
  1127. /// <param name="message"><see cref="ServiceAcceptMessage"/> message.</param>
  1128. protected virtual void OnServiceAcceptReceived(ServiceAcceptMessage message)
  1129. {
  1130. var handlers = ServiceAcceptReceived;
  1131. if (handlers != null)
  1132. handlers(this, new MessageEventArgs<ServiceAcceptMessage>(message));
  1133. }
  1134. /// <summary>
  1135. /// Called when <see cref="KeyExchangeInitMessage"/> message received.
  1136. /// </summary>
  1137. /// <param name="message"><see cref="KeyExchangeInitMessage"/> message.</param>
  1138. protected virtual void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
  1139. {
  1140. _keyExchangeInProgress = true;
  1141. _keyExchangeCompletedWaitHandle.Reset();
  1142. // Disable all registered messages except key exchange related
  1143. foreach (var messageMetadata in _messagesMetadata)
  1144. {
  1145. if (messageMetadata.Activated && messageMetadata.Number > 2 && (messageMetadata.Number < 20 || messageMetadata.Number > 30))
  1146. messageMetadata.Enabled = false;
  1147. }
  1148. _keyExchange = _serviceFactory.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms,
  1149. message.KeyExchangeAlgorithms);
  1150. ConnectionInfo.CurrentKeyExchangeAlgorithm = _keyExchange.Name;
  1151. _keyExchange.HostKeyReceived += KeyExchange_HostKeyReceived;
  1152. // Start the algorithm implementation
  1153. _keyExchange.Start(this, message);
  1154. var keyExchangeInitReceived = KeyExchangeInitReceived;
  1155. if (keyExchangeInitReceived != null)
  1156. keyExchangeInitReceived(this, new MessageEventArgs<KeyExchangeInitMessage>(message));
  1157. }
  1158. /// <summary>
  1159. /// Called when <see cref="NewKeysMessage"/> message received.
  1160. /// </summary>
  1161. /// <param name="message"><see cref="NewKeysMessage"/> message.</param>
  1162. protected virtual void OnNewKeysReceived(NewKeysMessage message)
  1163. {
  1164. // Update sessionId
  1165. if (SessionId == null)
  1166. {
  1167. SessionId = _keyExchange.ExchangeHash;
  1168. }
  1169. // Dispose of old ciphers and hash algorithms
  1170. if (_serverMac != null)
  1171. {
  1172. _serverMac.Clear();
  1173. _serverMac = null;
  1174. }
  1175. if (_clientMac != null)
  1176. {
  1177. _clientMac.Clear();
  1178. _clientMac = null;
  1179. }
  1180. // Update negotiated algorithms
  1181. _serverCipher = _keyExchange.CreateServerCipher();
  1182. _clientCipher = _keyExchange.CreateClientCipher();
  1183. _serverMac = _keyExchange.CreateServerHash();
  1184. _clientMac = _keyExchange.CreateClientHash();
  1185. _clientCompression = _keyExchange.CreateCompressor();
  1186. _serverDecompression = _keyExchange.CreateDecompressor();
  1187. // Dispose of old KeyExchange object as it is no longer needed.
  1188. if (_keyExchange != null)
  1189. {
  1190. _keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1191. _keyExchange.Dispose();
  1192. _keyExchange = null;
  1193. }
  1194. // Enable all active registered messages
  1195. foreach (var messageMetadata in _messagesMetadata)
  1196. {
  1197. if (messageMetadata.Activated)
  1198. messageMetadata.Enabled = true;
  1199. }
  1200. var newKeysReceived = NewKeysReceived;
  1201. if (newKeysReceived != null)
  1202. newKeysReceived(this, new MessageEventArgs<NewKeysMessage>(message));
  1203. // Signal that key exchange completed
  1204. _keyExchangeCompletedWaitHandle.Set();
  1205. _keyExchangeInProgress = false;
  1206. }
  1207. /// <summary>
  1208. /// Called when client is disconnecting from the server.
  1209. /// </summary>
  1210. void ISession.OnDisconnecting()
  1211. {
  1212. _isDisconnecting = true;
  1213. }
  1214. /// <summary>
  1215. /// Called when <see cref="RequestMessage"/> message received.
  1216. /// </summary>
  1217. /// <param name="message"><see cref="RequestMessage"/> message.</param>
  1218. protected virtual void OnUserAuthenticationRequestReceived(RequestMessage message)
  1219. {
  1220. var handlers = UserAuthenticationRequestReceived;
  1221. if (handlers != null)
  1222. handlers(this, new MessageEventArgs<RequestMessage>(message));
  1223. }
  1224. /// <summary>
  1225. /// Called when <see cref="FailureMessage"/> message received.
  1226. /// </summary>
  1227. /// <param name="message"><see cref="FailureMessage"/> message.</param>
  1228. protected virtual void OnUserAuthenticationFailureReceived(FailureMessage message)
  1229. {
  1230. var handlers = UserAuthenticationFailureReceived;
  1231. if (handlers != null)
  1232. handlers(this, new MessageEventArgs<FailureMessage>(message));
  1233. }
  1234. /// <summary>
  1235. /// Called when <see cref="SuccessMessage"/> message received.
  1236. /// </summary>
  1237. /// <param name="message"><see cref="SuccessMessage"/> message.</param>
  1238. protected virtual void OnUserAuthenticationSuccessReceived(SuccessMessage message)
  1239. {
  1240. var handlers = UserAuthenticationSuccessReceived;
  1241. if (handlers != null)
  1242. handlers(this, new MessageEventArgs<SuccessMessage>(message));
  1243. }
  1244. /// <summary>
  1245. /// Called when <see cref="BannerMessage"/> message received.
  1246. /// </summary>
  1247. /// <param name="message"><see cref="BannerMessage"/> message.</param>
  1248. protected virtual void OnUserAuthenticationBannerReceived(BannerMessage message)
  1249. {
  1250. var handlers = UserAuthenticationBannerReceived;
  1251. if (handlers != null)
  1252. handlers(this, new MessageEventArgs<BannerMessage>(message));
  1253. }
  1254. /// <summary>
  1255. /// Called when <see cref="GlobalRequestMessage"/> message received.
  1256. /// </summary>
  1257. /// <param name="message"><see cref="GlobalRequestMessage"/> message.</param>
  1258. protected virtual void OnGlobalRequestReceived(GlobalRequestMessage message)
  1259. {
  1260. var handlers = GlobalRequestReceived;
  1261. if (handlers != null)
  1262. handlers(this, new MessageEventArgs<GlobalRequestMessage>(message));
  1263. }
  1264. /// <summary>
  1265. /// Called when <see cref="RequestSuccessMessage"/> message received.
  1266. /// </summary>
  1267. /// <param name="message"><see cref="RequestSuccessMessage"/> message.</param>
  1268. protected virtual void OnRequestSuccessReceived(RequestSuccessMessage message)
  1269. {
  1270. var handlers = RequestSuccessReceived;
  1271. if (handlers != null)
  1272. handlers(this, new MessageEventArgs<RequestSuccessMessage>(message));
  1273. }
  1274. /// <summary>
  1275. /// Called when <see cref="RequestFailureMessage"/> message received.
  1276. /// </summary>
  1277. /// <param name="message"><see cref="RequestFailureMessage"/> message.</param>
  1278. protected virtual void OnRequestFailureReceived(RequestFailureMessage message)
  1279. {
  1280. var handlers = RequestFailureReceived;
  1281. if (handlers != null)
  1282. handlers(this, new MessageEventArgs<RequestFailureMessage>(message));
  1283. }
  1284. /// <summary>
  1285. /// Called when <see cref="ChannelOpenMessage"/> message received.
  1286. /// </summary>
  1287. /// <param name="message"><see cref="ChannelOpenMessage"/> message.</param>
  1288. protected virtual void OnChannelOpenReceived(ChannelOpenMessage message)
  1289. {
  1290. var handlers = ChannelOpenReceived;
  1291. if (handlers != null)
  1292. handlers(this, new MessageEventArgs<ChannelOpenMessage>(message));
  1293. }
  1294. /// <summary>
  1295. /// Called when <see cref="ChannelOpenConfirmationMessage"/> message received.
  1296. /// </summary>
  1297. /// <param name="message"><see cref="ChannelOpenConfirmationMessage"/> message.</param>
  1298. protected virtual void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage message)
  1299. {
  1300. var handlers = ChannelOpenConfirmationReceived;
  1301. if (handlers != null)
  1302. handlers(this, new MessageEventArgs<ChannelOpenConfirmationMessage>(message));
  1303. }
  1304. /// <summary>
  1305. /// Called when <see cref="ChannelOpenFailureMessage"/> message received.
  1306. /// </summary>
  1307. /// <param name="message"><see cref="ChannelOpenFailureMessage"/> message.</param>
  1308. protected virtual void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
  1309. {
  1310. var handlers = ChannelOpenFailureReceived;
  1311. if (handlers != null)
  1312. handlers(this, new MessageEventArgs<ChannelOpenFailureMessage>(message));
  1313. }
  1314. /// <summary>
  1315. /// Called when <see cref="ChannelWindowAdjustMessage"/> message received.
  1316. /// </summary>
  1317. /// <param name="message"><see cref="ChannelWindowAdjustMessage"/> message.</param>
  1318. protected virtual void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
  1319. {
  1320. var handlers = ChannelWindowAdjustReceived;
  1321. if (handlers != null)
  1322. handlers(this, new MessageEventArgs<ChannelWindowAdjustMessage>(message));
  1323. }
  1324. /// <summary>
  1325. /// Called when <see cref="ChannelDataMessage"/> message received.
  1326. /// </summary>
  1327. /// <param name="message"><see cref="ChannelDataMessage"/> message.</param>
  1328. protected virtual void OnChannelDataReceived(ChannelDataMessage message)
  1329. {
  1330. var handlers = ChannelDataReceived;
  1331. if (handlers != null)
  1332. handlers(this, new MessageEventArgs<ChannelDataMessage>(message));
  1333. }
  1334. /// <summary>
  1335. /// Called when <see cref="ChannelExtendedDataMessage"/> message received.
  1336. /// </summary>
  1337. /// <param name="message"><see cref="ChannelExtendedDataMessage"/> message.</param>
  1338. protected virtual void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
  1339. {
  1340. var handlers = ChannelExtendedDataReceived;
  1341. if (handlers != null)
  1342. handlers(this, new MessageEventArgs<ChannelExtendedDataMessage>(message));
  1343. }
  1344. /// <summary>
  1345. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1346. /// </summary>
  1347. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1348. protected virtual void OnChannelEofReceived(ChannelEofMessage message)
  1349. {
  1350. var handlers = ChannelEofReceived;
  1351. if (handlers != null)
  1352. handlers(this, new MessageEventArgs<ChannelEofMessage>(message));
  1353. }
  1354. /// <summary>
  1355. /// Called when <see cref="ChannelCloseMessage"/> message received.
  1356. /// </summary>
  1357. /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
  1358. protected virtual void OnChannelCloseReceived(ChannelCloseMessage message)
  1359. {
  1360. var handlers = ChannelCloseReceived;
  1361. if (handlers != null)
  1362. handlers(this, new MessageEventArgs<ChannelCloseMessage>(message));
  1363. }
  1364. /// <summary>
  1365. /// Called when <see cref="ChannelRequestMessage"/> message received.
  1366. /// </summary>
  1367. /// <param name="message"><see cref="ChannelRequestMessage"/> message.</param>
  1368. protected virtual void OnChannelRequestReceived(ChannelRequestMessage message)
  1369. {
  1370. var handlers = ChannelRequestReceived;
  1371. if (handlers != null)
  1372. handlers(this, new MessageEventArgs<ChannelRequestMessage>(message));
  1373. }
  1374. /// <summary>
  1375. /// Called when <see cref="ChannelSuccessMessage"/> message received.
  1376. /// </summary>
  1377. /// <param name="message"><see cref="ChannelSuccessMessage"/> message.</param>
  1378. protected virtual void OnChannelSuccessReceived(ChannelSuccessMessage message)
  1379. {
  1380. var handlers = ChannelSuccessReceived;
  1381. if (handlers != null)
  1382. handlers(this, new MessageEventArgs<ChannelSuccessMessage>(message));
  1383. }
  1384. /// <summary>
  1385. /// Called when <see cref="ChannelFailureMessage"/> message received.
  1386. /// </summary>
  1387. /// <param name="message"><see cref="ChannelFailureMessage"/> message.</param>
  1388. protected virtual void OnChannelFailureReceived(ChannelFailureMessage message)
  1389. {
  1390. var handlers = ChannelFailureReceived;
  1391. if (handlers != null)
  1392. handlers(this, new MessageEventArgs<ChannelFailureMessage>(message));
  1393. }
  1394. /// <summary>
  1395. /// Called when <see cref="Message"/> message received.
  1396. /// </summary>
  1397. /// <param name="message"><see cref="Message"/> message.</param>
  1398. protected virtual void OnMessageReceived(Message message)
  1399. {
  1400. var handlers = MessageReceived;
  1401. if (handlers != null)
  1402. handlers(this, new MessageEventArgs<Message>(message));
  1403. }
  1404. #endregion
  1405. private void KeyExchange_HostKeyReceived(object sender, HostKeyEventArgs e)
  1406. {
  1407. var handlers = HostKeyReceived;
  1408. if (handlers != null)
  1409. handlers(this, e);
  1410. }
  1411. /// <summary>
  1412. /// Reads the specified length of bytes from the server.
  1413. /// </summary>
  1414. /// <param name="length">The length.</param>
  1415. /// <returns>
  1416. /// The bytes read from the server.
  1417. /// </returns>
  1418. private byte[] Read(int length)
  1419. {
  1420. var buffer = new byte[length];
  1421. SocketRead(length, ref buffer);
  1422. return buffer;
  1423. }
  1424. #region Message loading functions
  1425. /// <summary>
  1426. /// Registers SSH message with the session.
  1427. /// </summary>
  1428. /// <param name="messageName">The name of the message to register with the session.</param>
  1429. public void RegisterMessage(string messageName)
  1430. {
  1431. InternalRegisterMessage(messageName);
  1432. }
  1433. /// <summary>
  1434. /// Unregister SSH message from the session.
  1435. /// </summary>
  1436. /// <param name="messageName">The name of the message to unregister with the session.</param>
  1437. public void UnRegisterMessage(string messageName)
  1438. {
  1439. InternalUnRegisterMessage(messageName);
  1440. }
  1441. #if TUNING
  1442. /// <summary>
  1443. /// Loads a message from a given buffer.
  1444. /// </summary>
  1445. /// <param name="data">An array of bytes from which to construct the message.</param>
  1446. /// <param name="offset">The zero-based byte offset in <paramref name="data"/> at which to begin reading.</param>
  1447. /// <returns>
  1448. /// A message constructed from <paramref name="data"/>.
  1449. /// </returns>
  1450. /// <exception cref="SshException">The type of the message is not supported.</exception>
  1451. private Message LoadMessage(byte[] data, int offset)
  1452. {
  1453. var messageType = data[offset];
  1454. var messageMetadata = (from m in _messagesMetadata where m.Number == messageType && m.Enabled && m.Activated select m).FirstOrDefault();
  1455. if (messageMetadata == null)
  1456. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Message type {0} is not valid.", messageType));
  1457. var message = messageMetadata.Type.CreateInstance<Message>();
  1458. message.Load(data, offset);
  1459. Log(string.Format("ReceiveMessage from server: '{0}': '{1}'.", message.GetType().Name, message));
  1460. return message;
  1461. }
  1462. #else
  1463. /// <summary>
  1464. /// Loads the message.
  1465. /// </summary>
  1466. /// <param name="data">Message data.</param>
  1467. /// <returns>New message</returns>
  1468. private Message LoadMessage(byte[] data)
  1469. {
  1470. var messageType = data[0];
  1471. var messageMetadata = (from m in _messagesMetadata where m.Number == messageType && m.Enabled && m.Activated select m).SingleOrDefault();
  1472. if (messageMetadata == null)
  1473. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Message type {0} is not valid.", messageType));
  1474. var message = messageMetadata.Type.CreateInstance<Message>();
  1475. message.Load(data);
  1476. Log(string.Format("ReceiveMessage from server: '{0}': '{1}'.", message.GetType().Name, message));
  1477. return message;
  1478. }
  1479. #endif
  1480. partial void InternalRegisterMessage(string messageName);
  1481. partial void InternalUnRegisterMessage(string messageName);
  1482. #endregion
  1483. partial void ExecuteThread(Action action);
  1484. /// <summary>
  1485. /// Gets a value indicating whether the socket is connected.
  1486. /// </summary>
  1487. /// <value>
  1488. /// <c>true</c> if the socket is connected; otherwise, <c>false</c>.
  1489. /// </value>
  1490. partial void IsSocketConnected(ref bool isConnected);
  1491. /// <summary>
  1492. /// Establishes a socket connection to the specified host and port.
  1493. /// </summary>
  1494. /// <param name="host">The host name of the server to connect to.</param>
  1495. /// <param name="port">The port to connect to.</param>
  1496. /// <exception cref="SshOperationTimeoutException">The connection failed to establish within the configured <see cref="Renci.SshNet.ConnectionInfo.Timeout"/>.</exception>
  1497. /// <exception cref="SocketException">An error occurred trying to establish the connection.</exception>
  1498. partial void SocketConnect(string host, int port);
  1499. /// <summary>
  1500. /// Closes the socket.
  1501. /// </summary>
  1502. /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
  1503. partial void SocketDisconnect();
  1504. /// <summary>
  1505. /// Performs a blocking read on the socket until <paramref name="length"/> bytes are received.
  1506. /// </summary>
  1507. /// <param name="length">The number of bytes to read.</param>
  1508. /// <param name="buffer">The buffer to read to.</param>
  1509. /// <exception cref="SshConnectionException">The socket is closed.</exception>
  1510. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  1511. /// <exception cref="SocketException">The read failed.</exception>
  1512. partial void SocketRead(int length, ref byte[] buffer);
  1513. /// <summary>
  1514. /// Performs a blocking read on the socket until a line is read.
  1515. /// </summary>
  1516. /// <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>
  1517. /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param>
  1518. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  1519. /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
  1520. partial void SocketReadLine(ref string response, TimeSpan timeout);
  1521. partial void Log(string text);
  1522. /// <summary>
  1523. /// Writes the specified data to the server.
  1524. /// </summary>
  1525. /// <param name="data">The data to write to the server.</param>
  1526. /// <exception cref="SshOperationTimeoutException">The write has timed-out.</exception>
  1527. /// <exception cref="SocketException">The write failed.</exception>
  1528. private void SocketWrite(byte[] data)
  1529. {
  1530. SocketWrite(data, 0, data.Length);
  1531. }
  1532. /// <summary>
  1533. /// Disconnects and disposes the socket.
  1534. /// </summary>
  1535. private void SocketDisconnectAndDispose()
  1536. {
  1537. if (_socket != null)
  1538. {
  1539. lock (_socketLock)
  1540. {
  1541. if (_socket != null)
  1542. {
  1543. if (_socket.Connected)
  1544. SocketDisconnect();
  1545. _socket.Dispose();
  1546. _socket = null;
  1547. }
  1548. }
  1549. }
  1550. }
  1551. /// <summary>
  1552. /// Listens for incoming message from the server and handles them. This method run as a task on separate thread.
  1553. /// </summary>
  1554. private void MessageListener()
  1555. {
  1556. try
  1557. {
  1558. while (_socket != null && _socket.Connected)
  1559. {
  1560. var message = ReceiveMessage();
  1561. HandleMessageCore(message);
  1562. }
  1563. }
  1564. catch (Exception exp)
  1565. {
  1566. RaiseError(exp);
  1567. }
  1568. finally
  1569. {
  1570. // signal that the message listener thread has stopped
  1571. _messageListenerCompleted.Set();
  1572. }
  1573. }
  1574. private byte SocketReadByte()
  1575. {
  1576. var buffer = new byte[1];
  1577. SocketRead(1, ref buffer);
  1578. return buffer[0];
  1579. }
  1580. private void SocketWriteByte(byte data)
  1581. {
  1582. SocketWrite(new[] {data});
  1583. }
  1584. private void ConnectSocks4()
  1585. {
  1586. // Send socks version number
  1587. SocketWriteByte(0x04);
  1588. // Send command code
  1589. SocketWriteByte(0x01);
  1590. // Send port
  1591. SocketWriteByte((byte)(ConnectionInfo.Port / 0xFF));
  1592. SocketWriteByte((byte)(ConnectionInfo.Port % 0xFF));
  1593. // Send IP
  1594. var ipAddress = ConnectionInfo.Host.GetIPAddress();
  1595. SocketWrite(ipAddress.GetAddressBytes());
  1596. // Send username
  1597. var username = new ASCIIEncoding().GetBytes(ConnectionInfo.ProxyUsername);
  1598. SocketWrite(username);
  1599. SocketWriteByte(0x00);
  1600. // Read 0
  1601. if (SocketReadByte() != 0)
  1602. {
  1603. throw new ProxyException("SOCKS4: Null is expected.");
  1604. }
  1605. // Read response code
  1606. var code = SocketReadByte();
  1607. switch (code)
  1608. {
  1609. case 0x5a:
  1610. break;
  1611. case 0x5b:
  1612. throw new ProxyException("SOCKS4: Connection rejected.");
  1613. case 0x5c:
  1614. throw new ProxyException("SOCKS4: Client is not running identd or not reachable from the server.");
  1615. case 0x5d:
  1616. throw new ProxyException("SOCKS4: Client's identd could not confirm the user ID string in the request.");
  1617. default:
  1618. throw new ProxyException("SOCKS4: Not valid response.");
  1619. }
  1620. var dummyBuffer = new byte[4];
  1621. // Read 2 bytes to be ignored
  1622. SocketRead(2, ref dummyBuffer);
  1623. // Read 4 bytes to be ignored
  1624. SocketRead(4, ref dummyBuffer);
  1625. }
  1626. private void ConnectSocks5()
  1627. {
  1628. // Send socks version number
  1629. SocketWriteByte(0x05);
  1630. // Send number of supported authentication methods
  1631. SocketWriteByte(0x02);
  1632. // Send supported authentication methods
  1633. SocketWriteByte(0x00); // No authentication
  1634. SocketWriteByte(0x02); // Username/Password
  1635. var socksVersion = SocketReadByte();
  1636. if (socksVersion != 0x05)
  1637. throw new ProxyException(string.Format("SOCKS Version '{0}' is not supported.", socksVersion));
  1638. var authenticationMethod = SocketReadByte();
  1639. switch (authenticationMethod)
  1640. {
  1641. case 0x00:
  1642. break;
  1643. case 0x02:
  1644. // Send version
  1645. SocketWriteByte(0x01);
  1646. var encoding = new ASCIIEncoding();
  1647. var username = encoding.GetBytes(ConnectionInfo.ProxyUsername);
  1648. if (username.Length > byte.MaxValue)
  1649. throw new ProxyException("Proxy username is too long.");
  1650. // Send username length
  1651. SocketWriteByte((byte)username.Length);
  1652. // Send username
  1653. SocketWrite(username);
  1654. var password = encoding.GetBytes(ConnectionInfo.ProxyPassword);
  1655. if (password.Length > byte.MaxValue)
  1656. throw new ProxyException("Proxy password is too long.");
  1657. // Send username length
  1658. SocketWriteByte((byte)password.Length);
  1659. // Send username
  1660. SocketWrite(password);
  1661. var serverVersion = SocketReadByte();
  1662. if (serverVersion != 1)
  1663. throw new ProxyException("SOCKS5: Server authentication version is not valid.");
  1664. var statusCode = SocketReadByte();
  1665. if (statusCode != 0)
  1666. throw new ProxyException("SOCKS5: Username/Password authentication failed.");
  1667. break;
  1668. case 0xFF:
  1669. throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
  1670. }
  1671. // Send socks version number
  1672. SocketWriteByte(0x05);
  1673. // Send command code
  1674. SocketWriteByte(0x01); // establish a TCP/IP stream connection
  1675. // Send reserved, must be 0x00
  1676. SocketWriteByte(0x00);
  1677. var ip = ConnectionInfo.Host.GetIPAddress();
  1678. // Send address type and address
  1679. if (ip.AddressFamily == AddressFamily.InterNetwork)
  1680. {
  1681. SocketWriteByte(0x01);
  1682. var address = ip.GetAddressBytes();
  1683. SocketWrite(address);
  1684. }
  1685. else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
  1686. {
  1687. SocketWriteByte(0x04);
  1688. var address = ip.GetAddressBytes();
  1689. SocketWrite(address);
  1690. }
  1691. else
  1692. {
  1693. throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
  1694. }
  1695. // Send port
  1696. SocketWriteByte((byte)(ConnectionInfo.Port / 0xFF));
  1697. SocketWriteByte((byte)(ConnectionInfo.Port % 0xFF));
  1698. // Read Server SOCKS5 version
  1699. if (SocketReadByte() != 5)
  1700. {
  1701. throw new ProxyException("SOCKS5: Version 5 is expected.");
  1702. }
  1703. // Read response code
  1704. var status = SocketReadByte();
  1705. switch (status)
  1706. {
  1707. case 0x00:
  1708. break;
  1709. case 0x01:
  1710. throw new ProxyException("SOCKS5: General failure.");
  1711. case 0x02:
  1712. throw new ProxyException("SOCKS5: Connection not allowed by ruleset.");
  1713. case 0x03:
  1714. throw new ProxyException("SOCKS5: Network unreachable.");
  1715. case 0x04:
  1716. throw new ProxyException("SOCKS5: Host unreachable.");
  1717. case 0x05:
  1718. throw new ProxyException("SOCKS5: Connection refused by destination host.");
  1719. case 0x06:
  1720. throw new ProxyException("SOCKS5: TTL expired.");
  1721. case 0x07:
  1722. throw new ProxyException("SOCKS5: Command not supported or protocol error.");
  1723. case 0x08:
  1724. throw new ProxyException("SOCKS5: Address type not supported.");
  1725. default:
  1726. throw new ProxyException("SOCKS4: Not valid response.");
  1727. }
  1728. // Read 0
  1729. if (SocketReadByte() != 0)
  1730. {
  1731. throw new ProxyException("SOCKS5: 0 byte is expected.");
  1732. }
  1733. var addressType = SocketReadByte();
  1734. var responseIp = new byte[16];
  1735. switch (addressType)
  1736. {
  1737. case 0x01:
  1738. SocketRead(4, ref responseIp);
  1739. break;
  1740. case 0x04:
  1741. SocketRead(16, ref responseIp);
  1742. break;
  1743. default:
  1744. throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
  1745. }
  1746. var port = new byte[2];
  1747. // Read 2 bytes to be ignored
  1748. SocketRead(2, ref port);
  1749. }
  1750. private void ConnectHttp()
  1751. {
  1752. var httpResponseRe = new Regex(@"HTTP/(?<version>\d[.]\d) (?<statusCode>\d{3}) (?<reasonPhrase>.+)$");
  1753. var httpHeaderRe = new Regex(@"(?<fieldName>[^\[\]()<>@,;:\""/?={} \t]+):(?<fieldValue>.+)?");
  1754. var encoding = new ASCIIEncoding();
  1755. SocketWrite(encoding.GetBytes(string.Format("CONNECT {0}:{1} HTTP/1.0\r\n", ConnectionInfo.Host, ConnectionInfo.Port)));
  1756. // Sent proxy authorization is specified
  1757. if (!string.IsNullOrEmpty(ConnectionInfo.ProxyUsername))
  1758. {
  1759. var authorization = string.Format("Proxy-Authorization: Basic {0}\r\n",
  1760. Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", ConnectionInfo.ProxyUsername, ConnectionInfo.ProxyPassword)))
  1761. );
  1762. SocketWrite(encoding.GetBytes(authorization));
  1763. }
  1764. SocketWrite(encoding.GetBytes("\r\n"));
  1765. HttpStatusCode? statusCode = null;
  1766. var response = string.Empty;
  1767. var contentLength = 0;
  1768. while (true)
  1769. {
  1770. SocketReadLine(ref response, ConnectionInfo.Timeout);
  1771. if (response == null)
  1772. // server shut down socket
  1773. break;
  1774. if (statusCode == null)
  1775. {
  1776. var statusMatch = httpResponseRe.Match(response);
  1777. if (statusMatch.Success)
  1778. {
  1779. var httpStatusCode = statusMatch.Result("${statusCode}");
  1780. statusCode = (HttpStatusCode) int.Parse(httpStatusCode);
  1781. if (statusCode != HttpStatusCode.OK)
  1782. {
  1783. var reasonPhrase = statusMatch.Result("${reasonPhrase}");
  1784. throw new ProxyException(string.Format("HTTP: Status code {0}, \"{1}\"", httpStatusCode,
  1785. reasonPhrase));
  1786. }
  1787. }
  1788. continue;
  1789. }
  1790. // continue on parsing message headers coming from the server
  1791. var headerMatch = httpHeaderRe.Match(response);
  1792. if (headerMatch.Success)
  1793. {
  1794. var fieldName = headerMatch.Result("${fieldName}");
  1795. if (fieldName.Equals("Content-Length", StringComparison.InvariantCultureIgnoreCase))
  1796. {
  1797. contentLength = int.Parse(headerMatch.Result("${fieldValue}"));
  1798. }
  1799. continue;
  1800. }
  1801. // check if we've reached the CRLF which separates request line and headers from the message body
  1802. if (response.Length == 0)
  1803. {
  1804. // read response body if specified
  1805. if (contentLength > 0)
  1806. {
  1807. var contentBody = new byte[contentLength];
  1808. SocketRead(contentLength, ref contentBody);
  1809. }
  1810. break;
  1811. }
  1812. }
  1813. if (statusCode == null)
  1814. throw new ProxyException("HTTP response does not contain status line.");
  1815. }
  1816. /// <summary>
  1817. /// Raises the <see cref="ErrorOccured"/> event.
  1818. /// </summary>
  1819. /// <param name="exp">The exp.</param>
  1820. private void RaiseError(Exception exp)
  1821. {
  1822. var connectionException = exp as SshConnectionException;
  1823. if (_isDisconnecting)
  1824. {
  1825. // a connection exception which is raised while isDisconnecting is normal and
  1826. // should be ignored
  1827. if (connectionException != null)
  1828. return;
  1829. // any timeout while disconnecting can be caused by loss of connectivity
  1830. // altogether and should be ignored
  1831. var socketException = exp as SocketException;
  1832. if (socketException != null && socketException.SocketErrorCode == SocketError.TimedOut)
  1833. return;
  1834. }
  1835. _exception = exp;
  1836. _exceptionWaitHandle.Set();
  1837. var errorOccured = ErrorOccured;
  1838. if (errorOccured != null)
  1839. errorOccured(this, new ExceptionEventArgs(exp));
  1840. if (connectionException != null)
  1841. {
  1842. Disconnect(connectionException.DisconnectReason, exp.ToString());
  1843. }
  1844. }
  1845. /// <summary>
  1846. /// Resets connection-specific information to ensure state of a previous connection
  1847. /// does not affect new connections.
  1848. /// </summary>
  1849. private void Reset()
  1850. {
  1851. if (_exceptionWaitHandle != null)
  1852. _exceptionWaitHandle.Reset();
  1853. if (_keyExchangeCompletedWaitHandle != null)
  1854. _keyExchangeCompletedWaitHandle.Reset();
  1855. if (_messageListenerCompleted != null)
  1856. _messageListenerCompleted.Set();
  1857. SessionId = null;
  1858. _isDisconnectMessageSent = false;
  1859. _isDisconnecting = false;
  1860. _isAuthenticated = false;
  1861. _exception = null;
  1862. _keyExchangeInProgress = false;
  1863. }
  1864. #region IDisposable implementation
  1865. private bool _disposed;
  1866. /// <summary>
  1867. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  1868. /// </summary>
  1869. public void Dispose()
  1870. {
  1871. Dispose(true);
  1872. GC.SuppressFinalize(this);
  1873. }
  1874. /// <summary>
  1875. /// Releases unmanaged and - optionally - managed resources
  1876. /// </summary>
  1877. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1878. protected virtual void Dispose(bool disposing)
  1879. {
  1880. // Check to see if Dispose has already been called.
  1881. if (!_disposed)
  1882. {
  1883. // If disposing equals true, dispose all managed
  1884. // and unmanaged ResourceMessages.
  1885. if (disposing)
  1886. {
  1887. Disconnect();
  1888. if (_serviceAccepted != null)
  1889. {
  1890. _serviceAccepted.Dispose();
  1891. _serviceAccepted = null;
  1892. }
  1893. if (_exceptionWaitHandle != null)
  1894. {
  1895. _exceptionWaitHandle.Dispose();
  1896. _exceptionWaitHandle = null;
  1897. }
  1898. if (_keyExchangeCompletedWaitHandle != null)
  1899. {
  1900. _keyExchangeCompletedWaitHandle.Dispose();
  1901. _keyExchangeCompletedWaitHandle = null;
  1902. }
  1903. if (_serverMac != null)
  1904. {
  1905. _serverMac.Clear();
  1906. _serverMac = null;
  1907. }
  1908. if (_clientMac != null)
  1909. {
  1910. _clientMac.Clear();
  1911. _clientMac = null;
  1912. }
  1913. if (_keyExchange != null)
  1914. {
  1915. _keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1916. _keyExchange.Dispose();
  1917. _keyExchange = null;
  1918. }
  1919. if (_bytesReadFromSocket != null)
  1920. {
  1921. _bytesReadFromSocket.Dispose();
  1922. _bytesReadFromSocket = null;
  1923. }
  1924. if (_messageListenerCompleted != null)
  1925. {
  1926. _messageListenerCompleted.Dispose();
  1927. _messageListenerCompleted = null;
  1928. }
  1929. }
  1930. // Note disposing has been done.
  1931. _disposed = true;
  1932. }
  1933. }
  1934. /// <summary>
  1935. /// Releases unmanaged resources and performs other cleanup operations before the
  1936. /// <see cref="Session"/> is reclaimed by garbage collection.
  1937. /// </summary>
  1938. ~Session()
  1939. {
  1940. // Do not re-create Dispose clean-up code here.
  1941. // Calling Dispose(false) is optimal in terms of
  1942. // readability and maintainability.
  1943. Dispose(false);
  1944. }
  1945. #endregion IDisposable implementation
  1946. #region ISession implementation
  1947. /// <summary>
  1948. /// Gets or sets the connection info.
  1949. /// </summary>
  1950. /// <value>The connection info.</value>
  1951. IConnectionInfo ISession.ConnectionInfo
  1952. {
  1953. get { return ConnectionInfo; }
  1954. }
  1955. WaitHandle ISession.MessageListenerCompleted
  1956. {
  1957. get { return _messageListenerCompleted; }
  1958. }
  1959. /// <summary>
  1960. /// Create a new SSH session channel.
  1961. /// </summary>
  1962. /// <returns>
  1963. /// A new SSH session channel.
  1964. /// </returns>
  1965. IChannelSession ISession.CreateChannelSession()
  1966. {
  1967. return new ChannelSession(this, NextChannelNumber, InitialLocalWindowSize, LocalChannelDataPacketSize);
  1968. }
  1969. /// <summary>
  1970. /// Create a new channel for a locally forwarded TCP/IP port.
  1971. /// </summary>
  1972. /// <returns>
  1973. /// A new channel for a locally forwarded TCP/IP port.
  1974. /// </returns>
  1975. IChannelDirectTcpip ISession.CreateChannelDirectTcpip()
  1976. {
  1977. return new ChannelDirectTcpip(this, NextChannelNumber, InitialLocalWindowSize, LocalChannelDataPacketSize);
  1978. }
  1979. /// <summary>
  1980. /// Creates a "forwarded-tcpip" SSH channel.
  1981. /// </summary>
  1982. /// <returns>
  1983. /// A new "forwarded-tcpip" SSH channel.
  1984. /// </returns>
  1985. IChannelForwardedTcpip ISession.CreateChannelForwardedTcpip(uint remoteChannelNumber, uint remoteWindowSize,
  1986. uint remoteChannelDataPacketSize)
  1987. {
  1988. return new ChannelForwardedTcpip(this,
  1989. NextChannelNumber,
  1990. InitialLocalWindowSize,
  1991. LocalChannelDataPacketSize,
  1992. remoteChannelNumber,
  1993. remoteWindowSize,
  1994. remoteChannelDataPacketSize);
  1995. }
  1996. /// <summary>
  1997. /// Sends a message to the server.
  1998. /// </summary>
  1999. /// <param name="message">The message to send.</param>
  2000. /// <exception cref="SshConnectionException">The client is not connected.</exception>
  2001. /// <exception cref="SshOperationTimeoutException">The operation timed out.</exception>
  2002. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  2003. void ISession.SendMessage(Message message)
  2004. {
  2005. SendMessage(message);
  2006. }
  2007. /// <summary>
  2008. /// Sends a message to the server.
  2009. /// </summary>
  2010. /// <param name="message">The message to send.</param>
  2011. /// <returns>
  2012. /// <c>true</c> if the message was sent to the server; otherwise, <c>false</c>.
  2013. /// </returns>
  2014. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  2015. /// <remarks>
  2016. /// This methods returns <c>false</c> when the attempt to send the message results in a
  2017. /// <see cref="SocketException"/> or a <see cref="SshException"/>.
  2018. /// </remarks>
  2019. bool ISession.TrySendMessage(Message message)
  2020. {
  2021. return TrySendMessage(message);
  2022. }
  2023. #endregion ISession implementation
  2024. private class MessageMetadata
  2025. {
  2026. public string Name { get; set; }
  2027. public byte Number { get; set; }
  2028. public bool Enabled { get; set; }
  2029. public bool Activated { get; set; }
  2030. public Type Type { get; set; }
  2031. }
  2032. }
  2033. }