ConnectionInfo.cs 21 KB

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