TlsBlockCipher.cs 13 KB

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