PrivateKeyFile.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using Renci.SshNet.Security;
  8. using Renci.SshNet.Common;
  9. using System.Globalization;
  10. using Renci.SshNet.Security.Cryptography;
  11. using Renci.SshNet.Security.Cryptography.Ciphers;
  12. using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
  13. using Renci.SshNet.Security.Cryptography.Ciphers.Paddings;
  14. using System.Diagnostics.CodeAnalysis;
  15. namespace Renci.SshNet
  16. {
  17. /// <summary>
  18. /// Represents private key information
  19. /// </summary>
  20. /// <example>
  21. /// <code source="..\..\Renci.SshNet.Tests\Data\Key.RSA.txt" language="Text" title="Private RSA key example" />
  22. /// </example>
  23. public class PrivateKeyFile : IDisposable
  24. {
  25. #if SILVERLIGHT
  26. private static readonly Regex _privateKeyRegex = new Regex(@"^-+ *BEGIN (?<keyName>\w+( \w+)*) PRIVATE KEY *-+\r?\n(Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: (?<cipherName>[A-Z0-9-]+),(?<salt>[A-F0-9]+)\r?\n\r?\n)?(?<data>([a-zA-Z0-9/+=]{1,80}\r?\n)+)-+ *END \k<keyName> PRIVATE KEY *-+", RegexOptions.Multiline);
  27. #else
  28. private static readonly Regex _privateKeyRegex = new Regex(@"^-+ *BEGIN (?<keyName>\w+( \w+)*) PRIVATE KEY *-+\r?\n(Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: (?<cipherName>[A-Z0-9-]+),(?<salt>[A-F0-9]+)\r?\n\r?\n)?(?<data>([a-zA-Z0-9/+=]{1,80}\r?\n)+)-+ *END \k<keyName> PRIVATE KEY *-+", RegexOptions.Compiled | RegexOptions.Multiline);
  29. #endif
  30. private Key _key;
  31. /// <summary>
  32. /// Gets the host key.
  33. /// </summary>
  34. public HostAlgorithm HostKey { get; private set; }
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="PrivateKeyFile"/> class.
  37. /// </summary>
  38. /// <param name="privateKey">The private key.</param>
  39. public PrivateKeyFile(Stream privateKey)
  40. {
  41. this.Open(privateKey, null);
  42. }
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="PrivateKeyFile"/> class.
  45. /// </summary>
  46. /// <param name="fileName">Name of the file.</param>
  47. /// <exception cref="ArgumentNullException"><paramref name="fileName"/> is null or empty.</exception>
  48. /// <remarks>This method calls <see cref="System.IO.File.Open(string, System.IO.FileMode)"/> internally, this method does not catch exceptions from <see cref="System.IO.File.Open(string, System.IO.FileMode)"/>.</remarks>
  49. public PrivateKeyFile(string fileName)
  50. : this(fileName, null)
  51. {
  52. }
  53. /// <summary>
  54. /// Initializes a new instance of the <see cref="PrivateKeyFile"/> class.
  55. /// </summary>
  56. /// <param name="fileName">Name of the file.</param>
  57. /// <param name="passPhrase">The pass phrase.</param>
  58. /// <exception cref="ArgumentNullException"><paramref name="fileName"/> is null or empty, or <paramref name="passPhrase"/> is null.</exception>
  59. /// <remarks>This method calls <see cref="System.IO.File.Open(string, System.IO.FileMode)"/> internally, this method does not catch exceptions from <see cref="System.IO.File.Open(string, System.IO.FileMode)"/>.</remarks>
  60. public PrivateKeyFile(string fileName, string passPhrase)
  61. {
  62. if (string.IsNullOrEmpty(fileName))
  63. throw new ArgumentNullException("fileName");
  64. using (var keyFile = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
  65. {
  66. this.Open(keyFile, passPhrase);
  67. }
  68. }
  69. /// <summary>
  70. /// Initializes a new instance of the <see cref="PrivateKeyFile"/> class.
  71. /// </summary>
  72. /// <param name="privateKey">The private key.</param>
  73. /// <param name="passPhrase">The pass phrase.</param>
  74. /// <exception cref="ArgumentNullException"><paramref name="privateKey"/> or <paramref name="passPhrase"/> is null.</exception>
  75. public PrivateKeyFile(Stream privateKey, string passPhrase)
  76. {
  77. this.Open(privateKey, passPhrase);
  78. }
  79. /// <summary>
  80. /// Opens the specified private key.
  81. /// </summary>
  82. /// <param name="privateKey">The private key.</param>
  83. /// <param name="passPhrase">The pass phrase.</param>
  84. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "this._key disposed in Dispose(bool) method.")]
  85. private void Open(Stream privateKey, string passPhrase)
  86. {
  87. if (privateKey == null)
  88. throw new ArgumentNullException("privateKey");
  89. Match privateKeyMatch;
  90. using (var sr = new StreamReader(privateKey))
  91. {
  92. var text = sr.ReadToEnd();
  93. privateKeyMatch = _privateKeyRegex.Match(text);
  94. }
  95. if (!privateKeyMatch.Success)
  96. {
  97. throw new SshException("Invalid private key file.");
  98. }
  99. var keyName = privateKeyMatch.Result("${keyName}");
  100. var cipherName = privateKeyMatch.Result("${cipherName}");
  101. var salt = privateKeyMatch.Result("${salt}");
  102. var data = privateKeyMatch.Result("${data}");
  103. var binaryData = Convert.FromBase64String(data);
  104. byte[] decryptedData;
  105. if (!string.IsNullOrEmpty(cipherName) && !string.IsNullOrEmpty(salt))
  106. {
  107. if (string.IsNullOrEmpty(passPhrase))
  108. throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty.");
  109. var binarySalt = new byte[salt.Length / 2];
  110. for (var i = 0; i < binarySalt.Length; i++)
  111. binarySalt[i] = Convert.ToByte(salt.Substring(i * 2, 2), 16);
  112. CipherInfo cipher;
  113. switch (cipherName)
  114. {
  115. case "DES-EDE3-CBC":
  116. cipher = new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
  117. break;
  118. case "DES-EDE3-CFB":
  119. cipher = new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CfbCipherMode(iv), new PKCS7Padding()));
  120. break;
  121. case "DES-CBC":
  122. cipher = new CipherInfo(64, (key, iv) => new DesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
  123. break;
  124. case "AES-128-CBC":
  125. cipher = new CipherInfo(128, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
  126. break;
  127. case "AES-192-CBC":
  128. cipher = new CipherInfo(192, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
  129. break;
  130. case "AES-256-CBC":
  131. cipher = new CipherInfo(256, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
  132. break;
  133. default:
  134. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Private key cipher \"{0}\" is not supported.", cipherName));
  135. }
  136. decryptedData = DecryptKey(cipher, binaryData, passPhrase, binarySalt);
  137. }
  138. else
  139. {
  140. decryptedData = binaryData;
  141. }
  142. switch (keyName)
  143. {
  144. case "RSA":
  145. this._key = new RsaKey(decryptedData.ToArray());
  146. this.HostKey = new KeyHostAlgorithm("ssh-rsa", this._key);
  147. break;
  148. case "DSA":
  149. this._key = new DsaKey(decryptedData.ToArray());
  150. this.HostKey = new KeyHostAlgorithm("ssh-dss", this._key);
  151. break;
  152. case "SSH2 ENCRYPTED":
  153. var reader = new SshDataReader(decryptedData);
  154. var magicNumber = reader.ReadUInt32();
  155. if (magicNumber != 0x3f6ff9eb)
  156. {
  157. throw new SshException("Invalid SSH2 private key.");
  158. }
  159. var totalLength = reader.ReadUInt32(); // Read total bytes length including magic number
  160. var keyType = reader.ReadString();
  161. var ssh2CipherName = reader.ReadString();
  162. var blobSize = (int)reader.ReadUInt32();
  163. byte[] keyData;
  164. if (ssh2CipherName == "none")
  165. {
  166. keyData = reader.ReadBytes(blobSize);
  167. }
  168. //else if (ssh2CipherName == "3des-cbc")
  169. //{
  170. // var key = GetCipherKey(passPhrase, 192 / 8);
  171. // var ssh2Сipher = new TripleDesCipher(key, null, null);
  172. // keyData = ssh2Сipher.Decrypt(reader.ReadBytes(blobSize));
  173. //}
  174. else
  175. {
  176. throw new SshException(string.Format("Cipher method '{0}' is not supported.", cipherName));
  177. }
  178. // TODO: Create two specific data types to avoid using SshDataReader class
  179. reader = new SshDataReader(keyData);
  180. var decryptedLength = reader.ReadUInt32();
  181. if (decryptedLength + 4 != blobSize)
  182. throw new SshException("Invalid passphrase.");
  183. if (keyType == "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}")
  184. {
  185. var exponent = reader.ReadBigIntWithBits();//e
  186. var d = reader.ReadBigIntWithBits();//d
  187. var modulus = reader.ReadBigIntWithBits();//n
  188. var inverseQ = reader.ReadBigIntWithBits();//u
  189. var q = reader.ReadBigIntWithBits();//p
  190. var p = reader.ReadBigIntWithBits();//q
  191. this._key = new RsaKey(modulus, exponent, d, p, q, inverseQ);
  192. this.HostKey = new KeyHostAlgorithm("ssh-rsa", this._key);
  193. }
  194. else if (keyType == "dl-modp{sign{dsa-nist-sha1},dh{plain}}")
  195. {
  196. var zero = reader.ReadUInt32();
  197. if (zero != 0)
  198. {
  199. throw new SshException("Invalid private key");
  200. }
  201. var p = reader.ReadBigIntWithBits();
  202. var g = reader.ReadBigIntWithBits();
  203. var q = reader.ReadBigIntWithBits();
  204. var y = reader.ReadBigIntWithBits();
  205. var x = reader.ReadBigIntWithBits();
  206. this._key = new DsaKey(p, q, g, y, x);
  207. this.HostKey = new KeyHostAlgorithm("ssh-dss", this._key);
  208. }
  209. else
  210. {
  211. throw new NotSupportedException(string.Format("Key type '{0}' is not supported.", keyType));
  212. }
  213. break;
  214. default:
  215. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Key '{0}' is not supported.", keyName));
  216. }
  217. }
  218. private static byte[] GetCipherKey(string passphrase, int length)
  219. {
  220. List<byte> cipherKey = new List<byte>();
  221. using (var md5 = new MD5Hash())
  222. {
  223. byte[] passwordBytes = Encoding.UTF8.GetBytes(passphrase);
  224. var hash = md5.ComputeHash(passwordBytes.ToArray()).AsEnumerable();
  225. cipherKey.AddRange(hash);
  226. while (cipherKey.Count < length)
  227. {
  228. hash = passwordBytes.Concat(hash);
  229. hash = md5.ComputeHash(hash.ToArray());
  230. cipherKey.AddRange(hash);
  231. }
  232. }
  233. return cipherKey.Take(length).ToArray();
  234. }
  235. /// <summary>
  236. /// Decrypts encrypted private key file data.
  237. /// </summary>
  238. /// <param name="cipherInfo">The cipher info.</param>
  239. /// <param name="cipherData">Encrypted data.</param>
  240. /// <param name="passPhrase">Decryption pass phrase.</param>
  241. /// <param name="binarySalt">Decryption binary salt.</param>
  242. /// <returns>Decrypted byte array.</returns>
  243. /// <exception cref="System.ArgumentNullException">cipherInfo</exception>
  244. /// <exception cref="ArgumentNullException"><paramref name="cipherInfo" />, <paramref name="cipherData" />, <paramref name="passPhrase" /> or <paramref name="binarySalt" /> is null.</exception>
  245. private static byte[] DecryptKey(CipherInfo cipherInfo, byte[] cipherData, string passPhrase, byte[] binarySalt)
  246. {
  247. if (cipherInfo == null)
  248. throw new ArgumentNullException("cipherInfo");
  249. if (cipherData == null)
  250. throw new ArgumentNullException("cipherData");
  251. if (binarySalt == null)
  252. throw new ArgumentNullException("binarySalt");
  253. List<byte> cipherKey = new List<byte>();
  254. using (var md5 = new MD5Hash())
  255. {
  256. var passwordBytes = Encoding.UTF8.GetBytes(passPhrase);
  257. // Use 8 bytes binary salkt
  258. var initVector = passwordBytes.Concat(binarySalt.Take(8));
  259. var hash = md5.ComputeHash(initVector.ToArray()).AsEnumerable();
  260. cipherKey.AddRange(hash);
  261. while (cipherKey.Count < cipherInfo.KeySize / 8)
  262. {
  263. hash = hash.Concat(initVector);
  264. hash = md5.ComputeHash(hash.ToArray());
  265. cipherKey.AddRange(hash);
  266. }
  267. }
  268. var cipher = cipherInfo.Cipher(cipherKey.ToArray(), binarySalt);
  269. return cipher.Decrypt(cipherData);
  270. }
  271. #region IDisposable Members
  272. private bool _isDisposed;
  273. /// <summary>
  274. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  275. /// </summary>
  276. public void Dispose()
  277. {
  278. Dispose(true);
  279. GC.SuppressFinalize(this);
  280. }
  281. /// <summary>
  282. /// Releases unmanaged and - optionally - managed resources
  283. /// </summary>
  284. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  285. protected virtual void Dispose(bool disposing)
  286. {
  287. // Check to see if Dispose has already been called.
  288. if (!this._isDisposed)
  289. {
  290. // If disposing equals true, dispose all managed
  291. // and unmanaged ResourceMessages.
  292. if (disposing)
  293. {
  294. // Dispose managed ResourceMessages.
  295. if (this._key != null)
  296. {
  297. ((IDisposable)this._key).Dispose();
  298. this._key = null;
  299. }
  300. }
  301. // Note disposing has been done.
  302. _isDisposed = true;
  303. }
  304. }
  305. /// <summary>
  306. /// Releases unmanaged resources and performs other cleanup operations before the
  307. /// <see cref="BaseClient"/> is reclaimed by garbage collection.
  308. /// </summary>
  309. ~PrivateKeyFile()
  310. {
  311. // Do not re-create Dispose clean-up code here.
  312. // Calling Dispose(false) is optimal in terms of
  313. // readability and maintainability.
  314. Dispose(false);
  315. }
  316. #endregion
  317. private class SshDataReader : SshData
  318. {
  319. public SshDataReader(byte[] data)
  320. {
  321. this.LoadBytes(data);
  322. }
  323. public new UInt32 ReadUInt32()
  324. {
  325. return base.ReadUInt32();
  326. }
  327. public new string ReadString()
  328. {
  329. return base.ReadString();
  330. }
  331. public new byte[] ReadBytes(int length)
  332. {
  333. return base.ReadBytes(length);
  334. }
  335. /// <summary>
  336. /// Reads next mpint data type from internal buffer where length specified in bits.
  337. /// </summary>
  338. /// <returns>mpint read.</returns>
  339. public BigInteger ReadBigIntWithBits()
  340. {
  341. var length = (int)base.ReadUInt32();
  342. length = (int)(length + 7) / 8;
  343. var data = base.ReadBytes(length);
  344. var bytesArray = new byte[data.Length + 1];
  345. Buffer.BlockCopy(data, 0, bytesArray, 1, data.Length);
  346. return new BigInteger(bytesArray.Reverse().ToArray());
  347. }
  348. protected override void LoadData()
  349. {
  350. }
  351. protected override void SaveData()
  352. {
  353. }
  354. }
  355. }
  356. }