Session.cs 94 KB

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