PasswordAuthenticationMethod.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading;
  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 partial 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 this._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 null.</exception>
  38. /// <exception cref="ArgumentException"><paramref name="password"/> is null.</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 null.</exception>
  49. /// <exception cref="ArgumentException"><paramref name="password"/> is null.</exception>
  50. public PasswordAuthenticationMethod(string username, byte[] password)
  51. : base(username)
  52. {
  53. if (password == null)
  54. throw new ArgumentNullException("password");
  55. this._password = password;
  56. this._requestMessage = new RequestMessagePassword(ServiceName.Connection, this.Username, this._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="System.ArgumentNullException"><paramref name="session" /> is null.</exception>
  66. public override AuthenticationResult Authenticate(Session session)
  67. {
  68. if (session == null)
  69. throw new ArgumentNullException("session");
  70. this._session = session;
  71. session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
  72. session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  73. session.MessageReceived += Session_MessageReceived;
  74. session.RegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  75. session.SendMessage(this._requestMessage);
  76. session.WaitOnHandle(this._authenticationCompleted);
  77. session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
  78. session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  79. session.MessageReceived -= Session_MessageReceived;
  80. if (this._exception != null)
  81. {
  82. throw this._exception;
  83. }
  84. return this._authenticationResult;
  85. }
  86. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  87. {
  88. this._authenticationResult = AuthenticationResult.Success;
  89. this._authenticationCompleted.Set();
  90. }
  91. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  92. {
  93. if (e.Message.PartialSuccess)
  94. this._authenticationResult = AuthenticationResult.PartialSuccess;
  95. else
  96. this._authenticationResult = AuthenticationResult.Failure;
  97. // Copy allowed authentication methods
  98. this.AllowedAuthentications = e.Message.AllowedAuthentications.ToList();
  99. this._authenticationCompleted.Set();
  100. }
  101. private void Session_MessageReceived(object sender, MessageEventArgs<Message> e)
  102. {
  103. if (e.Message is PasswordChangeRequiredMessage)
  104. {
  105. this._session.UnRegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  106. this.ExecuteThread(() =>
  107. {
  108. try
  109. {
  110. var eventArgs = new AuthenticationPasswordChangeEventArgs(this.Username);
  111. // Raise an event to allow user to supply a new password
  112. if (this.PasswordExpired != null)
  113. {
  114. this.PasswordExpired(this, eventArgs);
  115. }
  116. // Send new authentication request with new password
  117. this._session.SendMessage(new RequestMessagePassword(ServiceName.Connection, this.Username, this._password, eventArgs.NewPassword));
  118. }
  119. catch (Exception exp)
  120. {
  121. this._exception = exp;
  122. this._authenticationCompleted.Set();
  123. }
  124. });
  125. }
  126. }
  127. partial void ExecuteThread(Action action);
  128. #region IDisposable Members
  129. private bool _isDisposed;
  130. /// <summary>
  131. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  132. /// </summary>
  133. public void Dispose()
  134. {
  135. Dispose(true);
  136. GC.SuppressFinalize(this);
  137. }
  138. /// <summary>
  139. /// Releases unmanaged and - optionally - managed resources
  140. /// </summary>
  141. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  142. protected virtual void Dispose(bool disposing)
  143. {
  144. // Check to see if Dispose has already been called.
  145. if (!this._isDisposed)
  146. {
  147. // If disposing equals true, dispose all managed
  148. // and unmanaged resources.
  149. if (disposing)
  150. {
  151. // Dispose managed resources.
  152. if (this._authenticationCompleted != null)
  153. {
  154. this._authenticationCompleted.Dispose();
  155. this._authenticationCompleted = null;
  156. }
  157. }
  158. // Note disposing has been done.
  159. _isDisposed = true;
  160. }
  161. }
  162. /// <summary>
  163. /// Releases unmanaged resources and performs other cleanup operations before the
  164. /// <see cref="PasswordConnectionInfo"/> is reclaimed by garbage collection.
  165. /// </summary>
  166. ~PasswordAuthenticationMethod()
  167. {
  168. // Do not re-create Dispose clean-up code here.
  169. // Calling Dispose(false) is optimal in terms of
  170. // readability and maintainability.
  171. Dispose(false);
  172. }
  173. #endregion
  174. }
  175. }