PrivateKeyFile.cs 18 KB

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