PrivateKeyAuthenticationMethod.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Collections.ObjectModel;
  5. using Renci.SshNet.Messages.Authentication;
  6. using Renci.SshNet.Messages;
  7. using Renci.SshNet.Common;
  8. using System.Threading;
  9. namespace Renci.SshNet
  10. {
  11. /// <summary>
  12. /// Provides functionality to perform private key authentication.
  13. /// </summary>
  14. public class PrivateKeyAuthenticationMethod : AuthenticationMethod, IDisposable
  15. {
  16. private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
  17. private EventWaitHandle _authenticationCompleted = new ManualResetEvent(false);
  18. private bool _isSignatureRequired;
  19. /// <summary>
  20. /// Gets authentication method name
  21. /// </summary>
  22. public override string Name
  23. {
  24. get { return "publickey"; }
  25. }
  26. /// <summary>
  27. /// Gets the key files used for authentication.
  28. /// </summary>
  29. public ICollection<PrivateKeyFile> KeyFiles { get; private set; }
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="PrivateKeyAuthenticationMethod"/> class.
  32. /// </summary>
  33. /// <param name="username">The username.</param>
  34. /// <param name="keyFiles">The key files.</param>
  35. /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or null.</exception>
  36. public PrivateKeyAuthenticationMethod(string username, params PrivateKeyFile[] keyFiles)
  37. : base(username)
  38. {
  39. if (keyFiles == null)
  40. throw new ArgumentNullException("keyFiles");
  41. this.KeyFiles = new Collection<PrivateKeyFile>(keyFiles);
  42. }
  43. /// <summary>
  44. /// Authenticates the specified session.
  45. /// </summary>
  46. /// <param name="session">The session to authenticate.</param>
  47. /// <returns>
  48. /// Result of authentication process.
  49. /// </returns>
  50. public override AuthenticationResult Authenticate(Session session)
  51. {
  52. session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
  53. session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
  54. session.MessageReceived += Session_MessageReceived;
  55. session.RegisterMessage("SSH_MSG_USERAUTH_PK_OK");
  56. foreach (var keyFile in this.KeyFiles)
  57. {
  58. this._authenticationCompleted.Reset();
  59. this._isSignatureRequired = false;
  60. var message = new RequestMessagePublicKey(ServiceName.Connection, this.Username, keyFile.HostKey.Name, keyFile.HostKey.Data);
  61. if (this.KeyFiles.Count < 2)
  62. {
  63. // If only one key file provided then send signature for very first request
  64. var signatureData = new SignatureData(message, session.SessionId).GetBytes();
  65. message.Signature = keyFile.HostKey.Sign(signatureData);
  66. }
  67. // Send public key authentication request
  68. session.SendMessage(message);
  69. session.WaitOnHandle(this._authenticationCompleted);
  70. if (this._isSignatureRequired)
  71. {
  72. this._authenticationCompleted.Reset();
  73. var signatureMessage = new RequestMessagePublicKey(ServiceName.Connection, this.Username, keyFile.HostKey.Name, keyFile.HostKey.Data);
  74. var signatureData = new SignatureData(message, session.SessionId).GetBytes();
  75. signatureMessage.Signature = keyFile.HostKey.Sign(signatureData);
  76. // Send public key authentication request with signature
  77. session.SendMessage(signatureMessage);
  78. }
  79. session.WaitOnHandle(this._authenticationCompleted);
  80. if (this._authenticationResult == AuthenticationResult.Success)
  81. {
  82. break;
  83. }
  84. }
  85. session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
  86. session.UserAuthenticationFailureReceived -= Session_UserAuthenticationFailureReceived;
  87. session.MessageReceived -= Session_MessageReceived;
  88. session.UnRegisterMessage("SSH_MSG_USERAUTH_PK_OK");
  89. return this._authenticationResult;
  90. }
  91. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  92. {
  93. this._authenticationResult = AuthenticationResult.Success;
  94. this._authenticationCompleted.Set();
  95. }
  96. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  97. {
  98. if (e.Message.PartialSuccess)
  99. this._authenticationResult = AuthenticationResult.PartialSuccess;
  100. else
  101. this._authenticationResult = AuthenticationResult.Failure;
  102. // Copy allowed authentication methods
  103. this.AllowedAuthentications = e.Message.AllowedAuthentications.ToList();
  104. this._authenticationCompleted.Set();
  105. }
  106. private void Session_MessageReceived(object sender, MessageEventArgs<Message> e)
  107. {
  108. var publicKeyMessage = e.Message as PublicKeyMessage;
  109. if (publicKeyMessage != null)
  110. {
  111. this._isSignatureRequired = true;
  112. this._authenticationCompleted.Set();
  113. }
  114. }
  115. #region IDisposable Members
  116. private bool _isDisposed;
  117. /// <summary>
  118. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  119. /// </summary>
  120. public void Dispose()
  121. {
  122. Dispose(true);
  123. GC.SuppressFinalize(this);
  124. }
  125. /// <summary>
  126. /// Releases unmanaged and - optionally - managed resources
  127. /// </summary>
  128. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  129. protected virtual void Dispose(bool disposing)
  130. {
  131. // Check to see if Dispose has already been called.
  132. if (!this._isDisposed)
  133. {
  134. // If disposing equals true, dispose all managed
  135. // and unmanaged resources.
  136. if (disposing)
  137. {
  138. // Dispose managed resources.
  139. if (this._authenticationCompleted != null)
  140. {
  141. this._authenticationCompleted.Dispose();
  142. this._authenticationCompleted = null;
  143. }
  144. }
  145. // Note disposing has been done.
  146. _isDisposed = true;
  147. }
  148. }
  149. /// <summary>
  150. /// Releases unmanaged resources and performs other cleanup operations before the
  151. /// <see cref="PasswordConnectionInfo"/> is reclaimed by garbage collection.
  152. /// </summary>
  153. ~PrivateKeyAuthenticationMethod()
  154. {
  155. // Do not re-create Dispose clean-up code here.
  156. // Calling Dispose(false) is optimal in terms of
  157. // readability and maintainability.
  158. Dispose(false);
  159. }
  160. #endregion
  161. private class SignatureData : SshData
  162. {
  163. private readonly RequestMessagePublicKey _message;
  164. private readonly byte[] _sessionId;
  165. public SignatureData(RequestMessagePublicKey message, byte[] sessionId)
  166. {
  167. this._message = message;
  168. this._sessionId = sessionId;
  169. }
  170. protected override void LoadData()
  171. {
  172. throw new NotImplementedException();
  173. }
  174. protected override void SaveData()
  175. {
  176. this.WriteBinaryString(this._sessionId);
  177. this.Write((byte)50);
  178. this.Write(this._message.Username);
  179. this.WriteAscii("ssh-connection");
  180. this.WriteAscii("publickey");
  181. this.Write((byte)1);
  182. this.WriteAscii(this._message.PublicKeyAlgorithmName);
  183. this.WriteBinaryString(this._message.PublicKeyData);
  184. }
  185. }
  186. }
  187. }