Skip to content

Commit b9a7b29

Browse files
committed
ability to work as service (with installation)
separated connect addres and send address lot of improvements
1 parent 66a8b0d commit b9a7b29

21 files changed

+465
-68
lines changed

AutoTunnel/AutoTunnel.csproj

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,23 +42,34 @@
4242
<PropertyGroup>
4343
<AssemblyOriginatorKeyFile>..\force.snk</AssemblyOriginatorKeyFile>
4444
</PropertyGroup>
45+
<PropertyGroup>
46+
<ApplicationManifest>app.manifest</ApplicationManifest>
47+
</PropertyGroup>
48+
<PropertyGroup>
49+
<ApplicationIcon>..\tunnel_hUB_icon.ico</ApplicationIcon>
50+
</PropertyGroup>
4551
<ItemGroup>
4652
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
4753
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
4854
<Private>True</Private>
4955
</Reference>
5056
<Reference Include="System" />
57+
<Reference Include="System.Configuration.Install" />
5158
<Reference Include="System.Core" />
59+
<Reference Include="System.Drawing" />
60+
<Reference Include="System.ServiceProcess" />
5261
<Reference Include="System.Xml.Linq" />
5362
<Reference Include="System.Data.DataSetExtensions" />
5463
<Reference Include="System.Data" />
5564
<Reference Include="System.Xml" />
5665
</ItemGroup>
5766
<ItemGroup>
67+
<None Include="app.manifest" />
5868
<None Include="config.json">
5969
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
6070
</None>
6171
<Compile Include="ClientSender.cs" />
72+
<Compile Include="Config\RemoteClientConfig.cs" />
6273
<Compile Include="Config\RemoteServerConfig.cs" />
6374
<Compile Include="Config\MainConfig.cs" />
6475
<Compile Include="EndpointHelper.cs" />
@@ -81,6 +92,15 @@
8192
<Compile Include="Properties\AssemblyInfo.cs" />
8293
<Compile Include="BaseSender.cs" />
8394
<Compile Include="ReplySender.cs" />
95+
<Compile Include="Service\ConsoleHelper.cs" />
96+
<Compile Include="Service\MainService.cs">
97+
<SubType>Component</SubType>
98+
</Compile>
99+
<Compile Include="Service\MainServiceInstaller.cs">
100+
<SubType>Component</SubType>
101+
</Compile>
102+
<Compile Include="Service\MainServiceInstallHelper.cs" />
103+
<Compile Include="Starter.cs" />
84104
<Compile Include="TunnelStorage.cs" />
85105
<Compile Include="WinDivert.cs" />
86106
</ItemGroup>
@@ -104,6 +124,16 @@
104124
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
105125
</None>
106126
</ItemGroup>
127+
<ItemGroup>
128+
<None Include="..\tunnel_hUB_icon.ico">
129+
<Link>tunnel_hUB_icon.ico</Link>
130+
</None>
131+
</ItemGroup>
132+
<ItemGroup>
133+
<EmbeddedResource Include="..\tunnel_active.png">
134+
<Link>tunnel_active.png</Link>
135+
</EmbeddedResource>
136+
</ItemGroup>
107137
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
108138
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
109139
Other similar extension points exist, see Microsoft.Common.targets.

