Session.cs 91 KB

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