ConnectionInfo.cs 20 KB

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