ConnectionInfo.cs 22 KB

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