2
0

ConnectionInfo.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. public ConnectionInfo(string host, string username, params AuthenticationMethod[] authenticationMethods)
  185. : this(host, DEFAULT_PORT, username, ProxyTypes.None, null, 0, null, null, authenticationMethods)
  186. {
  187. }
  188. /// <summary>
  189. /// Initializes a new instance of the <see cref="ConnectionInfo"/> class.
  190. /// </summary>
  191. /// <param name="host">The host.</param>
  192. /// <param name="port">The port.</param>
  193. /// <param name="username">The username.</param>
  194. /// <param name="authenticationMethods">The authentication methods.</param>
  195. public ConnectionInfo(string host, int port, string username, params AuthenticationMethod[] authenticationMethods)
  196. : this(host, port, username, ProxyTypes.None, null, 0, null, null, authenticationMethods)
  197. {
  198. }
  199. // TODO: DOCS Add exception documentation for this class.
  200. /// <summary>
  201. /// Initializes a new instance of the <see cref="ConnectionInfo" /> class.
  202. /// </summary>
  203. /// <param name="host">Connection host.</param>
  204. /// <param name="port">Connection port.</param>
  205. /// <param name="username">Connection username.</param>
  206. /// <param name="proxyType">Type of the proxy.</param>
  207. /// <param name="proxyHost">The proxy host.</param>
  208. /// <param name="proxyPort">The proxy port.</param>
  209. /// <param name="proxyUsername">The proxy username.</param>
  210. /// <param name="proxyPassword">The proxy password.</param>
  211. /// <param name="authenticationMethods">The authentication methods.</param>
  212. /// <exception cref="System.ArgumentException">host</exception>
  213. /// <exception cref="System.ArgumentOutOfRangeException">proxyPort</exception>
  214. /// <exception cref="ArgumentException"><paramref name="host" /> is invalid, or <paramref name="username" /> is null or contains whitespace characters.</exception>
  215. /// <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>
  216. /// <exception cref="ArgumentException"><paramref name="host" /> is invalid, or <paramref name="username" /> is null or contains whitespace characters.</exception>
  217. public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params AuthenticationMethod[] authenticationMethods)
  218. {
  219. if (!host.IsValidHost())
  220. throw new ArgumentException("host");
  221. if (proxyType != ProxyTypes.None)
  222. {
  223. if (string.IsNullOrEmpty(proxyHost) && !proxyHost.IsValidHost())
  224. throw new ArgumentException("proxyHost");
  225. if (!proxyPort.IsValidPort())
  226. throw new ArgumentOutOfRangeException("proxyPort");
  227. }
  228. if (!port.IsValidPort())
  229. throw new ArgumentOutOfRangeException("port");
  230. if (username.IsNullOrWhiteSpace())
  231. throw new ArgumentException("username");
  232. if (authenticationMethods == null || authenticationMethods.Length < 1)
  233. throw new ArgumentException("authenticationMethods");
  234. // Set default connection values
  235. this.Timeout = TimeSpan.FromSeconds(30);
  236. this.RetryAttempts = 10;
  237. this.MaxSessions = 10;
  238. this.Encoding = Encoding.UTF8;
  239. this.KeyExchangeAlgorithms = new Dictionary<string, Type>
  240. {
  241. {"diffie-hellman-group-exchange-sha256", typeof (KeyExchangeDiffieHellmanGroupExchangeSha256)},
  242. {"diffie-hellman-group-exchange-sha1", typeof (KeyExchangeDiffieHellmanGroupExchangeSha1)},
  243. {"diffie-hellman-group14-sha1", typeof (KeyExchangeDiffieHellmanGroup14Sha1)},
  244. {"diffie-hellman-group1-sha1", typeof (KeyExchangeDiffieHellmanGroup1Sha1)},
  245. //{"ecdh-sha2-nistp256", typeof(KeyExchangeEllipticCurveDiffieHellman)},
  246. //{"ecdh-sha2-nistp256", typeof(...)},
  247. //{"ecdh-sha2-nistp384", typeof(...)},
  248. //{"ecdh-sha2-nistp521", typeof(...)},
  249. //"gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==" - WinSSHD
  250. //"gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==" - WinSSHD
  251. };
  252. this.Encryptions = new Dictionary<string, CipherInfo>
  253. {
  254. {"aes256-ctr", new CipherInfo(256, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
  255. {"3des-cbc", new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CbcCipherMode(iv), null))},
  256. {"aes128-cbc", new CipherInfo(128, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
  257. {"aes192-cbc", new CipherInfo(192, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
  258. {"aes256-cbc", new CipherInfo(256, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
  259. {"blowfish-cbc", new CipherInfo(128, (key, iv) => new BlowfishCipher(key, new CbcCipherMode(iv), null))},
  260. {"twofish-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  261. {"twofish192-cbc", new CipherInfo(192, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  262. {"twofish128-cbc", new CipherInfo(128, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  263. {"twofish256-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
  264. ////{"serpent256-cbc", typeof(CipherSerpent256CBC)},
  265. ////{"serpent192-cbc", typeof(...)},
  266. ////{"serpent128-cbc", typeof(...)},
  267. {"arcfour", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, false))},
  268. {"arcfour128", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, true))},
  269. {"arcfour256", new CipherInfo(256, (key, iv) => new Arc4Cipher(key, true))},
  270. ////{"idea-cbc", typeof(...)},
  271. {"cast128-cbc", new CipherInfo(128, (key, iv) => new CastCipher(key, new CbcCipherMode(iv), null))},
  272. ////{"rijndael-cbc@lysator.liu.se", typeof(...)},
  273. {"aes128-ctr", new CipherInfo(128, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
  274. {"aes192-ctr", new CipherInfo(192, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
  275. };
  276. this.HmacAlgorithms = new Dictionary<string, HashInfo>
  277. {
  278. {"hmac-md5", new HashInfo(16*8, key => new HMac<MD5Hash>(key))},
  279. {"hmac-sha1", new HashInfo(20*8, key => new HMac<SHA1Hash>(key))},
  280. {"hmac-sha2-256", new HashInfo(32*8, key => new HMac<SHA256Hash>(key))},
  281. {"hmac-sha2-256-96", new HashInfo(32*8, key => new HMac<SHA256Hash>(key, 96))},
  282. //{"hmac-sha2-512", new HashInfo(64 * 8, key => new HMac<SHA512Hash>(key))},
  283. //{"hmac-sha2-512-96", new HashInfo(64 * 8, key => new HMac<SHA512Hash>(key, 96))},
  284. //{"umac-64@openssh.com", typeof(HMacSha1)},
  285. {"hmac-ripemd160", new HashInfo(160, key => new HMac<RIPEMD160Hash>(key))},
  286. {"hmac-ripemd160@openssh.com", new HashInfo(160, key => new HMac<RIPEMD160Hash>(key))},
  287. {"hmac-md5-96", new HashInfo(16*8, key => new HMac<MD5Hash>(key, 96))},
  288. {"hmac-sha1-96", new HashInfo(20*8, key => new HMac<SHA1Hash>(key, 96))},
  289. //{"none", typeof(...)},
  290. };
  291. this.HostKeyAlgorithms = new Dictionary<string, Func<byte[], KeyHostAlgorithm>>
  292. {
  293. {"ssh-rsa", data => new KeyHostAlgorithm("ssh-rsa", new RsaKey(), data)},
  294. {"ssh-dss", data => new KeyHostAlgorithm("ssh-dss", new DsaKey(), data)},
  295. //{"ecdsa-sha2-nistp256 "}
  296. //{"x509v3-sign-rsa", () => { ... },
  297. //{"x509v3-sign-dss", () => { ... },
  298. //{"spki-sign-rsa", () => { ... },
  299. //{"spki-sign-dss", () => { ... },
  300. //{"pgp-sign-rsa", () => { ... },
  301. //{"pgp-sign-dss", () => { ... },
  302. };
  303. this.CompressionAlgorithms = new Dictionary<string, Type>
  304. {
  305. //{"zlib@openssh.com", typeof(ZlibOpenSsh)},
  306. //{"zlib", typeof(Zlib)},
  307. {"none", null},
  308. };
  309. this.ChannelRequests = new Dictionary<string, RequestInfo>
  310. {
  311. {EnvironmentVariableRequestInfo.NAME, new EnvironmentVariableRequestInfo()},
  312. {ExecRequestInfo.NAME, new ExecRequestInfo()},
  313. {ExitSignalRequestInfo.NAME, new ExitSignalRequestInfo()},
  314. {ExitStatusRequestInfo.NAME, new ExitStatusRequestInfo()},
  315. {PseudoTerminalRequestInfo.NAME, new PseudoTerminalRequestInfo()},
  316. {ShellRequestInfo.NAME, new ShellRequestInfo()},
  317. {SignalRequestInfo.NAME, new SignalRequestInfo()},
  318. {SubsystemRequestInfo.NAME, new SubsystemRequestInfo()},
  319. {WindowChangeRequestInfo.NAME, new WindowChangeRequestInfo()},
  320. {X11ForwardingRequestInfo.NAME, new X11ForwardingRequestInfo()},
  321. {XonXoffRequestInfo.NAME, new XonXoffRequestInfo()},
  322. {EndOfWriteRequestInfo.NAME, new EndOfWriteRequestInfo()},
  323. {KeepAliveRequestInfo.NAME, new KeepAliveRequestInfo()},
  324. };
  325. this.Host = host;
  326. this.Port = port;
  327. this.Username = username;
  328. this.ProxyType = proxyType;
  329. this.ProxyHost = proxyHost;
  330. this.ProxyPort = proxyPort;
  331. this.ProxyUsername = proxyUsername;
  332. this.ProxyPassword = proxyPassword;
  333. this.AuthenticationMethods = authenticationMethods;
  334. }
  335. /// <summary>
  336. /// Authenticates the specified session.
  337. /// </summary>
  338. /// <param name="session">The session to be authenticated.</param>
  339. /// <exception cref="ArgumentNullException"><paramref name="session"/> is null.</exception>
  340. /// <exception cref="SshAuthenticationException">No suitable authentication method found to complete authentication, or permission denied.</exception>
  341. public void Authenticate(Session session)
  342. {
  343. var clientAuthentication = new ClientAuthentication();
  344. clientAuthentication.Authenticate(this, session);
  345. }
  346. /// <summary>
  347. /// Signals that an authentication banner message was received from the server.
  348. /// </summary>
  349. /// <param name="sender">The session in which the banner message was received.</param>
  350. /// <param name="e">The banner message.{</param>
  351. void IConnectionInfo.UserAuthenticationBannerReceived(object sender, MessageEventArgs<BannerMessage> e)
  352. {
  353. var authenticationBanner = AuthenticationBanner;
  354. if (authenticationBanner != null)
  355. {
  356. authenticationBanner(this,
  357. new AuthenticationBannerEventArgs(Username, e.Message.Message, e.Message.Language));
  358. }
  359. }
  360. IAuthenticationMethod IConnectionInfo.CreateNoneAuthenticationMethod()
  361. {
  362. return new NoneAuthenticationMethod(Username);
  363. }
  364. IEnumerable<IAuthenticationMethod> IConnectionInfo.AuthenticationMethods
  365. {
  366. get { return AuthenticationMethods.Cast<IAuthenticationMethod>(); }
  367. }
  368. }
  369. }