Session.cs 80 KB

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