ConnectionInfo.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using Renci.SshNet.Security;
  6. using Renci.SshNet.Compression;
  7. using Renci.SshNet.Messages;
  8. using Renci.SshNet.Messages.Authentication;
  9. using Renci.SshNet.Common;
  10. using System.Threading;
  11. using System.Net;
  12. using Renci.SshNet.Messages.Connection;
  13. using Renci.SshNet.Security.Cryptography.Ciphers;
  14. using System.Security.Cryptography;
  15. using Renci.SshNet.Security.Cryptography;
  16. using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
  17. namespace Renci.SshNet
  18. {
  19. /// <summary>
  20. /// Represents remote connection information base class.
  21. /// </summary>
  22. public abstract class ConnectionInfo
  23. {
  24. /// <summary>
  25. /// Gets connection name
  26. /// </summary>
  27. public abstract string Name { get; }
  28. /// <summary>
  29. /// Gets a value indicating whether connection is authenticated.
  30. /// </summary>
  31. /// <value>
  32. /// <c>true</c> if connection is authenticated; otherwise, <c>false</c>.
  33. /// </value>
  34. public bool IsAuthenticated { get; private set; }
  35. /// <summary>
  36. /// Gets the authentication error message.
  37. /// </summary>
  38. public string ErrorMessage { get; private set; }
  39. /// <summary>
  40. /// Gets reference to the session object.
  41. /// </summary>
  42. protected Session Session { get; private set; }
  43. /// <summary>
  44. /// Gets supported key exchange algorithms for this connection.
  45. /// </summary>
  46. public IDictionary<string, Type> KeyExchangeAlgorithms { get; private set; }
  47. /// <summary>
  48. /// Gets supported encryptions for this connection.
  49. /// </summary>
  50. public IDictionary<string, CipherInfo> Encryptions { get; private set; }
  51. /// <summary>
  52. /// Gets supported hash algorithms for this connection.
  53. /// </summary>
  54. public IDictionary<string, Func<byte[], HashAlgorithm>> HmacAlgorithms { get; private set; }
  55. /// <summary>
  56. /// Gets supported host key algorithms for this connection.
  57. /// </summary>
  58. public IDictionary<string, Type> HostKeyAlgorithms { get; private set; }
  59. /// <summary>
  60. /// Gets supported authentication methods for this connection.
  61. /// </summary>
  62. public IDictionary<string, Type> AuthenticationMethods { get; private set; }
  63. /// <summary>
  64. /// Gets supported compression algorithms for this connection.
  65. /// </summary>
  66. public IDictionary<string, Type> CompressionAlgorithms { get; private set; }
  67. /// <summary>
  68. /// Gets supported channel requests for this connection.
  69. /// </summary>
  70. public IDictionary<string, RequestInfo> ChannelRequests { get; private set; }
  71. /// <summary>
  72. /// Gets connection host.
  73. /// </summary>
  74. public string Host { get; private set; }
  75. /// <summary>
  76. /// Gets connection port.
  77. /// </summary>
  78. public int Port { get; private set; }
  79. /// <summary>
  80. /// Gets connection username.
  81. /// </summary>
  82. public string Username { get; private set; }
  83. /// <summary>
  84. /// Gets or sets connection timeout.
  85. /// </summary>
  86. /// <value>
  87. /// Connection timeout.
  88. /// </value>
  89. public TimeSpan Timeout { get; set; }
  90. /// <summary>
  91. /// Gets or sets number of retry attempts when session channel creation failed.
  92. /// </summary>
  93. /// <value>
  94. /// Number of retry attempts.
  95. /// </value>
  96. public int RetryAttempts { get; set; }
  97. /// <summary>
  98. /// Gets or sets maximum number of session channels to be open simultaneously.
  99. /// </summary>
  100. /// <value>
  101. /// The max sessions.
  102. /// </value>
  103. public int MaxSessions { get; set; }
  104. /// <summary>
  105. /// Occurs when authentication banner is sent by the server.
  106. /// </summary>
  107. public event EventHandler<AuthenticationBannerEventArgs> AuthenticationBanner;
  108. /// <summary>
  109. /// Prevents a default instance of the <see cref="ConnectionInfo"/> class from being created.
  110. /// </summary>
  111. private ConnectionInfo()
  112. {
  113. // Set default connection values
  114. this.Timeout = TimeSpan.FromSeconds(30);
  115. this.RetryAttempts = 10;
  116. this.MaxSessions = 10;
  117. this.KeyExchangeAlgorithms = new Dictionary<string, Type>()
  118. {
  119. {"diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256)},
  120. {"diffie-hellman-group-exchange-sha1", typeof(KeyExchangeDiffieHellmanGroupExchangeSha1)},
  121. {"diffie-hellman-group14-sha1", typeof(KeyExchangeDiffieHellmanGroup14Sha1)},
  122. {"diffie-hellman-group1-sha1", typeof(KeyExchangeDiffieHellmanGroup1Sha1)},
  123. };
  124. this.Encryptions = new Dictionary<string, CipherInfo>()
  125. {
  126. {"3des-cbc", new CipherInfo(192, (key, iv)=>{ return new TripleDesCipher(key, new CbcCipherMode(iv), null); }) },
  127. {"aes128-cbc", new CipherInfo(128, (key, iv)=>{ return new AesCipher(key, new CbcCipherMode(iv), null); }) },
  128. {"aes192-cbc", new CipherInfo(192, (key, iv)=>{ return new AesCipher(key, new CbcCipherMode(iv), null); }) },
  129. {"aes256-cbc", new CipherInfo(256, (key, iv)=>{ return new AesCipher(key, new CbcCipherMode(iv), null); }) },
  130. {"blowfish-cbc", new CipherInfo(128, (key, iv)=>{ return new BlowfishCipher(key, new CbcCipherMode(iv), null); }) },
  131. ////{"twofish-cbc", typeof(...)},
  132. ////{"twofish192-cbc", typeof(...)},
  133. ////{"twofish128-cbc", typeof(...)},
  134. ////{"twofish256-cbc", typeof(...)},
  135. ////{"serpent256-cbc", typeof(CipherSerpent256CBC)},
  136. ////{"serpent192-cbc", typeof(...)},
  137. ////{"serpent128-cbc", typeof(...)},
  138. ////{"arcfour128", typeof(...)},
  139. ////{"arcfour256", typeof(...)},
  140. ////{"arcfour", typeof(...)},
  141. ////{"idea-cbc", typeof(...)},
  142. {"cast128-cbc", new CipherInfo(128, (key, iv)=>{ return new CastCipher(key, new CbcCipherMode(iv), null); }) },
  143. ////{"rijndael-cbc@lysator.liu.se", typeof(...)},
  144. {"aes128-ctr", new CipherInfo(128, (key, iv)=>{ return new AesCipher(key, new CtrCipherMode(iv), null); }) },
  145. {"aes192-ctr", new CipherInfo(192, (key, iv)=>{ return new AesCipher(key, new CtrCipherMode(iv), null); }) },
  146. {"aes256-ctr", new CipherInfo(256, (key, iv)=>{ return new AesCipher(key, new CtrCipherMode(iv), null); }) },
  147. };
  148. this.HmacAlgorithms = new Dictionary<string, Func<byte[], HashAlgorithm>>()
  149. {
  150. {"hmac-md5", (key) => { return new HMac<MD5Hash>(key.Take(16).ToArray());}},
  151. {"hmac-sha1", (key) => { return new HMac<SHA1Hash>(key.Take(20).ToArray());}},
  152. //{"umac-64@openssh.com", typeof(HMacSha1)},
  153. //{"hmac-ripemd160", typeof(HMacSha1)},
  154. //{"hmac-ripemd160@openssh.com", typeof(HMacSha1)},
  155. //{"hmac-md5-96", typeof(...)},
  156. //{"hmac-sha1-96", typeof(...)},
  157. //{"none", typeof(...)},
  158. };
  159. this.HostKeyAlgorithms = new Dictionary<string, Type>()
  160. {
  161. {"ssh-rsa", typeof(CryptoPublicKeyRsa)},
  162. {"ssh-dss", typeof(CryptoPublicKeyDss)},
  163. };
  164. this.AuthenticationMethods = new Dictionary<string, Type>()
  165. {
  166. {"none", typeof(ConnectionInfo)},
  167. {"publickey", typeof(PrivateKeyConnectionInfo)},
  168. {"password", typeof(PasswordConnectionInfo)},
  169. {"keyboard-interactive", typeof(KeyboardInteractiveConnectionInfo)},
  170. //{"hostbased", typeof(...)},
  171. //{"gssapi-keyex", typeof(...)},
  172. //{"gssapi-with-mic", typeof(...)},
  173. };
  174. this.CompressionAlgorithms = new Dictionary<string, Type>()
  175. {
  176. {"none", null},
  177. {"zlib", typeof(Zlib)},
  178. {"zlib@openssh.com", typeof(ZlibOpenSsh)},
  179. };
  180. this.ChannelRequests = new Dictionary<string, RequestInfo>()
  181. {
  182. {EnvironmentVariableRequestInfo.NAME, new EnvironmentVariableRequestInfo()},
  183. {ExecRequestInfo.NAME, new ExecRequestInfo()},
  184. {ExitSignalRequestInfo.NAME, new ExitSignalRequestInfo()},
  185. {ExitStatusRequestInfo.NAME, new ExitStatusRequestInfo()},
  186. {PseudoTerminalRequestInfo.NAME, new PseudoTerminalRequestInfo()},
  187. {ShellRequestInfo.NAME, new ShellRequestInfo()},
  188. {SignalRequestInfo.NAME, new SignalRequestInfo()},
  189. {SubsystemRequestInfo.NAME, new SubsystemRequestInfo()},
  190. {WindowChangeRequestInfo.NAME, new WindowChangeRequestInfo()},
  191. {X11ForwardingRequestInfo.NAME, new X11ForwardingRequestInfo()},
  192. {XonXoffRequestInfo.NAME, new XonXoffRequestInfo()},
  193. {EndOfWriteRequestInfo.NAME, new EndOfWriteRequestInfo()},
  194. {KeepAliveRequestInfo.NAME, new KeepAliveRequestInfo()},
  195. };
  196. }
  197. /// <summary>
  198. /// Initializes a new instance of the <see cref="ConnectionInfo"/> class.
  199. /// </summary>
  200. /// <param name="host">Connection host.</param>
  201. /// <param name="port">Connection port.</param>
  202. /// <param name="username">Connection username.</param>
  203. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  204. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  205. /// <exception cref="ArgumentException"><paramref name="username"/> is null or empty.</exception>
  206. protected ConnectionInfo(string host, int port, string username)
  207. : this()
  208. {
  209. if (!host.IsValidHost())
  210. throw new ArgumentException("host");
  211. if (!port.IsValidPort())
  212. throw new ArgumentOutOfRangeException("port");
  213. if (string.IsNullOrWhiteSpace(username))
  214. throw new ArgumentException("username");
  215. this.Host = host;
  216. this.Port = port;
  217. this.Username = username;
  218. }
  219. /// <summary>
  220. /// Authenticates the specified session.
  221. /// </summary>
  222. /// <param name="session">The session to be authenticated.</param>
  223. /// <returns>true if authenticated; otherwise false.</returns>
  224. /// <exception cref="ArgumentNullException"><paramref name="session"/> is null.</exception>
  225. public bool Authenticate(Session session)
  226. {
  227. if (session == null)
  228. throw new ArgumentNullException("session");
  229. this.Session = session;
  230. this.Session.RegisterMessage("SSH_MSG_USERAUTH_FAILURE");
  231. this.Session.RegisterMessage("SSH_MSG_USERAUTH_SUCCESS");
  232. this.Session.RegisterMessage("SSH_MSG_USERAUTH_BANNER");
  233. this.Session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  234. this.Session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessMessageReceived;
  235. this.Session.UserAuthenticationBannerReceived += Session_UserAuthenticationBannerMessageReceived;
  236. this.Session.MessageReceived += Session_MessageReceived;
  237. this.OnAuthenticate();
  238. this.Session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  239. this.Session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessMessageReceived;
  240. this.Session.UserAuthenticationBannerReceived -= Session_UserAuthenticationBannerMessageReceived;
  241. this.Session.MessageReceived -= Session_MessageReceived;
  242. this.Session.UnRegisterMessage("SSH_MSG_USERAUTH_FAILURE");
  243. this.Session.UnRegisterMessage("SSH_MSG_USERAUTH_SUCCESS");
  244. this.Session.UnRegisterMessage("SSH_MSG_USERAUTH_BANNER");
  245. return this.IsAuthenticated;
  246. }
  247. /// <summary>
  248. /// Called when connection needs to be authenticated.
  249. /// </summary>
  250. protected abstract void OnAuthenticate();
  251. /// <summary>
  252. /// Sends SSH message to the server.
  253. /// </summary>
  254. /// <param name="message">The message.</param>
  255. protected void SendMessage(Message message)
  256. {
  257. this.Session.SendMessage(message);
  258. }
  259. /// <summary>
  260. /// Waits the handle to signal.
  261. /// </summary>
  262. /// <param name="eventWaitHandle">The event wait handle.</param>
  263. protected void WaitHandle(WaitHandle eventWaitHandle)
  264. {
  265. this.Session.WaitHandle(eventWaitHandle);
  266. }
  267. /// <summary>
  268. /// Handles the UserAuthenticationFailureReceived event of the session.
  269. /// </summary>
  270. /// <param name="sender">The source of the event.</param>
  271. /// <param name="e">The event data.</param>
  272. protected virtual void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  273. {
  274. this.ErrorMessage = e.Message.Message;
  275. this.IsAuthenticated = false;
  276. }
  277. /// <summary>
  278. /// Handles the UserAuthenticationSuccessMessageReceived event of the session.
  279. /// </summary>
  280. /// <param name="sender">The source of the event.</param>
  281. /// <param name="e">The event data.</param>
  282. protected virtual void Session_UserAuthenticationSuccessMessageReceived(object sender, MessageEventArgs<SuccessMessage> e)
  283. {
  284. this.IsAuthenticated = true;
  285. }
  286. /// <summary>
  287. /// Handles the UserAuthenticationBannerMessageReceived event of the session.
  288. /// </summary>
  289. /// <param name="sender">The source of the event.</param>
  290. /// <param name="e">The event data.</param>
  291. protected virtual void Session_UserAuthenticationBannerMessageReceived(object sender, MessageEventArgs<BannerMessage> e)
  292. {
  293. if (this.AuthenticationBanner != null)
  294. {
  295. this.AuthenticationBanner(this, new AuthenticationBannerEventArgs(this.Username, e.Message.Message, e.Message.Language));
  296. }
  297. }
  298. /// <summary>
  299. /// Handles the MessageReceived event of the session.
  300. /// </summary>
  301. /// <param name="sender">The source of the event.</param>
  302. /// <param name="e">The event data.</param>
  303. protected virtual void Session_MessageReceived(object sender, MessageEventArgs<Message> e)
  304. {
  305. }
  306. }
  307. }