FastTlsAeadCipher.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls;
  8. using Best.HTTP.Shared.PlatformSupport.Memory;
  9. namespace Best.HTTP.Shared.TLS.Crypto.Impl
  10. {
  11. /// <summary>A generic TLS 1.2 AEAD cipher.</summary>
  12. [Best.HTTP.Shared.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  13. public sealed class FastTlsAeadCipher
  14. : TlsCipher
  15. {
  16. public const int AEAD_CCM = 1;
  17. public const int AEAD_CHACHA20_POLY1305 = 2;
  18. public const int AEAD_GCM = 3;
  19. private const int NONCE_RFC5288 = 1;
  20. private const int NONCE_RFC7905 = 2;
  21. private readonly TlsCryptoParameters m_cryptoParams;
  22. private readonly int m_keySize;
  23. private readonly int m_macSize;
  24. private readonly int m_fixed_iv_length;
  25. private readonly int m_record_iv_length;
  26. private readonly TlsAeadCipherImpl m_decryptCipher, m_encryptCipher;
  27. private readonly byte[] m_decryptNonce, m_encryptNonce;
  28. private readonly bool m_isTlsV13;
  29. private readonly int m_nonceMode;
  30. /// <exception cref="IOException"/>
  31. public FastTlsAeadCipher(TlsCryptoParameters cryptoParams, TlsAeadCipherImpl encryptCipher,
  32. TlsAeadCipherImpl decryptCipher, int keySize, int macSize, int aeadType)
  33. {
  34. SecurityParameters securityParameters = cryptoParams.SecurityParameters;
  35. ProtocolVersion negotiatedVersion = securityParameters.NegotiatedVersion;
  36. if (!TlsImplUtilities.IsTlsV12(negotiatedVersion))
  37. throw new TlsFatalAlert(AlertDescription.internal_error);
  38. this.m_isTlsV13 = TlsImplUtilities.IsTlsV13(negotiatedVersion);
  39. this.m_nonceMode = GetNonceMode(m_isTlsV13, aeadType);
  40. switch (m_nonceMode)
  41. {
  42. case NONCE_RFC5288:
  43. this.m_fixed_iv_length = 4;
  44. this.m_record_iv_length = 8;
  45. break;
  46. case NONCE_RFC7905:
  47. this.m_fixed_iv_length = 12;
  48. this.m_record_iv_length = 0;
  49. break;
  50. default:
  51. throw new TlsFatalAlert(AlertDescription.internal_error);
  52. }
  53. this.m_cryptoParams = cryptoParams;
  54. this.m_keySize = keySize;
  55. this.m_macSize = macSize;
  56. this.m_decryptCipher = decryptCipher;
  57. this.m_encryptCipher = encryptCipher;
  58. this.m_decryptNonce = new byte[m_fixed_iv_length];
  59. this.m_encryptNonce = new byte[m_fixed_iv_length];
  60. bool isServer = cryptoParams.IsServer;
  61. if (m_isTlsV13)
  62. {
  63. RekeyCipher(securityParameters, decryptCipher, m_decryptNonce, !isServer);
  64. RekeyCipher(securityParameters, encryptCipher, m_encryptNonce, isServer);
  65. return;
  66. }
  67. int keyBlockSize = (2 * keySize) + (2 * m_fixed_iv_length);
  68. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  69. Span<byte> keyBlock = keyBlockSize <= 512
  70. ? stackalloc byte[keyBlockSize]
  71. : new byte[keyBlockSize];
  72. TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock);
  73. if (isServer)
  74. {
  75. decryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..];
  76. encryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..];
  77. keyBlock[..m_fixed_iv_length].CopyTo(m_decryptNonce); keyBlock = keyBlock[m_fixed_iv_length..];
  78. keyBlock[..m_fixed_iv_length].CopyTo(m_encryptNonce); keyBlock = keyBlock[m_fixed_iv_length..];
  79. }
  80. else
  81. {
  82. encryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..];
  83. decryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..];
  84. keyBlock[..m_fixed_iv_length].CopyTo(m_encryptNonce); keyBlock = keyBlock[m_fixed_iv_length..];
  85. keyBlock[..m_fixed_iv_length].CopyTo(m_decryptNonce); keyBlock = keyBlock[m_fixed_iv_length..];
  86. }
  87. if (!keyBlock.IsEmpty)
  88. throw new TlsFatalAlert(AlertDescription.internal_error);
  89. #else
  90. byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize);
  91. int pos = 0;
  92. if (isServer)
  93. {
  94. decryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  95. encryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  96. Array.Copy(keyBlock, pos, m_decryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  97. Array.Copy(keyBlock, pos, m_encryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  98. }
  99. else
  100. {
  101. encryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  102. decryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  103. Array.Copy(keyBlock, pos, m_encryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  104. Array.Copy(keyBlock, pos, m_decryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  105. }
  106. if (pos != keyBlockSize)
  107. throw new TlsFatalAlert(AlertDescription.internal_error);
  108. #endif
  109. int nonceLength = m_fixed_iv_length + m_record_iv_length;
  110. // NOTE: Ensure dummy nonce is not part of the generated sequence(s)
  111. byte[] dummyNonce = new byte[nonceLength];
  112. dummyNonce[0] = (byte)~m_encryptNonce[0];
  113. dummyNonce[1] = (byte)~m_decryptNonce[1];
  114. encryptCipher.Init(dummyNonce, macSize, null);
  115. decryptCipher.Init(dummyNonce, macSize, null);
  116. }
  117. public int GetCiphertextDecodeLimit(int plaintextLimit)
  118. {
  119. return plaintextLimit + m_macSize + m_record_iv_length + (m_isTlsV13 ? 1 : 0);
  120. }
  121. public int GetCiphertextEncodeLimit(int plaintextLength, int plaintextLimit)
  122. {
  123. int innerPlaintextLimit = plaintextLength;
  124. if (m_isTlsV13)
  125. {
  126. // TODO[tls13] Add support for padding
  127. int maxPadding = 0;
  128. innerPlaintextLimit = 1 + System.Math.Min(plaintextLimit, plaintextLength + maxPadding);
  129. }
  130. return innerPlaintextLimit + m_macSize + m_record_iv_length;
  131. }
  132. public int GetPlaintextLimit(int ciphertextLimit)
  133. {
  134. return ciphertextLimit - m_macSize - m_record_iv_length - (m_isTlsV13 ? 1 : 0);
  135. }
  136. public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion,
  137. int headerAllocation, byte[] plaintext, int plaintextOffset, int plaintextLength)
  138. {
  139. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  140. return EncodePlaintext(seqNo, contentType, recordVersion, headerAllocation,
  141. plaintext.AsSpan(plaintextOffset, plaintextLength));
  142. #else
  143. byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length];
  144. switch (m_nonceMode)
  145. {
  146. case NONCE_RFC5288:
  147. Array.Copy(m_encryptNonce, 0, nonce, 0, m_encryptNonce.Length);
  148. // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number.
  149. TlsUtilities.WriteUint64(seqNo, nonce, m_encryptNonce.Length);
  150. break;
  151. case NONCE_RFC7905:
  152. TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8);
  153. for (int i = 0; i < m_encryptNonce.Length; ++i)
  154. {
  155. nonce[i] ^= m_encryptNonce[i];
  156. }
  157. break;
  158. default:
  159. throw new TlsFatalAlert(AlertDescription.internal_error);
  160. }
  161. int extraLength = m_isTlsV13 ? 1 : 0;
  162. // TODO[tls13] If we support adding padding to TLSInnerPlaintext, this will need review
  163. int encryptionLength = m_encryptCipher.GetOutputSize(plaintextLength + extraLength);
  164. int ciphertextLength = m_record_iv_length + encryptionLength;
  165. byte[] output = BufferPool.Get(headerAllocation + ciphertextLength, true); //new byte[headerAllocation + ciphertextLength];
  166. int outputPos = headerAllocation;
  167. if (m_record_iv_length != 0)
  168. {
  169. Array.Copy(nonce, nonce.Length - m_record_iv_length, output, outputPos, m_record_iv_length);
  170. outputPos += m_record_iv_length;
  171. }
  172. short recordType = m_isTlsV13 ? ContentType.application_data : contentType;
  173. byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength,
  174. plaintextLength);
  175. try
  176. {
  177. Array.Copy(plaintext, plaintextOffset, output, outputPos, plaintextLength);
  178. if (m_isTlsV13)
  179. {
  180. output[outputPos + plaintextLength] = (byte)contentType;
  181. }
  182. m_encryptCipher.Init(nonce, m_macSize, additionalData);
  183. outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintextLength + extraLength, output,
  184. outputPos);
  185. }
  186. catch (IOException e)
  187. {
  188. throw e;
  189. }
  190. catch (Exception e)
  191. {
  192. throw new TlsFatalAlert(AlertDescription.internal_error, e);
  193. }
  194. if (outputPos != headerAllocation + ciphertextLength)
  195. {
  196. // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction.
  197. throw new TlsFatalAlert(AlertDescription.internal_error);
  198. }
  199. return new TlsEncodeResult(output, 0, outputPos, recordType, true);
  200. #endif
  201. }
  202. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  203. public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion,
  204. int headerAllocation, ReadOnlySpan<byte> plaintext)
  205. {
  206. byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length];
  207. switch (m_nonceMode)
  208. {
  209. case NONCE_RFC5288:
  210. Array.Copy(m_encryptNonce, 0, nonce, 0, m_encryptNonce.Length);
  211. // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number.
  212. TlsUtilities.WriteUint64(seqNo, nonce, m_encryptNonce.Length);
  213. break;
  214. case NONCE_RFC7905:
  215. TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8);
  216. for (int i = 0; i < m_encryptNonce.Length; ++i)
  217. {
  218. nonce[i] ^= m_encryptNonce[i];
  219. }
  220. break;
  221. default:
  222. throw new TlsFatalAlert(AlertDescription.internal_error);
  223. }
  224. int extraLength = m_isTlsV13 ? 1 : 0;
  225. // TODO[tls13] If we support adding padding to TLSInnerPlaintext, this will need review
  226. int encryptionLength = m_encryptCipher.GetOutputSize(plaintext.Length + extraLength);
  227. int ciphertextLength = m_record_iv_length + encryptionLength;
  228. byte[] output = new byte[headerAllocation + ciphertextLength];
  229. int outputPos = headerAllocation;
  230. if (m_record_iv_length != 0)
  231. {
  232. Array.Copy(nonce, nonce.Length - m_record_iv_length, output, outputPos, m_record_iv_length);
  233. outputPos += m_record_iv_length;
  234. }
  235. short recordType = m_isTlsV13 ? ContentType.application_data : contentType;
  236. byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength,
  237. plaintext.Length);
  238. try
  239. {
  240. plaintext.CopyTo(output.AsSpan(outputPos));
  241. if (m_isTlsV13)
  242. {
  243. output[outputPos + plaintext.Length] = (byte)contentType;
  244. }
  245. m_encryptCipher.Init(nonce, m_macSize, additionalData);
  246. outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintext.Length + extraLength, output,
  247. outputPos);
  248. }
  249. catch (IOException e)
  250. {
  251. throw e;
  252. }
  253. catch (Exception e)
  254. {
  255. throw new TlsFatalAlert(AlertDescription.internal_error, e);
  256. }
  257. if (outputPos != output.Length)
  258. {
  259. // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction.
  260. throw new TlsFatalAlert(AlertDescription.internal_error);
  261. }
  262. return new TlsEncodeResult(output, 0, output.Length, recordType);
  263. }
  264. #endif
  265. public TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion,
  266. byte[] ciphertext, int ciphertextOffset, int ciphertextLength)
  267. {
  268. if (GetPlaintextLimit(ciphertextLength) < 0)
  269. throw new TlsFatalAlert(AlertDescription.decode_error);
  270. byte[] nonce = new byte[m_decryptNonce.Length + m_record_iv_length];
  271. switch (m_nonceMode)
  272. {
  273. case NONCE_RFC5288:
  274. Array.Copy(m_decryptNonce, 0, nonce, 0, m_decryptNonce.Length);
  275. Array.Copy(ciphertext, ciphertextOffset, nonce, nonce.Length - m_record_iv_length,
  276. m_record_iv_length);
  277. break;
  278. case NONCE_RFC7905:
  279. TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8);
  280. for (int i = 0; i < m_decryptNonce.Length; ++i)
  281. {
  282. nonce[i] ^= m_decryptNonce[i];
  283. }
  284. break;
  285. default:
  286. throw new TlsFatalAlert(AlertDescription.internal_error);
  287. }
  288. int encryptionOffset = ciphertextOffset + m_record_iv_length;
  289. int encryptionLength = ciphertextLength - m_record_iv_length;
  290. int plaintextLength = m_decryptCipher.GetOutputSize(encryptionLength);
  291. byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength,
  292. plaintextLength);
  293. int outputPos;
  294. try
  295. {
  296. m_decryptCipher.Init(nonce, m_macSize, additionalData);
  297. outputPos = m_decryptCipher.DoFinal(ciphertext, encryptionOffset, encryptionLength, ciphertext,
  298. encryptionOffset);
  299. }
  300. catch (IOException e)
  301. {
  302. throw;
  303. }
  304. catch (Exception e)
  305. {
  306. throw new TlsFatalAlert(AlertDescription.bad_record_mac, e);
  307. }
  308. if (outputPos != plaintextLength)
  309. {
  310. // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction.
  311. throw new TlsFatalAlert(AlertDescription.internal_error);
  312. }
  313. short contentType = recordType;
  314. if (m_isTlsV13)
  315. {
  316. // Strip padding and read true content type from TLSInnerPlaintext
  317. int pos = plaintextLength;
  318. for (; ; )
  319. {
  320. if (--pos < 0)
  321. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  322. byte octet = ciphertext[encryptionOffset + pos];
  323. if (0 != octet)
  324. {
  325. contentType = (short)(octet & 0xFF);
  326. plaintextLength = pos;
  327. break;
  328. }
  329. }
  330. }
  331. return new TlsDecodeResult(ciphertext, encryptionOffset, plaintextLength, contentType);
  332. }
  333. public void RekeyDecoder()
  334. {
  335. RekeyCipher(m_cryptoParams.SecurityParameters, m_decryptCipher, m_decryptNonce, !m_cryptoParams.IsServer);
  336. }
  337. public void RekeyEncoder()
  338. {
  339. RekeyCipher(m_cryptoParams.SecurityParameters, m_encryptCipher, m_encryptNonce, m_cryptoParams.IsServer);
  340. }
  341. public bool UsesOpaqueRecordType
  342. {
  343. get { return m_isTlsV13; }
  344. }
  345. private byte[] GetAdditionalData(long seqNo, short recordType, ProtocolVersion recordVersion,
  346. int ciphertextLength, int plaintextLength)
  347. {
  348. if (m_isTlsV13)
  349. {
  350. /*
  351. * TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length
  352. */
  353. byte[] additional_data = new byte[5];
  354. TlsUtilities.WriteUint8(recordType, additional_data, 0);
  355. TlsUtilities.WriteVersion(recordVersion, additional_data, 1);
  356. TlsUtilities.WriteUint16(ciphertextLength, additional_data, 3);
  357. return additional_data;
  358. }
  359. else
  360. {
  361. /*
  362. * seq_num + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length
  363. */
  364. byte[] additional_data = new byte[13];
  365. TlsUtilities.WriteUint64(seqNo, additional_data, 0);
  366. TlsUtilities.WriteUint8(recordType, additional_data, 8);
  367. TlsUtilities.WriteVersion(recordVersion, additional_data, 9);
  368. TlsUtilities.WriteUint16(plaintextLength, additional_data, 11);
  369. return additional_data;
  370. }
  371. }
  372. private void RekeyCipher(SecurityParameters securityParameters, TlsAeadCipherImpl cipher,
  373. byte[] nonce, bool serverSecret)
  374. {
  375. if (!m_isTlsV13)
  376. throw new TlsFatalAlert(AlertDescription.internal_error);
  377. TlsSecret secret = serverSecret
  378. ? securityParameters.TrafficSecretServer
  379. : securityParameters.TrafficSecretClient;
  380. // TODO[tls13] For early data, have to disable server->client
  381. if (null == secret)
  382. throw new TlsFatalAlert(AlertDescription.internal_error);
  383. Setup13Cipher(cipher, nonce, secret, securityParameters.PrfCryptoHashAlgorithm);
  384. }
  385. private void Setup13Cipher(TlsAeadCipherImpl cipher, byte[] nonce, TlsSecret secret,
  386. int cryptoHashAlgorithm)
  387. {
  388. byte[] key = TlsCryptoUtilities.HkdfExpandLabel(secret, cryptoHashAlgorithm, "key",
  389. TlsUtilities.EmptyBytes, m_keySize).Extract();
  390. byte[] iv = TlsCryptoUtilities.HkdfExpandLabel(secret, cryptoHashAlgorithm, "iv", TlsUtilities.EmptyBytes,
  391. m_fixed_iv_length).Extract();
  392. cipher.SetKey(key, 0, m_keySize);
  393. Array.Copy(iv, 0, nonce, 0, m_fixed_iv_length);
  394. // NOTE: Ensure dummy nonce is not part of the generated sequence(s)
  395. iv[0] ^= 0x80;
  396. cipher.Init(iv, m_macSize, null);
  397. }
  398. private static int GetNonceMode(bool isTLSv13, int aeadType)
  399. {
  400. switch (aeadType)
  401. {
  402. case AEAD_CCM:
  403. case AEAD_GCM:
  404. return isTLSv13 ? NONCE_RFC7905 : NONCE_RFC5288;
  405. case AEAD_CHACHA20_POLY1305:
  406. return NONCE_RFC7905;
  407. default:
  408. throw new TlsFatalAlert(AlertDescription.internal_error);
  409. }
  410. }
  411. }
  412. }
  413. #pragma warning restore
  414. #endif