You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

StreamEncryptor.cs 6.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using Shadowsocks.Encryption.CircularBuffer;
  6. using Shadowsocks.Controller;
  7. using NLog;
  8. namespace Shadowsocks.Encryption.Stream
  9. {
  10. public abstract class StreamEncryptor : EncryptorBase
  11. {
  12. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  13. // for UDP only
  14. protected static byte[] udpBuffer = new byte[65536];
  15. // every connection should create its own buffer
  16. private readonly ByteCircularBuffer buffer = new ByteCircularBuffer(TCPHandler.BufferSize * 2);
  17. // Is first packet
  18. protected bool ivReady;
  19. protected CipherFamily cipherFamily;
  20. protected CipherInfo CipherInfo;
  21. // long-time master key
  22. protected static byte[] key = Array.Empty<byte>();
  23. protected byte[] iv = Array.Empty<byte>();
  24. protected int keyLen;
  25. protected int ivLen;
  26. public StreamEncryptor(string method, string password)
  27. : base(method, password)
  28. {
  29. CipherInfo = getCiphers()[method.ToLower()];
  30. cipherFamily = CipherInfo.Type;
  31. var parameter = (StreamCipherParameter)CipherInfo.CipherParameter;
  32. keyLen = parameter.KeySize;
  33. ivLen = parameter.IvSize;
  34. InitKey(password);
  35. logger.Dump($"key {instanceId}", key, keyLen);
  36. }
  37. protected abstract Dictionary<string, CipherInfo> getCiphers();
  38. private void InitKey(string password)
  39. {
  40. byte[] passbuf = Encoding.UTF8.GetBytes(password);
  41. key ??= new byte[keyLen];
  42. if (key.Length != keyLen) Array.Resize(ref key, keyLen);
  43. LegacyDeriveKey(passbuf, key, keyLen);
  44. }
  45. public static void LegacyDeriveKey(byte[] password, byte[] key, int keylen)
  46. {
  47. byte[] result = new byte[password.Length + MD5_LEN];
  48. int i = 0;
  49. byte[] md5sum = Array.Empty<byte>();
  50. while (i < keylen)
  51. {
  52. if (i == 0)
  53. {
  54. md5sum = CryptoUtils.MD5(password);
  55. }
  56. else
  57. {
  58. Array.Copy(md5sum, 0, result, 0, MD5_LEN);
  59. Array.Copy(password, 0, result, MD5_LEN, password.Length);
  60. md5sum = CryptoUtils.MD5(result);
  61. }
  62. Array.Copy(md5sum, 0, key, i, Math.Min(MD5_LEN, keylen - i));
  63. i += MD5_LEN;
  64. }
  65. }
  66. protected virtual void initCipher(byte[] iv, bool isEncrypt)
  67. {
  68. if (ivLen == 0) return;
  69. this.iv = new byte[ivLen];
  70. Array.Copy(iv, this.iv, ivLen);
  71. }
  72. protected abstract void cipherUpdate(bool isEncrypt, int length, byte[] buf, byte[] outbuf);
  73. protected abstract int CipherEncrypt(Span<byte> plain, Span<byte> cipher);
  74. protected abstract int CipherDecrypt(Span<byte> plain, Span<byte> cipher);
  75. //protected static void randBytes(byte[] buf, int length) { RNG.GetBytes(buf, length); }
  76. #region TCP
  77. public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
  78. {
  79. int cipherOffset = 0;
  80. Debug.Assert(buffer != null, "_encCircularBuffer != null");
  81. buffer.Put(buf, 0, length);
  82. logger.Trace($"{instanceId} encrypt TCP, generate iv: {!ivReady}");
  83. if (!ivReady)
  84. {
  85. // Generate IV
  86. byte[] ivBytes = RNG.GetBytes(ivLen);
  87. initCipher(ivBytes, true);
  88. Array.Copy(ivBytes, 0, outbuf, 0, ivLen);
  89. cipherOffset = ivLen;
  90. ivReady = true;
  91. }
  92. int size = buffer.Size;
  93. byte[] plain = buffer.Get(size);
  94. byte[] cipher = new byte[size];
  95. cipherUpdate(true, size, plain, cipher);
  96. logger.DumpBase64($"plain {instanceId}", plain, size);
  97. logger.DumpBase64($"cipher {instanceId}", cipher, cipher.Length);
  98. logger.Dump($"iv {instanceId}", iv, ivLen);
  99. Buffer.BlockCopy(cipher, 0, outbuf, cipherOffset, size);
  100. outlength = size + cipherOffset;
  101. }
  102. public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
  103. {
  104. Debug.Assert(buffer != null, "_circularBuffer != null");
  105. buffer.Put(buf, 0, length);
  106. logger.Trace($"{instanceId} decrypt TCP, read iv: {!ivReady}");
  107. if (!ivReady)
  108. {
  109. if (buffer.Size <= ivLen)
  110. {
  111. // we need more data
  112. outlength = 0;
  113. return;
  114. }
  115. // start decryption
  116. ivReady = true;
  117. if (ivLen > 0)
  118. {
  119. byte[] iv = buffer.Get(ivLen);
  120. initCipher(iv, false);
  121. }
  122. else initCipher(Array.Empty<byte>(), false);
  123. }
  124. byte[] cipher = buffer.ToArray();
  125. cipherUpdate(false, cipher.Length, cipher, outbuf);
  126. logger.DumpBase64($"cipher {instanceId}", cipher, cipher.Length);
  127. logger.DumpBase64($"plain {instanceId}", outbuf, cipher.Length);
  128. logger.Dump($"iv {instanceId}", iv, ivLen);
  129. // move pointer only
  130. buffer.Skip(buffer.Size);
  131. outlength = cipher.Length;
  132. // done the decryption
  133. }
  134. #endregion
  135. #region UDP
  136. public override void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
  137. {
  138. // Generate IV
  139. RNG.GetBytes(outbuf, ivLen);
  140. initCipher(outbuf, true);
  141. lock (udpBuffer)
  142. {
  143. cipherUpdate(true, length, buf, udpBuffer);
  144. outlength = length + ivLen;
  145. Buffer.BlockCopy(udpBuffer, 0, outbuf, ivLen, length);
  146. }
  147. }
  148. public override void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
  149. {
  150. // Get IV from first pos
  151. initCipher(buf, false);
  152. outlength = length - ivLen;
  153. lock (udpBuffer)
  154. {
  155. // C# could be multi-threaded
  156. Buffer.BlockCopy(buf, ivLen, udpBuffer, 0, length - ivLen);
  157. cipherUpdate(false, length - ivLen, udpBuffer, outbuf);
  158. }
  159. }
  160. #endregion
  161. }
  162. }