2
0

KeyboardInteractiveAuthenticationMethod.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. using System;
  2. using System.Linq;
  3. using System.Threading;
  4. using Renci.SshNet.Messages;
  5. using Renci.SshNet.Messages.Authentication;
  6. using Renci.SshNet.Common;
  7. namespace Renci.SshNet
  8. {
  9. /// <summary>
  10. /// Provides functionality to perform keyboard interactive authentication.
  11. /// </summary>
  12. public partial class KeyboardInteractiveAuthenticationMethod : AuthenticationMethod, IDisposable
  13. {
  14. private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
  15. private Session _session;
  16. private EventWaitHandle _authenticationCompleted = new AutoResetEvent(false);
  17. private Exception _exception;
  18. private readonly RequestMessage _requestMessage;
  19. /// <summary>
  20. /// Gets authentication method name
  21. /// </summary>
  22. public override string Name
  23. {
  24. get { return this._requestMessage.MethodName; }
  25. }
  26. /// <summary>
  27. /// Occurs when server prompts for more authentication information.
  28. /// </summary>
  29. public event EventHandler<AuthenticationPromptEventArgs> AuthenticationPrompt;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="KeyboardInteractiveAuthenticationMethod"/> class.
  32. /// </summary>
  33. /// <param name="username">The username.</param>
  34. /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or null.</exception>
  35. public KeyboardInteractiveAuthenticationMethod(string username)
  36. : base(username)
  37. {
  38. this._requestMessage = new RequestMessageKeyboardInteractive(ServiceName.Connection, username);
  39. }
  40. /// <summary>
  41. /// Authenticates the specified session.
  42. /// </summary>
  43. /// <param name="session">The session to authenticate.</param>
  44. /// <returns>Result of authentication process.</returns>
  45. public override AuthenticationResult Authenticate(Session session)
  46. {
  47. this._session = session;
  48. session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
  49. session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  50. session.MessageReceived += Session_MessageReceived;
  51. session.RegisterMessage("SSH_MSG_USERAUTH_INFO_REQUEST");
  52. session.SendMessage(this._requestMessage);
  53. session.WaitOnHandle(this._authenticationCompleted);
  54. session.UnRegisterMessage("SSH_MSG_USERAUTH_INFO_REQUEST");
  55. session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
  56. session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  57. session.MessageReceived -= Session_MessageReceived;
  58. if (this._exception != null)
  59. {
  60. throw this._exception;
  61. }
  62. return this._authenticationResult;
  63. }
  64. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  65. {
  66. this._authenticationResult = AuthenticationResult.Success;
  67. this._authenticationCompleted.Set();
  68. }
  69. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  70. {
  71. if (e.Message.PartialSuccess)
  72. this._authenticationResult = AuthenticationResult.PartialSuccess;
  73. else
  74. this._authenticationResult = AuthenticationResult.Failure;
  75. // Copy allowed authentication methods
  76. this.AllowedAuthentications = e.Message.AllowedAuthentications.ToList();
  77. this._authenticationCompleted.Set();
  78. }
  79. private void Session_MessageReceived(object sender, MessageEventArgs<Message> e)
  80. {
  81. var informationRequestMessage = e.Message as InformationRequestMessage;
  82. if (informationRequestMessage != null)
  83. {
  84. var eventArgs = new AuthenticationPromptEventArgs(this.Username, informationRequestMessage.Instruction, informationRequestMessage.Language, informationRequestMessage.Prompts);
  85. this.ExecuteThread(() =>
  86. {
  87. try
  88. {
  89. if (this.AuthenticationPrompt != null)
  90. {
  91. this.AuthenticationPrompt(this, eventArgs);
  92. }
  93. var informationResponse = new InformationResponseMessage();
  94. foreach (var response in from r in eventArgs.Prompts orderby r.Id ascending select r.Response)
  95. {
  96. informationResponse.Responses.Add(response);
  97. }
  98. // Send information response message
  99. this._session.SendMessage(informationResponse);
  100. }
  101. catch (Exception exp)
  102. {
  103. this._exception = exp;
  104. this._authenticationCompleted.Set();
  105. }
  106. });
  107. }
  108. }
  109. partial void ExecuteThread(Action action);
  110. #region IDisposable Members
  111. private bool _isDisposed;
  112. /// <summary>
  113. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  114. /// </summary>
  115. public void Dispose()
  116. {
  117. Dispose(true);
  118. GC.SuppressFinalize(this);
  119. }
  120. /// <summary>
  121. /// Releases unmanaged and - optionally - managed resources
  122. /// </summary>
  123. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  124. protected virtual void Dispose(bool disposing)
  125. {
  126. // Check to see if Dispose has already been called.
  127. if (!this._isDisposed)
  128. {
  129. // If disposing equals true, dispose all managed
  130. // and unmanaged resources.
  131. if (disposing)
  132. {
  133. // Dispose managed resources.
  134. if (this._authenticationCompleted != null)
  135. {
  136. this._authenticationCompleted.Dispose();
  137. this._authenticationCompleted = null;
  138. }
  139. }
  140. // Note disposing has been done.
  141. _isDisposed = true;
  142. }
  143. }
  144. /// <summary>
  145. /// Releases unmanaged resources and performs other cleanup operations before the
  146. /// <see cref="PasswordConnectionInfo"/> is reclaimed by garbage collection.
  147. /// </summary>
  148. ~KeyboardInteractiveAuthenticationMethod()
  149. {
  150. // Do not re-create Dispose clean-up code here.
  151. // Calling Dispose(false) is optimal in terms of
  152. // readability and maintainability.
  153. Dispose(false);
  154. }
  155. #endregion
  156. }
  157. }