ConnectionInfo.cs 22 KB

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