ConnectionInfo.cs 18 KB

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