windows平台dns投毒

This commit is contained in:
陈国伟 2021-09-14 13:28:35 +08:00
parent ab9cd99c90
commit e37c5592a4
6 changed files with 161 additions and 148 deletions

View File

@ -15,6 +15,7 @@ namespace FastGithub.Dns
sealed class DnsOverUdpHostedService : BackgroundService
{
private readonly DnsOverUdpServer dnsOverUdpServer;
private readonly DnsPoisoningServer dnsPoisoningServer;
private readonly IEnumerable<IConflictValidator> conflictValidators;
private readonly ILogger<DnsOverUdpHostedService> logger;
@ -22,14 +23,17 @@ namespace FastGithub.Dns
/// dns后台服务
/// </summary>
/// <param name="dnsOverUdpServer"></param>
/// <param name="dnsPoisoningServer"></param>
/// <param name="conflictValidators"></param>
/// <param name="logger"></param>
public DnsOverUdpHostedService(
DnsOverUdpServer dnsOverUdpServer,
DnsPoisoningServer dnsPoisoningServer,
IEnumerable<IConflictValidator> conflictValidators,
ILogger<DnsOverUdpHostedService> logger)
{
this.dnsOverUdpServer = dnsOverUdpServer;
this.dnsPoisoningServer = dnsPoisoningServer;
this.conflictValidators = conflictValidators;
this.logger = logger;
}
@ -40,6 +44,8 @@ namespace FastGithub.Dns
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override async Task StartAsync(CancellationToken cancellationToken)
{
if (OperatingSystem.IsWindows() == false)
{
try
{
@ -56,6 +62,7 @@ namespace FastGithub.Dns
builder.Append($"4. 在局域网其它设备上运行本程序然后将本机DNS设置为局域网设备的IP");
this.logger.LogError(builder.ToString());
}
}
foreach (var item in this.conflictValidators)
{
@ -70,9 +77,17 @@ namespace FastGithub.Dns
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override Task ExecuteAsync(CancellationToken stoppingToken)
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
return this.dnsOverUdpServer.HandleAsync(stoppingToken);
if (OperatingSystem.IsWindows())
{
await Task.Yield();
this.dnsPoisoningServer.DnsPoisoning(stoppingToken);
}
else
{
await this.dnsOverUdpServer.HandleAsync(stoppingToken);
}
}
/// <summary>
@ -81,8 +96,11 @@ namespace FastGithub.Dns
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task StopAsync(CancellationToken cancellationToken)
{
if (OperatingSystem.IsWindows() == false)
{
this.dnsOverUdpServer.Dispose();
}
return base.StopAsync(cancellationToken);
}
}

View File

@ -47,11 +47,6 @@ namespace FastGithub.Dns
/// <exception cref="FastGithubException"></exception>
public void Listen(IPAddress address, int port)
{
if (OperatingSystem.IsWindows())
{
UdpTable.KillPortOwner(port);
}
if (LocalMachine.CanListenUdp(port) == false)
{
throw new FastGithubException($"udp端口{port}已经被其它进程占用");

View File

@ -0,0 +1,123 @@
using DNS.Protocol;
using DNS.Protocol.ResourceRecords;
using FastGithub.Configuration;
using Microsoft.Extensions.Logging;
using PacketDotNet;
using System;
using System.Linq;
using System.Net;
using System.Runtime.Versioning;
using System.Threading;
using WinDivertSharp;
namespace FastGithub.Dns
{
/// <summary>
/// dns投毒服务
/// </summary>
sealed class DnsPoisoningServer
{
const string DNS_FILTER = "udp.DstPort == 53";
private readonly FastGithubConfig fastGithubConfig;
private readonly ILogger<DnsPoisoningServer> logger;
private readonly TimeSpan ttl = TimeSpan.FromSeconds(10d);
/// <summary>
/// dns投毒后台服务
/// </summary>
/// <param name="fastGithubConfig"></param>
/// <param name="logger"></param>
public DnsPoisoningServer(
FastGithubConfig fastGithubConfig,
ILogger<DnsPoisoningServer> logger)
{
this.fastGithubConfig = fastGithubConfig;
this.logger = logger;
}
/// <summary>
/// DNS投毒
/// </summary>
/// <param name="cancellationToken"></param>
[SupportedOSPlatform("windows")]
public void DnsPoisoning(CancellationToken cancellationToken)
{
var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
if (handle == IntPtr.Zero)
{
return;
}
var packetLength = 0U;
var packetBuffer = new byte[ushort.MaxValue];
using var winDivertBuffer = new WinDivertBuffer(packetBuffer);
var winDivertAddress = new WinDivertAddress();
SystemDnsUtil.FlushResolverCache();
while (cancellationToken.IsCancellationRequested == false)
{
if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength))
{
try
{
this.ProcessDnsPacket(packetBuffer, ref packetLength);
}
catch (Exception ex)
{
this.logger.LogWarning(ex.Message);
}
WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
}
}
WinDivert.WinDivertClose(handle);
}
/// <summary>
/// 处理DNS数据包
/// </summary>
/// <param name="packetBuffer"></param>
private void ProcessDnsPacket(byte[] packetBuffer, ref uint packetLength)
{
var packetData = packetBuffer.AsSpan(0, (int)packetLength).ToArray();
var packet = Packet.ParsePacket(LinkLayers.Raw, packetData);
var ipPacket = (IPPacket)packet.PayloadPacket;
var udpPacket = (UdpPacket)ipPacket.PayloadPacket;
var request = Request.FromArray(udpPacket.PayloadData);
var question = request.Questions.FirstOrDefault();
if (question == null || question.Type != RecordType.A)
{
return;
}
var domain = question.Name;
if (this.fastGithubConfig.IsMatch(domain.ToString()) == false)
{
return;
}
// 反转ip
var sourAddress = ipPacket.SourceAddress;
ipPacket.SourceAddress = ipPacket.DestinationAddress;
ipPacket.DestinationAddress = sourAddress;
// 反转端口
var sourPort = udpPacket.SourcePort;
udpPacket.SourcePort = udpPacket.DestinationPort;
udpPacket.DestinationPort = sourPort;
// 设置dns响应
var response = Response.FromRequest(request);
var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
response.AnswerRecords.Add(record);
udpPacket.PayloadData = response.ToArray();
// 修改数据内容和数据长度
packet.Bytes.CopyTo(packetBuffer, 0);
packetLength = (uint)packet.Bytes.Length;
}
}
}

View File

@ -8,6 +8,8 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="DNS" Version="6.1.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="PacketDotNet" Version="1.3.0" />
<PackageReference Include="WinDivertSharp" Version="1.4.3.3" />
</ItemGroup>
<ItemGroup>

View File

@ -18,6 +18,7 @@ namespace FastGithub
{
services.TryAddSingleton<RequestResolver>();
services.TryAddSingleton<DnsOverUdpServer>();
services.TryAddSingleton<DnsPoisoningServer>();
services.TryAddSingleton<DnsOverHttpsMiddleware>();
services.AddSingleton<IConflictValidator, HostsConflictValidator>();
services.AddSingleton<IConflictValidator, ProxyConflictValidtor>();

View File

@ -1,126 +0,0 @@
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace FastGithub.Dns
{
/// <summary>
/// windows iphlpapi
/// </summary>
[SupportedOSPlatform("windows")]
unsafe static class UdpTable
{
private const int ERROR_INSUFFICIENT_BUFFER = 122;
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern uint GetExtendedUdpTable(void* pUdpTable, ref int pdwSize, bool bOrder, AddressFamily ulAf, UDP_TABLE_CLASS tableClass, uint reserved = 0);
/// <summary>
/// 杀死占用进程
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
public static bool KillPortOwner(int port)
{
if (TryGetOwnerProcessId(port, out var pid) == false)
{
return true;
}
try
{
var proess = Process.GetProcessById(pid);
proess.Kill();
return proess.WaitForExit(1000);
}
catch (ArgumentException)
{
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 获取udp端口的占用进程id
/// </summary>
/// <param name="port"></param>
/// <param name="processId"></param>
/// <returns></returns>
public static bool TryGetOwnerProcessId(int port, out int processId)
{
processId = 0;
var pdwSize = 0;
var result = GetExtendedUdpTable(null, ref pdwSize, false, AddressFamily.InterNetwork, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
if (result != ERROR_INSUFFICIENT_BUFFER)
{
return false;
}
var buffer = new byte[pdwSize];
fixed (byte* pUdpTable = &buffer[0])
{
result = GetExtendedUdpTable(pUdpTable, ref pdwSize, false, AddressFamily.InterNetwork, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
if (result != 0)
{
return false;
}
var prt = new IntPtr(pUdpTable);
var table = Marshal.PtrToStructure<MIB_UDPTABLE_OWNER_PID>(prt);
prt += sizeof(int);
for (var i = 0; i < table.dwNumEntries; i++)
{
var row = Marshal.PtrToStructure<MIB_UDPROW_OWNER_PID>(prt);
if (row.LocalPort == port)
{
processId = row.ProcessId;
return true;
}
prt += Marshal.SizeOf<MIB_UDPROW_OWNER_PID>();
}
}
return false;
}
private enum UDP_TABLE_CLASS
{
UDP_TABLE_BASIC,
UDP_TABLE_OWNER_PID,
UDP_TABLE_OWNER_MODULE
}
[StructLayout(LayoutKind.Sequential)]
private struct MIB_UDPTABLE_OWNER_PID
{
public uint dwNumEntries;
}
[StructLayout(LayoutKind.Sequential)]
private struct MIB_UDPROW_OWNER_PID
{
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public int owningPid;
public int ProcessId => owningPid;
public IPAddress LocalAddress => new(localAddr);
public ushort LocalPort => BinaryPrimitives.ReadUInt16BigEndian(this.localPort);
}
}
}