Skip to content

Commit

Permalink
改进传输加密,升级部分库以提升安全性
Browse files Browse the repository at this point in the history
  • Loading branch information
shaohaozhi committed Jul 21, 2024
1 parent b89679d commit 27af6ca
Show file tree
Hide file tree
Showing 8 changed files with 178 additions and 106 deletions.
80 changes: 51 additions & 29 deletions src/NSmartProxy.ClientRouter/Router.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using NSmartProxy.ClientRouter.Dispatchers;
using NSmartProxy.Data.Models;
using NSmartProxy.Infrastructure;
using System.IO.Compression;

namespace NSmartProxy.Client
{
Expand Down Expand Up @@ -95,8 +96,7 @@ public Router()

public Router(INSmartLogger logger) : this()
{
Logger = logger;//TODO 重复了,待优化

Logger = logger;
Global.Logger = logger;
}

Expand Down Expand Up @@ -458,7 +458,7 @@ private async Task OpenTransmission(int appId, TcpClient providerClient)
return;//tcp 开启隧道,并且不再利用此连接
case ControlMethod.ForceClose:
Logger.Info("客户端在别处被抢登,当前被强制下线。");
Close();
await Close();
return;
default: throw new Exception("非法请求:" + buffer[0]);
}
Expand Down Expand Up @@ -651,26 +651,36 @@ private async Task TcpTransferAsync(TcpClient providerClient, TcpClient toTarget
private async Task StreamTransfer(CancellationToken ct, NetworkStream fromStream, NetworkStream toStream,
string epString, ClientApp item)
{
byte[] buffer = new byte[Global.ClientTunnelBufferSize];
using (fromStream)
//if (item.IsCompress)
//{
// await StringUtil.DecompressInSnappierAsync(fromStream, toStream, ct);
//}
//else
{
int bytesRead;
while ((bytesRead =
await fromStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) != 0)
byte[] buffer = new byte[Global.ClientTunnelBufferSize];
if (item.IsCompress)
{
if (item.IsCompress)
using (GZipStream gZipStream = new GZipStream(fromStream, CompressionMode.Decompress))
{
var compressBuffer = StringUtil.DecompressInSnappy(buffer, 0, bytesRead);
bytesRead = compressBuffer.Length;
await toStream.WriteAsync(compressBuffer, 0, bytesRead, ct).ConfigureAwait(false);
int bytesRead;
while ((bytesRead = await gZipStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) != 0)
{
await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);
}
}
else
}
else
{
using (fromStream)
{
//bytesRead = buffer.Length;
await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);
}
int bytesRead;
while ((bytesRead =
await fromStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) != 0)
{
await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);

// await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);
}
}
}
}
Router.Logger.Debug($"{epString}对节点传输关闭。");
Expand All @@ -682,23 +692,35 @@ await fromStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false))
private async Task ToStaticTransfer(CancellationToken ct, NetworkStream fromStream, NetworkStream toStream,
string epString, ClientApp item)
{
byte[] buffer = new byte[Global.ClientTunnelBufferSize];
using (fromStream)
//if (item.IsCompress)
//{
// await StringUtil.CompressInSnappierAsync(fromStream, toStream, ct);
//}
//else
{
int bytesRead;
while ((bytesRead =
await fromStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) != 0)
byte[] buffer = new byte[Global.ClientTunnelBufferSize];
if (item.IsCompress)
{
if (item.IsCompress)
using(GZipStream gZipStream = new GZipStream(fromStream, CompressionMode.Compress))
{
var compressInSnappy = StringUtil.CompressInSnappy(buffer, 0, bytesRead);
var compressedBuffer = compressInSnappy.ContentBytes;
bytesRead = compressInSnappy.Length;
await toStream.WriteAsync(compressedBuffer, 0, bytesRead, ct).ConfigureAwait(false);
int bytesRead;
while ((bytesRead =await gZipStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) != 0)
{
await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);
}
}
else
}
else
{
using (fromStream)
{
await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);
int bytesRead;
while ((bytesRead =
await fromStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) != 0)
{

await toStream.WriteAsync(buffer, 0, bytesRead, ct).ConfigureAwait(false);
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>7.2</LangVersion>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="EasyCompressor.Snappier" Version="2.0.2" />
<PackageReference Include="NewtonSoft.Json" Version="13.0.3" />
<PackageReference Include="snappy.sharp" Version="1.0.0" />
<PackageReference Include="System.Buffers" Version="4.5.1" />
<PackageReference Include="System.IO.Pipelines" Version="8.0.0" />
</ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/NSmartProxy.Infrastructure/Shared/Global.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ public sealed class Global

public const int ClientUdpReceiveTimeout = 3000;//客户端udp接收超时时长(毫秒)

public const int ClientTunnelBufferSize = 81920; //客户端数据包大小
public const int ClientTunnelBufferSize = 1024 * 1024 * 1024; //客户端数据包大小
public const int ClientUdpBufferSize = 65535;//服务端udp数据包大小
#region 服务端配置

public const int StartArrangedPort = 20000;
public const string NSPServerDisplayName = "NSPServer";//windows服务显示名
public const string NSPServerServiceName = "NSPServer";//windows服务名

public const int ServerTunnelBufferSize = 81920;//服务端数据包大小
public const int ServerTunnelBufferSize = 1024 * 1024 * 1024;//服务端数据包大小
public const int ServerUdpBufferSize = 65535;//服务端udp数据包大小


Expand Down
73 changes: 43 additions & 30 deletions src/NSmartProxy.Infrastructure/StringUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@
using System.Text;
using NSmartProxy.Data;
using NSmartProxy.Infrastructure;
using Snappy.Sharp;
using NSmartProxy.Shared;
using EasyCompressor;
using System.Threading;
using System.Threading.Tasks;

namespace NSmartProxy
{
public static class StringUtil
{
//Lazy初始化一个snappier
private static Lazy<SnappierCompressor> _snappyCompressor = new Lazy<SnappierCompressor>(() => SnappierCompressor.Shared);


/// <summary>
/// 整型转双字节
/// </summary>
Expand Down Expand Up @@ -218,19 +223,20 @@ public static bool IsNum(this string str)
/// <param name="offset"></param>
/// <param name="length"></param>
/// <returns></returns>
public static byte[] DecompressInSnappy(byte[] compressed, int offset, int length)
{
SnappyDecompressor sd = new SnappyDecompressor();
try
{
return sd.Decompress(compressed, offset, length);
}
catch (Exception ex)
{
Global.Logger.Error("snappy解压缩失败", ex);
return null;
}
}
//public static byte[] DecompressInSnappy(byte[] compressed, int offset, int length)
//{
// SnappyDecompressor sd = new SnappyDecompressor();
// try
// {
// return sd.Decompress(compressed, offset, length);
// }
// catch (Exception ex)
// {
// _ = ex;
// //啥情況?
// return null;
// }
//}

/// <summary>
/// 使用snappy算法压缩
Expand All @@ -239,25 +245,32 @@ public static byte[] DecompressInSnappy(byte[] compressed, int offset, int lengt
/// <param name="offset"></param>
/// <param name="uncompressedLength"></param>
/// <returns></returns>
public static CompressedBytes CompressInSnappy(byte[] uncompressed, int offset, int uncompressedLength)
{
try
{
SnappyCompressor sc = new SnappyCompressor();
//public static CompressedBytes CompressInSnappy(byte[] uncompressed, int offset, int uncompressedLength)
//{
// SnappyCompressor sc = new SnappyCompressor();

//var bytes = Encoding.ASCII.GetBytes("HelloWor134ertegsdfgsfdgsdfgsdfgsfdgsdfgsdfgsdfgsdfgdsfgsdfgdsfgdfgdsfgld");
byte[] outBytes = new byte[sc.MaxCompressedLength(uncompressed.Length)];
// //var bytes = Encoding.ASCII.GetBytes("HelloWor134ertegsdfgsfdgsdfgsdfgsfdgsdfgsdfgsdfgsdfgdsfgsdfgdsfgdfgdsfgld");
// byte[] outBytes = new byte[sc.MaxCompressedLength(uncompressed.Length)];

int actualLength = sc.Compress(uncompressed, 0, uncompressedLength, outBytes);
return new CompressedBytes() { ContentBytes = outBytes, Length = actualLength };
}
catch (Exception ex)
{
Global.Logger.Error("snappy压缩失败", ex);
return null;
}
// int actualLength = sc.Compress(uncompressed, 0, uncompressedLength, outBytes);
// return new CompressedBytes() { ContentBytes = outBytes, Length = actualLength };
//}


public async static Task CompressInSnappierAsync(Stream inputStream, Stream outputStream, CancellationToken ct)
{
await _snappyCompressor.Value.CompressAsync(inputStream, outputStream,ct);
}

public async static Task DecompressInSnappierAsync(Stream inputStream, Stream outputStream, CancellationToken ct)
{
await _snappyCompressor.Value.DecompressAsync(inputStream, outputStream, ct);
}





/// <summary>
/// 压缩专用对象
/// </summary>
Expand Down
Loading

0 comments on commit 27af6ca

Please sign in to comment.