PrivateKeyConnectionInfo.cs 8.9 KB

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