PasswordAuthenticationMethod.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading;
  5. using Renci.SshNet.Abstractions;
  6. using Renci.SshNet.Common;
  7. using Renci.SshNet.Messages.Authentication;
  8. using Renci.SshNet.Messages;
  9. namespace Renci.SshNet
  10. {
  11. /// <summary>
  12. /// Provides functionality to perform password authentication.
  13. /// </summary>
  14. public class PasswordAuthenticationMethod : AuthenticationMethod, IDisposable
  15. {
  16. private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
  17. private Session _session;
  18. private EventWaitHandle _authenticationCompleted = new AutoResetEvent(false);
  19. private Exception _exception;
  20. private readonly RequestMessage _requestMessage;
  21. private readonly byte[] _password;
  22. /// <summary>
  23. /// Gets authentication method name
  24. /// </summary>
  25. public override string Name
  26. {
  27. get { return _requestMessage.MethodName; }
  28. }
  29. /// <summary>
  30. /// Occurs when user's password has expired and needs to be changed.
  31. /// </summary>
  32. public event EventHandler<AuthenticationPasswordChangeEventArgs> PasswordExpired;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="PasswordAuthenticationMethod"/> class.
  35. /// </summary>
  36. /// <param name="username">The username.</param>
  37. /// <param name="password">The password.</param>
  38. /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or null.</exception>
  39. /// <exception cref="ArgumentException"><paramref name="password"/> is null.</exception>
  40. public PasswordAuthenticationMethod(string username, string password)
  41. : this(username, Encoding.UTF8.GetBytes(password))
  42. {
  43. }
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="PasswordAuthenticationMethod"/> class.
  46. /// </summary>
  47. /// <param name="username">The username.</param>
  48. /// <param name="password">The password.</param>
  49. /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or null.</exception>
  50. /// <exception cref="ArgumentException"><paramref name="password"/> is null.</exception>
  51. public PasswordAuthenticationMethod(string username, byte[] password)
  52. : base(username)
  53. {
  54. if (password == null)
  55. throw new ArgumentNullException("password");
  56. _password = password;
  57. _requestMessage = new RequestMessagePassword(ServiceName.Connection, Username, _password);
  58. }
  59. /// <summary>
  60. /// Authenticates the specified session.
  61. /// </summary>
  62. /// <param name="session">The session to authenticate.</param>
  63. /// <returns>
  64. /// Result of authentication process.
  65. /// </returns>
  66. /// <exception cref="System.ArgumentNullException"><paramref name="session" /> is null.</exception>
  67. public override AuthenticationResult Authenticate(Session session)
  68. {
  69. if (session == null)
  70. throw new ArgumentNullException("session");
  71. _session = session;
  72. session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
  73. session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  74. session.MessageReceived += Session_MessageReceived;
  75. try
  76. {
  77. session.RegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  78. session.SendMessage(_requestMessage);
  79. session.WaitOnHandle(_authenticationCompleted);
  80. }
  81. finally
  82. {
  83. session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
  84. session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  85. session.MessageReceived -= Session_MessageReceived;
  86. }
  87. if (_exception != null)
  88. throw _exception;
  89. return _authenticationResult;
  90. }
  91. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  92. {
  93. _authenticationResult = AuthenticationResult.Success;
  94. _authenticationCompleted.Set();
  95. }
  96. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  97. {
  98. if (e.Message.PartialSuccess)
  99. _authenticationResult = AuthenticationResult.PartialSuccess;
  100. else
  101. _authenticationResult = AuthenticationResult.Failure;
  102. // Copy allowed authentication methods
  103. AllowedAuthentications = e.Message.AllowedAuthentications.ToList();
  104. _authenticationCompleted.Set();
  105. }
  106. private void Session_MessageReceived(object sender, MessageEventArgs<Message> e)
  107. {
  108. if (e.Message is PasswordChangeRequiredMessage)
  109. {
  110. _session.UnRegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  111. ThreadAbstraction.ExecuteThread(() =>
  112. {
  113. try
  114. {
  115. var eventArgs = new AuthenticationPasswordChangeEventArgs(Username);
  116. // Raise an event to allow user to supply a new password
  117. if (PasswordExpired != null)
  118. {
  119. PasswordExpired(this, eventArgs);
  120. }
  121. // Send new authentication request with new password
  122. _session.SendMessage(new RequestMessagePassword(ServiceName.Connection, Username, _password, eventArgs.NewPassword));
  123. }
  124. catch (Exception exp)
  125. {
  126. _exception = exp;
  127. _authenticationCompleted.Set();
  128. }
  129. });
  130. }
  131. }
  132. #region IDisposable Members
  133. private bool _isDisposed;
  134. /// <summary>
  135. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  136. /// </summary>
  137. public void Dispose()
  138. {
  139. Dispose(true);
  140. GC.SuppressFinalize(this);
  141. }
  142. /// <summary>
  143. /// Releases unmanaged and - optionally - managed resources
  144. /// </summary>
  145. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  146. protected virtual void Dispose(bool disposing)
  147. {
  148. if (_isDisposed)
  149. return;
  150. if (disposing)
  151. {
  152. if (_authenticationCompleted != null)
  153. {
  154. _authenticationCompleted.Dispose();
  155. _authenticationCompleted = null;
  156. }
  157. _isDisposed = true;
  158. }
  159. }
  160. /// <summary>
  161. /// Releases unmanaged resources and performs other cleanup operations before the
  162. /// <see cref="PasswordConnectionInfo"/> is reclaimed by garbage collection.
  163. /// </summary>
  164. ~PasswordAuthenticationMethod()
  165. {
  166. // Do not re-create Dispose clean-up code here.
  167. // Calling Dispose(false) is optimal in terms of
  168. // readability and maintainability.
  169. Dispose(false);
  170. }
  171. #endregion
  172. }
  173. }