-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTapMirror.cs
462 lines (401 loc) · 16.1 KB
/
TapMirror.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
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
// ReSharper disable once CheckNamespace
namespace HGM.Hotbird64.LicenseManager
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.None)]
public struct IpHeader // All fields in big-endian (network) order
{
private readonly byte ipHlV;
public byte Tos;
public short Length;
public ushort Id;
public short FragmentOffset;
public byte Ttl;
public byte Protocol;
public ushort Checksum;
public uint SourceIP;
public uint DestinationIP;
#if DEBUG
public byte HeaderLength => unchecked((byte)(ipHlV & 15));
public byte Version => unchecked((byte)(ipHlV >> 4));
#endif
}
public static class TapMirror
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
private const uint METHOD_BUFFERED = 0;
[SuppressMessage("ReSharper", "InconsistentNaming")]
private const uint FILE_ANY_ACCESS = 0;
[SuppressMessage("ReSharper", "InconsistentNaming")]
private const uint FILE_DEVICE_UNKNOWN = 0x00000022;
[SuppressMessage("ReSharper", "InconsistentNaming")]
private const int FILE_ATTRIBUTE_SYSTEM = 0x4;
[SuppressMessage("ReSharper", "InconsistentNaming")]
private const int FILE_FLAG_OVERLAPPED = 0x40000000;
public enum TapIoctl
{
GetMacAddress = 1,
GetVersion = 2,
GetMtu = 3,
GetInfo = 4, // Not implemented in NDIS6 versions
ConfigurePointToPoint = 5, // Superseeded by ConfigureIPv4Tunnel
SetMediaStatus = 6,
ConfigDhcpMasquerade = 7,
GetLogLine = 8, // Only enabled in DEBUG builds
SetDhcpOption = 9,
ConfigureIPv4Tunnel = 10, // Requires 8.2 or greater
SetArpSourceCheck = 11, // Requires 9.??? or greater
}
public class TapDeviceVariant
{
public string Class;
public string Suffix;
}
public class TapDeviceVariants : HashSet<TapDeviceVariant>
{
public string this[string Class] => this.FirstOrDefault(l => l.Class == Class)?.Suffix;
}
public class TapDevice
{
public string Guid;
public string Name;
public string ClassName;
public string DeviceSuffix;
public SafeFileHandle Handle;
public override string ToString() => $"{Name} ({ClassName})";
}
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.None)]
public struct TapConfigTun
{
private int address;
private int network;
private int mask;
public int Address
{
get => IPAddress.NetworkToHostOrder(address);
set => address = IPAddress.HostToNetworkOrder(value);
}
public int Network
{
get => IPAddress.NetworkToHostOrder(network);
set => network = IPAddress.HostToNetworkOrder(value);
}
public int Mask
{
get => IPAddress.NetworkToHostOrder(mask);
set => mask = IPAddress.HostToNetworkOrder(value);
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.None)]
public struct TapConfigDhcp
{
private int address;
private int mask;
private int dhcpServer;
public int LeaseDuration;
public int Address
{
get => IPAddress.NetworkToHostOrder(address);
set => address = IPAddress.HostToNetworkOrder(value);
}
public int Mask
{
get => IPAddress.NetworkToHostOrder(mask);
set => mask = IPAddress.HostToNetworkOrder(value);
}
public int DhcpServer
{
get => IPAddress.NetworkToHostOrder(dhcpServer);
set => dhcpServer = IPAddress.HostToNetworkOrder(value);
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.None)]
public struct TapDriverVersion
{
public int Major;
public int Minor;
public int Build; //unused but reported as 0
public int Revision; //unused and not reported
}
private static FileStream tap;
private static TapDevice device;
private static bool isVirtualCableConnected;
private static readonly TapDeviceVariants tapDeviceVariants = new TapDeviceVariants
{
new TapDeviceVariant { Class = "tap0801", Suffix = "tap" },
new TapDeviceVariant { Class = "tap0901", Suffix = "tap" },
new TapDeviceVariant { Class = "TEAMVIEWERVPN", Suffix = "dgt" },
};
public static bool IsStarted => tap != null;
public static Version Start(string subnet, string tapName = null)
{
ParseSubnet(subnet, out int address, out int network, out int mask);
device = OpenTapHandle(tapName);
Version version = DriverVersion;
if (version.Major == 8 && version.Minor < 2) throw new NotSupportedException("TAP driver 8.x or 9.x greater than 8.2 required");
SetSubnet(address, network, mask);
EnableDhcp(address, mask);
IsVirtualCableConnected = true;
new Thread(Mirror).Start();
return version;
}
public static void Stop()
{
tap?.Dispose();
device?.Handle?.Dispose();
device = null;
tap = null;
}
private static unsafe void Mirror()
{
tap = new FileStream(device.Handle, FileAccess.ReadWrite, Mtu, true);
byte[] buffer = new byte[Mtu];
while (true)
{
try
{
int bytesRead = tap.Read(buffer, 0, buffer.Length);
fixed (byte* b = buffer)
{
IpHeader* packet = (IpHeader*)b;
uint temp = packet->SourceIP;
packet->SourceIP = packet->DestinationIP;
packet->DestinationIP = temp;
}
tap.Write(buffer, 0, bytesRead);
if (Mtu > buffer.Length) buffer = new byte[Mtu];
}
catch (OperationCanceledException)
{
return;
}
catch
{
Stop();
throw;
}
}
}
private static unsafe int Mtu
{
get
{
int tapMtu;
DevCtl(TapIoctl.GetMtu, &tapMtu, sizeof(int));
return tapMtu;
}
}
public static unsafe Version DriverVersion
{
get
{
TapDriverVersion tapDriverVersion = new TapDriverVersion();
int len = DevCtl(TapIoctl.GetVersion, &tapDriverVersion, sizeof(TapDriverVersion));
switch (len)
{
case sizeof(int) * 2:
return new Version(tapDriverVersion.Major, tapDriverVersion.Minor);
case sizeof(int) * 3:
return new Version(tapDriverVersion.Major, tapDriverVersion.Minor, tapDriverVersion.Build);
case sizeof(int) * 4:
return new Version(tapDriverVersion.Major, tapDriverVersion.Minor, tapDriverVersion.Build, tapDriverVersion.Revision);
default:
throw new InvalidOperationException("Cannot determine TAP driver version");
}
}
}
public static string IpAddressString(int address) => new IPAddress(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(address))).ToString();
public static int IpAddressInt(string ipAddressString)
{
IPAddress ipAddress = IPAddress.Parse(ipAddressString);
if (ipAddress.AddressFamily != AddressFamily.InterNetwork) throw new FormatException($"{ipAddressString} is not a valid IPv4 address");
return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0));
}
private static void ParseSubnet(string subnet, out int address, out int network, out int mask)
{
int cidr;
string[] split = subnet.Split('/');
if (split.Length > 2) throw new FormatException("Subnet must be <IPv4 address>[/<CIDR mask>]");
if (split.Length == 2)
{
cidr = int.Parse(split[1], NumberStyles.None, CultureInfo.InvariantCulture);
if (cidr > 30 || cidr < 8) throw new ArgumentOutOfRangeException(nameof(cidr), "CIDR must be between 8 and 30");
address = IpAddressInt(split[0]);
}
else
{
cidr = 30;
address = IpAddressInt(subnet);
}
mask = unchecked((int)~(uint.MaxValue >> cidr));
network = address & mask;
int broadcast = address | ~mask;
unchecked
{
if ((uint)address <= (uint)network || (uint)address + 1 >= (uint)broadcast)
{
throw new ArgumentOutOfRangeException(
nameof(address),
$"For this subnet IPv4 address must be {((uint)network + 1 != (uint)broadcast - 2 ? $"between {IpAddressString((int)(uint)(network + 1))} and {IpAddressString((int)(uint)(broadcast - 2))}" : $"{IpAddressString((int)(uint)(network + 1))}")}"
);
}
}
}
public static bool IsValidSubnet(string subnet, out string reason)
{
reason = null;
try
{
ParseSubnet(subnet, out _, out _, out _);
return true;
}
catch (Exception ex)
{
reason = ex.Message;
return false;
}
}
private static unsafe void SetSubnet(int address, int network, int mask)
{
TapConfigTun tapConfigTun = new TapConfigTun { Address = address, Network = network, Mask = mask };
DevCtl(TapIoctl.ConfigureIPv4Tunnel, &tapConfigTun, sizeof(TapConfigTun));
}
private static unsafe void EnableDhcp(int address, int mask)
{
TapConfigDhcp tapConfigDhcp = new TapConfigDhcp
{
Address = address,
Mask = mask,
DhcpServer = unchecked((int)(uint)(address + 1)),
LeaseDuration = 24 * 60 * 60
};
DevCtl(TapIoctl.ConfigDhcpMasquerade, &tapConfigDhcp, sizeof(TapConfigDhcp));
}
public static unsafe bool IsVirtualCableConnected
{
get => isVirtualCableConnected && IsStarted;
set
{
int status = value ? 1 : 0;
DevCtl(TapIoctl.SetMediaStatus, &status, sizeof(int));
isVirtualCableConnected = value;
}
}
public static IEnumerable<TapDevice> GetTapDevices()
{
const string adapterKey = @"SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}";
using (RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(adapterKey, writable: false))
{
string[] keyNames = regAdapters?.GetSubKeyNames();
if (keyNames == null) yield break;
foreach (string keyName in keyNames)
{
RegistryKey regAdapter;
try
{
regAdapter = regAdapters.OpenSubKey(keyName, writable: false);
}
catch
{
continue;
}
try
{
string id = regAdapter?.GetValue("ComponentId")?.ToString();
if (!tapDeviceVariants.Select(v => v.Class).Contains(id) || id == null) continue;
string guid = regAdapter.GetValue("NetCfgInstanceId").ToString();
yield return new TapDevice
{
DeviceSuffix = tapDeviceVariants[id],
ClassName = id,
Guid = guid,
Name = GetDisplayName(guid)
};
}
finally
{
regAdapter?.Dispose();
}
}
}
}
private static TapDevice OpenTapHandle(string deviceName = null)
{
foreach (TapDevice tapDevice in GetTapDevices().Where(d => deviceName == null || d.Name == deviceName))
{
SafeFileHandle tapHandle = CreateFileW
(
$@"\\.\Global\{tapDevice.Guid}.{tapDevice.DeviceSuffix}",
FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open,
FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, IntPtr.Zero
);
if (tapHandle.IsInvalid) continue;
tapDevice.Handle = tapHandle;
return tapDevice;
}
throw new ConfigurationErrorsException($"No VPN devices{(deviceName == null ? "" : $" named \"{deviceName}\"")} available for use");
}
private static string GetDisplayName(string tapGuid)
{
RegistryKey regConnection = Registry.LocalMachine.OpenSubKey
(
$@"SYSTEM\CurrentControlSet\Control\Network\{{4D36E972-E325-11CE-BFC1-08002BE10318}}\{tapGuid}\Connection",
true
);
return regConnection?.GetValue("Name")?.ToString() ?? "";
}
private static unsafe int DevCtl(TapIoctl code, void* data, int len)
{
if
(
device?.Handle == null ||
device.Handle.IsClosed ||
device.Handle.IsInvalid
)
{
throw new InvalidOperationException("Not connected to a TAP device");
}
if (!DeviceIoControl
(
device.Handle, (FILE_DEVICE_UNKNOWN << 16) | (FILE_ANY_ACCESS << 14) | ((uint)code << 2) | METHOD_BUFFERED,
data, len, data, len, out len, IntPtr.Zero
))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return len;
}
[DllImport("Kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
private static extern SafeFileHandle CreateFileW(
string filename,
[MarshalAs(UnmanagedType.U4)] FileAccess fileaccess,
[MarshalAs(UnmanagedType.U4)] FileShare fileshare,
IntPtr securityattributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationdisposition,
uint flags,
IntPtr template);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.None, CallingConvention = CallingConvention.Winapi)]
private static extern unsafe bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
void* lpInBuffer,
int nInBufferSize,
void* lpOutBuffer,
int nOutBufferSize,
out int lpBytesReturned,
IntPtr lpOverlapped);
}
}