Session.cs 88 KB

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