ConnectionInfo.cs 19 KB

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