TlsAeadCipher.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. namespace BestHTTP.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. byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize);
  64. int pos = 0;
  65. if (isServer)
  66. {
  67. decryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  68. encryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  69. Array.Copy(keyBlock, pos, m_decryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  70. Array.Copy(keyBlock, pos, m_encryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  71. }
  72. else
  73. {
  74. encryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  75. decryptCipher.SetKey(keyBlock, pos, keySize); pos += keySize;
  76. Array.Copy(keyBlock, pos, m_encryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  77. Array.Copy(keyBlock, pos, m_decryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length;
  78. }
  79. if (keyBlockSize != pos)
  80. throw new TlsFatalAlert(AlertDescription.internal_error);
  81. int nonceLength = m_fixed_iv_length + m_record_iv_length;
  82. // NOTE: Ensure dummy nonce is not part of the generated sequence(s)
  83. byte[] dummyNonce = new byte[nonceLength];
  84. dummyNonce[0] = (byte)~m_encryptNonce[0];
  85. dummyNonce[1] = (byte)~m_decryptNonce[1];
  86. encryptCipher.Init(dummyNonce, macSize, null);
  87. decryptCipher.Init(dummyNonce, macSize, null);
  88. }
  89. public virtual int GetCiphertextDecodeLimit(int plaintextLimit)
  90. {
  91. return plaintextLimit + m_macSize + m_record_iv_length + (m_isTlsV13 ? 1 : 0);
  92. }
  93. public virtual int GetCiphertextEncodeLimit(int plaintextLength, int plaintextLimit)
  94. {
  95. int innerPlaintextLimit = plaintextLength;
  96. if (m_isTlsV13)
  97. {
  98. // TODO[tls13] Add support for padding
  99. int maxPadding = 0;
  100. innerPlaintextLimit = 1 + System.Math.Min(plaintextLimit, plaintextLength + maxPadding);
  101. }
  102. return innerPlaintextLimit + m_macSize + m_record_iv_length;
  103. }
  104. public virtual int GetPlaintextLimit(int ciphertextLimit)
  105. {
  106. return ciphertextLimit - m_macSize - m_record_iv_length - (m_isTlsV13 ? 1 : 0);
  107. }
  108. public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion,
  109. int headerAllocation, byte[] plaintext, int plaintextOffset, int plaintextLength)
  110. {
  111. byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length];
  112. switch (m_nonceMode)
  113. {
  114. case NONCE_RFC5288:
  115. Array.Copy(m_encryptNonce, 0, nonce, 0, m_encryptNonce.Length);
  116. // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number.
  117. TlsUtilities.WriteUint64(seqNo, nonce, m_encryptNonce.Length);
  118. break;
  119. case NONCE_RFC7905:
  120. TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8);
  121. for (int i = 0; i < m_encryptNonce.Length; ++i)
  122. {
  123. nonce[i] ^= m_encryptNonce[i];
  124. }
  125. break;
  126. default:
  127. throw new TlsFatalAlert(AlertDescription.internal_error);
  128. }
  129. int extraLength = m_isTlsV13 ? 1 : 0;
  130. // TODO[tls13] If we support adding padding to TLSInnerPlaintext, this will need review
  131. int encryptionLength = m_encryptCipher.GetOutputSize(plaintextLength + extraLength);
  132. int ciphertextLength = m_record_iv_length + encryptionLength;
  133. byte[] output = new byte[headerAllocation + ciphertextLength];
  134. int outputPos = headerAllocation;
  135. if (m_record_iv_length != 0)
  136. {
  137. Array.Copy(nonce, nonce.Length - m_record_iv_length, output, outputPos, m_record_iv_length);
  138. outputPos += m_record_iv_length;
  139. }
  140. short recordType = m_isTlsV13 ? ContentType.application_data : contentType;
  141. byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength,
  142. plaintextLength);
  143. try
  144. {
  145. m_encryptCipher.Init(nonce, m_macSize, additionalData);
  146. Array.Copy(plaintext, plaintextOffset, output, outputPos, plaintextLength);
  147. if (m_isTlsV13)
  148. {
  149. output[outputPos + plaintextLength] = (byte)contentType;
  150. }
  151. outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintextLength + extraLength, output,
  152. outputPos);
  153. }
  154. catch (IOException e)
  155. {
  156. throw e;
  157. }
  158. catch (Exception e)
  159. {
  160. throw new TlsFatalAlert(AlertDescription.internal_error, e);
  161. }
  162. if (outputPos != output.Length)
  163. {
  164. // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction.
  165. throw new TlsFatalAlert(AlertDescription.internal_error);
  166. }
  167. return new TlsEncodeResult(output, 0, output.Length, recordType);
  168. }
  169. public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion,
  170. byte[] ciphertext, int ciphertextOffset, int ciphertextLength)
  171. {
  172. if (GetPlaintextLimit(ciphertextLength) < 0)
  173. throw new TlsFatalAlert(AlertDescription.decode_error);
  174. byte[] nonce = new byte[m_decryptNonce.Length + m_record_iv_length];
  175. switch (m_nonceMode)
  176. {
  177. case NONCE_RFC5288:
  178. Array.Copy(m_decryptNonce, 0, nonce, 0, m_decryptNonce.Length);
  179. Array.Copy(ciphertext, ciphertextOffset, nonce, nonce.Length - m_record_iv_length,
  180. m_record_iv_length);
  181. break;
  182. case NONCE_RFC7905:
  183. TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8);
  184. for (int i = 0; i < m_decryptNonce.Length; ++i)
  185. {
  186. nonce[i] ^= m_decryptNonce[i];
  187. }
  188. break;
  189. default:
  190. throw new TlsFatalAlert(AlertDescription.internal_error);
  191. }
  192. int encryptionOffset = ciphertextOffset + m_record_iv_length;
  193. int encryptionLength = ciphertextLength - m_record_iv_length;
  194. int plaintextLength = m_decryptCipher.GetOutputSize(encryptionLength);
  195. byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength,
  196. plaintextLength);
  197. int outputPos;
  198. try
  199. {
  200. m_decryptCipher.Init(nonce, m_macSize, additionalData);
  201. outputPos = m_decryptCipher.DoFinal(ciphertext, encryptionOffset, encryptionLength, ciphertext,
  202. encryptionOffset);
  203. }
  204. catch (IOException e)
  205. {
  206. throw e;
  207. }
  208. catch (Exception e)
  209. {
  210. throw new TlsFatalAlert(AlertDescription.bad_record_mac, e);
  211. }
  212. if (outputPos != plaintextLength)
  213. {
  214. // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction.
  215. throw new TlsFatalAlert(AlertDescription.internal_error);
  216. }
  217. short contentType = recordType;
  218. if (m_isTlsV13)
  219. {
  220. // Strip padding and read true content type from TLSInnerPlaintext
  221. int pos = plaintextLength;
  222. for (;;)
  223. {
  224. if (--pos < 0)
  225. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  226. byte octet = ciphertext[encryptionOffset + pos];
  227. if (0 != octet)
  228. {
  229. contentType = (short)(octet & 0xFF);
  230. plaintextLength = pos;
  231. break;
  232. }
  233. }
  234. }
  235. return new TlsDecodeResult(ciphertext, encryptionOffset, plaintextLength, contentType);
  236. }
  237. public virtual void RekeyDecoder()
  238. {
  239. RekeyCipher(m_cryptoParams.SecurityParameters, m_decryptCipher, m_decryptNonce, !m_cryptoParams.IsServer);
  240. }
  241. public virtual void RekeyEncoder()
  242. {
  243. RekeyCipher(m_cryptoParams.SecurityParameters, m_encryptCipher, m_encryptNonce, m_cryptoParams.IsServer);
  244. }
  245. public virtual bool UsesOpaqueRecordType
  246. {
  247. get { return m_isTlsV13; }
  248. }
  249. protected virtual byte[] GetAdditionalData(long seqNo, short recordType, ProtocolVersion recordVersion,
  250. int ciphertextLength, int plaintextLength)
  251. {
  252. if (m_isTlsV13)
  253. {
  254. /*
  255. * TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length
  256. */
  257. byte[] additional_data = new byte[5];
  258. TlsUtilities.WriteUint8(recordType, additional_data, 0);
  259. TlsUtilities.WriteVersion(recordVersion, additional_data, 1);
  260. TlsUtilities.WriteUint16(ciphertextLength, additional_data, 3);
  261. return additional_data;
  262. }
  263. else
  264. {
  265. /*
  266. * seq_num + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length
  267. */
  268. byte[] additional_data = new byte[13];
  269. TlsUtilities.WriteUint64(seqNo, additional_data, 0);
  270. TlsUtilities.WriteUint8(recordType, additional_data, 8);
  271. TlsUtilities.WriteVersion(recordVersion, additional_data, 9);
  272. TlsUtilities.WriteUint16(plaintextLength, additional_data, 11);
  273. return additional_data;
  274. }
  275. }
  276. protected virtual void RekeyCipher(SecurityParameters securityParameters, TlsAeadCipherImpl cipher,
  277. byte[] nonce, bool serverSecret)
  278. {
  279. if (!m_isTlsV13)
  280. throw new TlsFatalAlert(AlertDescription.internal_error);
  281. TlsSecret secret = serverSecret
  282. ? securityParameters.TrafficSecretServer
  283. : securityParameters.TrafficSecretClient;
  284. // TODO[tls13] For early data, have to disable server->client
  285. if (null == secret)
  286. throw new TlsFatalAlert(AlertDescription.internal_error);
  287. Setup13Cipher(cipher, nonce, secret, securityParameters.PrfCryptoHashAlgorithm);
  288. }
  289. protected virtual void Setup13Cipher(TlsAeadCipherImpl cipher, byte[] nonce, TlsSecret secret,
  290. int cryptoHashAlgorithm)
  291. {
  292. byte[] key = TlsCryptoUtilities.HkdfExpandLabel(secret, cryptoHashAlgorithm, "key",
  293. TlsUtilities.EmptyBytes, m_keySize).Extract();
  294. byte[] iv = TlsCryptoUtilities.HkdfExpandLabel(secret, cryptoHashAlgorithm, "iv", TlsUtilities.EmptyBytes,
  295. m_fixed_iv_length).Extract();
  296. cipher.SetKey(key, 0, m_keySize);
  297. Array.Copy(iv, 0, nonce, 0, m_fixed_iv_length);
  298. // NOTE: Ensure dummy nonce is not part of the generated sequence(s)
  299. iv [0] ^= 0x80;
  300. cipher.Init(iv, m_macSize, null);
  301. }
  302. private static int GetNonceMode(bool isTLSv13, int aeadType)
  303. {
  304. switch (aeadType)
  305. {
  306. case AEAD_CCM:
  307. case AEAD_GCM:
  308. return isTLSv13 ? NONCE_RFC7905 : NONCE_RFC5288;
  309. case AEAD_CHACHA20_POLY1305:
  310. return NONCE_RFC7905;
  311. default:
  312. throw new TlsFatalAlert(AlertDescription.internal_error);
  313. }
  314. }
  315. }
  316. }
  317. #pragma warning restore
  318. #endif