TlsBlockCipher.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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.Parameters;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
  9. {
  10. /// <summary>
  11. /// A generic TLS 1.0-1.2 / SSLv3 block cipher. This can be used for AES or 3DES for example.
  12. /// </summary>
  13. public class TlsBlockCipher
  14. : TlsCipher
  15. {
  16. protected readonly TlsContext context;
  17. protected readonly byte[] randomData;
  18. protected readonly bool useExplicitIV;
  19. protected readonly bool encryptThenMac;
  20. protected readonly IBlockCipher encryptCipher;
  21. protected readonly IBlockCipher decryptCipher;
  22. protected readonly TlsMac mWriteMac;
  23. protected readonly TlsMac mReadMac;
  24. public virtual TlsMac WriteMac
  25. {
  26. get { return mWriteMac; }
  27. }
  28. public virtual TlsMac ReadMac
  29. {
  30. get { return mReadMac; }
  31. }
  32. /// <exception cref="IOException"></exception>
  33. public TlsBlockCipher(TlsContext context, IBlockCipher clientWriteCipher, IBlockCipher serverWriteCipher,
  34. IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize)
  35. {
  36. this.context = context;
  37. this.randomData = new byte[256];
  38. context.NonceRandomGenerator.NextBytes(randomData);
  39. this.useExplicitIV = TlsUtilities.IsTlsV11(context);
  40. this.encryptThenMac = context.SecurityParameters.encryptThenMac;
  41. int key_block_size = (2 * cipherKeySize) + clientWriteDigest.GetDigestSize()
  42. + serverWriteDigest.GetDigestSize();
  43. // From TLS 1.1 onwards, block ciphers don't need client_write_IV
  44. if (!useExplicitIV)
  45. {
  46. key_block_size += clientWriteCipher.GetBlockSize() + serverWriteCipher.GetBlockSize();
  47. }
  48. byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);
  49. int offset = 0;
  50. TlsMac clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset,
  51. clientWriteDigest.GetDigestSize());
  52. offset += clientWriteDigest.GetDigestSize();
  53. TlsMac serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset,
  54. serverWriteDigest.GetDigestSize());
  55. offset += serverWriteDigest.GetDigestSize();
  56. KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);
  57. offset += cipherKeySize;
  58. KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);
  59. offset += cipherKeySize;
  60. byte[] client_write_IV, server_write_IV;
  61. if (useExplicitIV)
  62. {
  63. client_write_IV = new byte[clientWriteCipher.GetBlockSize()];
  64. server_write_IV = new byte[serverWriteCipher.GetBlockSize()];
  65. }
  66. else
  67. {
  68. client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + clientWriteCipher.GetBlockSize());
  69. offset += clientWriteCipher.GetBlockSize();
  70. server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + serverWriteCipher.GetBlockSize());
  71. offset += serverWriteCipher.GetBlockSize();
  72. }
  73. if (offset != key_block_size)
  74. {
  75. throw new TlsFatalAlert(AlertDescription.internal_error);
  76. }
  77. ICipherParameters encryptParams, decryptParams;
  78. if (context.IsServer)
  79. {
  80. this.mWriteMac = serverWriteMac;
  81. this.mReadMac = clientWriteMac;
  82. this.encryptCipher = serverWriteCipher;
  83. this.decryptCipher = clientWriteCipher;
  84. encryptParams = new ParametersWithIV(server_write_key, server_write_IV);
  85. decryptParams = new ParametersWithIV(client_write_key, client_write_IV);
  86. }
  87. else
  88. {
  89. this.mWriteMac = clientWriteMac;
  90. this.mReadMac = serverWriteMac;
  91. this.encryptCipher = clientWriteCipher;
  92. this.decryptCipher = serverWriteCipher;
  93. encryptParams = new ParametersWithIV(client_write_key, client_write_IV);
  94. decryptParams = new ParametersWithIV(server_write_key, server_write_IV);
  95. }
  96. this.encryptCipher.Init(true, encryptParams);
  97. this.decryptCipher.Init(false, decryptParams);
  98. }
  99. public virtual int GetPlaintextLimit(int ciphertextLimit)
  100. {
  101. int blockSize = encryptCipher.GetBlockSize();
  102. int macSize = mWriteMac.Size;
  103. int plaintextLimit = ciphertextLimit;
  104. // An explicit IV consumes 1 block
  105. if (useExplicitIV)
  106. {
  107. plaintextLimit -= blockSize;
  108. }
  109. // Leave room for the MAC, and require block-alignment
  110. if (encryptThenMac)
  111. {
  112. plaintextLimit -= macSize;
  113. plaintextLimit -= plaintextLimit % blockSize;
  114. }
  115. else
  116. {
  117. plaintextLimit -= plaintextLimit % blockSize;
  118. plaintextLimit -= macSize;
  119. }
  120. // Minimum 1 byte of padding
  121. --plaintextLimit;
  122. return plaintextLimit;
  123. }
  124. byte[] explicitIV = null;
  125. public virtual byte[] EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len)
  126. {
  127. int blockSize = encryptCipher.GetBlockSize();
  128. int macSize = mWriteMac.Size;
  129. ProtocolVersion version = context.ServerVersion;
  130. int enc_input_length = len;
  131. if (!encryptThenMac)
  132. {
  133. enc_input_length += macSize;
  134. }
  135. int padding_length = blockSize - 1 - (enc_input_length % blockSize);
  136. /*
  137. * Don't use variable-length padding with truncated MACs.
  138. *
  139. * See "Tag Size Does Matter: Attacks and Proofs for the TLS Record Protocol", Paterson,
  140. * Ristenpart, Shrimpton.
  141. */
  142. if (encryptThenMac || !context.SecurityParameters.truncatedHMac)
  143. {
  144. // TODO[DTLS] Consider supporting in DTLS (without exceeding send limit though)
  145. if (!version.IsDtls && !version.IsSsl)
  146. {
  147. // Add a random number of extra blocks worth of padding
  148. int maxExtraPadBlocks = (255 - padding_length) / blockSize;
  149. int actualExtraPadBlocks = ChooseExtraPadBlocks(context.SecureRandom, maxExtraPadBlocks);
  150. padding_length += actualExtraPadBlocks * blockSize;
  151. }
  152. }
  153. int totalSize = len + macSize + padding_length + 1;
  154. if (useExplicitIV)
  155. {
  156. totalSize += blockSize;
  157. }
  158. byte[] outBuf = new byte[totalSize];
  159. int outOff = 0;
  160. if (useExplicitIV)
  161. {
  162. if (explicitIV == null || explicitIV.Length != blockSize) Array.Resize(ref explicitIV, blockSize);
  163. context.NonceRandomGenerator.NextBytes(explicitIV);
  164. encryptCipher.Init(true, new ParametersWithIV(null, explicitIV));
  165. Array.Copy(explicitIV, 0, outBuf, outOff, blockSize);
  166. outOff += blockSize;
  167. }
  168. int blocks_start = outOff;
  169. Array.Copy(plaintext, offset, outBuf, outOff, len);
  170. outOff += len;
  171. if (!encryptThenMac)
  172. {
  173. byte[] mac = mWriteMac.CalculateMac(seqNo, type, plaintext, offset, len);
  174. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  175. outOff += mac.Length;
  176. }
  177. for (int i = 0; i <= padding_length; i++)
  178. {
  179. outBuf[outOff++] = (byte)padding_length;
  180. }
  181. for (int i = blocks_start; i < outOff; i += blockSize)
  182. {
  183. encryptCipher.ProcessBlock(outBuf, i, outBuf, i);
  184. }
  185. if (encryptThenMac)
  186. {
  187. byte[] mac = mWriteMac.CalculateMac(seqNo, type, outBuf, 0, outOff);
  188. Array.Copy(mac, 0, outBuf, outOff, mac.Length);
  189. outOff += mac.Length;
  190. }
  191. // assert outBuf.length == outOff;
  192. return outBuf;
  193. }
  194. /// <exception cref="IOException"></exception>
  195. public virtual byte[] DecodeCiphertext(long seqNo, byte type, byte[] ciphertext, int offset, int len)
  196. {
  197. int blockSize = decryptCipher.GetBlockSize();
  198. int macSize = mReadMac.Size;
  199. int minLen = blockSize;
  200. if (encryptThenMac)
  201. {
  202. minLen += macSize;
  203. }
  204. else
  205. {
  206. minLen = System.Math.Max(minLen, macSize + 1);
  207. }
  208. if (useExplicitIV)
  209. {
  210. minLen += blockSize;
  211. }
  212. if (len < minLen)
  213. throw new TlsFatalAlert(AlertDescription.decode_error);
  214. int blocks_length = len;
  215. if (encryptThenMac)
  216. {
  217. blocks_length -= macSize;
  218. }
  219. if (blocks_length % blockSize != 0)
  220. throw new TlsFatalAlert(AlertDescription.decryption_failed);
  221. if (encryptThenMac)
  222. {
  223. int end = offset + len;
  224. byte[] receivedMac = Arrays.CopyOfRange(ciphertext, end - macSize, end);
  225. byte[] calculatedMac = mReadMac.CalculateMac(seqNo, type, ciphertext, offset, len - macSize);
  226. bool badMacEtm = !Arrays.ConstantTimeAreEqual(calculatedMac, receivedMac);
  227. if (badMacEtm)
  228. {
  229. /*
  230. * RFC 7366 3. The MAC SHALL be evaluated before any further processing such as
  231. * decryption is performed, and if the MAC verification fails, then processing SHALL
  232. * terminate immediately. For TLS, a fatal bad_record_mac MUST be generated [2]. For
  233. * DTLS, the record MUST be discarded, and a fatal bad_record_mac MAY be generated
  234. * [4]. This immediate response to a bad MAC eliminates any timing channels that may
  235. * be available through the use of manipulated packet data.
  236. */
  237. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  238. }
  239. }
  240. if (useExplicitIV)
  241. {
  242. decryptCipher.Init(false, new ParametersWithIV(null, ciphertext, offset, blockSize));
  243. offset += blockSize;
  244. blocks_length -= blockSize;
  245. }
  246. for (int i = 0; i < blocks_length; i += blockSize)
  247. {
  248. decryptCipher.ProcessBlock(ciphertext, offset + i, ciphertext, offset + i);
  249. }
  250. // If there's anything wrong with the padding, this will return zero
  251. int totalPad = CheckPaddingConstantTime(ciphertext, offset, blocks_length, blockSize, encryptThenMac ? 0 : macSize);
  252. bool badMac = (totalPad == 0);
  253. int dec_output_length = blocks_length - totalPad;
  254. if (!encryptThenMac)
  255. {
  256. dec_output_length -= macSize;
  257. int macInputLen = dec_output_length;
  258. int macOff = offset + macInputLen;
  259. byte[] receivedMac = Arrays.CopyOfRange(ciphertext, macOff, macOff + macSize);
  260. byte[] calculatedMac = mReadMac.CalculateMacConstantTime(seqNo, type, ciphertext, offset, macInputLen,
  261. blocks_length - macSize, randomData);
  262. badMac |= !Arrays.ConstantTimeAreEqual(calculatedMac, receivedMac);
  263. }
  264. if (badMac)
  265. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  266. return Arrays.CopyOfRange(ciphertext, offset, offset + dec_output_length);
  267. }
  268. protected virtual int CheckPaddingConstantTime(byte[] buf, int off, int len, int blockSize, int macSize)
  269. {
  270. int end = off + len;
  271. byte lastByte = buf[end - 1];
  272. int padlen = lastByte & 0xff;
  273. int totalPad = padlen + 1;
  274. int dummyIndex = 0;
  275. byte padDiff = 0;
  276. if ((TlsUtilities.IsSsl(context) && totalPad > blockSize) || (macSize + totalPad > len))
  277. {
  278. totalPad = 0;
  279. }
  280. else
  281. {
  282. int padPos = end - totalPad;
  283. do
  284. {
  285. padDiff |= (byte)(buf[padPos++] ^ lastByte);
  286. }
  287. while (padPos < end);
  288. dummyIndex = totalPad;
  289. if (padDiff != 0)
  290. {
  291. totalPad = 0;
  292. }
  293. }
  294. // Run some extra dummy checks so the number of checks is always constant
  295. {
  296. byte[] dummyPad = randomData;
  297. while (dummyIndex < 256)
  298. {
  299. padDiff |= (byte)(dummyPad[dummyIndex++] ^ lastByte);
  300. }
  301. // Ensure the above loop is not eliminated
  302. dummyPad[0] ^= padDiff;
  303. }
  304. return totalPad;
  305. }
  306. protected virtual int ChooseExtraPadBlocks(SecureRandom r, int max)
  307. {
  308. // return r.NextInt(max + 1);
  309. int x = r.NextInt();
  310. int n = LowestBitSet(x);
  311. return System.Math.Min(n, max);
  312. }
  313. protected virtual int LowestBitSet(int x)
  314. {
  315. if (x == 0)
  316. return 32;
  317. uint ux = (uint)x;
  318. int n = 0;
  319. while ((ux & 1U) == 0)
  320. {
  321. ++n;
  322. ux >>= 1;
  323. }
  324. return n;
  325. }
  326. }
  327. }
  328. #pragma warning restore
  329. #endif