forked from vpnhood/VpnHood
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Session.cs
504 lines (430 loc) · 20.3 KB
/
Session.cs
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using PacketDotNet;
using VpnHood.Common.Client;
using VpnHood.Common.JobController;
using VpnHood.Common.Logging;
using VpnHood.Common.Messaging;
using VpnHood.Common.Utils;
using VpnHood.Server.Configurations;
using VpnHood.Server.Exceptions;
using VpnHood.Tunneling;
using VpnHood.Tunneling.Factory;
using VpnHood.Tunneling.Messaging;
using ProtocolType = PacketDotNet.ProtocolType;
namespace VpnHood.Server;
public class Session : IAsyncDisposable, IJob
{
private readonly INetFilter _netFilter;
private readonly IAccessServer _accessServer;
private readonly SessionProxyManager _proxyManager;
private readonly ISocketFactory _socketFactory;
private readonly IPEndPoint _localEndPoint;
private readonly object _syncLock = new();
private readonly object _verifyRequestLock = new();
private readonly int _maxTcpConnectWaitCount;
private readonly int _maxTcpChannelCount;
private readonly int? _tcpBufferSize;
private readonly int? _tcpKernelSendBufferSize;
private readonly int? _tcpKernelReceiveBufferSize;
private readonly TimeSpan _tcpTimeout;
private readonly long _syncCacheSize;
private readonly TimeSpan _tcpConnectTimeout;
private readonly TrackingOptions _trackingOptions;
private readonly EventReporter _netScanExceptionReporter = new(VhLogger.Instance, "NetScan protector does not allow this request.", GeneralEventId.NetProtect);
private readonly EventReporter _maxTcpChannelExceptionReporter = new(VhLogger.Instance, "Maximum TcpChannel has been reached.", GeneralEventId.NetProtect);
private readonly EventReporter _maxTcpConnectWaitExceptionReporter = new(VhLogger.Instance, "Maximum TcpConnectWait has been reached.", GeneralEventId.NetProtect);
private readonly EventReporter _filterReporter = new(VhLogger.Instance, "Some requests has been blocked.", GeneralEventId.NetProtect);
private bool _isSyncing;
private readonly Traffic _syncTraffic = new ();
private int _tcpConnectWaitCount;
private readonly JobSection _syncJobSection;
public Tunnel Tunnel { get; }
public uint SessionId { get; }
public byte[] SessionKey { get; }
public SessionResponseBase SessionResponse { get; private set; }
public UdpChannel? UdpChannel { get; private set; }
public bool IsDisposed { get; private set; }
public NetScanDetector? NetScanDetector { get; }
public JobSection JobSection { get; } = new();
public HelloRequest? HelloRequest { get; }
public int TcpConnectWaitCount => _tcpConnectWaitCount;
public int TcpChannelCount => Tunnel.TcpProxyChannelCount + (UseUdpChannel ? 0 : Tunnel.DatagramChannels.Length);
public int UdpConnectionCount => _proxyManager.UdpClientCount + (UseUdpChannel ? 1 : 0);
public DateTime LastActivityTime => Tunnel.LastActivityTime;
internal Session(IAccessServer accessServer, SessionResponse sessionResponse,
INetFilter netFilter,
ISocketFactory socketFactory,
IPEndPoint localEndPoint, SessionOptions options, TrackingOptions trackingOptions,
HelloRequest? helloRequest)
{
var sessionTuple = Tuple.Create("SessionId", (object?)sessionResponse.SessionId);
var logScope = new LogScope();
logScope.Data.Add(sessionTuple);
_accessServer = accessServer ?? throw new ArgumentNullException(nameof(accessServer));
_socketFactory = socketFactory ?? throw new ArgumentNullException(nameof(socketFactory));
_proxyManager = new SessionProxyManager(this, socketFactory, new ProxyManagerOptions
{
UdpTimeout = options.UdpTimeoutValue,
IcmpTimeout = options.IcmpTimeoutValue,
MaxUdpWorkerCount = options.MaxUdpPortCount,
UseUdpProxy2 = options.UseUdpProxy2Value,
LogScope = logScope
});
_localEndPoint = localEndPoint;
_trackingOptions = trackingOptions;
_maxTcpConnectWaitCount = options.MaxTcpConnectWaitCountValue;
_maxTcpChannelCount = options.MaxTcpChannelCountValue;
_tcpBufferSize = options.TcpBufferSize;
_tcpKernelSendBufferSize = options.TcpKernelSendBufferSize;
_tcpKernelReceiveBufferSize = options.TcpKernelReceiveBufferSize;
_syncCacheSize = options.SyncCacheSizeValue;
_tcpTimeout = options.TcpTimeoutValue;
_tcpConnectTimeout = options.TcpConnectTimeoutValue;
_netFilter = netFilter;
_netScanExceptionReporter.LogScope.Data.AddRange(logScope.Data);
_maxTcpConnectWaitExceptionReporter.LogScope.Data.AddRange(logScope.Data);
_maxTcpChannelExceptionReporter.LogScope.Data.AddRange(logScope.Data);
_syncJobSection = new JobSection(options.SyncIntervalValue);
HelloRequest = helloRequest;
SessionResponse = new SessionResponseBase(sessionResponse);
SessionId = sessionResponse.SessionId;
SessionKey = sessionResponse.SessionKey ?? throw new InvalidOperationException($"{nameof(sessionResponse)} does not have {nameof(sessionResponse.SessionKey)}!");
var tunnelOptions = new TunnelOptions
{
MaxDatagramChannelCount = options.MaxDatagramChannelCountValue
};
Tunnel = new Tunnel(tunnelOptions);
Tunnel.OnPacketReceived += Tunnel_OnPacketReceived;
// ReSharper disable once MergeIntoPattern
if (options.NetScanLimit != null && options.NetScanTimeout != null)
NetScanDetector = new NetScanDetector(options.NetScanLimit.Value, options.NetScanTimeout.Value);
JobRunner.Default.Add(this);
}
public Task RunJob()
{
using var jobLock = _syncJobSection.Enter();
return Sync(jobLock.IsEntered, false);
}
public bool UseUdpChannel
{
// ReSharper disable once MergeIntoPattern
get => Tunnel.DatagramChannels.Length == 1 && Tunnel.DatagramChannels[0] is UdpChannel;
set
{
if (value == UseUdpChannel)
return;
if (value)
{
// remove tcpDatagram channels
foreach (var item in Tunnel.DatagramChannels.Where(x => x != UdpChannel))
Tunnel.RemoveChannel(item);
// create UdpKey
using var aes = Aes.Create();
aes.KeySize = 128;
aes.GenerateKey();
// Create the only one UdpChannel
UdpChannel = new UdpChannel(false, _socketFactory.CreateUdpClient(_localEndPoint.AddressFamily), SessionId, aes.Key);
try { Tunnel.AddChannel(UdpChannel); }
catch { UdpChannel.Dispose(); throw; }
}
else
{
// remove udp channels
foreach (var item in Tunnel.DatagramChannels.Where(x => x == UdpChannel))
Tunnel.RemoveChannel(item);
UdpChannel = null;
}
}
}
private void Tunnel_OnPacketReceived(object sender, ChannelPacketReceivedEventArgs e)
{
if (IsDisposed)
return;
// filter requests
foreach (var ipPacket in e.IpPackets)
{
var ipPacket2 = _netFilter.ProcessRequest(ipPacket);
if (ipPacket2 == null)
{
var ipeEndPointPair = PacketUtil.GetPacketEndPoints(ipPacket);
LogTrack(ipPacket.Protocol.ToString(), null, ipeEndPointPair.RemoteEndPoint, false, true, "NetFilter");
_filterReporter.Raised();
continue;
}
_ = _proxyManager.SendPacket(ipPacket2);
}
}
public Task Sync()
{
return Sync(true, false);
}
private async Task Sync(bool force, bool closeSession)
{
if (SessionResponse.ErrorCode != SessionErrorCode.Ok)
return;
using var scope = VhLogger.Instance.BeginScope(
$"Server => SessionId: {VhLogger.FormatSessionId(SessionId)}, TokenId: {VhLogger.FormatId(HelloRequest?.TokenId)}");
Traffic traffic;
lock (_syncLock)
{
if (_isSyncing)
return;
traffic = new Traffic
{
Sent = Tunnel.Traffic.Received - _syncTraffic.Sent, // Intentionally Reversed: sending to tunnel means receiving form client,
Received = Tunnel.Traffic.Sent - _syncTraffic.Received // Intentionally Reversed: receiving from tunnel means sending for client
};
var shouldSync = closeSession || (force && traffic.Total > 0) || traffic.Total >= _syncCacheSize;
if (!shouldSync)
return;
// reset usage and sync time; no matter it is successful or not to prevent frequent call
_syncTraffic.Add(traffic);
_isSyncing = true;
}
try
{
SessionResponse = closeSession
? await _accessServer.Session_Close(SessionId, traffic)
: await _accessServer.Session_AddUsage(SessionId, traffic);
// dispose for any error
if (SessionResponse.ErrorCode != SessionErrorCode.Ok)
await DisposeAsync(false, false);
}
catch (ApiException ex) when (ex.StatusCode == (int)HttpStatusCode.NotFound)
{
SessionResponse.ErrorCode = SessionErrorCode.AccessError;
SessionResponse.ErrorMessage = "Session Not Found.";
await DisposeAsync(false, false);
}
catch (Exception ex)
{
VhLogger.Instance.LogWarning(GeneralEventId.AccessServer, ex,
"Could not report usage to the access-server.");
}
finally
{
lock (_syncLock)
_isSyncing = false;
}
}
public void LogTrack(string protocol, IPEndPoint? localEndPoint, IPEndPoint? destinationEndPoint,
bool isNewLocal, bool isNewRemote, string? failReason)
{
if (!_trackingOptions.IsEnabled)
return;
if (_trackingOptions is { TrackDestinationIpValue: false, TrackDestinationPortValue: false } && !isNewLocal && failReason == null)
return;
if (!_trackingOptions.TrackTcpValue && protocol.Equals("tcp", StringComparison.OrdinalIgnoreCase) ||
!_trackingOptions.TrackUdpValue && protocol.Equals("udp", StringComparison.OrdinalIgnoreCase) ||
!_trackingOptions.TrackUdpValue && protocol.Equals("icmp", StringComparison.OrdinalIgnoreCase))
return;
var mode = (isNewLocal ? "L" : "") + ((isNewRemote ? "R" : ""));
var localPortStr = "-";
var destinationIpStr = "-";
var destinationPortStr = "-";
var netScanCount = "-";
failReason ??= "Ok";
if (localEndPoint != null)
localPortStr = _trackingOptions.TrackLocalPortValue ? localEndPoint.Port.ToString() : "*";
if (destinationEndPoint != null)
{
destinationIpStr = _trackingOptions.TrackDestinationIpValue ? VhUtil.RedactIpAddress(destinationEndPoint.Address) : "*";
destinationPortStr = _trackingOptions.TrackDestinationPortValue ? destinationEndPoint.Port.ToString() : "*";
netScanCount = NetScanDetector?.GetBurstCount(destinationEndPoint).ToString() ?? "*";
}
VhLogger.Instance.LogInformation(GeneralEventId.Track,
"{Proto,-4}\tSessionId {SessionId}\t{Mode,-2}\tTcpCount {TcpCount,4}\tUdpCount {UdpCount,4}\tTcpWait {TcpConnectWaitCount,3}\tNetScan {NetScan,3}\t" +
"SrcPort {SrcPort,-5}\tDstIp {DstIp,-15}\tDstPort {DstPort,-5}\t{Success,-10}",
protocol, SessionId, mode,
TcpChannelCount, _proxyManager.UdpClientCount, _tcpConnectWaitCount, netScanCount,
localPortStr, destinationIpStr, destinationPortStr, failReason);
}
private void ConfigTcpClient(TcpClient tcpClient)
{
if (_tcpKernelReceiveBufferSize != null)
tcpClient.ReceiveBufferSize = _tcpKernelReceiveBufferSize.Value;
if (_tcpKernelSendBufferSize != null)
tcpClient.ReceiveBufferSize = _tcpKernelSendBufferSize.Value;
}
public async Task ProcessTcpDatagramChannelRequest(TcpClientStream tcpClientStream, CancellationToken cancellationToken)
{
ConfigTcpClient(tcpClientStream.TcpClient);
// send OK reply
await StreamUtil.WriteJsonAsync(tcpClientStream.Stream, SessionResponse, cancellationToken);
// Disable UdpChannel
UseUdpChannel = false;
// add channel
VhLogger.Instance.LogTrace(GeneralEventId.DatagramChannel,
"Creating a TcpDatagramChannel channel. SessionId: {SessionId}", VhLogger.FormatSessionId(SessionId));
var channel = new TcpDatagramChannel(tcpClientStream);
try
{
Tunnel.AddChannel(channel);
}
catch
{
channel.Dispose();
throw;
}
}
public async Task ProcessTcpChannelRequest(TcpClientStream tcpClientStream, TcpProxyChannelRequest request,
CancellationToken cancellationToken)
{
var isRequestedEpException = false;
var isTcpConnectIncreased = false;
TcpClient? tcpClientHost = null;
TcpClientStream? tcpClientStreamHost = null;
TcpProxyChannel? tcpProxyChannel = null;
try
{
// connect to requested site
VhLogger.Instance.LogTrace(GeneralEventId.TcpProxyChannel,
$"Connecting to the requested endpoint. RequestedEP: {VhLogger.Format(request.DestinationEndPoint)}");
// Apply limitation
VerifyTcpChannelRequest(tcpClientStream, request);
// prepare client
Interlocked.Increment(ref _tcpConnectWaitCount);
isTcpConnectIncreased = true;
tcpClientHost = _socketFactory.CreateTcpClient(request.DestinationEndPoint.AddressFamily);
_socketFactory.SetKeepAlive(tcpClientHost.Client, true);
//tracking
LogTrack(ProtocolType.Tcp.ToString(), (IPEndPoint)tcpClientHost.Client.LocalEndPoint, request.DestinationEndPoint,
true, true, null);
// connect to requested destination
isRequestedEpException = true;
await VhUtil.RunTask(
tcpClientHost.ConnectAsync(request.DestinationEndPoint.Address, request.DestinationEndPoint.Port),
_tcpConnectTimeout, cancellationToken);
isRequestedEpException = false;
// send response
await StreamUtil.WriteJsonAsync(tcpClientStream.Stream, this.SessionResponse, cancellationToken);
// Dispose ssl stream and replace it with a Head-Cryptor
await tcpClientStream.Stream.DisposeAsync();
tcpClientStream.Stream = StreamHeadCryptor.Create(tcpClientStream.TcpClient.GetStream(),
request.CipherKey, null, request.CipherLength);
// add the connection
VhLogger.Instance.LogTrace(GeneralEventId.TcpProxyChannel,
$"Adding a {nameof(TcpProxyChannel)}. SessionId: {VhLogger.FormatSessionId(SessionId)}, CipherLength: {request.CipherLength}");
tcpClientStreamHost = new TcpClientStream(tcpClientHost, tcpClientHost.GetStream());
ConfigTcpClient(tcpClientStream.TcpClient);
ConfigTcpClient(tcpClientStreamHost.TcpClient);
tcpProxyChannel = new TcpProxyChannel(tcpClientStreamHost, tcpClientStream, _tcpTimeout, _tcpBufferSize, _tcpBufferSize);
Tunnel.AddChannel(tcpProxyChannel);
}
catch (Exception ex)
{
tcpClientHost?.Dispose();
tcpClientStreamHost?.Dispose();
tcpProxyChannel?.Dispose();
if (isRequestedEpException)
throw new ServerSessionException(tcpClientStream.IpEndPointPair.RemoteEndPoint,
this, SessionErrorCode.GeneralError, ex.Message);
throw;
}
finally
{
if (isTcpConnectIncreased)
Interlocked.Decrement(ref _tcpConnectWaitCount);
}
}
private void VerifyTcpChannelRequest(TcpClientStream tcpClientStream, TcpProxyChannelRequest request)
{
// filter
var newEndPoint = _netFilter.ProcessRequest(ProtocolType.Tcp, request.DestinationEndPoint);
if (newEndPoint == null)
{
LogTrack(ProtocolType.Tcp.ToString(), null, request.DestinationEndPoint, false, true, "NetFilter");
_filterReporter.Raised();
throw new RequestBlockedException(tcpClientStream.RemoteEndPoint, this);
}
request.DestinationEndPoint = newEndPoint;
lock (_verifyRequestLock)
{
// NetScan limit
VerifyNetScan(ProtocolType.Tcp, request.DestinationEndPoint);
// Channel Count limit
if (TcpChannelCount >= _maxTcpChannelCount)
{
LogTrack(ProtocolType.Tcp.ToString(), null, request.DestinationEndPoint, false, true, "MaxTcp");
_maxTcpChannelExceptionReporter.Raised();
throw new MaxTcpChannelException(tcpClientStream.RemoteEndPoint, this);
}
// Check tcp wait limit
if (TcpConnectWaitCount >= _maxTcpConnectWaitCount)
{
LogTrack(ProtocolType.Tcp.ToString(), null, request.DestinationEndPoint, false, true, "MaxTcpWait");
_maxTcpConnectWaitExceptionReporter.Raised();
throw new MaxTcpConnectWaitException(tcpClientStream.RemoteEndPoint, this);
}
}
}
private void VerifyNetScan(ProtocolType protocol, IPEndPoint remoteEndPoint)
{
if (NetScanDetector == null || NetScanDetector.Verify(remoteEndPoint)) return;
LogTrack(protocol.ToString(), null, remoteEndPoint, false, true, "NetScan");
_netScanExceptionReporter.Raised();
throw new NetScanException(remoteEndPoint, this);
}
public ValueTask Close()
{
return DisposeAsync(true, true);
}
public ValueTask DisposeAsync()
{
return DisposeAsync(true, false);
}
private async ValueTask DisposeAsync(bool sync, bool byUser)
{
if (IsDisposed) return;
IsDisposed = true;
Tunnel.OnPacketReceived -= Tunnel_OnPacketReceived;
Tunnel.Dispose();
_proxyManager.Dispose();
_netScanExceptionReporter.Dispose();
_maxTcpChannelExceptionReporter.Dispose();
_maxTcpConnectWaitExceptionReporter.Dispose();
if (sync)
await Sync(true, byUser);
// if there is no reason it is temporary
var reason = "Cleanup";
if (SessionResponse.ErrorCode != SessionErrorCode.Ok)
reason = byUser ? "User" : "Access";
// Report removing session
VhLogger.Instance.LogInformation(GeneralEventId.SessionTrack,
"SessionId: {SessionId-5}\t{Mode,-5}\tActor: {Actor,-7}\tSuppressBy: {SuppressedBy,-8}\tErrorCode: {ErrorCode,-20}\tMessage: {message}",
SessionId, "Close", reason, SessionResponse.SuppressedBy, SessionResponse.ErrorCode, SessionResponse.ErrorMessage ?? "None");
}
private class SessionProxyManager : ProxyManager
{
private readonly Session _session;
protected override bool IsPingSupported => true;
public SessionProxyManager(Session session, ISocketFactory socketFactory, ProxyManagerOptions options)
: base(socketFactory, options)
{
_session = session;
}
public override Task OnPacketReceived(IPPacket ipPacket)
{
if (VhLogger.IsDiagnoseMode)
PacketUtil.LogPacket(ipPacket, "Delegating packet to client via proxy.");
ipPacket = _session._netFilter.ProcessReply(ipPacket);
return _session.Tunnel.SendPacket(ipPacket);
}
public override void OnNewEndPoint(ProtocolType protocolType, IPEndPoint localEndPoint, IPEndPoint remoteEndPoint,
bool isNewLocalEndPoint, bool isNewRemoteEndPoint)
{
_session.LogTrack(protocolType.ToString(), localEndPoint, remoteEndPoint, isNewLocalEndPoint, isNewRemoteEndPoint, null);
}
public override void OnNewRemoteEndPoint(ProtocolType protocolType, IPEndPoint remoteEndPoint)
{
_session.VerifyNetScan(protocolType, remoteEndPoint);
}
}
}