TlsBlockCipher.cs 15 KB

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