KeyboardInteractiveAuthenticationMethod.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. using System;
  2. using System.Linq;
  3. using System.Runtime.ExceptionServices;
  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 keyboard interactive authentication.
  13. /// </summary>
  14. public class KeyboardInteractiveAuthenticationMethod : AuthenticationMethod, IDisposable
  15. {
  16. private readonly RequestMessage _requestMessage;
  17. private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
  18. private Session _session;
  19. private EventWaitHandle _authenticationCompleted = new AutoResetEvent(initialState: false);
  20. private Exception _exception;
  21. private bool _isDisposed;
  22. /// <summary>
  23. /// Gets the name of the authentication method.
  24. /// </summary>
  25. /// <value>
  26. /// The name of the authentication method.
  27. /// </value>
  28. public override string Name
  29. {
  30. get { return _requestMessage.MethodName; }
  31. }
  32. /// <summary>
  33. /// Occurs when server prompts for more authentication information.
  34. /// </summary>
  35. public event EventHandler<AuthenticationPromptEventArgs> AuthenticationPrompt;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="KeyboardInteractiveAuthenticationMethod"/> class.
  38. /// </summary>
  39. /// <param name="username">The username.</param>
  40. /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or <see langword="null"/>.</exception>
  41. public KeyboardInteractiveAuthenticationMethod(string username)
  42. : base(username)
  43. {
  44. _requestMessage = new RequestMessageKeyboardInteractive(ServiceName.Connection, username);
  45. }
  46. /// <summary>
  47. /// Authenticates the specified session.
  48. /// </summary>
  49. /// <param name="session">The session to authenticate.</param>
  50. /// <returns>Result of authentication process.</returns>
  51. public override AuthenticationResult Authenticate(Session session)
  52. {
  53. _session = session;
  54. session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
  55. session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  56. session.UserAuthenticationInformationRequestReceived += Session_UserAuthenticationInformationRequestReceived;
  57. session.RegisterMessage("SSH_MSG_USERAUTH_INFO_REQUEST");
  58. try
  59. {
  60. session.SendMessage(_requestMessage);
  61. session.WaitOnHandle(_authenticationCompleted);
  62. }
  63. finally
  64. {
  65. session.UnRegisterMessage("SSH_MSG_USERAUTH_INFO_REQUEST");
  66. session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
  67. session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  68. session.UserAuthenticationInformationRequestReceived -= Session_UserAuthenticationInformationRequestReceived;
  69. }
  70. if (_exception != null)
  71. {
  72. ExceptionDispatchInfo.Capture(_exception).Throw();
  73. }
  74. return _authenticationResult;
  75. }
  76. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  77. {
  78. _authenticationResult = AuthenticationResult.Success;
  79. _ = _authenticationCompleted.Set();
  80. }
  81. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  82. {
  83. if (e.Message.PartialSuccess)
  84. {
  85. _authenticationResult = AuthenticationResult.PartialSuccess;
  86. }
  87. else
  88. {
  89. _authenticationResult = AuthenticationResult.Failure;
  90. }
  91. // Copy allowed authentication methods
  92. AllowedAuthentications = e.Message.AllowedAuthentications;
  93. _ = _authenticationCompleted.Set();
  94. }
  95. private void Session_UserAuthenticationInformationRequestReceived(object sender, MessageEventArgs<InformationRequestMessage> e)
  96. {
  97. var informationRequestMessage = e.Message;
  98. var eventArgs = new AuthenticationPromptEventArgs(Username,
  99. informationRequestMessage.Instruction,
  100. informationRequestMessage.Language,
  101. informationRequestMessage.Prompts);
  102. ThreadAbstraction.ExecuteThread(() =>
  103. {
  104. try
  105. {
  106. AuthenticationPrompt?.Invoke(this, eventArgs);
  107. var informationResponse = new InformationResponseMessage();
  108. foreach (var response in from r in eventArgs.Prompts orderby r.Id ascending select r.Response)
  109. {
  110. informationResponse.Responses.Add(response);
  111. }
  112. // Send information response message
  113. _session.SendMessage(informationResponse);
  114. }
  115. catch (Exception exp)
  116. {
  117. _exception = exp;
  118. _ = _authenticationCompleted.Set();
  119. }
  120. });
  121. }
  122. /// <summary>
  123. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  124. /// </summary>
  125. public void Dispose()
  126. {
  127. Dispose(disposing: true);
  128. GC.SuppressFinalize(this);
  129. }
  130. /// <summary>
  131. /// Releases unmanaged and - optionally - managed resources.
  132. /// </summary>
  133. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  134. protected virtual void Dispose(bool disposing)
  135. {
  136. if (_isDisposed)
  137. {
  138. return;
  139. }
  140. if (disposing)
  141. {
  142. var authenticationCompleted = _authenticationCompleted;
  143. if (authenticationCompleted != null)
  144. {
  145. _authenticationCompleted = null;
  146. authenticationCompleted.Dispose();
  147. }
  148. _isDisposed = true;
  149. }
  150. }
  151. /// <summary>
  152. /// Finalizes an instance of the <see cref="KeyboardInteractiveAuthenticationMethod"/> class.
  153. /// </summary>
  154. ~KeyboardInteractiveAuthenticationMethod()
  155. {
  156. Dispose(disposing: false);
  157. }
  158. }
  159. }