Session.cs 102 KB

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