PasswordAuthenticationMethod.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using System;
  2. using System.Runtime.ExceptionServices;
  3. using System.Text;
  4. using System.Threading;
  5. using Renci.SshNet.Abstractions;
  6. using Renci.SshNet.Common;
  7. using Renci.SshNet.Messages;
  8. using Renci.SshNet.Messages.Authentication;
  9. namespace Renci.SshNet
  10. {
  11. /// <summary>
  12. /// Provides functionality to perform password authentication.
  13. /// </summary>
  14. public class PasswordAuthenticationMethod : AuthenticationMethod
  15. {
  16. private readonly RequestMessagePassword _requestMessage;
  17. private readonly byte[] _password;
  18. private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
  19. private Session _session;
  20. private EventWaitHandle _authenticationCompleted = new AutoResetEvent(initialState: false);
  21. private Exception _exception;
  22. private bool _isDisposed;
  23. /// <summary>
  24. /// Gets the name of the authentication method.
  25. /// </summary>
  26. public override string Name
  27. {
  28. get { return _requestMessage.MethodName; }
  29. }
  30. /// <summary>
  31. /// Gets the password as a sequence of bytes.
  32. /// </summary>
  33. /// <value>
  34. /// The password as a sequence of bytes.
  35. /// </value>
  36. internal byte[] Password
  37. {
  38. get { return _password; }
  39. }
  40. /// <summary>
  41. /// Occurs when user's password has expired and needs to be changed.
  42. /// </summary>
  43. public event EventHandler<AuthenticationPasswordChangeEventArgs> PasswordExpired;
  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 <see langword="null"/>.</exception>
  50. /// <exception cref="ArgumentException"><paramref name="password"/> is <see langword="null"/>.</exception>
  51. public PasswordAuthenticationMethod(string username, string password)
  52. : this(username, Encoding.UTF8.GetBytes(password))
  53. {
  54. }
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="PasswordAuthenticationMethod"/> class.
  57. /// </summary>
  58. /// <param name="username">The username.</param>
  59. /// <param name="password">The password.</param>
  60. /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or <see langword="null"/>.</exception>
  61. /// <exception cref="ArgumentException"><paramref name="password"/> is <see langword="null"/>.</exception>
  62. public PasswordAuthenticationMethod(string username, byte[] password)
  63. : base(username)
  64. {
  65. ThrowHelper.ThrowIfNull(password);
  66. _password = password;
  67. _requestMessage = new RequestMessagePassword(ServiceName.Connection, Username, _password);
  68. }
  69. /// <summary>
  70. /// Authenticates the specified session.
  71. /// </summary>
  72. /// <param name="session">The session to authenticate.</param>
  73. /// <returns>
  74. /// Result of authentication process.
  75. /// </returns>
  76. /// <exception cref="ArgumentNullException"><paramref name="session" /> is <see langword="null"/>.</exception>
  77. public override AuthenticationResult Authenticate(Session session)
  78. {
  79. ThrowHelper.ThrowIfNull(session);
  80. _session = session;
  81. session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
  82. session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  83. session.UserAuthenticationPasswordChangeRequiredReceived += Session_UserAuthenticationPasswordChangeRequiredReceived;
  84. try
  85. {
  86. session.RegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  87. session.SendMessage(_requestMessage);
  88. session.WaitOnHandle(_authenticationCompleted);
  89. }
  90. finally
  91. {
  92. session.UnRegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  93. session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
  94. session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  95. session.UserAuthenticationPasswordChangeRequiredReceived -= Session_UserAuthenticationPasswordChangeRequiredReceived;
  96. }
  97. if (_exception != null)
  98. {
  99. ExceptionDispatchInfo.Capture(_exception).Throw();
  100. }
  101. return _authenticationResult;
  102. }
  103. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  104. {
  105. _authenticationResult = AuthenticationResult.Success;
  106. _ = _authenticationCompleted.Set();
  107. }
  108. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  109. {
  110. if (e.Message.PartialSuccess)
  111. {
  112. _authenticationResult = AuthenticationResult.PartialSuccess;
  113. }
  114. else
  115. {
  116. _authenticationResult = AuthenticationResult.Failure;
  117. }
  118. // Copy allowed authentication methods
  119. AllowedAuthentications = e.Message.AllowedAuthentications;
  120. _ = _authenticationCompleted.Set();
  121. }
  122. private void Session_UserAuthenticationPasswordChangeRequiredReceived(object sender, MessageEventArgs<PasswordChangeRequiredMessage> e)
  123. {
  124. _session.UnRegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
  125. ThreadAbstraction.ExecuteThread(() =>
  126. {
  127. try
  128. {
  129. var eventArgs = new AuthenticationPasswordChangeEventArgs(Username);
  130. // Raise an event to allow user to supply a new password
  131. PasswordExpired?.Invoke(this, eventArgs);
  132. // Send new authentication request with new password
  133. _session.SendMessage(new RequestMessagePassword(ServiceName.Connection, Username, _password, eventArgs.NewPassword));
  134. }
  135. catch (Exception exp)
  136. {
  137. _exception = exp;
  138. _ = _authenticationCompleted.Set();
  139. }
  140. });
  141. }
  142. /// <inheritdoc/>
  143. protected override void Dispose(bool disposing)
  144. {
  145. if (_isDisposed)
  146. {
  147. return;
  148. }
  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. base.Dispose(disposing);
  160. }
  161. }
  162. }