AutoTunnel/BaseSender.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,19 @@ private void StartInternal()
5757
{
5858
if (!WinDivert.WinDivertRecv(_handle, packet, packet.Length, ref addr, ref packetLen))
5959
{
60-
LogHelper.Log.WriteLine("Cannot receive network data: " + Marshal.GetLastWin32Error());
61-
Thread.Sleep(1000);
60+
// showing error only if handle is not removed
61+
if (_handle != IntPtr.Zero)
62+
{
63+
LogHelper.Log.WriteLine("Cannot receive network data: " + Marshal.GetLastWin32Error());
64+
Thread.Sleep(1000);
65+
}
66+
67+
continue;
68+
}
69+
// we cannot handle such packets,
70+
// todo: think about writing to log
71+
if (packetLen >= ((65507 / 16) * 16) - 16)
72+
{
6273
continue;
6374
}
6475
// Console.WriteLine("Recv: " + packet[16] + "." + packet[17] + "." + packet[18] + "." + packet[19] + ":" + (packet[23] | ((uint)packet[22] << 8)));

AutoTunnel/ClientSender.cs

Lines changed: 59 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
using System;
2+
using System.Linq;
3+
using System.Net;
24
using System.Net.Sockets;
35
using System.Threading;
46
using System.Threading.Tasks;
@@ -17,8 +19,6 @@ public class ClientSender : BaseSender
1719

1820
private EncryptHelper _encryptHelper;
1921

20-
private DecryptHelper _decryptHelper;
21-
2222
private readonly byte[] _serverKey;
2323

2424
private readonly ManualResetEvent _initingEvent = new ManualResetEvent(false);
@@ -29,21 +29,47 @@ public class ClientSender : BaseSender
2929

3030
private readonly RemoteServerConfig _config;
3131

32+
private IPEndPoint _connectEP;
33+
3234
public ClientSender(RemoteServerConfig config, TunnelStorage storage)
33-
: base(null, EndpointHelper.ParseEndPoint(config.Address, 1).Address, storage)
35+
: base(null, EndpointHelper.ParseEndPoint(config.TunnelHost, 1).Address, storage)
3436
{
3537
storage.OutgoingConnectionAdresses.Add(DstAddr);
3638
_config = config;
3739
_serverKey = PasswordHelper.GenerateKey(config.Key);
3840
_packetWriter = new PacketWriter();
3941

40-
LogHelper.Log.WriteLine("Tunnel watcher was created for " + config.Address);
42+
LogHelper.Log.WriteLine("Tunnel watcher was created for " + config.TunnelHost);
4143

4244
Task.Factory.StartNew(ReceiveCycle);
4345
if (config.KeepAlive)
4446
Task.Factory.StartNew(PingCycle);
4547
if (config.ConnectOnStart)
4648
Init();
49+
IPAddress dummy;
50+
if (!IPAddress.TryParse(config.TunnelHost, out dummy))
51+
Task.Factory.StartNew(CheckHostChange);
52+
}
53+
54+
private void CheckHostChange()
55+
{
56+
// checking if target host has changed it ip address to other
57+
while (!_disposed)
58+
{
59+
var addresses = Dns.GetHostAddresses(_config.TunnelHost);
60+
if (addresses.Length > 0)
61+
{
62+
if (!addresses.Any(x => x.Equals(DstAddr)))
63+
{
64+
Storage.OutgoingConnectionAdresses.Remove(DstAddr);
65+
DstAddr = addresses.First();
66+
ReInitDivert(DstAddr);
67+
Storage.OutgoingConnectionAdresses.Add(DstAddr);
68+
}
69+
}
70+
71+
Thread.Sleep(60 * 1000);
72+
}
4773
}
4874

4975
private int _isIniting;
@@ -66,17 +92,18 @@ private void InitInternal()
6692
var cs = new ClientHandshake();
6793
var sendingPacketLen = cs.GetPacketForSending();
6894
_encryptHelper = new EncryptHelper(_serverKey);
69-
_decryptHelper = new DecryptHelper(_serverKey);
95+
var decryptHelper = new DecryptHelper(_serverKey);
96+
97+
var ep = EndpointHelper.ParseEndPoint(_config.ConnectHost, 12017);
7098

71-
var ep = EndpointHelper.ParseEndPoint(_config.Address, 12017);
72-
if (!ep.Address.Equals(DstAddr))
99+
if (!ep.Equals(_connectEP) && _connectEP != null)
73100
{
74-
Storage.OutgoingConnectionAdresses.Remove(DstAddr);
75-
ReInitDivert(ep.Address);
76-
Storage.OutgoingConnectionAdresses.Add(DstAddr);
101+
Storage.RemoveSession(_connectEP);
77102
}
78103

79-
Storage.SetNewEndPoint(new byte[16], ep);
104+
_connectEP = ep;
105+
106+
Storage.AddSession(new byte[16], ep).IsClientSession = true;
80107

81108
LogHelper.Log.WriteLine("Initializing connection to " + ep);
82109

@@ -118,16 +145,18 @@ private void InitInternal()
118145
return;
119146
}
120147

121-
var decLen = _decryptHelper.Decrypt(_receiveBuffer, 4);
148+
var decLen = decryptHelper.Decrypt(_receiveBuffer, 4);
122149
if (decLen < 9)
123150
{
124151
Console.Error.WriteLine("Invalid server response");
125152
return;
126153
}
127154

