Session.cs 101 KB

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