Repository navigation
Expand file tree
/
Copy pathAEADCrypto.cs
More file actions
313 lines (268 loc) · 11.4 KB
/
Copy pathAEADCrypto.cs
File metadata and controls
313 lines (268 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
using CryptoBase;
using Shadowsocks.Net.Crypto.Exception;
using Shadowsocks.Net.Crypto.Stream;
using Splat;
using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
namespace Shadowsocks.Net.Crypto.AEAD
{
public abstract class AEADCrypto : CryptoBase, IEnableLogger
{
// We are using the same saltLen and keyLen
private const string Info = "ss-subkey";
private static readonly byte[] InfoBytes = Encoding.ASCII.GetBytes(Info);
// every connection should create its own buffer
private readonly byte[] buffer = new byte[65536];
private int bufPtr = 0;
public const int ChunkLengthBytes = 2;
public const uint ChunkLengthMask = 0x3FFFu;
protected CipherFamily cipherFamily;
protected CipherInfo CipherInfo;
protected static byte[] masterKey = Array.Empty<byte>();
protected byte[] sessionKey = Array.Empty<byte>();
protected int keyLen;
protected int saltLen;
protected int tagLen;
protected int nonceLen;
protected byte[] salt;
protected byte[] nonce;
// Is first packet
protected bool saltReady;
// Is first chunk(tcp request)
protected bool tcpRequestSent;
// [len(2)][lentag][data][datatag]
private int ChunkOverhead => tagLen * 2 + 2;
public AEADCrypto(string method, string password)
: base(method, password)
{
CipherInfo = GetCiphers()[method.ToLower()];
cipherFamily = CipherInfo.Type;
AEADCipherParameter parameter = (AEADCipherParameter)CipherInfo.CipherParameter;
keyLen = parameter.KeySize;
saltLen = parameter.SaltSize;
tagLen = parameter.TagSize;
nonceLen = parameter.NonceSize;
InitKey(password);
salt = new byte[saltLen];
// Initialize all-zero nonce for each connection
nonce = new byte[nonceLen];
this.Log().Debug($"masterkey {instanceId} {masterKey} {keyLen}");
this.Log().Debug($"nonce {instanceId} {nonce} {keyLen}");
}
protected abstract Dictionary<string, CipherInfo> GetCiphers();
protected void InitKey(string password)
{
byte[] passbuf = Encoding.UTF8.GetBytes(password);
// init master key
if (masterKey == null)
{
masterKey = new byte[keyLen];
}
if (masterKey.Length != keyLen)
{
Array.Resize(ref masterKey, keyLen);
}
StreamCrypto.LegacyDeriveKey(passbuf, masterKey, keyLen);
// init session key
sessionKey = new byte[keyLen];
}
public virtual void InitCipher(byte[] salt, bool isEncrypt)
{
this.salt = new byte[saltLen];
Array.Copy(salt, this.salt, saltLen);
HKDF.DeriveKey(HashAlgorithmName.SHA1, masterKey, sessionKey, salt, InfoBytes);
this.Log().Debug($"salt {instanceId}", salt, saltLen);
this.Log().Debug($"sessionkey {instanceId}", sessionKey, keyLen);
}
public abstract int CipherEncrypt(ReadOnlySpan<byte> plain, Span<byte> cipher);
public abstract int CipherDecrypt(Span<byte> plain, ReadOnlySpan<byte> cipher);
#region TCP
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Encrypt(ReadOnlySpan<byte> plain, Span<byte> cipher)
{
// push data
Span<byte> tmp = buffer.AsSpan(0, plain.Length + bufPtr);
plain.CopyTo(tmp.Slice(bufPtr));
int outlength = 0;
if (!saltReady)
{
saltReady = true;
// Generate salt
byte[] saltBytes = RNG.GetBytes(saltLen);
InitCipher(saltBytes, true);
saltBytes.CopyTo(cipher);
outlength = saltLen;
}
while (true)
{
// calculate next chunk size
int bufSize = tmp.Length;
if (bufSize <= 0)
{
return outlength;
}
int chunklength = (int)Math.Min(bufSize, ChunkLengthMask);
// read next chunk
int encChunkLength = ChunkEncrypt(tmp.Slice(0, chunklength), cipher.Slice(outlength));
tmp = tmp.Slice(chunklength);
outlength += encChunkLength;
// check if we have enough space for outbuf
// if not, keep buf for next run, at this condition, buffer is not empty
if (outlength + ChunkOverhead > cipher.Length)
{
this.Log().Debug("enc outbuf almost full, giving up");
// write rest data to head of shared buffer
tmp.CopyTo(buffer);
bufPtr = tmp.Length;
return outlength;
}
// check if buffer empty
bufSize = tmp.Length;
if (bufSize <= 0)
{
this.Log().Debug("No more data to encrypt, leaving");
return outlength;
}
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Decrypt(Span<byte> plain, ReadOnlySpan<byte> cipher)
{
int outlength = 0;
// drop all into buffer
Span<byte> tmp = buffer.AsSpan(0, cipher.Length + bufPtr);
cipher.CopyTo(tmp.Slice(bufPtr));
int bufSize = tmp.Length;
this.Log().Debug($"{instanceId} decrypt tcp, read salt: {!saltReady}");
if (!saltReady)
{
// check if we get the leading salt
if (bufSize <= saltLen)
{
// need more, write back cache
tmp.CopyTo(buffer);
bufPtr = tmp.Length;
return outlength;
}
saltReady = true;
byte[] salt = tmp.Slice(0, saltLen).ToArray();
tmp = tmp.Slice(saltLen);
InitCipher(salt, false);
}
// handle chunks
while (true)
{
bufSize = tmp.Length;
// check if we have any data
if (bufSize <= 0)
{
this.Log().Debug("No data in buffer");
return outlength;
}
// first get chunk length
if (bufSize <= ChunkLengthBytes + tagLen)
{
// so we only have chunk length and its tag?
// wait more
this.Log().Debug($"{instanceId} not enough data to decrypt chunk. write {tmp.Length} byte back to buffer.");
tmp.CopyTo(buffer);
bufPtr = tmp.Length;
return outlength;
}
this.Log().Debug($"{instanceId} try decrypt to offset {outlength}");
int len = ChunkDecrypt(plain.Slice(outlength), tmp);
if (len <= 0)
{
this.Log().Debug($"{instanceId} no chunk decrypted, write {tmp.Length} byte back to buffer.");
// no chunk decrypted
tmp.CopyTo(buffer);
bufPtr = tmp.Length;
return outlength;
}
this.Log().Debug($"{instanceId} decrypted {len} to offset {outlength}");
// drop decrypted data
tmp = tmp.Slice(ChunkLengthBytes + tagLen + len + tagLen);
outlength += len;
// logger.Debug("aead dec outlength " + outlength);
if (outlength + ChunkOverhead > cipher.Length)
{
this.Log().Debug($"{instanceId} output almost full, write {tmp.Length} byte back to buffer.");
tmp.CopyTo(buffer);
bufPtr = tmp.Length;
return outlength;
}
bufSize = tmp.Length;
// check if we already done all of them
if (bufSize <= 0)
{
bufPtr = 0;
this.Log().Debug($"{instanceId} no data in buffer, already all done");
return outlength;
}
}
}
#endregion
#region UDP
[MethodImpl(MethodImplOptions.Synchronized)]
public override int EncryptUDP(ReadOnlySpan<byte> plain, Span<byte> cipher)
{
RNG.GetSpan(cipher.Slice(0, saltLen));
InitCipher(cipher.Slice(0, saltLen).ToArray(), true);
return saltLen + CipherEncrypt(plain, cipher.Slice(saltLen));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int DecryptUDP(Span<byte> plain, ReadOnlySpan<byte> cipher)
{
InitCipher(cipher.Slice(0, saltLen).ToArray(), false);
return CipherDecrypt(plain, cipher.Slice(saltLen));
}
#endregion
[MethodImpl(MethodImplOptions.Synchronized)]
private int ChunkEncrypt(ReadOnlySpan<byte> plain, Span<byte> cipher)
{
if (plain.Length > ChunkLengthMask)
{
this.Log().Error("enc chunk too big");
throw new CryptoErrorException();
}
byte[] lenbuf = BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder((short)plain.Length));
int cipherLenSize = CipherEncrypt(lenbuf, cipher);
nonce.Increment();
int cipherDataSize = CipherEncrypt(plain, cipher.Slice(cipherLenSize));
nonce.Increment();
return cipherLenSize + cipherDataSize;
}
[MethodImpl(MethodImplOptions.Synchronized)]
private int ChunkDecrypt(Span<byte> plain, ReadOnlySpan<byte> cipher)
{
// try to dec chunk len
byte[] chunkLengthByte = new byte[ChunkLengthBytes];
CipherDecrypt(chunkLengthByte, cipher.Slice(0, ChunkLengthBytes + tagLen));
ushort chunkLength = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(chunkLengthByte, 0));
if (chunkLength > ChunkLengthMask)
{
// we get invalid chunk
this.Log().Error($"{instanceId} Invalid chunk length: {chunkLength}");
throw new CryptoErrorException();
}
// logger.Debug("Get the real chunk len:" + chunkLength);
int bufSize = cipher.Length;
if (bufSize < ChunkLengthBytes + tagLen /* we haven't remove them */+ chunkLength + tagLen)
{
this.Log().Debug($"{instanceId} need {ChunkLengthBytes + tagLen + chunkLength + tagLen}, but have {cipher.Length}");
return 0;
}
nonce.Increment();
// we have enough data to decrypt one chunk
// drop chunk len and its tag from buffer
int len = CipherDecrypt(plain, cipher.Slice(ChunkLengthBytes + tagLen, chunkLength + tagLen));
nonce.Increment();
this.Log().Debug($"{instanceId} decrypted {len} byte chunk used {ChunkLengthBytes + tagLen + chunkLength + tagLen} from {cipher.Length}");
return len;
}
}
}