Session.cs 94 KB

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