ConnectionInfo.cs 18 KB

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