PrivateKeyAuthenticationMethod.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. 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 KeyFiles)
  57. {
  58. _authenticationCompleted.Reset();
  59. _isSignatureRequired = false;
  60. var message = new RequestMessagePublicKey(ServiceName.Connection, Username, keyFile.HostKey.Name, keyFile.HostKey.Data);
  61. if (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(_authenticationCompleted);
  70. if (_isSignatureRequired)
  71. {
  72. _authenticationCompleted.Reset();
  73. var signatureMessage = new RequestMessagePublicKey(ServiceName.Connection, 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(_authenticationCompleted);
  80. if (_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 _authenticationResult;
  90. }
  91. private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
  92. {
  93. _authenticationResult = AuthenticationResult.Success;
  94. _authenticationCompleted.Set();
  95. }
  96. private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
  97. {
  98. if (e.Message.PartialSuccess)
  99. _authenticationResult = AuthenticationResult.PartialSuccess;
  100. else
  101. _authenticationResult = AuthenticationResult.Failure;
  102. // Copy allowed authentication methods
  103. AllowedAuthentications = e.Message.AllowedAuthentications.ToList();
  104. _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. _isSignatureRequired = true;
  112. _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 (!_isDisposed)
  133. {
  134. // If disposing equals true, dispose all managed
  135. // and unmanaged resources.
  136. if (disposing)
  137. {
  138. // Dispose managed resources.
  139. if (_authenticationCompleted != null)
  140. {
  141. _authenticationCompleted.Dispose();
  142. _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. private readonly byte[] _serviceName;
  166. private readonly byte[] _authenticationMethod;
  167. #if TUNING
  168. protected override int BufferCapacity
  169. {
  170. get
  171. {
  172. var capacity = base.BufferCapacity;
  173. capacity += 4; // SessionId length
  174. capacity += _sessionId.Length; // SessionId
  175. capacity += 1; // Authentication Message Code
  176. capacity += 4; // UserName length
  177. capacity += _message.Username.Length; // UserName
  178. capacity += 4; // ServiceName length
  179. capacity += _serviceName.Length; // ServiceName
  180. capacity += 4; // AuthenticationMethod length
  181. capacity += _authenticationMethod.Length; // AuthenticationMethod
  182. capacity += 1; // TRUE
  183. capacity += 4; // PublicKeyAlgorithmName length
  184. capacity += _message.PublicKeyAlgorithmName.Length; // PublicKeyAlgorithmName
  185. capacity += 4; // PublicKeyData length
  186. capacity += _message.PublicKeyData.Length; // PublicKeyData
  187. return capacity;
  188. }
  189. }
  190. #endif
  191. public SignatureData(RequestMessagePublicKey message, byte[] sessionId)
  192. {
  193. _message = message;
  194. _sessionId = sessionId;
  195. _serviceName = ServiceName.Connection.ToArray();
  196. _authenticationMethod = Ascii.GetBytes("publickey");
  197. }
  198. protected override void LoadData()
  199. {
  200. throw new NotImplementedException();
  201. }
  202. protected override void SaveData()
  203. {
  204. WriteBinaryString(_sessionId);
  205. Write((byte) RequestMessage.AuthenticationMessageCode);
  206. WriteBinaryString(_message.Username);
  207. WriteBinaryString(_serviceName);
  208. WriteBinaryString(_authenticationMethod);
  209. Write((byte)1); // TRUE
  210. WriteBinaryString(_message.PublicKeyAlgorithmName);
  211. WriteBinaryString(_message.PublicKeyData);
  212. }
  213. }
  214. }
  215. }