Session.cs 81 KB

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