PrivateKeyAuthenticationMethod.cs 8.7 KB

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