Session.cs 93 KB

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