ConnectionInfo.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using Renci.SshNet.Security;
  7. using Renci.SshNet.Messages.Connection;
  8. using Renci.SshNet.Common;
  9. using Renci.SshNet.Messages.Authentication;
  10. using Renci.SshNet.Security.Cryptography;
  11. using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
  12. using Renci.SshNet.Security.Cryptography.Ciphers;
  13. namespace Renci.SshNet
  14. {
  15. /// <summary>
  16. /// Represents remote connection information class.
  17. /// </summary>
  18. /// <remarks>
  19. /// This class is NOT thread-safe. Do not use the same <see cref="ConnectionInfo"/> with multiple
  20. /// client instances.
  21. /// </remarks>
  22. public class ConnectionInfo : IConnectionInfo
  23. {
  24. internal static int DEFAULT_PORT = 22;
  25. /// <summary>
  26. /// Gets supported key exchange algorithms for this connection.
  27. /// </summary>
  28. public IDictionary<string, Type> KeyExchangeAlgorithms { get; private set; }
  29. /// <summary>
  30. /// Gets supported encryptions for this connection.
  31. /// </summary>
  32. public IDictionary<string, CipherInfo> Encryptions { get; private set; }
  33. /// <summary>
  34. /// Gets supported hash algorithms for this connection.
  35. /// </summary>
  36. public IDictionary<string, HashInfo> HmacAlgorithms { get; private set; }
  37. /// <summary>
  38. /// Gets supported host key algorithms for this connection.
  39. /// </summary>
  40. public IDictionary<string, Func<byte[], KeyHostAlgorithm>> HostKeyAlgorithms { get; private set; }
  41. /// <summary>
  42. /// Gets supported authentication methods for this connection.
  43. /// </summary>
  44. public IEnumerable<AuthenticationMethod> AuthenticationMethods { get; private set; }
  45. /// <summary>
  46. /// Gets supported compression algorithms for this connection.
  47. /// </summary>
  48. public IDictionary<string, Type> CompressionAlgorithms { get; private set; }
  49. /// <summary>
  50. /// Gets the supported channel requests for this connection.
  51. /// </summary>
  52. /// <value>
  53. /// The supported channel requests for this connection.
  54. /// </value>
  55. public IDictionary<string, RequestInfo> ChannelRequests { get; private set; }
  56. /// <summary>
  57. /// Gets a value indicating whether connection is authenticated.
  58. /// </summary>
  59. /// <value>
  60. /// <c>true</c> if connection is authenticated; otherwise, <c>false</c>.
  61. /// </value>
  62. public bool IsAuthenticated { get; private set; }
  63. /// <summary>
  64. /// Gets connection host.
  65. /// </summary>
  66. public string Host { get; private set; }
  67. /// <summary>
  68. /// Gets connection port.
  69. /// </summary>
  70. /// <value>
  71. /// The connection port. The default value is 22.
  72. /// </value>
  73. public int Port { get; private set; }
  74. /// <summary>
  75. /// Gets connection username.
  76. /// </summary>
  77. public string Username { get; private set; }
  78. /// <summary>
  79. /// Gets proxy type.
  80. /// </summary>
  81. /// <value>
  82. /// The type of the proxy.
  83. /// </value>
  84. public ProxyTypes ProxyType { get; private set; }
  85. /// <summary>
  86. /// Gets proxy connection host.
  87. /// </summary>
  88. public string ProxyHost { get; private set; }
  89. /// <summary>
  90. /// Gets proxy connection port.
  91. /// </summary>
  92. public int ProxyPort { get; private set; }
  93. /// <summary>
  94. /// Gets proxy connection username.
  95. /// </summary>
  96. public string ProxyUsername { get; private set; }
  97. /// <summary>
  98. /// Gets proxy connection password.
  99. /// </summary>
  100. public string ProxyPassword { get; private set; }
  101. /// <summary>
  102. /// Gets or sets connection timeout.
  103. /// </summary>
  104. /// <value>
  105. /// The connection timeout. The default value is 30 seconds.
  106. /// </value>
  107. /// <example>
  108. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect Timeout" language="C#" title="Specify connection timeout" />
  109. /// </example>
  110. public TimeSpan Timeout { get; set; }
  111. /// <summary>
  112. /// Gets or sets the character encoding.
  113. /// </summary>
  114. /// <value>
  115. /// The character encoding. The default is <see cref="System.Text.Encoding.UTF8"/>.
  116. /// </value>
  117. public Encoding Encoding { get; set; }
  118. /// <summary>
  119. /// Gets or sets number of retry attempts when session channel creation failed.
  120. /// </summary>
  121. /// <value>
  122. /// The number of retry attempts when session channel creation failed. The default
  123. /// value is 10.
  124. /// </value>
  125. public int RetryAttempts { get; set; }
  126. /// <summary>
  127. /// Gets or sets maximum number of session channels to be open simultaneously.
  128. /// </summary>
  129. /// <value>
  130. /// The maximum number of session channels to be open simultaneously. The default
  131. /// value is 10.
  132. /// </value>
  133. public int MaxSessions { get; set; }
  134. /// <summary>
  135. /// Occurs when authentication banner is sent by the server.
  136. /// </summary>
  137. /// <example>
  138. /// <code source="..\..\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo AuthenticationBanner" language="C#" title="Display authentication banner" />
  139. /// </example>
  140. public event EventHandler<AuthenticationBannerEventArgs> AuthenticationBanner;
  141. /// <summary>
  142. /// Gets the current key exchange algorithm.
  143. /// </summary>
  144. public string CurrentKeyExchangeAlgorithm { get; internal set; }
  145. /// <summary>
  146. /// Gets the current server encryption.
  147. /// </summary>
  148. public string CurrentServerEncryption { get; internal set; }
  149. /// <summary>
  150. /// Gets the current client encryption.
  151. /// </summary>
  152. public string CurrentClientEncryption { get; internal set; }
  153. /// <summary>
  154. /// Gets the current server hash algorithm.
  155. /// </summary>
  156. public string CurrentServerHmacAlgorithm { get; internal set; }
  157. /// <summary>
  158. /// Gets the current client hash algorithm.
  159. /// </summary>
  160. public string CurrentClientHmacAlgorithm { get; internal set; }
  161. /// <summary>
  162. /// Gets the current host key algorithm.
  163. /// </summary>
  164. public string CurrentHostKeyAlgorithm { get; internal set; }
  165. /// <summary>
  166. /// Gets the current server compression algorithm.
  167. /// </summary>
  168. public string CurrentServerCompressionAlgorithm { get; internal set; }
  169. /// <summary>
  170. /// Gets the server version.
  171. /// </summary>
  172. public string ServerVersion { get; internal set; }
  173. /// <summary>
  174. /// Get the client version.
  175. /// </summary>
  176. public string ClientVersion { get; internal set; }
  177. /// <summary>
  178. /// Gets the current client compression algorithm.
  179. /// </summary>
  180. public string CurrentClientCompressionAlgorithm { get; internal set; }
  181. /// <summary>
  182. /// Initializes a new instance of the <see cref="ConnectionInfo"/> class.
  183. /// </summary>
  184. /// <param name="host">The host.</param>
  185. /// <param name="username">The username.</param>
  186. /// <param name="authenticationMethods">The authentication methods.</param>
  187. /// <exception cref="ArgumentNullException"><paramref name="host"/> is <c>null</c>.</exception>
  188. /// <exception cref="ArgumentException"><paramref name="host"/> is a zero-length string.</exception>
  189. /// <exception cref="ArgumentException"><paramref name="username" /> is null, a zero-length string or contains only whitespace characters.</exception>
  190. /// <exception cref="ArgumentNullException"><paramref name="authenticationMethods"/> is <c>null</c>.</exception>
  191. /// <exception cref="ArgumentException">No <paramref name="authenticationMethods"/> specified.</exception>
  192. public ConnectionInfo(string host, string username, params AuthenticationMethod[] authenticationMethods)
  193. : this(host, DEFAULT_PORT, username, ProxyTypes.None, null, 0, null, null, authenticationMethods)
  194. {
  195. }
  196. /// <summary>
  197. /// Initializes a new instance of the <see cref="ConnectionInfo"/> class.
  198. /// </summary>
  199. /// <param name="host">The host.</param>
  200. /// <param name="port">The port.</param>
  201. /// <param name="username">The username.</param>
  202. /// <param name="authenticationMethods">The authentication methods.</param>
  203. /// <exception cref="ArgumentNullException"><paramref name="host"/> is <c>null</c>.</exception>
  204. /// <exception cref="ArgumentException"><paramref name="username" /> is null, a zero-length string or contains only whitespace characters.</exception>
  205. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is not within <see cref="F:System.Net.IPEndPoint.MinPort" /> and <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception>
  206. /// <exception cref="ArgumentNullException"><paramref name="authenticationMethods"/> is <c>null</c>.</exception>
  207. /// <exception cref="ArgumentException">No <paramref name="authenticationMethods"/> specified.</exception>
  208. public ConnectionInfo(string host, int port, string username, params AuthenticationMethod[] authenticationMethods)
  209. : this(host, port, username, ProxyTypes.None, null, 0, null, null, authenticationMethods)
  210. {
  211. }
  212. // TODO: DOCS Add exception documentation for this class.
  213. /// <summary>
  214. /// Initializes a new instance of the <see cref="ConnectionInfo" /> class.
  215. /// </summary>
  216. /// <param name="host">Connection host.</param>
  217. /// <param name="port">Connection port.</param>
  218. /// <param name="username">Connection username.</param>
  219. /// <param name="proxyType">Type of the proxy.</param>
  220. /// <param name="proxyHost">The proxy host.</param>
  221. /// <param name="proxyPort">The proxy port.</param>
  222. /// <param name="proxyUsername">The proxy username.</param>
  223. /// <param name="proxyPassword">The proxy password.</param>
  224. /// <param name="authenticationMethods">The authentication methods.</param>
  225. /// <exception cref="ArgumentNullException"><paramref name="host"/> is <c>null</c>.</exception>
  226. /// <exception cref="ArgumentException"><paramref name="username" /> is null, a zero-length string or contains only whitespace characters.</exception>
  227. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is not within <see cref="F:System.Net.IPEndPoint.MinPort" /> and <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception>
  228. /// <exception cref="ArgumentNullException"><paramref name="proxyType"/> is not <see cref="ProxyTypes.None"/> and <paramref name="proxyHost" /> is <c>null</c>.</exception>
  229. /// <exception cref="ArgumentOutOfRangeException"><paramref name="proxyType"/> is not <see cref="ProxyTypes.None"/> and <paramref name="proxyPort" /> is not within <see cref="F:System.Net.IPEndPoint.MinPort" /> and <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception>
  230. /// <exception cref="ArgumentNullException"><paramref name="authenticationMethods"/> is <c>null</c>.</exception>
  231. /// <exception cref="ArgumentException">No <paramref name="authenticationMethods"/> specified.</exception>
  232. public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params AuthenticationMethod[] authenticationMethods)
  233. {
  234. if (host == null)
  235. throw new ArgumentNullException("host");
  236. port.ValidatePort("port");
  237. if (username == null)
  238. throw new ArgumentNullException("username");
  239. if (username.All(char.IsWhiteSpace))
  240. throw new ArgumentException("Cannot be empty or contain only whitespace.", "username");
  241. if (proxyType != ProxyTypes.None)
  242. {
  243. if (proxyHost == null)
  244. throw new ArgumentNullException("proxyHost");
  245. proxyPort.ValidatePort("proxyPort");
  246. }
  247. if (authenticationMethods == null)
  248. throw new ArgumentNullException("authenticationMethods");
  249. if (!authenticationMethods.Any())
  250. throw new ArgumentException("At least one authentication method should be specified.", "authenticationMethods");
  251. // Set default connection values
  252. this.Timeout = TimeSpan.FromSeconds(30);
  253. this.RetryAttempts = 10;
  254. this.MaxSessions = 10;
  255. this.Encoding = Encoding.UTF8;
  256. this.KeyExchangeAlgorithms = new Dictionary<string, Type>
  257. {
  258. {"diffie-hellman-group-exchange-sha256", typeof (KeyExchangeDiffieHellmanGroupExchangeSha256)},
  259. {"diffie-hellman-group-exchange-sha1", typeof (KeyExchangeDiffieHellmanGroupExchangeSha1)},
  260. {"diffie-hellman-group14-sha1", typeof (KeyExchangeDiffieHellmanGroup14Sha1)},
  261. {"diffie-hellman-group1-sha1", typeof (KeyExchangeDiffieHellmanGroup1Sha1)},
  262. //{"ecdh-sha2-nistp256", typeof(KeyExchangeEllipticCurveDiffieHellman)},
  263. //{"ecdh-sha2-nistp256", typeof(...)},
  264. //{"ecdh-sha2-nistp384", typeof(...)},
  265. //{"ecdh-sha2-nistp521", typeof(...)},
  266. //"gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==" - WinSSHD
  267. //"gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==" - WinSSHD
  268. };
  269. this.Encryptions = new Dictionary<string, CipherInfo>
  270. {
  271. {"aes256-ctr", new CipherInfo(256, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
  272. {"3des-cbc", new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CbcCipherMode(iv), null))},
  273. {"aes128-cbc", new CipherInfo(128, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
  274. {"aes192-cbc", new CipherInfo(192, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
  275. {"aes256-cbc", new CipherInfo(256, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
  276. {"blowfish-cbc", new CipherInfo(128, (key, iv) => new BlowfishCipher(key, new CbcCipherMode(iv), null))},
  277. {"twofish-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  278. {"twofish192-cbc", new CipherInfo(192, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  279. {"twofish128-cbc", new CipherInfo(128, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  280. {"twofish256-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  281. ////{"serpent256-cbc", typeof(CipherSerpent256CBC)},
  282. ////{"serpent192-cbc", typeof(...)},
  283. ////{"serpent128-cbc", typeof(...)},
  284. {"arcfour", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, false))},
  285. {"arcfour128", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, true))},
  286. {"arcfour256", new CipherInfo(256, (key, iv) => new Arc4Cipher(key, true))},
  287. ////{"idea-cbc", typeof(...)},
  288. {"cast128-cbc", new CipherInfo(128, (key, iv) => new CastCipher(key, new CbcCipherMode(iv), null))},
  289. ////{"rijndael-cbc@lysator.liu.se", typeof(...)},
  290. {"aes128-ctr", new CipherInfo(128, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
  291. {"aes192-ctr", new CipherInfo(192, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
  292. };
  293. this.HmacAlgorithms = new Dictionary<string, HashInfo>
  294. {
  295. {"hmac-md5", new HashInfo(16*8, key => new HMac<MD5Hash>(key))},
  296. {"hmac-sha1", new HashInfo(20*8, key => new HMac<SHA1Hash>(key))},
  297. {"hmac-sha2-256", new HashInfo(32*8, key => new HMac<SHA256Hash>(key))},
  298. {"hmac-sha2-256-96", new HashInfo(32*8, key => new HMac<SHA256Hash>(key, 96))},
  299. //{"hmac-sha2-512", new HashInfo(64 * 8, key => new HMac<SHA512Hash>(key))},
  300. //{"hmac-sha2-512-96", new HashInfo(64 * 8, key => new HMac<SHA512Hash>(key, 96))},
  301. //{"umac-64@openssh.com", typeof(HMacSha1)},
  302. {"hmac-ripemd160", new HashInfo(160, key => new HMac<RIPEMD160Hash>(key))},
  303. {"hmac-ripemd160@openssh.com", new HashInfo(160, key => new HMac<RIPEMD160Hash>(key))},
  304. {"hmac-md5-96", new HashInfo(16*8, key => new HMac<MD5Hash>(key, 96))},
  305. {"hmac-sha1-96", new HashInfo(20*8, key => new HMac<SHA1Hash>(key, 96))},
  306. //{"none", typeof(...)},
  307. };
  308. this.HostKeyAlgorithms = new Dictionary<string, Func<byte[], KeyHostAlgorithm>>
  309. {
  310. {"ssh-rsa", data => new KeyHostAlgorithm("ssh-rsa", new RsaKey(), data)},
  311. {"ssh-dss", data => new KeyHostAlgorithm("ssh-dss", new DsaKey(), data)},
  312. //{"ecdsa-sha2-nistp256 "}
  313. //{"x509v3-sign-rsa", () => { ... },
  314. //{"x509v3-sign-dss", () => { ... },
  315. //{"spki-sign-rsa", () => { ... },
  316. //{"spki-sign-dss", () => { ... },
  317. //{"pgp-sign-rsa", () => { ... },
  318. //{"pgp-sign-dss", () => { ... },
  319. };
  320. this.CompressionAlgorithms = new Dictionary<string, Type>
  321. {
  322. //{"zlib@openssh.com", typeof(ZlibOpenSsh)},
  323. //{"zlib", typeof(Zlib)},
  324. {"none", null},
  325. };
  326. this.ChannelRequests = new Dictionary<string, RequestInfo>
  327. {
  328. {EnvironmentVariableRequestInfo.NAME, new EnvironmentVariableRequestInfo()},
  329. {ExecRequestInfo.NAME, new ExecRequestInfo()},
  330. {ExitSignalRequestInfo.NAME, new ExitSignalRequestInfo()},
  331. {ExitStatusRequestInfo.NAME, new ExitStatusRequestInfo()},
  332. {PseudoTerminalRequestInfo.NAME, new PseudoTerminalRequestInfo()},
  333. {ShellRequestInfo.NAME, new ShellRequestInfo()},
  334. {SignalRequestInfo.NAME, new SignalRequestInfo()},
  335. {SubsystemRequestInfo.NAME, new SubsystemRequestInfo()},
  336. {WindowChangeRequestInfo.NAME, new WindowChangeRequestInfo()},
  337. {X11ForwardingRequestInfo.NAME, new X11ForwardingRequestInfo()},
  338. {XonXoffRequestInfo.NAME, new XonXoffRequestInfo()},
  339. {EndOfWriteRequestInfo.NAME, new EndOfWriteRequestInfo()},
  340. {KeepAliveRequestInfo.NAME, new KeepAliveRequestInfo()},
  341. };
  342. this.Host = host;
  343. this.Port = port;
  344. this.Username = username;
  345. this.ProxyType = proxyType;
  346. this.ProxyHost = proxyHost;
  347. this.ProxyPort = proxyPort;
  348. this.ProxyUsername = proxyUsername;
  349. this.ProxyPassword = proxyPassword;
  350. this.AuthenticationMethods = authenticationMethods;
  351. }
  352. /// <summary>
  353. /// Authenticates the specified session.
  354. /// </summary>
  355. /// <param name="session">The session to be authenticated.</param>
  356. /// <exception cref="ArgumentNullException"><paramref name="session"/> is null.</exception>
  357. /// <exception cref="SshAuthenticationException">No suitable authentication method found to complete authentication, or permission denied.</exception>
  358. internal void Authenticate(ISession session)
  359. {
  360. IsAuthenticated = false;
  361. var clientAuthentication = new ClientAuthentication();
  362. clientAuthentication.Authenticate(this, session);
  363. IsAuthenticated = true;
  364. }
  365. /// <summary>
  366. /// Signals that an authentication banner message was received from the server.
  367. /// </summary>
  368. /// <param name="sender">The session in which the banner message was received.</param>
  369. /// <param name="e">The banner message.{</param>
  370. void IConnectionInfo.UserAuthenticationBannerReceived(object sender, MessageEventArgs<BannerMessage> e)
  371. {
  372. var authenticationBanner = AuthenticationBanner;
  373. if (authenticationBanner != null)
  374. {
  375. authenticationBanner(this,
  376. new AuthenticationBannerEventArgs(Username, e.Message.Message, e.Message.Language));
  377. }
  378. }
  379. IAuthenticationMethod IConnectionInfo.CreateNoneAuthenticationMethod()
  380. {
  381. return new NoneAuthenticationMethod(Username);
  382. }
  383. IEnumerable<IAuthenticationMethod> IConnectionInfo.AuthenticationMethods
  384. {
  385. get { return AuthenticationMethods.Cast<IAuthenticationMethod>(); }
  386. }
  387. }
  388. }