TlsAeadCipher.cs 20 KB

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