PasswordAuthenticationMethod.cs 7.4 KB

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