FastTlsBlockCipher.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace BestHTTP.Connections.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 key_block_size = (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. key_block_size += clientCipher.GetBlockSize() + serverCipher.GetBlockSize();
  66. }
  67. byte[] key_block = TlsImplUtilities.CalculateKeyBlock(cryptoParams, key_block_size);
  68. int offset = 0;
  69. clientMac.SetKey(key_block, offset, clientMac.MacLength);
  70. offset += clientMac.MacLength;
  71. serverMac.SetKey(key_block, offset, serverMac.MacLength);
  72. offset += serverMac.MacLength;
  73. clientCipher.SetKey(key_block, offset, cipherKeySize);
  74. offset += cipherKeySize;
  75. serverCipher.SetKey(key_block, offset, cipherKeySize);
  76. offset += cipherKeySize;
  77. int clientIVLength = clientCipher.GetBlockSize();
  78. int serverIVLength = serverCipher.GetBlockSize();
  79. if (m_useExplicitIV)
  80. {
  81. clientCipher.Init(new byte[clientIVLength], 0, clientIVLength);
  82. serverCipher.Init(new byte[serverIVLength], 0, serverIVLength);
  83. }
  84. else
  85. {
  86. clientCipher.Init(key_block, offset, clientIVLength);
  87. offset += clientIVLength;
  88. serverCipher.Init(key_block, offset, serverIVLength);
  89. offset += serverIVLength;
  90. }
  91. if (offset != key_block_size)
  92. throw new TlsFatalAlert(AlertDescription.internal_error);
  93. if (cryptoParams.IsServer)
  94. {
  95. this.m_writeMac = new TlsSuiteHmac(cryptoParams, serverMac);
  96. this.m_readMac = new TlsSuiteHmac(cryptoParams, clientMac);
  97. }
  98. else
  99. {
  100. this.m_writeMac = new TlsSuiteHmac(cryptoParams, clientMac);
  101. this.m_readMac = new TlsSuiteHmac(cryptoParams, serverMac);
  102. }
  103. }
  104. public virtual int GetCiphertextDecodeLimit(int plaintextLimit)
  105. {
  106. int blockSize = m_decryptCipher.GetBlockSize();
  107. int macSize = m_readMac.Size;
  108. int maxPadding = 256;
  109. return GetCiphertextLength(blockSize, macSize, maxPadding, plaintextLimit);
  110. }
  111. public virtual int GetCiphertextEncodeLimit(int plaintextLength, int plaintextLimit)
  112. {
  113. int blockSize = m_encryptCipher.GetBlockSize();
  114. int macSize = m_writeMac.Size;
  115. int maxPadding = m_useExtraPadding ? 256 : blockSize;
  116. return GetCiphertextLength(blockSize, macSize, maxPadding, plaintextLength);
  117. }
  118. public virtual int GetPlaintextLimit(int ciphertextLimit)
  119. {
  120. int blockSize = m_encryptCipher.GetBlockSize();
  121. int macSize = m_writeMac.Size;
  122. int plaintextLimit = ciphertextLimit;
  123. // Leave room for the MAC, and require block-alignment
  124. if (m_encryptThenMac)
  125. {
  126. plaintextLimit -= macSize;
  127. plaintextLimit -= plaintextLimit % blockSize;
  128. }
  129. else
  130. {
  131. plaintextLimit -= plaintextLimit % blockSize;
  132. plaintextLimit -= macSize;
  133. }
  134. // Minimum 1 byte of padding
  135. --plaintextLimit;
  136. // An explicit IV consumes 1 block
  137. if (m_useExplicitIV)
  138. {
  139. plaintextLimit -= blockSize;
  140. }
  141. return plaintextLimit;
  142. }
  143. public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion,
  144. int headerAllocation, byte[] plaintext, int offset, int len)
  145. {
  146. int blockSize = m_encryptCipher.GetBlockSize();
  147. int macSize = m_writeMac.Size;
  148. int enc_input_length = len;
  149. if (!m_encryptThenMac)
  150. {
  151. enc_input_length += macSize;
  152. }
  153. int padding_length = blockSize - (enc_input_length % blockSize);
  154. if (m_useExtraPadding)
  155. {
  156. // Add a random number of extra blocks worth of padding
  157. int maxExtraPadBlocks = (256 - padding_length) / blockSize;
  158. int actualExtraPadBlocks = ChooseExtraPadBlocks(maxExtraPadBlocks);
  159. padding_length += actualExtraPadBlocks * blockSize;
  160. }
  161. int totalSize = len + macSize + padding_length;
  162. if (m_useExplicitIV)
  163. {
  164. totalSize += blockSize;
  165. }
  166. byte[] outBuf = new byte[headerAllocation + totalSize];
  167. int outOff = headerAllocation;
  168. if (m_useExplicitIV)
  169. {
  170. // Technically the explicit IV will be the encryption of this nonce
  171. byte[] explicitIV = m_cryptoParams.NonceGenerator.GenerateNonce(blockSize);
  172. Array.Copy(explicitIV, 0, outBuf, outOff, blockSize);
  173. outOff += blockSize;
  174. }
  175. Array.Copy(plaintext, offset, outBuf, outOff, len);
  176. outOff += len;
  177. if (!m_encryptThenMac)
  178. {
  179. byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, plaintext, offset, len);
  180. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  181. outOff += mac.Length;
  182. }
  183. byte padByte = (byte)(padding_length - 1);
  184. for (int i = 0; i < padding_length; ++i)
  185. {
  186. outBuf[outOff++] = padByte;
  187. }
  188. m_encryptCipher.DoFinal(outBuf, headerAllocation, outOff - headerAllocation, outBuf, headerAllocation);
  189. if (m_encryptThenMac)
  190. {
  191. byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, outBuf, headerAllocation,
  192. outOff - headerAllocation);
  193. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  194. outOff += mac.Length;
  195. }
  196. if (outOff != outBuf.Length)
  197. throw new TlsFatalAlert(AlertDescription.internal_error);
  198. return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType);
  199. }
  200. public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion,
  201. byte[] ciphertext, int offset, int len)
  202. {
  203. int blockSize = m_decryptCipher.GetBlockSize();
  204. int macSize = m_readMac.Size;
  205. int minLen = blockSize;
  206. if (m_encryptThenMac)
  207. {
  208. minLen += macSize;
  209. }
  210. else
  211. {
  212. minLen = System.Math.Max(minLen, macSize + 1);
  213. }
  214. if (m_useExplicitIV)
  215. {
  216. minLen += blockSize;
  217. }
  218. if (len < minLen)
  219. throw new TlsFatalAlert(AlertDescription.decode_error);
  220. int blocks_length = len;
  221. if (m_encryptThenMac)
  222. {
  223. blocks_length -= macSize;
  224. }
  225. if (blocks_length % blockSize != 0)
  226. throw new TlsFatalAlert(AlertDescription.decryption_failed);
  227. if (m_encryptThenMac)
  228. {
  229. byte[] expectedMac = m_readMac.CalculateMac(seqNo, recordType, ciphertext, offset, len - macSize);
  230. bool checkMac = TlsUtilities.ConstantTimeAreEqual(macSize, expectedMac, 0, ciphertext,
  231. offset + len - macSize);
  232. if (!checkMac)
  233. {
  234. /*
  235. * RFC 7366 3. The MAC SHALL be evaluated before any further processing such as
  236. * decryption is performed, and if the MAC verification fails, then processing SHALL
  237. * terminate immediately. For TLS, a fatal bad_record_mac MUST be generated [2]. For
  238. * DTLS, the record MUST be discarded, and a fatal bad_record_mac MAY be generated
  239. * [4]. This immediate response to a bad MAC eliminates any timing channels that may
  240. * be available through the use of manipulated packet data.
  241. */
  242. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  243. }
  244. }
  245. m_decryptCipher.DoFinal(ciphertext, offset, blocks_length, ciphertext, offset);
  246. if (m_useExplicitIV)
  247. {
  248. offset += blockSize;
  249. blocks_length -= blockSize;
  250. }
  251. // If there's anything wrong with the padding, this will return zero
  252. int totalPad = CheckPaddingConstantTime(ciphertext, offset, blocks_length, blockSize,
  253. m_encryptThenMac ? 0 : macSize);
  254. bool badMac = (totalPad == 0);
  255. int dec_output_length = blocks_length - totalPad;
  256. if (!m_encryptThenMac)
  257. {
  258. dec_output_length -= macSize;
  259. byte[] expectedMac = m_readMac.CalculateMacConstantTime(seqNo, recordType, ciphertext, offset,
  260. dec_output_length, blocks_length - macSize, m_randomData);
  261. badMac |= !TlsUtilities.ConstantTimeAreEqual(macSize, expectedMac, 0, ciphertext,
  262. offset + dec_output_length);
  263. }
  264. if (badMac)
  265. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  266. return new TlsDecodeResult(ciphertext, offset, dec_output_length, recordType);
  267. }
  268. public virtual void RekeyDecoder()
  269. {
  270. throw new TlsFatalAlert(AlertDescription.internal_error);
  271. }
  272. public virtual void RekeyEncoder()
  273. {
  274. throw new TlsFatalAlert(AlertDescription.internal_error);
  275. }
  276. public virtual bool UsesOpaqueRecordType
  277. {
  278. get { return false; }
  279. }
  280. protected virtual int CheckPaddingConstantTime(byte[] buf, int off, int len, int blockSize, int macSize)
  281. {
  282. int end = off + len;
  283. byte lastByte = buf[end - 1];
  284. int padlen = lastByte & 0xff;
  285. int totalPad = padlen + 1;
  286. int dummyIndex = 0;
  287. byte padDiff = 0;
  288. int totalPadLimit = System.Math.Min(m_acceptExtraPadding ? 256 : blockSize, len - macSize);
  289. if (totalPad > totalPadLimit)
  290. {
  291. totalPad = 0;
  292. }
  293. else
  294. {
  295. int padPos = end - totalPad;
  296. do
  297. {
  298. padDiff |= (byte)(buf[padPos++] ^ lastByte);
  299. }
  300. while (padPos < end);
  301. dummyIndex = totalPad;
  302. if (padDiff != 0)
  303. {
  304. totalPad = 0;
  305. }
  306. }
  307. // Run some extra dummy checks so the number of checks is always constant
  308. {
  309. byte[] dummyPad = m_randomData;
  310. while (dummyIndex < 256)
  311. {
  312. padDiff |= (byte)(dummyPad[dummyIndex++] ^ lastByte);
  313. }
  314. // Ensure the above loop is not eliminated
  315. dummyPad[0] ^= padDiff;
  316. }
  317. return totalPad;
  318. }
  319. protected virtual int ChooseExtraPadBlocks(int max)
  320. {
  321. byte[] random = m_cryptoParams.NonceGenerator.GenerateNonce(4);
  322. int x = (int)Pack.LE_To_UInt32(random, 0);
  323. int n = Integers.NumberOfTrailingZeros(x);
  324. return System.Math.Min(n, max);
  325. }
  326. protected virtual int GetCiphertextLength(int blockSize, int macSize, int maxPadding, int plaintextLength)
  327. {
  328. int ciphertextLength = plaintextLength;
  329. // An explicit IV consumes 1 block
  330. if (m_useExplicitIV)
  331. {
  332. ciphertextLength += blockSize;
  333. }
  334. // Leave room for the MAC and (block-aligning) padding
  335. ciphertextLength += maxPadding;
  336. if (m_encryptThenMac)
  337. {
  338. ciphertextLength -= (ciphertextLength % blockSize);
  339. ciphertextLength += macSize;
  340. }
  341. else
  342. {
  343. ciphertextLength += macSize;
  344. ciphertextLength -= (ciphertextLength % blockSize);
  345. }
  346. return ciphertextLength;
  347. }
  348. }
  349. }
  350. #pragma warning restore
  351. #endif