JksStore.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  10. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  11. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
  12. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
  13. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  14. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
  15. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
  16. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  17. using Best.HTTP.SecureProtocol.Org.BouncyCastle.X509;
  18. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Security
  19. {
  20. public class JksStore
  21. {
  22. private static readonly int Magic = unchecked((int)0xFEEDFEED);
  23. private static readonly AlgorithmIdentifier JksObfuscationAlg = new AlgorithmIdentifier(
  24. new DerObjectIdentifier("1.3.6.1.4.1.42.2.17.1.1"), DerNull.Instance);
  25. private readonly Dictionary<string, JksTrustedCertEntry> m_certificateEntries =
  26. new Dictionary<string, JksTrustedCertEntry>(StringComparer.OrdinalIgnoreCase);
  27. private readonly Dictionary<string, JksKeyEntry> m_keyEntries =
  28. new Dictionary<string, JksKeyEntry>(StringComparer.OrdinalIgnoreCase);
  29. public JksStore()
  30. {
  31. }
  32. /// <exception cref="IOException"/>
  33. public bool Probe(Stream stream)
  34. {
  35. using (var br = new BinaryReader(stream))
  36. try
  37. {
  38. return Magic == BinaryReaders.ReadInt32BigEndian(br);
  39. }
  40. catch (EndOfStreamException)
  41. {
  42. return false;
  43. }
  44. }
  45. /// <exception cref="IOException"/>
  46. public AsymmetricKeyParameter GetKey(string alias, char[] password)
  47. {
  48. if (alias == null)
  49. throw new ArgumentNullException(nameof(alias));
  50. if (password == null)
  51. throw new ArgumentNullException(nameof(password));
  52. if (!m_keyEntries.TryGetValue(alias, out JksKeyEntry keyEntry))
  53. return null;
  54. if (!JksObfuscationAlg.Equals(keyEntry.keyData.EncryptionAlgorithm))
  55. throw new IOException("unknown encryption algorithm");
  56. byte[] encryptedData = keyEntry.keyData.GetEncryptedData();
  57. // key length is encryptedData - salt - checksum
  58. int pkcs8Len = encryptedData.Length - 40;
  59. IDigest digest = DigestUtilities.GetDigest("SHA-1");
  60. // key decryption
  61. byte[] keyStream = CalculateKeyStream(digest, password, encryptedData, pkcs8Len);
  62. byte[] pkcs8Key = new byte[pkcs8Len];
  63. for (int i = 0; i < pkcs8Len; ++i)
  64. {
  65. pkcs8Key[i] = (byte)(encryptedData[20 + i] ^ keyStream[i]);
  66. }
  67. Array.Clear(keyStream, 0, keyStream.Length);
  68. // integrity check
  69. byte[] checksum = GetKeyChecksum(digest, password, pkcs8Key);
  70. if (!Arrays.ConstantTimeAreEqual(20, encryptedData, pkcs8Len + 20, checksum, 0))
  71. throw new IOException("cannot recover key");
  72. return PrivateKeyFactory.CreateKey(pkcs8Key);
  73. }
  74. private byte[] GetKeyChecksum(IDigest digest, char[] password, byte[] pkcs8Key)
  75. {
  76. AddPassword(digest, password);
  77. return DigestUtilities.DoFinal(digest, pkcs8Key);
  78. }
  79. private byte[] CalculateKeyStream(IDigest digest, char[] password, byte[] salt, int count)
  80. {
  81. byte[] keyStream = new byte[count];
  82. byte[] hash = Arrays.CopyOf(salt, 20);
  83. int index = 0;
  84. while (index < count)
  85. {
  86. AddPassword(digest, password);
  87. digest.BlockUpdate(hash, 0, hash.Length);
  88. digest.DoFinal(hash, 0);
  89. int length = System.Math.Min(hash.Length, keyStream.Length - index);
  90. Array.Copy(hash, 0, keyStream, index, length);
  91. index += length;
  92. }
  93. return keyStream;
  94. }
  95. public X509Certificate[] GetCertificateChain(string alias)
  96. {
  97. if (m_keyEntries.TryGetValue(alias, out var keyEntry))
  98. return CloneChain(keyEntry.chain);
  99. return null;
  100. }
  101. public X509Certificate GetCertificate(string alias)
  102. {
  103. if (m_certificateEntries.TryGetValue(alias, out var certEntry))
  104. return certEntry.cert;
  105. if (m_keyEntries.TryGetValue(alias, out var keyEntry))
  106. return keyEntry.chain?[0];
  107. return null;
  108. }
  109. public DateTime? GetCreationDate(string alias)
  110. {
  111. if (m_certificateEntries.TryGetValue(alias, out var certEntry))
  112. return certEntry.date;
  113. if (m_keyEntries.TryGetValue(alias, out var keyEntry))
  114. return keyEntry.date;
  115. return null;
  116. }
  117. /// <exception cref="IOException"/>
  118. public void SetKeyEntry(string alias, AsymmetricKeyParameter key, char[] password, X509Certificate[] chain)
  119. {
  120. alias = ConvertAlias(alias);
  121. if (ContainsAlias(alias))
  122. throw new IOException("alias [" + alias + "] already in use");
  123. byte[] pkcs8Key = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key).GetEncoded();
  124. byte[] protectedKey = new byte[pkcs8Key.Length + 40];
  125. SecureRandom rnd = CryptoServicesRegistrar.GetSecureRandom();
  126. rnd.NextBytes(protectedKey, 0, 20);
  127. IDigest digest = DigestUtilities.GetDigest("SHA-1");
  128. byte[] checksum = GetKeyChecksum(digest, password, pkcs8Key);
  129. Array.Copy(checksum, 0, protectedKey, 20 + pkcs8Key.Length, 20);
  130. byte[] keyStream = CalculateKeyStream(digest, password, protectedKey, pkcs8Key.Length);
  131. for (int i = 0; i != keyStream.Length; i++)
  132. {
  133. protectedKey[20 + i] = (byte)(pkcs8Key[i] ^ keyStream[i]);
  134. }
  135. Array.Clear(keyStream, 0, keyStream.Length);
  136. try
  137. {
  138. var epki = new EncryptedPrivateKeyInfo(JksObfuscationAlg, protectedKey);
  139. m_keyEntries.Add(alias, new JksKeyEntry(DateTime.UtcNow, epki.GetEncoded(), CloneChain(chain)));
  140. }
  141. catch (Exception e)
  142. {
  143. throw new IOException("unable to encode encrypted private key", e);
  144. }
  145. }
  146. /// <exception cref="IOException"/>
  147. public void SetKeyEntry(string alias, byte[] key, X509Certificate[] chain)
  148. {
  149. alias = ConvertAlias(alias);
  150. if (ContainsAlias(alias))
  151. throw new IOException("alias [" + alias + "] already in use");
  152. m_keyEntries.Add(alias, new JksKeyEntry(DateTime.UtcNow, key, CloneChain(chain)));
  153. }
  154. /// <exception cref="IOException"/>
  155. public void SetCertificateEntry(string alias, X509Certificate cert)
  156. {
  157. alias = ConvertAlias(alias);
  158. if (ContainsAlias(alias))
  159. throw new IOException("alias [" + alias + "] already in use");
  160. m_certificateEntries.Add(alias, new JksTrustedCertEntry(DateTime.UtcNow, cert));
  161. }
  162. public void DeleteEntry(string alias)
  163. {
  164. if (!m_keyEntries.Remove(alias))
  165. {
  166. m_certificateEntries.Remove(alias);
  167. }
  168. }
  169. public IEnumerable<string> Aliases
  170. {
  171. get
  172. {
  173. var aliases = new HashSet<string>(m_certificateEntries.Keys);
  174. aliases.UnionWith(m_keyEntries.Keys);
  175. return CollectionUtilities.Proxy(aliases);
  176. }
  177. }
  178. public bool ContainsAlias(string alias)
  179. {
  180. return IsCertificateEntry(alias) || IsKeyEntry(alias);
  181. }
  182. public int Count
  183. {
  184. get { return m_certificateEntries.Count + m_keyEntries.Count; }
  185. }
  186. public bool IsKeyEntry(string alias)
  187. {
  188. return m_keyEntries.ContainsKey(alias);
  189. }
  190. public bool IsCertificateEntry(string alias)
  191. {
  192. return m_certificateEntries.ContainsKey(alias);
  193. }
  194. public string GetCertificateAlias(X509Certificate cert)
  195. {
  196. foreach (var entry in m_certificateEntries)
  197. {
  198. if (entry.Value.cert.Equals(cert))
  199. return entry.Key;
  200. }
  201. return null;
  202. }
  203. /// <exception cref="IOException"/>
  204. public void Save(Stream stream, char[] password)
  205. {
  206. if (stream == null)
  207. throw new ArgumentNullException(nameof(stream));
  208. if (password == null)
  209. throw new ArgumentNullException(nameof(password));
  210. IDigest checksumDigest = CreateChecksumDigest(password);
  211. BinaryWriter bw = new BinaryWriter(new DigestStream(stream, null, checksumDigest));
  212. BinaryWriters.WriteInt32BigEndian(bw, Magic);
  213. BinaryWriters.WriteInt32BigEndian(bw, 2);
  214. BinaryWriters.WriteInt32BigEndian(bw, Count);
  215. foreach (var entry in m_keyEntries)
  216. {
  217. string alias = entry.Key;
  218. JksKeyEntry keyEntry = entry.Value;
  219. BinaryWriters.WriteInt32BigEndian(bw, 1);
  220. WriteUtf(bw, alias);
  221. WriteDateTime(bw, keyEntry.date);
  222. WriteBufferWithInt32Length(bw, keyEntry.keyData.GetEncoded());
  223. X509Certificate[] chain = keyEntry.chain;
  224. int chainLength = chain == null ? 0 : chain.Length;
  225. BinaryWriters.WriteInt32BigEndian(bw, chainLength);
  226. for (int i = 0; i < chainLength; ++i)
  227. {
  228. WriteTypedCertificate(bw, chain[i]);
  229. }
  230. }
  231. foreach (var entry in m_certificateEntries)
  232. {
  233. string alias = entry.Key;
  234. JksTrustedCertEntry certEntry = entry.Value;
  235. BinaryWriters.WriteInt32BigEndian(bw, 2);
  236. WriteUtf(bw, alias);
  237. WriteDateTime(bw, certEntry.date);
  238. WriteTypedCertificate(bw, certEntry.cert);
  239. }
  240. byte[] checksum = DigestUtilities.DoFinal(checksumDigest);
  241. bw.Write(checksum);
  242. bw.Flush();
  243. }
  244. /// <exception cref="IOException"/>
  245. public void Load(Stream stream, char[] password)
  246. {
  247. if (stream == null)
  248. throw new ArgumentNullException(nameof(stream));
  249. m_certificateEntries.Clear();
  250. m_keyEntries.Clear();
  251. using (var storeStream = ValidateStream(stream, password))
  252. {
  253. BinaryReader br = new BinaryReader(storeStream);
  254. int magic = BinaryReaders.ReadInt32BigEndian(br);
  255. int storeVersion = BinaryReaders.ReadInt32BigEndian(br);
  256. if (!(magic == Magic && (storeVersion == 1 || storeVersion == 2)))
  257. throw new IOException("Invalid keystore format");
  258. int numEntries = BinaryReaders.ReadInt32BigEndian(br);
  259. for (int t = 0; t < numEntries; t++)
  260. {
  261. int tag = BinaryReaders.ReadInt32BigEndian(br);
  262. switch (tag)
  263. {
  264. case 1: // keys
  265. {
  266. string alias = ReadUtf(br);
  267. DateTime date = ReadDateTime(br);
  268. // encrypted key data
  269. byte[] keyData = ReadBufferWithInt32Length(br);
  270. // certificate chain
  271. int chainLength = BinaryReaders.ReadInt32BigEndian(br);
  272. X509Certificate[] chain = null;
  273. if (chainLength > 0)
  274. {
  275. var certs = new List<X509Certificate>(System.Math.Min(10, chainLength));
  276. for (int certNo = 0; certNo != chainLength; certNo++)
  277. {
  278. certs.Add(ReadTypedCertificate(br, storeVersion));
  279. }
  280. chain = certs.ToArray();
  281. }
  282. m_keyEntries.Add(alias, new JksKeyEntry(date, keyData, chain));
  283. break;
  284. }
  285. case 2: // certificate
  286. {
  287. string alias = ReadUtf(br);
  288. DateTime date = ReadDateTime(br);
  289. X509Certificate cert = ReadTypedCertificate(br, storeVersion);
  290. m_certificateEntries.Add(alias, new JksTrustedCertEntry(date, cert));
  291. break;
  292. }
  293. default:
  294. throw new IOException("unable to discern entry type");
  295. }
  296. }
  297. if (storeStream.Position != storeStream.Length)
  298. throw new IOException("password incorrect or store tampered with");
  299. }
  300. }
  301. /*
  302. * Validate password takes the checksum of the store and will either.
  303. * 1. If password is null, load the store into memory, return the result.
  304. * 2. If password is not null, load the store into memory, test the checksum, and if successful return
  305. * a new input stream instance of the store.
  306. * 3. Fail if there is a password and an invalid checksum.
  307. *
  308. * @param inputStream The input stream.
  309. * @param password the password.
  310. * @return Either the passed in input stream or a new input stream.
  311. */
  312. /// <exception cref="IOException"/>
  313. private ErasableByteStream ValidateStream(Stream inputStream, char[] password)
  314. {
  315. byte[] rawStore = Streams.ReadAll(inputStream);
  316. int checksumPos = rawStore.Length - 20;
  317. if (password != null)
  318. {
  319. byte[] checksum = CalculateChecksum(password, rawStore, 0, checksumPos);
  320. if (!Arrays.ConstantTimeAreEqual(20, checksum, 0, rawStore, checksumPos))
  321. {
  322. Array.Clear(rawStore, 0, rawStore.Length);
  323. throw new IOException("password incorrect or store tampered with");
  324. }
  325. }
  326. return new ErasableByteStream(rawStore, 0, checksumPos);
  327. }
  328. private static void AddPassword(IDigest digest, char[] password)
  329. {
  330. // Encoding.BigEndianUnicode
  331. for (int i = 0; i < password.Length; ++i)
  332. {
  333. digest.Update((byte)(password[i] >> 8));
  334. digest.Update((byte)password[i]);
  335. }
  336. }
  337. private static byte[] CalculateChecksum(char[] password, byte[] buffer, int offset, int length)
  338. {
  339. IDigest checksumDigest = CreateChecksumDigest(password);
  340. checksumDigest.BlockUpdate(buffer, offset, length);
  341. return DigestUtilities.DoFinal(checksumDigest);
  342. }
  343. private static X509Certificate[] CloneChain(X509Certificate[] chain)
  344. {
  345. return (X509Certificate[])chain?.Clone();
  346. }
  347. private static string ConvertAlias(string alias)
  348. {
  349. return alias.ToLowerInvariant();
  350. }
  351. private static IDigest CreateChecksumDigest(char[] password)
  352. {
  353. IDigest digest = DigestUtilities.GetDigest("SHA-1");
  354. AddPassword(digest, password);
  355. //
  356. // This "Mighty Aphrodite" string goes all the way back to the
  357. // first java betas in the mid 90's, why who knows? But see
  358. // https://cryptosense.com/mighty-aphrodite-dark-secrets-of-the-java-keystore/
  359. //
  360. byte[] prefix = Encoding.UTF8.GetBytes("Mighty Aphrodite");
  361. digest.BlockUpdate(prefix, 0, prefix.Length);
  362. return digest;
  363. }
  364. private static byte[] ReadBufferWithInt16Length(BinaryReader br)
  365. {
  366. int length = BinaryReaders.ReadInt16BigEndian(br);
  367. return BinaryReaders.ReadBytesFully(br, length);
  368. }
  369. private static byte[] ReadBufferWithInt32Length(BinaryReader br)
  370. {
  371. int length = BinaryReaders.ReadInt32BigEndian(br);
  372. return BinaryReaders.ReadBytesFully(br, length);
  373. }
  374. private static DateTime ReadDateTime(BinaryReader br)
  375. {
  376. long unixMS = BinaryReaders.ReadInt64BigEndian(br);
  377. return DateTimeUtilities.UnixMsToDateTime(unixMS);
  378. }
  379. private static X509Certificate ReadTypedCertificate(BinaryReader br, int storeVersion)
  380. {
  381. if (storeVersion == 2)
  382. {
  383. string certFormat = ReadUtf(br);
  384. if ("X.509" != certFormat)
  385. throw new IOException("Unsupported certificate format: " + certFormat);
  386. }
  387. byte[] certData = ReadBufferWithInt32Length(br);
  388. try
  389. {
  390. return new X509Certificate(certData);
  391. }
  392. finally
  393. {
  394. Array.Clear(certData, 0, certData.Length);
  395. }
  396. }
  397. private static string ReadUtf(BinaryReader br)
  398. {
  399. byte[] utfBytes = ReadBufferWithInt16Length(br);
  400. /*
  401. * FIXME JKS actually uses a "modified UTF-8" format. For the moment we will just support single-byte
  402. * encodings that aren't null bytes.
  403. */
  404. for (int i = 0; i < utfBytes.Length; ++i)
  405. {
  406. byte utfByte = utfBytes[i];
  407. if (utfByte == 0 || (utfByte & 0x80) != 0)
  408. throw new NotSupportedException("Currently missing support for modified UTF-8 encoding in JKS");
  409. }
  410. return Encoding.UTF8.GetString(utfBytes);
  411. }
  412. private static void WriteBufferWithInt16Length(BinaryWriter bw, byte[] buffer)
  413. {
  414. BinaryWriters.WriteInt16BigEndian(bw, Convert.ToInt16(buffer.Length));
  415. bw.Write(buffer);
  416. }
  417. private static void WriteBufferWithInt32Length(BinaryWriter bw, byte[] buffer)
  418. {
  419. BinaryWriters.WriteInt32BigEndian(bw, buffer.Length);
  420. bw.Write(buffer);
  421. }
  422. private static void WriteDateTime(BinaryWriter bw, DateTime dateTime)
  423. {
  424. long unixMS = DateTimeUtilities.DateTimeToUnixMs(dateTime);
  425. BinaryWriters.WriteInt64BigEndian(bw, unixMS);
  426. }
  427. private static void WriteTypedCertificate(BinaryWriter bw, X509Certificate cert)
  428. {
  429. WriteUtf(bw, "X.509");
  430. WriteBufferWithInt32Length(bw, cert.GetEncoded());
  431. }
  432. private static void WriteUtf(BinaryWriter bw, string s)
  433. {
  434. byte[] utfBytes = Encoding.UTF8.GetBytes(s);
  435. /*
  436. * FIXME JKS actually uses a "modified UTF-8" format. For the moment we will just support single-byte
  437. * encodings that aren't null bytes.
  438. */
  439. for (int i = 0; i < utfBytes.Length; ++i)
  440. {
  441. byte utfByte = utfBytes[i];
  442. if (utfByte == 0 || (utfByte & 0x80) != 0)
  443. throw new NotSupportedException("Currently missing support for modified UTF-8 encoding in JKS");
  444. }
  445. WriteBufferWithInt16Length(bw, utfBytes);
  446. }
  447. /**
  448. * JksTrustedCertEntry is a internal container for the certificate entry.
  449. */
  450. private sealed class JksTrustedCertEntry
  451. {
  452. internal readonly DateTime date;
  453. internal readonly X509Certificate cert;
  454. internal JksTrustedCertEntry(DateTime date, X509Certificate cert)
  455. {
  456. this.date = date;
  457. this.cert = cert;
  458. }
  459. }
  460. private sealed class JksKeyEntry
  461. {
  462. internal readonly DateTime date;
  463. internal readonly EncryptedPrivateKeyInfo keyData;
  464. internal readonly X509Certificate[] chain;
  465. internal JksKeyEntry(DateTime date, byte[] keyData, X509Certificate[] chain)
  466. {
  467. this.date = date;
  468. this.keyData = EncryptedPrivateKeyInfo.GetInstance(Asn1Sequence.GetInstance(keyData));
  469. this.chain = chain;
  470. }
  471. }
  472. private sealed class ErasableByteStream
  473. : MemoryStream
  474. {
  475. internal ErasableByteStream(byte[] buffer, int index, int count)
  476. : base(buffer, index, count, false, true)
  477. {
  478. }
  479. protected override void Dispose(bool disposing)
  480. {
  481. if (disposing)
  482. {
  483. Position = 0L;
  484. byte[] rawStore = GetBuffer();
  485. Array.Clear(rawStore, 0, rawStore.Length);
  486. }
  487. base.Dispose(disposing);
  488. }
  489. }
  490. }
  491. }
  492. #pragma warning restore
  493. #endif