FastTlsBlockCipher.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.Crypto.Utilities;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace Best.HTTP.Shared.TLS.Crypto.Impl
  11. {
  12. /// <summary>A generic TLS 1.0-1.2 block cipher. This can be used for AES or 3DES for example.</summary>
  13. public class FastTlsBlockCipher
  14. : TlsCipher
  15. {
  16. protected readonly TlsCryptoParameters m_cryptoParams;
  17. protected readonly byte[] m_randomData;
  18. protected readonly bool m_encryptThenMac;
  19. protected readonly bool m_useExplicitIV;
  20. protected readonly bool m_acceptExtraPadding;
  21. protected readonly bool m_useExtraPadding;
  22. protected readonly TlsBlockCipherImpl m_decryptCipher, m_encryptCipher;
  23. protected readonly TlsSuiteMac m_readMac, m_writeMac;
  24. /// <exception cref="IOException"/>
  25. public FastTlsBlockCipher(TlsCryptoParameters cryptoParams, TlsBlockCipherImpl encryptCipher,
  26. TlsBlockCipherImpl decryptCipher, TlsHmac clientMac, TlsHmac serverMac, int cipherKeySize)
  27. {
  28. SecurityParameters securityParameters = cryptoParams.SecurityParameters;
  29. ProtocolVersion negotiatedVersion = securityParameters.NegotiatedVersion;
  30. if (TlsImplUtilities.IsTlsV13(negotiatedVersion))
  31. throw new TlsFatalAlert(AlertDescription.internal_error);
  32. this.m_cryptoParams = cryptoParams;
  33. this.m_randomData = cryptoParams.NonceGenerator.GenerateNonce(256);
  34. this.m_encryptThenMac = securityParameters.IsEncryptThenMac;
  35. this.m_useExplicitIV = TlsImplUtilities.IsTlsV11(negotiatedVersion);
  36. this.m_acceptExtraPadding = !negotiatedVersion.IsSsl;
  37. /*
  38. * Don't use variable-length padding with truncated MACs.
  39. *
  40. * See "Tag Size Does Matter: Attacks and Proofs for the TLS Record Protocol", Paterson,
  41. * Ristenpart, Shrimpton.
  42. *
  43. * TODO[DTLS] Consider supporting in DTLS (without exceeding send limit though)
  44. */
  45. this.m_useExtraPadding = securityParameters.IsExtendedPadding
  46. && ProtocolVersion.TLSv10.IsEqualOrEarlierVersionOf(negotiatedVersion)
  47. && (m_encryptThenMac || !securityParameters.IsTruncatedHmac);
  48. this.m_encryptCipher = encryptCipher;
  49. this.m_decryptCipher = decryptCipher;
  50. TlsBlockCipherImpl clientCipher, serverCipher;
  51. if (cryptoParams.IsServer)
  52. {
  53. clientCipher = decryptCipher;
  54. serverCipher = encryptCipher;
  55. }
  56. else
  57. {
  58. clientCipher = encryptCipher;
  59. serverCipher = decryptCipher;
  60. }
  61. int keyBlockSize = (2 * cipherKeySize) + clientMac.MacLength + serverMac.MacLength;
  62. // From TLS 1.1 onwards, block ciphers don't need IVs from the key_block
  63. if (!m_useExplicitIV)
  64. {
  65. keyBlockSize += clientCipher.GetBlockSize() + serverCipher.GetBlockSize();
  66. }
  67. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  68. Span<byte> keyBlock = keyBlockSize <= 512
  69. ? stackalloc byte[keyBlockSize]
  70. : new byte[keyBlockSize];
  71. TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock);
  72. clientMac.SetKey(keyBlock[..clientMac.MacLength]); keyBlock = keyBlock[clientMac.MacLength..];
  73. serverMac.SetKey(keyBlock[..serverMac.MacLength]); keyBlock = keyBlock[serverMac.MacLength..];
  74. clientCipher.SetKey(keyBlock[..cipherKeySize]); keyBlock = keyBlock[cipherKeySize..];
  75. serverCipher.SetKey(keyBlock[..cipherKeySize]); keyBlock = keyBlock[cipherKeySize..];
  76. int clientIVLength = clientCipher.GetBlockSize();
  77. int serverIVLength = serverCipher.GetBlockSize();
  78. if (m_useExplicitIV)
  79. {
  80. clientCipher.Init(clientIVLength <= 64 ? stackalloc byte[clientIVLength] : new byte[clientIVLength]);
  81. serverCipher.Init(serverIVLength <= 64 ? stackalloc byte[serverIVLength] : new byte[serverIVLength]);
  82. }
  83. else
  84. {
  85. clientCipher.Init(keyBlock[..clientIVLength]); keyBlock = keyBlock[clientIVLength..];
  86. serverCipher.Init(keyBlock[..serverIVLength]); keyBlock = keyBlock[serverIVLength..];
  87. }
  88. if (!keyBlock.IsEmpty)
  89. throw new TlsFatalAlert(AlertDescription.internal_error);
  90. #else
  91. byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize);
  92. int pos = 0;
  93. clientMac.SetKey(keyBlock, pos, clientMac.MacLength);
  94. pos += clientMac.MacLength;
  95. serverMac.SetKey(keyBlock, pos, serverMac.MacLength);
  96. pos += serverMac.MacLength;
  97. clientCipher.SetKey(keyBlock, pos, cipherKeySize);
  98. pos += cipherKeySize;
  99. serverCipher.SetKey(keyBlock, pos, cipherKeySize);
  100. pos += cipherKeySize;
  101. int clientIVLength = clientCipher.GetBlockSize();
  102. int serverIVLength = serverCipher.GetBlockSize();
  103. if (m_useExplicitIV)
  104. {
  105. clientCipher.Init(new byte[clientIVLength], 0, clientIVLength);
  106. serverCipher.Init(new byte[serverIVLength], 0, serverIVLength);
  107. }
  108. else
  109. {
  110. clientCipher.Init(keyBlock, pos, clientIVLength);
  111. pos += clientIVLength;
  112. serverCipher.Init(keyBlock, pos, serverIVLength);
  113. pos += serverIVLength;
  114. }
  115. if (pos != keyBlockSize)
  116. throw new TlsFatalAlert(AlertDescription.internal_error);
  117. #endif
  118. if (cryptoParams.IsServer)
  119. {
  120. this.m_writeMac = new TlsSuiteHmac(cryptoParams, serverMac);
  121. this.m_readMac = new TlsSuiteHmac(cryptoParams, clientMac);
  122. }
  123. else
  124. {
  125. this.m_writeMac = new TlsSuiteHmac(cryptoParams, clientMac);
  126. this.m_readMac = new TlsSuiteHmac(cryptoParams, serverMac);
  127. }
  128. }
  129. public virtual int GetCiphertextDecodeLimit(int plaintextLimit)
  130. {
  131. int blockSize = m_decryptCipher.GetBlockSize();
  132. int macSize = m_readMac.Size;
  133. int maxPadding = 256;
  134. return GetCiphertextLength(blockSize, macSize, maxPadding, plaintextLimit);
  135. }
  136. public virtual int GetCiphertextEncodeLimit(int plaintextLength, int plaintextLimit)
  137. {
  138. int blockSize = m_encryptCipher.GetBlockSize();
  139. int macSize = m_writeMac.Size;
  140. int maxPadding = m_useExtraPadding ? 256 : blockSize;
  141. return GetCiphertextLength(blockSize, macSize, maxPadding, plaintextLength);
  142. }
  143. public virtual int GetPlaintextLimit(int ciphertextLimit)
  144. {
  145. int blockSize = m_encryptCipher.GetBlockSize();
  146. int macSize = m_writeMac.Size;
  147. int plaintextLimit = ciphertextLimit;
  148. // Leave room for the MAC, and require block-alignment
  149. if (m_encryptThenMac)
  150. {
  151. plaintextLimit -= macSize;
  152. plaintextLimit -= plaintextLimit % blockSize;
  153. }
  154. else
  155. {
  156. plaintextLimit -= plaintextLimit % blockSize;
  157. plaintextLimit -= macSize;
  158. }
  159. // Minimum 1 byte of padding
  160. --plaintextLimit;
  161. // An explicit IV consumes 1 block
  162. if (m_useExplicitIV)
  163. {
  164. plaintextLimit -= blockSize;
  165. }
  166. return plaintextLimit;
  167. }
  168. public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion,
  169. int headerAllocation, byte[] plaintext, int offset, int len)
  170. {
  171. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  172. return EncodePlaintext(seqNo, contentType, recordVersion, headerAllocation, plaintext.AsSpan(offset, len));
  173. #else
  174. int blockSize = m_encryptCipher.GetBlockSize();
  175. int macSize = m_writeMac.Size;
  176. int enc_input_length = len;
  177. if (!m_encryptThenMac)
  178. {
  179. enc_input_length += macSize;
  180. }
  181. int padding_length = blockSize - (enc_input_length % blockSize);
  182. if (m_useExtraPadding)
  183. {
  184. // Add a random number of extra blocks worth of padding
  185. int maxExtraPadBlocks = (256 - padding_length) / blockSize;
  186. int actualExtraPadBlocks = ChooseExtraPadBlocks(maxExtraPadBlocks);
  187. padding_length += actualExtraPadBlocks * blockSize;
  188. }
  189. int totalSize = len + macSize + padding_length;
  190. if (m_useExplicitIV)
  191. {
  192. totalSize += blockSize;
  193. }
  194. byte[] outBuf = new byte[headerAllocation + totalSize];
  195. int outOff = headerAllocation;
  196. if (m_useExplicitIV)
  197. {
  198. // Technically the explicit IV will be the encryption of this nonce
  199. byte[] explicitIV = m_cryptoParams.NonceGenerator.GenerateNonce(blockSize);
  200. Array.Copy(explicitIV, 0, outBuf, outOff, blockSize);
  201. outOff += blockSize;
  202. }
  203. Array.Copy(plaintext, offset, outBuf, outOff, len);
  204. outOff += len;
  205. if (!m_encryptThenMac)
  206. {
  207. byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, plaintext, offset, len);
  208. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  209. outOff += mac.Length;
  210. }
  211. byte padByte = (byte)(padding_length - 1);
  212. for (int i = 0; i < padding_length; ++i)
  213. {
  214. outBuf[outOff++] = padByte;
  215. }
  216. m_encryptCipher.DoFinal(outBuf, headerAllocation, outOff - headerAllocation, outBuf, headerAllocation);
  217. if (m_encryptThenMac)
  218. {
  219. byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, outBuf, headerAllocation,
  220. outOff - headerAllocation);
  221. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  222. outOff += mac.Length;
  223. }
  224. if (outOff != outBuf.Length)
  225. throw new TlsFatalAlert(AlertDescription.internal_error);
  226. return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType);
  227. #endif
  228. }
  229. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  230. public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion,
  231. int headerAllocation, ReadOnlySpan<byte> plaintext)
  232. {
  233. int blockSize = m_encryptCipher.GetBlockSize();
  234. int macSize = m_writeMac.Size;
  235. int enc_input_length = plaintext.Length;
  236. if (!m_encryptThenMac)
  237. {
  238. enc_input_length += macSize;
  239. }
  240. int padding_length = blockSize - (enc_input_length % blockSize);
  241. if (m_useExtraPadding)
  242. {
  243. // Add a random number of extra blocks worth of padding
  244. int maxExtraPadBlocks = (256 - padding_length) / blockSize;
  245. int actualExtraPadBlocks = ChooseExtraPadBlocks(maxExtraPadBlocks);
  246. padding_length += actualExtraPadBlocks * blockSize;
  247. }
  248. int totalSize = plaintext.Length + macSize + padding_length;
  249. if (m_useExplicitIV)
  250. {
  251. totalSize += blockSize;
  252. }
  253. byte[] outBuf = new byte[headerAllocation + totalSize];
  254. int outOff = headerAllocation;
  255. if (m_useExplicitIV)
  256. {
  257. // Technically the explicit IV will be the encryption of this nonce
  258. byte[] explicitIV = m_cryptoParams.NonceGenerator.GenerateNonce(blockSize);
  259. Array.Copy(explicitIV, 0, outBuf, outOff, blockSize);
  260. outOff += blockSize;
  261. }
  262. plaintext.CopyTo(outBuf.AsSpan(outOff));
  263. outOff += plaintext.Length;
  264. if (!m_encryptThenMac)
  265. {
  266. byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, plaintext);
  267. mac.CopyTo(outBuf.AsSpan(outOff));
  268. outOff += mac.Length;
  269. }
  270. byte padByte = (byte)(padding_length - 1);
  271. for (int i = 0; i < padding_length; ++i)
  272. {
  273. outBuf[outOff++] = padByte;
  274. }
  275. m_encryptCipher.DoFinal(outBuf, headerAllocation, outOff - headerAllocation, outBuf, headerAllocation);
  276. if (m_encryptThenMac)
  277. {
  278. byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, outBuf, headerAllocation,
  279. outOff - headerAllocation);
  280. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  281. outOff += mac.Length;
  282. }
  283. if (outOff != outBuf.Length)
  284. throw new TlsFatalAlert(AlertDescription.internal_error);
  285. return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType);
  286. }
  287. #endif
  288. public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion,
  289. byte[] ciphertext, int offset, int len)
  290. {
  291. int blockSize = m_decryptCipher.GetBlockSize();
  292. int macSize = m_readMac.Size;
  293. int minLen = blockSize;
  294. if (m_encryptThenMac)
  295. {
  296. minLen += macSize;
  297. }
  298. else
  299. {
  300. minLen = System.Math.Max(minLen, macSize + 1);
  301. }
  302. if (m_useExplicitIV)
  303. {
  304. minLen += blockSize;
  305. }
  306. if (len < minLen)
  307. throw new TlsFatalAlert(AlertDescription.decode_error);
  308. int blocks_length = len;
  309. if (m_encryptThenMac)
  310. {
  311. blocks_length -= macSize;
  312. }
  313. if (blocks_length % blockSize != 0)
  314. throw new TlsFatalAlert(AlertDescription.decryption_failed);
  315. if (m_encryptThenMac)
  316. {
  317. byte[] expectedMac = m_readMac.CalculateMac(seqNo, recordType, ciphertext, offset, len - macSize);
  318. bool checkMac = TlsUtilities.ConstantTimeAreEqual(macSize, expectedMac, 0, ciphertext,
  319. offset + len - macSize);
  320. if (!checkMac)
  321. {
  322. /*
  323. * RFC 7366 3. The MAC SHALL be evaluated before any further processing such as
  324. * decryption is performed, and if the MAC verification fails, then processing SHALL
  325. * terminate immediately. For TLS, a fatal bad_record_mac MUST be generated [2]. For
  326. * DTLS, the record MUST be discarded, and a fatal bad_record_mac MAY be generated
  327. * [4]. This immediate response to a bad MAC eliminates any timing channels that may
  328. * be available through the use of manipulated packet data.
  329. */
  330. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  331. }
  332. }
  333. m_decryptCipher.DoFinal(ciphertext, offset, blocks_length, ciphertext, offset);
  334. if (m_useExplicitIV)
  335. {
  336. offset += blockSize;
  337. blocks_length -= blockSize;
  338. }
  339. // If there's anything wrong with the padding, this will return zero
  340. int totalPad = CheckPaddingConstantTime(ciphertext, offset, blocks_length, blockSize,
  341. m_encryptThenMac ? 0 : macSize);
  342. bool badMac = (totalPad == 0);
  343. int dec_output_length = blocks_length - totalPad;
  344. if (!m_encryptThenMac)
  345. {
  346. dec_output_length -= macSize;
  347. byte[] expectedMac = m_readMac.CalculateMacConstantTime(seqNo, recordType, ciphertext, offset,
  348. dec_output_length, blocks_length - macSize, m_randomData);
  349. badMac |= !TlsUtilities.ConstantTimeAreEqual(macSize, expectedMac, 0, ciphertext,
  350. offset + dec_output_length);
  351. }
  352. if (badMac)
  353. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  354. return new TlsDecodeResult(ciphertext, offset, dec_output_length, recordType);
  355. }
  356. public virtual void RekeyDecoder()
  357. {
  358. throw new TlsFatalAlert(AlertDescription.internal_error);
  359. }
  360. public virtual void RekeyEncoder()
  361. {
  362. throw new TlsFatalAlert(AlertDescription.internal_error);
  363. }
  364. public virtual bool UsesOpaqueRecordType
  365. {
  366. get { return false; }
  367. }
  368. protected virtual int CheckPaddingConstantTime(byte[] buf, int off, int len, int blockSize, int macSize)
  369. {
  370. int end = off + len;
  371. byte lastByte = buf[end - 1];
  372. int padlen = lastByte & 0xff;
  373. int totalPad = padlen + 1;
  374. int dummyIndex = 0;
  375. byte padDiff = 0;
  376. int totalPadLimit = System.Math.Min(m_acceptExtraPadding ? 256 : blockSize, len - macSize);
  377. if (totalPad > totalPadLimit)
  378. {
  379. totalPad = 0;
  380. }
  381. else
  382. {
  383. int padPos = end - totalPad;
  384. do
  385. {
  386. padDiff |= (byte)(buf[padPos++] ^ lastByte);
  387. }
  388. while (padPos < end);
  389. dummyIndex = totalPad;
  390. if (padDiff != 0)
  391. {
  392. totalPad = 0;
  393. }
  394. }
  395. // Run some extra dummy checks so the number of checks is always constant
  396. {
  397. byte[] dummyPad = m_randomData;
  398. while (dummyIndex < 256)
  399. {
  400. padDiff |= (byte)(dummyPad[dummyIndex++] ^ lastByte);
  401. }
  402. // Ensure the above loop is not eliminated
  403. dummyPad[0] ^= padDiff;
  404. }
  405. return totalPad;
  406. }
  407. protected virtual int ChooseExtraPadBlocks(int max)
  408. {
  409. byte[] random = m_cryptoParams.NonceGenerator.GenerateNonce(4);
  410. int x = (int)Pack.LE_To_UInt32(random, 0);
  411. int n = Integers.NumberOfTrailingZeros(x);
  412. return System.Math.Min(n, max);
  413. }
  414. protected virtual int GetCiphertextLength(int blockSize, int macSize, int maxPadding, int plaintextLength)
  415. {
  416. int ciphertextLength = plaintextLength;
  417. // An explicit IV consumes 1 block
  418. if (m_useExplicitIV)
  419. {
  420. ciphertextLength += blockSize;
  421. }
  422. // Leave room for the MAC and (block-aligning) padding
  423. ciphertextLength += maxPadding;
  424. if (m_encryptThenMac)
  425. {
  426. ciphertextLength -= (ciphertextLength % blockSize);
  427. ciphertextLength += macSize;
  428. }
  429. else
  430. {
  431. ciphertextLength += macSize;
  432. ciphertextLength -= (ciphertextLength % blockSize);
  433. }
  434. return ciphertextLength;
  435. }
  436. }
  437. }
  438. #pragma warning restore
  439. #endif