Session.cs 81 KB

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