Session.cs 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  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 reference to task that listens for incoming messages
  60. /// </summary>
  61. private EventWaitHandle _messageListenerCompleted;
  62. /// <summary>
  63. /// Specifies outbound packet number
  64. /// </summary>
  65. private volatile UInt32 _outboundPacketSequence = 0;
  66. /// <summary>
  67. /// Specifies incoming packet number
  68. /// </summary>
  69. private UInt32 _inboundPacketSequence = 0;
  70. /// <summary>
  71. /// WaitHandle to signal that last service request was accepted
  72. /// </summary>
  73. private EventWaitHandle _serviceAccepted = new AutoResetEvent(false);
  74. /// <summary>
  75. /// WaitHandle to signal that exception was thrown by another thread.
  76. /// </summary>
  77. private EventWaitHandle _exceptionWaitHandle = new AutoResetEvent(false);
  78. /// <summary>
  79. /// WaitHandle to signal that key exchange was completed.
  80. /// </summary>
  81. private EventWaitHandle _keyExchangeCompletedWaitHandle = new ManualResetEvent(false);
  82. /// <summary>
  83. /// WaitHandle to signal that key exchange is in progress.
  84. /// </summary>
  85. private bool _keyExchangeInProgress = false;
  86. /// <summary>
  87. /// Exception that need to be thrown by waiting thread
  88. /// </summary>
  89. private Exception _exception;
  90. /// <summary>
  91. /// Specifies whether connection is authenticated
  92. /// </summary>
  93. private bool _isAuthenticated;
  94. /// <summary>
  95. /// Specifies whether user issued Disconnect command or not
  96. /// </summary>
  97. private bool _isDisconnecting;
  98. private KeyExchange _keyExchange;
  99. private HashAlgorithm _serverMac;
  100. private HashAlgorithm _clientMac;
  101. private BlockCipher _clientCipher;
  102. private BlockCipher _serverCipher;
  103. private Compressor _serverDecompression;
  104. private Compressor _clientCompression;
  105. private SemaphoreLight _sessionSemaphore;
  106. /// <summary>
  107. /// Gets the session semaphore that controls session channels.
  108. /// </summary>
  109. /// <value>The session semaphore.</value>
  110. public SemaphoreLight SessionSemaphore
  111. {
  112. get
  113. {
  114. if (this._sessionSemaphore == null)
  115. {
  116. lock (this)
  117. {
  118. if (this._sessionSemaphore == null)
  119. {
  120. this._sessionSemaphore = new SemaphoreLight(this.ConnectionInfo.MaxSessions);
  121. }
  122. }
  123. }
  124. return this._sessionSemaphore;
  125. }
  126. }
  127. private bool _isDisconnectMessageSent;
  128. private uint _nextChannelNumber;
  129. /// <summary>
  130. /// Gets the next channel number.
  131. /// </summary>
  132. /// <value>The next channel number.</value>
  133. internal uint NextChannelNumber
  134. {
  135. get
  136. {
  137. uint result;
  138. lock (this)
  139. {
  140. result = this._nextChannelNumber++;
  141. }
  142. return result;
  143. }
  144. }
  145. /// <summary>
  146. /// Gets a value indicating whether socket connected.
  147. /// </summary>
  148. /// <value>
  149. /// <c>true</c> if socket connected; otherwise, <c>false</c>.
  150. /// </value>
  151. public bool IsConnected
  152. {
  153. get
  154. {
  155. return this._socket != null && this._socket.Connected && this._isAuthenticated && this._messageListenerCompleted != null;
  156. }
  157. }
  158. /// <summary>
  159. /// Gets or sets the session id.
  160. /// </summary>
  161. /// <value>The session id.</value>
  162. public byte[] SessionId { get; private set; }
  163. private Message _clientInitMessage;
  164. /// <summary>
  165. /// Gets the client init message.
  166. /// </summary>
  167. /// <value>The client init message.</value>
  168. public Message ClientInitMessage
  169. {
  170. get
  171. {
  172. if (this._clientInitMessage == null)
  173. {
  174. this._clientInitMessage = new KeyExchangeInitMessage()
  175. {
  176. KeyExchangeAlgorithms = this.ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(),
  177. ServerHostKeyAlgorithms = this.ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(),
  178. EncryptionAlgorithmsClientToServer = this.ConnectionInfo.Encryptions.Keys.ToArray(),
  179. EncryptionAlgorithmsServerToClient = this.ConnectionInfo.Encryptions.Keys.ToArray(),
  180. MacAlgorithmsClientToServer = this.ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
  181. MacAlgorithmsServerToClient = this.ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
  182. CompressionAlgorithmsClientToServer = this.ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
  183. CompressionAlgorithmsServerToClient = this.ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
  184. LanguagesClientToServer = new string[] { string.Empty },
  185. LanguagesServerToClient = new string[] { string.Empty },
  186. FirstKexPacketFollows = false,
  187. Reserved = 0,
  188. };
  189. }
  190. return this._clientInitMessage;
  191. }
  192. }
  193. /// <summary>
  194. /// Gets or sets the server version string.
  195. /// </summary>
  196. /// <value>The server version.</value>
  197. public string ServerVersion { get; private set; }
  198. /// <summary>
  199. /// Gets or sets the client version string.
  200. /// </summary>
  201. /// <value>The client version.</value>
  202. public string ClientVersion { get; private set; }
  203. /// <summary>
  204. /// Gets or sets the connection info.
  205. /// </summary>
  206. /// <value>The connection info.</value>
  207. public ConnectionInfo ConnectionInfo { get; private set; }
  208. /// <summary>
  209. /// Occurs when an error occurred.
  210. /// </summary>
  211. public event EventHandler<ExceptionEventArgs> ErrorOccured;
  212. /// <summary>
  213. /// Occurs when session has been disconnected form the server.
  214. /// </summary>
  215. public event EventHandler<EventArgs> Disconnected;
  216. /// <summary>
  217. /// Occurs when host key received.
  218. /// </summary>
  219. public event EventHandler<HostKeyEventArgs> HostKeyReceived;
  220. #region Message events
  221. /// <summary>
  222. /// Occurs when <see cref="DisconnectMessage"/> message received
  223. /// </summary>
  224. internal event EventHandler<MessageEventArgs<DisconnectMessage>> DisconnectReceived;
  225. /// <summary>
  226. /// Occurs when <see cref="IgnoreMessage"/> message received
  227. /// </summary>
  228. internal event EventHandler<MessageEventArgs<IgnoreMessage>> IgnoreReceived;
  229. /// <summary>
  230. /// Occurs when <see cref="UnimplementedMessage"/> message received
  231. /// </summary>
  232. internal event EventHandler<MessageEventArgs<UnimplementedMessage>> UnimplementedReceived;
  233. /// <summary>
  234. /// Occurs when <see cref="DebugMessage"/> message received
  235. /// </summary>
  236. internal event EventHandler<MessageEventArgs<DebugMessage>> DebugReceived;
  237. /// <summary>
  238. /// Occurs when <see cref="ServiceRequestMessage"/> message received
  239. /// </summary>
  240. internal event EventHandler<MessageEventArgs<ServiceRequestMessage>> ServiceRequestReceived;
  241. /// <summary>
  242. /// Occurs when <see cref="ServiceAcceptMessage"/> message received
  243. /// </summary>
  244. internal event EventHandler<MessageEventArgs<ServiceAcceptMessage>> ServiceAcceptReceived;
  245. /// <summary>
  246. /// Occurs when <see cref="KeyExchangeInitMessage"/> message received
  247. /// </summary>
  248. internal event EventHandler<MessageEventArgs<KeyExchangeInitMessage>> KeyExchangeInitReceived;
  249. /// <summary>
  250. /// Occurs when <see cref="NewKeysMessage"/> message received
  251. /// </summary>
  252. internal event EventHandler<MessageEventArgs<NewKeysMessage>> NewKeysReceived;
  253. /// <summary>
  254. /// Occurs when <see cref="RequestMessage"/> message received
  255. /// </summary>
  256. internal event EventHandler<MessageEventArgs<RequestMessage>> UserAuthenticationRequestReceived;
  257. /// <summary>
  258. /// Occurs when <see cref="FailureMessage"/> message received
  259. /// </summary>
  260. internal event EventHandler<MessageEventArgs<FailureMessage>> UserAuthenticationFailureReceived;
  261. /// <summary>
  262. /// Occurs when <see cref="SuccessMessage"/> message received
  263. /// </summary>
  264. internal event EventHandler<MessageEventArgs<SuccessMessage>> UserAuthenticationSuccessReceived;
  265. /// <summary>
  266. /// Occurs when <see cref="BannerMessage"/> message received
  267. /// </summary>
  268. internal event EventHandler<MessageEventArgs<BannerMessage>> UserAuthenticationBannerReceived;
  269. /// <summary>
  270. /// Occurs when <see cref="GlobalRequestMessage"/> message received
  271. /// </summary>
  272. internal event EventHandler<MessageEventArgs<GlobalRequestMessage>> GlobalRequestReceived;
  273. /// <summary>
  274. /// Occurs when <see cref="RequestSuccessMessage"/> message received
  275. /// </summary>
  276. internal event EventHandler<MessageEventArgs<RequestSuccessMessage>> RequestSuccessReceived;
  277. /// <summary>
  278. /// Occurs when <see cref="RequestFailureMessage"/> message received
  279. /// </summary>
  280. internal event EventHandler<MessageEventArgs<RequestFailureMessage>> RequestFailureReceived;
  281. /// <summary>
  282. /// Occurs when <see cref="ChannelOpenMessage"/> message received
  283. /// </summary>
  284. internal event EventHandler<MessageEventArgs<ChannelOpenMessage>> ChannelOpenReceived;
  285. /// <summary>
  286. /// Occurs when <see cref="ChannelOpenConfirmationMessage"/> message received
  287. /// </summary>
  288. internal event EventHandler<MessageEventArgs<ChannelOpenConfirmationMessage>> ChannelOpenConfirmationReceived;
  289. /// <summary>
  290. /// Occurs when <see cref="ChannelOpenFailureMessage"/> message received
  291. /// </summary>
  292. internal event EventHandler<MessageEventArgs<ChannelOpenFailureMessage>> ChannelOpenFailureReceived;
  293. /// <summary>
  294. /// Occurs when <see cref="ChannelWindowAdjustMessage"/> message received
  295. /// </summary>
  296. internal event EventHandler<MessageEventArgs<ChannelWindowAdjustMessage>> ChannelWindowAdjustReceived;
  297. /// <summary>
  298. /// Occurs when <see cref="ChannelDataMessage"/> message received
  299. /// </summary>
  300. internal event EventHandler<MessageEventArgs<ChannelDataMessage>> ChannelDataReceived;
  301. /// <summary>
  302. /// Occurs when <see cref="ChannelExtendedDataMessage"/> message received
  303. /// </summary>
  304. internal event EventHandler<MessageEventArgs<ChannelExtendedDataMessage>> ChannelExtendedDataReceived;
  305. /// <summary>
  306. /// Occurs when <see cref="ChannelEofMessage"/> message received
  307. /// </summary>
  308. internal event EventHandler<MessageEventArgs<ChannelEofMessage>> ChannelEofReceived;
  309. /// <summary>
  310. /// Occurs when <see cref="ChannelCloseMessage"/> message received
  311. /// </summary>
  312. internal event EventHandler<MessageEventArgs<ChannelCloseMessage>> ChannelCloseReceived;
  313. /// <summary>
  314. /// Occurs when <see cref="ChannelRequestMessage"/> message received
  315. /// </summary>
  316. internal event EventHandler<MessageEventArgs<ChannelRequestMessage>> ChannelRequestReceived;
  317. /// <summary>
  318. /// Occurs when <see cref="ChannelSuccessMessage"/> message received
  319. /// </summary>
  320. internal event EventHandler<MessageEventArgs<ChannelSuccessMessage>> ChannelSuccessReceived;
  321. /// <summary>
  322. /// Occurs when <see cref="ChannelFailureMessage"/> message received
  323. /// </summary>
  324. internal event EventHandler<MessageEventArgs<ChannelFailureMessage>> ChannelFailureReceived;
  325. /// <summary>
  326. /// Occurs when message received and is not handled by any of the event handlers
  327. /// </summary>
  328. internal event EventHandler<MessageEventArgs<Message>> MessageReceived;
  329. #endregion
  330. /// <summary>
  331. /// Initializes a new instance of the <see cref="Session"/> class.
  332. /// </summary>
  333. /// <param name="connectionInfo">The connection info.</param>
  334. internal Session(ConnectionInfo connectionInfo)
  335. {
  336. this.ConnectionInfo = connectionInfo;
  337. //this.ClientVersion = string.Format(CultureInfo.CurrentCulture, "SSH-2.0-Renci.SshNet.SshClient.{0}", this.GetType().Assembly.GetName().Version);
  338. this.ClientVersion = string.Format(CultureInfo.CurrentCulture, "SSH-2.0-Renci.SshNet.SshClient.0.0.1");
  339. }
  340. /// <summary>
  341. /// Connects to the server.
  342. /// </summary>
  343. public void Connect()
  344. {
  345. // TODO: Add exception documentation for Proxy.
  346. if (this.ConnectionInfo == null)
  347. {
  348. throw new ArgumentNullException("connectionInfo");
  349. }
  350. if (this.IsConnected)
  351. return;
  352. try
  353. {
  354. _authenticationConnection.Wait();
  355. if (this.IsConnected)
  356. return;
  357. lock (this)
  358. {
  359. // If connected don't connect again
  360. if (this.IsConnected)
  361. return;
  362. // Build list of available messages while connecting
  363. this._messagesMetadata = GetMessagesMetadata();
  364. switch (this.ConnectionInfo.ProxyType)
  365. {
  366. case ProxyTypes.None:
  367. this.SocketConnect(this.ConnectionInfo.Host, this.ConnectionInfo.Port);
  368. break;
  369. case ProxyTypes.Socks4:
  370. this.SocketConnect(this.ConnectionInfo.ProxyHost, this.ConnectionInfo.ProxyPort);
  371. this.ConnectSocks4(this._socket);
  372. break;
  373. case ProxyTypes.Socks5:
  374. this.SocketConnect(this.ConnectionInfo.ProxyHost, this.ConnectionInfo.ProxyPort);
  375. this.ConnectSocks5(this._socket);
  376. break;
  377. case ProxyTypes.Http:
  378. this.SocketConnect(this.ConnectionInfo.ProxyHost, this.ConnectionInfo.ProxyPort);
  379. this.ConnectHttp(this._socket);
  380. break;
  381. default:
  382. break;
  383. }
  384. Match versionMatch = null;
  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.WaitHandle(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.WaitHandle(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 WaitHandle(WaitHandle waitHandle)
  515. {
  516. var waitHandles = new WaitHandle[]
  517. {
  518. this._exceptionWaitHandle,
  519. waitHandle,
  520. };
  521. var index = EventWaitHandle.WaitAny(waitHandles, this.ConnectionInfo.Timeout);
  522. if (index < 1)
  523. {
  524. throw this._exception;
  525. }
  526. else if (index > 1)
  527. {
  528. this.SendDisconnect(DisconnectReason.ByApplication, "Operation timeout");
  529. throw new SshOperationTimeoutException("Session operation has timed out");
  530. }
  531. }
  532. /// <summary>
  533. /// Sends packet message to the server.
  534. /// </summary>
  535. /// <param name="message">The message.</param>
  536. internal void SendMessage(Message message)
  537. {
  538. if (this._socket == null || !this._socket.Connected)
  539. return;
  540. if (this._keyExchangeInProgress && !(message is IKeyExchangedAllowed))
  541. {
  542. // Wait for key exchange to be completed
  543. this.WaitHandle(this._keyExchangeCompletedWaitHandle);
  544. }
  545. this.Log(string.Format("SendMessage to server '{0}': '{1}'.", message.GetType().Name, message.ToString()));
  546. // Messages can be sent by different thread so we need to synchronize it
  547. var paddingMultiplier = this._clientCipher == null ? (byte)8 : (byte)this._clientCipher.BlockSize; // Should be recalculate base on cipher min length if cipher specified
  548. var messageData = message.GetBytes();
  549. if (messageData.Length > Session.MAXIMUM_PAYLOAD_SIZE)
  550. {
  551. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Payload cannot be more then {0} bytes.", Session.MAXIMUM_PAYLOAD_SIZE));
  552. }
  553. if (this._clientCompression != null)
  554. {
  555. messageData = this._clientCompression.Compress(messageData);
  556. }
  557. var packetLength = messageData.Length + 4 + 1; // add length bytes and padding byte
  558. byte paddingLength = (byte)((-packetLength) & (paddingMultiplier - 1));
  559. if (paddingLength < paddingMultiplier)
  560. {
  561. paddingLength += paddingMultiplier;
  562. }
  563. // Build Packet data
  564. var packetData = new byte[4 + 1 + messageData.Length + paddingLength];
  565. // Add packet length
  566. ((uint)packetData.Length - 4).GetBytes().CopyTo(packetData, 0);
  567. // Add packet padding length
  568. packetData[4] = paddingLength;
  569. // Add packet payload
  570. messageData.CopyTo(packetData, 4 + 1);
  571. // Add random padding
  572. var paddingBytes = new byte[paddingLength];
  573. _randomizer.GetBytes(paddingBytes);
  574. paddingBytes.CopyTo(packetData, 4 + 1 + messageData.Length);
  575. // Lock handling of _outboundPacketSequence since it must be sent sequently to server
  576. lock (this._socket)
  577. {
  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._socket);
  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></returns>
  653. private Message ReceiveMessage()
  654. {
  655. if (!this._socket.Connected)
  656. return null;
  657. // No lock needed since all messages read by only one thread
  658. var blockSize = this._serverCipher == null ? (byte)8 : (byte)this._serverCipher.BlockSize;
  659. // Read packet length first
  660. var firstBlock = this.Read(blockSize);
  661. if (this._serverCipher != null)
  662. {
  663. firstBlock = this._serverCipher.Decrypt(firstBlock);
  664. }
  665. var packetLength = (uint)(firstBlock[0] << 24 | firstBlock[1] << 16 | firstBlock[2] << 8 | firstBlock[3]);
  666. // Test packet minimum and maximum boundaries
  667. if (packetLength < Math.Max((byte)16, blockSize) - 4 || packetLength > Session.MAXIMUM_PACKET_SIZE - 4)
  668. throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length {0}", packetLength), DisconnectReason.ProtocolError);
  669. // Read rest of the packet data
  670. int bytesToRead = (int)(packetLength - (blockSize - 4));
  671. var data = new byte[bytesToRead + blockSize];
  672. firstBlock.CopyTo(data, 0);
  673. byte[] serverHash = null;
  674. if (this._serverMac != null)
  675. {
  676. serverHash = new byte[this._serverMac.HashSize / 8];
  677. bytesToRead += serverHash.Length;
  678. }
  679. if (bytesToRead > 0)
  680. {
  681. var nextBlocks = this.Read(bytesToRead);
  682. if (serverHash != null)
  683. {
  684. Buffer.BlockCopy(nextBlocks, nextBlocks.Length - serverHash.Length, serverHash, 0, serverHash.Length);
  685. nextBlocks = nextBlocks.Take(nextBlocks.Length - serverHash.Length).ToArray();
  686. }
  687. if (nextBlocks.Length > 0)
  688. {
  689. if (this._serverCipher != null)
  690. {
  691. nextBlocks = this._serverCipher.Decrypt(nextBlocks);
  692. }
  693. nextBlocks.CopyTo(data, blockSize);
  694. }
  695. }
  696. var paddingLength = data[4];
  697. var messagePayload = new byte[packetLength - paddingLength - 1];
  698. Buffer.BlockCopy(data, 5, messagePayload, 0, messagePayload.Length);
  699. if (this._serverDecompression != null)
  700. {
  701. messagePayload = this._serverDecompression.Decompress(messagePayload);
  702. }
  703. // Validate message against MAC
  704. if (this._serverMac != null)
  705. {
  706. var clientHashData = new byte[4 + data.Length];
  707. var lengthBytes = this._inboundPacketSequence.GetBytes();
  708. lengthBytes.CopyTo(clientHashData, 0);
  709. data.CopyTo(clientHashData, 4);
  710. // Calculate packet hash
  711. var clientHash = this._serverMac.ComputeHash(clientHashData);
  712. if (!serverHash.SequenceEqual(clientHash))
  713. {
  714. throw new SshConnectionException("MAC error", DisconnectReason.MacError);
  715. }
  716. }
  717. this._inboundPacketSequence++;
  718. return this.LoadMessage(messagePayload);
  719. }
  720. private void SendDisconnect(DisconnectReason reasonCode, string message)
  721. {
  722. // If disconnect message was sent already dont send it again
  723. if (this._isDisconnectMessageSent)
  724. return;
  725. var disconnectMessage = new DisconnectMessage(reasonCode, message);
  726. this.SendMessage(disconnectMessage);
  727. this._isDisconnectMessageSent = true;
  728. }
  729. partial void HandleMessageCore(Message message);
  730. /// <summary>
  731. /// Handles the message.
  732. /// </summary>
  733. /// <typeparam name="T"></typeparam>
  734. /// <param name="message">The message.</param>
  735. private void HandleMessage<T>(T message) where T : Message
  736. {
  737. this.OnMessageReceived(message);
  738. }
  739. #region Handle transport messages
  740. private void HandleMessage(DisconnectMessage message)
  741. {
  742. this.OnDisconnectReceived(message);
  743. // Shutdown and disconnect from the socket
  744. if (this._socket != null)
  745. {
  746. lock (this._socket)
  747. {
  748. if (this._socket != null)
  749. {
  750. this.SocketDisconnect();
  751. // When socket is disconnected wait for listener to finish
  752. if (this._messageListenerCompleted != null)
  753. {
  754. // Wait for listener task to finish
  755. this._messageListenerCompleted.WaitOne();
  756. this._messageListenerCompleted.Dispose();
  757. this._messageListenerCompleted = null;
  758. }
  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("Disconnect received.");
  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 SocketConnect(string host, int port);
  1293. partial void SocketDisconnect();
  1294. partial void SocketRead(int length, ref byte[] buffer);
  1295. partial void SocketReadLine(ref string response);
  1296. partial void Log(string text);
  1297. /// <summary>
  1298. /// Writes the specified data to the server.
  1299. /// </summary>
  1300. /// <param name="data">The data.</param>
  1301. partial void SocketWrite(byte[] data);
  1302. /// <summary>
  1303. /// Listens for incoming message from the server and handles them. This method run as a task on separate thread.
  1304. /// </summary>
  1305. private void MessageListener()
  1306. {
  1307. try
  1308. {
  1309. while (this._socket.Connected)
  1310. {
  1311. var message = this.ReceiveMessage();
  1312. if (message == null)
  1313. {
  1314. throw new NullReferenceException("The 'message' variable cannot be null");
  1315. }
  1316. this.HandleMessageCore(message);
  1317. }
  1318. }
  1319. catch (Exception exp)
  1320. {
  1321. this.RaiseError(exp);
  1322. }
  1323. }
  1324. private byte SocketReadByte()
  1325. {
  1326. byte[] buffer = new byte[1];
  1327. this.SocketRead(1, ref buffer);
  1328. return buffer[0];
  1329. }
  1330. private void SocketWriteByte(byte data)
  1331. {
  1332. this.SocketWrite(new byte[] { data });
  1333. }
  1334. private void ConnectSocks4(Socket socket)
  1335. {
  1336. // Send socks version number
  1337. this.SocketWriteByte(0x04);
  1338. // Send command code
  1339. this.SocketWriteByte(0x01);
  1340. // Send port
  1341. this.SocketWriteByte((byte)(this.ConnectionInfo.Port / 0xFF));
  1342. this.SocketWriteByte((byte)(this.ConnectionInfo.Port % 0xFF));
  1343. // Send IP
  1344. IPAddress ipAddress;
  1345. #if SILVERLIGHT
  1346. if (!IPAddress.TryParse(this.ConnectionInfo.Host, out ipAddress))
  1347. {
  1348. throw new ProxyException("SOCKS4: Silverlight supports only IP addresses.");
  1349. }
  1350. #else
  1351. ipAddress = Dns.GetHostAddresses(this.ConnectionInfo.Host).First();
  1352. #endif
  1353. this.SocketWrite(ipAddress.GetAddressBytes());
  1354. // Send username
  1355. var username = new Renci.SshNet.Common.ASCIIEncoding().GetBytes(this.ConnectionInfo.ProxyUsername);
  1356. this.SocketWrite(username);
  1357. this.SocketWriteByte(0x00);
  1358. // Read 0
  1359. if (this.SocketReadByte() != 0)
  1360. {
  1361. throw new ProxyException("SOCKS4: Null is expected.");
  1362. }
  1363. // Read response code
  1364. var code = this.SocketReadByte();
  1365. switch (code)
  1366. {
  1367. case 0x5a:
  1368. break;
  1369. case 0x5b:
  1370. throw new ProxyException("SOCKS4: Connection rejected.");
  1371. case 0x5c:
  1372. throw new ProxyException("SOCKS4: Client is not running identd or not reachable from the server.");
  1373. case 0x5d:
  1374. throw new ProxyException("SOCKS4: Client's identd could not confirm the user ID string in the request.");
  1375. default:
  1376. throw new ProxyException("SOCKS4: Not valid response.");
  1377. }
  1378. byte[] dummyBuffer = new byte[4];
  1379. // Read 2 bytes to be ignored
  1380. this.SocketRead(2, ref dummyBuffer);
  1381. // Read 4 bytes to be ignored
  1382. this.SocketRead(4, ref dummyBuffer);
  1383. }
  1384. private void ConnectSocks5(Socket socket)
  1385. {
  1386. // Send socks version number
  1387. this.SocketWriteByte(0x05);
  1388. // Send number of supported authentication methods
  1389. this.SocketWriteByte(0x02);
  1390. // Send supported authentication methods
  1391. this.SocketWriteByte(0x00); // No authentication
  1392. this.SocketWriteByte(0x02); // Username/Password
  1393. var socksVersion = this.SocketReadByte();
  1394. if (socksVersion != 0x05)
  1395. throw new ProxyException(string.Format("SOCKS Version '{0}' is not supported.", socksVersion));
  1396. var authenticationMethod = this.SocketReadByte();
  1397. switch (authenticationMethod)
  1398. {
  1399. case 0x00:
  1400. break;
  1401. case 0x02:
  1402. // Send version
  1403. this.SocketWriteByte(0x01);
  1404. var encoding = new Renci.SshNet.Common.ASCIIEncoding();
  1405. var username = encoding.GetBytes(this.ConnectionInfo.ProxyUsername);
  1406. if (username.Length > byte.MaxValue)
  1407. throw new ProxyException("Proxy username is too long.");
  1408. // Send username length
  1409. this.SocketWriteByte((byte)username.Length);
  1410. // Send username
  1411. this.SocketWrite(username);
  1412. var password = encoding.GetBytes(this.ConnectionInfo.ProxyPassword);
  1413. if (password.Length > byte.MaxValue)
  1414. throw new ProxyException("Proxy password is too long.");
  1415. // Send username length
  1416. this.SocketWriteByte((byte)password.Length);
  1417. // Send username
  1418. this.SocketWrite(password);
  1419. var serverVersion = this.SocketReadByte();
  1420. if (serverVersion != 1)
  1421. throw new ProxyException("SOCKS5: Server authentication version is not valid.");
  1422. var statusCode = this.SocketReadByte();
  1423. if (statusCode != 0)
  1424. throw new ProxyException("SOCKS5: Username/Password authentication failed.");
  1425. break;
  1426. case 0xFF:
  1427. throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
  1428. default:
  1429. break;
  1430. }
  1431. // Send socks version number
  1432. this.SocketWriteByte(0x05);
  1433. // Send command code
  1434. this.SocketWriteByte(0x01); // establish a TCP/IP stream connection
  1435. // Send reserved, must be 0x00
  1436. this.SocketWriteByte(0x00);
  1437. IPAddress ip;
  1438. #if SILVERLIGHT
  1439. if (!IPAddress.TryParse(this.ConnectionInfo.Host, out ip))
  1440. {
  1441. throw new ProxyException("SOCKS4: Silverlight supports only IP addresses.");
  1442. }
  1443. #else
  1444. ip = Dns.GetHostAddresses(this.ConnectionInfo.Host).First();
  1445. #endif
  1446. // Send address type and address
  1447. if (ip.AddressFamily == AddressFamily.InterNetwork)
  1448. {
  1449. this.SocketWriteByte(0x01);
  1450. var address = ip.GetAddressBytes();
  1451. this.SocketWrite(address);
  1452. }
  1453. else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
  1454. {
  1455. this.SocketWriteByte(0x04);
  1456. var address = ip.GetAddressBytes();
  1457. this.SocketWrite(address);
  1458. }
  1459. else
  1460. {
  1461. throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
  1462. }
  1463. // Send port
  1464. this.SocketWriteByte((byte)(this.ConnectionInfo.Port / 0xFF));
  1465. this.SocketWriteByte((byte)(this.ConnectionInfo.Port % 0xFF));
  1466. // Read Server SOCKS5 version
  1467. if (this.SocketReadByte() != 5)
  1468. {
  1469. throw new ProxyException("SOCKS5: Version 5 is expected.");
  1470. }
  1471. // Read response code
  1472. var status = this.SocketReadByte();
  1473. switch (status)
  1474. {
  1475. case 0x00:
  1476. break;
  1477. case 0x01:
  1478. throw new ProxyException("SOCKS5: General failure.");
  1479. case 0x02:
  1480. throw new ProxyException("SOCKS5: Connection not allowed by ruleset.");
  1481. case 0x03:
  1482. throw new ProxyException("SOCKS5: Network unreachable.");
  1483. case 0x04:
  1484. throw new ProxyException("SOCKS5: Host unreachable.");
  1485. case 0x05:
  1486. throw new ProxyException("SOCKS5: Connection refused by destination host.");
  1487. case 0x06:
  1488. throw new ProxyException("SOCKS5: TTL expired.");
  1489. case 0x07:
  1490. throw new ProxyException("SOCKS5: Command not supported or protocol error.");
  1491. case 0x08:
  1492. throw new ProxyException("SOCKS5: Address type not supported.");
  1493. default:
  1494. throw new ProxyException("SOCKS4: Not valid response.");
  1495. }
  1496. // Read 0
  1497. if (this.SocketReadByte() != 0)
  1498. {
  1499. throw new ProxyException("SOCKS5: 0 byte is expected.");
  1500. }
  1501. var addressType = this.SocketReadByte();
  1502. byte[] responseIp = new byte[16];
  1503. switch (addressType)
  1504. {
  1505. case 0x01:
  1506. this.SocketRead(4, ref responseIp);
  1507. break;
  1508. case 0x04:
  1509. this.SocketRead(16, ref responseIp);
  1510. break;
  1511. default:
  1512. throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
  1513. }
  1514. byte[] port = new byte[2];
  1515. // Read 2 bytes to be ignored
  1516. this.SocketRead(2, ref port);
  1517. }
  1518. private void ConnectHttp(Socket socket)
  1519. {
  1520. var httpResponseRe = new Regex(@"HTTP/(?<version>\d[.]\d) (?<statusCode>\d{3}) (?<reasonPhrase>.+)$");
  1521. var httpHeaderRe = new Regex(@"(?<fieldName>[^\[\]()<>@,;:\""/?={} \t]+):(?<fieldValue>.+)?");
  1522. var encoding = new Renci.SshNet.Common.ASCIIEncoding();
  1523. this.SocketWrite(encoding.GetBytes(string.Format("CONNECT {0}:{1} HTTP/1.0\r\n", this.ConnectionInfo.Host, this.ConnectionInfo.Port)));
  1524. // Sent proxy authorization is specified
  1525. if (!string.IsNullOrEmpty(this.ConnectionInfo.ProxyUsername))
  1526. {
  1527. var authorization = string.Format("Proxy-Authorization: Basic {0}\r\n",
  1528. Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", this.ConnectionInfo.ProxyUsername, this.ConnectionInfo.ProxyPassword)))
  1529. );
  1530. this.SocketWrite(encoding.GetBytes(authorization));
  1531. }
  1532. this.SocketWrite(encoding.GetBytes("\r\n"));
  1533. var statusCode = 0;
  1534. var response = string.Empty;
  1535. var contentLength = 0;
  1536. while (true)
  1537. {
  1538. this.SocketReadLine(ref response);
  1539. System.Diagnostics.Debug.WriteLine(response);
  1540. var match = httpResponseRe.Match(response);
  1541. if (match.Success)
  1542. {
  1543. statusCode = int.Parse(match.Result("${statusCode}"));
  1544. continue;
  1545. }
  1546. else
  1547. {
  1548. match = httpHeaderRe.Match(response);
  1549. if (match.Success)
  1550. {
  1551. var fieldName = match.Result("${fieldName}");
  1552. if (fieldName.Equals("Content-Length", StringComparison.InvariantCultureIgnoreCase))
  1553. {
  1554. contentLength = int.Parse(match.Result("${fieldValue}"));
  1555. }
  1556. continue;
  1557. }
  1558. }
  1559. // Read response body if specified
  1560. if (string.IsNullOrEmpty(response) && contentLength > 0)
  1561. {
  1562. var contentBody = new byte[contentLength];
  1563. this.SocketRead(contentLength, ref contentBody);
  1564. }
  1565. if (statusCode == 200 && string.IsNullOrEmpty(response))
  1566. {
  1567. // Once all HTTP header information is read, exit
  1568. break;
  1569. }
  1570. else
  1571. {
  1572. var reasonPhrase = match.Result("${reasonPhrase}");
  1573. throw new ProxyException(string.Format("HTTP: Status code {0}, Reason \"{1}\"", statusCode, reasonPhrase));
  1574. }
  1575. }
  1576. }
  1577. /// <summary>
  1578. /// Raises the <see cref="ErrorOccured"/> event.
  1579. /// </summary>
  1580. /// <param name="exp">The exp.</param>
  1581. private void RaiseError(Exception exp)
  1582. {
  1583. var connectionException = exp as SshConnectionException;
  1584. // If connection exception was raised while isDisconnecting is true then this is expected
  1585. // case and should be ignore
  1586. if (connectionException != null && this._isDisconnecting)
  1587. return;
  1588. this._exception = exp;
  1589. this._exceptionWaitHandle.Set();
  1590. if (this.ErrorOccured != null)
  1591. {
  1592. this.ErrorOccured(this, new ExceptionEventArgs(exp));
  1593. }
  1594. if (connectionException != null && connectionException.DisconnectReason != DisconnectReason.ConnectionLost)
  1595. {
  1596. this.SendDisconnect(connectionException.DisconnectReason, exp.ToString());
  1597. }
  1598. }
  1599. #region IDisposable Members
  1600. private bool _disposed = false;
  1601. /// <summary>
  1602. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  1603. /// </summary>
  1604. public void Dispose()
  1605. {
  1606. Dispose(true);
  1607. GC.SuppressFinalize(this);
  1608. }
  1609. /// <summary>
  1610. /// Releases unmanaged and - optionally - managed resources
  1611. /// </summary>
  1612. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1613. protected virtual void Dispose(bool disposing)
  1614. {
  1615. // Check to see if Dispose has already been called.
  1616. if (!this._disposed)
  1617. {
  1618. // If disposing equals true, dispose all managed
  1619. // and unmanaged ResourceMessages.
  1620. if (disposing)
  1621. {
  1622. if (this._socket != null)
  1623. {
  1624. this._socket.Dispose();
  1625. this._socket = null;
  1626. }
  1627. if (this._messageListenerCompleted != null)
  1628. {
  1629. // Wait for socket to be closed and for task to complete before disposing a task
  1630. this._messageListenerCompleted.WaitOne();
  1631. this._messageListenerCompleted.Dispose();
  1632. this._messageListenerCompleted = null;
  1633. }
  1634. if (this._serviceAccepted != null)
  1635. {
  1636. this._serviceAccepted.Dispose();
  1637. this._serviceAccepted = null;
  1638. }
  1639. if (this._exceptionWaitHandle != null)
  1640. {
  1641. this._exceptionWaitHandle.Dispose();
  1642. this._exceptionWaitHandle = null;
  1643. }
  1644. if (this._keyExchangeCompletedWaitHandle != null)
  1645. {
  1646. this._keyExchangeCompletedWaitHandle.Dispose();
  1647. this._keyExchangeCompletedWaitHandle = null;
  1648. }
  1649. if (this._serverMac != null)
  1650. {
  1651. this._serverMac.Clear();
  1652. this._serverMac = null;
  1653. }
  1654. if (this._clientMac != null)
  1655. {
  1656. this._clientMac.Clear();
  1657. this._clientMac = null;
  1658. }
  1659. if (this._keyExchange != null)
  1660. {
  1661. this._keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
  1662. this._keyExchange.Dispose();
  1663. this._keyExchange = null;
  1664. }
  1665. }
  1666. // Note disposing has been done.
  1667. this._disposed = true;
  1668. }
  1669. }
  1670. /// <summary>
  1671. /// Releases unmanaged resources and performs other cleanup operations before the
  1672. /// <see cref="Session"/> is reclaimed by garbage collection.
  1673. /// </summary>
  1674. ~Session()
  1675. {
  1676. // Do not re-create Dispose clean-up code here.
  1677. // Calling Dispose(false) is optimal in terms of
  1678. // readability and maintainability.
  1679. Dispose(false);
  1680. }
  1681. #endregion
  1682. private class MessageMetadata
  1683. {
  1684. public string Name { get; set; }
  1685. public byte Number { get; set; }
  1686. public bool Enabled { get; set; }
  1687. public bool Activated { get; set; }
  1688. public Type Type { get; set; }
  1689. }
  1690. }
  1691. }