Session.cs 93 KB

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