ConnectionInfo.cs 21 KB

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