Session.cs 102 KB

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