DnsInterceptor.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. using DNS.Protocol;
  2. using DNS.Protocol.ResourceRecords;
  3. using FastGithub.Configuration;
  4. using Microsoft.Extensions.Logging;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Buffers.Binary;
  8. using System.ComponentModel;
  9. using System.Diagnostics.CodeAnalysis;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Runtime.InteropServices;
  13. using System.Runtime.Versioning;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using WinDivertSharp;
  17. namespace FastGithub.PacketIntercept.Dns
  18. {
  19. /// <summary>
  20. /// dns拦截器
  21. /// </summary>
  22. [SupportedOSPlatform("windows")]
  23. sealed class DnsInterceptor : IDnsInterceptor
  24. {
  25. private const string DNS_FILTER = "udp.DstPort == 53";
  26. private readonly FastGithubConfig fastGithubConfig;
  27. private readonly ILogger<DnsInterceptor> logger;
  28. private readonly TimeSpan ttl = TimeSpan.FromMinutes(10d);
  29. /// <summary>
  30. /// 刷新DNS缓存
  31. /// </summary>
  32. [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)]
  33. private static extern void DnsFlushResolverCache();
  34. /// <summary>
  35. /// dns拦截器
  36. /// </summary>
  37. /// <param name="fastGithubConfig"></param>
  38. /// <param name="logger"></param>
  39. /// <param name="options"></param>
  40. public DnsInterceptor(
  41. FastGithubConfig fastGithubConfig,
  42. ILogger<DnsInterceptor> logger,
  43. IOptionsMonitor<FastGithubOptions> options)
  44. {
  45. this.fastGithubConfig = fastGithubConfig;
  46. this.logger = logger;
  47. options.OnChange(_ => DnsFlushResolverCache());
  48. }
  49. /// <summary>
  50. /// DNS拦截
  51. /// </summary>
  52. /// <param name="cancellationToken"></param>
  53. /// <exception cref="Win32Exception"></exception>
  54. /// <returns></returns>
  55. public async Task InterceptAsync(CancellationToken cancellationToken)
  56. {
  57. await Task.Yield();
  58. var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  59. if (handle == IntPtr.MaxValue || handle == IntPtr.Zero)
  60. {
  61. const int ERROR_INVALID_HANDLE = 0x6;
  62. throw new Win32Exception(ERROR_INVALID_HANDLE, "打开驱动失败");
  63. }
  64. cancellationToken.Register(hwnd =>
  65. {
  66. WinDivert.WinDivertClose((IntPtr)hwnd!);
  67. DnsFlushResolverCache();
  68. }, handle);
  69. var packetLength = 0U;
  70. using var winDivertBuffer = new WinDivertBuffer();
  71. var winDivertAddress = new WinDivertAddress();
  72. DnsFlushResolverCache();
  73. while (cancellationToken.IsCancellationRequested == false)
  74. {
  75. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false)
  76. {
  77. throw new Win32Exception();
  78. }
  79. try
  80. {
  81. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  82. }
  83. catch (Exception ex)
  84. {
  85. this.logger.LogWarning(ex.Message);
  86. }
  87. finally
  88. {
  89. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  90. }
  91. }
  92. }
  93. /// <summary>
  94. /// 修改DNS数据包
  95. /// </summary>
  96. /// <param name="winDivertBuffer"></param>
  97. /// <param name="winDivertAddress"></param>
  98. /// <param name="packetLength"></param>
  99. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  100. {
  101. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  102. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  103. if (TryParseRequest(requestPayload, out var request) == false ||
  104. request.OperationCode != OperationCode.Query ||
  105. request.Questions.Count == 0)
  106. {
  107. return;
  108. }
  109. var question = request.Questions.First();
  110. if (question.Type != RecordType.A)
  111. {
  112. return;
  113. }
  114. var domain = question.Name;
  115. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  116. {
  117. return;
  118. }
  119. // dns响应数据
  120. var response = Response.FromRequest(request);
  121. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  122. response.AnswerRecords.Add(record);
  123. var responsePayload = response.ToArray();
  124. // 修改payload和包长
  125. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  126. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  127. // 修改ip包
  128. if (packet.IPv4Header != null)
  129. {
  130. var destAddress = packet.IPv4Header->DstAddr;
  131. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  132. packet.IPv4Header->SrcAddr = destAddress;
  133. packet.IPv4Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  134. }
  135. else
  136. {
  137. var destAddress = packet.IPv6Header->DstAddr;
  138. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  139. packet.IPv6Header->SrcAddr = destAddress;
  140. packet.IPv6Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  141. }
  142. // 修改udp包
  143. var destPort = packet.UdpHeader->DstPort;
  144. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  145. packet.UdpHeader->SrcPort = destPort;
  146. packet.UdpHeader->Length = BinaryPrimitives.ReverseEndianness((ushort)(sizeof(UdpHeader) + responsePayload.Length));
  147. winDivertAddress.Impostor = true;
  148. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  149. this.logger.LogInformation($"{domain} => {IPAddress.Loopback}");
  150. }
  151. /// <summary>
  152. /// 尝试解析请求
  153. /// </summary>
  154. /// <param name="payload"></param>
  155. /// <param name="request"></param>
  156. /// <returns></returns>
  157. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  158. {
  159. try
  160. {
  161. request = Request.FromArray(payload);
  162. return true;
  163. }
  164. catch (Exception)
  165. {
  166. request = null;
  167. return false;
  168. }
  169. }
  170. }
  171. }