128-
var sessionKey = cs.GetPacketFromServer(_decryptHelper.InnerBuf, decLen);
155+
var sessionKey = cs.GetPacketFromServer(decryptHelper.InnerBuf, decLen);
129156
_encryptHelper = new EncryptHelper(sessionKey);
130-
_decryptHelper = new DecryptHelper(sessionKey);
157+
var session = Storage.GetSession(ep);
158+
session.Decryptor = new DecryptHelper(sessionKey);
159+
Session = session;
131160
LogHelper.Log.WriteLine("Initialized connection to " + ep);
132161
_isInited = true;
133162
_initingEvent.Set();
@@ -177,7 +206,19 @@ private void ReceiveCycle()
177206
if (_disposed)
178207
return;
179208

180-
var len = _socket.Receive(buf);
209+
int len;
210+
211+
try
212+
{
213+
len = _socket.Receive(buf);
214+
}
215+
catch (Exception)
216+
{
217+
LogHelper.Log.WriteLine("Receive data error");
218+
Thread.Sleep(1000);
219+
continue;
220+
}
221+
181222
// just drop data, assume that it is invalid
182223
if (len % 16 != 0)
183224
{
@@ -192,8 +233,9 @@ private void ReceiveCycle()
192233
}
193234
}
194235

195-
var decLen = _decryptHelper.Decrypt(buf, 0);
196-
_packetWriter.Write(_decryptHelper.InnerBuf, decLen);
236+
var decryptHelper = Session.Decryptor;
237+
var decLen = decryptHelper.Decrypt(buf, 0);
238+
_packetWriter.Write(decryptHelper.InnerBuf, decLen);
197239
}
198240
}
199241

AutoTunnel/Config/MainConfig.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public class MainConfig
1414
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
1515
public bool AddFirewallRule { get; set; }
1616

17-
public string[] Keys { get; set; }
17+
public RemoteClientConfig[] RemoteClients { get; set; }
1818

1919
[DefaultValue(12017)]
2020
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using Newtonsoft.Json;
2+
3+
namespace Force.AutoTunnel.Config
4+
{
5+
public class RemoteClientConfig
6+
{
7+
public string Key { get; set; }
8+
9+
[JsonIgnore]
10+
public byte[] BinaryKey { get; set; }
11+
12+
public string Description { get; set; }
13+
}
14+
}

AutoTunnel/Config/RemoteServerConfig.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
{
33
public class RemoteServerConfig
44
{
5-
public string Address { get; set; }
5+
public string TunnelHost { get; set; }
6+
7+
public string ConnectHost { get; set; }
68

79
public string Key { get; set; }
810

AutoTunnel/FirewallHelper.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ public static void AddOpenFirewallRule(string port)
1212
ProcessRunner.RunProcess("netsh", "firewall add portopening TCP " + port + " AutoTunnel ENABLE all");
1313
else
1414
{
15-
ProcessRunner.RunProcess("netsh", "advfirewall firewall delete rule name=\"AutoTunnel\" protocol=TCP dir=in localport=" + port);
16-
ProcessRunner.RunProcess("netsh", "advfirewall firewall add rule name=\"AutoTunnel\" protocol=TCP dir=in localport=" + port + " action=allow");
15+
ProcessRunner.RunProcess("netsh", "advfirewall firewall delete rule name=\"AutoTunnel\" protocol=UDP dir=in localport=" + port);
16+
ProcessRunner.RunProcess("netsh", "advfirewall firewall add rule name=\"AutoTunnel\" protocol=UDP dir=in localport=" + port + " action=allow");
1717
}
1818
}
1919

@@ -25,7 +25,7 @@ public static void DeleteFirewallRule(string port)
2525
}
2626
else
2727
{
28-
ProcessRunner.RunProcess("netsh", "advfirewall firewall delete rule name=\"AutoTunnel\" protocol=TCP dir=in localport=" + port);
28+
ProcessRunner.RunProcess("netsh", "advfirewall firewall delete rule name=\"AutoTunnel\" protocol=UDP dir=in");
2929
}
3030
}
3131

0 commit comments

Comments
 (0)