Skip to content

Commit

Permalink
authorize on server.
Browse files Browse the repository at this point in the history
  • Loading branch information
tmoonlight committed Apr 21, 2019
1 parent e1e1954 commit e1e9f3f
Show file tree
Hide file tree
Showing 12 changed files with 708 additions and 102 deletions.
4 changes: 2 additions & 2 deletions src/NSmartProxy.ClientRouter/Router.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public async Task Start()
ClientModel clientModel = null;//
try
{
//TODO 非第一次则算作重连,发送clientid过去
//非第一次则算作重连,发送clientid过去
clientModel = await ConnectionManager.InitConfig(this.ClientConfig, IsStarted).ConfigureAwait(false);
}
catch (Exception ex)
Expand Down Expand Up @@ -206,7 +206,7 @@ private async Task OpenTrasferation(int appId, TcpClient providerClient)
byte[] buffer = new byte[1];
NetworkStream providerClientStream = providerClient.GetStream();
//接收首条消息,首条消息中返回的是appid和客户端
//TODO 客户端长连接,需要保活,终止则说明服务端断开
//TODO 消费端长连接,需要在server端保活
// providerClient.keep
// providerClient.Client.

Expand Down
577 changes: 577 additions & 0 deletions src/NSmartProxy.Infrastructure/EncryptHelper.cs

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion src/NSmartProxy.Infrastructure/Extensions/StreamExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ namespace NSmartProxy.Infrastructure
{
public static class StreamExtension
{
public static async Task WriteAndFlushAsync(this Stream stream, byte[] buffer, int offset, int count)
public static async Task WriteAndFlushAsync(this Stream stream, byte[] buffer, int offset = 0, int count = 0)
{
//不让赋值默认值,只能暂时给个0
if (count == 0) count = buffer.Length;
await stream.WriteAsync(buffer, offset, count);
await stream.FlushAsync();
}
Expand Down
13 changes: 13 additions & 0 deletions src/NSmartProxy/Authorize/NSPContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace NSmartProxy.Authorize
{
public class NSPContext
{
//服务端会话池,登陆后的会话都在这里

//public
}
}
107 changes: 107 additions & 0 deletions src/NSmartProxy/Authorize/SecurityTcpClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using NSmartProxy.Infrastructure;

namespace NSmartProxy.Authorize
{
public class AuthResult
{
public bool Success { get; set; }

}

/// <summary>
/// 标识位 token长度 token值
/// 2位固定0xF9 2 n
/// </summary>
public class SecurityTcpClient : TcpClient
{
public string Token = "";
public readonly byte F9 = 0xF9;//固定标识位
public String ErrorMessage = "";

public SecurityTcpClient(string secureToken) : base()
{
Token = secureToken;
}

/// <summary>
/// 带加密串传输
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <returns></returns>
public async Task ConnectWithAuthAsync(string host, int port)
{
if (String.IsNullOrEmpty(Token))
{
return;
}

//标识位 token长度 值
int requestLength = 1 + 2 + Token.Length;

var stream = this.GetStream();
await base.ConnectAsync(host, port);
await stream.WriteAsync(new byte[] { F9 });
await stream.WriteAsync(StringUtil.IntTo2Bytes(Token.Length));
await stream.WriteAndFlushAsync(ASCIIEncoding.ASCII.GetBytes(Token));
}

////传输加密,待开发
//public SslStream GetSslStream()
//{
// return new SslStream(this.GetStream());
//}

/// <summary>
/// 服务端校验
/// </summary>
/// <returns></returns>
public async Task<AuthResult> AuthorizeAsync()
{
var stream = this.GetStream();
//标识 1
var protocolBytes = ArrayPool<byte>.Shared.Rent(1);
if (await stream.ReadAsync(protocolBytes, 0, protocolBytes.Length) == 0)
{
ErrorMessage += "读取到0字节,客户端已关闭?";
return null;
}
if (protocolBytes[0] != F9)
{
ErrorMessage += $"非法头部 {protocolBytes[0]}";
}

//2.token长度 2
var lengthBytes = ArrayPool<byte>.Shared.Rent(2);
if (await stream.ReadAsync(lengthBytes, 0, lengthBytes.Length) == 0)
{
ErrorMessage += "读取到0字节,客户端已关闭?";
return null;
}
int tokenLength = StringUtil.DoubleBytesToInt(lengthBytes);

//3.校验
var tokenBytes = ArrayPool<byte>.Shared.Rent(tokenLength);
if (await stream.ReadAsync(tokenBytes, 0, tokenBytes.Length) == 0)
{
ErrorMessage += "获取token失败?";
return null;
}

var token = ASCIIEncoding.ASCII.GetString(tokenBytes);
//TODO ***校验Token

return new AuthResult()
{
Success = false
};
}
}
}
1 change: 1 addition & 0 deletions src/NSmartProxy/ClientConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ public async Task<TcpClient> GetClient(int consumerPort)
var clientID = PortAppMap[consumerPort].ClientId;
var appID = PortAppMap[consumerPort].AppId;

//TODO ***需要处理服务端长时间不来请求的情况(无法建立隧道)
TcpClient client = await Clients[clientID].AppMap[appID].PopClientAsync();
PortAppMap[consumerPort].ReverseClients.Add(client);
return client;
Expand Down
2 changes: 2 additions & 0 deletions src/NSmartProxy/Extension/HttpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ private async Task ProcessHttpRequestAsync(HttpListenerContext context)
response.ContentEncoding = Encoding.UTF8;
response.ContentType = "text/html;charset=utf-8";

//TODO ***通过request来的值进行接口调用

//getJson
var json = GetClientsInfoJson();
await response.OutputStream.WriteAsync(HtmlUtil.GetContent(json.ToString()));
Expand Down
2 changes: 0 additions & 2 deletions src/NSmartProxy/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ public async Task Start()
}

//3.开启心跳检测线程
//TODO 服务端心跳检测
ProcessHeartbeatsCheck(Global.HeartbeatCheckInterval, ctsConsumer);

//4.开启配置服务(常开)
Expand Down Expand Up @@ -306,7 +305,6 @@ private async Task ProcessConfigRequestAsync(TcpClient client)
await ProcessAppRequestProtocol(client);
break;
case Protocol.Heartbeat:
//TODO 记录服务端更新时间
await ProcessHeartbeatProtocol(client);
break;
case Protocol.CloseClient:
Expand Down
4 changes: 1 addition & 3 deletions src/NSmartProxyWinform/FodyWeavers.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
</Weavers>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd" />
89 changes: 1 addition & 88 deletions src/NSmartProxyWinform/FodyWeavers.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -3,94 +3,7 @@
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
<xs:element name="Weavers">
<xs:complexType>
<xs:all>
<xs:element name="Costura" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:all>
<xs:element minOccurs="0" maxOccurs="1" name="ExcludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="IncludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="Unmanaged32Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged 32 bit assembly names to include, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="Unmanaged64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged 64 bit assembly names to include, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="PreloadOrder" type="xs:string">
<xs:annotation>
<xs:documentation>The order of preloaded assemblies, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
</xs:all>
<xs:attribute name="CreateTemporaryAssemblies" type="xs:boolean">
<xs:annotation>
<xs:documentation>This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IncludeDebugSymbols" type="xs:boolean">
<xs:annotation>
<xs:documentation>Controls if .pdbs for reference assemblies are also embedded.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="DisableCompression" type="xs:boolean">
<xs:annotation>
<xs:documentation>Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="DisableCleanup" type="xs:boolean">
<xs:annotation>
<xs:documentation>As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="LoadAtModuleInit" type="xs:boolean">
<xs:annotation>
<xs:documentation>Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IgnoreSatelliteAssemblies" type="xs:boolean">
<xs:annotation>
<xs:documentation>Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="ExcludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with |</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IncludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="Unmanaged32Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged 32 bit assembly names to include, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="Unmanaged64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged 64 bit assembly names to include, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="PreloadOrder" type="xs:string">
<xs:annotation>
<xs:documentation>The order of preloaded assemblies, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:all>
<xs:all></xs:all>
<xs:attribute name="VerifyAssembly" type="xs:boolean">
<xs:annotation>
<xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
Expand Down
6 changes: 1 addition & 5 deletions src/NSmartProxyWinform/NSmartProxyWinform.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Costura.Fody.3.3.3\build\Costura.Fody.props" Condition="Exists('..\packages\Costura.Fody.3.3.3\build\Costura.Fody.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand Down Expand Up @@ -39,9 +38,6 @@
<ApplicationIcon>nsp.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Costura, Version=3.3.3.0, Culture=neutral, PublicKeyToken=9919ef960d84173d, processorArchitecture=MSIL">
<HintPath>..\packages\Costura.Fody.3.3.3\lib\net40\Costura.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
</Reference>
Expand Down Expand Up @@ -166,5 +162,5 @@
<Content Include="Resources\servicestopped.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Fody.4.0.2\build\Fody.targets" Condition="Exists('..\packages\Fody.4.0.2\build\Fody.targets')" />

</Project>
1 change: 0 additions & 1 deletion src/NSmartProxyWinform/packages.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Costura.Fody" version="3.3.3" targetFramework="net461" />
<package id="Fody" version="4.0.2" targetFramework="net461" developmentDependency="true" />
<package id="log4net" version="2.0.8" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration" version="2.2.0" targetFramework="net461" />
Expand Down

0 comments on commit e1e9f3f

Please sign in to comment.