Session.cs 90 KB

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