TlsBlockCipher.cs 19 KB

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