ConnectionInfo.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using Renci.SshNet.Security;
  6. using Renci.SshNet.Compression;
  7. using Renci.SshNet.Messages;
  8. using Renci.SshNet.Messages.Authentication;
  9. using Renci.SshNet.Common;
  10. using System.Threading;
  11. using System.Net;
  12. using Renci.SshNet.Messages.Connection;
  13. using Renci.SshNet.Security.Cryptography.Ciphers;
  14. using System.Security.Cryptography;
  15. using Renci.SshNet.Security.Cryptography;
  16. using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
  17. using System.Net.Sockets;
  18. using System.Text;
  19. namespace Renci.SshNet
  20. {
  21. /// <summary>
  22. /// Represents remote connection information base class.
  23. /// </summary>
  24. public abstract partial class ConnectionInfo
  25. {
  26. /// <summary>
  27. /// Gets connection name
  28. /// </summary>
  29. public abstract string Name { get; }
  30. /// <summary>
  31. /// Gets a value indicating whether connection is authenticated.
  32. /// </summary>
  33. /// <value>
  34. /// <c>true</c> if connection is authenticated; otherwise, <c>false</c>.
  35. /// </value>
  36. public bool IsAuthenticated { get; private set; }
  37. /// <summary>
  38. /// Gets the authentication error message.
  39. /// </summary>
  40. public string ErrorMessage { get; private set; }
  41. /// <summary>
  42. /// Gets reference to the session object.
  43. /// </summary>
  44. protected Session Session { get; private set; }
  45. /// <summary>
  46. /// Gets supported key exchange algorithms for this connection.
  47. /// </summary>
  48. public IDictionary<string, Type> KeyExchangeAlgorithms { get; private set; }
  49. /// <summary>
  50. /// Gets supported encryptions for this connection.
  51. /// </summary>
  52. public IDictionary<string, CipherInfo> Encryptions { get; private set; }
  53. /// <summary>
  54. /// Gets supported hash algorithms for this connection.
  55. /// </summary>
  56. public IDictionary<string, Func<byte[], HashAlgorithm>> HmacAlgorithms { get; private set; }
  57. /// <summary>
  58. /// Gets supported host key algorithms for this connection.
  59. /// </summary>
  60. public IDictionary<string, Func<byte[], HostAlgorithm>> HostKeyAlgorithms { get; private set; }
  61. /// <summary>
  62. /// Gets supported authentication methods for this connection.
  63. /// </summary>
  64. public IDictionary<string, Type> AuthenticationMethods { get; private set; }
  65. /// <summary>
  66. /// Gets supported compression algorithms for this connection.
  67. /// </summary>
  68. public IDictionary<string, Type> CompressionAlgorithms { get; private set; }
  69. /// <summary>
  70. /// Gets supported channel requests for this connection.
  71. /// </summary>
  72. public IDictionary<string, RequestInfo> ChannelRequests { get; private set; }
  73. /// <summary>
  74. /// Gets connection host.
  75. /// </summary>
  76. public string Host { get; private set; }
  77. /// <summary>
  78. /// Gets connection port.
  79. /// </summary>
  80. public int Port { get; private set; }
  81. /// <summary>
  82. /// Gets connection username.
  83. /// </summary>
  84. public string Username { get; private set; }
  85. /// <summary>
  86. /// Gets proxy type.
  87. /// </summary>
  88. /// <value>
  89. /// The type of the proxy.
  90. /// </value>
  91. public ProxyTypes ProxyType { get; private set; }
  92. /// <summary>
  93. /// Gets proxy connection host.
  94. /// </summary>
  95. public string ProxyHost { get; private set; }
  96. /// <summary>
  97. /// Gets proxy connection port.
  98. /// </summary>
  99. public int ProxyPort { get; private set; }
  100. /// <summary>
  101. /// Gets proxy connection username.
  102. /// </summary>
  103. public string ProxyUsername { get; private set; }
  104. /// <summary>
  105. /// Gets proxy connection password.
  106. /// </summary>
  107. public string ProxyPassword { get; private set; }
  108. /// <summary>
  109. /// Gets or sets connection timeout.
  110. /// </summary>
  111. /// <value>
  112. /// Connection timeout.
  113. /// </value>
  114. public TimeSpan Timeout { get; set; }
  115. /// <summary>
  116. /// Gets or sets number of retry attempts when session channel creation failed.
  117. /// </summary>
  118. /// <value>
  119. /// Number of retry attempts.
  120. /// </value>
  121. public int RetryAttempts { get; set; }
  122. /// <summary>
  123. /// Gets or sets maximum number of session channels to be open simultaneously.
  124. /// </summary>
  125. /// <value>
  126. /// The max sessions.
  127. /// </value>
  128. public int MaxSessions { get; set; }
  129. /// <summary>
  130. /// Occurs when authentication banner is sent by the server.
  131. /// </summary>
  132. public event EventHandler<AuthenticationBannerEventArgs> AuthenticationBanner;
  133. /// <summary>
  134. /// Gets the current key exchange algorithm.
  135. /// </summary>
  136. public string CurrentKeyExchangeAlgorithm { get; internal set; }
  137. /// <summary>
  138. /// Gets the current server encryption.
  139. /// </summary>
  140. public string CurrentServerEncryption { get; internal set; }
  141. /// <summary>
  142. /// Gets the current client encryption.
  143. /// </summary>
  144. public string CurrentClientEncryption { get; internal set; }
  145. /// <summary>
  146. /// Gets the current server hash algorithm.
  147. /// </summary>
  148. public string CurrentServerHmacAlgorithm { get; internal set; }
  149. /// <summary>
  150. /// Gets the current client hash algorithm.
  151. /// </summary>
  152. public string CurrentClientHmacAlgorithm { get; internal set; }
  153. /// <summary>
  154. /// Gets the current host key algorithm.
  155. /// </summary>
  156. public string CurrentHostKeyAlgorithm { get; internal set; }
  157. /// <summary>
  158. /// Gets the current server compression algorithm.
  159. /// </summary>
  160. public string CurrentServerCompressionAlgorithm { get; internal set; }
  161. /// <summary>
  162. /// Gets the current client compression algorithm.
  163. /// </summary>
  164. public string CurrentClientCompressionAlgorithm { get; internal set; }
  165. /// <summary>
  166. /// Prevents a default instance of the <see cref="ConnectionInfo"/> class from being created.
  167. /// </summary>
  168. private ConnectionInfo()
  169. {
  170. // Set default connection values
  171. this.Timeout = TimeSpan.FromSeconds(30);
  172. this.RetryAttempts = 10;
  173. this.MaxSessions = 10;
  174. this.KeyExchangeAlgorithms = new Dictionary<string, Type>()
  175. {
  176. {"diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256)},
  177. {"diffie-hellman-group-exchange-sha1", typeof(KeyExchangeDiffieHellmanGroupExchangeSha1)},
  178. {"diffie-hellman-group14-sha1", typeof(KeyExchangeDiffieHellmanGroup14Sha1)},
  179. {"diffie-hellman-group1-sha1", typeof(KeyExchangeDiffieHellmanGroup1Sha1)},
  180. };
  181. this.Encryptions = new Dictionary<string, CipherInfo>()
  182. {
  183. {"3des-cbc", new CipherInfo(192, (key, iv)=>{ return new TripleDesCipher(key, new CbcCipherMode(iv), null); }) },
  184. {"aes128-cbc", new CipherInfo(128, (key, iv)=>{ return new AesCipher(key, new CbcCipherMode(iv), null); }) },
  185. {"aes192-cbc", new CipherInfo(192, (key, iv)=>{ return new AesCipher(key, new CbcCipherMode(iv), null); }) },
  186. {"aes256-cbc", new CipherInfo(256, (key, iv)=>{ return new AesCipher(key, new CbcCipherMode(iv), null); }) },
  187. {"blowfish-cbc", new CipherInfo(128, (key, iv)=>{ return new BlowfishCipher(key, new CbcCipherMode(iv), null); }) },
  188. ////{"twofish-cbc", typeof(...)},
  189. ////{"twofish192-cbc", typeof(...)},
  190. ////{"twofish128-cbc", typeof(...)},
  191. ////{"twofish256-cbc", typeof(...)},
  192. ////{"serpent256-cbc", typeof(CipherSerpent256CBC)},
  193. ////{"serpent192-cbc", typeof(...)},
  194. ////{"serpent128-cbc", typeof(...)},
  195. ////{"arcfour128", typeof(...)},
  196. ////{"arcfour256", typeof(...)},
  197. ////{"arcfour", typeof(...)},
  198. ////{"idea-cbc", typeof(...)},
  199. {"cast128-cbc", new CipherInfo(128, (key, iv)=>{ return new CastCipher(key, new CbcCipherMode(iv), null); }) },
  200. ////{"rijndael-cbc@lysator.liu.se", typeof(...)},
  201. {"aes128-ctr", new CipherInfo(128, (key, iv)=>{ return new AesCipher(key, new CtrCipherMode(iv), null); }) },
  202. {"aes192-ctr", new CipherInfo(192, (key, iv)=>{ return new AesCipher(key, new CtrCipherMode(iv), null); }) },
  203. {"aes256-ctr", new CipherInfo(256, (key, iv)=>{ return new AesCipher(key, new CtrCipherMode(iv), null); }) },
  204. };
  205. this.HmacAlgorithms = new Dictionary<string, Func<byte[], HashAlgorithm>>()
  206. {
  207. {"hmac-md5", (key) => { return new HMac<MD5Hash>(key.Take(16).ToArray());}},
  208. {"hmac-sha1", (key) => { return new HMac<SHA1Hash>(key.Take(20).ToArray());}},
  209. //{"umac-64@openssh.com", typeof(HMacSha1)},
  210. //{"hmac-ripemd160", typeof(HMacSha1)},
  211. //{"hmac-ripemd160@openssh.com", typeof(HMacSha1)},
  212. //{"hmac-md5-96", typeof(...)},
  213. //{"hmac-sha1-96", typeof(...)},
  214. //{"none", typeof(...)},
  215. };
  216. this.HostKeyAlgorithms = new Dictionary<string, Func<byte[], HostAlgorithm>>()
  217. {
  218. {"ssh-rsa", (data) => { return new KeyHostAlgorithm("ssh-rsa", new RsaKey(), data); }},
  219. {"ssh-dss", (data) => { return new KeyHostAlgorithm("ssh-dss", new DsaKey(), data); }},
  220. //{"x509v3-sign-rsa", () => { ... },
  221. //{"x509v3-sign-dss", () => { ... },
  222. //{"spki-sign-rsa", () => { ... },
  223. //{"spki-sign-dss", () => { ... },
  224. //{"pgp-sign-rsa", () => { ... },
  225. //{"pgp-sign-dss", () => { ... },
  226. };
  227. this.AuthenticationMethods = new Dictionary<string, Type>()
  228. {
  229. {"none", typeof(ConnectionInfo)},
  230. {"publickey", typeof(PrivateKeyConnectionInfo)},
  231. {"password", typeof(PasswordConnectionInfo)},
  232. {"keyboard-interactive", typeof(KeyboardInteractiveConnectionInfo)},
  233. //{"hostbased", typeof(...)},
  234. //{"gssapi-keyex", typeof(...)},
  235. //{"gssapi-with-mic", typeof(...)},
  236. };
  237. this.CompressionAlgorithms = new Dictionary<string, Type>()
  238. {
  239. {"none", null},
  240. //{"zlib", typeof(Zlib)},
  241. //{"zlib@openssh.com", typeof(ZlibOpenSsh)},
  242. };
  243. this.ChannelRequests = new Dictionary<string, RequestInfo>()
  244. {
  245. {EnvironmentVariableRequestInfo.NAME, new EnvironmentVariableRequestInfo()},
  246. {ExecRequestInfo.NAME, new ExecRequestInfo()},
  247. {ExitSignalRequestInfo.NAME, new ExitSignalRequestInfo()},
  248. {ExitStatusRequestInfo.NAME, new ExitStatusRequestInfo()},
  249. {PseudoTerminalRequestInfo.NAME, new PseudoTerminalRequestInfo()},
  250. {ShellRequestInfo.NAME, new ShellRequestInfo()},
  251. {SignalRequestInfo.NAME, new SignalRequestInfo()},
  252. {SubsystemRequestInfo.NAME, new SubsystemRequestInfo()},
  253. {WindowChangeRequestInfo.NAME, new WindowChangeRequestInfo()},
  254. {X11ForwardingRequestInfo.NAME, new X11ForwardingRequestInfo()},
  255. {XonXoffRequestInfo.NAME, new XonXoffRequestInfo()},
  256. {EndOfWriteRequestInfo.NAME, new EndOfWriteRequestInfo()},
  257. {KeepAliveRequestInfo.NAME, new KeepAliveRequestInfo()},
  258. };
  259. }
  260. /// <summary>
  261. /// Initializes a new instance of the <see cref="ConnectionInfo"/> class.
  262. /// </summary>
  263. /// <param name="host">Connection host.</param>
  264. /// <param name="port">Connection port.</param>
  265. /// <param name="username">Connection username.</param>
  266. /// <param name="proxyType">Type of the proxy.</param>
  267. /// <param name="proxyHost">The proxy host.</param>
  268. /// <param name="proxyPort">The proxy port.</param>
  269. /// <param name="proxyUsername">The proxy username.</param>
  270. /// <param name="proxyPassword">The proxy password.</param>
  271. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  272. ///
  273. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  274. ///
  275. /// <exception cref="ArgumentException"><paramref name="username"/> is null or empty.</exception>
  276. protected ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword)
  277. : this()
  278. {
  279. if (!host.IsValidHost())
  280. throw new ArgumentException("host");
  281. if (!string.IsNullOrEmpty(proxyHost) && !proxyHost.IsValidHost())
  282. throw new ArgumentException("proxyHost");
  283. if (!port.IsValidPort())
  284. throw new ArgumentOutOfRangeException("port");
  285. if (!proxyPort.IsValidPort())
  286. throw new ArgumentOutOfRangeException("proxyPort");
  287. if (username.IsNullOrWhiteSpace())
  288. throw new ArgumentException("username");
  289. this.Host = host;
  290. this.Port = port;
  291. this.Username = username;
  292. this.ProxyType = proxyType;
  293. this.ProxyHost = proxyHost;
  294. this.ProxyPort = proxyPort;
  295. this.ProxyUsername = proxyUsername;
  296. this.ProxyPassword = proxyPassword;
  297. }
  298. /// <summary>
  299. /// Authenticates the specified session.
  300. /// </summary>
  301. /// <param name="session">The session to be authenticated.</param>
  302. /// <returns>true if authenticated; otherwise false.</returns>
  303. /// <exception cref="ArgumentNullException"><paramref name="session"/> is null.</exception>
  304. public bool Authenticate(Session session)
  305. {
  306. if (session == null)
  307. throw new ArgumentNullException("session");
  308. this.Session = session;
  309. this.Session.RegisterMessage("SSH_MSG_USERAUTH_FAILURE");
  310. this.Session.RegisterMessage("SSH_MSG_USERAUTH_SUCCESS");
  311. this.Session.RegisterMessage("SSH_MSG_USERAUTH_BANNER");
  312. this.Session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  313. this.Session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessMessageReceived;
  314. this.Session.UserAuthenticationBannerReceived += Session_UserAuthenticationBannerMessageReceived;
  315. this.Session.MessageReceived += Session_MessageReceived;
  316. this.OnAuthenticate();
  317. this.Session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  318. this.Session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessMessageReceived;
  319. this.Session.UserAuthenticationBannerReceived -= Session_UserAuthenticationBannerMessageReceived;
  320. this.Session.MessageReceived -= Session_MessageReceived;
  321. this.Session.UnRegisterMessage("SSH_MSG_USERAUTH_FAILURE");
  322. this.Session.UnRegisterMessage("SSH_MSG_USERAUTH_SUCCESS");
  323. this.Session.UnRegisterMessage("SSH_MSG_USERAUTH_BANNER");
  324. return this.IsAuthenticated;
  325. }
  326. /// <summary>
  327. /// Called when connection needs to be authenticated.
  328. /// </summary>
  329. protected abstract void OnAuthenticate();
  330. /// <summary>
  331. /// Sends SSH message to the server.
  332. /// </summary>
  333. /// <param name="message">The message.</param>
  334. protected void SendMessage(Message message)
  335. {
  336. this.Session.SendMessage(message);
  337. }
  338. /// <summary>
  339. /// Waits the handle to signal.
  340. /// </summary>
  341. /// <param name="eventWaitHandle">The event wait handle.</param>
  342. protected void WaitHandle(WaitHandle eventWaitHandle)
  343. {
  344. this.Session.WaitHandle(eventWaitHandle);
  345. }
  346. /// <summary>
  347. /// Handles the UserAuthenticationFailureReceived event of the session.
  348. /// </summary>
  349. /// <param name="sender">The source of the event.</param>
  350. /// <param name="e">The event data.</param>
  351. protected virtual void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  352. {
  353. this.ErrorMessage = e.Message.Message;
  354. this.IsAuthenticated = false;
  355. }
  356. /// <summary>
  357. /// Handles the UserAuthenticationSuccessMessageReceived event of the session.
  358. /// </summary>
  359. /// <param name="sender">The source of the event.</param>
  360. /// <param name="e">The event data.</param>
  361. protected virtual void Session_UserAuthenticationSuccessMessageReceived(object sender, MessageEventArgs<SuccessMessage> e)
  362. {
  363. this.IsAuthenticated = true;
  364. }
  365. /// <summary>
  366. /// Handles the UserAuthenticationBannerMessageReceived event of the session.
  367. /// </summary>
  368. /// <param name="sender">The source of the event.</param>
  369. /// <param name="e">The event data.</param>
  370. protected virtual void Session_UserAuthenticationBannerMessageReceived(object sender, MessageEventArgs<BannerMessage> e)
  371. {
  372. if (this.AuthenticationBanner != null)
  373. {
  374. this.AuthenticationBanner(this, new AuthenticationBannerEventArgs(this.Username, e.Message.Message, e.Message.Language));
  375. }
  376. }
  377. /// <summary>
  378. /// Handles the MessageReceived event of the session.
  379. /// </summary>
  380. /// <param name="sender">The source of the event.</param>
  381. /// <param name="e">The event data.</param>
  382. protected virtual void Session_MessageReceived(object sender, MessageEventArgs<Message> e)
  383. {
  384. }
  385. }
  386. }