Session.cs 101 KB

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