2
0

KeyboardInteractiveAuthenticationMethod.cs 7.2 KB

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