Session.cs 100 KB

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